diff --git a/bower.json b/bower.json index 839184ce..25214b0b 100644 --- a/bower.json +++ b/bower.json @@ -13,9 +13,9 @@ "!src/**/*" ], "dependencies": { - "es6-promise": "^3.2.1", - "fetch": "^0.11.0", - "pubnub": "^3.14.4" + "es6-promise": "^4.0.5", + "fetch": "^2.0.2", + "pubnub": "^4.4.2" }, "moduleType": [ "amd", @@ -38,4 +38,4 @@ "type": "git", "url": "git://github.com/ringcentral/ringcentral-js.git" } -} \ No newline at end of file +} diff --git a/build/ringcentral.js b/build/ringcentral.js index 672401b1..cf382369 100644 --- a/build/ringcentral.js +++ b/build/ringcentral.js @@ -75,7 +75,7 @@ var Constants = __webpack_require__(17); * @param {string} [options.appName] * @param {string} [options.appVersion] * @param {string} [options.redirectUri] - * @param {PUBNUB} [options.PUBNUB] + * @param {PubNub} [options.PubNub] * @param {function(new:Promise)} [options.Promise] * @param {Storage} [options.localStorage] * @param {fetch} [options.fetch] @@ -183,8 +183,15 @@ module.exports = SDK; /* 1 */ /***/ function(module, exports) { +/* +object-assign +(c) Sindre Sorhus +@license MIT +*/ + 'use strict'; /* eslint-disable no-unused-vars */ +var getOwnPropertySymbols = Object.getOwnPropertySymbols; var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; @@ -205,7 +212,7 @@ function shouldUseNative() { // Detect buggy property enumeration order in older V8 versions. // https://bugs.chromium.org/p/v8/issues/detail?id=4118 - var test1 = new String('abc'); // eslint-disable-line + var test1 = new String('abc'); // eslint-disable-line no-new-wrappers test1[5] = 'de'; if (Object.getOwnPropertyNames(test1)[0] === '5') { return false; @@ -234,7 +241,7 @@ function shouldUseNative() { } return true; - } catch (e) { + } catch (err) { // We don't expect any of the above to throw, but better to be safe. return false; } @@ -254,8 +261,8 @@ module.exports = shouldUseNative() ? Object.assign : function (target, source) { } } - if (Object.getOwnPropertySymbols) { - symbols = Object.getOwnPropertySymbols(from); + if (getOwnPropertySymbols) { + symbols = getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; @@ -1343,14 +1350,14 @@ var root = (typeof window !== "undefined" && window) || /** * @constructor - * @param {PUBNUB} [options.PUBNUB] + * @param {PubNub} [options.PubNub] * @param {function(new:Promise)} [options.Promise] * @param {Storage} [options.localStorage] * @param {fetch} [options.fetch] * @param {function(new:Request)} [options.Request] * @param {function(new:Response)} [options.Response] * @param {function(new:Headers)} [options.Headers] - * @property {PUBNUB} PUBNUB + * @property {PubNub} PubNub * @property {Storage} localStorage * @property {function(new:Promise)} Promise * @property {fetch} fetch @@ -1362,7 +1369,7 @@ function Externals(options) { options = options || {}; - this.PUBNUB = options.PUBNUB || root.PUBNUB || pubnub; + this.PubNub = options.PubNub || root.PubNub || pubnub; this.localStorage = options.localStorage || ((typeof root.localStorage !== 'undefined') ? root.localStorage : {}); this.Promise = options.Promise || root.Promise || (es6Promise && es6Promise.Promise); @@ -1385,8 +1392,8 @@ function Externals(options) { throw new Error('LocalStorage is missing'); } - if (!this.PUBNUB) { - throw new Error('PUBNUB is missing'); + if (!this.PubNub) { + throw new Error('PubNub is missing'); } } @@ -2212,7 +2219,7 @@ module.exports = Auth; /* 17 */ /***/ function(module, exports, __webpack_require__) { -var version = ("3.0.0"); +var version = ("3.1.0"); // This will become false during the Webpack build, so no traces of package.json will be there if (false) { @@ -2502,7 +2509,7 @@ Subscription.prototype.resubscribe = function() { }; /** - * Remove subscription and disconnect from PUBNUB + * Remove subscription and disconnect from PubNub * This method resets subscription at client side but backend is not notified * @return {Subscription} */ @@ -2574,7 +2581,7 @@ Subscription.prototype._decrypt = function(message) { if (this.subscription().deliveryMode.encryptionKey) { - message = this._externals.PUBNUB.crypto_obj.decrypt(message, this.subscription().deliveryMode.encryptionKey, { + message = this._pubnub.decrypt(message, this.subscription().deliveryMode.encryptionKey, { encryptKey: false, keyEncoding: 'base64', keyLength: 128, @@ -2624,13 +2631,11 @@ Subscription.prototype._subscribeAtPubnub = function() { } else { // Init from scratch - this._pubnub = this._externals.PUBNUB.init({ + this._pubnub = new this._externals.PubNub({ ssl: true, subscribe_key: deliveryMode.subscriberKey }); - this._pubnub.ready(); //TODO This may be not needed anymore - } this._pubnubLastChannel = deliveryMode.address; diff --git a/build/ringcentral.js.map b/build/ringcentral.js.map index 02aa5f6b..192dc3e5 100644 --- a/build/ringcentral.js.map +++ b/build/ringcentral.js.map @@ -1 +1 @@ -{"version":3,"sources":["webpack:///webpack/universalModuleDefinition","webpack:///webpack/bootstrap e778b74917863b61271c","webpack:///./src/SDK.js","webpack:///./~/object-assign/index.js","webpack:///./src/core/Cache.js","webpack:///./src/http/Client.js","webpack:///./~/is-plain-object/index.js","webpack:///./~/is-plain-object/~/isobject/index.js","webpack:///./~/events/events.js","webpack:///./src/http/ApiResponse.js","webpack:///./~/querystring/index.js","webpack:///./~/querystring/decode.js","webpack:///./~/querystring/encode.js","webpack:///./src/core/Externals.js","webpack:///external {\"amd\":\"pubnub\"}","webpack:///external {\"amd\":\"es6-promise\"}","webpack:///external {\"amd\":\"fetch-ponyfill\"}","webpack:///./src/platform/Platform.js","webpack:///./src/platform/Auth.js","webpack:///./src/core/Constants.js","webpack:///./src/subscription/Subscription.js","webpack:///./src/subscription/CachedSubscription.js"],"names":[],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iDAAiD;AACjD,CAAC;AACD,O;ACVA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,uBAAe;AACf;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;;AAGA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;;;;;;ACtCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,sBAAsB;AACjC,WAAW,QAAQ;AACnB,WAAW,MAAM;AACjB,WAAW,sBAAsB;AACjC,WAAW,uBAAuB;AAClC,WAAW,sBAAsB;AACjC,WAAW,IAAI;AACf,WAAW,IAAI;AACf,WAAW,QAAQ;AACnB,cAAc,UAAU;AACxB,cAAc,MAAM;AACpB,cAAc,OAAO;AACrB,cAAc,SAAS;AACvB;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,KAAK;;AAEL;AACA;;AAEA;AACA,iDAAiD;AACjD;AACA;AACA;AACA,KAAK;;AAEL;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;AACA,YAAY;AACZ;AACA;AACA;AACA;;AAEA;AACA,YAAY;AACZ;AACA;AACA;AACA;;AAEA;AACA,WAAW,IAAI;AACf,WAAW,IAAI;AACf,YAAY;AACZ;AACA;AACA,2CAA2C;AAC3C;AACA;AACA,KAAK;AACL;;AAEA;AACA,WAAW,OAAO;AAClB,WAAW,IAAI;AACf,WAAW,IAAI;AACf,YAAY;AACZ;AACA;;AAEA;AACA,mBAAmB;AACnB,KAAK;AACL;AACA;;AAEA,iDAAiD;AACjD;AACA;AACA;AACA,KAAK;;AAEL;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA,qB;;;;;;AC3HA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA,gCAAgC;AAChC;AACA;AACA;AACA;;AAEA;AACA;AACA,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,GAAG;AACH,kCAAkC;AAClC;AACA;AACA;;AAEA;AACA,EAAE;AACF;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA,gBAAgB,sBAAsB;AACtC;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AAC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A;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;;AAEA,SAAS;AACT;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;;AAEA;;AAEA;;AAEA;AACA,aAAa,OAAO;AACpB,cAAc,OAAO;AACrB,cAAc,OAAO;AACrB,cAAc,YAAY;AAC1B;;AAEA,wB;;;;;;AC/LA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;;;;;;ACpCA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;;;;;;;ACZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA,eAAe,SAAS;AACxB;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA,GAAG;AACH,oBAAoB,SAAS;AAC7B;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;;;;;;AC7SA;AACA,WAAW,UAAU;AACrB,WAAW,QAAQ;AACnB,WAAW,SAAS;AACpB,WAAW,OAAO;AAClB,cAAc,UAAU;AACxB,cAAc,QAAQ;AACtB,cAAc,SAAS;AACvB,cAAc,OAAO;AACrB,cAAc,OAAO;AACrB,cAAc,cAAc;AAC5B;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,WAAW,SAAS;AACpB,YAAY;AACZ;AACA;;AAEA;;AAEA;;AAEA;AACA;;AAEA;;AAEA,KAAK;;AAEL;AACA;;AAEA,KAAK;;AAEL;;AAEA;AACA,YAAY;AACZ;AACA;AACA;AACA;;AAEA;AACA,YAAY;AACZ;AACA;AACA;AACA;;AAEA;AACA,YAAY;AACZ;AACA;AACA;AACA;;AAEA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,YAAY;AACZ;AACA;;AAEA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA,KAAK;;AAEL;;AAEA;;AAEA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;;AAEA;AACA,YAAY;AACZ;AACA;;AAEA;;AAEA;;AAEA;;AAEA;;AAEA;;AAEA,kEAAkE;;AAElE;;AAEA;;AAEA;AACA;;AAEA;;AAEA;;AAEA;;AAEA;;AAEA;;AAEA;;AAEA;;AAEA,SAAS;;AAET;;AAEA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB;AACA,YAAY;AACZ;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA,SAAS;;AAET;AACA;AACA;AACA;AACA,KAAK;;AAEL;AACA;AACA;AACA;AACA;AACA,KAAK;;AAEL;;AAEA,6B;;;;;;ACvQA;;AAEA;AACA;;;;;;;ACHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA,iBAAiB,SAAS;AAC1B;AACA;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA;AACA;;AAEA;AACA;;;;;;;AC/EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT,OAAO;AACP;AACA;AACA,KAAK;;AAEL;;AAEA;AACA;AACA;AACA;;;;;;;AC/DA;AACA;AACA;;AAEA;AACA;AACA,uBAAuB,aAAa,EAAE;;AAEtC;AACA;AACA,WAAW,OAAO;AAClB,WAAW,sBAAsB;AACjC,WAAW,QAAQ;AACnB,WAAW,MAAM;AACjB,WAAW,sBAAsB;AACjC,WAAW,uBAAuB;AAClC,WAAW,sBAAsB;AACjC,cAAc,OAAO;AACrB,cAAc,QAAQ;AACtB,cAAc,sBAAsB;AACpC,cAAc,MAAM;AACpB,cAAc,sBAAsB;AACpC,cAAc,uBAAuB;AACrC,cAAc,sBAAsB;AACpC;AACA;;AAEA;;AAEA;AACA,oHAAoH;AACpH;;AAEA,uDAAuD,sBAAsB;;AAE7E;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;;;;;;;;AC1DA,gD;;;;;;ACAA,gD;;;;;;ACAA,gD;;;;;;ACAA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,IAAI;AACf,WAAW,IAAI;AACf,WAAW,QAAQ;AACnB,WAAW,UAAU;AACrB,WAAW,MAAM;AACjB,WAAW,OAAO;AAClB,cAAc,UAAU;AACxB,cAAc,MAAM;AACpB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,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,QAAQ;AACnB,YAAY;AACZ;AACA;AACA,oCAAoC,GAAG,yCAAyC;AAChF;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;;AAEL;;AAEA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;;AAEA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;;AAEA,0B;;;;;;ACzpBA;AACA,WAAW,MAAM;AACjB,WAAW,OAAO;AAClB,WAAW,IAAI;AACf;AACA,cAAc,MAAM;AACpB,cAAc,IAAI;AAClB,cAAc,OAAO;AACrB;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA,qEAAqE;;AAErE;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA,aAAa;AACb;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;;AAEA;;AAEA;AACA;AACA,KAAK;;AAEL;AACA;;AAEA;;AAEA;;AAEA;;AAEA;AACA;AACA,YAAY;AACZ;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA,YAAY;AACZ;AACA;;AAEA;;AAEA;;AAEA;AACA,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA,KAAK;;AAEL;;AAEA;;AAEA;AACA;AACA;AACA;AACA,yBAAyB;AACzB;AACA;AACA,uCAAuC;AACvC;AACA;AACA;;;;;;;ACrHA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,E;;;;;;ACVA;;AAEA;AACA,WAAW,SAAS;AACpB,WAAW,UAAU;AACrB,WAAW,IAAI;AACf,WAAW,IAAI;AACf,cAAc,UAAU;AACxB,cAAc,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,WAAW,MAAM;AACjB,WAAW,OAAO;AAClB,WAAW,IAAI;AACf,WAAW,IAAI;AACf,YAAY;AACZ;AACA,cAAc,MAAM;AACpB;AACA;AACA;;AAEA;;AAEA;;AAEA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;;AAEA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,WAAW,SAAS;AACpB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;;AAEA,oC","file":"ringcentral.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory(require(undefined), require(undefined), require(undefined));\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([\"pubnub\", \"es6-promise\", \"fetch-ponyfill\"], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"SDK\"] = factory(require(undefined), require(undefined), require(undefined));\n\telse\n\t\troot[\"RingCentral\"] = root[\"RingCentral\"] || {}, root[\"RingCentral\"][\"SDK\"] = factory(root[undefined], root[undefined], root[undefined]);\n})(this, function(__WEBPACK_EXTERNAL_MODULE_12__, __WEBPACK_EXTERNAL_MODULE_13__, __WEBPACK_EXTERNAL_MODULE_14__) {\nreturn \n\n\n/** WEBPACK FOOTER **\n ** webpack/universalModuleDefinition\n **/"," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId])\n \t\t\treturn installedModules[moduleId].exports;\n\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\texports: {},\n \t\t\tid: moduleId,\n \t\t\tloaded: false\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.loaded = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"/build/\";\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(0);\n\n\n\n/** WEBPACK FOOTER **\n ** webpack/bootstrap e778b74917863b61271c\n **/","/**\n * @namespace RingCentral\n */\nvar objectAssign = require('object-assign');\nvar Cache = require(\"./core/Cache\");\nvar Client = require(\"./http/Client\");\nvar Externals = require(\"./core/Externals\");\nvar Platform = require(\"./platform/Platform\");\nvar Subscription = require(\"./subscription/Subscription\");\nvar CachedSubscription = require(\"./subscription/CachedSubscription\");\nvar Constants = require(\"./core/Constants\");\n\n/**\n * @constructor\n * @param {string} options.server\n * @param {string} options.appSecret\n * @param {string} options.appKey\n * @param {string} [options.cachePrefix]\n * @param {string} [options.appName]\n * @param {string} [options.appVersion]\n * @param {string} [options.redirectUri]\n * @param {PUBNUB} [options.PUBNUB]\n * @param {function(new:Promise)} [options.Promise]\n * @param {Storage} [options.localStorage]\n * @param {fetch} [options.fetch]\n * @param {function(new:Request)} [options.Request]\n * @param {function(new:Response)} [options.Response]\n * @param {function(new:Headers)} [options.Headers]\n * @param {int} [options.refreshDelayMs]\n * @param {int} [options.refreshHandicapMs]\n * @param {boolean} [options.clearCacheOnRefreshError]\n * @property {Externals} _externals\n * @property {Cache} _cache\n * @property {Client} _client\n * @property {Platform} _platform\n */\nfunction SDK(options) {\n\n /** @private */\n this._externals = new Externals(options);\n\n /** @private */\n this._cache = new Cache({\n externals: this._externals,\n prefix: options.cachePrefix\n });\n\n /** @private */\n this._client = new Client(this._externals);\n\n /** @private */\n this._platform = new Platform(objectAssign({}, options, {\n externals: this._externals,\n client: this._client,\n cache: this._cache\n }));\n\n}\n\nSDK.version = Constants.version;\n\nSDK.server = {\n sandbox: 'https://platform.devtest.ringcentral.com',\n production: 'https://platform.ringcentral.com'\n};\n\n/**\n * @return {Platform}\n */\nSDK.prototype.platform = function() {\n return this._platform;\n};\n\n/**\n * @return {Cache}\n */\nSDK.prototype.cache = function() {\n return this._cache;\n};\n\n/**\n * @param {int} [options.pollInterval]\n * @param {int} [options.renewHandicapMs]\n * @return {Subscription}\n */\nSDK.prototype.createSubscription = function(options) {\n return new Subscription(objectAssign({}, options, {\n externals: this._externals,\n platform: this._platform\n }));\n};\n\n/**\n * @param {string} options.cacheKey\n * @param {int} [options.pollInterval]\n * @param {int} [options.renewHandicapMs]\n * @return {CachedSubscription}\n */\nSDK.prototype.createCachedSubscription = function(options) {\n\n if (typeof arguments[0] == 'string') {\n options = {cacheKey: arguments[0].toString()};\n } else {\n options = options || {};\n }\n\n return new CachedSubscription(objectAssign({}, options, {\n externals: this._externals,\n platform: this._platform,\n cache: this._cache\n }));\n\n};\n\nSDK.handleLoginRedirect = function(origin) {\n\n var response = window.location.hash ? window.location.hash : window.location.search;\n var msg = {};\n msg[Constants.authResponseProperty] = response;\n window.opener.postMessage(msg, origin || window.location.origin);\n\n};\n\nmodule.exports = SDK;\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/SDK.js\n ** module id = 0\n ** module chunks = 0 1\n **/","'use strict';\n/* eslint-disable no-unused-vars */\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\nvar propIsEnumerable = Object.prototype.propertyIsEnumerable;\n\nfunction toObject(val) {\n\tif (val === null || val === undefined) {\n\t\tthrow new TypeError('Object.assign cannot be called with null or undefined');\n\t}\n\n\treturn Object(val);\n}\n\nfunction shouldUseNative() {\n\ttry {\n\t\tif (!Object.assign) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// Detect buggy property enumeration order in older V8 versions.\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=4118\n\t\tvar test1 = new String('abc'); // eslint-disable-line\n\t\ttest1[5] = 'de';\n\t\tif (Object.getOwnPropertyNames(test1)[0] === '5') {\n\t\t\treturn false;\n\t\t}\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=3056\n\t\tvar test2 = {};\n\t\tfor (var i = 0; i < 10; i++) {\n\t\t\ttest2['_' + String.fromCharCode(i)] = i;\n\t\t}\n\t\tvar order2 = Object.getOwnPropertyNames(test2).map(function (n) {\n\t\t\treturn test2[n];\n\t\t});\n\t\tif (order2.join('') !== '0123456789') {\n\t\t\treturn false;\n\t\t}\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=3056\n\t\tvar test3 = {};\n\t\t'abcdefghijklmnopqrst'.split('').forEach(function (letter) {\n\t\t\ttest3[letter] = letter;\n\t\t});\n\t\tif (Object.keys(Object.assign({}, test3)).join('') !==\n\t\t\t\t'abcdefghijklmnopqrst') {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t} catch (e) {\n\t\t// We don't expect any of the above to throw, but better to be safe.\n\t\treturn false;\n\t}\n}\n\nmodule.exports = shouldUseNative() ? Object.assign : function (target, source) {\n\tvar from;\n\tvar to = toObject(target);\n\tvar symbols;\n\n\tfor (var s = 1; s < arguments.length; s++) {\n\t\tfrom = Object(arguments[s]);\n\n\t\tfor (var key in from) {\n\t\t\tif (hasOwnProperty.call(from, key)) {\n\t\t\t\tto[key] = from[key];\n\t\t\t}\n\t\t}\n\n\t\tif (Object.getOwnPropertySymbols) {\n\t\t\tsymbols = Object.getOwnPropertySymbols(from);\n\t\t\tfor (var i = 0; i < symbols.length; i++) {\n\t\t\t\tif (propIsEnumerable.call(from, symbols[i])) {\n\t\t\t\t\tto[symbols[i]] = from[symbols[i]];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn to;\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/object-assign/index.js\n ** module id = 1\n ** module chunks = 0 1\n **/","/**\n * @param {Externals} options.externals\n * @param {string} [options.prefix]\n * @property {Externals} _externals\n */\nfunction Cache(options) {\n\n /** @private */\n this._prefix = options.prefix || Cache.defaultPrefix;\n\n /** @private */\n this._externals = options.externals;\n\n}\n\nCache.defaultPrefix = 'rc-';\n\nCache.prototype.setItem = function(key, data) {\n this._externals.localStorage[this._prefixKey(key)] = JSON.stringify(data);\n return this;\n};\n\nCache.prototype.removeItem = function(key) {\n delete this._externals.localStorage[this._prefixKey(key)];\n return this;\n};\n\nCache.prototype.getItem = function(key) {\n var item = this._externals.localStorage[this._prefixKey(key)];\n if (!item) return null;\n return JSON.parse(item);\n};\n\nCache.prototype.clean = function() {\n\n for (var key in this._externals.localStorage) {\n\n if (!this._externals.localStorage.hasOwnProperty(key)) continue;\n\n if (key.indexOf(this._prefix) === 0) {\n delete this._externals.localStorage[key];\n }\n\n }\n\n return this;\n\n};\n\nCache.prototype._prefixKey = function(key) {\n return this._prefix + key;\n};\n\nmodule.exports = Cache;\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/core/Cache.js\n ** module id = 2\n ** module chunks = 0 1\n **/","var isPlainObject = require(\"is-plain-object\");\nvar EventEmitter = require(\"events\").EventEmitter;\nvar ApiResponse = require(\"./ApiResponse\");\nvar qs = require(\"querystring\");\n\nfunction findHeaderName(name, headers) {\n name = name.toLowerCase();\n return Object.keys(headers).reduce(function(res, key) {\n if (res) return res;\n if (name == key.toLowerCase()) return key;\n return res;\n }, null);\n}\n\n/**\n * @param {Externals} externals\n * @property {Externals} _externals\n */\nfunction Client(externals) {\n\n EventEmitter.call(this);\n\n /** @private */\n this._externals = externals;\n\n this.events = {\n beforeRequest: 'beforeRequest',\n requestSuccess: 'requestSuccess',\n requestError: 'requestError'\n };\n\n}\n\nClient._allowedMethods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS', 'HEAD'];\n\nClient.prototype = Object.create(EventEmitter.prototype);\n\n/**\n * @param {Request} request\n * @return {Promise}\n */\nClient.prototype.sendRequest = function(request) {\n\n var apiResponse = new ApiResponse({\n externals: this._externals,\n request: request\n });\n\n return (new this._externals.Promise(function(resolve) {\n\n //TODO Stop request if listeners return false\n this.emit(this.events.beforeRequest, apiResponse);\n\n resolve(this._loadResponse(request));\n\n }.bind(this))).then(function(response) {\n\n return apiResponse.receiveResponse(response);\n\n }).then(function() {\n\n if (!apiResponse.ok()) throw new Error('Response has unsuccessful status');\n\n this.emit(this.events.requestSuccess, apiResponse);\n\n return apiResponse;\n\n }.bind(this)).catch(function(e) {\n\n if (!e.apiResponse) e = this.makeError(e, apiResponse);\n\n this.emit(this.events.requestError, e);\n\n throw e;\n\n }.bind(this));\n\n};\n\n/**\n * @param {Request} request\n * @return {Promise}\n * @private\n */\nClient.prototype._loadResponse = function(request) {\n return this._externals.fetch.call(null, request);\n};\n\n/**\n * Wraps the JS Error object with transaction information\n * @param {Error|IApiError} e\n * @param {ApiResponse} apiResponse\n * @return {IApiError}\n */\nClient.prototype.makeError = function(e, apiResponse) {\n\n // Wrap only if regular error\n if (!e.hasOwnProperty('apiResponse') && !e.hasOwnProperty('originalMessage')) {\n\n e.apiResponse = apiResponse;\n e.originalMessage = e.message;\n e.message = (apiResponse && apiResponse.error(true)) || e.originalMessage;\n\n }\n\n return e;\n\n};\n\n/**\n *\n * @param {object} init\n * @param {object} [init.url]\n * @param {object} [init.body]\n * @param {string} [init.method]\n * @param {object} [init.query]\n * @param {object} [init.headers]\n * @param {object} [init.credentials]\n * @param {object} [init.mode]\n * @return {Request}\n */\nClient.prototype.createRequest = function(init) {\n\n init = init || {};\n init.headers = init.headers || {};\n\n // Sanity checks\n if (!init.url) throw new Error('Url is not defined');\n if (!init.method) init.method = 'GET';\n init.method = init.method.toUpperCase();\n if (init.method && Client._allowedMethods.indexOf(init.method) < 0) {\n throw new Error('Method has wrong value: ' + init.method);\n }\n\n // Defaults\n init.credentials = init.credentials || 'include';\n init.mode = init.mode || 'cors';\n\n // Append Query String\n if (init.query) {\n init.url = init.url + (init.url.indexOf('?') > -1 ? '&' : '?') + qs.stringify(init.query);\n }\n\n if (!(findHeaderName('Accept', init.headers))) {\n init.headers.Accept = ApiResponse._jsonContentType;\n }\n\n // Serialize body\n if (isPlainObject(init.body) || !init.body) {\n\n var contentTypeHeaderName = findHeaderName(ApiResponse._contentType, init.headers);\n\n if (!contentTypeHeaderName) {\n contentTypeHeaderName = ApiResponse._contentType;\n init.headers[contentTypeHeaderName] = ApiResponse._jsonContentType;\n }\n\n var contentType = init.headers[contentTypeHeaderName];\n\n // Assign a new encoded body\n if (contentType.indexOf(ApiResponse._jsonContentType) > -1) {\n if ((init.method === 'GET' || init.method === 'HEAD') && !!init.body) {\n // oddly setting body to null still result in TypeError in phantomjs\n init.body = undefined;\n } else {\n init.body = JSON.stringify(init.body);\n }\n\n } else if (contentType.indexOf(ApiResponse._urlencodedContentType) > -1) {\n init.body = qs.stringify(init.body);\n }\n\n }\n\n // Create a request with encoded body\n var req = new this._externals.Request(init.url, init);\n\n // Keep the original body accessible directly (for mocks)\n req.originalBody = init.body;\n\n return req;\n\n};\n\n/**\n * @typedef {object} IApiError\n * @property {string} stack\n * @property {string} originalMessage\n * @property {ApiResponse} apiResponse\n */\n\nmodule.exports = Client;\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/http/Client.js\n ** module id = 3\n ** module chunks = 0 1\n **/","/*!\n * is-plain-object \n *\n * Copyright (c) 2014-2015, Jon Schlinkert.\n * Licensed under the MIT License.\n */\n\n'use strict';\n\nvar isObject = require('isobject');\n\nfunction isObjectObject(o) {\n return isObject(o) === true\n && Object.prototype.toString.call(o) === '[object Object]';\n}\n\nmodule.exports = function isPlainObject(o) {\n var ctor,prot;\n \n if (isObjectObject(o) === false) return false;\n \n // If has modified constructor\n ctor = o.constructor;\n if (typeof ctor !== 'function') return false;\n \n // If has modified prototype\n prot = ctor.prototype;\n if (isObjectObject(prot) === false) return false;\n \n // If constructor does not have an Object-specific method\n if (prot.hasOwnProperty('isPrototypeOf') === false) {\n return false;\n }\n \n // Most likely a plain Object\n return true;\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/is-plain-object/index.js\n ** module id = 4\n ** module chunks = 0 1\n **/","/*!\n * isobject \n *\n * Copyright (c) 2014-2015, Jon Schlinkert.\n * Licensed under the MIT License.\n */\n\n'use strict';\n\nmodule.exports = function isObject(val) {\n return val != null && typeof val === 'object'\n && !Array.isArray(val);\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/is-plain-object/~/isobject/index.js\n ** module id = 5\n ** module chunks = 0 1\n **/","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nfunction EventEmitter() {\n this._events = this._events || {};\n this._maxListeners = this._maxListeners || undefined;\n}\nmodule.exports = EventEmitter;\n\n// Backwards-compat with node 0.10.x\nEventEmitter.EventEmitter = EventEmitter;\n\nEventEmitter.prototype._events = undefined;\nEventEmitter.prototype._maxListeners = undefined;\n\n// By default EventEmitters will print a warning if more than 10 listeners are\n// added to it. This is a useful default which helps finding memory leaks.\nEventEmitter.defaultMaxListeners = 10;\n\n// Obviously not all Emitters should be limited to 10. This function allows\n// that to be increased. Set to zero for unlimited.\nEventEmitter.prototype.setMaxListeners = function(n) {\n if (!isNumber(n) || n < 0 || isNaN(n))\n throw TypeError('n must be a positive number');\n this._maxListeners = n;\n return this;\n};\n\nEventEmitter.prototype.emit = function(type) {\n var er, handler, len, args, i, listeners;\n\n if (!this._events)\n this._events = {};\n\n // If there is no 'error' event listener then throw.\n if (type === 'error') {\n if (!this._events.error ||\n (isObject(this._events.error) && !this._events.error.length)) {\n er = arguments[1];\n if (er instanceof Error) {\n throw er; // Unhandled 'error' event\n } else {\n // At least give some kind of context to the user\n var err = new Error('Uncaught, unspecified \"error\" event. (' + er + ')');\n err.context = er;\n throw err;\n }\n }\n }\n\n handler = this._events[type];\n\n if (isUndefined(handler))\n return false;\n\n if (isFunction(handler)) {\n switch (arguments.length) {\n // fast cases\n case 1:\n handler.call(this);\n break;\n case 2:\n handler.call(this, arguments[1]);\n break;\n case 3:\n handler.call(this, arguments[1], arguments[2]);\n break;\n // slower\n default:\n args = Array.prototype.slice.call(arguments, 1);\n handler.apply(this, args);\n }\n } else if (isObject(handler)) {\n args = Array.prototype.slice.call(arguments, 1);\n listeners = handler.slice();\n len = listeners.length;\n for (i = 0; i < len; i++)\n listeners[i].apply(this, args);\n }\n\n return true;\n};\n\nEventEmitter.prototype.addListener = function(type, listener) {\n var m;\n\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n if (!this._events)\n this._events = {};\n\n // To avoid recursion in the case that type === \"newListener\"! Before\n // adding it to the listeners, first emit \"newListener\".\n if (this._events.newListener)\n this.emit('newListener', type,\n isFunction(listener.listener) ?\n listener.listener : listener);\n\n if (!this._events[type])\n // Optimize the case of one listener. Don't need the extra array object.\n this._events[type] = listener;\n else if (isObject(this._events[type]))\n // If we've already got an array, just append.\n this._events[type].push(listener);\n else\n // Adding the second element, need to change to array.\n this._events[type] = [this._events[type], listener];\n\n // Check for listener leak\n if (isObject(this._events[type]) && !this._events[type].warned) {\n if (!isUndefined(this._maxListeners)) {\n m = this._maxListeners;\n } else {\n m = EventEmitter.defaultMaxListeners;\n }\n\n if (m && m > 0 && this._events[type].length > m) {\n this._events[type].warned = true;\n console.error('(node) warning: possible EventEmitter memory ' +\n 'leak detected. %d listeners added. ' +\n 'Use emitter.setMaxListeners() to increase limit.',\n this._events[type].length);\n if (typeof console.trace === 'function') {\n // not supported in IE 10\n console.trace();\n }\n }\n }\n\n return this;\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.once = function(type, listener) {\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n var fired = false;\n\n function g() {\n this.removeListener(type, g);\n\n if (!fired) {\n fired = true;\n listener.apply(this, arguments);\n }\n }\n\n g.listener = listener;\n this.on(type, g);\n\n return this;\n};\n\n// emits a 'removeListener' event iff the listener was removed\nEventEmitter.prototype.removeListener = function(type, listener) {\n var list, position, length, i;\n\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n if (!this._events || !this._events[type])\n return this;\n\n list = this._events[type];\n length = list.length;\n position = -1;\n\n if (list === listener ||\n (isFunction(list.listener) && list.listener === listener)) {\n delete this._events[type];\n if (this._events.removeListener)\n this.emit('removeListener', type, listener);\n\n } else if (isObject(list)) {\n for (i = length; i-- > 0;) {\n if (list[i] === listener ||\n (list[i].listener && list[i].listener === listener)) {\n position = i;\n break;\n }\n }\n\n if (position < 0)\n return this;\n\n if (list.length === 1) {\n list.length = 0;\n delete this._events[type];\n } else {\n list.splice(position, 1);\n }\n\n if (this._events.removeListener)\n this.emit('removeListener', type, listener);\n }\n\n return this;\n};\n\nEventEmitter.prototype.removeAllListeners = function(type) {\n var key, listeners;\n\n if (!this._events)\n return this;\n\n // not listening for removeListener, no need to emit\n if (!this._events.removeListener) {\n if (arguments.length === 0)\n this._events = {};\n else if (this._events[type])\n delete this._events[type];\n return this;\n }\n\n // emit removeListener for all listeners on all events\n if (arguments.length === 0) {\n for (key in this._events) {\n if (key === 'removeListener') continue;\n this.removeAllListeners(key);\n }\n this.removeAllListeners('removeListener');\n this._events = {};\n return this;\n }\n\n listeners = this._events[type];\n\n if (isFunction(listeners)) {\n this.removeListener(type, listeners);\n } else if (listeners) {\n // LIFO order\n while (listeners.length)\n this.removeListener(type, listeners[listeners.length - 1]);\n }\n delete this._events[type];\n\n return this;\n};\n\nEventEmitter.prototype.listeners = function(type) {\n var ret;\n if (!this._events || !this._events[type])\n ret = [];\n else if (isFunction(this._events[type]))\n ret = [this._events[type]];\n else\n ret = this._events[type].slice();\n return ret;\n};\n\nEventEmitter.prototype.listenerCount = function(type) {\n if (this._events) {\n var evlistener = this._events[type];\n\n if (isFunction(evlistener))\n return 1;\n else if (evlistener)\n return evlistener.length;\n }\n return 0;\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n return emitter.listenerCount(type);\n};\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/events/events.js\n ** module id = 6\n ** module chunks = 0 1\n **/","/**\n * @param {Externals} options.externals\n * @param {Request} [options.request]\n * @param {Response} [options.response]\n * @param {string} [options.responseText]\n * @property {Externals} _externals\n * @property {Request} _request\n * @property {Response} _response\n * @property {string} _text\n * @property {object} _json\n * @property {ApiResponse[]} _multipart\n */\nfunction ApiResponse(options) {\n\n /** @private */\n this._externals = options.externals;\n\n /** @private */\n this._request = options.request;\n\n /** @private */\n this._response = options.response;\n\n /** @private */\n this._text = options.responseText || '';\n\n /** @private */\n this._json = null;\n\n /** @private */\n this._multipart = [];\n\n}\n\nApiResponse._contentType = 'Content-Type';\nApiResponse._jsonContentType = 'application/json';\nApiResponse._multipartContentType = 'multipart/mixed';\nApiResponse._urlencodedContentType = 'application/x-www-form-urlencoded';\nApiResponse._headerSeparator = ':';\nApiResponse._bodySeparator = '\\n\\n';\nApiResponse._boundarySeparator = '--';\nApiResponse._unauthorizedStatus = 401;\n\n/**\n * @param {Response} response\n * @return {Promise}\n */\nApiResponse.prototype.receiveResponse = function(response) {\n\n this._response = response;\n\n return (new this._externals.Promise(function(resolve) {\n\n // Ignore if not textual type\n if (!this._isMultipart() && !this._isJson()) return resolve('');\n\n return resolve(this.response().text());\n\n }.bind(this))).then(function(text) {\n\n this._text = text;\n return text;\n\n }.bind(this));\n\n};\n\n/**\n * @return {Response}\n */\nApiResponse.prototype.response = function() {\n return this._response;\n};\n\n/**\n * @return {Request}\n */\nApiResponse.prototype.request = function() {\n return this._request;\n};\n\n/**\n * @return {boolean}\n */\nApiResponse.prototype.ok = function() {\n return this._response && this._response.ok;\n};\n\n/**\n * @return {string}\n */\nApiResponse.prototype.text = function() {\n // Since we read text only in case JSON or Multipart\n if (!this._isJson() && !this._isMultipart()) throw new Error('Response is not text');\n return this._text;\n};\n\n/**\n * @return {object}\n */\nApiResponse.prototype.json = function() {\n if (!this._isJson()) throw new Error('Response is not JSON');\n if (!this._json) {\n this._json = this._text ? JSON.parse(this._text) : null;\n }\n return this._json;\n};\n\n/**\n * @param [skipOKCheck]\n * @return {string}\n */\nApiResponse.prototype.error = function(skipOKCheck) {\n\n if (this.ok() && !skipOKCheck) return null;\n\n var message = (this._response && this._response.status ? this._response.status + ' ' : '') +\n (this._response && this._response.statusText ? this._response.statusText : '');\n\n try {\n\n if (this.json().message) message = this.json().message;\n if (this.json().error_description) message = this.json().error_description;\n if (this.json().description) message = this.json().description;\n\n } catch (e) {}\n\n return message;\n\n};\n\n/**\n * If it is not known upfront what would be the response, client code can treat any response as multipart\n * @return {ApiResponse[]}\n */\nApiResponse.prototype.toMultipart = function() {\n if (!this._isMultipart()) return [this];\n return this.multipart();\n};\n\n/**\n * @return {ApiResponse[]}\n */\nApiResponse.prototype.multipart = function() {\n\n if (!this._isMultipart()) throw new Error('Response is not multipart');\n\n if (!this._multipart.length) {\n\n // Step 1. Split multipart response\n\n var text = this.text();\n\n if (!text) throw new Error('No response body');\n\n var boundary = this._getContentType().match(/boundary=([^;]+)/i)[1];\n\n if (!boundary) throw new Error('Cannot find boundary');\n\n var parts = text.toString().split(ApiResponse._boundarySeparator + boundary);\n\n if (parts[0].trim() === '') parts.shift();\n if (parts[parts.length - 1].trim() == ApiResponse._boundarySeparator) parts.pop();\n\n if (parts.length < 1) throw new Error('No parts in body');\n\n // Step 2. Parse status info\n\n var statusInfo = this._create(parts.shift(), this._response.status, this._response.statusText).json();\n\n // Step 3. Parse all other parts\n\n this._multipart = parts.map(function(part, i) {\n\n var status = statusInfo.response[i].status;\n\n return this._create(part, status);\n\n }.bind(this));\n\n }\n\n return this._multipart;\n\n};\n\n/**\n * @private\n */\nApiResponse.prototype._isContentType = function(contentType) {\n return this._getContentType().indexOf(contentType) > -1;\n};\n\n/**\n * @private\n */\nApiResponse.prototype._getContentType = function() {\n return this._response.headers.get(ApiResponse._contentType) || '';\n};\n\n/**\n * @private\n */\nApiResponse.prototype._isMultipart = function() {\n return this._isContentType(ApiResponse._multipartContentType);\n};\n\n/**\n * @private\n */\nApiResponse.prototype._isJson = function() {\n return this._isContentType(ApiResponse._jsonContentType);\n};\n\n/**\n * Method is used to create ApiResponse object from string parts of multipart/mixed response\n * @param {string} [text]\n * @param {number} [status]\n * @param {string} [statusText]\n * @private\n * @return {ApiResponse}\n */\nApiResponse.prototype._create = function(text, status, statusText) {\n\n text = text || '';\n status = status || 200;\n statusText = statusText || 'OK';\n\n text = text.replace(/\\r/g, '');\n\n var headers = new this._externals.Headers(),\n headersAndBody = text.split(ApiResponse._bodySeparator),\n headersText = (headersAndBody.length > 1) ? headersAndBody.shift() : '';\n\n text = headersAndBody.length > 0 ? headersAndBody.join(ApiResponse._bodySeparator) : null;\n\n (headersText || '')\n .split('\\n')\n .forEach(function(header) {\n\n var split = header.trim().split(ApiResponse._headerSeparator),\n key = split.shift().trim(),\n value = split.join(ApiResponse._headerSeparator).trim();\n\n if (key) headers.append(key, value);\n\n });\n\n var response = new this._externals.Response(text, {\n headers: headers,\n status: status,\n statusText: statusText\n });\n\n return new ApiResponse({\n externals: this._externals,\n request: null,\n response: response,\n responseText: text\n });\n\n};\n\nmodule.exports = ApiResponse;\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/http/ApiResponse.js\n ** module id = 7\n ** module chunks = 0 1\n **/","'use strict';\n\nexports.decode = exports.parse = require('./decode');\nexports.encode = exports.stringify = require('./encode');\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/querystring/index.js\n ** module id = 8\n ** module chunks = 0 1\n **/","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n// If obj.hasOwnProperty has been overridden, then calling\n// obj.hasOwnProperty(prop) will break.\n// See: https://github.com/joyent/node/issues/1707\nfunction hasOwnProperty(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n\nmodule.exports = function(qs, sep, eq, options) {\n sep = sep || '&';\n eq = eq || '=';\n var obj = {};\n\n if (typeof qs !== 'string' || qs.length === 0) {\n return obj;\n }\n\n var regexp = /\\+/g;\n qs = qs.split(sep);\n\n var maxKeys = 1000;\n if (options && typeof options.maxKeys === 'number') {\n maxKeys = options.maxKeys;\n }\n\n var len = qs.length;\n // maxKeys <= 0 means that we should not limit keys count\n if (maxKeys > 0 && len > maxKeys) {\n len = maxKeys;\n }\n\n for (var i = 0; i < len; ++i) {\n var x = qs[i].replace(regexp, '%20'),\n idx = x.indexOf(eq),\n kstr, vstr, k, v;\n\n if (idx >= 0) {\n kstr = x.substr(0, idx);\n vstr = x.substr(idx + 1);\n } else {\n kstr = x;\n vstr = '';\n }\n\n k = decodeURIComponent(kstr);\n v = decodeURIComponent(vstr);\n\n if (!hasOwnProperty(obj, k)) {\n obj[k] = v;\n } else if (Array.isArray(obj[k])) {\n obj[k].push(v);\n } else {\n obj[k] = [obj[k], v];\n }\n }\n\n return obj;\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/querystring/decode.js\n ** module id = 9\n ** module chunks = 0 1\n **/","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nvar stringifyPrimitive = function(v) {\n switch (typeof v) {\n case 'string':\n return v;\n\n case 'boolean':\n return v ? 'true' : 'false';\n\n case 'number':\n return isFinite(v) ? v : '';\n\n default:\n return '';\n }\n};\n\nmodule.exports = function(obj, sep, eq, name) {\n sep = sep || '&';\n eq = eq || '=';\n if (obj === null) {\n obj = undefined;\n }\n\n if (typeof obj === 'object') {\n return Object.keys(obj).map(function(k) {\n var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;\n if (Array.isArray(obj[k])) {\n return obj[k].map(function(v) {\n return ks + encodeURIComponent(stringifyPrimitive(v));\n }).join(sep);\n } else {\n return ks + encodeURIComponent(stringifyPrimitive(obj[k]));\n }\n }).join(sep);\n\n }\n\n if (!name) return '';\n return encodeURIComponent(stringifyPrimitive(name)) + eq +\n encodeURIComponent(stringifyPrimitive(obj));\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/querystring/encode.js\n ** module id = 10\n ** module chunks = 0 1\n **/","var pubnub = require(\"pubnub\");\nvar es6Promise = require(\"es6-promise\");\nvar FetchPonyfill = require(\"fetch-ponyfill\");\n\nvar root = (typeof window !== \"undefined\" && window) ||\n (typeof global !== \"undefined\" && global) ||\n (function(){ return this; })();\n\n/**\n * @constructor\n * @param {PUBNUB} [options.PUBNUB]\n * @param {function(new:Promise)} [options.Promise]\n * @param {Storage} [options.localStorage]\n * @param {fetch} [options.fetch]\n * @param {function(new:Request)} [options.Request]\n * @param {function(new:Response)} [options.Response]\n * @param {function(new:Headers)} [options.Headers]\n * @property {PUBNUB} PUBNUB\n * @property {Storage} localStorage\n * @property {function(new:Promise)} Promise\n * @property {fetch} fetch\n * @property {function(new:Request)} Request\n * @property {function(new:Response)} Response\n * @property {function(new:Headers)} Headers\n */\nfunction Externals(options) {\n\n options = options || {};\n\n this.PUBNUB = options.PUBNUB || root.PUBNUB || pubnub;\n this.localStorage = options.localStorage || ((typeof root.localStorage !== 'undefined') ? root.localStorage : {});\n this.Promise = options.Promise || root.Promise || (es6Promise && es6Promise.Promise);\n\n var fetchPonyfill = FetchPonyfill ? FetchPonyfill({Promise: this.Promise}) : {};\n\n this.fetch = options.fetch || root.fetch || fetchPonyfill.fetch;\n this.Request = options.Request || root.Request || fetchPonyfill.Request;\n this.Response = options.Response || root.Response || fetchPonyfill.Response;\n this.Headers = options.Headers || root.Headers || fetchPonyfill.Headers;\n\n if (!this.fetch || !this.Response || !this.Request || !this.Headers) {\n throw new Error('Fetch API is missing');\n }\n\n if (!this.Promise) {\n throw new Error('Promise is missing');\n }\n\n if (!this.localStorage) {\n throw new Error('LocalStorage is missing');\n }\n\n if (!this.PUBNUB) {\n throw new Error('PUBNUB is missing');\n }\n\n}\n\nmodule.exports = Externals;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/core/Externals.js\n ** module id = 11\n ** module chunks = 0 1\n **/","module.exports = __WEBPACK_EXTERNAL_MODULE_12__;\n\n\n/*****************\n ** WEBPACK FOOTER\n ** external {\"amd\":\"pubnub\"}\n ** module id = 12\n ** module chunks = 0 1\n **/","module.exports = __WEBPACK_EXTERNAL_MODULE_13__;\n\n\n/*****************\n ** WEBPACK FOOTER\n ** external {\"amd\":\"es6-promise\"}\n ** module id = 13\n ** module chunks = 0 1\n **/","module.exports = __WEBPACK_EXTERNAL_MODULE_14__;\n\n\n/*****************\n ** WEBPACK FOOTER\n ** external {\"amd\":\"fetch-ponyfill\"}\n ** module id = 14\n ** module chunks = 0 1\n **/","var EventEmitter = require(\"events\").EventEmitter;\nvar qs = require(\"querystring\");\nvar objectAssign = require('object-assign');\nvar Auth = require(\"./Auth\");\nvar Constants = require(\"../core/Constants\");\nvar ApiResponse = require(\"../http/ApiResponse\");\n\n/**\n * @constructor\n * @param {string} options.server\n * @param {string} options.appSecret\n * @param {string} options.appKey\n * @param {string} [options.appName]\n * @param {string} [options.appVersion]\n * @param {string} [options.redirectUri]\n * @param {int} [options.refreshDelayMs]\n * @param {int} [options.refreshHandicapMs]\n * @param {boolean} [options.clearCacheOnRefreshError]\n * @param {Externals} options.externals\n * @param {Cache} options.cache\n * @param {Client} options.client\n * @property {Externals} _externals\n * @property {Cache} _cache\n * @property {Client} _client\n * @property {Promise} _refreshPromise\n * @property {Auth} _auth\n */\nfunction Platform(options) {\n\n EventEmitter.call(this);\n\n this.events = {\n beforeLogin: 'beforeLogin',\n loginSuccess: 'loginSuccess',\n loginError: 'loginError',\n beforeRefresh: 'beforeRefresh',\n refreshSuccess: 'refreshSuccess',\n refreshError: 'refreshError',\n beforeLogout: 'beforeLogout',\n logoutSuccess: 'logoutSuccess',\n logoutError: 'logoutError'\n };\n\n options = options || {};\n\n /** @private */\n this._server = options.server;\n\n /** @private */\n this._appKey = options.appKey;\n\n /** @private */\n this._appSecret = options.appSecret;\n\n /** @private */\n this._redirectUri = options.redirectUri || '';\n\n /** @private */\n this._refreshDelayMs = options.refreshDelayMs || 100;\n\n /** @private */\n this._clearCacheOnRefreshError = typeof options.clearCacheOnRefreshError !== 'undefined' ?\n options.clearCacheOnRefreshError :\n true;\n\n /** @private */\n this._userAgent = (options.appName ?\n (options.appName + (options.appVersion ? '/' + options.appVersion : '')) + ' ' :\n '') + 'RCJSSDK/' + Constants.version;\n\n /** @private */\n this._externals = options.externals;\n\n /** @private */\n this._cache = options.cache;\n\n /** @private */\n this._client = options.client;\n\n /** @private */\n this._refreshPromise = null;\n\n /** @private */\n this._auth = new Auth({\n cache: this._cache,\n cacheId: Platform._cacheId,\n refreshHandicapMs: options.refreshHandicapMs\n });\n\n}\n\nPlatform._urlPrefix = '/restapi';\nPlatform._apiVersion = 'v1.0';\nPlatform._tokenEndpoint = '/restapi/oauth/token';\nPlatform._revokeEndpoint = '/restapi/oauth/revoke';\nPlatform._authorizeEndpoint = '/restapi/oauth/authorize';\nPlatform._cacheId = 'platform';\n\nPlatform.prototype = Object.create(EventEmitter.prototype);\n\nPlatform.prototype.delay = function(timeout) {\n return new this._externals.Promise(function(resolve, reject) {\n setTimeout(function() {\n resolve(null);\n }, timeout);\n });\n};\n\n/**\n * @return {Auth}\n */\nPlatform.prototype.auth = function() {\n return this._auth;\n};\n\n/**\n * @return {Client}\n */\nPlatform.prototype.client = function() {\n return this._client;\n};\n\n/**\n * @param {string} path\n * @param {object} [options]\n * @param {boolean} [options.addServer]\n * @param {string} [options.addMethod]\n * @param {boolean} [options.addToken]\n * @return {string}\n */\nPlatform.prototype.createUrl = function(path, options) {\n\n path = path || '';\n options = options || {};\n\n var builtUrl = '',\n hasHttp = path.indexOf('http://') != -1 || path.indexOf('https://') != -1;\n\n if (options.addServer && !hasHttp) builtUrl += this._server;\n\n if (path.indexOf(Platform._urlPrefix) == -1 && !hasHttp) builtUrl += Platform._urlPrefix + '/' + Platform._apiVersion;\n\n builtUrl += path;\n\n if (options.addMethod || options.addToken) builtUrl += (path.indexOf('?') > -1 ? '&' : '?');\n\n if (options.addMethod) builtUrl += '_method=' + options.addMethod;\n if (options.addToken) builtUrl += (options.addMethod ? '&' : '') + 'access_token=' + this._auth.accessToken();\n\n return builtUrl;\n\n};\n\n/**\n * @param {string} [options.redirectUri] Overrides default RedirectURI\n * @param {string} [options.state]\n * @param {string} [options.brandId]\n * @param {string} [options.display]\n * @param {string} [options.prompt]\n * @param {boolean} [options.implicit] Use Implicit Grant flow\n * @return {string}\n */\nPlatform.prototype.loginUrl = function(options) {\n\n options = options || {};\n\n return this.createUrl(Platform._authorizeEndpoint + '?' + qs.stringify({\n 'response_type': options.implicit ? 'token' : 'code',\n 'redirect_uri': options.redirectUri || this._redirectUri,\n 'client_id': this._appKey,\n 'state': options.state || '',\n 'brand_id': options.brandId || '',\n 'display': options.display || '',\n 'prompt': options.prompt || ''\n }), {addServer: true});\n\n};\n\n/**\n * @param {string} url\n * @return {Object}\n */\nPlatform.prototype.parseLoginRedirect = function(url) {\n\n function getParts(url, separator) {\n return url.split(separator).reverse()[0];\n }\n\n var response = (url.indexOf('#') === 0 && getParts(url, '#')) ||\n (url.indexOf('?') === 0 && getParts(url, '?')) ||\n null;\n\n if (!response) throw new Error('Unable to parse response');\n\n var queryString = qs.parse(response);\n\n if (!queryString) throw new Error('Unable to parse response');\n\n var error = queryString.error_description || queryString.error;\n\n if (error) {\n var e = new Error(error);\n e.error = queryString.error;\n throw e;\n }\n\n return queryString;\n\n};\n\n/**\n * Convenience method to handle 3-legged OAuth\n *\n * Attention! This is an experimental method and it's signature and behavior may change without notice.\n *\n * @experimental\n * @param {string} options.url\n * @param {number} [options.width]\n * @param {number} [options.height]\n * @param {object} [options.login] additional options for login()\n * @param {string} [options.origin]\n * @param {string} [options.property] name of window.postMessage's event data property\n * @param {string} [options.target] target for window.open()\n * @return {Promise}\n */\nPlatform.prototype.loginWindow = function(options) {\n\n return new this._externals.Promise(function(resolve, reject) {\n\n if (typeof window === 'undefined') throw new Error('This method can be used only in browser');\n\n if (!options.url) throw new Error('Missing mandatory URL parameter');\n\n options = options || {};\n options.url = options.url || 400;\n options.width = options.width || 400;\n options.height = options.height || 600;\n options.origin = options.origin || window.location.origin;\n options.property = options.property || Constants.authResponseProperty;\n options.target = options.target || '_blank';\n\n var dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left;\n var dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top;\n\n var width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;\n var height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;\n\n var left = ((width / 2) - (options.width / 2)) + dualScreenLeft;\n var top = ((height / 2) - (options.height / 2)) + dualScreenTop;\n var win = window.open(options.url, '_blank', (options.target == '_blank') ? 'scrollbars=yes, status=yes, width=' + options.width + ', height=' + options.height + ', left=' + left + ', top=' + top : '');\n\n if(!win) {\n throw new Error('Could not open login window. Please allow popups for this site');\n }\n\n if (win.focus) win.focus();\n\n var eventMethod = window.addEventListener ? 'addEventListener' : 'attachEvent';\n var eventRemoveMethod = eventMethod == 'addEventListener' ? 'removeEventListener' : 'detachEvent';\n var messageEvent = eventMethod == 'addEventListener' ? 'message' : 'onmessage';\n\n var eventListener = function(e) {\n\n try {\n\n if (e.origin != options.origin) return;\n if (!e.data || !e.data[options.property]) return; // keep waiting\n\n win.close();\n window[eventRemoveMethod](messageEvent, eventListener);\n\n\n var loginOptions = this.parseLoginRedirect(e.data[options.property]);\n\n if (!loginOptions.code && !loginOptions.access_token) throw new Error('No authorization code or token');\n\n resolve(loginOptions);\n\n /* jshint -W002 */\n } catch (e) {\n reject(e);\n }\n\n }.bind(this);\n\n window[eventMethod](messageEvent, eventListener, false);\n\n }.bind(this));\n\n};\n\n/**\n * @return {Promise}\n */\nPlatform.prototype.loggedIn = function() {\n\n return this.ensureLoggedIn().then(function() {\n return true;\n }).catch(function() {\n return false;\n });\n\n};\n\n/**\n * @param {string} options.username\n * @param {string} options.password\n * @param {string} [options.extension]\n * @param {string} [options.code]\n * @param {string} [options.redirectUri]\n * @param {string} [options.endpointId]\n * @param {string} [options.accessTokenTtl]\n * @param {string} [options.refreshTokenTtl]\n * @param {string} [options.access_token]\n * @returns {Promise}\n */\nPlatform.prototype.login = function(options) {\n\n return (new this._externals.Promise(function(resolve) {\n\n options = options || {};\n\n this.emit(this.events.beforeLogin);\n\n var body = {};\n\n if (options.access_token) {\n\n //TODO Potentially make a request to /oauth/tokeninfo\n return resolve(options);\n\n }\n\n if (!options.code) {\n\n body.grant_type = 'password';\n body.username = options.username;\n body.password = options.password;\n body.extension = options.extension || '';\n\n } else if (options.code) {\n\n body.grant_type = 'authorization_code';\n body.code = options.code;\n body.redirect_uri = options.redirectUri || this._redirectUri;\n //body.client_id = this.getCredentials().key; // not needed\n\n }\n\n if (options.endpointId) body.endpoint_id = options.endpointId;\n if (options.accessTokenTtl) body.accessTokenTtl = options.accessTokenTtl;\n if (options.refreshTokenTtl) body.refreshTokenTtl = options.refreshTokenTtl;\n\n resolve(this._tokenRequest(Platform._tokenEndpoint, body));\n\n }.bind(this))).then(function(res) {\n\n var apiResponse = res.json ? res : null;\n var json = apiResponse && apiResponse.json() || res;\n\n this._auth.setData(json);\n\n this.emit(this.events.loginSuccess, apiResponse);\n\n return apiResponse;\n\n }.bind(this)).catch(function(e) {\n\n if (this._clearCacheOnRefreshError) {\n this._cache.clean();\n }\n\n this.emit(this.events.loginError, e);\n\n throw e;\n\n }.bind(this));\n\n};\n\n/**\n * @returns {Promise}\n * @private\n */\nPlatform.prototype._refresh = function() {\n\n return this.delay(this._refreshDelayMs).then(function() {\n\n this.emit(this.events.beforeRefresh);\n\n // Perform sanity checks\n if (!this._auth.refreshToken()) throw new Error('Refresh token is missing');\n if (!this._auth.refreshTokenValid()) throw new Error('Refresh token has expired');\n\n return this._tokenRequest(Platform._tokenEndpoint, {\n \"grant_type\": \"refresh_token\",\n \"refresh_token\": this._auth.refreshToken(),\n \"access_token_ttl\": this._auth.data().expires_in + 1,\n \"refresh_token_ttl\": this._auth.data().refresh_token_expires_in + 1\n });\n\n }.bind(this)).then(function(/** @type {ApiResponse} */ res) {\n\n var json = res.json();\n\n if (!json.access_token) {\n throw this._client.makeError(new Error('Malformed OAuth response'), res);\n }\n\n this._auth.setData(json);\n\n this.emit(this.events.refreshSuccess, res);\n\n return res;\n\n }.bind(this)).catch(function(e) {\n\n e = this._client.makeError(e);\n\n if (this._clearCacheOnRefreshError) {\n this._cache.clean();\n }\n\n this.emit(this.events.refreshError, e);\n\n throw e;\n\n }.bind(this));\n\n};\n\n/**\n * @returns {Promise}\n */\nPlatform.prototype.refresh = function() {\n\n if (!this._refreshPromise) {\n\n this._refreshPromise = this._refresh()\n .then(function(res) {\n this._refreshPromise = null;\n return res;\n }.bind(this))\n .catch(function(e) {\n this._refreshPromise = null;\n throw e;\n }.bind(this));\n\n }\n\n return this._refreshPromise;\n\n};\n\n/**\n * @returns {Promise}\n */\nPlatform.prototype.logout = function() {\n\n return (new this._externals.Promise(function(resolve) {\n\n this.emit(this.events.beforeLogout);\n\n resolve(this._tokenRequest(Platform._revokeEndpoint, {\n token: this._auth.accessToken()\n }));\n\n }.bind(this))).then(function(res) {\n\n this._cache.clean();\n\n this.emit(this.events.logoutSuccess, res);\n\n return res;\n\n }.bind(this)).catch(function(e) {\n\n this.emit(this.events.logoutError, e);\n\n throw e;\n\n }.bind(this));\n\n};\n\n/**\n * @param {Request} request\n * @param {object} [options]\n * @param {boolean} [options.skipAuthCheck]\n * @return {Promise}\n */\nPlatform.prototype.inflateRequest = function(request, options) {\n\n options = options || {};\n\n if (options.skipAuthCheck) return this._externals.Promise.resolve(request);\n\n return this.ensureLoggedIn().then(function() {\n\n request.headers.set('X-User-Agent', this._userAgent);\n request.headers.set('Client-Id', this._appKey);\n request.headers.set('Authorization', this._authHeader());\n //request.url = this.createUrl(request.url, {addServer: true}); //FIXME Spec prevents this...\n\n return request;\n\n }.bind(this));\n\n};\n\n/**\n * @param {Request} request\n * @param {object} [options]\n * @param {boolean} [options.skipAuthCheck]\n * @param {boolean} [options.retry] Will be set by this method if SDK makes second request\n * @return {Promise}\n */\nPlatform.prototype.sendRequest = function(request, options) {\n\n return this.inflateRequest(request, options).then(function(request) {\n\n options = options || {};\n\n return this._client.sendRequest(request);\n\n }.bind(this)).catch(function(e) {\n\n // Guard is for errors that come from polling\n if (!e.apiResponse || !e.apiResponse.response() ||\n (e.apiResponse.response().status != ApiResponse._unauthorizedStatus) ||\n options.retry) throw e;\n\n this._auth.cancelAccessToken();\n\n options.retry = true;\n\n return this.sendRequest(request, options);\n\n }.bind(this));\n\n};\n\n/**\n * General purpose function to send anything to server\n * @param {string} options.url\n * @param {object} [options.body]\n * @param {string} [options.method]\n * @param {object} [options.query]\n * @param {object} [options.headers]\n * @param {boolean} [options.skipAuthCheck]\n * @return {Promise}\n */\nPlatform.prototype.send = function(options) {\n\n options = options || {};\n\n //FIXME https://github.com/bitinn/node-fetch/issues/43\n options.url = this.createUrl(options.url, {addServer: true});\n\n return this.sendRequest(this._client.createRequest(options), options);\n\n};\n\n/**\n * @param {string} url\n * @param {object} [query]\n * @param {object} [options]\n * @param {object} [options.headers]\n * @param {boolean} [options.skipAuthCheck]\n * @return {Promise}\n */\nPlatform.prototype.get = function(url, query, options) {\n return this.send(objectAssign({}, {method: 'GET', url: url, query: query}, options));\n};\n\n/**\n * @param {string} url\n * @param {object} body\n * @param {object} [query]\n * @param {object} [options]\n * @param {object} [options.headers]\n * @param {boolean} [options.skipAuthCheck]\n * @return {Promise}\n */\nPlatform.prototype.post = function(url, body, query, options) {\n return this.send(objectAssign({}, {method: 'POST', url: url, query: query, body: body}, options));\n};\n\n/**\n * @param {string} url\n * @param {object} [body]\n * @param {object} [query]\n * @param {object} [options]\n * @param {object} [options.headers]\n * @param {boolean} [options.skipAuthCheck]\n * @return {Promise}\n */\nPlatform.prototype.put = function(url, body, query, options) {\n return this.send(objectAssign({}, {method: 'PUT', url: url, query: query, body: body}, options));\n};\n\n/**\n * @param {string} url\n * @param {string} [query]\n * @param {object} [options]\n * @param {object} [options.headers]\n * @param {boolean} [options.skipAuthCheck]\n * @return {Promise}\n */\nPlatform.prototype['delete'] = function(url, query, options) {\n return this.send(objectAssign({}, {method: 'DELETE', url: url, query: query}, options));\n};\n\nPlatform.prototype.ensureLoggedIn = function() {\n if (this._isAccessTokenValid()) return this._externals.Promise.resolve();\n return this.refresh();\n};\n\n/**\n * @param path\n * @param body\n * @return {Promise.}\n * @private\n */\nPlatform.prototype._tokenRequest = function(path, body) {\n\n return this.send({\n url: path,\n skipAuthCheck: true,\n body: body,\n method: 'POST',\n headers: {\n 'Authorization': 'Basic ' + this._apiKey(),\n 'Content-Type': ApiResponse._urlencodedContentType\n }\n });\n\n};\n\n/**\n * @return {boolean}\n * @private\n */\nPlatform.prototype._isAccessTokenValid = function() {\n return this._auth.accessTokenValid();\n};\n\n/**\n * @return {string}\n * @private\n */\nPlatform.prototype._apiKey = function() {\n var apiKey = this._appKey + ':' + this._appSecret;\n return (typeof btoa == 'function') ? btoa(apiKey) : new Buffer(apiKey).toString('base64');\n};\n\n/**\n * @return {string}\n * @private\n */\nPlatform.prototype._authHeader = function() {\n var token = this._auth.accessToken();\n return this._auth.tokenType() + (token ? ' ' + token : '');\n};\n\nmodule.exports = Platform;\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/platform/Platform.js\n ** module id = 15\n ** module chunks = 0 1\n **/","/**\n * @param {Cache} options.cache\n * @param {string} options.cacheId\n * @param {int} [options.refreshHandicapMs]\n * @constructor\n * @property {Cache} _cache\n * @property {int} _refreshHandicapMs\n * @property {string} _cacheId\n */\nfunction Auth(options) {\n\n /** @private */\n this._cache = options.cache;\n\n /** @private */\n this._cacheId = options.cacheId;\n\n /** @private */\n this._refreshHandicapMs = options.refreshHandicapMs || 60 * 1000; // 1 minute\n\n}\n\nAuth.prototype.accessToken = function() {\n return this.data().access_token;\n};\n\nAuth.prototype.refreshToken = function() {\n return this.data().refresh_token;\n};\n\nAuth.prototype.tokenType = function() {\n return this.data().token_type;\n};\n\n/**\n * @return {{token_type: string, access_token: string, expires_in: number, refresh_token: string, refresh_token_expires_in: number}}\n */\nAuth.prototype.data = function() {\n\n return this._cache.getItem(this._cacheId) || {\n token_type: '',\n access_token: '',\n expires_in: 0,\n refresh_token: '',\n refresh_token_expires_in: 0\n };\n\n};\n\n/**\n * @param {object} newData\n * @return {Auth}\n */\nAuth.prototype.setData = function(newData) {\n\n newData = newData || {};\n\n var data = this.data();\n\n Object.keys(newData).forEach(function(key) {\n data[key] = newData[key];\n });\n\n data.expire_time = Date.now() + (data.expires_in * 1000);\n data.refresh_token_expire_time = Date.now() + (data.refresh_token_expires_in * 1000);\n\n this._cache.setItem(this._cacheId, data);\n\n return this;\n\n};\n\n/**\n * Check if there is a valid (not expired) access token\n * @return {boolean}\n */\nAuth.prototype.accessTokenValid = function() {\n\n var authData = this.data();\n return (authData.expire_time - this._refreshHandicapMs > Date.now());\n\n};\n\n/**\n * Check if there is a valid (not expired) access token\n * @return {boolean}\n */\nAuth.prototype.refreshTokenValid = function() {\n\n return (this.data().refresh_token_expire_time > Date.now());\n\n};\n\n/**\n * @return {Auth}\n */\nAuth.prototype.cancelAccessToken = function() {\n\n return this.setData({\n access_token: '',\n expires_in: 0\n });\n\n};\n\nmodule.exports = Auth;\n\n//export interface IAuthData {\n// remember?:boolean;\n// token_type?:string;\n// access_token?:string;\n// expires_in?:number; // actually it's string\n// expire_time?:number;\n// refresh_token?:string;\n// refresh_token_expires_in?:number; // actually it's string\n// refresh_token_expire_time?:number;\n// scope?:string;\n//}\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/platform/Auth.js\n ** module id = 16\n ** module chunks = 0 1\n **/","var version = process.env.RCSDK_VERSION;\n\n// This will become false during the Webpack build, so no traces of package.json will be there\nif (!process.env.RCSDK_VERSION) {\n version = require('../../package.json').version;\n}\n\nmodule.exports = {\n version: version,\n authResponseProperty: 'RCAuthorizationResponse'\n};\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/core/Constants.js\n ** module id = 17\n ** module chunks = 0 1\n **/","var EventEmitter = require(\"events\").EventEmitter;\n\n/**\n * @param {Platform} options.platform\n * @param {Externals} options.externals\n * @param {int} [options.pollInterval]\n * @param {int} [options.renewHandicapMs]\n * @property {Externals} _externals\n * @property {Platform} _platform\n * @property {int} _pollInterval\n * @property {int} _renewHandicapMs\n * @property {PUBNUB} _pubnub\n * @property {string} _pubnubLastChannel\n * @property {int} _timeout\n * @property {ISubscription} _subscription\n * @constructor\n */\nfunction Subscription(options) {\n\n EventEmitter.call(this);\n\n options = options || {};\n\n this.events = {\n notification: 'notification',\n removeSuccess: 'removeSuccess',\n removeError: 'removeError',\n renewSuccess: 'renewSuccess',\n renewError: 'renewError',\n subscribeSuccess: 'subscribeSuccess',\n subscribeError: 'subscribeError'\n };\n\n /** @private */\n this._externals = options.externals;\n\n /** @private */\n this._platform = options.platform;\n\n /** @private */\n this._pollInterval = options.pollInterval || 10 * 1000;\n\n /** @private */\n this._renewHandicapMs = options.renewHandicapMs || 2 * 60 * 1000;\n\n /** @private */\n this._pubnub = null;\n\n /** @private */\n this._pubnubLastChannel = null;\n\n /** @private */\n this._timeout = null;\n\n /** @private */\n this._subscription = null;\n\n}\n\nSubscription.prototype = Object.create(EventEmitter.prototype);\n\nSubscription.prototype.subscribed = function() {\n\n var subscription = this.subscription();\n\n return !!(subscription.id &&\n subscription.deliveryMode &&\n subscription.deliveryMode.subscriberKey &&\n subscription.deliveryMode.address);\n\n};\n\n/**\n * @return {boolean}\n */\nSubscription.prototype.alive = function() {\n return this.subscribed() && Date.now() < this.expirationTime();\n};\n\n/**\n * @return {boolean}\n */\nSubscription.prototype.expired = function() {\n if (!this.subscribed()) return true;\n return !this.subscribed() || Date.now() > this.subscription().expirationTime;\n};\n\nSubscription.prototype.expirationTime = function() {\n return new Date(this.subscription().expirationTime || 0).getTime() - this._renewHandicapMs;\n};\n\n/**\n * @param {ISubscription} subscription\n * @return {Subscription}\n */\nSubscription.prototype.setSubscription = function(subscription) {\n\n subscription = subscription || {};\n\n this._clearTimeout();\n this._setSubscription(subscription);\n this._subscribeAtPubnub();\n this._setTimeout();\n\n return this;\n\n};\n\n/**\n * @return {ISubscription}\n */\nSubscription.prototype.subscription = function() {\n return this._subscription || {};\n};\n\n/**\n * Creates or updates subscription if there is an active one\n * @returns {Promise}\n */\nSubscription.prototype.register = function() {\n\n if (this.alive()) {\n return this.renew();\n } else {\n return this.subscribe();\n }\n\n};\n\n/**\n * @return {string[]}\n */\nSubscription.prototype.eventFilters = function() {\n return this.subscription().eventFilters || [];\n};\n\n/**\n * @param {string[]} events\n * @return {Subscription}\n */\nSubscription.prototype.addEventFilters = function(events) {\n this.setEventFilters(this.eventFilters().concat(events));\n return this;\n};\n\n/**\n * @param {string[]} events\n * @return {Subscription}\n */\nSubscription.prototype.setEventFilters = function(events) {\n var subscription = this.subscription();\n subscription.eventFilters = events;\n this._setSubscription(subscription);\n return this;\n};\n\n/**\n * @returns {Promise}\n */\nSubscription.prototype.subscribe = function() {\n\n return (new this._externals.Promise(function(resolve) {\n\n this._clearTimeout();\n\n if (!this.eventFilters().length) throw new Error('Events are undefined');\n\n resolve(this._platform.post('/subscription', {\n eventFilters: this._getFullEventFilters(),\n deliveryMode: {\n transportType: 'PubNub'\n }\n }));\n\n }.bind(this))).then(function(response) {\n\n var json = response.json();\n\n this.setSubscription(json)\n .emit(this.events.subscribeSuccess, response);\n\n return response;\n\n }.bind(this)).catch(function(e) {\n\n e = this._platform.client().makeError(e);\n\n this.reset()\n .emit(this.events.subscribeError, e);\n\n throw e;\n\n }.bind(this));\n\n};\n\n/**\n * @returns {Promise}\n */\nSubscription.prototype.renew = function() {\n\n return (new this._externals.Promise(function(resolve) {\n\n this._clearTimeout();\n\n if (!this.subscribed()) throw new Error('No subscription');\n\n if (!this.eventFilters().length) throw new Error('Events are undefined');\n\n resolve(this._platform.put('/subscription/' + this.subscription().id, {\n eventFilters: this._getFullEventFilters()\n }));\n\n }.bind(this))).then(function(response) {\n\n var json = response.json();\n\n this.setSubscription(json)\n .emit(this.events.renewSuccess, response);\n\n return response;\n\n }.bind(this)).catch(function(e) {\n\n e = this._platform.client().makeError(e);\n\n this.reset()\n .emit(this.events.renewError, e);\n\n throw e;\n\n }.bind(this));\n\n};\n\n/**\n * @returns {Promise}\n */\nSubscription.prototype.remove = function() {\n\n return (new this._externals.Promise(function(resolve) {\n\n if (!this.subscribed()) throw new Error('No subscription');\n\n resolve(this._platform.delete('/subscription/' + this.subscription().id));\n\n }.bind(this))).then(function(response) {\n\n this.reset()\n .emit(this.events.removeSuccess, response);\n\n return response;\n\n }.bind(this)).catch(function(e) {\n\n e = this._platform.client().makeError(e);\n\n this.emit(this.events.removeError, e);\n\n throw e;\n\n }.bind(this));\n\n};\n\n/**\n * @returns {Promise}\n */\nSubscription.prototype.resubscribe = function() {\n var filters = this.eventFilters();\n return this.reset().setEventFilters(filters).subscribe();\n};\n\n/**\n * Remove subscription and disconnect from PUBNUB\n * This method resets subscription at client side but backend is not notified\n * @return {Subscription}\n */\nSubscription.prototype.reset = function() {\n this._clearTimeout();\n if (this.subscribed() && this._pubnub) this._pubnub.unsubscribe({channel: this.subscription().deliveryMode.address});\n this._setSubscription(null);\n return this;\n};\n\n/**\n * @param subscription\n * @private\n */\nSubscription.prototype._setSubscription = function(subscription) {\n this._subscription = subscription;\n};\n\n/**\n * @return {string[]}\n * @private\n */\nSubscription.prototype._getFullEventFilters = function() {\n\n return this.eventFilters().map(function(event) {\n return this._platform.createUrl(event);\n }.bind(this));\n\n};\n\n/**\n * @return {Subscription}\n * @private\n */\nSubscription.prototype._setTimeout = function() {\n\n this._clearTimeout();\n\n if (!this.alive()) throw new Error('Subscription is not alive');\n\n this._timeout = setInterval(function() {\n\n if (this.alive()) return;\n\n if (this.expired()) {\n this.subscribe();\n } else {\n this.renew();\n }\n\n }.bind(this), this._pollInterval);\n\n return this;\n\n};\n\n/**\n * @return {Subscription}\n * @private\n */\nSubscription.prototype._clearTimeout = function() {\n clearInterval(this._timeout);\n return this;\n};\n\nSubscription.prototype._decrypt = function(message) {\n\n if (!this.subscribed()) throw new Error('No subscription');\n\n if (this.subscription().deliveryMode.encryptionKey) {\n\n message = this._externals.PUBNUB.crypto_obj.decrypt(message, this.subscription().deliveryMode.encryptionKey, {\n encryptKey: false,\n keyEncoding: 'base64',\n keyLength: 128,\n mode: 'ecb'\n });\n\n }\n\n return message;\n\n};\n\n/**\n * @param message\n * @return {Subscription}\n * @private\n */\nSubscription.prototype._notify = function(message) {\n this.emit(this.events.notification, this._decrypt(message));\n return this;\n};\n\n/**\n * @return {Subscription}\n * @private\n */\nSubscription.prototype._subscribeAtPubnub = function() {\n\n if (!this.alive()) throw new Error('Subscription is not alive');\n\n var deliveryMode = this.subscription().deliveryMode;\n\n if (this._pubnub) {\n\n if (this._pubnubLastChannel == deliveryMode.address) { // Nothing to update, keep listening to same channel\n return this;\n } else if (this._pubnubLastChannel) { // Need to subscribe to new channel\n this._pubnub.unsubscribe({channel: this._pubnubLastChannel});\n }\n\n // Re-init for new data\n this._pubnub = this._pubnub.init({\n ssl: true,\n subscribe_key: deliveryMode.subscriberKey\n });\n\n } else {\n\n // Init from scratch\n this._pubnub = this._externals.PUBNUB.init({\n ssl: true,\n subscribe_key: deliveryMode.subscriberKey\n });\n\n this._pubnub.ready(); //TODO This may be not needed anymore\n\n }\n\n this._pubnubLastChannel = deliveryMode.address;\n\n this._pubnub.subscribe({\n channel: deliveryMode.address,\n message: this._notify.bind(this),\n connect: function() {}\n });\n\n return this;\n\n};\n\nmodule.exports = Subscription;\n\n/**\n * The complete Triforce, or one or more components of the Triforce.\n * @typedef {Object} ISubscription\n * @property {string} [id]\n * @property {string} [uri]\n * @property {string[]} [eventFilters]\n * @property {string} [expirationTime] Format: 2014-03-12T19:54:35.613Z\n * @property {int} [expiresIn]\n * @property {string} [deliveryMode.transportType]\n * @property {boolean} [deliveryMode.encryption]\n * @property {string} [deliveryMode.address]\n * @property {string} [deliveryMode.subscriberKey]\n * @property {string} [deliveryMode.encryptionKey]\n * @property {string} [deliveryMode.secretKey]\n * @property {string} [creationTime]\n * @property {string} [status] Active\n */\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/subscription/Subscription.js\n ** module id = 18\n ** module chunks = 0 1\n **/","var Subscription = require(\"./Subscription\");\n\n/**\n * @param {Platform} options.platform\n * @param {Externals} options.externals\n * @param {Cache} options.cache\n * @param {string} options.cacheKey\n * @param {int} [options.pollInterval]\n * @param {int} [options.renewHandicapMs]\n * @return {CachedSubscription}\n * @constructor\n * @property {Cache} _cache\n * @extends Subscription\n */\nfunction CachedSubscription(options) {\n\n options = options || {};\n\n if (!options.cacheKey) throw new Error('Cached Subscription requires cacheKey parameter to be defined');\n\n /** @private */\n this._cacheKey = options.cacheKey;\n\n Subscription.call(this, options);\n\n /** @private */\n this._cache = options.cache;\n\n // This is not used in this class\n this._subscription = undefined;\n\n}\n\nCachedSubscription.prototype = Object.create(Subscription.prototype);\n\nCachedSubscription.prototype.subscription = function() {\n return this._cache.getItem(this._cacheKey) || {};\n};\n\nCachedSubscription.prototype._setSubscription = function(subscription) {\n return this._cache.setItem(this._cacheKey, subscription);\n};\n\n/**\n * This function checks whether there are any pre-defined eventFilters in cache and if not -- uses provided as defaults\n * @param {string[]} events\n * @return {CachedSubscription}\n */\nCachedSubscription.prototype.restore = function(events) {\n\n if (!this.eventFilters().length) {\n this.setEventFilters(events);\n }\n\n return this;\n\n};\n\nmodule.exports = CachedSubscription;\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/subscription/CachedSubscription.js\n ** module id = 19\n ** module chunks = 0 1\n **/"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack:///webpack/universalModuleDefinition","webpack:///webpack/bootstrap c20b2b45729ee57a5332","webpack:///./src/SDK.js","webpack:///./~/object-assign/index.js","webpack:///./src/core/Cache.js","webpack:///./src/http/Client.js","webpack:///./~/is-plain-object/index.js","webpack:///./~/isobject/index.js","webpack:///./~/events/events.js","webpack:///./src/http/ApiResponse.js","webpack:///./~/querystring/index.js","webpack:///./~/querystring/decode.js","webpack:///./~/querystring/encode.js","webpack:///./src/core/Externals.js","webpack:///external {\"amd\":\"pubnub\"}","webpack:///external {\"amd\":\"es6-promise\"}","webpack:///external {\"amd\":\"fetch-ponyfill\"}","webpack:///./src/platform/Platform.js","webpack:///./src/platform/Auth.js","webpack:///./src/core/Constants.js","webpack:///./src/subscription/Subscription.js","webpack:///./src/subscription/CachedSubscription.js"],"names":[],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iDAAiD;AACjD,CAAC;AACD,O;ACVA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,uBAAe;AACf;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;;AAGA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;;;;;;ACtCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,sBAAsB;AACjC,WAAW,QAAQ;AACnB,WAAW,MAAM;AACjB,WAAW,sBAAsB;AACjC,WAAW,uBAAuB;AAClC,WAAW,sBAAsB;AACjC,WAAW,IAAI;AACf,WAAW,IAAI;AACf,WAAW,QAAQ;AACnB,cAAc,UAAU;AACxB,cAAc,MAAM;AACpB,cAAc,OAAO;AACrB,cAAc,SAAS;AACvB;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,KAAK;;AAEL;AACA;;AAEA;AACA,iDAAiD;AACjD;AACA;AACA;AACA,KAAK;;AAEL;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;AACA,YAAY;AACZ;AACA;AACA;AACA;;AAEA;AACA,YAAY;AACZ;AACA;AACA;AACA;;AAEA;AACA,WAAW,IAAI;AACf,WAAW,IAAI;AACf,YAAY;AACZ;AACA;AACA,2CAA2C;AAC3C;AACA;AACA,KAAK;AACL;;AAEA;AACA,WAAW,OAAO;AAClB,WAAW,IAAI;AACf,WAAW,IAAI;AACf,YAAY;AACZ;AACA;;AAEA;AACA,mBAAmB;AACnB,KAAK;AACL;AACA;;AAEA,iDAAiD;AACjD;AACA;AACA;AACA,KAAK;;AAEL;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA,qB;;;;;;AC3HA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA,gCAAgC;AAChC;AACA;AACA;AACA;;AAEA;AACA;AACA,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;AACA;A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AO;AAClB,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;;AAEA,SAAS;AACT;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;;AAEA;;AAEA;;AAEA;AACA,aAAa,OAAO;AACpB,cAAc,OAAO;AACrB,cAAc,OAAO;AACrB,cAAc,YAAY;AAC1B;;AAEA,wB;;;;;;AC/LA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;;;;;;ACpCA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;;;;;;;ACZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA,eAAe,SAAS;AACxB;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA,GAAG;AACH,oBAAoB,SAAS;AAC7B;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;;;;;;AC7SA;AACA,WAAW,UAAU;AACrB,WAAW,QAAQ;AACnB,WAAW,SAAS;AACpB,WAAW,OAAO;AAClB,cAAc,UAAU;AACxB,cAAc,QAAQ;AACtB,cAAc,SAAS;AACvB,cAAc,OAAO;AACrB,cAAc,OAAO;AACrB,cAAc,cAAc;AAC5B;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,WAAW,SAAS;AACpB,YAAY;AACZ;AACA;;AAEA;;AAEA;;AAEA;AACA;;AAEA;;AAEA,KAAK;;AAEL;AACA;;AAEA,KAAK;;AAEL;;AAEA;AACA,YAAY;AACZ;AACA;AACA;AACA;;AAEA;AACA,YAAY;AACZ;AACA;AACA;AACA;;AAEA;AACA,YAAY;AACZ;AACA;AACA;AACA;;AAEA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,YAAY;AACZ;AACA;;AAEA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA,KAAK;;AAEL;;AAEA;;AAEA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;;AAEA;AACA,YAAY;AACZ;AACA;;AAEA;;AAEA;;AAEA;;AAEA;;AAEA;;AAEA,kEAAkE;;AAElE;;AAEA;;AAEA;AACA;;AAEA;;AAEA;;AAEA;;AAEA;;AAEA;;AAEA;;AAEA;;AAEA,SAAS;;AAET;;AAEA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB;AACA,YAAY;AACZ;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA,SAAS;;AAET;AACA;AACA;AACA;AACA,KAAK;;AAEL;AACA;AACA;AACA;AACA;AACA,KAAK;;AAEL;;AAEA,6B;;;;;;ACvQA;;AAEA;AACA;;;;;;;ACHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA,iBAAiB,SAAS;AAC1B;AACA;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA;AACA;;AAEA;AACA;;;;;;;AC/EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT,OAAO;AACP;AACA;AACA,KAAK;;AAEL;;AAEA;AACA;AACA;AACA;;;;;;;AC/DA;AACA;AACA;;AAEA;AACA;AACA,uBAAuB,aAAa,EAAE;;AAEtC;AACA;AACA,WAAW,OAAO;AAClB,WAAW,sBAAsB;AACjC,WAAW,QAAQ;AACnB,WAAW,MAAM;AACjB,WAAW,sBAAsB;AACjC,WAAW,uBAAuB;AAClC,WAAW,sBAAsB;AACjC,cAAc,OAAO;AACrB,cAAc,QAAQ;AACtB,cAAc,sBAAsB;AACpC,cAAc,MAAM;AACpB,cAAc,sBAAsB;AACpC,cAAc,uBAAuB;AACrC,cAAc,sBAAsB;AACpC;AACA;;AAEA;;AAEA;AACA,oHAAoH;AACpH;;AAEA,uDAAuD,sBAAsB;;AAE7E;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;;;;;;;;AC1DA,gD;;;;;;ACAA,gD;;;;;;ACAA,gD;;;;;;ACAA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,OAAO;A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AAClB,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,QAAQ;AACnB,YAAY;AACZ;AACA;AACA,oCAAoC,GAAG,kDAAkD;AACzF;;AAEA;AACA,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,QAAQ;AACnB,YAAY;AACZ;AACA;AACA,oCAAoC,GAAG,yCAAyC;AAChF;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;;AAEL;;AAEA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;;AAEA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;;AAEA,0B;;;;;;ACzpBA;AACA,WAAW,MAAM;AACjB,WAAW,OAAO;AAClB,WAAW,IAAI;AACf;AACA,cAAc,MAAM;AACpB,cAAc,IAAI;AAClB,cAAc,OAAO;AACrB;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA,qEAAqE;;AAErE;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA,aAAa;AACb;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;;AAEA;;AAEA;AACA;AACA,KAAK;;AAEL;AACA;;AAEA;;AAEA;;AAEA;;AAEA;AACA;AACA,YAAY;AACZ;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA,YAAY;AACZ;AACA;;AAEA;;AAEA;;AAEA;AACA,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA,KAAK;;AAEL;;AAEA;;AAEA;AACA;AACA;AACA;AACA,yBAAyB;AACzB;AACA;AACA,uCAAuC;AACvC;AACA;AACA;;;;;;;ACrHA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,OAAO;AACrB,cAAc,OAAO;AACrB,cAAc,OAAO;AACrB,cAAc,OAAO;AACrB,cAAc,OAAO;AACrB,G;;;;;;ACjbA;;AAEA;AACA,WAAW,SAAS;AACpB,WAAW,UAAU;AACrB,WAAW,MAAM;AACjB,WAAW,OAAO;AAClB,WAAW,IAAI;AACf,WAAW,IAAI;AACf,YAAY;AACZ;AACA,cAAc,MAAM;AACpB;AACA;AACA;;AAEA;;AAEA;;AAEA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;;AAEA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,WAAW,SAAS;AACpB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;;AAEA,oC","file":"ringcentral.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory(require(undefined), require(undefined), require(undefined));\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([\"pubnub\", \"es6-promise\", \"fetch-ponyfill\"], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"SDK\"] = factory(require(undefined), require(undefined), require(undefined));\n\telse\n\t\troot[\"RingCentral\"] = root[\"RingCentral\"] || {}, root[\"RingCentral\"][\"SDK\"] = factory(root[undefined], root[undefined], root[undefined]);\n})(this, function(__WEBPACK_EXTERNAL_MODULE_12__, __WEBPACK_EXTERNAL_MODULE_13__, __WEBPACK_EXTERNAL_MODULE_14__) {\nreturn \n\n\n// WEBPACK FOOTER //\n// webpack/universalModuleDefinition"," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId])\n \t\t\treturn installedModules[moduleId].exports;\n\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\texports: {},\n \t\t\tid: moduleId,\n \t\t\tloaded: false\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.loaded = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"/build/\";\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(0);\n\n\n\n// WEBPACK FOOTER //\n// webpack/bootstrap c20b2b45729ee57a5332","/**\n * @namespace RingCentral\n */\nvar objectAssign = require('object-assign');\nvar Cache = require(\"./core/Cache\");\nvar Client = require(\"./http/Client\");\nvar Externals = require(\"./core/Externals\");\nvar Platform = require(\"./platform/Platform\");\nvar Subscription = require(\"./subscription/Subscription\");\nvar CachedSubscription = require(\"./subscription/CachedSubscription\");\nvar Constants = require(\"./core/Constants\");\n\n/**\n * @constructor\n * @param {string} options.server\n * @param {string} options.appSecret\n * @param {string} options.appKey\n * @param {string} [options.cachePrefix]\n * @param {string} [options.appName]\n * @param {string} [options.appVersion]\n * @param {string} [options.redirectUri]\n * @param {PubNub} [options.PubNub]\n * @param {function(new:Promise)} [options.Promise]\n * @param {Storage} [options.localStorage]\n * @param {fetch} [options.fetch]\n * @param {function(new:Request)} [options.Request]\n * @param {function(new:Response)} [options.Response]\n * @param {function(new:Headers)} [options.Headers]\n * @param {int} [options.refreshDelayMs]\n * @param {int} [options.refreshHandicapMs]\n * @param {boolean} [options.clearCacheOnRefreshError]\n * @property {Externals} _externals\n * @property {Cache} _cache\n * @property {Client} _client\n * @property {Platform} _platform\n */\nfunction SDK(options) {\n\n /** @private */\n this._externals = new Externals(options);\n\n /** @private */\n this._cache = new Cache({\n externals: this._externals,\n prefix: options.cachePrefix\n });\n\n /** @private */\n this._client = new Client(this._externals);\n\n /** @private */\n this._platform = new Platform(objectAssign({}, options, {\n externals: this._externals,\n client: this._client,\n cache: this._cache\n }));\n\n}\n\nSDK.version = Constants.version;\n\nSDK.server = {\n sandbox: 'https://platform.devtest.ringcentral.com',\n production: 'https://platform.ringcentral.com'\n};\n\n/**\n * @return {Platform}\n */\nSDK.prototype.platform = function() {\n return this._platform;\n};\n\n/**\n * @return {Cache}\n */\nSDK.prototype.cache = function() {\n return this._cache;\n};\n\n/**\n * @param {int} [options.pollInterval]\n * @param {int} [options.renewHandicapMs]\n * @return {Subscription}\n */\nSDK.prototype.createSubscription = function(options) {\n return new Subscription(objectAssign({}, options, {\n externals: this._externals,\n platform: this._platform\n }));\n};\n\n/**\n * @param {string} options.cacheKey\n * @param {int} [options.pollInterval]\n * @param {int} [options.renewHandicapMs]\n * @return {CachedSubscription}\n */\nSDK.prototype.createCachedSubscription = function(options) {\n\n if (typeof arguments[0] == 'string') {\n options = {cacheKey: arguments[0].toString()};\n } else {\n options = options || {};\n }\n\n return new CachedSubscription(objectAssign({}, options, {\n externals: this._externals,\n platform: this._platform,\n cache: this._cache\n }));\n\n};\n\nSDK.handleLoginRedirect = function(origin) {\n\n var response = window.location.hash ? window.location.hash : window.location.search;\n var msg = {};\n msg[Constants.authResponseProperty] = response;\n window.opener.postMessage(msg, origin || window.location.origin);\n\n};\n\nmodule.exports = SDK;\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/SDK.js\n// module id = 0\n// module chunks = 0 1","/*\nobject-assign\n(c) Sindre Sorhus\n@license MIT\n*/\n\n'use strict';\n/* eslint-disable no-unused-vars */\nvar getOwnPropertySymbols = Object.getOwnPropertySymbols;\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\nvar propIsEnumerable = Object.prototype.propertyIsEnumerable;\n\nfunction toObject(val) {\n\tif (val === null || val === undefined) {\n\t\tthrow new TypeError('Object.assign cannot be called with null or undefined');\n\t}\n\n\treturn Object(val);\n}\n\nfunction shouldUseNative() {\n\ttry {\n\t\tif (!Object.assign) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// Detect buggy property enumeration order in older V8 versions.\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=4118\n\t\tvar test1 = new String('abc'); // eslint-disable-line no-new-wrappers\n\t\ttest1[5] = 'de';\n\t\tif (Object.getOwnPropertyNames(test1)[0] === '5') {\n\t\t\treturn false;\n\t\t}\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=3056\n\t\tvar test2 = {};\n\t\tfor (var i = 0; i < 10; i++) {\n\t\t\ttest2['_' + String.fromCharCode(i)] = i;\n\t\t}\n\t\tvar order2 = Object.getOwnPropertyNames(test2).map(function (n) {\n\t\t\treturn test2[n];\n\t\t});\n\t\tif (order2.join('') !== '0123456789') {\n\t\t\treturn false;\n\t\t}\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=3056\n\t\tvar test3 = {};\n\t\t'abcdefghijklmnopqrst'.split('').forEach(function (letter) {\n\t\t\ttest3[letter] = letter;\n\t\t});\n\t\tif (Object.keys(Object.assign({}, test3)).join('') !==\n\t\t\t\t'abcdefghijklmnopqrst') {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t} catch (err) {\n\t\t// We don't expect any of the above to throw, but better to be safe.\n\t\treturn false;\n\t}\n}\n\nmodule.exports = shouldUseNative() ? Object.assign : function (target, source) {\n\tvar from;\n\tvar to = toObject(target);\n\tvar symbols;\n\n\tfor (var s = 1; s < arguments.length; s++) {\n\t\tfrom = Object(arguments[s]);\n\n\t\tfor (var key in from) {\n\t\t\tif (hasOwnProperty.call(from, key)) {\n\t\t\t\tto[key] = from[key];\n\t\t\t}\n\t\t}\n\n\t\tif (getOwnPropertySymbols) {\n\t\t\tsymbols = getOwnPropertySymbols(from);\n\t\t\tfor (var i = 0; i < symbols.length; i++) {\n\t\t\t\tif (propIsEnumerable.call(from, symbols[i])) {\n\t\t\t\t\tto[symbols[i]] = from[symbols[i]];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn to;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/object-assign/index.js\n// module id = 1\n// module chunks = 0 1","/**\n * @param {Externals} options.externals\n * @param {string} [options.prefix]\n * @property {Externals} _externals\n */\nfunction Cache(options) {\n\n /** @private */\n this._prefix = options.prefix || Cache.defaultPrefix;\n\n /** @private */\n this._externals = options.externals;\n\n}\n\nCache.defaultPrefix = 'rc-';\n\nCache.prototype.setItem = function(key, data) {\n this._externals.localStorage[this._prefixKey(key)] = JSON.stringify(data);\n return this;\n};\n\nCache.prototype.removeItem = function(key) {\n delete this._externals.localStorage[this._prefixKey(key)];\n return this;\n};\n\nCache.prototype.getItem = function(key) {\n var item = this._externals.localStorage[this._prefixKey(key)];\n if (!item) return null;\n return JSON.parse(item);\n};\n\nCache.prototype.clean = function() {\n\n for (var key in this._externals.localStorage) {\n\n if (!this._externals.localStorage.hasOwnProperty(key)) continue;\n\n if (key.indexOf(this._prefix) === 0) {\n delete this._externals.localStorage[key];\n }\n\n }\n\n return this;\n\n};\n\nCache.prototype._prefixKey = function(key) {\n return this._prefix + key;\n};\n\nmodule.exports = Cache;\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/core/Cache.js\n// module id = 2\n// module chunks = 0 1","var isPlainObject = require(\"is-plain-object\");\nvar EventEmitter = require(\"events\").EventEmitter;\nvar ApiResponse = require(\"./ApiResponse\");\nvar qs = require(\"querystring\");\n\nfunction findHeaderName(name, headers) {\n name = name.toLowerCase();\n return Object.keys(headers).reduce(function(res, key) {\n if (res) return res;\n if (name == key.toLowerCase()) return key;\n return res;\n }, null);\n}\n\n/**\n * @param {Externals} externals\n * @property {Externals} _externals\n */\nfunction Client(externals) {\n\n EventEmitter.call(this);\n\n /** @private */\n this._externals = externals;\n\n this.events = {\n beforeRequest: 'beforeRequest',\n requestSuccess: 'requestSuccess',\n requestError: 'requestError'\n };\n\n}\n\nClient._allowedMethods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS', 'HEAD'];\n\nClient.prototype = Object.create(EventEmitter.prototype);\n\n/**\n * @param {Request} request\n * @return {Promise}\n */\nClient.prototype.sendRequest = function(request) {\n\n var apiResponse = new ApiResponse({\n externals: this._externals,\n request: request\n });\n\n return (new this._externals.Promise(function(resolve) {\n\n //TODO Stop request if listeners return false\n this.emit(this.events.beforeRequest, apiResponse);\n\n resolve(this._loadResponse(request));\n\n }.bind(this))).then(function(response) {\n\n return apiResponse.receiveResponse(response);\n\n }).then(function() {\n\n if (!apiResponse.ok()) throw new Error('Response has unsuccessful status');\n\n this.emit(this.events.requestSuccess, apiResponse);\n\n return apiResponse;\n\n }.bind(this)).catch(function(e) {\n\n if (!e.apiResponse) e = this.makeError(e, apiResponse);\n\n this.emit(this.events.requestError, e);\n\n throw e;\n\n }.bind(this));\n\n};\n\n/**\n * @param {Request} request\n * @return {Promise}\n * @private\n */\nClient.prototype._loadResponse = function(request) {\n return this._externals.fetch.call(null, request);\n};\n\n/**\n * Wraps the JS Error object with transaction information\n * @param {Error|IApiError} e\n * @param {ApiResponse} apiResponse\n * @return {IApiError}\n */\nClient.prototype.makeError = function(e, apiResponse) {\n\n // Wrap only if regular error\n if (!e.hasOwnProperty('apiResponse') && !e.hasOwnProperty('originalMessage')) {\n\n e.apiResponse = apiResponse;\n e.originalMessage = e.message;\n e.message = (apiResponse && apiResponse.error(true)) || e.originalMessage;\n\n }\n\n return e;\n\n};\n\n/**\n *\n * @param {object} init\n * @param {object} [init.url]\n * @param {object} [init.body]\n * @param {string} [init.method]\n * @param {object} [init.query]\n * @param {object} [init.headers]\n * @param {object} [init.credentials]\n * @param {object} [init.mode]\n * @return {Request}\n */\nClient.prototype.createRequest = function(init) {\n\n init = init || {};\n init.headers = init.headers || {};\n\n // Sanity checks\n if (!init.url) throw new Error('Url is not defined');\n if (!init.method) init.method = 'GET';\n init.method = init.method.toUpperCase();\n if (init.method && Client._allowedMethods.indexOf(init.method) < 0) {\n throw new Error('Method has wrong value: ' + init.method);\n }\n\n // Defaults\n init.credentials = init.credentials || 'include';\n init.mode = init.mode || 'cors';\n\n // Append Query String\n if (init.query) {\n init.url = init.url + (init.url.indexOf('?') > -1 ? '&' : '?') + qs.stringify(init.query);\n }\n\n if (!(findHeaderName('Accept', init.headers))) {\n init.headers.Accept = ApiResponse._jsonContentType;\n }\n\n // Serialize body\n if (isPlainObject(init.body) || !init.body) {\n\n var contentTypeHeaderName = findHeaderName(ApiResponse._contentType, init.headers);\n\n if (!contentTypeHeaderName) {\n contentTypeHeaderName = ApiResponse._contentType;\n init.headers[contentTypeHeaderName] = ApiResponse._jsonContentType;\n }\n\n var contentType = init.headers[contentTypeHeaderName];\n\n // Assign a new encoded body\n if (contentType.indexOf(ApiResponse._jsonContentType) > -1) {\n if ((init.method === 'GET' || init.method === 'HEAD') && !!init.body) {\n // oddly setting body to null still result in TypeError in phantomjs\n init.body = undefined;\n } else {\n init.body = JSON.stringify(init.body);\n }\n\n } else if (contentType.indexOf(ApiResponse._urlencodedContentType) > -1) {\n init.body = qs.stringify(init.body);\n }\n\n }\n\n // Create a request with encoded body\n var req = new this._externals.Request(init.url, init);\n\n // Keep the original body accessible directly (for mocks)\n req.originalBody = init.body;\n\n return req;\n\n};\n\n/**\n * @typedef {object} IApiError\n * @property {string} stack\n * @property {string} originalMessage\n * @property {ApiResponse} apiResponse\n */\n\nmodule.exports = Client;\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/http/Client.js\n// module id = 3\n// module chunks = 0 1","/*!\n * is-plain-object \n *\n * Copyright (c) 2014-2015, Jon Schlinkert.\n * Licensed under the MIT License.\n */\n\n'use strict';\n\nvar isObject = require('isobject');\n\nfunction isObjectObject(o) {\n return isObject(o) === true\n && Object.prototype.toString.call(o) === '[object Object]';\n}\n\nmodule.exports = function isPlainObject(o) {\n var ctor,prot;\n \n if (isObjectObject(o) === false) return false;\n \n // If has modified constructor\n ctor = o.constructor;\n if (typeof ctor !== 'function') return false;\n \n // If has modified prototype\n prot = ctor.prototype;\n if (isObjectObject(prot) === false) return false;\n \n // If constructor does not have an Object-specific method\n if (prot.hasOwnProperty('isPrototypeOf') === false) {\n return false;\n }\n \n // Most likely a plain Object\n return true;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/is-plain-object/index.js\n// module id = 4\n// module chunks = 0 1","/*!\n * isobject \n *\n * Copyright (c) 2014-2015, Jon Schlinkert.\n * Licensed under the MIT License.\n */\n\n'use strict';\n\nmodule.exports = function isObject(val) {\n return val != null && typeof val === 'object'\n && !Array.isArray(val);\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/isobject/index.js\n// module id = 5\n// module chunks = 0 1","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nfunction EventEmitter() {\n this._events = this._events || {};\n this._maxListeners = this._maxListeners || undefined;\n}\nmodule.exports = EventEmitter;\n\n// Backwards-compat with node 0.10.x\nEventEmitter.EventEmitter = EventEmitter;\n\nEventEmitter.prototype._events = undefined;\nEventEmitter.prototype._maxListeners = undefined;\n\n// By default EventEmitters will print a warning if more than 10 listeners are\n// added to it. This is a useful default which helps finding memory leaks.\nEventEmitter.defaultMaxListeners = 10;\n\n// Obviously not all Emitters should be limited to 10. This function allows\n// that to be increased. Set to zero for unlimited.\nEventEmitter.prototype.setMaxListeners = function(n) {\n if (!isNumber(n) || n < 0 || isNaN(n))\n throw TypeError('n must be a positive number');\n this._maxListeners = n;\n return this;\n};\n\nEventEmitter.prototype.emit = function(type) {\n var er, handler, len, args, i, listeners;\n\n if (!this._events)\n this._events = {};\n\n // If there is no 'error' event listener then throw.\n if (type === 'error') {\n if (!this._events.error ||\n (isObject(this._events.error) && !this._events.error.length)) {\n er = arguments[1];\n if (er instanceof Error) {\n throw er; // Unhandled 'error' event\n } else {\n // At least give some kind of context to the user\n var err = new Error('Uncaught, unspecified \"error\" event. (' + er + ')');\n err.context = er;\n throw err;\n }\n }\n }\n\n handler = this._events[type];\n\n if (isUndefined(handler))\n return false;\n\n if (isFunction(handler)) {\n switch (arguments.length) {\n // fast cases\n case 1:\n handler.call(this);\n break;\n case 2:\n handler.call(this, arguments[1]);\n break;\n case 3:\n handler.call(this, arguments[1], arguments[2]);\n break;\n // slower\n default:\n args = Array.prototype.slice.call(arguments, 1);\n handler.apply(this, args);\n }\n } else if (isObject(handler)) {\n args = Array.prototype.slice.call(arguments, 1);\n listeners = handler.slice();\n len = listeners.length;\n for (i = 0; i < len; i++)\n listeners[i].apply(this, args);\n }\n\n return true;\n};\n\nEventEmitter.prototype.addListener = function(type, listener) {\n var m;\n\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n if (!this._events)\n this._events = {};\n\n // To avoid recursion in the case that type === \"newListener\"! Before\n // adding it to the listeners, first emit \"newListener\".\n if (this._events.newListener)\n this.emit('newListener', type,\n isFunction(listener.listener) ?\n listener.listener : listener);\n\n if (!this._events[type])\n // Optimize the case of one listener. Don't need the extra array object.\n this._events[type] = listener;\n else if (isObject(this._events[type]))\n // If we've already got an array, just append.\n this._events[type].push(listener);\n else\n // Adding the second element, need to change to array.\n this._events[type] = [this._events[type], listener];\n\n // Check for listener leak\n if (isObject(this._events[type]) && !this._events[type].warned) {\n if (!isUndefined(this._maxListeners)) {\n m = this._maxListeners;\n } else {\n m = EventEmitter.defaultMaxListeners;\n }\n\n if (m && m > 0 && this._events[type].length > m) {\n this._events[type].warned = true;\n console.error('(node) warning: possible EventEmitter memory ' +\n 'leak detected. %d listeners added. ' +\n 'Use emitter.setMaxListeners() to increase limit.',\n this._events[type].length);\n if (typeof console.trace === 'function') {\n // not supported in IE 10\n console.trace();\n }\n }\n }\n\n return this;\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.once = function(type, listener) {\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n var fired = false;\n\n function g() {\n this.removeListener(type, g);\n\n if (!fired) {\n fired = true;\n listener.apply(this, arguments);\n }\n }\n\n g.listener = listener;\n this.on(type, g);\n\n return this;\n};\n\n// emits a 'removeListener' event iff the listener was removed\nEventEmitter.prototype.removeListener = function(type, listener) {\n var list, position, length, i;\n\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n if (!this._events || !this._events[type])\n return this;\n\n list = this._events[type];\n length = list.length;\n position = -1;\n\n if (list === listener ||\n (isFunction(list.listener) && list.listener === listener)) {\n delete this._events[type];\n if (this._events.removeListener)\n this.emit('removeListener', type, listener);\n\n } else if (isObject(list)) {\n for (i = length; i-- > 0;) {\n if (list[i] === listener ||\n (list[i].listener && list[i].listener === listener)) {\n position = i;\n break;\n }\n }\n\n if (position < 0)\n return this;\n\n if (list.length === 1) {\n list.length = 0;\n delete this._events[type];\n } else {\n list.splice(position, 1);\n }\n\n if (this._events.removeListener)\n this.emit('removeListener', type, listener);\n }\n\n return this;\n};\n\nEventEmitter.prototype.removeAllListeners = function(type) {\n var key, listeners;\n\n if (!this._events)\n return this;\n\n // not listening for removeListener, no need to emit\n if (!this._events.removeListener) {\n if (arguments.length === 0)\n this._events = {};\n else if (this._events[type])\n delete this._events[type];\n return this;\n }\n\n // emit removeListener for all listeners on all events\n if (arguments.length === 0) {\n for (key in this._events) {\n if (key === 'removeListener') continue;\n this.removeAllListeners(key);\n }\n this.removeAllListeners('removeListener');\n this._events = {};\n return this;\n }\n\n listeners = this._events[type];\n\n if (isFunction(listeners)) {\n this.removeListener(type, listeners);\n } else if (listeners) {\n // LIFO order\n while (listeners.length)\n this.removeListener(type, listeners[listeners.length - 1]);\n }\n delete this._events[type];\n\n return this;\n};\n\nEventEmitter.prototype.listeners = function(type) {\n var ret;\n if (!this._events || !this._events[type])\n ret = [];\n else if (isFunction(this._events[type]))\n ret = [this._events[type]];\n else\n ret = this._events[type].slice();\n return ret;\n};\n\nEventEmitter.prototype.listenerCount = function(type) {\n if (this._events) {\n var evlistener = this._events[type];\n\n if (isFunction(evlistener))\n return 1;\n else if (evlistener)\n return evlistener.length;\n }\n return 0;\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n return emitter.listenerCount(type);\n};\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/events/events.js\n// module id = 6\n// module chunks = 0 1","/**\n * @param {Externals} options.externals\n * @param {Request} [options.request]\n * @param {Response} [options.response]\n * @param {string} [options.responseText]\n * @property {Externals} _externals\n * @property {Request} _request\n * @property {Response} _response\n * @property {string} _text\n * @property {object} _json\n * @property {ApiResponse[]} _multipart\n */\nfunction ApiResponse(options) {\n\n /** @private */\n this._externals = options.externals;\n\n /** @private */\n this._request = options.request;\n\n /** @private */\n this._response = options.response;\n\n /** @private */\n this._text = options.responseText || '';\n\n /** @private */\n this._json = null;\n\n /** @private */\n this._multipart = [];\n\n}\n\nApiResponse._contentType = 'Content-Type';\nApiResponse._jsonContentType = 'application/json';\nApiResponse._multipartContentType = 'multipart/mixed';\nApiResponse._urlencodedContentType = 'application/x-www-form-urlencoded';\nApiResponse._headerSeparator = ':';\nApiResponse._bodySeparator = '\\n\\n';\nApiResponse._boundarySeparator = '--';\nApiResponse._unauthorizedStatus = 401;\n\n/**\n * @param {Response} response\n * @return {Promise}\n */\nApiResponse.prototype.receiveResponse = function(response) {\n\n this._response = response;\n\n return (new this._externals.Promise(function(resolve) {\n\n // Ignore if not textual type\n if (!this._isMultipart() && !this._isJson()) return resolve('');\n\n return resolve(this.response().text());\n\n }.bind(this))).then(function(text) {\n\n this._text = text;\n return text;\n\n }.bind(this));\n\n};\n\n/**\n * @return {Response}\n */\nApiResponse.prototype.response = function() {\n return this._response;\n};\n\n/**\n * @return {Request}\n */\nApiResponse.prototype.request = function() {\n return this._request;\n};\n\n/**\n * @return {boolean}\n */\nApiResponse.prototype.ok = function() {\n return this._response && this._response.ok;\n};\n\n/**\n * @return {string}\n */\nApiResponse.prototype.text = function() {\n // Since we read text only in case JSON or Multipart\n if (!this._isJson() && !this._isMultipart()) throw new Error('Response is not text');\n return this._text;\n};\n\n/**\n * @return {object}\n */\nApiResponse.prototype.json = function() {\n if (!this._isJson()) throw new Error('Response is not JSON');\n if (!this._json) {\n this._json = this._text ? JSON.parse(this._text) : null;\n }\n return this._json;\n};\n\n/**\n * @param [skipOKCheck]\n * @return {string}\n */\nApiResponse.prototype.error = function(skipOKCheck) {\n\n if (this.ok() && !skipOKCheck) return null;\n\n var message = (this._response && this._response.status ? this._response.status + ' ' : '') +\n (this._response && this._response.statusText ? this._response.statusText : '');\n\n try {\n\n if (this.json().message) message = this.json().message;\n if (this.json().error_description) message = this.json().error_description;\n if (this.json().description) message = this.json().description;\n\n } catch (e) {}\n\n return message;\n\n};\n\n/**\n * If it is not known upfront what would be the response, client code can treat any response as multipart\n * @return {ApiResponse[]}\n */\nApiResponse.prototype.toMultipart = function() {\n if (!this._isMultipart()) return [this];\n return this.multipart();\n};\n\n/**\n * @return {ApiResponse[]}\n */\nApiResponse.prototype.multipart = function() {\n\n if (!this._isMultipart()) throw new Error('Response is not multipart');\n\n if (!this._multipart.length) {\n\n // Step 1. Split multipart response\n\n var text = this.text();\n\n if (!text) throw new Error('No response body');\n\n var boundary = this._getContentType().match(/boundary=([^;]+)/i)[1];\n\n if (!boundary) throw new Error('Cannot find boundary');\n\n var parts = text.toString().split(ApiResponse._boundarySeparator + boundary);\n\n if (parts[0].trim() === '') parts.shift();\n if (parts[parts.length - 1].trim() == ApiResponse._boundarySeparator) parts.pop();\n\n if (parts.length < 1) throw new Error('No parts in body');\n\n // Step 2. Parse status info\n\n var statusInfo = this._create(parts.shift(), this._response.status, this._response.statusText).json();\n\n // Step 3. Parse all other parts\n\n this._multipart = parts.map(function(part, i) {\n\n var status = statusInfo.response[i].status;\n\n return this._create(part, status);\n\n }.bind(this));\n\n }\n\n return this._multipart;\n\n};\n\n/**\n * @private\n */\nApiResponse.prototype._isContentType = function(contentType) {\n return this._getContentType().indexOf(contentType) > -1;\n};\n\n/**\n * @private\n */\nApiResponse.prototype._getContentType = function() {\n return this._response.headers.get(ApiResponse._contentType) || '';\n};\n\n/**\n * @private\n */\nApiResponse.prototype._isMultipart = function() {\n return this._isContentType(ApiResponse._multipartContentType);\n};\n\n/**\n * @private\n */\nApiResponse.prototype._isJson = function() {\n return this._isContentType(ApiResponse._jsonContentType);\n};\n\n/**\n * Method is used to create ApiResponse object from string parts of multipart/mixed response\n * @param {string} [text]\n * @param {number} [status]\n * @param {string} [statusText]\n * @private\n * @return {ApiResponse}\n */\nApiResponse.prototype._create = function(text, status, statusText) {\n\n text = text || '';\n status = status || 200;\n statusText = statusText || 'OK';\n\n text = text.replace(/\\r/g, '');\n\n var headers = new this._externals.Headers(),\n headersAndBody = text.split(ApiResponse._bodySeparator),\n headersText = (headersAndBody.length > 1) ? headersAndBody.shift() : '';\n\n text = headersAndBody.length > 0 ? headersAndBody.join(ApiResponse._bodySeparator) : null;\n\n (headersText || '')\n .split('\\n')\n .forEach(function(header) {\n\n var split = header.trim().split(ApiResponse._headerSeparator),\n key = split.shift().trim(),\n value = split.join(ApiResponse._headerSeparator).trim();\n\n if (key) headers.append(key, value);\n\n });\n\n var response = new this._externals.Response(text, {\n headers: headers,\n status: status,\n statusText: statusText\n });\n\n return new ApiResponse({\n externals: this._externals,\n request: null,\n response: response,\n responseText: text\n });\n\n};\n\nmodule.exports = ApiResponse;\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/http/ApiResponse.js\n// module id = 7\n// module chunks = 0 1","'use strict';\n\nexports.decode = exports.parse = require('./decode');\nexports.encode = exports.stringify = require('./encode');\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/querystring/index.js\n// module id = 8\n// module chunks = 0 1","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n// If obj.hasOwnProperty has been overridden, then calling\n// obj.hasOwnProperty(prop) will break.\n// See: https://github.com/joyent/node/issues/1707\nfunction hasOwnProperty(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n\nmodule.exports = function(qs, sep, eq, options) {\n sep = sep || '&';\n eq = eq || '=';\n var obj = {};\n\n if (typeof qs !== 'string' || qs.length === 0) {\n return obj;\n }\n\n var regexp = /\\+/g;\n qs = qs.split(sep);\n\n var maxKeys = 1000;\n if (options && typeof options.maxKeys === 'number') {\n maxKeys = options.maxKeys;\n }\n\n var len = qs.length;\n // maxKeys <= 0 means that we should not limit keys count\n if (maxKeys > 0 && len > maxKeys) {\n len = maxKeys;\n }\n\n for (var i = 0; i < len; ++i) {\n var x = qs[i].replace(regexp, '%20'),\n idx = x.indexOf(eq),\n kstr, vstr, k, v;\n\n if (idx >= 0) {\n kstr = x.substr(0, idx);\n vstr = x.substr(idx + 1);\n } else {\n kstr = x;\n vstr = '';\n }\n\n k = decodeURIComponent(kstr);\n v = decodeURIComponent(vstr);\n\n if (!hasOwnProperty(obj, k)) {\n obj[k] = v;\n } else if (Array.isArray(obj[k])) {\n obj[k].push(v);\n } else {\n obj[k] = [obj[k], v];\n }\n }\n\n return obj;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/querystring/decode.js\n// module id = 9\n// module chunks = 0 1","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nvar stringifyPrimitive = function(v) {\n switch (typeof v) {\n case 'string':\n return v;\n\n case 'boolean':\n return v ? 'true' : 'false';\n\n case 'number':\n return isFinite(v) ? v : '';\n\n default:\n return '';\n }\n};\n\nmodule.exports = function(obj, sep, eq, name) {\n sep = sep || '&';\n eq = eq || '=';\n if (obj === null) {\n obj = undefined;\n }\n\n if (typeof obj === 'object') {\n return Object.keys(obj).map(function(k) {\n var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;\n if (Array.isArray(obj[k])) {\n return obj[k].map(function(v) {\n return ks + encodeURIComponent(stringifyPrimitive(v));\n }).join(sep);\n } else {\n return ks + encodeURIComponent(stringifyPrimitive(obj[k]));\n }\n }).join(sep);\n\n }\n\n if (!name) return '';\n return encodeURIComponent(stringifyPrimitive(name)) + eq +\n encodeURIComponent(stringifyPrimitive(obj));\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/querystring/encode.js\n// module id = 10\n// module chunks = 0 1","var pubnub = require(\"pubnub\");\nvar es6Promise = require(\"es6-promise\");\nvar FetchPonyfill = require(\"fetch-ponyfill\");\n\nvar root = (typeof window !== \"undefined\" && window) ||\n (typeof global !== \"undefined\" && global) ||\n (function(){ return this; })();\n\n/**\n * @constructor\n * @param {PubNub} [options.PubNub]\n * @param {function(new:Promise)} [options.Promise]\n * @param {Storage} [options.localStorage]\n * @param {fetch} [options.fetch]\n * @param {function(new:Request)} [options.Request]\n * @param {function(new:Response)} [options.Response]\n * @param {function(new:Headers)} [options.Headers]\n * @property {PubNub} PubNub\n * @property {Storage} localStorage\n * @property {function(new:Promise)} Promise\n * @property {fetch} fetch\n * @property {function(new:Request)} Request\n * @property {function(new:Response)} Response\n * @property {function(new:Headers)} Headers\n */\nfunction Externals(options) {\n\n options = options || {};\n\n this.PubNub = options.PubNub || root.PubNub || pubnub;\n this.localStorage = options.localStorage || ((typeof root.localStorage !== 'undefined') ? root.localStorage : {});\n this.Promise = options.Promise || root.Promise || (es6Promise && es6Promise.Promise);\n\n var fetchPonyfill = FetchPonyfill ? FetchPonyfill({Promise: this.Promise}) : {};\n\n this.fetch = options.fetch || root.fetch || fetchPonyfill.fetch;\n this.Request = options.Request || root.Request || fetchPonyfill.Request;\n this.Response = options.Response || root.Response || fetchPonyfill.Response;\n this.Headers = options.Headers || root.Headers || fetchPonyfill.Headers;\n\n if (!this.fetch || !this.Response || !this.Request || !this.Headers) {\n throw new Error('Fetch API is missing');\n }\n\n if (!this.Promise) {\n throw new Error('Promise is missing');\n }\n\n if (!this.localStorage) {\n throw new Error('LocalStorage is missing');\n }\n\n if (!this.PubNub) {\n throw new Error('PubNub is missing');\n }\n\n}\n\nmodule.exports = Externals;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/core/Externals.js\n// module id = 11\n// module chunks = 0 1","module.exports = __WEBPACK_EXTERNAL_MODULE_12__;\n\n\n//////////////////\n// WEBPACK FOOTER\n// external {\"amd\":\"pubnub\"}\n// module id = 12\n// module chunks = 0 1","module.exports = __WEBPACK_EXTERNAL_MODULE_13__;\n\n\n//////////////////\n// WEBPACK FOOTER\n// external {\"amd\":\"es6-promise\"}\n// module id = 13\n// module chunks = 0 1","module.exports = __WEBPACK_EXTERNAL_MODULE_14__;\n\n\n//////////////////\n// WEBPACK FOOTER\n// external {\"amd\":\"fetch-ponyfill\"}\n// module id = 14\n// module chunks = 0 1","var EventEmitter = require(\"events\").EventEmitter;\nvar qs = require(\"querystring\");\nvar objectAssign = require('object-assign');\nvar Auth = require(\"./Auth\");\nvar Constants = require(\"../core/Constants\");\nvar ApiResponse = require(\"../http/ApiResponse\");\n\n/**\n * @constructor\n * @param {string} options.server\n * @param {string} options.appSecret\n * @param {string} options.appKey\n * @param {string} [options.appName]\n * @param {string} [options.appVersion]\n * @param {string} [options.redirectUri]\n * @param {int} [options.refreshDelayMs]\n * @param {int} [options.refreshHandicapMs]\n * @param {boolean} [options.clearCacheOnRefreshError]\n * @param {Externals} options.externals\n * @param {Cache} options.cache\n * @param {Client} options.client\n * @property {Externals} _externals\n * @property {Cache} _cache\n * @property {Client} _client\n * @property {Promise} _refreshPromise\n * @property {Auth} _auth\n */\nfunction Platform(options) {\n\n EventEmitter.call(this);\n\n this.events = {\n beforeLogin: 'beforeLogin',\n loginSuccess: 'loginSuccess',\n loginError: 'loginError',\n beforeRefresh: 'beforeRefresh',\n refreshSuccess: 'refreshSuccess',\n refreshError: 'refreshError',\n beforeLogout: 'beforeLogout',\n logoutSuccess: 'logoutSuccess',\n logoutError: 'logoutError'\n };\n\n options = options || {};\n\n /** @private */\n this._server = options.server;\n\n /** @private */\n this._appKey = options.appKey;\n\n /** @private */\n this._appSecret = options.appSecret;\n\n /** @private */\n this._redirectUri = options.redirectUri || '';\n\n /** @private */\n this._refreshDelayMs = options.refreshDelayMs || 100;\n\n /** @private */\n this._clearCacheOnRefreshError = typeof options.clearCacheOnRefreshError !== 'undefined' ?\n options.clearCacheOnRefreshError :\n true;\n\n /** @private */\n this._userAgent = (options.appName ?\n (options.appName + (options.appVersion ? '/' + options.appVersion : '')) + ' ' :\n '') + 'RCJSSDK/' + Constants.version;\n\n /** @private */\n this._externals = options.externals;\n\n /** @private */\n this._cache = options.cache;\n\n /** @private */\n this._client = options.client;\n\n /** @private */\n this._refreshPromise = null;\n\n /** @private */\n this._auth = new Auth({\n cache: this._cache,\n cacheId: Platform._cacheId,\n refreshHandicapMs: options.refreshHandicapMs\n });\n\n}\n\nPlatform._urlPrefix = '/restapi';\nPlatform._apiVersion = 'v1.0';\nPlatform._tokenEndpoint = '/restapi/oauth/token';\nPlatform._revokeEndpoint = '/restapi/oauth/revoke';\nPlatform._authorizeEndpoint = '/restapi/oauth/authorize';\nPlatform._cacheId = 'platform';\n\nPlatform.prototype = Object.create(EventEmitter.prototype);\n\nPlatform.prototype.delay = function(timeout) {\n return new this._externals.Promise(function(resolve, reject) {\n setTimeout(function() {\n resolve(null);\n }, timeout);\n });\n};\n\n/**\n * @return {Auth}\n */\nPlatform.prototype.auth = function() {\n return this._auth;\n};\n\n/**\n * @return {Client}\n */\nPlatform.prototype.client = function() {\n return this._client;\n};\n\n/**\n * @param {string} path\n * @param {object} [options]\n * @param {boolean} [options.addServer]\n * @param {string} [options.addMethod]\n * @param {boolean} [options.addToken]\n * @return {string}\n */\nPlatform.prototype.createUrl = function(path, options) {\n\n path = path || '';\n options = options || {};\n\n var builtUrl = '',\n hasHttp = path.indexOf('http://') != -1 || path.indexOf('https://') != -1;\n\n if (options.addServer && !hasHttp) builtUrl += this._server;\n\n if (path.indexOf(Platform._urlPrefix) == -1 && !hasHttp) builtUrl += Platform._urlPrefix + '/' + Platform._apiVersion;\n\n builtUrl += path;\n\n if (options.addMethod || options.addToken) builtUrl += (path.indexOf('?') > -1 ? '&' : '?');\n\n if (options.addMethod) builtUrl += '_method=' + options.addMethod;\n if (options.addToken) builtUrl += (options.addMethod ? '&' : '') + 'access_token=' + this._auth.accessToken();\n\n return builtUrl;\n\n};\n\n/**\n * @param {string} [options.redirectUri] Overrides default RedirectURI\n * @param {string} [options.state]\n * @param {string} [options.brandId]\n * @param {string} [options.display]\n * @param {string} [options.prompt]\n * @param {boolean} [options.implicit] Use Implicit Grant flow\n * @return {string}\n */\nPlatform.prototype.loginUrl = function(options) {\n\n options = options || {};\n\n return this.createUrl(Platform._authorizeEndpoint + '?' + qs.stringify({\n 'response_type': options.implicit ? 'token' : 'code',\n 'redirect_uri': options.redirectUri || this._redirectUri,\n 'client_id': this._appKey,\n 'state': options.state || '',\n 'brand_id': options.brandId || '',\n 'display': options.display || '',\n 'prompt': options.prompt || ''\n }), {addServer: true});\n\n};\n\n/**\n * @param {string} url\n * @return {Object}\n */\nPlatform.prototype.parseLoginRedirect = function(url) {\n\n function getParts(url, separator) {\n return url.split(separator).reverse()[0];\n }\n\n var response = (url.indexOf('#') === 0 && getParts(url, '#')) ||\n (url.indexOf('?') === 0 && getParts(url, '?')) ||\n null;\n\n if (!response) throw new Error('Unable to parse response');\n\n var queryString = qs.parse(response);\n\n if (!queryString) throw new Error('Unable to parse response');\n\n var error = queryString.error_description || queryString.error;\n\n if (error) {\n var e = new Error(error);\n e.error = queryString.error;\n throw e;\n }\n\n return queryString;\n\n};\n\n/**\n * Convenience method to handle 3-legged OAuth\n *\n * Attention! This is an experimental method and it's signature and behavior may change without notice.\n *\n * @experimental\n * @param {string} options.url\n * @param {number} [options.width]\n * @param {number} [options.height]\n * @param {object} [options.login] additional options for login()\n * @param {string} [options.origin]\n * @param {string} [options.property] name of window.postMessage's event data property\n * @param {string} [options.target] target for window.open()\n * @return {Promise}\n */\nPlatform.prototype.loginWindow = function(options) {\n\n return new this._externals.Promise(function(resolve, reject) {\n\n if (typeof window === 'undefined') throw new Error('This method can be used only in browser');\n\n if (!options.url) throw new Error('Missing mandatory URL parameter');\n\n options = options || {};\n options.url = options.url || 400;\n options.width = options.width || 400;\n options.height = options.height || 600;\n options.origin = options.origin || window.location.origin;\n options.property = options.property || Constants.authResponseProperty;\n options.target = options.target || '_blank';\n\n var dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left;\n var dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top;\n\n var width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;\n var height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;\n\n var left = ((width / 2) - (options.width / 2)) + dualScreenLeft;\n var top = ((height / 2) - (options.height / 2)) + dualScreenTop;\n var win = window.open(options.url, '_blank', (options.target == '_blank') ? 'scrollbars=yes, status=yes, width=' + options.width + ', height=' + options.height + ', left=' + left + ', top=' + top : '');\n\n if(!win) {\n throw new Error('Could not open login window. Please allow popups for this site');\n }\n\n if (win.focus) win.focus();\n\n var eventMethod = window.addEventListener ? 'addEventListener' : 'attachEvent';\n var eventRemoveMethod = eventMethod == 'addEventListener' ? 'removeEventListener' : 'detachEvent';\n var messageEvent = eventMethod == 'addEventListener' ? 'message' : 'onmessage';\n\n var eventListener = function(e) {\n\n try {\n\n if (e.origin != options.origin) return;\n if (!e.data || !e.data[options.property]) return; // keep waiting\n\n win.close();\n window[eventRemoveMethod](messageEvent, eventListener);\n\n\n var loginOptions = this.parseLoginRedirect(e.data[options.property]);\n\n if (!loginOptions.code && !loginOptions.access_token) throw new Error('No authorization code or token');\n\n resolve(loginOptions);\n\n /* jshint -W002 */\n } catch (e) {\n reject(e);\n }\n\n }.bind(this);\n\n window[eventMethod](messageEvent, eventListener, false);\n\n }.bind(this));\n\n};\n\n/**\n * @return {Promise}\n */\nPlatform.prototype.loggedIn = function() {\n\n return this.ensureLoggedIn().then(function() {\n return true;\n }).catch(function() {\n return false;\n });\n\n};\n\n/**\n * @param {string} options.username\n * @param {string} options.password\n * @param {string} [options.extension]\n * @param {string} [options.code]\n * @param {string} [options.redirectUri]\n * @param {string} [options.endpointId]\n * @param {string} [options.accessTokenTtl]\n * @param {string} [options.refreshTokenTtl]\n * @param {string} [options.access_token]\n * @returns {Promise}\n */\nPlatform.prototype.login = function(options) {\n\n return (new this._externals.Promise(function(resolve) {\n\n options = options || {};\n\n this.emit(this.events.beforeLogin);\n\n var body = {};\n\n if (options.access_token) {\n\n //TODO Potentially make a request to /oauth/tokeninfo\n return resolve(options);\n\n }\n\n if (!options.code) {\n\n body.grant_type = 'password';\n body.username = options.username;\n body.password = options.password;\n body.extension = options.extension || '';\n\n } else if (options.code) {\n\n body.grant_type = 'authorization_code';\n body.code = options.code;\n body.redirect_uri = options.redirectUri || this._redirectUri;\n //body.client_id = this.getCredentials().key; // not needed\n\n }\n\n if (options.endpointId) body.endpoint_id = options.endpointId;\n if (options.accessTokenTtl) body.accessTokenTtl = options.accessTokenTtl;\n if (options.refreshTokenTtl) body.refreshTokenTtl = options.refreshTokenTtl;\n\n resolve(this._tokenRequest(Platform._tokenEndpoint, body));\n\n }.bind(this))).then(function(res) {\n\n var apiResponse = res.json ? res : null;\n var json = apiResponse && apiResponse.json() || res;\n\n this._auth.setData(json);\n\n this.emit(this.events.loginSuccess, apiResponse);\n\n return apiResponse;\n\n }.bind(this)).catch(function(e) {\n\n if (this._clearCacheOnRefreshError) {\n this._cache.clean();\n }\n\n this.emit(this.events.loginError, e);\n\n throw e;\n\n }.bind(this));\n\n};\n\n/**\n * @returns {Promise}\n * @private\n */\nPlatform.prototype._refresh = function() {\n\n return this.delay(this._refreshDelayMs).then(function() {\n\n this.emit(this.events.beforeRefresh);\n\n // Perform sanity checks\n if (!this._auth.refreshToken()) throw new Error('Refresh token is missing');\n if (!this._auth.refreshTokenValid()) throw new Error('Refresh token has expired');\n\n return this._tokenRequest(Platform._tokenEndpoint, {\n \"grant_type\": \"refresh_token\",\n \"refresh_token\": this._auth.refreshToken(),\n \"access_token_ttl\": this._auth.data().expires_in + 1,\n \"refresh_token_ttl\": this._auth.data().refresh_token_expires_in + 1\n });\n\n }.bind(this)).then(function(/** @type {ApiResponse} */ res) {\n\n var json = res.json();\n\n if (!json.access_token) {\n throw this._client.makeError(new Error('Malformed OAuth response'), res);\n }\n\n this._auth.setData(json);\n\n this.emit(this.events.refreshSuccess, res);\n\n return res;\n\n }.bind(this)).catch(function(e) {\n\n e = this._client.makeError(e);\n\n if (this._clearCacheOnRefreshError) {\n this._cache.clean();\n }\n\n this.emit(this.events.refreshError, e);\n\n throw e;\n\n }.bind(this));\n\n};\n\n/**\n * @returns {Promise}\n */\nPlatform.prototype.refresh = function() {\n\n if (!this._refreshPromise) {\n\n this._refreshPromise = this._refresh()\n .then(function(res) {\n this._refreshPromise = null;\n return res;\n }.bind(this))\n .catch(function(e) {\n this._refreshPromise = null;\n throw e;\n }.bind(this));\n\n }\n\n return this._refreshPromise;\n\n};\n\n/**\n * @returns {Promise}\n */\nPlatform.prototype.logout = function() {\n\n return (new this._externals.Promise(function(resolve) {\n\n this.emit(this.events.beforeLogout);\n\n resolve(this._tokenRequest(Platform._revokeEndpoint, {\n token: this._auth.accessToken()\n }));\n\n }.bind(this))).then(function(res) {\n\n this._cache.clean();\n\n this.emit(this.events.logoutSuccess, res);\n\n return res;\n\n }.bind(this)).catch(function(e) {\n\n this.emit(this.events.logoutError, e);\n\n throw e;\n\n }.bind(this));\n\n};\n\n/**\n * @param {Request} request\n * @param {object} [options]\n * @param {boolean} [options.skipAuthCheck]\n * @return {Promise}\n */\nPlatform.prototype.inflateRequest = function(request, options) {\n\n options = options || {};\n\n if (options.skipAuthCheck) return this._externals.Promise.resolve(request);\n\n return this.ensureLoggedIn().then(function() {\n\n request.headers.set('X-User-Agent', this._userAgent);\n request.headers.set('Client-Id', this._appKey);\n request.headers.set('Authorization', this._authHeader());\n //request.url = this.createUrl(request.url, {addServer: true}); //FIXME Spec prevents this...\n\n return request;\n\n }.bind(this));\n\n};\n\n/**\n * @param {Request} request\n * @param {object} [options]\n * @param {boolean} [options.skipAuthCheck]\n * @param {boolean} [options.retry] Will be set by this method if SDK makes second request\n * @return {Promise}\n */\nPlatform.prototype.sendRequest = function(request, options) {\n\n return this.inflateRequest(request, options).then(function(request) {\n\n options = options || {};\n\n return this._client.sendRequest(request);\n\n }.bind(this)).catch(function(e) {\n\n // Guard is for errors that come from polling\n if (!e.apiResponse || !e.apiResponse.response() ||\n (e.apiResponse.response().status != ApiResponse._unauthorizedStatus) ||\n options.retry) throw e;\n\n this._auth.cancelAccessToken();\n\n options.retry = true;\n\n return this.sendRequest(request, options);\n\n }.bind(this));\n\n};\n\n/**\n * General purpose function to send anything to server\n * @param {string} options.url\n * @param {object} [options.body]\n * @param {string} [options.method]\n * @param {object} [options.query]\n * @param {object} [options.headers]\n * @param {boolean} [options.skipAuthCheck]\n * @return {Promise}\n */\nPlatform.prototype.send = function(options) {\n\n options = options || {};\n\n //FIXME https://github.com/bitinn/node-fetch/issues/43\n options.url = this.createUrl(options.url, {addServer: true});\n\n return this.sendRequest(this._client.createRequest(options), options);\n\n};\n\n/**\n * @param {string} url\n * @param {object} [query]\n * @param {object} [options]\n * @param {object} [options.headers]\n * @param {boolean} [options.skipAuthCheck]\n * @return {Promise}\n */\nPlatform.prototype.get = function(url, query, options) {\n return this.send(objectAssign({}, {method: 'GET', url: url, query: query}, options));\n};\n\n/**\n * @param {string} url\n * @param {object} body\n * @param {object} [query]\n * @param {object} [options]\n * @param {object} [options.headers]\n * @param {boolean} [options.skipAuthCheck]\n * @return {Promise}\n */\nPlatform.prototype.post = function(url, body, query, options) {\n return this.send(objectAssign({}, {method: 'POST', url: url, query: query, body: body}, options));\n};\n\n/**\n * @param {string} url\n * @param {object} [body]\n * @param {object} [query]\n * @param {object} [options]\n * @param {object} [options.headers]\n * @param {boolean} [options.skipAuthCheck]\n * @return {Promise}\n */\nPlatform.prototype.put = function(url, body, query, options) {\n return this.send(objectAssign({}, {method: 'PUT', url: url, query: query, body: body}, options));\n};\n\n/**\n * @param {string} url\n * @param {string} [query]\n * @param {object} [options]\n * @param {object} [options.headers]\n * @param {boolean} [options.skipAuthCheck]\n * @return {Promise}\n */\nPlatform.prototype['delete'] = function(url, query, options) {\n return this.send(objectAssign({}, {method: 'DELETE', url: url, query: query}, options));\n};\n\nPlatform.prototype.ensureLoggedIn = function() {\n if (this._isAccessTokenValid()) return this._externals.Promise.resolve();\n return this.refresh();\n};\n\n/**\n * @param path\n * @param body\n * @return {Promise.}\n * @private\n */\nPlatform.prototype._tokenRequest = function(path, body) {\n\n return this.send({\n url: path,\n skipAuthCheck: true,\n body: body,\n method: 'POST',\n headers: {\n 'Authorization': 'Basic ' + this._apiKey(),\n 'Content-Type': ApiResponse._urlencodedContentType\n }\n });\n\n};\n\n/**\n * @return {boolean}\n * @private\n */\nPlatform.prototype._isAccessTokenValid = function() {\n return this._auth.accessTokenValid();\n};\n\n/**\n * @return {string}\n * @private\n */\nPlatform.prototype._apiKey = function() {\n var apiKey = this._appKey + ':' + this._appSecret;\n return (typeof btoa == 'function') ? btoa(apiKey) : new Buffer(apiKey).toString('base64');\n};\n\n/**\n * @return {string}\n * @private\n */\nPlatform.prototype._authHeader = function() {\n var token = this._auth.accessToken();\n return this._auth.tokenType() + (token ? ' ' + token : '');\n};\n\nmodule.exports = Platform;\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/platform/Platform.js\n// module id = 15\n// module chunks = 0 1","/**\n * @param {Cache} options.cache\n * @param {string} options.cacheId\n * @param {int} [options.refreshHandicapMs]\n * @constructor\n * @property {Cache} _cache\n * @property {int} _refreshHandicapMs\n * @property {string} _cacheId\n */\nfunction Auth(options) {\n\n /** @private */\n this._cache = options.cache;\n\n /** @private */\n this._cacheId = options.cacheId;\n\n /** @private */\n this._refreshHandicapMs = options.refreshHandicapMs || 60 * 1000; // 1 minute\n\n}\n\nAuth.prototype.accessToken = function() {\n return this.data().access_token;\n};\n\nAuth.prototype.refreshToken = function() {\n return this.data().refresh_token;\n};\n\nAuth.prototype.tokenType = function() {\n return this.data().token_type;\n};\n\n/**\n * @return {{token_type: string, access_token: string, expires_in: number, refresh_token: string, refresh_token_expires_in: number}}\n */\nAuth.prototype.data = function() {\n\n return this._cache.getItem(this._cacheId) || {\n token_type: '',\n access_token: '',\n expires_in: 0,\n refresh_token: '',\n refresh_token_expires_in: 0\n };\n\n};\n\n/**\n * @param {object} newData\n * @return {Auth}\n */\nAuth.prototype.setData = function(newData) {\n\n newData = newData || {};\n\n var data = this.data();\n\n Object.keys(newData).forEach(function(key) {\n data[key] = newData[key];\n });\n\n data.expire_time = Date.now() + (data.expires_in * 1000);\n data.refresh_token_expire_time = Date.now() + (data.refresh_token_expires_in * 1000);\n\n this._cache.setItem(this._cacheId, data);\n\n return this;\n\n};\n\n/**\n * Check if there is a valid (not expired) access token\n * @return {boolean}\n */\nAuth.prototype.accessTokenValid = function() {\n\n var authData = this.data();\n return (authData.expire_time - this._refreshHandicapMs > Date.now());\n\n};\n\n/**\n * Check if there is a valid (not expired) access token\n * @return {boolean}\n */\nAuth.prototype.refreshTokenValid = function() {\n\n return (this.data().refresh_token_expire_time > Date.now());\n\n};\n\n/**\n * @return {Auth}\n */\nAuth.prototype.cancelAccessToken = function() {\n\n return this.setData({\n access_token: '',\n expires_in: 0\n });\n\n};\n\nmodule.exports = Auth;\n\n//export interface IAuthData {\n// remember?:boolean;\n// token_type?:string;\n// access_token?:string;\n// expires_in?:number; // actually it's string\n// expire_time?:number;\n// refresh_token?:string;\n// refresh_token_expires_in?:number; // actually it's string\n// refresh_token_expire_time?:number;\n// scope?:string;\n//}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/platform/Auth.js\n// module id = 16\n// module chunks = 0 1","var version = process.env.RCSDK_VERSION;\n\n// This will become false during the Webpack build, so no traces of package.json will be there\nif (!process.env.RCSDK_VERSION) {\n version = require('../../package.json').version;\n}\n\nmodule.exports = {\n version: version,\n authResponseProperty: 'RCAuthorizationResponse'\n};\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/core/Constants.js\n// module id = 17\n// module chunks = 0 1","var EventEmitter = require(\"events\").EventEmitter;\n\n/**\n * @param {Platform} options.platform\n * @param {Externals} options.externals\n * @param {int} [options.pollInterval]\n * @param {int} [options.renewHandicapMs]\n * @property {Externals} _externals\n * @property {Platform} _platform\n * @property {int} _pollInterval\n * @property {int} _renewHandicapMs\n * @property {PUBNUB} _pubnub\n * @property {string} _pubnubLastChannel\n * @property {int} _timeout\n * @property {ISubscription} _subscription\n * @constructor\n */\nfunction Subscription(options) {\n\n EventEmitter.call(this);\n\n options = options || {};\n\n this.events = {\n notification: 'notification',\n removeSuccess: 'removeSuccess',\n removeError: 'removeError',\n renewSuccess: 'renewSuccess',\n renewError: 'renewError',\n subscribeSuccess: 'subscribeSuccess',\n subscribeError: 'subscribeError'\n };\n\n /** @private */\n this._externals = options.externals;\n\n /** @private */\n this._platform = options.platform;\n\n /** @private */\n this._pollInterval = options.pollInterval || 10 * 1000;\n\n /** @private */\n this._renewHandicapMs = options.renewHandicapMs || 2 * 60 * 1000;\n\n /** @private */\n this._pubnub = null;\n\n /** @private */\n this._pubnubLastChannel = null;\n\n /** @private */\n this._timeout = null;\n\n /** @private */\n this._subscription = null;\n\n}\n\nSubscription.prototype = Object.create(EventEmitter.prototype);\n\nSubscription.prototype.subscribed = function() {\n\n var subscription = this.subscription();\n\n return !!(subscription.id &&\n subscription.deliveryMode &&\n subscription.deliveryMode.subscriberKey &&\n subscription.deliveryMode.address);\n\n};\n\n/**\n * @return {boolean}\n */\nSubscription.prototype.alive = function() {\n return this.subscribed() && Date.now() < this.expirationTime();\n};\n\n/**\n * @return {boolean}\n */\nSubscription.prototype.expired = function() {\n if (!this.subscribed()) return true;\n return !this.subscribed() || Date.now() > this.subscription().expirationTime;\n};\n\nSubscription.prototype.expirationTime = function() {\n return new Date(this.subscription().expirationTime || 0).getTime() - this._renewHandicapMs;\n};\n\n/**\n * @param {ISubscription} subscription\n * @return {Subscription}\n */\nSubscription.prototype.setSubscription = function(subscription) {\n\n subscription = subscription || {};\n\n this._clearTimeout();\n this._setSubscription(subscription);\n this._subscribeAtPubnub();\n this._setTimeout();\n\n return this;\n\n};\n\n/**\n * @return {ISubscription}\n */\nSubscription.prototype.subscription = function() {\n return this._subscription || {};\n};\n\n/**\n * Creates or updates subscription if there is an active one\n * @returns {Promise}\n */\nSubscription.prototype.register = function() {\n\n if (this.alive()) {\n return this.renew();\n } else {\n return this.subscribe();\n }\n\n};\n\n/**\n * @return {string[]}\n */\nSubscription.prototype.eventFilters = function() {\n return this.subscription().eventFilters || [];\n};\n\n/**\n * @param {string[]} events\n * @return {Subscription}\n */\nSubscription.prototype.addEventFilters = function(events) {\n this.setEventFilters(this.eventFilters().concat(events));\n return this;\n};\n\n/**\n * @param {string[]} events\n * @return {Subscription}\n */\nSubscription.prototype.setEventFilters = function(events) {\n var subscription = this.subscription();\n subscription.eventFilters = events;\n this._setSubscription(subscription);\n return this;\n};\n\n/**\n * @returns {Promise}\n */\nSubscription.prototype.subscribe = function() {\n\n return (new this._externals.Promise(function(resolve) {\n\n this._clearTimeout();\n\n if (!this.eventFilters().length) throw new Error('Events are undefined');\n\n resolve(this._platform.post('/subscription', {\n eventFilters: this._getFullEventFilters(),\n deliveryMode: {\n transportType: 'PubNub'\n }\n }));\n\n }.bind(this))).then(function(response) {\n\n var json = response.json();\n\n this.setSubscription(json)\n .emit(this.events.subscribeSuccess, response);\n\n return response;\n\n }.bind(this)).catch(function(e) {\n\n e = this._platform.client().makeError(e);\n\n this.reset()\n .emit(this.events.subscribeError, e);\n\n throw e;\n\n }.bind(this));\n\n};\n\n/**\n * @returns {Promise}\n */\nSubscription.prototype.renew = function() {\n\n return (new this._externals.Promise(function(resolve) {\n\n this._clearTimeout();\n\n if (!this.subscribed()) throw new Error('No subscription');\n\n if (!this.eventFilters().length) throw new Error('Events are undefined');\n\n resolve(this._platform.put('/subscription/' + this.subscription().id, {\n eventFilters: this._getFullEventFilters()\n }));\n\n }.bind(this))).then(function(response) {\n\n var json = response.json();\n\n this.setSubscription(json)\n .emit(this.events.renewSuccess, response);\n\n return response;\n\n }.bind(this)).catch(function(e) {\n\n e = this._platform.client().makeError(e);\n\n this.reset()\n .emit(this.events.renewError, e);\n\n throw e;\n\n }.bind(this));\n\n};\n\n/**\n * @returns {Promise}\n */\nSubscription.prototype.remove = function() {\n\n return (new this._externals.Promise(function(resolve) {\n\n if (!this.subscribed()) throw new Error('No subscription');\n\n resolve(this._platform.delete('/subscription/' + this.subscription().id));\n\n }.bind(this))).then(function(response) {\n\n this.reset()\n .emit(this.events.removeSuccess, response);\n\n return response;\n\n }.bind(this)).catch(function(e) {\n\n e = this._platform.client().makeError(e);\n\n this.emit(this.events.removeError, e);\n\n throw e;\n\n }.bind(this));\n\n};\n\n/**\n * @returns {Promise}\n */\nSubscription.prototype.resubscribe = function() {\n var filters = this.eventFilters();\n return this.reset().setEventFilters(filters).subscribe();\n};\n\n/**\n * Remove subscription and disconnect from PubNub\n * This method resets subscription at client side but backend is not notified\n * @return {Subscription}\n */\nSubscription.prototype.reset = function() {\n this._clearTimeout();\n if (this.subscribed() && this._pubnub) this._pubnub.unsubscribe({channel: this.subscription().deliveryMode.address});\n this._setSubscription(null);\n return this;\n};\n\n/**\n * @param subscription\n * @private\n */\nSubscription.prototype._setSubscription = function(subscription) {\n this._subscription = subscription;\n};\n\n/**\n * @return {string[]}\n * @private\n */\nSubscription.prototype._getFullEventFilters = function() {\n\n return this.eventFilters().map(function(event) {\n return this._platform.createUrl(event);\n }.bind(this));\n\n};\n\n/**\n * @return {Subscription}\n * @private\n */\nSubscription.prototype._setTimeout = function() {\n\n this._clearTimeout();\n\n if (!this.alive()) throw new Error('Subscription is not alive');\n\n this._timeout = setInterval(function() {\n\n if (this.alive()) return;\n\n if (this.expired()) {\n this.subscribe();\n } else {\n this.renew();\n }\n\n }.bind(this), this._pollInterval);\n\n return this;\n\n};\n\n/**\n * @return {Subscription}\n * @private\n */\nSubscription.prototype._clearTimeout = function() {\n clearInterval(this._timeout);\n return this;\n};\n\nSubscription.prototype._decrypt = function(message) {\n\n if (!this.subscribed()) throw new Error('No subscription');\n\n if (this.subscription().deliveryMode.encryptionKey) {\n\n message = this._pubnub.decrypt(message, this.subscription().deliveryMode.encryptionKey, {\n encryptKey: false,\n keyEncoding: 'base64',\n keyLength: 128,\n mode: 'ecb'\n });\n\n }\n\n return message;\n\n};\n\n/**\n * @param message\n * @return {Subscription}\n * @private\n */\nSubscription.prototype._notify = function(message) {\n this.emit(this.events.notification, this._decrypt(message));\n return this;\n};\n\n/**\n * @return {Subscription}\n * @private\n */\nSubscription.prototype._subscribeAtPubnub = function() {\n\n if (!this.alive()) throw new Error('Subscription is not alive');\n\n var deliveryMode = this.subscription().deliveryMode;\n\n if (this._pubnub) {\n\n if (this._pubnubLastChannel == deliveryMode.address) { // Nothing to update, keep listening to same channel\n return this;\n } else if (this._pubnubLastChannel) { // Need to subscribe to new channel\n this._pubnub.unsubscribe({channel: this._pubnubLastChannel});\n }\n\n // Re-init for new data\n this._pubnub = this._pubnub.init({\n ssl: true,\n subscribe_key: deliveryMode.subscriberKey\n });\n\n } else {\n\n // Init from scratch\n this._pubnub = new this._externals.PubNub({\n ssl: true,\n subscribe_key: deliveryMode.subscriberKey\n });\n\n }\n\n this._pubnubLastChannel = deliveryMode.address;\n\n this._pubnub.subscribe({\n channel: deliveryMode.address,\n message: this._notify.bind(this),\n connect: function() {}\n });\n\n return this;\n\n};\n\nmodule.exports = Subscription;\n\n/**\n * The complete Triforce, or one or more components of the Triforce.\n * @typedef {Object} ISubscription\n * @property {string} [id]\n * @property {string} [uri]\n * @property {string[]} [eventFilters]\n * @property {string} [expirationTime] Format: 2014-03-12T19:54:35.613Z\n * @property {int} [expiresIn]\n * @property {string} [deliveryMode.transportType]\n * @property {boolean} [deliveryMode.encryption]\n * @property {string} [deliveryMode.address]\n * @property {string} [deliveryMode.subscriberKey]\n * @property {string} [deliveryMode.encryptionKey]\n * @property {string} [deliveryMode.secretKey]\n * @property {string} [creationTime]\n * @property {string} [status] Active\n */\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/subscription/Subscription.js\n// module id = 18\n// module chunks = 0 1","var Subscription = require(\"./Subscription\");\n\n/**\n * @param {Platform} options.platform\n * @param {Externals} options.externals\n * @param {Cache} options.cache\n * @param {string} options.cacheKey\n * @param {int} [options.pollInterval]\n * @param {int} [options.renewHandicapMs]\n * @return {CachedSubscription}\n * @constructor\n * @property {Cache} _cache\n * @extends Subscription\n */\nfunction CachedSubscription(options) {\n\n options = options || {};\n\n if (!options.cacheKey) throw new Error('Cached Subscription requires cacheKey parameter to be defined');\n\n /** @private */\n this._cacheKey = options.cacheKey;\n\n Subscription.call(this, options);\n\n /** @private */\n this._cache = options.cache;\n\n // This is not used in this class\n this._subscription = undefined;\n\n}\n\nCachedSubscription.prototype = Object.create(Subscription.prototype);\n\nCachedSubscription.prototype.subscription = function() {\n return this._cache.getItem(this._cacheKey) || {};\n};\n\nCachedSubscription.prototype._setSubscription = function(subscription) {\n return this._cache.setItem(this._cacheKey, subscription);\n};\n\n/**\n * This function checks whether there are any pre-defined eventFilters in cache and if not -- uses provided as defaults\n * @param {string[]} events\n * @return {CachedSubscription}\n */\nCachedSubscription.prototype.restore = function(events) {\n\n if (!this.eventFilters().length) {\n this.setEventFilters(events);\n }\n\n return this;\n\n};\n\nmodule.exports = CachedSubscription;\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/subscription/CachedSubscription.js\n// module id = 19\n// module chunks = 0 1"],"sourceRoot":""} \ No newline at end of file diff --git a/build/ringcentral.min.js b/build/ringcentral.min.js index 81e2a6f4..06ab39ad 100644 --- a/build/ringcentral.min.js +++ b/build/ringcentral.min.js @@ -1,4 +1,9 @@ -!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require(void 0),require(void 0),require(void 0)):"function"==typeof define&&define.amd?define(["pubnub","es6-promise","fetch-ponyfill"],t):"object"==typeof exports?exports.SDK=t(require(void 0),require(void 0),require(void 0)):(e.RingCentral=e.RingCentral||{},e.RingCentral.SDK=t(e[void 0],e[void 0],e[void 0]))}(this,function(e,t,r){return function(e){function t(n){if(r[n])return r[n].exports;var s=r[n]={exports:{},id:n,loaded:!1};return e[n].call(s.exports,s,s.exports,t),s.loaded=!0,s.exports}var r={};return t.m=e,t.c=r,t.p="/build/",t(0)}([function(e,t,r){function n(e){this._externals=new h(e),this._cache=new i({externals:this._externals,prefix:e.cachePrefix}),this._client=new o(this._externals),this._platform=new u(s({},e,{externals:this._externals,client:this._client,cache:this._cache}))}var s=r(1),i=r(2),o=r(3),h=r(11),u=r(15),c=r(18),a=r(19),p=r(17);n.version=p.version,n.server={sandbox:"https://platform.devtest.ringcentral.com",production:"https://platform.ringcentral.com"},n.prototype.platform=function(){return this._platform},n.prototype.cache=function(){return this._cache},n.prototype.createSubscription=function(e){return new c(s({},e,{externals:this._externals,platform:this._platform}))},n.prototype.createCachedSubscription=function(e){return e="string"==typeof arguments[0]?{cacheKey:arguments[0].toString()}:e||{},new a(s({},e,{externals:this._externals,platform:this._platform,cache:this._cache}))},n.handleLoginRedirect=function(e){var t=window.location.hash?window.location.hash:window.location.search,r={};r[p.authResponseProperty]=t,window.opener.postMessage(r,e||window.location.origin)},e.exports=n},function(e,t){"use strict";function r(e){if(null===e||void 0===e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}function n(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},r=0;r<10;r++)t["_"+String.fromCharCode(r)]=r;var n=Object.getOwnPropertyNames(t).map(function(e){return t[e]});if("0123456789"!==n.join(""))return!1;var s={};return"abcdefghijklmnopqrst".split("").forEach(function(e){s[e]=e}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},s)).join("")}catch(i){return!1}}var s=Object.prototype.hasOwnProperty,i=Object.prototype.propertyIsEnumerable;e.exports=n()?Object.assign:function(e,t){for(var n,o,h=r(e),u=1;u-1?"&":"?")+u.stringify(e.query)),n("Accept",e.headers)||(e.headers.Accept=h._jsonContentType),i(e.body)||!e.body){var t=n(h._contentType,e.headers);t||(t=h._contentType,e.headers[t]=h._jsonContentType);var r=e.headers[t];r.indexOf(h._jsonContentType)>-1?"GET"!==e.method&&"HEAD"!==e.method||!e.body?e.body=JSON.stringify(e.body):e.body=void 0:r.indexOf(h._urlencodedContentType)>-1&&(e.body=u.stringify(e.body))}var o=new this._externals.Request(e.url,e);return o.originalBody=e.body,o},e.exports=s},function(e,t,r){/*! +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require(void 0),require(void 0),require(void 0)):"function"==typeof define&&define.amd?define(["pubnub","es6-promise","fetch-ponyfill"],t):"object"==typeof exports?exports.SDK=t(require(void 0),require(void 0),require(void 0)):(e.RingCentral=e.RingCentral||{},e.RingCentral.SDK=t(e[void 0],e[void 0],e[void 0]))}(this,function(e,t,r){return function(e){function t(n){if(r[n])return r[n].exports;var s=r[n]={exports:{},id:n,loaded:!1};return e[n].call(s.exports,s,s.exports,t),s.loaded=!0,s.exports}var r={};return t.m=e,t.c=r,t.p="/build/",t(0)}([function(e,t,r){function n(e){this._externals=new h(e),this._cache=new i({externals:this._externals,prefix:e.cachePrefix}),this._client=new o(this._externals),this._platform=new u(s({},e,{externals:this._externals,client:this._client,cache:this._cache}))}var s=r(1),i=r(2),o=r(3),h=r(11),u=r(15),c=r(18),a=r(19),p=r(17);n.version=p.version,n.server={sandbox:"https://platform.devtest.ringcentral.com",production:"https://platform.ringcentral.com"},n.prototype.platform=function(){return this._platform},n.prototype.cache=function(){return this._cache},n.prototype.createSubscription=function(e){return new c(s({},e,{externals:this._externals,platform:this._platform}))},n.prototype.createCachedSubscription=function(e){return e="string"==typeof arguments[0]?{cacheKey:arguments[0].toString()}:e||{},new a(s({},e,{externals:this._externals,platform:this._platform,cache:this._cache}))},n.handleLoginRedirect=function(e){var t=window.location.hash?window.location.hash:window.location.search,r={};r[p.authResponseProperty]=t,window.opener.postMessage(r,e||window.location.origin)},e.exports=n},function(e,t){/* +object-assign +(c) Sindre Sorhus +@license MIT +*/ +"use strict";function r(e){if(null===e||void 0===e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}function n(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},r=0;r<10;r++)t["_"+String.fromCharCode(r)]=r;var n=Object.getOwnPropertyNames(t).map(function(e){return t[e]});if("0123456789"!==n.join(""))return!1;var s={};return"abcdefghijklmnopqrst".split("").forEach(function(e){s[e]=e}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},s)).join("")}catch(e){return!1}}var s=Object.getOwnPropertySymbols,i=Object.prototype.hasOwnProperty,o=Object.prototype.propertyIsEnumerable;e.exports=n()?Object.assign:function(e,t){for(var n,h,u=r(e),c=1;c-1?"&":"?")+u.stringify(e.query)),n("Accept",e.headers)||(e.headers.Accept=h._jsonContentType),i(e.body)||!e.body){var t=n(h._contentType,e.headers);t||(t=h._contentType,e.headers[t]=h._jsonContentType);var r=e.headers[t];r.indexOf(h._jsonContentType)>-1?"GET"!==e.method&&"HEAD"!==e.method||!e.body?e.body=JSON.stringify(e.body):e.body=void 0:r.indexOf(h._urlencodedContentType)>-1&&(e.body=u.stringify(e.body))}var o=new this._externals.Request(e.url,e);return o.originalBody=e.body,o},e.exports=s},function(e,t,r){/*! * is-plain-object * * Copyright (c) 2014-2015, Jon Schlinkert. @@ -10,5 +15,5 @@ * Copyright (c) 2014-2015, Jon Schlinkert. * Licensed under the MIT License. */ -"use strict";e.exports=function(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)}},function(e,t){function r(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function n(e){return"function"==typeof e}function s(e){return"number"==typeof e}function i(e){return"object"==typeof e&&null!==e}function o(e){return void 0===e}e.exports=r,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._maxListeners=void 0,r.defaultMaxListeners=10,r.prototype.setMaxListeners=function(e){if(!s(e)||e<0||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},r.prototype.emit=function(e){var t,r,s,h,u,c;if(this._events||(this._events={}),"error"===e&&(!this._events.error||i(this._events.error)&&!this._events.error.length)){if(t=arguments[1],t instanceof Error)throw t;var a=new Error('Uncaught, unspecified "error" event. ('+t+")");throw a.context=t,a}if(r=this._events[e],o(r))return!1;if(n(r))switch(arguments.length){case 1:r.call(this);break;case 2:r.call(this,arguments[1]);break;case 3:r.call(this,arguments[1],arguments[2]);break;default:h=Array.prototype.slice.call(arguments,1),r.apply(this,h)}else if(i(r))for(h=Array.prototype.slice.call(arguments,1),c=r.slice(),s=c.length,u=0;u0&&this._events[e].length>s&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace())),this},r.prototype.on=r.prototype.addListener,r.prototype.once=function(e,t){function r(){this.removeListener(e,r),s||(s=!0,t.apply(this,arguments))}if(!n(t))throw TypeError("listener must be a function");var s=!1;return r.listener=t,this.on(e,r),this},r.prototype.removeListener=function(e,t){var r,s,o,h;if(!n(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(r=this._events[e],o=r.length,s=-1,r===t||n(r.listener)&&r.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(i(r)){for(h=o;h-- >0;)if(r[h]===t||r[h].listener&&r[h].listener===t){s=h;break}if(s<0)return this;1===r.length?(r.length=0,delete this._events[e]):r.splice(s,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},r.prototype.removeAllListeners=function(e){var t,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(r=this._events[e],n(r))this.removeListener(e,r);else if(r)for(;r.length;)this.removeListener(e,r[r.length-1]);return delete this._events[e],this},r.prototype.listeners=function(e){var t;return t=this._events&&this._events[e]?n(this._events[e])?[this._events[e]]:this._events[e].slice():[]},r.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(n(t))return 1;if(t)return t.length}return 0},r.listenerCount=function(e,t){return e.listenerCount(t)}},function(e,t){function r(e){this._externals=e.externals,this._request=e.request,this._response=e.response,this._text=e.responseText||"",this._json=null,this._multipart=[]}r._contentType="Content-Type",r._jsonContentType="application/json",r._multipartContentType="multipart/mixed",r._urlencodedContentType="application/x-www-form-urlencoded",r._headerSeparator=":",r._bodySeparator="\n\n",r._boundarySeparator="--",r._unauthorizedStatus=401,r.prototype.receiveResponse=function(e){return this._response=e,new this._externals.Promise(function(e){return e(this._isMultipart()||this._isJson()?this.response().text():"")}.bind(this)).then(function(e){return this._text=e,e}.bind(this))},r.prototype.response=function(){return this._response},r.prototype.request=function(){return this._request},r.prototype.ok=function(){return this._response&&this._response.ok},r.prototype.text=function(){if(!this._isJson()&&!this._isMultipart())throw new Error("Response is not text");return this._text},r.prototype.json=function(){if(!this._isJson())throw new Error("Response is not JSON");return this._json||(this._json=this._text?JSON.parse(this._text):null),this._json},r.prototype.error=function(e){if(this.ok()&&!e)return null;var t=(this._response&&this._response.status?this._response.status+" ":"")+(this._response&&this._response.statusText?this._response.statusText:"");try{this.json().message&&(t=this.json().message),this.json().error_description&&(t=this.json().error_description),this.json().description&&(t=this.json().description)}catch(r){}return t},r.prototype.toMultipart=function(){return this._isMultipart()?this.multipart():[this]},r.prototype.multipart=function(){if(!this._isMultipart())throw new Error("Response is not multipart");if(!this._multipart.length){var e=this.text();if(!e)throw new Error("No response body");var t=this._getContentType().match(/boundary=([^;]+)/i)[1];if(!t)throw new Error("Cannot find boundary");var n=e.toString().split(r._boundarySeparator+t);if(""===n[0].trim()&&n.shift(),n[n.length-1].trim()==r._boundarySeparator&&n.pop(),n.length<1)throw new Error("No parts in body");var s=this._create(n.shift(),this._response.status,this._response.statusText).json();this._multipart=n.map(function(e,t){var r=s.response[t].status;return this._create(e,r)}.bind(this))}return this._multipart},r.prototype._isContentType=function(e){return this._getContentType().indexOf(e)>-1},r.prototype._getContentType=function(){return this._response.headers.get(r._contentType)||""},r.prototype._isMultipart=function(){return this._isContentType(r._multipartContentType)},r.prototype._isJson=function(){return this._isContentType(r._jsonContentType)},r.prototype._create=function(e,t,n){e=e||"",t=t||200,n=n||"OK",e=e.replace(/\r/g,"");var s=new this._externals.Headers,i=e.split(r._bodySeparator),o=i.length>1?i.shift():"";e=i.length>0?i.join(r._bodySeparator):null,(o||"").split("\n").forEach(function(e){var t=e.trim().split(r._headerSeparator),n=t.shift().trim(),i=t.join(r._headerSeparator).trim();n&&s.append(n,i)});var h=new this._externals.Response(e,{headers:s,status:t,statusText:n});return new r({externals:this._externals,request:null,response:h,responseText:e})},e.exports=r},function(e,t,r){"use strict";t.decode=t.parse=r(9),t.encode=t.stringify=r(10)},function(e,t){"use strict";function r(e,t){return Object.prototype.hasOwnProperty.call(e,t)}e.exports=function(e,t,n,s){t=t||"&",n=n||"=";var i={};if("string"!=typeof e||0===e.length)return i;var o=/\+/g;e=e.split(t);var h=1e3;s&&"number"==typeof s.maxKeys&&(h=s.maxKeys);var u=e.length;h>0&&u>h&&(u=h);for(var c=0;c=0?(a=d.substr(0,_),p=d.substr(_+1)):(a=d,p=""),l=decodeURIComponent(a),f=decodeURIComponent(p),r(i,l)?Array.isArray(i[l])?i[l].push(f):i[l]=[i[l],f]:i[l]=f}return i}},function(e,t){"use strict";var r=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};e.exports=function(e,t,n,s){return t=t||"&",n=n||"=",null===e&&(e=void 0),"object"==typeof e?Object.keys(e).map(function(s){var i=encodeURIComponent(r(s))+n;return Array.isArray(e[s])?e[s].map(function(e){return i+encodeURIComponent(r(e))}).join(t):i+encodeURIComponent(r(e[s]))}).join(t):s?encodeURIComponent(r(s))+n+encodeURIComponent(r(e)):""}},function(e,t,r){(function(t){function n(e){e=e||{},this.PUBNUB=e.PUBNUB||h.PUBNUB||s,this.localStorage=e.localStorage||("undefined"!=typeof h.localStorage?h.localStorage:{}),this.Promise=e.Promise||h.Promise||i&&i.Promise;var t=o?o({Promise:this.Promise}):{};if(this.fetch=e.fetch||h.fetch||t.fetch,this.Request=e.Request||h.Request||t.Request,this.Response=e.Response||h.Response||t.Response,this.Headers=e.Headers||h.Headers||t.Headers,!(this.fetch&&this.Response&&this.Request&&this.Headers))throw new Error("Fetch API is missing");if(!this.Promise)throw new Error("Promise is missing");if(!this.localStorage)throw new Error("LocalStorage is missing");if(!this.PUBNUB)throw new Error("PUBNUB is missing")}var s=r(12),i=r(13),o=r(14),h="undefined"!=typeof window&&window||"undefined"!=typeof t&&t||function(){return this}();e.exports=n}).call(t,function(){return this}())},function(t,r){t.exports=e},function(e,r){e.exports=t},function(e,t){e.exports=r},function(e,t,r){function n(e){s.call(this),this.events={beforeLogin:"beforeLogin",loginSuccess:"loginSuccess",loginError:"loginError",beforeRefresh:"beforeRefresh",refreshSuccess:"refreshSuccess",refreshError:"refreshError",beforeLogout:"beforeLogout",logoutSuccess:"logoutSuccess",logoutError:"logoutError"},e=e||{},this._server=e.server,this._appKey=e.appKey,this._appSecret=e.appSecret,this._redirectUri=e.redirectUri||"",this._refreshDelayMs=e.refreshDelayMs||100,this._clearCacheOnRefreshError="undefined"==typeof e.clearCacheOnRefreshError||e.clearCacheOnRefreshError,this._userAgent=(e.appName?e.appName+(e.appVersion?"/"+e.appVersion:"")+" ":"")+"RCJSSDK/"+u.version,this._externals=e.externals,this._cache=e.cache,this._client=e.client,this._refreshPromise=null,this._auth=new h({cache:this._cache,cacheId:n._cacheId,refreshHandicapMs:e.refreshHandicapMs})}var s=r(6).EventEmitter,i=r(8),o=r(1),h=r(16),u=r(17),c=r(7);n._urlPrefix="/restapi",n._apiVersion="v1.0",n._tokenEndpoint="/restapi/oauth/token",n._revokeEndpoint="/restapi/oauth/revoke",n._authorizeEndpoint="/restapi/oauth/authorize",n._cacheId="platform",n.prototype=Object.create(s.prototype),n.prototype.delay=function(e){return new this._externals.Promise(function(t,r){setTimeout(function(){t(null)},e)})},n.prototype.auth=function(){return this._auth},n.prototype.client=function(){return this._client},n.prototype.createUrl=function(e,t){e=e||"",t=t||{};var r="",s=e.indexOf("http://")!=-1||e.indexOf("https://")!=-1;return t.addServer&&!s&&(r+=this._server),e.indexOf(n._urlPrefix)!=-1||s||(r+=n._urlPrefix+"/"+n._apiVersion),r+=e,(t.addMethod||t.addToken)&&(r+=e.indexOf("?")>-1?"&":"?"),t.addMethod&&(r+="_method="+t.addMethod),t.addToken&&(r+=(t.addMethod?"&":"")+"access_token="+this._auth.accessToken()),r},n.prototype.loginUrl=function(e){return e=e||{},this.createUrl(n._authorizeEndpoint+"?"+i.stringify({response_type:e.implicit?"token":"code",redirect_uri:e.redirectUri||this._redirectUri,client_id:this._appKey,state:e.state||"",brand_id:e.brandId||"",display:e.display||"",prompt:e.prompt||""}),{addServer:!0})},n.prototype.parseLoginRedirect=function(e){function t(e,t){return e.split(t).reverse()[0]}var r=0===e.indexOf("#")&&t(e,"#")||0===e.indexOf("?")&&t(e,"?")||null;if(!r)throw new Error("Unable to parse response");var n=i.parse(r);if(!n)throw new Error("Unable to parse response");var s=n.error_description||n.error;if(s){var o=new Error(s);throw o.error=n.error,o}return n},n.prototype.loginWindow=function(e){return new this._externals.Promise(function(t,r){if("undefined"==typeof window)throw new Error("This method can be used only in browser");if(!e.url)throw new Error("Missing mandatory URL parameter");e=e||{},e.url=e.url||400,e.width=e.width||400,e.height=e.height||600,e.origin=e.origin||window.location.origin,e.property=e.property||u.authResponseProperty,e.target=e.target||"_blank";var n=void 0!==window.screenLeft?window.screenLeft:screen.left,s=void 0!==window.screenTop?window.screenTop:screen.top,i=window.innerWidth?window.innerWidth:document.documentElement.clientWidth?document.documentElement.clientWidth:screen.width,o=window.innerHeight?window.innerHeight:document.documentElement.clientHeight?document.documentElement.clientHeight:screen.height,h=i/2-e.width/2+n,c=o/2-e.height/2+s,a=window.open(e.url,"_blank","_blank"==e.target?"scrollbars=yes, status=yes, width="+e.width+", height="+e.height+", left="+h+", top="+c:"");if(!a)throw new Error("Could not open login window. Please allow popups for this site");a.focus&&a.focus();var p=window.addEventListener?"addEventListener":"attachEvent",l="addEventListener"==p?"removeEventListener":"detachEvent",f="addEventListener"==p?"message":"onmessage",d=function(n){try{if(n.origin!=e.origin)return;if(!n.data||!n.data[e.property])return;a.close(),window[l](f,d);var s=this.parseLoginRedirect(n.data[e.property]);if(!s.code&&!s.access_token)throw new Error("No authorization code or token");t(s)}catch(n){r(n)}}.bind(this);window[p](f,d,!1)}.bind(this))},n.prototype.loggedIn=function(){return this.ensureLoggedIn().then(function(){return!0})["catch"](function(){return!1})},n.prototype.login=function(e){return new this._externals.Promise(function(t){e=e||{},this.emit(this.events.beforeLogin);var r={};return e.access_token?t(e):(e.code?e.code&&(r.grant_type="authorization_code",r.code=e.code,r.redirect_uri=e.redirectUri||this._redirectUri):(r.grant_type="password",r.username=e.username,r.password=e.password,r.extension=e.extension||""),e.endpointId&&(r.endpoint_id=e.endpointId),e.accessTokenTtl&&(r.accessTokenTtl=e.accessTokenTtl),e.refreshTokenTtl&&(r.refreshTokenTtl=e.refreshTokenTtl),void t(this._tokenRequest(n._tokenEndpoint,r)))}.bind(this)).then(function(e){var t=e.json?e:null,r=t&&t.json()||e;return this._auth.setData(r),this.emit(this.events.loginSuccess,t),t}.bind(this))["catch"](function(e){throw this._clearCacheOnRefreshError&&this._cache.clean(),this.emit(this.events.loginError,e),e}.bind(this))},n.prototype._refresh=function(){return this.delay(this._refreshDelayMs).then(function(){if(this.emit(this.events.beforeRefresh),!this._auth.refreshToken())throw new Error("Refresh token is missing");if(!this._auth.refreshTokenValid())throw new Error("Refresh token has expired");return this._tokenRequest(n._tokenEndpoint,{grant_type:"refresh_token",refresh_token:this._auth.refreshToken(),access_token_ttl:this._auth.data().expires_in+1,refresh_token_ttl:this._auth.data().refresh_token_expires_in+1})}.bind(this)).then(function(e){var t=e.json();if(!t.access_token)throw this._client.makeError(new Error("Malformed OAuth response"),e);return this._auth.setData(t),this.emit(this.events.refreshSuccess,e),e}.bind(this))["catch"](function(e){throw e=this._client.makeError(e),this._clearCacheOnRefreshError&&this._cache.clean(),this.emit(this.events.refreshError,e),e}.bind(this))},n.prototype.refresh=function(){return this._refreshPromise||(this._refreshPromise=this._refresh().then(function(e){return this._refreshPromise=null,e}.bind(this))["catch"](function(e){throw this._refreshPromise=null,e}.bind(this))),this._refreshPromise},n.prototype.logout=function(){return new this._externals.Promise(function(e){this.emit(this.events.beforeLogout),e(this._tokenRequest(n._revokeEndpoint,{token:this._auth.accessToken()}))}.bind(this)).then(function(e){return this._cache.clean(),this.emit(this.events.logoutSuccess,e),e}.bind(this))["catch"](function(e){throw this.emit(this.events.logoutError,e),e}.bind(this))},n.prototype.inflateRequest=function(e,t){return t=t||{},t.skipAuthCheck?this._externals.Promise.resolve(e):this.ensureLoggedIn().then(function(){return e.headers.set("X-User-Agent",this._userAgent),e.headers.set("Client-Id",this._appKey),e.headers.set("Authorization",this._authHeader()),e}.bind(this))},n.prototype.sendRequest=function(e,t){return this.inflateRequest(e,t).then(function(e){return t=t||{},this._client.sendRequest(e)}.bind(this))["catch"](function(r){if(!r.apiResponse||!r.apiResponse.response()||r.apiResponse.response().status!=c._unauthorizedStatus||t.retry)throw r;return this._auth.cancelAccessToken(),t.retry=!0,this.sendRequest(e,t)}.bind(this))},n.prototype.send=function(e){return e=e||{},e.url=this.createUrl(e.url,{addServer:!0}),this.sendRequest(this._client.createRequest(e),e)},n.prototype.get=function(e,t,r){return this.send(o({},{method:"GET",url:e,query:t},r))},n.prototype.post=function(e,t,r,n){return this.send(o({},{method:"POST",url:e,query:r,body:t},n))},n.prototype.put=function(e,t,r,n){return this.send(o({},{method:"PUT",url:e,query:r,body:t},n))},n.prototype["delete"]=function(e,t,r){return this.send(o({},{method:"DELETE",url:e,query:t},r))},n.prototype.ensureLoggedIn=function(){return this._isAccessTokenValid()?this._externals.Promise.resolve():this.refresh()},n.prototype._tokenRequest=function(e,t){return this.send({url:e,skipAuthCheck:!0,body:t,method:"POST",headers:{Authorization:"Basic "+this._apiKey(),"Content-Type":c._urlencodedContentType}})},n.prototype._isAccessTokenValid=function(){return this._auth.accessTokenValid()},n.prototype._apiKey=function(){var e=this._appKey+":"+this._appSecret;return"function"==typeof btoa?btoa(e):new Buffer(e).toString("base64")},n.prototype._authHeader=function(){var e=this._auth.accessToken();return this._auth.tokenType()+(e?" "+e:"")},e.exports=n},function(e,t){function r(e){this._cache=e.cache,this._cacheId=e.cacheId,this._refreshHandicapMs=e.refreshHandicapMs||6e4}r.prototype.accessToken=function(){return this.data().access_token},r.prototype.refreshToken=function(){return this.data().refresh_token},r.prototype.tokenType=function(){return this.data().token_type},r.prototype.data=function(){return this._cache.getItem(this._cacheId)||{token_type:"",access_token:"",expires_in:0,refresh_token:"",refresh_token_expires_in:0}},r.prototype.setData=function(e){e=e||{};var t=this.data();return Object.keys(e).forEach(function(r){t[r]=e[r]}),t.expire_time=Date.now()+1e3*t.expires_in,t.refresh_token_expire_time=Date.now()+1e3*t.refresh_token_expires_in,this._cache.setItem(this._cacheId,t),this},r.prototype.accessTokenValid=function(){var e=this.data();return e.expire_time-this._refreshHandicapMs>Date.now()},r.prototype.refreshTokenValid=function(){return this.data().refresh_token_expire_time>Date.now()},r.prototype.cancelAccessToken=function(){return this.setData({access_token:"",expires_in:0})},e.exports=r},function(e,t,r){var n="3.0.0";e.exports={version:n,authResponseProperty:"RCAuthorizationResponse"}},function(e,t,r){function n(e){s.call(this),e=e||{},this.events={notification:"notification",removeSuccess:"removeSuccess",removeError:"removeError",renewSuccess:"renewSuccess",renewError:"renewError",subscribeSuccess:"subscribeSuccess",subscribeError:"subscribeError"},this._externals=e.externals,this._platform=e.platform,this._pollInterval=e.pollInterval||1e4,this._renewHandicapMs=e.renewHandicapMs||12e4,this._pubnub=null,this._pubnubLastChannel=null,this._timeout=null,this._subscription=null}var s=r(6).EventEmitter;n.prototype=Object.create(s.prototype),n.prototype.subscribed=function(){var e=this.subscription();return!!(e.id&&e.deliveryMode&&e.deliveryMode.subscriberKey&&e.deliveryMode.address)},n.prototype.alive=function(){return this.subscribed()&&Date.now()this.subscription().expirationTime)},n.prototype.expirationTime=function(){return new Date(this.subscription().expirationTime||0).getTime()-this._renewHandicapMs},n.prototype.setSubscription=function(e){return e=e||{},this._clearTimeout(),this._setSubscription(e),this._subscribeAtPubnub(),this._setTimeout(),this},n.prototype.subscription=function(){return this._subscription||{}},n.prototype.register=function(){return this.alive()?this.renew():this.subscribe()},n.prototype.eventFilters=function(){return this.subscription().eventFilters||[]},n.prototype.addEventFilters=function(e){return this.setEventFilters(this.eventFilters().concat(e)),this},n.prototype.setEventFilters=function(e){var t=this.subscription();return t.eventFilters=e,this._setSubscription(t),this},n.prototype.subscribe=function(){return new this._externals.Promise(function(e){if(this._clearTimeout(),!this.eventFilters().length)throw new Error("Events are undefined");e(this._platform.post("/subscription",{eventFilters:this._getFullEventFilters(),deliveryMode:{transportType:"PubNub"}}))}.bind(this)).then(function(e){var t=e.json();return this.setSubscription(t).emit(this.events.subscribeSuccess,e),e}.bind(this))["catch"](function(e){throw e=this._platform.client().makeError(e),this.reset().emit(this.events.subscribeError,e),e}.bind(this))},n.prototype.renew=function(){return new this._externals.Promise(function(e){if(this._clearTimeout(),!this.subscribed())throw new Error("No subscription");if(!this.eventFilters().length)throw new Error("Events are undefined");e(this._platform.put("/subscription/"+this.subscription().id,{eventFilters:this._getFullEventFilters()}))}.bind(this)).then(function(e){var t=e.json();return this.setSubscription(t).emit(this.events.renewSuccess,e),e}.bind(this))["catch"](function(e){throw e=this._platform.client().makeError(e),this.reset().emit(this.events.renewError,e),e}.bind(this))},n.prototype.remove=function(){return new this._externals.Promise(function(e){if(!this.subscribed())throw new Error("No subscription");e(this._platform["delete"]("/subscription/"+this.subscription().id))}.bind(this)).then(function(e){return this.reset().emit(this.events.removeSuccess,e),e}.bind(this))["catch"](function(e){throw e=this._platform.client().makeError(e),this.emit(this.events.removeError,e),e}.bind(this))},n.prototype.resubscribe=function(){var e=this.eventFilters();return this.reset().setEventFilters(e).subscribe()},n.prototype.reset=function(){return this._clearTimeout(),this.subscribed()&&this._pubnub&&this._pubnub.unsubscribe({channel:this.subscription().deliveryMode.address}),this._setSubscription(null),this},n.prototype._setSubscription=function(e){this._subscription=e},n.prototype._getFullEventFilters=function(){return this.eventFilters().map(function(e){return this._platform.createUrl(e)}.bind(this))},n.prototype._setTimeout=function(){if(this._clearTimeout(),!this.alive())throw new Error("Subscription is not alive");return this._timeout=setInterval(function(){this.alive()||(this.expired()?this.subscribe():this.renew())}.bind(this),this._pollInterval),this},n.prototype._clearTimeout=function(){return clearInterval(this._timeout),this},n.prototype._decrypt=function(e){if(!this.subscribed())throw new Error("No subscription");return this.subscription().deliveryMode.encryptionKey&&(e=this._externals.PUBNUB.crypto_obj.decrypt(e,this.subscription().deliveryMode.encryptionKey,{encryptKey:!1,keyEncoding:"base64",keyLength:128,mode:"ecb"})),e},n.prototype._notify=function(e){return this.emit(this.events.notification,this._decrypt(e)),this},n.prototype._subscribeAtPubnub=function(){if(!this.alive())throw new Error("Subscription is not alive");var e=this.subscription().deliveryMode;if(this._pubnub){if(this._pubnubLastChannel==e.address)return this;this._pubnubLastChannel&&this._pubnub.unsubscribe({channel:this._pubnubLastChannel}),this._pubnub=this._pubnub.init({ssl:!0,subscribe_key:e.subscriberKey})}else this._pubnub=this._externals.PUBNUB.init({ssl:!0,subscribe_key:e.subscriberKey}),this._pubnub.ready();return this._pubnubLastChannel=e.address,this._pubnub.subscribe({channel:e.address,message:this._notify.bind(this),connect:function(){}}),this},e.exports=n},function(e,t,r){function n(e){if(e=e||{},!e.cacheKey)throw new Error("Cached Subscription requires cacheKey parameter to be defined");this._cacheKey=e.cacheKey,s.call(this,e),this._cache=e.cache,this._subscription=void 0}var s=r(18);n.prototype=Object.create(s.prototype),n.prototype.subscription=function(){return this._cache.getItem(this._cacheKey)||{}},n.prototype._setSubscription=function(e){return this._cache.setItem(this._cacheKey,e)},n.prototype.restore=function(e){return this.eventFilters().length||this.setEventFilters(e),this},e.exports=n}])}); +"use strict";e.exports=function(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)}},function(e,t){function r(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function n(e){return"function"==typeof e}function s(e){return"number"==typeof e}function i(e){return"object"==typeof e&&null!==e}function o(e){return void 0===e}e.exports=r,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._maxListeners=void 0,r.defaultMaxListeners=10,r.prototype.setMaxListeners=function(e){if(!s(e)||e<0||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},r.prototype.emit=function(e){var t,r,s,h,u,c;if(this._events||(this._events={}),"error"===e&&(!this._events.error||i(this._events.error)&&!this._events.error.length)){if(t=arguments[1],t instanceof Error)throw t;var a=new Error('Uncaught, unspecified "error" event. ('+t+")");throw a.context=t,a}if(r=this._events[e],o(r))return!1;if(n(r))switch(arguments.length){case 1:r.call(this);break;case 2:r.call(this,arguments[1]);break;case 3:r.call(this,arguments[1],arguments[2]);break;default:h=Array.prototype.slice.call(arguments,1),r.apply(this,h)}else if(i(r))for(h=Array.prototype.slice.call(arguments,1),c=r.slice(),s=c.length,u=0;u0&&this._events[e].length>s&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace())),this},r.prototype.on=r.prototype.addListener,r.prototype.once=function(e,t){function r(){this.removeListener(e,r),s||(s=!0,t.apply(this,arguments))}if(!n(t))throw TypeError("listener must be a function");var s=!1;return r.listener=t,this.on(e,r),this},r.prototype.removeListener=function(e,t){var r,s,o,h;if(!n(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(r=this._events[e],o=r.length,s=-1,r===t||n(r.listener)&&r.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(i(r)){for(h=o;h-- >0;)if(r[h]===t||r[h].listener&&r[h].listener===t){s=h;break}if(s<0)return this;1===r.length?(r.length=0,delete this._events[e]):r.splice(s,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},r.prototype.removeAllListeners=function(e){var t,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(r=this._events[e],n(r))this.removeListener(e,r);else if(r)for(;r.length;)this.removeListener(e,r[r.length-1]);return delete this._events[e],this},r.prototype.listeners=function(e){var t;return t=this._events&&this._events[e]?n(this._events[e])?[this._events[e]]:this._events[e].slice():[]},r.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(n(t))return 1;if(t)return t.length}return 0},r.listenerCount=function(e,t){return e.listenerCount(t)}},function(e,t){function r(e){this._externals=e.externals,this._request=e.request,this._response=e.response,this._text=e.responseText||"",this._json=null,this._multipart=[]}r._contentType="Content-Type",r._jsonContentType="application/json",r._multipartContentType="multipart/mixed",r._urlencodedContentType="application/x-www-form-urlencoded",r._headerSeparator=":",r._bodySeparator="\n\n",r._boundarySeparator="--",r._unauthorizedStatus=401,r.prototype.receiveResponse=function(e){return this._response=e,new this._externals.Promise(function(e){return e(this._isMultipart()||this._isJson()?this.response().text():"")}.bind(this)).then(function(e){return this._text=e,e}.bind(this))},r.prototype.response=function(){return this._response},r.prototype.request=function(){return this._request},r.prototype.ok=function(){return this._response&&this._response.ok},r.prototype.text=function(){if(!this._isJson()&&!this._isMultipart())throw new Error("Response is not text");return this._text},r.prototype.json=function(){if(!this._isJson())throw new Error("Response is not JSON");return this._json||(this._json=this._text?JSON.parse(this._text):null),this._json},r.prototype.error=function(e){if(this.ok()&&!e)return null;var t=(this._response&&this._response.status?this._response.status+" ":"")+(this._response&&this._response.statusText?this._response.statusText:"");try{this.json().message&&(t=this.json().message),this.json().error_description&&(t=this.json().error_description),this.json().description&&(t=this.json().description)}catch(e){}return t},r.prototype.toMultipart=function(){return this._isMultipart()?this.multipart():[this]},r.prototype.multipart=function(){if(!this._isMultipart())throw new Error("Response is not multipart");if(!this._multipart.length){var e=this.text();if(!e)throw new Error("No response body");var t=this._getContentType().match(/boundary=([^;]+)/i)[1];if(!t)throw new Error("Cannot find boundary");var n=e.toString().split(r._boundarySeparator+t);if(""===n[0].trim()&&n.shift(),n[n.length-1].trim()==r._boundarySeparator&&n.pop(),n.length<1)throw new Error("No parts in body");var s=this._create(n.shift(),this._response.status,this._response.statusText).json();this._multipart=n.map(function(e,t){var r=s.response[t].status;return this._create(e,r)}.bind(this))}return this._multipart},r.prototype._isContentType=function(e){return this._getContentType().indexOf(e)>-1},r.prototype._getContentType=function(){return this._response.headers.get(r._contentType)||""},r.prototype._isMultipart=function(){return this._isContentType(r._multipartContentType)},r.prototype._isJson=function(){return this._isContentType(r._jsonContentType)},r.prototype._create=function(e,t,n){e=e||"",t=t||200,n=n||"OK",e=e.replace(/\r/g,"");var s=new this._externals.Headers,i=e.split(r._bodySeparator),o=i.length>1?i.shift():"";e=i.length>0?i.join(r._bodySeparator):null,(o||"").split("\n").forEach(function(e){var t=e.trim().split(r._headerSeparator),n=t.shift().trim(),i=t.join(r._headerSeparator).trim();n&&s.append(n,i)});var h=new this._externals.Response(e,{headers:s,status:t,statusText:n});return new r({externals:this._externals,request:null,response:h,responseText:e})},e.exports=r},function(e,t,r){"use strict";t.decode=t.parse=r(9),t.encode=t.stringify=r(10)},function(e,t){"use strict";function r(e,t){return Object.prototype.hasOwnProperty.call(e,t)}e.exports=function(e,t,n,s){t=t||"&",n=n||"=";var i={};if("string"!=typeof e||0===e.length)return i;var o=/\+/g;e=e.split(t);var h=1e3;s&&"number"==typeof s.maxKeys&&(h=s.maxKeys);var u=e.length;h>0&&u>h&&(u=h);for(var c=0;c=0?(a=d.substr(0,_),p=d.substr(_+1)):(a=d,p=""),l=decodeURIComponent(a),f=decodeURIComponent(p),r(i,l)?Array.isArray(i[l])?i[l].push(f):i[l]=[i[l],f]:i[l]=f}return i}},function(e,t){"use strict";var r=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};e.exports=function(e,t,n,s){return t=t||"&",n=n||"=",null===e&&(e=void 0),"object"==typeof e?Object.keys(e).map(function(s){var i=encodeURIComponent(r(s))+n;return Array.isArray(e[s])?e[s].map(function(e){return i+encodeURIComponent(r(e))}).join(t):i+encodeURIComponent(r(e[s]))}).join(t):s?encodeURIComponent(r(s))+n+encodeURIComponent(r(e)):""}},function(e,t,r){(function(t){function n(e){e=e||{},this.PubNub=e.PubNub||h.PubNub||s,this.localStorage=e.localStorage||("undefined"!=typeof h.localStorage?h.localStorage:{}),this.Promise=e.Promise||h.Promise||i&&i.Promise;var t=o?o({Promise:this.Promise}):{};if(this.fetch=e.fetch||h.fetch||t.fetch,this.Request=e.Request||h.Request||t.Request,this.Response=e.Response||h.Response||t.Response,this.Headers=e.Headers||h.Headers||t.Headers,!(this.fetch&&this.Response&&this.Request&&this.Headers))throw new Error("Fetch API is missing");if(!this.Promise)throw new Error("Promise is missing");if(!this.localStorage)throw new Error("LocalStorage is missing");if(!this.PubNub)throw new Error("PubNub is missing")}var s=r(12),i=r(13),o=r(14),h="undefined"!=typeof window&&window||"undefined"!=typeof t&&t||function(){return this}();e.exports=n}).call(t,function(){return this}())},function(t,r){t.exports=e},function(e,r){e.exports=t},function(e,t){e.exports=r},function(e,t,r){function n(e){s.call(this),this.events={beforeLogin:"beforeLogin",loginSuccess:"loginSuccess",loginError:"loginError",beforeRefresh:"beforeRefresh",refreshSuccess:"refreshSuccess",refreshError:"refreshError",beforeLogout:"beforeLogout",logoutSuccess:"logoutSuccess",logoutError:"logoutError"},e=e||{},this._server=e.server,this._appKey=e.appKey,this._appSecret=e.appSecret,this._redirectUri=e.redirectUri||"",this._refreshDelayMs=e.refreshDelayMs||100,this._clearCacheOnRefreshError="undefined"==typeof e.clearCacheOnRefreshError||e.clearCacheOnRefreshError,this._userAgent=(e.appName?e.appName+(e.appVersion?"/"+e.appVersion:"")+" ":"")+"RCJSSDK/"+u.version,this._externals=e.externals,this._cache=e.cache,this._client=e.client,this._refreshPromise=null,this._auth=new h({cache:this._cache,cacheId:n._cacheId,refreshHandicapMs:e.refreshHandicapMs})}var s=r(6).EventEmitter,i=r(8),o=r(1),h=r(16),u=r(17),c=r(7);n._urlPrefix="/restapi",n._apiVersion="v1.0",n._tokenEndpoint="/restapi/oauth/token",n._revokeEndpoint="/restapi/oauth/revoke",n._authorizeEndpoint="/restapi/oauth/authorize",n._cacheId="platform",n.prototype=Object.create(s.prototype),n.prototype.delay=function(e){return new this._externals.Promise(function(t,r){setTimeout(function(){t(null)},e)})},n.prototype.auth=function(){return this._auth},n.prototype.client=function(){return this._client},n.prototype.createUrl=function(e,t){e=e||"",t=t||{};var r="",s=e.indexOf("http://")!=-1||e.indexOf("https://")!=-1;return t.addServer&&!s&&(r+=this._server),e.indexOf(n._urlPrefix)!=-1||s||(r+=n._urlPrefix+"/"+n._apiVersion),r+=e,(t.addMethod||t.addToken)&&(r+=e.indexOf("?")>-1?"&":"?"),t.addMethod&&(r+="_method="+t.addMethod),t.addToken&&(r+=(t.addMethod?"&":"")+"access_token="+this._auth.accessToken()),r},n.prototype.loginUrl=function(e){return e=e||{},this.createUrl(n._authorizeEndpoint+"?"+i.stringify({response_type:e.implicit?"token":"code",redirect_uri:e.redirectUri||this._redirectUri,client_id:this._appKey,state:e.state||"",brand_id:e.brandId||"",display:e.display||"",prompt:e.prompt||""}),{addServer:!0})},n.prototype.parseLoginRedirect=function(e){function t(e,t){return e.split(t).reverse()[0]}var r=0===e.indexOf("#")&&t(e,"#")||0===e.indexOf("?")&&t(e,"?")||null;if(!r)throw new Error("Unable to parse response");var n=i.parse(r);if(!n)throw new Error("Unable to parse response");var s=n.error_description||n.error;if(s){var o=new Error(s);throw o.error=n.error,o}return n},n.prototype.loginWindow=function(e){return new this._externals.Promise(function(t,r){if("undefined"==typeof window)throw new Error("This method can be used only in browser");if(!e.url)throw new Error("Missing mandatory URL parameter");e=e||{},e.url=e.url||400,e.width=e.width||400,e.height=e.height||600,e.origin=e.origin||window.location.origin,e.property=e.property||u.authResponseProperty,e.target=e.target||"_blank";var n=void 0!==window.screenLeft?window.screenLeft:screen.left,s=void 0!==window.screenTop?window.screenTop:screen.top,i=window.innerWidth?window.innerWidth:document.documentElement.clientWidth?document.documentElement.clientWidth:screen.width,o=window.innerHeight?window.innerHeight:document.documentElement.clientHeight?document.documentElement.clientHeight:screen.height,h=i/2-e.width/2+n,c=o/2-e.height/2+s,a=window.open(e.url,"_blank","_blank"==e.target?"scrollbars=yes, status=yes, width="+e.width+", height="+e.height+", left="+h+", top="+c:"");if(!a)throw new Error("Could not open login window. Please allow popups for this site");a.focus&&a.focus();var p=window.addEventListener?"addEventListener":"attachEvent",l="addEventListener"==p?"removeEventListener":"detachEvent",f="addEventListener"==p?"message":"onmessage",d=function(n){try{if(n.origin!=e.origin)return;if(!n.data||!n.data[e.property])return;a.close(),window[l](f,d);var s=this.parseLoginRedirect(n.data[e.property]);if(!s.code&&!s.access_token)throw new Error("No authorization code or token");t(s)}catch(e){r(e)}}.bind(this);window[p](f,d,!1)}.bind(this))},n.prototype.loggedIn=function(){return this.ensureLoggedIn().then(function(){return!0}).catch(function(){return!1})},n.prototype.login=function(e){return new this._externals.Promise(function(t){e=e||{},this.emit(this.events.beforeLogin);var r={};return e.access_token?t(e):(e.code?e.code&&(r.grant_type="authorization_code",r.code=e.code,r.redirect_uri=e.redirectUri||this._redirectUri):(r.grant_type="password",r.username=e.username,r.password=e.password,r.extension=e.extension||""),e.endpointId&&(r.endpoint_id=e.endpointId),e.accessTokenTtl&&(r.accessTokenTtl=e.accessTokenTtl),e.refreshTokenTtl&&(r.refreshTokenTtl=e.refreshTokenTtl),void t(this._tokenRequest(n._tokenEndpoint,r)))}.bind(this)).then(function(e){var t=e.json?e:null,r=t&&t.json()||e;return this._auth.setData(r),this.emit(this.events.loginSuccess,t),t}.bind(this)).catch(function(e){throw this._clearCacheOnRefreshError&&this._cache.clean(),this.emit(this.events.loginError,e),e}.bind(this))},n.prototype._refresh=function(){return this.delay(this._refreshDelayMs).then(function(){if(this.emit(this.events.beforeRefresh),!this._auth.refreshToken())throw new Error("Refresh token is missing");if(!this._auth.refreshTokenValid())throw new Error("Refresh token has expired");return this._tokenRequest(n._tokenEndpoint,{grant_type:"refresh_token",refresh_token:this._auth.refreshToken(),access_token_ttl:this._auth.data().expires_in+1,refresh_token_ttl:this._auth.data().refresh_token_expires_in+1})}.bind(this)).then(function(e){var t=e.json();if(!t.access_token)throw this._client.makeError(new Error("Malformed OAuth response"),e);return this._auth.setData(t),this.emit(this.events.refreshSuccess,e),e}.bind(this)).catch(function(e){throw e=this._client.makeError(e),this._clearCacheOnRefreshError&&this._cache.clean(),this.emit(this.events.refreshError,e),e}.bind(this))},n.prototype.refresh=function(){return this._refreshPromise||(this._refreshPromise=this._refresh().then(function(e){return this._refreshPromise=null,e}.bind(this)).catch(function(e){throw this._refreshPromise=null,e}.bind(this))),this._refreshPromise},n.prototype.logout=function(){return new this._externals.Promise(function(e){this.emit(this.events.beforeLogout),e(this._tokenRequest(n._revokeEndpoint,{token:this._auth.accessToken()}))}.bind(this)).then(function(e){return this._cache.clean(),this.emit(this.events.logoutSuccess,e),e}.bind(this)).catch(function(e){throw this.emit(this.events.logoutError,e),e}.bind(this))},n.prototype.inflateRequest=function(e,t){return t=t||{},t.skipAuthCheck?this._externals.Promise.resolve(e):this.ensureLoggedIn().then(function(){return e.headers.set("X-User-Agent",this._userAgent),e.headers.set("Client-Id",this._appKey),e.headers.set("Authorization",this._authHeader()),e}.bind(this))},n.prototype.sendRequest=function(e,t){return this.inflateRequest(e,t).then(function(e){return t=t||{},this._client.sendRequest(e)}.bind(this)).catch(function(r){if(!r.apiResponse||!r.apiResponse.response()||r.apiResponse.response().status!=c._unauthorizedStatus||t.retry)throw r;return this._auth.cancelAccessToken(),t.retry=!0,this.sendRequest(e,t)}.bind(this))},n.prototype.send=function(e){return e=e||{},e.url=this.createUrl(e.url,{addServer:!0}),this.sendRequest(this._client.createRequest(e),e)},n.prototype.get=function(e,t,r){return this.send(o({},{method:"GET",url:e,query:t},r))},n.prototype.post=function(e,t,r,n){return this.send(o({},{method:"POST",url:e,query:r,body:t},n))},n.prototype.put=function(e,t,r,n){return this.send(o({},{method:"PUT",url:e,query:r,body:t},n))},n.prototype.delete=function(e,t,r){return this.send(o({},{method:"DELETE",url:e,query:t},r))},n.prototype.ensureLoggedIn=function(){return this._isAccessTokenValid()?this._externals.Promise.resolve():this.refresh()},n.prototype._tokenRequest=function(e,t){return this.send({url:e,skipAuthCheck:!0,body:t,method:"POST",headers:{Authorization:"Basic "+this._apiKey(),"Content-Type":c._urlencodedContentType}})},n.prototype._isAccessTokenValid=function(){return this._auth.accessTokenValid()},n.prototype._apiKey=function(){var e=this._appKey+":"+this._appSecret;return"function"==typeof btoa?btoa(e):new Buffer(e).toString("base64")},n.prototype._authHeader=function(){var e=this._auth.accessToken();return this._auth.tokenType()+(e?" "+e:"")},e.exports=n},function(e,t){function r(e){this._cache=e.cache,this._cacheId=e.cacheId,this._refreshHandicapMs=e.refreshHandicapMs||6e4}r.prototype.accessToken=function(){return this.data().access_token},r.prototype.refreshToken=function(){return this.data().refresh_token},r.prototype.tokenType=function(){return this.data().token_type},r.prototype.data=function(){return this._cache.getItem(this._cacheId)||{token_type:"",access_token:"",expires_in:0,refresh_token:"",refresh_token_expires_in:0}},r.prototype.setData=function(e){e=e||{};var t=this.data();return Object.keys(e).forEach(function(r){t[r]=e[r]}),t.expire_time=Date.now()+1e3*t.expires_in,t.refresh_token_expire_time=Date.now()+1e3*t.refresh_token_expires_in,this._cache.setItem(this._cacheId,t),this},r.prototype.accessTokenValid=function(){var e=this.data();return e.expire_time-this._refreshHandicapMs>Date.now()},r.prototype.refreshTokenValid=function(){return this.data().refresh_token_expire_time>Date.now()},r.prototype.cancelAccessToken=function(){return this.setData({access_token:"",expires_in:0})},e.exports=r},function(e,t,r){var n="3.1.0";e.exports={version:n,authResponseProperty:"RCAuthorizationResponse"}},function(e,t,r){function n(e){s.call(this),e=e||{},this.events={notification:"notification",removeSuccess:"removeSuccess",removeError:"removeError",renewSuccess:"renewSuccess",renewError:"renewError",subscribeSuccess:"subscribeSuccess",subscribeError:"subscribeError"},this._externals=e.externals,this._platform=e.platform,this._pollInterval=e.pollInterval||1e4,this._renewHandicapMs=e.renewHandicapMs||12e4,this._pubnub=null,this._pubnubLastChannel=null,this._timeout=null,this._subscription=null}var s=r(6).EventEmitter;n.prototype=Object.create(s.prototype),n.prototype.subscribed=function(){var e=this.subscription();return!!(e.id&&e.deliveryMode&&e.deliveryMode.subscriberKey&&e.deliveryMode.address)},n.prototype.alive=function(){return this.subscribed()&&Date.now()this.subscription().expirationTime)},n.prototype.expirationTime=function(){return new Date(this.subscription().expirationTime||0).getTime()-this._renewHandicapMs},n.prototype.setSubscription=function(e){return e=e||{},this._clearTimeout(),this._setSubscription(e),this._subscribeAtPubnub(),this._setTimeout(),this},n.prototype.subscription=function(){return this._subscription||{}},n.prototype.register=function(){return this.alive()?this.renew():this.subscribe()},n.prototype.eventFilters=function(){return this.subscription().eventFilters||[]},n.prototype.addEventFilters=function(e){return this.setEventFilters(this.eventFilters().concat(e)),this},n.prototype.setEventFilters=function(e){var t=this.subscription();return t.eventFilters=e,this._setSubscription(t),this},n.prototype.subscribe=function(){return new this._externals.Promise(function(e){if(this._clearTimeout(),!this.eventFilters().length)throw new Error("Events are undefined");e(this._platform.post("/subscription",{eventFilters:this._getFullEventFilters(),deliveryMode:{transportType:"PubNub"}}))}.bind(this)).then(function(e){var t=e.json();return this.setSubscription(t).emit(this.events.subscribeSuccess,e),e}.bind(this)).catch(function(e){throw e=this._platform.client().makeError(e),this.reset().emit(this.events.subscribeError,e),e}.bind(this))},n.prototype.renew=function(){return new this._externals.Promise(function(e){if(this._clearTimeout(),!this.subscribed())throw new Error("No subscription");if(!this.eventFilters().length)throw new Error("Events are undefined");e(this._platform.put("/subscription/"+this.subscription().id,{eventFilters:this._getFullEventFilters()}))}.bind(this)).then(function(e){var t=e.json();return this.setSubscription(t).emit(this.events.renewSuccess,e),e}.bind(this)).catch(function(e){throw e=this._platform.client().makeError(e),this.reset().emit(this.events.renewError,e),e}.bind(this))},n.prototype.remove=function(){return new this._externals.Promise(function(e){if(!this.subscribed())throw new Error("No subscription");e(this._platform.delete("/subscription/"+this.subscription().id))}.bind(this)).then(function(e){return this.reset().emit(this.events.removeSuccess,e),e}.bind(this)).catch(function(e){throw e=this._platform.client().makeError(e),this.emit(this.events.removeError,e),e}.bind(this))},n.prototype.resubscribe=function(){var e=this.eventFilters();return this.reset().setEventFilters(e).subscribe()},n.prototype.reset=function(){return this._clearTimeout(),this.subscribed()&&this._pubnub&&this._pubnub.unsubscribe({channel:this.subscription().deliveryMode.address}),this._setSubscription(null),this},n.prototype._setSubscription=function(e){this._subscription=e},n.prototype._getFullEventFilters=function(){return this.eventFilters().map(function(e){return this._platform.createUrl(e)}.bind(this))},n.prototype._setTimeout=function(){if(this._clearTimeout(),!this.alive())throw new Error("Subscription is not alive");return this._timeout=setInterval(function(){this.alive()||(this.expired()?this.subscribe():this.renew())}.bind(this),this._pollInterval),this},n.prototype._clearTimeout=function(){return clearInterval(this._timeout),this},n.prototype._decrypt=function(e){if(!this.subscribed())throw new Error("No subscription");return this.subscription().deliveryMode.encryptionKey&&(e=this._pubnub.decrypt(e,this.subscription().deliveryMode.encryptionKey,{encryptKey:!1,keyEncoding:"base64",keyLength:128,mode:"ecb"})),e},n.prototype._notify=function(e){return this.emit(this.events.notification,this._decrypt(e)),this},n.prototype._subscribeAtPubnub=function(){if(!this.alive())throw new Error("Subscription is not alive");var e=this.subscription().deliveryMode;if(this._pubnub){if(this._pubnubLastChannel==e.address)return this;this._pubnubLastChannel&&this._pubnub.unsubscribe({channel:this._pubnubLastChannel}),this._pubnub=this._pubnub.init({ssl:!0,subscribe_key:e.subscriberKey})}else this._pubnub=new this._externals.PubNub({ssl:!0,subscribe_key:e.subscriberKey});return this._pubnubLastChannel=e.address,this._pubnub.subscribe({channel:e.address,message:this._notify.bind(this),connect:function(){}}),this},e.exports=n},function(e,t,r){function n(e){if(e=e||{},!e.cacheKey)throw new Error("Cached Subscription requires cacheKey parameter to be defined");this._cacheKey=e.cacheKey,s.call(this,e),this._cache=e.cache,this._subscription=void 0}var s=r(18);n.prototype=Object.create(s.prototype),n.prototype.subscription=function(){return this._cache.getItem(this._cacheKey)||{}},n.prototype._setSubscription=function(e){return this._cache.setItem(this._cacheKey,e)},n.prototype.restore=function(e){return this.eventFilters().length||this.setEventFilters(e),this},e.exports=n}])}); //# sourceMappingURL=ringcentral.min.js.map \ No newline at end of file diff --git a/build/ringcentral.min.js.map b/build/ringcentral.min.js.map index d8d17696..f12c7bf1 100644 --- a/build/ringcentral.min.js.map +++ b/build/ringcentral.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["webpack:///webpack/universalModuleDefinition?5ca6","webpack:///ringcentral.min.js","webpack:///webpack/bootstrap e778b74917863b61271c?e9bc","webpack:///./src/SDK.js?d032","webpack:///./~/object-assign/index.js?2927","webpack:///./src/core/Cache.js?1256","webpack:///./src/http/Client.js?4230","webpack:///./~/is-plain-object/index.js?2af1","webpack:///./~/is-plain-object/~/isobject/index.js?f4f9","webpack:///./~/events/events.js?7c71","webpack:///./src/http/ApiResponse.js?d4a4","webpack:///./~/querystring/index.js?fce8","webpack:///./~/querystring/decode.js?c250","webpack:///./~/querystring/encode.js?e86b","webpack:///./src/core/Externals.js?fdf1","webpack:///external {\"amd\":\"pubnub\"}?3fcf","webpack:///external {\"amd\":\"es6-promise\"}?8a6b","webpack:///external {\"amd\":\"fetch-ponyfill\"}?ec6e","webpack:///./src/platform/Platform.js?8f42","webpack:///./src/platform/Auth.js?cef5","webpack:///./src/core/Constants.js?22d0","webpack:///./src/subscription/Subscription.js?3ae8","webpack:///./src/subscription/CachedSubscription.js?3294"],"names":["root","factory","exports","module","require","undefined","define","amd","this","__WEBPACK_EXTERNAL_MODULE_12__","__WEBPACK_EXTERNAL_MODULE_13__","__WEBPACK_EXTERNAL_MODULE_14__","modules","__webpack_require__","moduleId","installedModules","id","loaded","call","m","c","p","SDK","options","_externals","Externals","_cache","Cache","externals","prefix","cachePrefix","_client","Client","_platform","Platform","objectAssign","client","cache","Subscription","CachedSubscription","Constants","version","server","sandbox","production","prototype","platform","createSubscription","createCachedSubscription","arguments","cacheKey","toString","handleLoginRedirect","origin","response","window","location","hash","search","msg","authResponseProperty","opener","postMessage","toObject","val","TypeError","Object","shouldUseNative","assign","test1","String","getOwnPropertyNames","test2","i","fromCharCode","order2","map","n","join","test3","split","forEach","letter","keys","e","hasOwnProperty","propIsEnumerable","propertyIsEnumerable","target","source","from","symbols","to","s","length","key","getOwnPropertySymbols","_prefix","defaultPrefix","setItem","data","localStorage","_prefixKey","JSON","stringify","removeItem","getItem","item","parse","clean","indexOf","findHeaderName","name","headers","toLowerCase","reduce","res","EventEmitter","events","beforeRequest","requestSuccess","requestError","isPlainObject","ApiResponse","qs","_allowedMethods","create","sendRequest","request","apiResponse","Promise","resolve","emit","_loadResponse","bind","then","receiveResponse","ok","Error","makeError","fetch","originalMessage","message","error","createRequest","init","url","method","toUpperCase","credentials","mode","query","Accept","_jsonContentType","body","contentTypeHeaderName","_contentType","contentType","_urlencodedContentType","req","Request","originalBody","isObjectObject","o","isObject","ctor","prot","constructor","Array","isArray","_events","_maxListeners","isFunction","arg","isNumber","isUndefined","defaultMaxListeners","setMaxListeners","isNaN","type","er","handler","len","args","listeners","err","context","slice","apply","addListener","listener","newListener","push","warned","console","trace","on","once","g","removeListener","fired","list","position","splice","removeAllListeners","ret","listenerCount","evlistener","emitter","_request","_response","_text","responseText","_json","_multipart","_multipartContentType","_headerSeparator","_bodySeparator","_boundarySeparator","_unauthorizedStatus","_isMultipart","_isJson","text","json","skipOKCheck","status","statusText","error_description","description","toMultipart","multipart","boundary","_getContentType","match","parts","trim","shift","pop","statusInfo","_create","part","_isContentType","get","replace","Headers","headersAndBody","headersText","header","value","append","Response","decode","encode","obj","prop","sep","eq","regexp","maxKeys","kstr","vstr","k","v","x","idx","substr","decodeURIComponent","stringifyPrimitive","isFinite","ks","encodeURIComponent","global","PUBNUB","pubnub","es6Promise","fetchPonyfill","FetchPonyfill","beforeLogin","loginSuccess","loginError","beforeRefresh","refreshSuccess","refreshError","beforeLogout","logoutSuccess","logoutError","_server","_appKey","appKey","_appSecret","appSecret","_redirectUri","redirectUri","_refreshDelayMs","refreshDelayMs","_clearCacheOnRefreshError","clearCacheOnRefreshError","_userAgent","appName","appVersion","_refreshPromise","_auth","Auth","cacheId","_cacheId","refreshHandicapMs","_urlPrefix","_apiVersion","_tokenEndpoint","_revokeEndpoint","_authorizeEndpoint","delay","timeout","reject","setTimeout","auth","createUrl","path","builtUrl","hasHttp","addServer","addMethod","addToken","accessToken","loginUrl","response_type","implicit","redirect_uri","client_id","state","brand_id","brandId","display","prompt","parseLoginRedirect","getParts","separator","reverse","queryString","loginWindow","width","height","property","dualScreenLeft","screenLeft","screen","left","dualScreenTop","screenTop","top","innerWidth","document","documentElement","clientWidth","innerHeight","clientHeight","win","open","focus","eventMethod","addEventListener","eventRemoveMethod","messageEvent","eventListener","close","loginOptions","code","access_token","loggedIn","ensureLoggedIn","login","grant_type","username","password","extension","endpointId","endpoint_id","accessTokenTtl","refreshTokenTtl","_tokenRequest","setData","_refresh","refreshToken","refreshTokenValid","refresh_token","access_token_ttl","expires_in","refresh_token_ttl","refresh_token_expires_in","refresh","logout","token","inflateRequest","skipAuthCheck","set","_authHeader","retry","cancelAccessToken","send","post","put","_isAccessTokenValid","Authorization","_apiKey","Content-Type","accessTokenValid","apiKey","btoa","Buffer","tokenType","_refreshHandicapMs","token_type","newData","expire_time","Date","now","refresh_token_expire_time","authData","notification","removeSuccess","removeError","renewSuccess","renewError","subscribeSuccess","subscribeError","_pollInterval","pollInterval","_renewHandicapMs","renewHandicapMs","_pubnub","_pubnubLastChannel","_timeout","_subscription","subscribed","subscription","deliveryMode","subscriberKey","address","alive","expirationTime","expired","getTime","setSubscription","_clearTimeout","_setSubscription","_subscribeAtPubnub","_setTimeout","register","renew","subscribe","eventFilters","addEventFilters","setEventFilters","concat","_getFullEventFilters","transportType","reset","remove","resubscribe","filters","unsubscribe","channel","event","setInterval","clearInterval","_decrypt","encryptionKey","crypto_obj","decrypt","encryptKey","keyEncoding","keyLength","_notify","ssl","subscribe_key","ready","connect","_cacheKey","restore"],"mappings":"CAAA,SAAAA,EAAAC,GACA,gBAAAC,UAAA,gBAAAC,QACAA,OAAAD,QAAAD,EAAAG,QAAAC,QAAAD,QAAAC,QAAAD,QAAAC,SACA,kBAAAC,gBAAAC,IACA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,qBAItCta,KAAAqa,QAAAra,KAAAqa,QAAA5R,MACAwU,KAAA,EACAC,cAAAvC,EAAAC,oBAMA5a,MAAAqa,QAAAra,KAAAgB,WAAAwP,OAAA/H,MACAwU,KAAA,EACAC,cAAAvC,EAAAC,gBAGA5a,KAAAqa,QAAA8C,OAYA,OARAnd,MAAAsa,mBAAAK,EAAAE,QAEA7a,KAAAqa,QAAAoB,WACAY,QAAA1B,EAAAE,QACAvS,QAAAtI,KAAAgd,QAAAlV,KAAA9H,MACAod,QAAA,eAGApd,MAIAL,EAAAD,QAAAoC,GpB4sEM,SAASnC,EAAQD,EAASW,GqB/lFhC,QAAA0B,GAAAhB,GAIA,GAFAA,SAEAA,EAAA2B,SAAA,SAAAwF,OAAA,gEAGAlI,MAAAqd,UAAAtc,EAAA2B,SAEAZ,EAAApB,KAAAV,KAAAe,GAGAf,KAAAkB,OAAAH,EAAAc,MAGA7B,KAAAwa,cAAA3a,OA7BA,GAAAiC,GAAAzB,EAAA,GAiCA0B,GAAAM,UAAAqB,OAAA4D,OAAAxF,EAAAO,WAEAN,EAAAM,UAAAqY,aAAA,WACA,MAAA1a,MAAAkB,OAAAgF,QAAAlG,KAAAqd,gBAGAtb,EAAAM,UAAA+Y,iBAAA,SAAAV,GACA,MAAA1a,MAAAkB,OAAAyE,QAAA3F,KAAAqd,UAAA3C,IAQA3Y,EAAAM,UAAAib,QAAA,SAAAxW,GAMA,MAJA9G,MAAA0b,eAAApW,QACAtF,KAAA4b,gBAAA9U,GAGA9G,MAIAL,EAAAD,QAAAqC","file":"ringcentral.min.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory(require(undefined), require(undefined), require(undefined));\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([\"pubnub\", \"es6-promise\", \"fetch-ponyfill\"], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"SDK\"] = factory(require(undefined), require(undefined), require(undefined));\n\telse\n\t\troot[\"RingCentral\"] = root[\"RingCentral\"] || {}, root[\"RingCentral\"][\"SDK\"] = factory(root[undefined], root[undefined], root[undefined]);\n})(this, function(__WEBPACK_EXTERNAL_MODULE_12__, __WEBPACK_EXTERNAL_MODULE_13__, __WEBPACK_EXTERNAL_MODULE_14__) {\nreturn \n\n\n/** WEBPACK FOOTER **\n ** webpack/universalModuleDefinition\n **/","(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory(require(undefined), require(undefined), require(undefined));\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([\"pubnub\", \"es6-promise\", \"fetch-ponyfill\"], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"SDK\"] = factory(require(undefined), require(undefined), require(undefined));\n\telse\n\t\troot[\"RingCentral\"] = root[\"RingCentral\"] || {}, root[\"RingCentral\"][\"SDK\"] = factory(root[undefined], root[undefined], root[undefined]);\n})(this, function(__WEBPACK_EXTERNAL_MODULE_12__, __WEBPACK_EXTERNAL_MODULE_13__, __WEBPACK_EXTERNAL_MODULE_14__) {\nreturn /******/ (function(modules) { // webpackBootstrap\n/******/ \t// The module cache\n/******/ \tvar installedModules = {};\n/******/\n/******/ \t// The require function\n/******/ \tfunction __webpack_require__(moduleId) {\n/******/\n/******/ \t\t// Check if module is in cache\n/******/ \t\tif(installedModules[moduleId])\n/******/ \t\t\treturn installedModules[moduleId].exports;\n/******/\n/******/ \t\t// Create a new module (and put it into the cache)\n/******/ \t\tvar module = installedModules[moduleId] = {\n/******/ \t\t\texports: {},\n/******/ \t\t\tid: moduleId,\n/******/ \t\t\tloaded: false\n/******/ \t\t};\n/******/\n/******/ \t\t// Execute the module function\n/******/ \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n/******/\n/******/ \t\t// Flag the module as loaded\n/******/ \t\tmodule.loaded = true;\n/******/\n/******/ \t\t// Return the exports of the module\n/******/ \t\treturn module.exports;\n/******/ \t}\n/******/\n/******/\n/******/ \t// expose the modules object (__webpack_modules__)\n/******/ \t__webpack_require__.m = modules;\n/******/\n/******/ \t// expose the module cache\n/******/ \t__webpack_require__.c = installedModules;\n/******/\n/******/ \t// __webpack_public_path__\n/******/ \t__webpack_require__.p = \"/build/\";\n/******/\n/******/ \t// Load entry module and return exports\n/******/ \treturn __webpack_require__(0);\n/******/ })\n/************************************************************************/\n/******/ ([\n/* 0 */\n/***/ function(module, exports, __webpack_require__) {\n\n/**\n * @namespace RingCentral\n */\nvar objectAssign = __webpack_require__(1);\nvar Cache = __webpack_require__(2);\nvar Client = __webpack_require__(3);\nvar Externals = __webpack_require__(11);\nvar Platform = __webpack_require__(15);\nvar Subscription = __webpack_require__(18);\nvar CachedSubscription = __webpack_require__(19);\nvar Constants = __webpack_require__(17);\n\n/**\n * @constructor\n * @param {string} options.server\n * @param {string} options.appSecret\n * @param {string} options.appKey\n * @param {string} [options.cachePrefix]\n * @param {string} [options.appName]\n * @param {string} [options.appVersion]\n * @param {string} [options.redirectUri]\n * @param {PUBNUB} [options.PUBNUB]\n * @param {function(new:Promise)} [options.Promise]\n * @param {Storage} [options.localStorage]\n * @param {fetch} [options.fetch]\n * @param {function(new:Request)} [options.Request]\n * @param {function(new:Response)} [options.Response]\n * @param {function(new:Headers)} [options.Headers]\n * @param {int} [options.refreshDelayMs]\n * @param {int} [options.refreshHandicapMs]\n * @param {boolean} [options.clearCacheOnRefreshError]\n * @property {Externals} _externals\n * @property {Cache} _cache\n * @property {Client} _client\n * @property {Platform} _platform\n */\nfunction SDK(options) {\n\n /** @private */\n this._externals = new Externals(options);\n\n /** @private */\n this._cache = new Cache({\n externals: this._externals,\n prefix: options.cachePrefix\n });\n\n /** @private */\n this._client = new Client(this._externals);\n\n /** @private */\n this._platform = new Platform(objectAssign({}, options, {\n externals: this._externals,\n client: this._client,\n cache: this._cache\n }));\n\n}\n\nSDK.version = Constants.version;\n\nSDK.server = {\n sandbox: 'https://platform.devtest.ringcentral.com',\n production: 'https://platform.ringcentral.com'\n};\n\n/**\n * @return {Platform}\n */\nSDK.prototype.platform = function() {\n return this._platform;\n};\n\n/**\n * @return {Cache}\n */\nSDK.prototype.cache = function() {\n return this._cache;\n};\n\n/**\n * @param {int} [options.pollInterval]\n * @param {int} [options.renewHandicapMs]\n * @return {Subscription}\n */\nSDK.prototype.createSubscription = function(options) {\n return new Subscription(objectAssign({}, options, {\n externals: this._externals,\n platform: this._platform\n }));\n};\n\n/**\n * @param {string} options.cacheKey\n * @param {int} [options.pollInterval]\n * @param {int} [options.renewHandicapMs]\n * @return {CachedSubscription}\n */\nSDK.prototype.createCachedSubscription = function(options) {\n\n if (typeof arguments[0] == 'string') {\n options = {cacheKey: arguments[0].toString()};\n } else {\n options = options || {};\n }\n\n return new CachedSubscription(objectAssign({}, options, {\n externals: this._externals,\n platform: this._platform,\n cache: this._cache\n }));\n\n};\n\nSDK.handleLoginRedirect = function(origin) {\n\n var response = window.location.hash ? window.location.hash : window.location.search;\n var msg = {};\n msg[Constants.authResponseProperty] = response;\n window.opener.postMessage(msg, origin || window.location.origin);\n\n};\n\nmodule.exports = SDK;\n\n/***/ },\n/* 1 */\n/***/ function(module, exports) {\n\n'use strict';\n/* eslint-disable no-unused-vars */\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\nvar propIsEnumerable = Object.prototype.propertyIsEnumerable;\n\nfunction toObject(val) {\n\tif (val === null || val === undefined) {\n\t\tthrow new TypeError('Object.assign cannot be called with null or undefined');\n\t}\n\n\treturn Object(val);\n}\n\nfunction shouldUseNative() {\n\ttry {\n\t\tif (!Object.assign) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// Detect buggy property enumeration order in older V8 versions.\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=4118\n\t\tvar test1 = new String('abc'); // eslint-disable-line\n\t\ttest1[5] = 'de';\n\t\tif (Object.getOwnPropertyNames(test1)[0] === '5') {\n\t\t\treturn false;\n\t\t}\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=3056\n\t\tvar test2 = {};\n\t\tfor (var i = 0; i < 10; i++) {\n\t\t\ttest2['_' + String.fromCharCode(i)] = i;\n\t\t}\n\t\tvar order2 = Object.getOwnPropertyNames(test2).map(function (n) {\n\t\t\treturn test2[n];\n\t\t});\n\t\tif (order2.join('') !== '0123456789') {\n\t\t\treturn false;\n\t\t}\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=3056\n\t\tvar test3 = {};\n\t\t'abcdefghijklmnopqrst'.split('').forEach(function (letter) {\n\t\t\ttest3[letter] = letter;\n\t\t});\n\t\tif (Object.keys(Object.assign({}, test3)).join('') !==\n\t\t\t\t'abcdefghijklmnopqrst') {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t} catch (e) {\n\t\t// We don't expect any of the above to throw, but better to be safe.\n\t\treturn false;\n\t}\n}\n\nmodule.exports = shouldUseNative() ? Object.assign : function (target, source) {\n\tvar from;\n\tvar to = toObject(target);\n\tvar symbols;\n\n\tfor (var s = 1; s < arguments.length; s++) {\n\t\tfrom = Object(arguments[s]);\n\n\t\tfor (var key in from) {\n\t\t\tif (hasOwnProperty.call(from, key)) {\n\t\t\t\tto[key] = from[key];\n\t\t\t}\n\t\t}\n\n\t\tif (Object.getOwnPropertySymbols) {\n\t\t\tsymbols = Object.getOwnPropertySymbols(from);\n\t\t\tfor (var i = 0; i < symbols.length; i++) {\n\t\t\t\tif (propIsEnumerable.call(from, symbols[i])) {\n\t\t\t\t\tto[symbols[i]] = from[symbols[i]];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn to;\n};\n\n\n/***/ },\n/* 2 */\n/***/ function(module, exports) {\n\n/**\n * @param {Externals} options.externals\n * @param {string} [options.prefix]\n * @property {Externals} _externals\n */\nfunction Cache(options) {\n\n /** @private */\n this._prefix = options.prefix || Cache.defaultPrefix;\n\n /** @private */\n this._externals = options.externals;\n\n}\n\nCache.defaultPrefix = 'rc-';\n\nCache.prototype.setItem = function(key, data) {\n this._externals.localStorage[this._prefixKey(key)] = JSON.stringify(data);\n return this;\n};\n\nCache.prototype.removeItem = function(key) {\n delete this._externals.localStorage[this._prefixKey(key)];\n return this;\n};\n\nCache.prototype.getItem = function(key) {\n var item = this._externals.localStorage[this._prefixKey(key)];\n if (!item) return null;\n return JSON.parse(item);\n};\n\nCache.prototype.clean = function() {\n\n for (var key in this._externals.localStorage) {\n\n if (!this._externals.localStorage.hasOwnProperty(key)) continue;\n\n if (key.indexOf(this._prefix) === 0) {\n delete this._externals.localStorage[key];\n }\n\n }\n\n return this;\n\n};\n\nCache.prototype._prefixKey = function(key) {\n return this._prefix + key;\n};\n\nmodule.exports = Cache;\n\n/***/ },\n/* 3 */\n/***/ function(module, exports, __webpack_require__) {\n\nvar isPlainObject = __webpack_require__(4);\nvar EventEmitter = __webpack_require__(6).EventEmitter;\nvar ApiResponse = __webpack_require__(7);\nvar qs = __webpack_require__(8);\n\nfunction findHeaderName(name, headers) {\n name = name.toLowerCase();\n return Object.keys(headers).reduce(function(res, key) {\n if (res) return res;\n if (name == key.toLowerCase()) return key;\n return res;\n }, null);\n}\n\n/**\n * @param {Externals} externals\n * @property {Externals} _externals\n */\nfunction Client(externals) {\n\n EventEmitter.call(this);\n\n /** @private */\n this._externals = externals;\n\n this.events = {\n beforeRequest: 'beforeRequest',\n requestSuccess: 'requestSuccess',\n requestError: 'requestError'\n };\n\n}\n\nClient._allowedMethods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS', 'HEAD'];\n\nClient.prototype = Object.create(EventEmitter.prototype);\n\n/**\n * @param {Request} request\n * @return {Promise}\n */\nClient.prototype.sendRequest = function(request) {\n\n var apiResponse = new ApiResponse({\n externals: this._externals,\n request: request\n });\n\n return (new this._externals.Promise(function(resolve) {\n\n //TODO Stop request if listeners return false\n this.emit(this.events.beforeRequest, apiResponse);\n\n resolve(this._loadResponse(request));\n\n }.bind(this))).then(function(response) {\n\n return apiResponse.receiveResponse(response);\n\n }).then(function() {\n\n if (!apiResponse.ok()) throw new Error('Response has unsuccessful status');\n\n this.emit(this.events.requestSuccess, apiResponse);\n\n return apiResponse;\n\n }.bind(this)).catch(function(e) {\n\n if (!e.apiResponse) e = this.makeError(e, apiResponse);\n\n this.emit(this.events.requestError, e);\n\n throw e;\n\n }.bind(this));\n\n};\n\n/**\n * @param {Request} request\n * @return {Promise}\n * @private\n */\nClient.prototype._loadResponse = function(request) {\n return this._externals.fetch.call(null, request);\n};\n\n/**\n * Wraps the JS Error object with transaction information\n * @param {Error|IApiError} e\n * @param {ApiResponse} apiResponse\n * @return {IApiError}\n */\nClient.prototype.makeError = function(e, apiResponse) {\n\n // Wrap only if regular error\n if (!e.hasOwnProperty('apiResponse') && !e.hasOwnProperty('originalMessage')) {\n\n e.apiResponse = apiResponse;\n e.originalMessage = e.message;\n e.message = (apiResponse && apiResponse.error(true)) || e.originalMessage;\n\n }\n\n return e;\n\n};\n\n/**\n *\n * @param {object} init\n * @param {object} [init.url]\n * @param {object} [init.body]\n * @param {string} [init.method]\n * @param {object} [init.query]\n * @param {object} [init.headers]\n * @param {object} [init.credentials]\n * @param {object} [init.mode]\n * @return {Request}\n */\nClient.prototype.createRequest = function(init) {\n\n init = init || {};\n init.headers = init.headers || {};\n\n // Sanity checks\n if (!init.url) throw new Error('Url is not defined');\n if (!init.method) init.method = 'GET';\n init.method = init.method.toUpperCase();\n if (init.method && Client._allowedMethods.indexOf(init.method) < 0) {\n throw new Error('Method has wrong value: ' + init.method);\n }\n\n // Defaults\n init.credentials = init.credentials || 'include';\n init.mode = init.mode || 'cors';\n\n // Append Query String\n if (init.query) {\n init.url = init.url + (init.url.indexOf('?') > -1 ? '&' : '?') + qs.stringify(init.query);\n }\n\n if (!(findHeaderName('Accept', init.headers))) {\n init.headers.Accept = ApiResponse._jsonContentType;\n }\n\n // Serialize body\n if (isPlainObject(init.body) || !init.body) {\n\n var contentTypeHeaderName = findHeaderName(ApiResponse._contentType, init.headers);\n\n if (!contentTypeHeaderName) {\n contentTypeHeaderName = ApiResponse._contentType;\n init.headers[contentTypeHeaderName] = ApiResponse._jsonContentType;\n }\n\n var contentType = init.headers[contentTypeHeaderName];\n\n // Assign a new encoded body\n if (contentType.indexOf(ApiResponse._jsonContentType) > -1) {\n if ((init.method === 'GET' || init.method === 'HEAD') && !!init.body) {\n // oddly setting body to null still result in TypeError in phantomjs\n init.body = undefined;\n } else {\n init.body = JSON.stringify(init.body);\n }\n\n } else if (contentType.indexOf(ApiResponse._urlencodedContentType) > -1) {\n init.body = qs.stringify(init.body);\n }\n\n }\n\n // Create a request with encoded body\n var req = new this._externals.Request(init.url, init);\n\n // Keep the original body accessible directly (for mocks)\n req.originalBody = init.body;\n\n return req;\n\n};\n\n/**\n * @typedef {object} IApiError\n * @property {string} stack\n * @property {string} originalMessage\n * @property {ApiResponse} apiResponse\n */\n\nmodule.exports = Client;\n\n/***/ },\n/* 4 */\n/***/ function(module, exports, __webpack_require__) {\n\n/*!\n * is-plain-object \n *\n * Copyright (c) 2014-2015, Jon Schlinkert.\n * Licensed under the MIT License.\n */\n\n'use strict';\n\nvar isObject = __webpack_require__(5);\n\nfunction isObjectObject(o) {\n return isObject(o) === true\n && Object.prototype.toString.call(o) === '[object Object]';\n}\n\nmodule.exports = function isPlainObject(o) {\n var ctor,prot;\n \n if (isObjectObject(o) === false) return false;\n \n // If has modified constructor\n ctor = o.constructor;\n if (typeof ctor !== 'function') return false;\n \n // If has modified prototype\n prot = ctor.prototype;\n if (isObjectObject(prot) === false) return false;\n \n // If constructor does not have an Object-specific method\n if (prot.hasOwnProperty('isPrototypeOf') === false) {\n return false;\n }\n \n // Most likely a plain Object\n return true;\n};\n\n\n/***/ },\n/* 5 */\n/***/ function(module, exports) {\n\n/*!\n * isobject \n *\n * Copyright (c) 2014-2015, Jon Schlinkert.\n * Licensed under the MIT License.\n */\n\n'use strict';\n\nmodule.exports = function isObject(val) {\n return val != null && typeof val === 'object'\n && !Array.isArray(val);\n};\n\n\n/***/ },\n/* 6 */\n/***/ function(module, exports) {\n\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nfunction EventEmitter() {\n this._events = this._events || {};\n this._maxListeners = this._maxListeners || undefined;\n}\nmodule.exports = EventEmitter;\n\n// Backwards-compat with node 0.10.x\nEventEmitter.EventEmitter = EventEmitter;\n\nEventEmitter.prototype._events = undefined;\nEventEmitter.prototype._maxListeners = undefined;\n\n// By default EventEmitters will print a warning if more than 10 listeners are\n// added to it. This is a useful default which helps finding memory leaks.\nEventEmitter.defaultMaxListeners = 10;\n\n// Obviously not all Emitters should be limited to 10. This function allows\n// that to be increased. Set to zero for unlimited.\nEventEmitter.prototype.setMaxListeners = function(n) {\n if (!isNumber(n) || n < 0 || isNaN(n))\n throw TypeError('n must be a positive number');\n this._maxListeners = n;\n return this;\n};\n\nEventEmitter.prototype.emit = function(type) {\n var er, handler, len, args, i, listeners;\n\n if (!this._events)\n this._events = {};\n\n // If there is no 'error' event listener then throw.\n if (type === 'error') {\n if (!this._events.error ||\n (isObject(this._events.error) && !this._events.error.length)) {\n er = arguments[1];\n if (er instanceof Error) {\n throw er; // Unhandled 'error' event\n } else {\n // At least give some kind of context to the user\n var err = new Error('Uncaught, unspecified \"error\" event. (' + er + ')');\n err.context = er;\n throw err;\n }\n }\n }\n\n handler = this._events[type];\n\n if (isUndefined(handler))\n return false;\n\n if (isFunction(handler)) {\n switch (arguments.length) {\n // fast cases\n case 1:\n handler.call(this);\n break;\n case 2:\n handler.call(this, arguments[1]);\n break;\n case 3:\n handler.call(this, arguments[1], arguments[2]);\n break;\n // slower\n default:\n args = Array.prototype.slice.call(arguments, 1);\n handler.apply(this, args);\n }\n } else if (isObject(handler)) {\n args = Array.prototype.slice.call(arguments, 1);\n listeners = handler.slice();\n len = listeners.length;\n for (i = 0; i < len; i++)\n listeners[i].apply(this, args);\n }\n\n return true;\n};\n\nEventEmitter.prototype.addListener = function(type, listener) {\n var m;\n\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n if (!this._events)\n this._events = {};\n\n // To avoid recursion in the case that type === \"newListener\"! Before\n // adding it to the listeners, first emit \"newListener\".\n if (this._events.newListener)\n this.emit('newListener', type,\n isFunction(listener.listener) ?\n listener.listener : listener);\n\n if (!this._events[type])\n // Optimize the case of one listener. Don't need the extra array object.\n this._events[type] = listener;\n else if (isObject(this._events[type]))\n // If we've already got an array, just append.\n this._events[type].push(listener);\n else\n // Adding the second element, need to change to array.\n this._events[type] = [this._events[type], listener];\n\n // Check for listener leak\n if (isObject(this._events[type]) && !this._events[type].warned) {\n if (!isUndefined(this._maxListeners)) {\n m = this._maxListeners;\n } else {\n m = EventEmitter.defaultMaxListeners;\n }\n\n if (m && m > 0 && this._events[type].length > m) {\n this._events[type].warned = true;\n console.error('(node) warning: possible EventEmitter memory ' +\n 'leak detected. %d listeners added. ' +\n 'Use emitter.setMaxListeners() to increase limit.',\n this._events[type].length);\n if (typeof console.trace === 'function') {\n // not supported in IE 10\n console.trace();\n }\n }\n }\n\n return this;\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.once = function(type, listener) {\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n var fired = false;\n\n function g() {\n this.removeListener(type, g);\n\n if (!fired) {\n fired = true;\n listener.apply(this, arguments);\n }\n }\n\n g.listener = listener;\n this.on(type, g);\n\n return this;\n};\n\n// emits a 'removeListener' event iff the listener was removed\nEventEmitter.prototype.removeListener = function(type, listener) {\n var list, position, length, i;\n\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n if (!this._events || !this._events[type])\n return this;\n\n list = this._events[type];\n length = list.length;\n position = -1;\n\n if (list === listener ||\n (isFunction(list.listener) && list.listener === listener)) {\n delete this._events[type];\n if (this._events.removeListener)\n this.emit('removeListener', type, listener);\n\n } else if (isObject(list)) {\n for (i = length; i-- > 0;) {\n if (list[i] === listener ||\n (list[i].listener && list[i].listener === listener)) {\n position = i;\n break;\n }\n }\n\n if (position < 0)\n return this;\n\n if (list.length === 1) {\n list.length = 0;\n delete this._events[type];\n } else {\n list.splice(position, 1);\n }\n\n if (this._events.removeListener)\n this.emit('removeListener', type, listener);\n }\n\n return this;\n};\n\nEventEmitter.prototype.removeAllListeners = function(type) {\n var key, listeners;\n\n if (!this._events)\n return this;\n\n // not listening for removeListener, no need to emit\n if (!this._events.removeListener) {\n if (arguments.length === 0)\n this._events = {};\n else if (this._events[type])\n delete this._events[type];\n return this;\n }\n\n // emit removeListener for all listeners on all events\n if (arguments.length === 0) {\n for (key in this._events) {\n if (key === 'removeListener') continue;\n this.removeAllListeners(key);\n }\n this.removeAllListeners('removeListener');\n this._events = {};\n return this;\n }\n\n listeners = this._events[type];\n\n if (isFunction(listeners)) {\n this.removeListener(type, listeners);\n } else if (listeners) {\n // LIFO order\n while (listeners.length)\n this.removeListener(type, listeners[listeners.length - 1]);\n }\n delete this._events[type];\n\n return this;\n};\n\nEventEmitter.prototype.listeners = function(type) {\n var ret;\n if (!this._events || !this._events[type])\n ret = [];\n else if (isFunction(this._events[type]))\n ret = [this._events[type]];\n else\n ret = this._events[type].slice();\n return ret;\n};\n\nEventEmitter.prototype.listenerCount = function(type) {\n if (this._events) {\n var evlistener = this._events[type];\n\n if (isFunction(evlistener))\n return 1;\n else if (evlistener)\n return evlistener.length;\n }\n return 0;\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n return emitter.listenerCount(type);\n};\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\n\n\n/***/ },\n/* 7 */\n/***/ function(module, exports) {\n\n/**\n * @param {Externals} options.externals\n * @param {Request} [options.request]\n * @param {Response} [options.response]\n * @param {string} [options.responseText]\n * @property {Externals} _externals\n * @property {Request} _request\n * @property {Response} _response\n * @property {string} _text\n * @property {object} _json\n * @property {ApiResponse[]} _multipart\n */\nfunction ApiResponse(options) {\n\n /** @private */\n this._externals = options.externals;\n\n /** @private */\n this._request = options.request;\n\n /** @private */\n this._response = options.response;\n\n /** @private */\n this._text = options.responseText || '';\n\n /** @private */\n this._json = null;\n\n /** @private */\n this._multipart = [];\n\n}\n\nApiResponse._contentType = 'Content-Type';\nApiResponse._jsonContentType = 'application/json';\nApiResponse._multipartContentType = 'multipart/mixed';\nApiResponse._urlencodedContentType = 'application/x-www-form-urlencoded';\nApiResponse._headerSeparator = ':';\nApiResponse._bodySeparator = '\\n\\n';\nApiResponse._boundarySeparator = '--';\nApiResponse._unauthorizedStatus = 401;\n\n/**\n * @param {Response} response\n * @return {Promise}\n */\nApiResponse.prototype.receiveResponse = function(response) {\n\n this._response = response;\n\n return (new this._externals.Promise(function(resolve) {\n\n // Ignore if not textual type\n if (!this._isMultipart() && !this._isJson()) return resolve('');\n\n return resolve(this.response().text());\n\n }.bind(this))).then(function(text) {\n\n this._text = text;\n return text;\n\n }.bind(this));\n\n};\n\n/**\n * @return {Response}\n */\nApiResponse.prototype.response = function() {\n return this._response;\n};\n\n/**\n * @return {Request}\n */\nApiResponse.prototype.request = function() {\n return this._request;\n};\n\n/**\n * @return {boolean}\n */\nApiResponse.prototype.ok = function() {\n return this._response && this._response.ok;\n};\n\n/**\n * @return {string}\n */\nApiResponse.prototype.text = function() {\n // Since we read text only in case JSON or Multipart\n if (!this._isJson() && !this._isMultipart()) throw new Error('Response is not text');\n return this._text;\n};\n\n/**\n * @return {object}\n */\nApiResponse.prototype.json = function() {\n if (!this._isJson()) throw new Error('Response is not JSON');\n if (!this._json) {\n this._json = this._text ? JSON.parse(this._text) : null;\n }\n return this._json;\n};\n\n/**\n * @param [skipOKCheck]\n * @return {string}\n */\nApiResponse.prototype.error = function(skipOKCheck) {\n\n if (this.ok() && !skipOKCheck) return null;\n\n var message = (this._response && this._response.status ? this._response.status + ' ' : '') +\n (this._response && this._response.statusText ? this._response.statusText : '');\n\n try {\n\n if (this.json().message) message = this.json().message;\n if (this.json().error_description) message = this.json().error_description;\n if (this.json().description) message = this.json().description;\n\n } catch (e) {}\n\n return message;\n\n};\n\n/**\n * If it is not known upfront what would be the response, client code can treat any response as multipart\n * @return {ApiResponse[]}\n */\nApiResponse.prototype.toMultipart = function() {\n if (!this._isMultipart()) return [this];\n return this.multipart();\n};\n\n/**\n * @return {ApiResponse[]}\n */\nApiResponse.prototype.multipart = function() {\n\n if (!this._isMultipart()) throw new Error('Response is not multipart');\n\n if (!this._multipart.length) {\n\n // Step 1. Split multipart response\n\n var text = this.text();\n\n if (!text) throw new Error('No response body');\n\n var boundary = this._getContentType().match(/boundary=([^;]+)/i)[1];\n\n if (!boundary) throw new Error('Cannot find boundary');\n\n var parts = text.toString().split(ApiResponse._boundarySeparator + boundary);\n\n if (parts[0].trim() === '') parts.shift();\n if (parts[parts.length - 1].trim() == ApiResponse._boundarySeparator) parts.pop();\n\n if (parts.length < 1) throw new Error('No parts in body');\n\n // Step 2. Parse status info\n\n var statusInfo = this._create(parts.shift(), this._response.status, this._response.statusText).json();\n\n // Step 3. Parse all other parts\n\n this._multipart = parts.map(function(part, i) {\n\n var status = statusInfo.response[i].status;\n\n return this._create(part, status);\n\n }.bind(this));\n\n }\n\n return this._multipart;\n\n};\n\n/**\n * @private\n */\nApiResponse.prototype._isContentType = function(contentType) {\n return this._getContentType().indexOf(contentType) > -1;\n};\n\n/**\n * @private\n */\nApiResponse.prototype._getContentType = function() {\n return this._response.headers.get(ApiResponse._contentType) || '';\n};\n\n/**\n * @private\n */\nApiResponse.prototype._isMultipart = function() {\n return this._isContentType(ApiResponse._multipartContentType);\n};\n\n/**\n * @private\n */\nApiResponse.prototype._isJson = function() {\n return this._isContentType(ApiResponse._jsonContentType);\n};\n\n/**\n * Method is used to create ApiResponse object from string parts of multipart/mixed response\n * @param {string} [text]\n * @param {number} [status]\n * @param {string} [statusText]\n * @private\n * @return {ApiResponse}\n */\nApiResponse.prototype._create = function(text, status, statusText) {\n\n text = text || '';\n status = status || 200;\n statusText = statusText || 'OK';\n\n text = text.replace(/\\r/g, '');\n\n var headers = new this._externals.Headers(),\n headersAndBody = text.split(ApiResponse._bodySeparator),\n headersText = (headersAndBody.length > 1) ? headersAndBody.shift() : '';\n\n text = headersAndBody.length > 0 ? headersAndBody.join(ApiResponse._bodySeparator) : null;\n\n (headersText || '')\n .split('\\n')\n .forEach(function(header) {\n\n var split = header.trim().split(ApiResponse._headerSeparator),\n key = split.shift().trim(),\n value = split.join(ApiResponse._headerSeparator).trim();\n\n if (key) headers.append(key, value);\n\n });\n\n var response = new this._externals.Response(text, {\n headers: headers,\n status: status,\n statusText: statusText\n });\n\n return new ApiResponse({\n externals: this._externals,\n request: null,\n response: response,\n responseText: text\n });\n\n};\n\nmodule.exports = ApiResponse;\n\n/***/ },\n/* 8 */\n/***/ function(module, exports, __webpack_require__) {\n\n'use strict';\n\nexports.decode = exports.parse = __webpack_require__(9);\nexports.encode = exports.stringify = __webpack_require__(10);\n\n\n/***/ },\n/* 9 */\n/***/ function(module, exports) {\n\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n// If obj.hasOwnProperty has been overridden, then calling\n// obj.hasOwnProperty(prop) will break.\n// See: https://github.com/joyent/node/issues/1707\nfunction hasOwnProperty(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n\nmodule.exports = function(qs, sep, eq, options) {\n sep = sep || '&';\n eq = eq || '=';\n var obj = {};\n\n if (typeof qs !== 'string' || qs.length === 0) {\n return obj;\n }\n\n var regexp = /\\+/g;\n qs = qs.split(sep);\n\n var maxKeys = 1000;\n if (options && typeof options.maxKeys === 'number') {\n maxKeys = options.maxKeys;\n }\n\n var len = qs.length;\n // maxKeys <= 0 means that we should not limit keys count\n if (maxKeys > 0 && len > maxKeys) {\n len = maxKeys;\n }\n\n for (var i = 0; i < len; ++i) {\n var x = qs[i].replace(regexp, '%20'),\n idx = x.indexOf(eq),\n kstr, vstr, k, v;\n\n if (idx >= 0) {\n kstr = x.substr(0, idx);\n vstr = x.substr(idx + 1);\n } else {\n kstr = x;\n vstr = '';\n }\n\n k = decodeURIComponent(kstr);\n v = decodeURIComponent(vstr);\n\n if (!hasOwnProperty(obj, k)) {\n obj[k] = v;\n } else if (Array.isArray(obj[k])) {\n obj[k].push(v);\n } else {\n obj[k] = [obj[k], v];\n }\n }\n\n return obj;\n};\n\n\n/***/ },\n/* 10 */\n/***/ function(module, exports) {\n\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nvar stringifyPrimitive = function(v) {\n switch (typeof v) {\n case 'string':\n return v;\n\n case 'boolean':\n return v ? 'true' : 'false';\n\n case 'number':\n return isFinite(v) ? v : '';\n\n default:\n return '';\n }\n};\n\nmodule.exports = function(obj, sep, eq, name) {\n sep = sep || '&';\n eq = eq || '=';\n if (obj === null) {\n obj = undefined;\n }\n\n if (typeof obj === 'object') {\n return Object.keys(obj).map(function(k) {\n var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;\n if (Array.isArray(obj[k])) {\n return obj[k].map(function(v) {\n return ks + encodeURIComponent(stringifyPrimitive(v));\n }).join(sep);\n } else {\n return ks + encodeURIComponent(stringifyPrimitive(obj[k]));\n }\n }).join(sep);\n\n }\n\n if (!name) return '';\n return encodeURIComponent(stringifyPrimitive(name)) + eq +\n encodeURIComponent(stringifyPrimitive(obj));\n};\n\n\n/***/ },\n/* 11 */\n/***/ function(module, exports, __webpack_require__) {\n\n/* WEBPACK VAR INJECTION */(function(global) {var pubnub = __webpack_require__(12);\nvar es6Promise = __webpack_require__(13);\nvar FetchPonyfill = __webpack_require__(14);\n\nvar root = (typeof window !== \"undefined\" && window) ||\n (typeof global !== \"undefined\" && global) ||\n (function(){ return this; })();\n\n/**\n * @constructor\n * @param {PUBNUB} [options.PUBNUB]\n * @param {function(new:Promise)} [options.Promise]\n * @param {Storage} [options.localStorage]\n * @param {fetch} [options.fetch]\n * @param {function(new:Request)} [options.Request]\n * @param {function(new:Response)} [options.Response]\n * @param {function(new:Headers)} [options.Headers]\n * @property {PUBNUB} PUBNUB\n * @property {Storage} localStorage\n * @property {function(new:Promise)} Promise\n * @property {fetch} fetch\n * @property {function(new:Request)} Request\n * @property {function(new:Response)} Response\n * @property {function(new:Headers)} Headers\n */\nfunction Externals(options) {\n\n options = options || {};\n\n this.PUBNUB = options.PUBNUB || root.PUBNUB || pubnub;\n this.localStorage = options.localStorage || ((typeof root.localStorage !== 'undefined') ? root.localStorage : {});\n this.Promise = options.Promise || root.Promise || (es6Promise && es6Promise.Promise);\n\n var fetchPonyfill = FetchPonyfill ? FetchPonyfill({Promise: this.Promise}) : {};\n\n this.fetch = options.fetch || root.fetch || fetchPonyfill.fetch;\n this.Request = options.Request || root.Request || fetchPonyfill.Request;\n this.Response = options.Response || root.Response || fetchPonyfill.Response;\n this.Headers = options.Headers || root.Headers || fetchPonyfill.Headers;\n\n if (!this.fetch || !this.Response || !this.Request || !this.Headers) {\n throw new Error('Fetch API is missing');\n }\n\n if (!this.Promise) {\n throw new Error('Promise is missing');\n }\n\n if (!this.localStorage) {\n throw new Error('LocalStorage is missing');\n }\n\n if (!this.PUBNUB) {\n throw new Error('PUBNUB is missing');\n }\n\n}\n\nmodule.exports = Externals;\n\n/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))\n\n/***/ },\n/* 12 */\n/***/ function(module, exports) {\n\nmodule.exports = __WEBPACK_EXTERNAL_MODULE_12__;\n\n/***/ },\n/* 13 */\n/***/ function(module, exports) {\n\nmodule.exports = __WEBPACK_EXTERNAL_MODULE_13__;\n\n/***/ },\n/* 14 */\n/***/ function(module, exports) {\n\nmodule.exports = __WEBPACK_EXTERNAL_MODULE_14__;\n\n/***/ },\n/* 15 */\n/***/ function(module, exports, __webpack_require__) {\n\nvar EventEmitter = __webpack_require__(6).EventEmitter;\nvar qs = __webpack_require__(8);\nvar objectAssign = __webpack_require__(1);\nvar Auth = __webpack_require__(16);\nvar Constants = __webpack_require__(17);\nvar ApiResponse = __webpack_require__(7);\n\n/**\n * @constructor\n * @param {string} options.server\n * @param {string} options.appSecret\n * @param {string} options.appKey\n * @param {string} [options.appName]\n * @param {string} [options.appVersion]\n * @param {string} [options.redirectUri]\n * @param {int} [options.refreshDelayMs]\n * @param {int} [options.refreshHandicapMs]\n * @param {boolean} [options.clearCacheOnRefreshError]\n * @param {Externals} options.externals\n * @param {Cache} options.cache\n * @param {Client} options.client\n * @property {Externals} _externals\n * @property {Cache} _cache\n * @property {Client} _client\n * @property {Promise} _refreshPromise\n * @property {Auth} _auth\n */\nfunction Platform(options) {\n\n EventEmitter.call(this);\n\n this.events = {\n beforeLogin: 'beforeLogin',\n loginSuccess: 'loginSuccess',\n loginError: 'loginError',\n beforeRefresh: 'beforeRefresh',\n refreshSuccess: 'refreshSuccess',\n refreshError: 'refreshError',\n beforeLogout: 'beforeLogout',\n logoutSuccess: 'logoutSuccess',\n logoutError: 'logoutError'\n };\n\n options = options || {};\n\n /** @private */\n this._server = options.server;\n\n /** @private */\n this._appKey = options.appKey;\n\n /** @private */\n this._appSecret = options.appSecret;\n\n /** @private */\n this._redirectUri = options.redirectUri || '';\n\n /** @private */\n this._refreshDelayMs = options.refreshDelayMs || 100;\n\n /** @private */\n this._clearCacheOnRefreshError = typeof options.clearCacheOnRefreshError !== 'undefined' ?\n options.clearCacheOnRefreshError :\n true;\n\n /** @private */\n this._userAgent = (options.appName ?\n (options.appName + (options.appVersion ? '/' + options.appVersion : '')) + ' ' :\n '') + 'RCJSSDK/' + Constants.version;\n\n /** @private */\n this._externals = options.externals;\n\n /** @private */\n this._cache = options.cache;\n\n /** @private */\n this._client = options.client;\n\n /** @private */\n this._refreshPromise = null;\n\n /** @private */\n this._auth = new Auth({\n cache: this._cache,\n cacheId: Platform._cacheId,\n refreshHandicapMs: options.refreshHandicapMs\n });\n\n}\n\nPlatform._urlPrefix = '/restapi';\nPlatform._apiVersion = 'v1.0';\nPlatform._tokenEndpoint = '/restapi/oauth/token';\nPlatform._revokeEndpoint = '/restapi/oauth/revoke';\nPlatform._authorizeEndpoint = '/restapi/oauth/authorize';\nPlatform._cacheId = 'platform';\n\nPlatform.prototype = Object.create(EventEmitter.prototype);\n\nPlatform.prototype.delay = function(timeout) {\n return new this._externals.Promise(function(resolve, reject) {\n setTimeout(function() {\n resolve(null);\n }, timeout);\n });\n};\n\n/**\n * @return {Auth}\n */\nPlatform.prototype.auth = function() {\n return this._auth;\n};\n\n/**\n * @return {Client}\n */\nPlatform.prototype.client = function() {\n return this._client;\n};\n\n/**\n * @param {string} path\n * @param {object} [options]\n * @param {boolean} [options.addServer]\n * @param {string} [options.addMethod]\n * @param {boolean} [options.addToken]\n * @return {string}\n */\nPlatform.prototype.createUrl = function(path, options) {\n\n path = path || '';\n options = options || {};\n\n var builtUrl = '',\n hasHttp = path.indexOf('http://') != -1 || path.indexOf('https://') != -1;\n\n if (options.addServer && !hasHttp) builtUrl += this._server;\n\n if (path.indexOf(Platform._urlPrefix) == -1 && !hasHttp) builtUrl += Platform._urlPrefix + '/' + Platform._apiVersion;\n\n builtUrl += path;\n\n if (options.addMethod || options.addToken) builtUrl += (path.indexOf('?') > -1 ? '&' : '?');\n\n if (options.addMethod) builtUrl += '_method=' + options.addMethod;\n if (options.addToken) builtUrl += (options.addMethod ? '&' : '') + 'access_token=' + this._auth.accessToken();\n\n return builtUrl;\n\n};\n\n/**\n * @param {string} [options.redirectUri] Overrides default RedirectURI\n * @param {string} [options.state]\n * @param {string} [options.brandId]\n * @param {string} [options.display]\n * @param {string} [options.prompt]\n * @param {boolean} [options.implicit] Use Implicit Grant flow\n * @return {string}\n */\nPlatform.prototype.loginUrl = function(options) {\n\n options = options || {};\n\n return this.createUrl(Platform._authorizeEndpoint + '?' + qs.stringify({\n 'response_type': options.implicit ? 'token' : 'code',\n 'redirect_uri': options.redirectUri || this._redirectUri,\n 'client_id': this._appKey,\n 'state': options.state || '',\n 'brand_id': options.brandId || '',\n 'display': options.display || '',\n 'prompt': options.prompt || ''\n }), {addServer: true});\n\n};\n\n/**\n * @param {string} url\n * @return {Object}\n */\nPlatform.prototype.parseLoginRedirect = function(url) {\n\n function getParts(url, separator) {\n return url.split(separator).reverse()[0];\n }\n\n var response = (url.indexOf('#') === 0 && getParts(url, '#')) ||\n (url.indexOf('?') === 0 && getParts(url, '?')) ||\n null;\n\n if (!response) throw new Error('Unable to parse response');\n\n var queryString = qs.parse(response);\n\n if (!queryString) throw new Error('Unable to parse response');\n\n var error = queryString.error_description || queryString.error;\n\n if (error) {\n var e = new Error(error);\n e.error = queryString.error;\n throw e;\n }\n\n return queryString;\n\n};\n\n/**\n * Convenience method to handle 3-legged OAuth\n *\n * Attention! This is an experimental method and it's signature and behavior may change without notice.\n *\n * @experimental\n * @param {string} options.url\n * @param {number} [options.width]\n * @param {number} [options.height]\n * @param {object} [options.login] additional options for login()\n * @param {string} [options.origin]\n * @param {string} [options.property] name of window.postMessage's event data property\n * @param {string} [options.target] target for window.open()\n * @return {Promise}\n */\nPlatform.prototype.loginWindow = function(options) {\n\n return new this._externals.Promise(function(resolve, reject) {\n\n if (typeof window === 'undefined') throw new Error('This method can be used only in browser');\n\n if (!options.url) throw new Error('Missing mandatory URL parameter');\n\n options = options || {};\n options.url = options.url || 400;\n options.width = options.width || 400;\n options.height = options.height || 600;\n options.origin = options.origin || window.location.origin;\n options.property = options.property || Constants.authResponseProperty;\n options.target = options.target || '_blank';\n\n var dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left;\n var dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top;\n\n var width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;\n var height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;\n\n var left = ((width / 2) - (options.width / 2)) + dualScreenLeft;\n var top = ((height / 2) - (options.height / 2)) + dualScreenTop;\n var win = window.open(options.url, '_blank', (options.target == '_blank') ? 'scrollbars=yes, status=yes, width=' + options.width + ', height=' + options.height + ', left=' + left + ', top=' + top : '');\n\n if(!win) {\n throw new Error('Could not open login window. Please allow popups for this site');\n }\n\n if (win.focus) win.focus();\n\n var eventMethod = window.addEventListener ? 'addEventListener' : 'attachEvent';\n var eventRemoveMethod = eventMethod == 'addEventListener' ? 'removeEventListener' : 'detachEvent';\n var messageEvent = eventMethod == 'addEventListener' ? 'message' : 'onmessage';\n\n var eventListener = function(e) {\n\n try {\n\n if (e.origin != options.origin) return;\n if (!e.data || !e.data[options.property]) return; // keep waiting\n\n win.close();\n window[eventRemoveMethod](messageEvent, eventListener);\n\n\n var loginOptions = this.parseLoginRedirect(e.data[options.property]);\n\n if (!loginOptions.code && !loginOptions.access_token) throw new Error('No authorization code or token');\n\n resolve(loginOptions);\n\n /* jshint -W002 */\n } catch (e) {\n reject(e);\n }\n\n }.bind(this);\n\n window[eventMethod](messageEvent, eventListener, false);\n\n }.bind(this));\n\n};\n\n/**\n * @return {Promise}\n */\nPlatform.prototype.loggedIn = function() {\n\n return this.ensureLoggedIn().then(function() {\n return true;\n }).catch(function() {\n return false;\n });\n\n};\n\n/**\n * @param {string} options.username\n * @param {string} options.password\n * @param {string} [options.extension]\n * @param {string} [options.code]\n * @param {string} [options.redirectUri]\n * @param {string} [options.endpointId]\n * @param {string} [options.accessTokenTtl]\n * @param {string} [options.refreshTokenTtl]\n * @param {string} [options.access_token]\n * @returns {Promise}\n */\nPlatform.prototype.login = function(options) {\n\n return (new this._externals.Promise(function(resolve) {\n\n options = options || {};\n\n this.emit(this.events.beforeLogin);\n\n var body = {};\n\n if (options.access_token) {\n\n //TODO Potentially make a request to /oauth/tokeninfo\n return resolve(options);\n\n }\n\n if (!options.code) {\n\n body.grant_type = 'password';\n body.username = options.username;\n body.password = options.password;\n body.extension = options.extension || '';\n\n } else if (options.code) {\n\n body.grant_type = 'authorization_code';\n body.code = options.code;\n body.redirect_uri = options.redirectUri || this._redirectUri;\n //body.client_id = this.getCredentials().key; // not needed\n\n }\n\n if (options.endpointId) body.endpoint_id = options.endpointId;\n if (options.accessTokenTtl) body.accessTokenTtl = options.accessTokenTtl;\n if (options.refreshTokenTtl) body.refreshTokenTtl = options.refreshTokenTtl;\n\n resolve(this._tokenRequest(Platform._tokenEndpoint, body));\n\n }.bind(this))).then(function(res) {\n\n var apiResponse = res.json ? res : null;\n var json = apiResponse && apiResponse.json() || res;\n\n this._auth.setData(json);\n\n this.emit(this.events.loginSuccess, apiResponse);\n\n return apiResponse;\n\n }.bind(this)).catch(function(e) {\n\n if (this._clearCacheOnRefreshError) {\n this._cache.clean();\n }\n\n this.emit(this.events.loginError, e);\n\n throw e;\n\n }.bind(this));\n\n};\n\n/**\n * @returns {Promise}\n * @private\n */\nPlatform.prototype._refresh = function() {\n\n return this.delay(this._refreshDelayMs).then(function() {\n\n this.emit(this.events.beforeRefresh);\n\n // Perform sanity checks\n if (!this._auth.refreshToken()) throw new Error('Refresh token is missing');\n if (!this._auth.refreshTokenValid()) throw new Error('Refresh token has expired');\n\n return this._tokenRequest(Platform._tokenEndpoint, {\n \"grant_type\": \"refresh_token\",\n \"refresh_token\": this._auth.refreshToken(),\n \"access_token_ttl\": this._auth.data().expires_in + 1,\n \"refresh_token_ttl\": this._auth.data().refresh_token_expires_in + 1\n });\n\n }.bind(this)).then(function(/** @type {ApiResponse} */ res) {\n\n var json = res.json();\n\n if (!json.access_token) {\n throw this._client.makeError(new Error('Malformed OAuth response'), res);\n }\n\n this._auth.setData(json);\n\n this.emit(this.events.refreshSuccess, res);\n\n return res;\n\n }.bind(this)).catch(function(e) {\n\n e = this._client.makeError(e);\n\n if (this._clearCacheOnRefreshError) {\n this._cache.clean();\n }\n\n this.emit(this.events.refreshError, e);\n\n throw e;\n\n }.bind(this));\n\n};\n\n/**\n * @returns {Promise}\n */\nPlatform.prototype.refresh = function() {\n\n if (!this._refreshPromise) {\n\n this._refreshPromise = this._refresh()\n .then(function(res) {\n this._refreshPromise = null;\n return res;\n }.bind(this))\n .catch(function(e) {\n this._refreshPromise = null;\n throw e;\n }.bind(this));\n\n }\n\n return this._refreshPromise;\n\n};\n\n/**\n * @returns {Promise}\n */\nPlatform.prototype.logout = function() {\n\n return (new this._externals.Promise(function(resolve) {\n\n this.emit(this.events.beforeLogout);\n\n resolve(this._tokenRequest(Platform._revokeEndpoint, {\n token: this._auth.accessToken()\n }));\n\n }.bind(this))).then(function(res) {\n\n this._cache.clean();\n\n this.emit(this.events.logoutSuccess, res);\n\n return res;\n\n }.bind(this)).catch(function(e) {\n\n this.emit(this.events.logoutError, e);\n\n throw e;\n\n }.bind(this));\n\n};\n\n/**\n * @param {Request} request\n * @param {object} [options]\n * @param {boolean} [options.skipAuthCheck]\n * @return {Promise}\n */\nPlatform.prototype.inflateRequest = function(request, options) {\n\n options = options || {};\n\n if (options.skipAuthCheck) return this._externals.Promise.resolve(request);\n\n return this.ensureLoggedIn().then(function() {\n\n request.headers.set('X-User-Agent', this._userAgent);\n request.headers.set('Client-Id', this._appKey);\n request.headers.set('Authorization', this._authHeader());\n //request.url = this.createUrl(request.url, {addServer: true}); //FIXME Spec prevents this...\n\n return request;\n\n }.bind(this));\n\n};\n\n/**\n * @param {Request} request\n * @param {object} [options]\n * @param {boolean} [options.skipAuthCheck]\n * @param {boolean} [options.retry] Will be set by this method if SDK makes second request\n * @return {Promise}\n */\nPlatform.prototype.sendRequest = function(request, options) {\n\n return this.inflateRequest(request, options).then(function(request) {\n\n options = options || {};\n\n return this._client.sendRequest(request);\n\n }.bind(this)).catch(function(e) {\n\n // Guard is for errors that come from polling\n if (!e.apiResponse || !e.apiResponse.response() ||\n (e.apiResponse.response().status != ApiResponse._unauthorizedStatus) ||\n options.retry) throw e;\n\n this._auth.cancelAccessToken();\n\n options.retry = true;\n\n return this.sendRequest(request, options);\n\n }.bind(this));\n\n};\n\n/**\n * General purpose function to send anything to server\n * @param {string} options.url\n * @param {object} [options.body]\n * @param {string} [options.method]\n * @param {object} [options.query]\n * @param {object} [options.headers]\n * @param {boolean} [options.skipAuthCheck]\n * @return {Promise}\n */\nPlatform.prototype.send = function(options) {\n\n options = options || {};\n\n //FIXME https://github.com/bitinn/node-fetch/issues/43\n options.url = this.createUrl(options.url, {addServer: true});\n\n return this.sendRequest(this._client.createRequest(options), options);\n\n};\n\n/**\n * @param {string} url\n * @param {object} [query]\n * @param {object} [options]\n * @param {object} [options.headers]\n * @param {boolean} [options.skipAuthCheck]\n * @return {Promise}\n */\nPlatform.prototype.get = function(url, query, options) {\n return this.send(objectAssign({}, {method: 'GET', url: url, query: query}, options));\n};\n\n/**\n * @param {string} url\n * @param {object} body\n * @param {object} [query]\n * @param {object} [options]\n * @param {object} [options.headers]\n * @param {boolean} [options.skipAuthCheck]\n * @return {Promise}\n */\nPlatform.prototype.post = function(url, body, query, options) {\n return this.send(objectAssign({}, {method: 'POST', url: url, query: query, body: body}, options));\n};\n\n/**\n * @param {string} url\n * @param {object} [body]\n * @param {object} [query]\n * @param {object} [options]\n * @param {object} [options.headers]\n * @param {boolean} [options.skipAuthCheck]\n * @return {Promise}\n */\nPlatform.prototype.put = function(url, body, query, options) {\n return this.send(objectAssign({}, {method: 'PUT', url: url, query: query, body: body}, options));\n};\n\n/**\n * @param {string} url\n * @param {string} [query]\n * @param {object} [options]\n * @param {object} [options.headers]\n * @param {boolean} [options.skipAuthCheck]\n * @return {Promise}\n */\nPlatform.prototype['delete'] = function(url, query, options) {\n return this.send(objectAssign({}, {method: 'DELETE', url: url, query: query}, options));\n};\n\nPlatform.prototype.ensureLoggedIn = function() {\n if (this._isAccessTokenValid()) return this._externals.Promise.resolve();\n return this.refresh();\n};\n\n/**\n * @param path\n * @param body\n * @return {Promise.}\n * @private\n */\nPlatform.prototype._tokenRequest = function(path, body) {\n\n return this.send({\n url: path,\n skipAuthCheck: true,\n body: body,\n method: 'POST',\n headers: {\n 'Authorization': 'Basic ' + this._apiKey(),\n 'Content-Type': ApiResponse._urlencodedContentType\n }\n });\n\n};\n\n/**\n * @return {boolean}\n * @private\n */\nPlatform.prototype._isAccessTokenValid = function() {\n return this._auth.accessTokenValid();\n};\n\n/**\n * @return {string}\n * @private\n */\nPlatform.prototype._apiKey = function() {\n var apiKey = this._appKey + ':' + this._appSecret;\n return (typeof btoa == 'function') ? btoa(apiKey) : new Buffer(apiKey).toString('base64');\n};\n\n/**\n * @return {string}\n * @private\n */\nPlatform.prototype._authHeader = function() {\n var token = this._auth.accessToken();\n return this._auth.tokenType() + (token ? ' ' + token : '');\n};\n\nmodule.exports = Platform;\n\n/***/ },\n/* 16 */\n/***/ function(module, exports) {\n\n/**\n * @param {Cache} options.cache\n * @param {string} options.cacheId\n * @param {int} [options.refreshHandicapMs]\n * @constructor\n * @property {Cache} _cache\n * @property {int} _refreshHandicapMs\n * @property {string} _cacheId\n */\nfunction Auth(options) {\n\n /** @private */\n this._cache = options.cache;\n\n /** @private */\n this._cacheId = options.cacheId;\n\n /** @private */\n this._refreshHandicapMs = options.refreshHandicapMs || 60 * 1000; // 1 minute\n\n}\n\nAuth.prototype.accessToken = function() {\n return this.data().access_token;\n};\n\nAuth.prototype.refreshToken = function() {\n return this.data().refresh_token;\n};\n\nAuth.prototype.tokenType = function() {\n return this.data().token_type;\n};\n\n/**\n * @return {{token_type: string, access_token: string, expires_in: number, refresh_token: string, refresh_token_expires_in: number}}\n */\nAuth.prototype.data = function() {\n\n return this._cache.getItem(this._cacheId) || {\n token_type: '',\n access_token: '',\n expires_in: 0,\n refresh_token: '',\n refresh_token_expires_in: 0\n };\n\n};\n\n/**\n * @param {object} newData\n * @return {Auth}\n */\nAuth.prototype.setData = function(newData) {\n\n newData = newData || {};\n\n var data = this.data();\n\n Object.keys(newData).forEach(function(key) {\n data[key] = newData[key];\n });\n\n data.expire_time = Date.now() + (data.expires_in * 1000);\n data.refresh_token_expire_time = Date.now() + (data.refresh_token_expires_in * 1000);\n\n this._cache.setItem(this._cacheId, data);\n\n return this;\n\n};\n\n/**\n * Check if there is a valid (not expired) access token\n * @return {boolean}\n */\nAuth.prototype.accessTokenValid = function() {\n\n var authData = this.data();\n return (authData.expire_time - this._refreshHandicapMs > Date.now());\n\n};\n\n/**\n * Check if there is a valid (not expired) access token\n * @return {boolean}\n */\nAuth.prototype.refreshTokenValid = function() {\n\n return (this.data().refresh_token_expire_time > Date.now());\n\n};\n\n/**\n * @return {Auth}\n */\nAuth.prototype.cancelAccessToken = function() {\n\n return this.setData({\n access_token: '',\n expires_in: 0\n });\n\n};\n\nmodule.exports = Auth;\n\n//export interface IAuthData {\n// remember?:boolean;\n// token_type?:string;\n// access_token?:string;\n// expires_in?:number; // actually it's string\n// expire_time?:number;\n// refresh_token?:string;\n// refresh_token_expires_in?:number; // actually it's string\n// refresh_token_expire_time?:number;\n// scope?:string;\n//}\n\n\n/***/ },\n/* 17 */\n/***/ function(module, exports, __webpack_require__) {\n\nvar version = (\"3.0.0\");\n\n// This will become false during the Webpack build, so no traces of package.json will be there\nif (false) {\n version = require('../../package.json').version;\n}\n\nmodule.exports = {\n version: version,\n authResponseProperty: 'RCAuthorizationResponse'\n};\n\n/***/ },\n/* 18 */\n/***/ function(module, exports, __webpack_require__) {\n\nvar EventEmitter = __webpack_require__(6).EventEmitter;\n\n/**\n * @param {Platform} options.platform\n * @param {Externals} options.externals\n * @param {int} [options.pollInterval]\n * @param {int} [options.renewHandicapMs]\n * @property {Externals} _externals\n * @property {Platform} _platform\n * @property {int} _pollInterval\n * @property {int} _renewHandicapMs\n * @property {PUBNUB} _pubnub\n * @property {string} _pubnubLastChannel\n * @property {int} _timeout\n * @property {ISubscription} _subscription\n * @constructor\n */\nfunction Subscription(options) {\n\n EventEmitter.call(this);\n\n options = options || {};\n\n this.events = {\n notification: 'notification',\n removeSuccess: 'removeSuccess',\n removeError: 'removeError',\n renewSuccess: 'renewSuccess',\n renewError: 'renewError',\n subscribeSuccess: 'subscribeSuccess',\n subscribeError: 'subscribeError'\n };\n\n /** @private */\n this._externals = options.externals;\n\n /** @private */\n this._platform = options.platform;\n\n /** @private */\n this._pollInterval = options.pollInterval || 10 * 1000;\n\n /** @private */\n this._renewHandicapMs = options.renewHandicapMs || 2 * 60 * 1000;\n\n /** @private */\n this._pubnub = null;\n\n /** @private */\n this._pubnubLastChannel = null;\n\n /** @private */\n this._timeout = null;\n\n /** @private */\n this._subscription = null;\n\n}\n\nSubscription.prototype = Object.create(EventEmitter.prototype);\n\nSubscription.prototype.subscribed = function() {\n\n var subscription = this.subscription();\n\n return !!(subscription.id &&\n subscription.deliveryMode &&\n subscription.deliveryMode.subscriberKey &&\n subscription.deliveryMode.address);\n\n};\n\n/**\n * @return {boolean}\n */\nSubscription.prototype.alive = function() {\n return this.subscribed() && Date.now() < this.expirationTime();\n};\n\n/**\n * @return {boolean}\n */\nSubscription.prototype.expired = function() {\n if (!this.subscribed()) return true;\n return !this.subscribed() || Date.now() > this.subscription().expirationTime;\n};\n\nSubscription.prototype.expirationTime = function() {\n return new Date(this.subscription().expirationTime || 0).getTime() - this._renewHandicapMs;\n};\n\n/**\n * @param {ISubscription} subscription\n * @return {Subscription}\n */\nSubscription.prototype.setSubscription = function(subscription) {\n\n subscription = subscription || {};\n\n this._clearTimeout();\n this._setSubscription(subscription);\n this._subscribeAtPubnub();\n this._setTimeout();\n\n return this;\n\n};\n\n/**\n * @return {ISubscription}\n */\nSubscription.prototype.subscription = function() {\n return this._subscription || {};\n};\n\n/**\n * Creates or updates subscription if there is an active one\n * @returns {Promise}\n */\nSubscription.prototype.register = function() {\n\n if (this.alive()) {\n return this.renew();\n } else {\n return this.subscribe();\n }\n\n};\n\n/**\n * @return {string[]}\n */\nSubscription.prototype.eventFilters = function() {\n return this.subscription().eventFilters || [];\n};\n\n/**\n * @param {string[]} events\n * @return {Subscription}\n */\nSubscription.prototype.addEventFilters = function(events) {\n this.setEventFilters(this.eventFilters().concat(events));\n return this;\n};\n\n/**\n * @param {string[]} events\n * @return {Subscription}\n */\nSubscription.prototype.setEventFilters = function(events) {\n var subscription = this.subscription();\n subscription.eventFilters = events;\n this._setSubscription(subscription);\n return this;\n};\n\n/**\n * @returns {Promise}\n */\nSubscription.prototype.subscribe = function() {\n\n return (new this._externals.Promise(function(resolve) {\n\n this._clearTimeout();\n\n if (!this.eventFilters().length) throw new Error('Events are undefined');\n\n resolve(this._platform.post('/subscription', {\n eventFilters: this._getFullEventFilters(),\n deliveryMode: {\n transportType: 'PubNub'\n }\n }));\n\n }.bind(this))).then(function(response) {\n\n var json = response.json();\n\n this.setSubscription(json)\n .emit(this.events.subscribeSuccess, response);\n\n return response;\n\n }.bind(this)).catch(function(e) {\n\n e = this._platform.client().makeError(e);\n\n this.reset()\n .emit(this.events.subscribeError, e);\n\n throw e;\n\n }.bind(this));\n\n};\n\n/**\n * @returns {Promise}\n */\nSubscription.prototype.renew = function() {\n\n return (new this._externals.Promise(function(resolve) {\n\n this._clearTimeout();\n\n if (!this.subscribed()) throw new Error('No subscription');\n\n if (!this.eventFilters().length) throw new Error('Events are undefined');\n\n resolve(this._platform.put('/subscription/' + this.subscription().id, {\n eventFilters: this._getFullEventFilters()\n }));\n\n }.bind(this))).then(function(response) {\n\n var json = response.json();\n\n this.setSubscription(json)\n .emit(this.events.renewSuccess, response);\n\n return response;\n\n }.bind(this)).catch(function(e) {\n\n e = this._platform.client().makeError(e);\n\n this.reset()\n .emit(this.events.renewError, e);\n\n throw e;\n\n }.bind(this));\n\n};\n\n/**\n * @returns {Promise}\n */\nSubscription.prototype.remove = function() {\n\n return (new this._externals.Promise(function(resolve) {\n\n if (!this.subscribed()) throw new Error('No subscription');\n\n resolve(this._platform.delete('/subscription/' + this.subscription().id));\n\n }.bind(this))).then(function(response) {\n\n this.reset()\n .emit(this.events.removeSuccess, response);\n\n return response;\n\n }.bind(this)).catch(function(e) {\n\n e = this._platform.client().makeError(e);\n\n this.emit(this.events.removeError, e);\n\n throw e;\n\n }.bind(this));\n\n};\n\n/**\n * @returns {Promise}\n */\nSubscription.prototype.resubscribe = function() {\n var filters = this.eventFilters();\n return this.reset().setEventFilters(filters).subscribe();\n};\n\n/**\n * Remove subscription and disconnect from PUBNUB\n * This method resets subscription at client side but backend is not notified\n * @return {Subscription}\n */\nSubscription.prototype.reset = function() {\n this._clearTimeout();\n if (this.subscribed() && this._pubnub) this._pubnub.unsubscribe({channel: this.subscription().deliveryMode.address});\n this._setSubscription(null);\n return this;\n};\n\n/**\n * @param subscription\n * @private\n */\nSubscription.prototype._setSubscription = function(subscription) {\n this._subscription = subscription;\n};\n\n/**\n * @return {string[]}\n * @private\n */\nSubscription.prototype._getFullEventFilters = function() {\n\n return this.eventFilters().map(function(event) {\n return this._platform.createUrl(event);\n }.bind(this));\n\n};\n\n/**\n * @return {Subscription}\n * @private\n */\nSubscription.prototype._setTimeout = function() {\n\n this._clearTimeout();\n\n if (!this.alive()) throw new Error('Subscription is not alive');\n\n this._timeout = setInterval(function() {\n\n if (this.alive()) return;\n\n if (this.expired()) {\n this.subscribe();\n } else {\n this.renew();\n }\n\n }.bind(this), this._pollInterval);\n\n return this;\n\n};\n\n/**\n * @return {Subscription}\n * @private\n */\nSubscription.prototype._clearTimeout = function() {\n clearInterval(this._timeout);\n return this;\n};\n\nSubscription.prototype._decrypt = function(message) {\n\n if (!this.subscribed()) throw new Error('No subscription');\n\n if (this.subscription().deliveryMode.encryptionKey) {\n\n message = this._externals.PUBNUB.crypto_obj.decrypt(message, this.subscription().deliveryMode.encryptionKey, {\n encryptKey: false,\n keyEncoding: 'base64',\n keyLength: 128,\n mode: 'ecb'\n });\n\n }\n\n return message;\n\n};\n\n/**\n * @param message\n * @return {Subscription}\n * @private\n */\nSubscription.prototype._notify = function(message) {\n this.emit(this.events.notification, this._decrypt(message));\n return this;\n};\n\n/**\n * @return {Subscription}\n * @private\n */\nSubscription.prototype._subscribeAtPubnub = function() {\n\n if (!this.alive()) throw new Error('Subscription is not alive');\n\n var deliveryMode = this.subscription().deliveryMode;\n\n if (this._pubnub) {\n\n if (this._pubnubLastChannel == deliveryMode.address) { // Nothing to update, keep listening to same channel\n return this;\n } else if (this._pubnubLastChannel) { // Need to subscribe to new channel\n this._pubnub.unsubscribe({channel: this._pubnubLastChannel});\n }\n\n // Re-init for new data\n this._pubnub = this._pubnub.init({\n ssl: true,\n subscribe_key: deliveryMode.subscriberKey\n });\n\n } else {\n\n // Init from scratch\n this._pubnub = this._externals.PUBNUB.init({\n ssl: true,\n subscribe_key: deliveryMode.subscriberKey\n });\n\n this._pubnub.ready(); //TODO This may be not needed anymore\n\n }\n\n this._pubnubLastChannel = deliveryMode.address;\n\n this._pubnub.subscribe({\n channel: deliveryMode.address,\n message: this._notify.bind(this),\n connect: function() {}\n });\n\n return this;\n\n};\n\nmodule.exports = Subscription;\n\n/**\n * The complete Triforce, or one or more components of the Triforce.\n * @typedef {Object} ISubscription\n * @property {string} [id]\n * @property {string} [uri]\n * @property {string[]} [eventFilters]\n * @property {string} [expirationTime] Format: 2014-03-12T19:54:35.613Z\n * @property {int} [expiresIn]\n * @property {string} [deliveryMode.transportType]\n * @property {boolean} [deliveryMode.encryption]\n * @property {string} [deliveryMode.address]\n * @property {string} [deliveryMode.subscriberKey]\n * @property {string} [deliveryMode.encryptionKey]\n * @property {string} [deliveryMode.secretKey]\n * @property {string} [creationTime]\n * @property {string} [status] Active\n */\n\n/***/ },\n/* 19 */\n/***/ function(module, exports, __webpack_require__) {\n\nvar Subscription = __webpack_require__(18);\n\n/**\n * @param {Platform} options.platform\n * @param {Externals} options.externals\n * @param {Cache} options.cache\n * @param {string} options.cacheKey\n * @param {int} [options.pollInterval]\n * @param {int} [options.renewHandicapMs]\n * @return {CachedSubscription}\n * @constructor\n * @property {Cache} _cache\n * @extends Subscription\n */\nfunction CachedSubscription(options) {\n\n options = options || {};\n\n if (!options.cacheKey) throw new Error('Cached Subscription requires cacheKey parameter to be defined');\n\n /** @private */\n this._cacheKey = options.cacheKey;\n\n Subscription.call(this, options);\n\n /** @private */\n this._cache = options.cache;\n\n // This is not used in this class\n this._subscription = undefined;\n\n}\n\nCachedSubscription.prototype = Object.create(Subscription.prototype);\n\nCachedSubscription.prototype.subscription = function() {\n return this._cache.getItem(this._cacheKey) || {};\n};\n\nCachedSubscription.prototype._setSubscription = function(subscription) {\n return this._cache.setItem(this._cacheKey, subscription);\n};\n\n/**\n * This function checks whether there are any pre-defined eventFilters in cache and if not -- uses provided as defaults\n * @param {string[]} events\n * @return {CachedSubscription}\n */\nCachedSubscription.prototype.restore = function(events) {\n\n if (!this.eventFilters().length) {\n this.setEventFilters(events);\n }\n\n return this;\n\n};\n\nmodule.exports = CachedSubscription;\n\n/***/ }\n/******/ ])\n});\n;\n\n\n/** WEBPACK FOOTER **\n ** ringcentral.min.js\n **/"," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId])\n \t\t\treturn installedModules[moduleId].exports;\n\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\texports: {},\n \t\t\tid: moduleId,\n \t\t\tloaded: false\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.loaded = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"/build/\";\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(0);\n\n\n\n/** WEBPACK FOOTER **\n ** webpack/bootstrap e778b74917863b61271c\n **/","/**\n * @namespace RingCentral\n */\nvar objectAssign = require('object-assign');\nvar Cache = require(\"./core/Cache\");\nvar Client = require(\"./http/Client\");\nvar Externals = require(\"./core/Externals\");\nvar Platform = require(\"./platform/Platform\");\nvar Subscription = require(\"./subscription/Subscription\");\nvar CachedSubscription = require(\"./subscription/CachedSubscription\");\nvar Constants = require(\"./core/Constants\");\n\n/**\n * @constructor\n * @param {string} options.server\n * @param {string} options.appSecret\n * @param {string} options.appKey\n * @param {string} [options.cachePrefix]\n * @param {string} [options.appName]\n * @param {string} [options.appVersion]\n * @param {string} [options.redirectUri]\n * @param {PUBNUB} [options.PUBNUB]\n * @param {function(new:Promise)} [options.Promise]\n * @param {Storage} [options.localStorage]\n * @param {fetch} [options.fetch]\n * @param {function(new:Request)} [options.Request]\n * @param {function(new:Response)} [options.Response]\n * @param {function(new:Headers)} [options.Headers]\n * @param {int} [options.refreshDelayMs]\n * @param {int} [options.refreshHandicapMs]\n * @param {boolean} [options.clearCacheOnRefreshError]\n * @property {Externals} _externals\n * @property {Cache} _cache\n * @property {Client} _client\n * @property {Platform} _platform\n */\nfunction SDK(options) {\n\n /** @private */\n this._externals = new Externals(options);\n\n /** @private */\n this._cache = new Cache({\n externals: this._externals,\n prefix: options.cachePrefix\n });\n\n /** @private */\n this._client = new Client(this._externals);\n\n /** @private */\n this._platform = new Platform(objectAssign({}, options, {\n externals: this._externals,\n client: this._client,\n cache: this._cache\n }));\n\n}\n\nSDK.version = Constants.version;\n\nSDK.server = {\n sandbox: 'https://platform.devtest.ringcentral.com',\n production: 'https://platform.ringcentral.com'\n};\n\n/**\n * @return {Platform}\n */\nSDK.prototype.platform = function() {\n return this._platform;\n};\n\n/**\n * @return {Cache}\n */\nSDK.prototype.cache = function() {\n return this._cache;\n};\n\n/**\n * @param {int} [options.pollInterval]\n * @param {int} [options.renewHandicapMs]\n * @return {Subscription}\n */\nSDK.prototype.createSubscription = function(options) {\n return new Subscription(objectAssign({}, options, {\n externals: this._externals,\n platform: this._platform\n }));\n};\n\n/**\n * @param {string} options.cacheKey\n * @param {int} [options.pollInterval]\n * @param {int} [options.renewHandicapMs]\n * @return {CachedSubscription}\n */\nSDK.prototype.createCachedSubscription = function(options) {\n\n if (typeof arguments[0] == 'string') {\n options = {cacheKey: arguments[0].toString()};\n } else {\n options = options || {};\n }\n\n return new CachedSubscription(objectAssign({}, options, {\n externals: this._externals,\n platform: this._platform,\n cache: this._cache\n }));\n\n};\n\nSDK.handleLoginRedirect = function(origin) {\n\n var response = window.location.hash ? window.location.hash : window.location.search;\n var msg = {};\n msg[Constants.authResponseProperty] = response;\n window.opener.postMessage(msg, origin || window.location.origin);\n\n};\n\nmodule.exports = SDK;\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/SDK.js\n ** module id = 0\n ** module chunks = 0 1\n **/","'use strict';\n/* eslint-disable no-unused-vars */\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\nvar propIsEnumerable = Object.prototype.propertyIsEnumerable;\n\nfunction toObject(val) {\n\tif (val === null || val === undefined) {\n\t\tthrow new TypeError('Object.assign cannot be called with null or undefined');\n\t}\n\n\treturn Object(val);\n}\n\nfunction shouldUseNative() {\n\ttry {\n\t\tif (!Object.assign) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// Detect buggy property enumeration order in older V8 versions.\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=4118\n\t\tvar test1 = new String('abc'); // eslint-disable-line\n\t\ttest1[5] = 'de';\n\t\tif (Object.getOwnPropertyNames(test1)[0] === '5') {\n\t\t\treturn false;\n\t\t}\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=3056\n\t\tvar test2 = {};\n\t\tfor (var i = 0; i < 10; i++) {\n\t\t\ttest2['_' + String.fromCharCode(i)] = i;\n\t\t}\n\t\tvar order2 = Object.getOwnPropertyNames(test2).map(function (n) {\n\t\t\treturn test2[n];\n\t\t});\n\t\tif (order2.join('') !== '0123456789') {\n\t\t\treturn false;\n\t\t}\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=3056\n\t\tvar test3 = {};\n\t\t'abcdefghijklmnopqrst'.split('').forEach(function (letter) {\n\t\t\ttest3[letter] = letter;\n\t\t});\n\t\tif (Object.keys(Object.assign({}, test3)).join('') !==\n\t\t\t\t'abcdefghijklmnopqrst') {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t} catch (e) {\n\t\t// We don't expect any of the above to throw, but better to be safe.\n\t\treturn false;\n\t}\n}\n\nmodule.exports = shouldUseNative() ? Object.assign : function (target, source) {\n\tvar from;\n\tvar to = toObject(target);\n\tvar symbols;\n\n\tfor (var s = 1; s < arguments.length; s++) {\n\t\tfrom = Object(arguments[s]);\n\n\t\tfor (var key in from) {\n\t\t\tif (hasOwnProperty.call(from, key)) {\n\t\t\t\tto[key] = from[key];\n\t\t\t}\n\t\t}\n\n\t\tif (Object.getOwnPropertySymbols) {\n\t\t\tsymbols = Object.getOwnPropertySymbols(from);\n\t\t\tfor (var i = 0; i < symbols.length; i++) {\n\t\t\t\tif (propIsEnumerable.call(from, symbols[i])) {\n\t\t\t\t\tto[symbols[i]] = from[symbols[i]];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn to;\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/object-assign/index.js\n ** module id = 1\n ** module chunks = 0 1\n **/","/**\n * @param {Externals} options.externals\n * @param {string} [options.prefix]\n * @property {Externals} _externals\n */\nfunction Cache(options) {\n\n /** @private */\n this._prefix = options.prefix || Cache.defaultPrefix;\n\n /** @private */\n this._externals = options.externals;\n\n}\n\nCache.defaultPrefix = 'rc-';\n\nCache.prototype.setItem = function(key, data) {\n this._externals.localStorage[this._prefixKey(key)] = JSON.stringify(data);\n return this;\n};\n\nCache.prototype.removeItem = function(key) {\n delete this._externals.localStorage[this._prefixKey(key)];\n return this;\n};\n\nCache.prototype.getItem = function(key) {\n var item = this._externals.localStorage[this._prefixKey(key)];\n if (!item) return null;\n return JSON.parse(item);\n};\n\nCache.prototype.clean = function() {\n\n for (var key in this._externals.localStorage) {\n\n if (!this._externals.localStorage.hasOwnProperty(key)) continue;\n\n if (key.indexOf(this._prefix) === 0) {\n delete this._externals.localStorage[key];\n }\n\n }\n\n return this;\n\n};\n\nCache.prototype._prefixKey = function(key) {\n return this._prefix + key;\n};\n\nmodule.exports = Cache;\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/core/Cache.js\n ** module id = 2\n ** module chunks = 0 1\n **/","var isPlainObject = require(\"is-plain-object\");\nvar EventEmitter = require(\"events\").EventEmitter;\nvar ApiResponse = require(\"./ApiResponse\");\nvar qs = require(\"querystring\");\n\nfunction findHeaderName(name, headers) {\n name = name.toLowerCase();\n return Object.keys(headers).reduce(function(res, key) {\n if (res) return res;\n if (name == key.toLowerCase()) return key;\n return res;\n }, null);\n}\n\n/**\n * @param {Externals} externals\n * @property {Externals} _externals\n */\nfunction Client(externals) {\n\n EventEmitter.call(this);\n\n /** @private */\n this._externals = externals;\n\n this.events = {\n beforeRequest: 'beforeRequest',\n requestSuccess: 'requestSuccess',\n requestError: 'requestError'\n };\n\n}\n\nClient._allowedMethods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS', 'HEAD'];\n\nClient.prototype = Object.create(EventEmitter.prototype);\n\n/**\n * @param {Request} request\n * @return {Promise}\n */\nClient.prototype.sendRequest = function(request) {\n\n var apiResponse = new ApiResponse({\n externals: this._externals,\n request: request\n });\n\n return (new this._externals.Promise(function(resolve) {\n\n //TODO Stop request if listeners return false\n this.emit(this.events.beforeRequest, apiResponse);\n\n resolve(this._loadResponse(request));\n\n }.bind(this))).then(function(response) {\n\n return apiResponse.receiveResponse(response);\n\n }).then(function() {\n\n if (!apiResponse.ok()) throw new Error('Response has unsuccessful status');\n\n this.emit(this.events.requestSuccess, apiResponse);\n\n return apiResponse;\n\n }.bind(this)).catch(function(e) {\n\n if (!e.apiResponse) e = this.makeError(e, apiResponse);\n\n this.emit(this.events.requestError, e);\n\n throw e;\n\n }.bind(this));\n\n};\n\n/**\n * @param {Request} request\n * @return {Promise}\n * @private\n */\nClient.prototype._loadResponse = function(request) {\n return this._externals.fetch.call(null, request);\n};\n\n/**\n * Wraps the JS Error object with transaction information\n * @param {Error|IApiError} e\n * @param {ApiResponse} apiResponse\n * @return {IApiError}\n */\nClient.prototype.makeError = function(e, apiResponse) {\n\n // Wrap only if regular error\n if (!e.hasOwnProperty('apiResponse') && !e.hasOwnProperty('originalMessage')) {\n\n e.apiResponse = apiResponse;\n e.originalMessage = e.message;\n e.message = (apiResponse && apiResponse.error(true)) || e.originalMessage;\n\n }\n\n return e;\n\n};\n\n/**\n *\n * @param {object} init\n * @param {object} [init.url]\n * @param {object} [init.body]\n * @param {string} [init.method]\n * @param {object} [init.query]\n * @param {object} [init.headers]\n * @param {object} [init.credentials]\n * @param {object} [init.mode]\n * @return {Request}\n */\nClient.prototype.createRequest = function(init) {\n\n init = init || {};\n init.headers = init.headers || {};\n\n // Sanity checks\n if (!init.url) throw new Error('Url is not defined');\n if (!init.method) init.method = 'GET';\n init.method = init.method.toUpperCase();\n if (init.method && Client._allowedMethods.indexOf(init.method) < 0) {\n throw new Error('Method has wrong value: ' + init.method);\n }\n\n // Defaults\n init.credentials = init.credentials || 'include';\n init.mode = init.mode || 'cors';\n\n // Append Query String\n if (init.query) {\n init.url = init.url + (init.url.indexOf('?') > -1 ? '&' : '?') + qs.stringify(init.query);\n }\n\n if (!(findHeaderName('Accept', init.headers))) {\n init.headers.Accept = ApiResponse._jsonContentType;\n }\n\n // Serialize body\n if (isPlainObject(init.body) || !init.body) {\n\n var contentTypeHeaderName = findHeaderName(ApiResponse._contentType, init.headers);\n\n if (!contentTypeHeaderName) {\n contentTypeHeaderName = ApiResponse._contentType;\n init.headers[contentTypeHeaderName] = ApiResponse._jsonContentType;\n }\n\n var contentType = init.headers[contentTypeHeaderName];\n\n // Assign a new encoded body\n if (contentType.indexOf(ApiResponse._jsonContentType) > -1) {\n if ((init.method === 'GET' || init.method === 'HEAD') && !!init.body) {\n // oddly setting body to null still result in TypeError in phantomjs\n init.body = undefined;\n } else {\n init.body = JSON.stringify(init.body);\n }\n\n } else if (contentType.indexOf(ApiResponse._urlencodedContentType) > -1) {\n init.body = qs.stringify(init.body);\n }\n\n }\n\n // Create a request with encoded body\n var req = new this._externals.Request(init.url, init);\n\n // Keep the original body accessible directly (for mocks)\n req.originalBody = init.body;\n\n return req;\n\n};\n\n/**\n * @typedef {object} IApiError\n * @property {string} stack\n * @property {string} originalMessage\n * @property {ApiResponse} apiResponse\n */\n\nmodule.exports = Client;\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/http/Client.js\n ** module id = 3\n ** module chunks = 0 1\n **/","/*!\n * is-plain-object \n *\n * Copyright (c) 2014-2015, Jon Schlinkert.\n * Licensed under the MIT License.\n */\n\n'use strict';\n\nvar isObject = require('isobject');\n\nfunction isObjectObject(o) {\n return isObject(o) === true\n && Object.prototype.toString.call(o) === '[object Object]';\n}\n\nmodule.exports = function isPlainObject(o) {\n var ctor,prot;\n \n if (isObjectObject(o) === false) return false;\n \n // If has modified constructor\n ctor = o.constructor;\n if (typeof ctor !== 'function') return false;\n \n // If has modified prototype\n prot = ctor.prototype;\n if (isObjectObject(prot) === false) return false;\n \n // If constructor does not have an Object-specific method\n if (prot.hasOwnProperty('isPrototypeOf') === false) {\n return false;\n }\n \n // Most likely a plain Object\n return true;\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/is-plain-object/index.js\n ** module id = 4\n ** module chunks = 0 1\n **/","/*!\n * isobject \n *\n * Copyright (c) 2014-2015, Jon Schlinkert.\n * Licensed under the MIT License.\n */\n\n'use strict';\n\nmodule.exports = function isObject(val) {\n return val != null && typeof val === 'object'\n && !Array.isArray(val);\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/is-plain-object/~/isobject/index.js\n ** module id = 5\n ** module chunks = 0 1\n **/","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nfunction EventEmitter() {\n this._events = this._events || {};\n this._maxListeners = this._maxListeners || undefined;\n}\nmodule.exports = EventEmitter;\n\n// Backwards-compat with node 0.10.x\nEventEmitter.EventEmitter = EventEmitter;\n\nEventEmitter.prototype._events = undefined;\nEventEmitter.prototype._maxListeners = undefined;\n\n// By default EventEmitters will print a warning if more than 10 listeners are\n// added to it. This is a useful default which helps finding memory leaks.\nEventEmitter.defaultMaxListeners = 10;\n\n// Obviously not all Emitters should be limited to 10. This function allows\n// that to be increased. Set to zero for unlimited.\nEventEmitter.prototype.setMaxListeners = function(n) {\n if (!isNumber(n) || n < 0 || isNaN(n))\n throw TypeError('n must be a positive number');\n this._maxListeners = n;\n return this;\n};\n\nEventEmitter.prototype.emit = function(type) {\n var er, handler, len, args, i, listeners;\n\n if (!this._events)\n this._events = {};\n\n // If there is no 'error' event listener then throw.\n if (type === 'error') {\n if (!this._events.error ||\n (isObject(this._events.error) && !this._events.error.length)) {\n er = arguments[1];\n if (er instanceof Error) {\n throw er; // Unhandled 'error' event\n } else {\n // At least give some kind of context to the user\n var err = new Error('Uncaught, unspecified \"error\" event. (' + er + ')');\n err.context = er;\n throw err;\n }\n }\n }\n\n handler = this._events[type];\n\n if (isUndefined(handler))\n return false;\n\n if (isFunction(handler)) {\n switch (arguments.length) {\n // fast cases\n case 1:\n handler.call(this);\n break;\n case 2:\n handler.call(this, arguments[1]);\n break;\n case 3:\n handler.call(this, arguments[1], arguments[2]);\n break;\n // slower\n default:\n args = Array.prototype.slice.call(arguments, 1);\n handler.apply(this, args);\n }\n } else if (isObject(handler)) {\n args = Array.prototype.slice.call(arguments, 1);\n listeners = handler.slice();\n len = listeners.length;\n for (i = 0; i < len; i++)\n listeners[i].apply(this, args);\n }\n\n return true;\n};\n\nEventEmitter.prototype.addListener = function(type, listener) {\n var m;\n\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n if (!this._events)\n this._events = {};\n\n // To avoid recursion in the case that type === \"newListener\"! Before\n // adding it to the listeners, first emit \"newListener\".\n if (this._events.newListener)\n this.emit('newListener', type,\n isFunction(listener.listener) ?\n listener.listener : listener);\n\n if (!this._events[type])\n // Optimize the case of one listener. Don't need the extra array object.\n this._events[type] = listener;\n else if (isObject(this._events[type]))\n // If we've already got an array, just append.\n this._events[type].push(listener);\n else\n // Adding the second element, need to change to array.\n this._events[type] = [this._events[type], listener];\n\n // Check for listener leak\n if (isObject(this._events[type]) && !this._events[type].warned) {\n if (!isUndefined(this._maxListeners)) {\n m = this._maxListeners;\n } else {\n m = EventEmitter.defaultMaxListeners;\n }\n\n if (m && m > 0 && this._events[type].length > m) {\n this._events[type].warned = true;\n console.error('(node) warning: possible EventEmitter memory ' +\n 'leak detected. %d listeners added. ' +\n 'Use emitter.setMaxListeners() to increase limit.',\n this._events[type].length);\n if (typeof console.trace === 'function') {\n // not supported in IE 10\n console.trace();\n }\n }\n }\n\n return this;\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.once = function(type, listener) {\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n var fired = false;\n\n function g() {\n this.removeListener(type, g);\n\n if (!fired) {\n fired = true;\n listener.apply(this, arguments);\n }\n }\n\n g.listener = listener;\n this.on(type, g);\n\n return this;\n};\n\n// emits a 'removeListener' event iff the listener was removed\nEventEmitter.prototype.removeListener = function(type, listener) {\n var list, position, length, i;\n\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n if (!this._events || !this._events[type])\n return this;\n\n list = this._events[type];\n length = list.length;\n position = -1;\n\n if (list === listener ||\n (isFunction(list.listener) && list.listener === listener)) {\n delete this._events[type];\n if (this._events.removeListener)\n this.emit('removeListener', type, listener);\n\n } else if (isObject(list)) {\n for (i = length; i-- > 0;) {\n if (list[i] === listener ||\n (list[i].listener && list[i].listener === listener)) {\n position = i;\n break;\n }\n }\n\n if (position < 0)\n return this;\n\n if (list.length === 1) {\n list.length = 0;\n delete this._events[type];\n } else {\n list.splice(position, 1);\n }\n\n if (this._events.removeListener)\n this.emit('removeListener', type, listener);\n }\n\n return this;\n};\n\nEventEmitter.prototype.removeAllListeners = function(type) {\n var key, listeners;\n\n if (!this._events)\n return this;\n\n // not listening for removeListener, no need to emit\n if (!this._events.removeListener) {\n if (arguments.length === 0)\n this._events = {};\n else if (this._events[type])\n delete this._events[type];\n return this;\n }\n\n // emit removeListener for all listeners on all events\n if (arguments.length === 0) {\n for (key in this._events) {\n if (key === 'removeListener') continue;\n this.removeAllListeners(key);\n }\n this.removeAllListeners('removeListener');\n this._events = {};\n return this;\n }\n\n listeners = this._events[type];\n\n if (isFunction(listeners)) {\n this.removeListener(type, listeners);\n } else if (listeners) {\n // LIFO order\n while (listeners.length)\n this.removeListener(type, listeners[listeners.length - 1]);\n }\n delete this._events[type];\n\n return this;\n};\n\nEventEmitter.prototype.listeners = function(type) {\n var ret;\n if (!this._events || !this._events[type])\n ret = [];\n else if (isFunction(this._events[type]))\n ret = [this._events[type]];\n else\n ret = this._events[type].slice();\n return ret;\n};\n\nEventEmitter.prototype.listenerCount = function(type) {\n if (this._events) {\n var evlistener = this._events[type];\n\n if (isFunction(evlistener))\n return 1;\n else if (evlistener)\n return evlistener.length;\n }\n return 0;\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n return emitter.listenerCount(type);\n};\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/events/events.js\n ** module id = 6\n ** module chunks = 0 1\n **/","/**\n * @param {Externals} options.externals\n * @param {Request} [options.request]\n * @param {Response} [options.response]\n * @param {string} [options.responseText]\n * @property {Externals} _externals\n * @property {Request} _request\n * @property {Response} _response\n * @property {string} _text\n * @property {object} _json\n * @property {ApiResponse[]} _multipart\n */\nfunction ApiResponse(options) {\n\n /** @private */\n this._externals = options.externals;\n\n /** @private */\n this._request = options.request;\n\n /** @private */\n this._response = options.response;\n\n /** @private */\n this._text = options.responseText || '';\n\n /** @private */\n this._json = null;\n\n /** @private */\n this._multipart = [];\n\n}\n\nApiResponse._contentType = 'Content-Type';\nApiResponse._jsonContentType = 'application/json';\nApiResponse._multipartContentType = 'multipart/mixed';\nApiResponse._urlencodedContentType = 'application/x-www-form-urlencoded';\nApiResponse._headerSeparator = ':';\nApiResponse._bodySeparator = '\\n\\n';\nApiResponse._boundarySeparator = '--';\nApiResponse._unauthorizedStatus = 401;\n\n/**\n * @param {Response} response\n * @return {Promise}\n */\nApiResponse.prototype.receiveResponse = function(response) {\n\n this._response = response;\n\n return (new this._externals.Promise(function(resolve) {\n\n // Ignore if not textual type\n if (!this._isMultipart() && !this._isJson()) return resolve('');\n\n return resolve(this.response().text());\n\n }.bind(this))).then(function(text) {\n\n this._text = text;\n return text;\n\n }.bind(this));\n\n};\n\n/**\n * @return {Response}\n */\nApiResponse.prototype.response = function() {\n return this._response;\n};\n\n/**\n * @return {Request}\n */\nApiResponse.prototype.request = function() {\n return this._request;\n};\n\n/**\n * @return {boolean}\n */\nApiResponse.prototype.ok = function() {\n return this._response && this._response.ok;\n};\n\n/**\n * @return {string}\n */\nApiResponse.prototype.text = function() {\n // Since we read text only in case JSON or Multipart\n if (!this._isJson() && !this._isMultipart()) throw new Error('Response is not text');\n return this._text;\n};\n\n/**\n * @return {object}\n */\nApiResponse.prototype.json = function() {\n if (!this._isJson()) throw new Error('Response is not JSON');\n if (!this._json) {\n this._json = this._text ? JSON.parse(this._text) : null;\n }\n return this._json;\n};\n\n/**\n * @param [skipOKCheck]\n * @return {string}\n */\nApiResponse.prototype.error = function(skipOKCheck) {\n\n if (this.ok() && !skipOKCheck) return null;\n\n var message = (this._response && this._response.status ? this._response.status + ' ' : '') +\n (this._response && this._response.statusText ? this._response.statusText : '');\n\n try {\n\n if (this.json().message) message = this.json().message;\n if (this.json().error_description) message = this.json().error_description;\n if (this.json().description) message = this.json().description;\n\n } catch (e) {}\n\n return message;\n\n};\n\n/**\n * If it is not known upfront what would be the response, client code can treat any response as multipart\n * @return {ApiResponse[]}\n */\nApiResponse.prototype.toMultipart = function() {\n if (!this._isMultipart()) return [this];\n return this.multipart();\n};\n\n/**\n * @return {ApiResponse[]}\n */\nApiResponse.prototype.multipart = function() {\n\n if (!this._isMultipart()) throw new Error('Response is not multipart');\n\n if (!this._multipart.length) {\n\n // Step 1. Split multipart response\n\n var text = this.text();\n\n if (!text) throw new Error('No response body');\n\n var boundary = this._getContentType().match(/boundary=([^;]+)/i)[1];\n\n if (!boundary) throw new Error('Cannot find boundary');\n\n var parts = text.toString().split(ApiResponse._boundarySeparator + boundary);\n\n if (parts[0].trim() === '') parts.shift();\n if (parts[parts.length - 1].trim() == ApiResponse._boundarySeparator) parts.pop();\n\n if (parts.length < 1) throw new Error('No parts in body');\n\n // Step 2. Parse status info\n\n var statusInfo = this._create(parts.shift(), this._response.status, this._response.statusText).json();\n\n // Step 3. Parse all other parts\n\n this._multipart = parts.map(function(part, i) {\n\n var status = statusInfo.response[i].status;\n\n return this._create(part, status);\n\n }.bind(this));\n\n }\n\n return this._multipart;\n\n};\n\n/**\n * @private\n */\nApiResponse.prototype._isContentType = function(contentType) {\n return this._getContentType().indexOf(contentType) > -1;\n};\n\n/**\n * @private\n */\nApiResponse.prototype._getContentType = function() {\n return this._response.headers.get(ApiResponse._contentType) || '';\n};\n\n/**\n * @private\n */\nApiResponse.prototype._isMultipart = function() {\n return this._isContentType(ApiResponse._multipartContentType);\n};\n\n/**\n * @private\n */\nApiResponse.prototype._isJson = function() {\n return this._isContentType(ApiResponse._jsonContentType);\n};\n\n/**\n * Method is used to create ApiResponse object from string parts of multipart/mixed response\n * @param {string} [text]\n * @param {number} [status]\n * @param {string} [statusText]\n * @private\n * @return {ApiResponse}\n */\nApiResponse.prototype._create = function(text, status, statusText) {\n\n text = text || '';\n status = status || 200;\n statusText = statusText || 'OK';\n\n text = text.replace(/\\r/g, '');\n\n var headers = new this._externals.Headers(),\n headersAndBody = text.split(ApiResponse._bodySeparator),\n headersText = (headersAndBody.length > 1) ? headersAndBody.shift() : '';\n\n text = headersAndBody.length > 0 ? headersAndBody.join(ApiResponse._bodySeparator) : null;\n\n (headersText || '')\n .split('\\n')\n .forEach(function(header) {\n\n var split = header.trim().split(ApiResponse._headerSeparator),\n key = split.shift().trim(),\n value = split.join(ApiResponse._headerSeparator).trim();\n\n if (key) headers.append(key, value);\n\n });\n\n var response = new this._externals.Response(text, {\n headers: headers,\n status: status,\n statusText: statusText\n });\n\n return new ApiResponse({\n externals: this._externals,\n request: null,\n response: response,\n responseText: text\n });\n\n};\n\nmodule.exports = ApiResponse;\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/http/ApiResponse.js\n ** module id = 7\n ** module chunks = 0 1\n **/","'use strict';\n\nexports.decode = exports.parse = require('./decode');\nexports.encode = exports.stringify = require('./encode');\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/querystring/index.js\n ** module id = 8\n ** module chunks = 0 1\n **/","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n// If obj.hasOwnProperty has been overridden, then calling\n// obj.hasOwnProperty(prop) will break.\n// See: https://github.com/joyent/node/issues/1707\nfunction hasOwnProperty(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n\nmodule.exports = function(qs, sep, eq, options) {\n sep = sep || '&';\n eq = eq || '=';\n var obj = {};\n\n if (typeof qs !== 'string' || qs.length === 0) {\n return obj;\n }\n\n var regexp = /\\+/g;\n qs = qs.split(sep);\n\n var maxKeys = 1000;\n if (options && typeof options.maxKeys === 'number') {\n maxKeys = options.maxKeys;\n }\n\n var len = qs.length;\n // maxKeys <= 0 means that we should not limit keys count\n if (maxKeys > 0 && len > maxKeys) {\n len = maxKeys;\n }\n\n for (var i = 0; i < len; ++i) {\n var x = qs[i].replace(regexp, '%20'),\n idx = x.indexOf(eq),\n kstr, vstr, k, v;\n\n if (idx >= 0) {\n kstr = x.substr(0, idx);\n vstr = x.substr(idx + 1);\n } else {\n kstr = x;\n vstr = '';\n }\n\n k = decodeURIComponent(kstr);\n v = decodeURIComponent(vstr);\n\n if (!hasOwnProperty(obj, k)) {\n obj[k] = v;\n } else if (Array.isArray(obj[k])) {\n obj[k].push(v);\n } else {\n obj[k] = [obj[k], v];\n }\n }\n\n return obj;\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/querystring/decode.js\n ** module id = 9\n ** module chunks = 0 1\n **/","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nvar stringifyPrimitive = function(v) {\n switch (typeof v) {\n case 'string':\n return v;\n\n case 'boolean':\n return v ? 'true' : 'false';\n\n case 'number':\n return isFinite(v) ? v : '';\n\n default:\n return '';\n }\n};\n\nmodule.exports = function(obj, sep, eq, name) {\n sep = sep || '&';\n eq = eq || '=';\n if (obj === null) {\n obj = undefined;\n }\n\n if (typeof obj === 'object') {\n return Object.keys(obj).map(function(k) {\n var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;\n if (Array.isArray(obj[k])) {\n return obj[k].map(function(v) {\n return ks + encodeURIComponent(stringifyPrimitive(v));\n }).join(sep);\n } else {\n return ks + encodeURIComponent(stringifyPrimitive(obj[k]));\n }\n }).join(sep);\n\n }\n\n if (!name) return '';\n return encodeURIComponent(stringifyPrimitive(name)) + eq +\n encodeURIComponent(stringifyPrimitive(obj));\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/querystring/encode.js\n ** module id = 10\n ** module chunks = 0 1\n **/","var pubnub = require(\"pubnub\");\nvar es6Promise = require(\"es6-promise\");\nvar FetchPonyfill = require(\"fetch-ponyfill\");\n\nvar root = (typeof window !== \"undefined\" && window) ||\n (typeof global !== \"undefined\" && global) ||\n (function(){ return this; })();\n\n/**\n * @constructor\n * @param {PUBNUB} [options.PUBNUB]\n * @param {function(new:Promise)} [options.Promise]\n * @param {Storage} [options.localStorage]\n * @param {fetch} [options.fetch]\n * @param {function(new:Request)} [options.Request]\n * @param {function(new:Response)} [options.Response]\n * @param {function(new:Headers)} [options.Headers]\n * @property {PUBNUB} PUBNUB\n * @property {Storage} localStorage\n * @property {function(new:Promise)} Promise\n * @property {fetch} fetch\n * @property {function(new:Request)} Request\n * @property {function(new:Response)} Response\n * @property {function(new:Headers)} Headers\n */\nfunction Externals(options) {\n\n options = options || {};\n\n this.PUBNUB = options.PUBNUB || root.PUBNUB || pubnub;\n this.localStorage = options.localStorage || ((typeof root.localStorage !== 'undefined') ? root.localStorage : {});\n this.Promise = options.Promise || root.Promise || (es6Promise && es6Promise.Promise);\n\n var fetchPonyfill = FetchPonyfill ? FetchPonyfill({Promise: this.Promise}) : {};\n\n this.fetch = options.fetch || root.fetch || fetchPonyfill.fetch;\n this.Request = options.Request || root.Request || fetchPonyfill.Request;\n this.Response = options.Response || root.Response || fetchPonyfill.Response;\n this.Headers = options.Headers || root.Headers || fetchPonyfill.Headers;\n\n if (!this.fetch || !this.Response || !this.Request || !this.Headers) {\n throw new Error('Fetch API is missing');\n }\n\n if (!this.Promise) {\n throw new Error('Promise is missing');\n }\n\n if (!this.localStorage) {\n throw new Error('LocalStorage is missing');\n }\n\n if (!this.PUBNUB) {\n throw new Error('PUBNUB is missing');\n }\n\n}\n\nmodule.exports = Externals;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/core/Externals.js\n ** module id = 11\n ** module chunks = 0 1\n **/","module.exports = __WEBPACK_EXTERNAL_MODULE_12__;\n\n\n/*****************\n ** WEBPACK FOOTER\n ** external {\"amd\":\"pubnub\"}\n ** module id = 12\n ** module chunks = 0 1\n **/","module.exports = __WEBPACK_EXTERNAL_MODULE_13__;\n\n\n/*****************\n ** WEBPACK FOOTER\n ** external {\"amd\":\"es6-promise\"}\n ** module id = 13\n ** module chunks = 0 1\n **/","module.exports = __WEBPACK_EXTERNAL_MODULE_14__;\n\n\n/*****************\n ** WEBPACK FOOTER\n ** external {\"amd\":\"fetch-ponyfill\"}\n ** module id = 14\n ** module chunks = 0 1\n **/","var EventEmitter = require(\"events\").EventEmitter;\nvar qs = require(\"querystring\");\nvar objectAssign = require('object-assign');\nvar Auth = require(\"./Auth\");\nvar Constants = require(\"../core/Constants\");\nvar ApiResponse = require(\"../http/ApiResponse\");\n\n/**\n * @constructor\n * @param {string} options.server\n * @param {string} options.appSecret\n * @param {string} options.appKey\n * @param {string} [options.appName]\n * @param {string} [options.appVersion]\n * @param {string} [options.redirectUri]\n * @param {int} [options.refreshDelayMs]\n * @param {int} [options.refreshHandicapMs]\n * @param {boolean} [options.clearCacheOnRefreshError]\n * @param {Externals} options.externals\n * @param {Cache} options.cache\n * @param {Client} options.client\n * @property {Externals} _externals\n * @property {Cache} _cache\n * @property {Client} _client\n * @property {Promise} _refreshPromise\n * @property {Auth} _auth\n */\nfunction Platform(options) {\n\n EventEmitter.call(this);\n\n this.events = {\n beforeLogin: 'beforeLogin',\n loginSuccess: 'loginSuccess',\n loginError: 'loginError',\n beforeRefresh: 'beforeRefresh',\n refreshSuccess: 'refreshSuccess',\n refreshError: 'refreshError',\n beforeLogout: 'beforeLogout',\n logoutSuccess: 'logoutSuccess',\n logoutError: 'logoutError'\n };\n\n options = options || {};\n\n /** @private */\n this._server = options.server;\n\n /** @private */\n this._appKey = options.appKey;\n\n /** @private */\n this._appSecret = options.appSecret;\n\n /** @private */\n this._redirectUri = options.redirectUri || '';\n\n /** @private */\n this._refreshDelayMs = options.refreshDelayMs || 100;\n\n /** @private */\n this._clearCacheOnRefreshError = typeof options.clearCacheOnRefreshError !== 'undefined' ?\n options.clearCacheOnRefreshError :\n true;\n\n /** @private */\n this._userAgent = (options.appName ?\n (options.appName + (options.appVersion ? '/' + options.appVersion : '')) + ' ' :\n '') + 'RCJSSDK/' + Constants.version;\n\n /** @private */\n this._externals = options.externals;\n\n /** @private */\n this._cache = options.cache;\n\n /** @private */\n this._client = options.client;\n\n /** @private */\n this._refreshPromise = null;\n\n /** @private */\n this._auth = new Auth({\n cache: this._cache,\n cacheId: Platform._cacheId,\n refreshHandicapMs: options.refreshHandicapMs\n });\n\n}\n\nPlatform._urlPrefix = '/restapi';\nPlatform._apiVersion = 'v1.0';\nPlatform._tokenEndpoint = '/restapi/oauth/token';\nPlatform._revokeEndpoint = '/restapi/oauth/revoke';\nPlatform._authorizeEndpoint = '/restapi/oauth/authorize';\nPlatform._cacheId = 'platform';\n\nPlatform.prototype = Object.create(EventEmitter.prototype);\n\nPlatform.prototype.delay = function(timeout) {\n return new this._externals.Promise(function(resolve, reject) {\n setTimeout(function() {\n resolve(null);\n }, timeout);\n });\n};\n\n/**\n * @return {Auth}\n */\nPlatform.prototype.auth = function() {\n return this._auth;\n};\n\n/**\n * @return {Client}\n */\nPlatform.prototype.client = function() {\n return this._client;\n};\n\n/**\n * @param {string} path\n * @param {object} [options]\n * @param {boolean} [options.addServer]\n * @param {string} [options.addMethod]\n * @param {boolean} [options.addToken]\n * @return {string}\n */\nPlatform.prototype.createUrl = function(path, options) {\n\n path = path || '';\n options = options || {};\n\n var builtUrl = '',\n hasHttp = path.indexOf('http://') != -1 || path.indexOf('https://') != -1;\n\n if (options.addServer && !hasHttp) builtUrl += this._server;\n\n if (path.indexOf(Platform._urlPrefix) == -1 && !hasHttp) builtUrl += Platform._urlPrefix + '/' + Platform._apiVersion;\n\n builtUrl += path;\n\n if (options.addMethod || options.addToken) builtUrl += (path.indexOf('?') > -1 ? '&' : '?');\n\n if (options.addMethod) builtUrl += '_method=' + options.addMethod;\n if (options.addToken) builtUrl += (options.addMethod ? '&' : '') + 'access_token=' + this._auth.accessToken();\n\n return builtUrl;\n\n};\n\n/**\n * @param {string} [options.redirectUri] Overrides default RedirectURI\n * @param {string} [options.state]\n * @param {string} [options.brandId]\n * @param {string} [options.display]\n * @param {string} [options.prompt]\n * @param {boolean} [options.implicit] Use Implicit Grant flow\n * @return {string}\n */\nPlatform.prototype.loginUrl = function(options) {\n\n options = options || {};\n\n return this.createUrl(Platform._authorizeEndpoint + '?' + qs.stringify({\n 'response_type': options.implicit ? 'token' : 'code',\n 'redirect_uri': options.redirectUri || this._redirectUri,\n 'client_id': this._appKey,\n 'state': options.state || '',\n 'brand_id': options.brandId || '',\n 'display': options.display || '',\n 'prompt': options.prompt || ''\n }), {addServer: true});\n\n};\n\n/**\n * @param {string} url\n * @return {Object}\n */\nPlatform.prototype.parseLoginRedirect = function(url) {\n\n function getParts(url, separator) {\n return url.split(separator).reverse()[0];\n }\n\n var response = (url.indexOf('#') === 0 && getParts(url, '#')) ||\n (url.indexOf('?') === 0 && getParts(url, '?')) ||\n null;\n\n if (!response) throw new Error('Unable to parse response');\n\n var queryString = qs.parse(response);\n\n if (!queryString) throw new Error('Unable to parse response');\n\n var error = queryString.error_description || queryString.error;\n\n if (error) {\n var e = new Error(error);\n e.error = queryString.error;\n throw e;\n }\n\n return queryString;\n\n};\n\n/**\n * Convenience method to handle 3-legged OAuth\n *\n * Attention! This is an experimental method and it's signature and behavior may change without notice.\n *\n * @experimental\n * @param {string} options.url\n * @param {number} [options.width]\n * @param {number} [options.height]\n * @param {object} [options.login] additional options for login()\n * @param {string} [options.origin]\n * @param {string} [options.property] name of window.postMessage's event data property\n * @param {string} [options.target] target for window.open()\n * @return {Promise}\n */\nPlatform.prototype.loginWindow = function(options) {\n\n return new this._externals.Promise(function(resolve, reject) {\n\n if (typeof window === 'undefined') throw new Error('This method can be used only in browser');\n\n if (!options.url) throw new Error('Missing mandatory URL parameter');\n\n options = options || {};\n options.url = options.url || 400;\n options.width = options.width || 400;\n options.height = options.height || 600;\n options.origin = options.origin || window.location.origin;\n options.property = options.property || Constants.authResponseProperty;\n options.target = options.target || '_blank';\n\n var dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left;\n var dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top;\n\n var width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;\n var height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;\n\n var left = ((width / 2) - (options.width / 2)) + dualScreenLeft;\n var top = ((height / 2) - (options.height / 2)) + dualScreenTop;\n var win = window.open(options.url, '_blank', (options.target == '_blank') ? 'scrollbars=yes, status=yes, width=' + options.width + ', height=' + options.height + ', left=' + left + ', top=' + top : '');\n\n if(!win) {\n throw new Error('Could not open login window. Please allow popups for this site');\n }\n\n if (win.focus) win.focus();\n\n var eventMethod = window.addEventListener ? 'addEventListener' : 'attachEvent';\n var eventRemoveMethod = eventMethod == 'addEventListener' ? 'removeEventListener' : 'detachEvent';\n var messageEvent = eventMethod == 'addEventListener' ? 'message' : 'onmessage';\n\n var eventListener = function(e) {\n\n try {\n\n if (e.origin != options.origin) return;\n if (!e.data || !e.data[options.property]) return; // keep waiting\n\n win.close();\n window[eventRemoveMethod](messageEvent, eventListener);\n\n\n var loginOptions = this.parseLoginRedirect(e.data[options.property]);\n\n if (!loginOptions.code && !loginOptions.access_token) throw new Error('No authorization code or token');\n\n resolve(loginOptions);\n\n /* jshint -W002 */\n } catch (e) {\n reject(e);\n }\n\n }.bind(this);\n\n window[eventMethod](messageEvent, eventListener, false);\n\n }.bind(this));\n\n};\n\n/**\n * @return {Promise}\n */\nPlatform.prototype.loggedIn = function() {\n\n return this.ensureLoggedIn().then(function() {\n return true;\n }).catch(function() {\n return false;\n });\n\n};\n\n/**\n * @param {string} options.username\n * @param {string} options.password\n * @param {string} [options.extension]\n * @param {string} [options.code]\n * @param {string} [options.redirectUri]\n * @param {string} [options.endpointId]\n * @param {string} [options.accessTokenTtl]\n * @param {string} [options.refreshTokenTtl]\n * @param {string} [options.access_token]\n * @returns {Promise}\n */\nPlatform.prototype.login = function(options) {\n\n return (new this._externals.Promise(function(resolve) {\n\n options = options || {};\n\n this.emit(this.events.beforeLogin);\n\n var body = {};\n\n if (options.access_token) {\n\n //TODO Potentially make a request to /oauth/tokeninfo\n return resolve(options);\n\n }\n\n if (!options.code) {\n\n body.grant_type = 'password';\n body.username = options.username;\n body.password = options.password;\n body.extension = options.extension || '';\n\n } else if (options.code) {\n\n body.grant_type = 'authorization_code';\n body.code = options.code;\n body.redirect_uri = options.redirectUri || this._redirectUri;\n //body.client_id = this.getCredentials().key; // not needed\n\n }\n\n if (options.endpointId) body.endpoint_id = options.endpointId;\n if (options.accessTokenTtl) body.accessTokenTtl = options.accessTokenTtl;\n if (options.refreshTokenTtl) body.refreshTokenTtl = options.refreshTokenTtl;\n\n resolve(this._tokenRequest(Platform._tokenEndpoint, body));\n\n }.bind(this))).then(function(res) {\n\n var apiResponse = res.json ? res : null;\n var json = apiResponse && apiResponse.json() || res;\n\n this._auth.setData(json);\n\n this.emit(this.events.loginSuccess, apiResponse);\n\n return apiResponse;\n\n }.bind(this)).catch(function(e) {\n\n if (this._clearCacheOnRefreshError) {\n this._cache.clean();\n }\n\n this.emit(this.events.loginError, e);\n\n throw e;\n\n }.bind(this));\n\n};\n\n/**\n * @returns {Promise}\n * @private\n */\nPlatform.prototype._refresh = function() {\n\n return this.delay(this._refreshDelayMs).then(function() {\n\n this.emit(this.events.beforeRefresh);\n\n // Perform sanity checks\n if (!this._auth.refreshToken()) throw new Error('Refresh token is missing');\n if (!this._auth.refreshTokenValid()) throw new Error('Refresh token has expired');\n\n return this._tokenRequest(Platform._tokenEndpoint, {\n \"grant_type\": \"refresh_token\",\n \"refresh_token\": this._auth.refreshToken(),\n \"access_token_ttl\": this._auth.data().expires_in + 1,\n \"refresh_token_ttl\": this._auth.data().refresh_token_expires_in + 1\n });\n\n }.bind(this)).then(function(/** @type {ApiResponse} */ res) {\n\n var json = res.json();\n\n if (!json.access_token) {\n throw this._client.makeError(new Error('Malformed OAuth response'), res);\n }\n\n this._auth.setData(json);\n\n this.emit(this.events.refreshSuccess, res);\n\n return res;\n\n }.bind(this)).catch(function(e) {\n\n e = this._client.makeError(e);\n\n if (this._clearCacheOnRefreshError) {\n this._cache.clean();\n }\n\n this.emit(this.events.refreshError, e);\n\n throw e;\n\n }.bind(this));\n\n};\n\n/**\n * @returns {Promise}\n */\nPlatform.prototype.refresh = function() {\n\n if (!this._refreshPromise) {\n\n this._refreshPromise = this._refresh()\n .then(function(res) {\n this._refreshPromise = null;\n return res;\n }.bind(this))\n .catch(function(e) {\n this._refreshPromise = null;\n throw e;\n }.bind(this));\n\n }\n\n return this._refreshPromise;\n\n};\n\n/**\n * @returns {Promise}\n */\nPlatform.prototype.logout = function() {\n\n return (new this._externals.Promise(function(resolve) {\n\n this.emit(this.events.beforeLogout);\n\n resolve(this._tokenRequest(Platform._revokeEndpoint, {\n token: this._auth.accessToken()\n }));\n\n }.bind(this))).then(function(res) {\n\n this._cache.clean();\n\n this.emit(this.events.logoutSuccess, res);\n\n return res;\n\n }.bind(this)).catch(function(e) {\n\n this.emit(this.events.logoutError, e);\n\n throw e;\n\n }.bind(this));\n\n};\n\n/**\n * @param {Request} request\n * @param {object} [options]\n * @param {boolean} [options.skipAuthCheck]\n * @return {Promise}\n */\nPlatform.prototype.inflateRequest = function(request, options) {\n\n options = options || {};\n\n if (options.skipAuthCheck) return this._externals.Promise.resolve(request);\n\n return this.ensureLoggedIn().then(function() {\n\n request.headers.set('X-User-Agent', this._userAgent);\n request.headers.set('Client-Id', this._appKey);\n request.headers.set('Authorization', this._authHeader());\n //request.url = this.createUrl(request.url, {addServer: true}); //FIXME Spec prevents this...\n\n return request;\n\n }.bind(this));\n\n};\n\n/**\n * @param {Request} request\n * @param {object} [options]\n * @param {boolean} [options.skipAuthCheck]\n * @param {boolean} [options.retry] Will be set by this method if SDK makes second request\n * @return {Promise}\n */\nPlatform.prototype.sendRequest = function(request, options) {\n\n return this.inflateRequest(request, options).then(function(request) {\n\n options = options || {};\n\n return this._client.sendRequest(request);\n\n }.bind(this)).catch(function(e) {\n\n // Guard is for errors that come from polling\n if (!e.apiResponse || !e.apiResponse.response() ||\n (e.apiResponse.response().status != ApiResponse._unauthorizedStatus) ||\n options.retry) throw e;\n\n this._auth.cancelAccessToken();\n\n options.retry = true;\n\n return this.sendRequest(request, options);\n\n }.bind(this));\n\n};\n\n/**\n * General purpose function to send anything to server\n * @param {string} options.url\n * @param {object} [options.body]\n * @param {string} [options.method]\n * @param {object} [options.query]\n * @param {object} [options.headers]\n * @param {boolean} [options.skipAuthCheck]\n * @return {Promise}\n */\nPlatform.prototype.send = function(options) {\n\n options = options || {};\n\n //FIXME https://github.com/bitinn/node-fetch/issues/43\n options.url = this.createUrl(options.url, {addServer: true});\n\n return this.sendRequest(this._client.createRequest(options), options);\n\n};\n\n/**\n * @param {string} url\n * @param {object} [query]\n * @param {object} [options]\n * @param {object} [options.headers]\n * @param {boolean} [options.skipAuthCheck]\n * @return {Promise}\n */\nPlatform.prototype.get = function(url, query, options) {\n return this.send(objectAssign({}, {method: 'GET', url: url, query: query}, options));\n};\n\n/**\n * @param {string} url\n * @param {object} body\n * @param {object} [query]\n * @param {object} [options]\n * @param {object} [options.headers]\n * @param {boolean} [options.skipAuthCheck]\n * @return {Promise}\n */\nPlatform.prototype.post = function(url, body, query, options) {\n return this.send(objectAssign({}, {method: 'POST', url: url, query: query, body: body}, options));\n};\n\n/**\n * @param {string} url\n * @param {object} [body]\n * @param {object} [query]\n * @param {object} [options]\n * @param {object} [options.headers]\n * @param {boolean} [options.skipAuthCheck]\n * @return {Promise}\n */\nPlatform.prototype.put = function(url, body, query, options) {\n return this.send(objectAssign({}, {method: 'PUT', url: url, query: query, body: body}, options));\n};\n\n/**\n * @param {string} url\n * @param {string} [query]\n * @param {object} [options]\n * @param {object} [options.headers]\n * @param {boolean} [options.skipAuthCheck]\n * @return {Promise}\n */\nPlatform.prototype['delete'] = function(url, query, options) {\n return this.send(objectAssign({}, {method: 'DELETE', url: url, query: query}, options));\n};\n\nPlatform.prototype.ensureLoggedIn = function() {\n if (this._isAccessTokenValid()) return this._externals.Promise.resolve();\n return this.refresh();\n};\n\n/**\n * @param path\n * @param body\n * @return {Promise.}\n * @private\n */\nPlatform.prototype._tokenRequest = function(path, body) {\n\n return this.send({\n url: path,\n skipAuthCheck: true,\n body: body,\n method: 'POST',\n headers: {\n 'Authorization': 'Basic ' + this._apiKey(),\n 'Content-Type': ApiResponse._urlencodedContentType\n }\n });\n\n};\n\n/**\n * @return {boolean}\n * @private\n */\nPlatform.prototype._isAccessTokenValid = function() {\n return this._auth.accessTokenValid();\n};\n\n/**\n * @return {string}\n * @private\n */\nPlatform.prototype._apiKey = function() {\n var apiKey = this._appKey + ':' + this._appSecret;\n return (typeof btoa == 'function') ? btoa(apiKey) : new Buffer(apiKey).toString('base64');\n};\n\n/**\n * @return {string}\n * @private\n */\nPlatform.prototype._authHeader = function() {\n var token = this._auth.accessToken();\n return this._auth.tokenType() + (token ? ' ' + token : '');\n};\n\nmodule.exports = Platform;\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/platform/Platform.js\n ** module id = 15\n ** module chunks = 0 1\n **/","/**\n * @param {Cache} options.cache\n * @param {string} options.cacheId\n * @param {int} [options.refreshHandicapMs]\n * @constructor\n * @property {Cache} _cache\n * @property {int} _refreshHandicapMs\n * @property {string} _cacheId\n */\nfunction Auth(options) {\n\n /** @private */\n this._cache = options.cache;\n\n /** @private */\n this._cacheId = options.cacheId;\n\n /** @private */\n this._refreshHandicapMs = options.refreshHandicapMs || 60 * 1000; // 1 minute\n\n}\n\nAuth.prototype.accessToken = function() {\n return this.data().access_token;\n};\n\nAuth.prototype.refreshToken = function() {\n return this.data().refresh_token;\n};\n\nAuth.prototype.tokenType = function() {\n return this.data().token_type;\n};\n\n/**\n * @return {{token_type: string, access_token: string, expires_in: number, refresh_token: string, refresh_token_expires_in: number}}\n */\nAuth.prototype.data = function() {\n\n return this._cache.getItem(this._cacheId) || {\n token_type: '',\n access_token: '',\n expires_in: 0,\n refresh_token: '',\n refresh_token_expires_in: 0\n };\n\n};\n\n/**\n * @param {object} newData\n * @return {Auth}\n */\nAuth.prototype.setData = function(newData) {\n\n newData = newData || {};\n\n var data = this.data();\n\n Object.keys(newData).forEach(function(key) {\n data[key] = newData[key];\n });\n\n data.expire_time = Date.now() + (data.expires_in * 1000);\n data.refresh_token_expire_time = Date.now() + (data.refresh_token_expires_in * 1000);\n\n this._cache.setItem(this._cacheId, data);\n\n return this;\n\n};\n\n/**\n * Check if there is a valid (not expired) access token\n * @return {boolean}\n */\nAuth.prototype.accessTokenValid = function() {\n\n var authData = this.data();\n return (authData.expire_time - this._refreshHandicapMs > Date.now());\n\n};\n\n/**\n * Check if there is a valid (not expired) access token\n * @return {boolean}\n */\nAuth.prototype.refreshTokenValid = function() {\n\n return (this.data().refresh_token_expire_time > Date.now());\n\n};\n\n/**\n * @return {Auth}\n */\nAuth.prototype.cancelAccessToken = function() {\n\n return this.setData({\n access_token: '',\n expires_in: 0\n });\n\n};\n\nmodule.exports = Auth;\n\n//export interface IAuthData {\n// remember?:boolean;\n// token_type?:string;\n// access_token?:string;\n// expires_in?:number; // actually it's string\n// expire_time?:number;\n// refresh_token?:string;\n// refresh_token_expires_in?:number; // actually it's string\n// refresh_token_expire_time?:number;\n// scope?:string;\n//}\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/platform/Auth.js\n ** module id = 16\n ** module chunks = 0 1\n **/","var version = process.env.RCSDK_VERSION;\n\n// This will become false during the Webpack build, so no traces of package.json will be there\nif (!process.env.RCSDK_VERSION) {\n version = require('../../package.json').version;\n}\n\nmodule.exports = {\n version: version,\n authResponseProperty: 'RCAuthorizationResponse'\n};\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/core/Constants.js\n ** module id = 17\n ** module chunks = 0 1\n **/","var EventEmitter = require(\"events\").EventEmitter;\n\n/**\n * @param {Platform} options.platform\n * @param {Externals} options.externals\n * @param {int} [options.pollInterval]\n * @param {int} [options.renewHandicapMs]\n * @property {Externals} _externals\n * @property {Platform} _platform\n * @property {int} _pollInterval\n * @property {int} _renewHandicapMs\n * @property {PUBNUB} _pubnub\n * @property {string} _pubnubLastChannel\n * @property {int} _timeout\n * @property {ISubscription} _subscription\n * @constructor\n */\nfunction Subscription(options) {\n\n EventEmitter.call(this);\n\n options = options || {};\n\n this.events = {\n notification: 'notification',\n removeSuccess: 'removeSuccess',\n removeError: 'removeError',\n renewSuccess: 'renewSuccess',\n renewError: 'renewError',\n subscribeSuccess: 'subscribeSuccess',\n subscribeError: 'subscribeError'\n };\n\n /** @private */\n this._externals = options.externals;\n\n /** @private */\n this._platform = options.platform;\n\n /** @private */\n this._pollInterval = options.pollInterval || 10 * 1000;\n\n /** @private */\n this._renewHandicapMs = options.renewHandicapMs || 2 * 60 * 1000;\n\n /** @private */\n this._pubnub = null;\n\n /** @private */\n this._pubnubLastChannel = null;\n\n /** @private */\n this._timeout = null;\n\n /** @private */\n this._subscription = null;\n\n}\n\nSubscription.prototype = Object.create(EventEmitter.prototype);\n\nSubscription.prototype.subscribed = function() {\n\n var subscription = this.subscription();\n\n return !!(subscription.id &&\n subscription.deliveryMode &&\n subscription.deliveryMode.subscriberKey &&\n subscription.deliveryMode.address);\n\n};\n\n/**\n * @return {boolean}\n */\nSubscription.prototype.alive = function() {\n return this.subscribed() && Date.now() < this.expirationTime();\n};\n\n/**\n * @return {boolean}\n */\nSubscription.prototype.expired = function() {\n if (!this.subscribed()) return true;\n return !this.subscribed() || Date.now() > this.subscription().expirationTime;\n};\n\nSubscription.prototype.expirationTime = function() {\n return new Date(this.subscription().expirationTime || 0).getTime() - this._renewHandicapMs;\n};\n\n/**\n * @param {ISubscription} subscription\n * @return {Subscription}\n */\nSubscription.prototype.setSubscription = function(subscription) {\n\n subscription = subscription || {};\n\n this._clearTimeout();\n this._setSubscription(subscription);\n this._subscribeAtPubnub();\n this._setTimeout();\n\n return this;\n\n};\n\n/**\n * @return {ISubscription}\n */\nSubscription.prototype.subscription = function() {\n return this._subscription || {};\n};\n\n/**\n * Creates or updates subscription if there is an active one\n * @returns {Promise}\n */\nSubscription.prototype.register = function() {\n\n if (this.alive()) {\n return this.renew();\n } else {\n return this.subscribe();\n }\n\n};\n\n/**\n * @return {string[]}\n */\nSubscription.prototype.eventFilters = function() {\n return this.subscription().eventFilters || [];\n};\n\n/**\n * @param {string[]} events\n * @return {Subscription}\n */\nSubscription.prototype.addEventFilters = function(events) {\n this.setEventFilters(this.eventFilters().concat(events));\n return this;\n};\n\n/**\n * @param {string[]} events\n * @return {Subscription}\n */\nSubscription.prototype.setEventFilters = function(events) {\n var subscription = this.subscription();\n subscription.eventFilters = events;\n this._setSubscription(subscription);\n return this;\n};\n\n/**\n * @returns {Promise}\n */\nSubscription.prototype.subscribe = function() {\n\n return (new this._externals.Promise(function(resolve) {\n\n this._clearTimeout();\n\n if (!this.eventFilters().length) throw new Error('Events are undefined');\n\n resolve(this._platform.post('/subscription', {\n eventFilters: this._getFullEventFilters(),\n deliveryMode: {\n transportType: 'PubNub'\n }\n }));\n\n }.bind(this))).then(function(response) {\n\n var json = response.json();\n\n this.setSubscription(json)\n .emit(this.events.subscribeSuccess, response);\n\n return response;\n\n }.bind(this)).catch(function(e) {\n\n e = this._platform.client().makeError(e);\n\n this.reset()\n .emit(this.events.subscribeError, e);\n\n throw e;\n\n }.bind(this));\n\n};\n\n/**\n * @returns {Promise}\n */\nSubscription.prototype.renew = function() {\n\n return (new this._externals.Promise(function(resolve) {\n\n this._clearTimeout();\n\n if (!this.subscribed()) throw new Error('No subscription');\n\n if (!this.eventFilters().length) throw new Error('Events are undefined');\n\n resolve(this._platform.put('/subscription/' + this.subscription().id, {\n eventFilters: this._getFullEventFilters()\n }));\n\n }.bind(this))).then(function(response) {\n\n var json = response.json();\n\n this.setSubscription(json)\n .emit(this.events.renewSuccess, response);\n\n return response;\n\n }.bind(this)).catch(function(e) {\n\n e = this._platform.client().makeError(e);\n\n this.reset()\n .emit(this.events.renewError, e);\n\n throw e;\n\n }.bind(this));\n\n};\n\n/**\n * @returns {Promise}\n */\nSubscription.prototype.remove = function() {\n\n return (new this._externals.Promise(function(resolve) {\n\n if (!this.subscribed()) throw new Error('No subscription');\n\n resolve(this._platform.delete('/subscription/' + this.subscription().id));\n\n }.bind(this))).then(function(response) {\n\n this.reset()\n .emit(this.events.removeSuccess, response);\n\n return response;\n\n }.bind(this)).catch(function(e) {\n\n e = this._platform.client().makeError(e);\n\n this.emit(this.events.removeError, e);\n\n throw e;\n\n }.bind(this));\n\n};\n\n/**\n * @returns {Promise}\n */\nSubscription.prototype.resubscribe = function() {\n var filters = this.eventFilters();\n return this.reset().setEventFilters(filters).subscribe();\n};\n\n/**\n * Remove subscription and disconnect from PUBNUB\n * This method resets subscription at client side but backend is not notified\n * @return {Subscription}\n */\nSubscription.prototype.reset = function() {\n this._clearTimeout();\n if (this.subscribed() && this._pubnub) this._pubnub.unsubscribe({channel: this.subscription().deliveryMode.address});\n this._setSubscription(null);\n return this;\n};\n\n/**\n * @param subscription\n * @private\n */\nSubscription.prototype._setSubscription = function(subscription) {\n this._subscription = subscription;\n};\n\n/**\n * @return {string[]}\n * @private\n */\nSubscription.prototype._getFullEventFilters = function() {\n\n return this.eventFilters().map(function(event) {\n return this._platform.createUrl(event);\n }.bind(this));\n\n};\n\n/**\n * @return {Subscription}\n * @private\n */\nSubscription.prototype._setTimeout = function() {\n\n this._clearTimeout();\n\n if (!this.alive()) throw new Error('Subscription is not alive');\n\n this._timeout = setInterval(function() {\n\n if (this.alive()) return;\n\n if (this.expired()) {\n this.subscribe();\n } else {\n this.renew();\n }\n\n }.bind(this), this._pollInterval);\n\n return this;\n\n};\n\n/**\n * @return {Subscription}\n * @private\n */\nSubscription.prototype._clearTimeout = function() {\n clearInterval(this._timeout);\n return this;\n};\n\nSubscription.prototype._decrypt = function(message) {\n\n if (!this.subscribed()) throw new Error('No subscription');\n\n if (this.subscription().deliveryMode.encryptionKey) {\n\n message = this._externals.PUBNUB.crypto_obj.decrypt(message, this.subscription().deliveryMode.encryptionKey, {\n encryptKey: false,\n keyEncoding: 'base64',\n keyLength: 128,\n mode: 'ecb'\n });\n\n }\n\n return message;\n\n};\n\n/**\n * @param message\n * @return {Subscription}\n * @private\n */\nSubscription.prototype._notify = function(message) {\n this.emit(this.events.notification, this._decrypt(message));\n return this;\n};\n\n/**\n * @return {Subscription}\n * @private\n */\nSubscription.prototype._subscribeAtPubnub = function() {\n\n if (!this.alive()) throw new Error('Subscription is not alive');\n\n var deliveryMode = this.subscription().deliveryMode;\n\n if (this._pubnub) {\n\n if (this._pubnubLastChannel == deliveryMode.address) { // Nothing to update, keep listening to same channel\n return this;\n } else if (this._pubnubLastChannel) { // Need to subscribe to new channel\n this._pubnub.unsubscribe({channel: this._pubnubLastChannel});\n }\n\n // Re-init for new data\n this._pubnub = this._pubnub.init({\n ssl: true,\n subscribe_key: deliveryMode.subscriberKey\n });\n\n } else {\n\n // Init from scratch\n this._pubnub = this._externals.PUBNUB.init({\n ssl: true,\n subscribe_key: deliveryMode.subscriberKey\n });\n\n this._pubnub.ready(); //TODO This may be not needed anymore\n\n }\n\n this._pubnubLastChannel = deliveryMode.address;\n\n this._pubnub.subscribe({\n channel: deliveryMode.address,\n message: this._notify.bind(this),\n connect: function() {}\n });\n\n return this;\n\n};\n\nmodule.exports = Subscription;\n\n/**\n * The complete Triforce, or one or more components of the Triforce.\n * @typedef {Object} ISubscription\n * @property {string} [id]\n * @property {string} [uri]\n * @property {string[]} [eventFilters]\n * @property {string} [expirationTime] Format: 2014-03-12T19:54:35.613Z\n * @property {int} [expiresIn]\n * @property {string} [deliveryMode.transportType]\n * @property {boolean} [deliveryMode.encryption]\n * @property {string} [deliveryMode.address]\n * @property {string} [deliveryMode.subscriberKey]\n * @property {string} [deliveryMode.encryptionKey]\n * @property {string} [deliveryMode.secretKey]\n * @property {string} [creationTime]\n * @property {string} [status] Active\n */\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/subscription/Subscription.js\n ** module id = 18\n ** module chunks = 0 1\n **/","var Subscription = require(\"./Subscription\");\n\n/**\n * @param {Platform} options.platform\n * @param {Externals} options.externals\n * @param {Cache} options.cache\n * @param {string} options.cacheKey\n * @param {int} [options.pollInterval]\n * @param {int} [options.renewHandicapMs]\n * @return {CachedSubscription}\n * @constructor\n * @property {Cache} _cache\n * @extends Subscription\n */\nfunction CachedSubscription(options) {\n\n options = options || {};\n\n if (!options.cacheKey) throw new Error('Cached Subscription requires cacheKey parameter to be defined');\n\n /** @private */\n this._cacheKey = options.cacheKey;\n\n Subscription.call(this, options);\n\n /** @private */\n this._cache = options.cache;\n\n // This is not used in this class\n this._subscription = undefined;\n\n}\n\nCachedSubscription.prototype = Object.create(Subscription.prototype);\n\nCachedSubscription.prototype.subscription = function() {\n return this._cache.getItem(this._cacheKey) || {};\n};\n\nCachedSubscription.prototype._setSubscription = function(subscription) {\n return this._cache.setItem(this._cacheKey, subscription);\n};\n\n/**\n * This function checks whether there are any pre-defined eventFilters in cache and if not -- uses provided as defaults\n * @param {string[]} events\n * @return {CachedSubscription}\n */\nCachedSubscription.prototype.restore = function(events) {\n\n if (!this.eventFilters().length) {\n this.setEventFilters(events);\n }\n\n return this;\n\n};\n\nmodule.exports = CachedSubscription;\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/subscription/CachedSubscription.js\n ** module id = 19\n ** module chunks = 0 1\n **/"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack:///webpack/universalModuleDefinition?5ca6","webpack:///ringcentral.min.js","webpack:///webpack/bootstrap c20b2b45729ee57a5332?7780","webpack:///./src/SDK.js?d032","webpack:///./~/object-assign/index.js?2927","webpack:///./src/core/Cache.js?1256","webpack:///./src/http/Client.js?4230","webpack:///./~/is-plain-object/index.js?2af1","webpack:///./~/isobject/index.js?cf96","webpack:///./~/events/events.js?7c71","webpack:///./src/http/ApiResponse.js?d4a4","webpack:///./~/querystring/index.js?fce8","webpack:///./~/querystring/decode.js?c250","webpack:///./~/querystring/encode.js?e86b","webpack:///./src/core/Externals.js?fdf1","webpack:///external {\"amd\":\"pubnub\"}?3fcf","webpack:///external {\"amd\":\"es6-promise\"}?8a6b","webpack:///external {\"amd\":\"fetch-ponyfill\"}?ec6e","webpack:///./src/platform/Platform.js?8f42","webpack:///./src/platform/Auth.js?cef5","webpack:///./src/core/Constants.js?22d0","webpack:///./src/subscription/Subscription.js?3ae8","webpack:///./src/subscription/CachedSubscription.js?3294"],"names":["root","factory","exports","module","require","undefined","define","amd","this","__WEBPACK_EXTERNAL_MODULE_12__","__WEBPACK_EXTERNAL_MODULE_13__","__WEBPACK_EXTERNAL_MODULE_14__","modules","__webpack_require__","moduleId","installedModules","id","loaded","call","m","c","p","SDK","options","_externals","Externals","_cache","Cache","externals","prefix","cachePrefix","_client","Client","_platform","Platform","objectAssign","client","cache","Subscription","CachedSubscription","Constants","version","server","sandbox","production","prototype","platform","createSubscription","createCachedSubscription","arguments","cacheKey","toString","handleLoginRedirect","origin","response","window","location","hash","search","msg","authResponseProperty","opener","postMessage","toObject","val","TypeError","Object","shouldUseNative","assign","test1","String","getOwnPropertyNames","test2","i","fromCharCode","order2","map","n","join","test3","split","forEach","letter","keys","err","getOwnPropertySymbols","hasOwnProperty","propIsEnumerable","propertyIsEnumerable","target","source","from","symbols","to","s","length","key","_prefix","defaultPrefix","setItem","data","localStorage","_prefixKey","JSON","stringify","removeItem","getItem","item","parse","clean","indexOf","findHeaderName","name","headers","toLowerCase","reduce","res","EventEmitter","events","beforeRequest","requestSuccess","requestError","isPlainObject","ApiResponse","qs","_allowedMethods","create","sendRequest","request","apiResponse","Promise","resolve","emit","_loadResponse","bind","then","receiveResponse","ok","Error","catch","e","makeError","fetch","originalMessage","message","error","createRequest","init","url","method","toUpperCase","credentials","mode","query","Accept","_jsonContentType","body","contentTypeHeaderName","_contentType","contentType","_urlencodedContentType","req","Request","originalBody","isObjectObject","o","isObject","ctor","prot","constructor","Array","isArray","_events","_maxListeners","isFunction","arg","isNumber","isUndefined","defaultMaxListeners","setMaxListeners","isNaN","type","er","handler","len","args","listeners","context","slice","apply","addListener","listener","newListener","push","warned","console","trace","on","once","g","removeListener","fired","list","position","splice","removeAllListeners","ret","listenerCount","evlistener","emitter","_request","_response","_text","responseText","_json","_multipart","_multipartContentType","_headerSeparator","_bodySeparator","_boundarySeparator","_unauthorizedStatus","_isMultipart","_isJson","text","json","skipOKCheck","status","statusText","error_description","description","toMultipart","multipart","boundary","_getContentType","match","parts","trim","shift","pop","statusInfo","_create","part","_isContentType","get","replace","Headers","headersAndBody","headersText","header","value","append","Response","decode","encode","obj","prop","sep","eq","regexp","maxKeys","kstr","vstr","k","v","x","idx","substr","decodeURIComponent","stringifyPrimitive","isFinite","ks","encodeURIComponent","global","PubNub","pubnub","es6Promise","fetchPonyfill","FetchPonyfill","beforeLogin","loginSuccess","loginError","beforeRefresh","refreshSuccess","refreshError","beforeLogout","logoutSuccess","logoutError","_server","_appKey","appKey","_appSecret","appSecret","_redirectUri","redirectUri","_refreshDelayMs","refreshDelayMs","_clearCacheOnRefreshError","clearCacheOnRefreshError","_userAgent","appName","appVersion","_refreshPromise","_auth","Auth","cacheId","_cacheId","refreshHandicapMs","_urlPrefix","_apiVersion","_tokenEndpoint","_revokeEndpoint","_authorizeEndpoint","delay","timeout","reject","setTimeout","auth","createUrl","path","builtUrl","hasHttp","addServer","addMethod","addToken","accessToken","loginUrl","response_type","implicit","redirect_uri","client_id","state","brand_id","brandId","display","prompt","parseLoginRedirect","getParts","separator","reverse","queryString","loginWindow","width","height","property","dualScreenLeft","screenLeft","screen","left","dualScreenTop","screenTop","top","innerWidth","document","documentElement","clientWidth","innerHeight","clientHeight","win","open","focus","eventMethod","addEventListener","eventRemoveMethod","messageEvent","eventListener","close","loginOptions","code","access_token","loggedIn","ensureLoggedIn","login","grant_type","username","password","extension","endpointId","endpoint_id","accessTokenTtl","refreshTokenTtl","_tokenRequest","setData","_refresh","refreshToken","refreshTokenValid","refresh_token","access_token_ttl","expires_in","refresh_token_ttl","refresh_token_expires_in","refresh","logout","token","inflateRequest","skipAuthCheck","set","_authHeader","retry","cancelAccessToken","send","post","put","_isAccessTokenValid","Authorization","_apiKey","Content-Type","accessTokenValid","apiKey","btoa","Buffer","tokenType","_refreshHandicapMs","token_type","newData","expire_time","Date","now","refresh_token_expire_time","authData","notification","removeSuccess","removeError","renewSuccess","renewError","subscribeSuccess","subscribeError","_pollInterval","pollInterval","_renewHandicapMs","renewHandicapMs","_pubnub","_pubnubLastChannel","_timeout","_subscription","subscribed","subscription","deliveryMode","subscriberKey","address","alive","expirationTime","expired","getTime","setSubscription","_clearTimeout","_setSubscription","_subscribeAtPubnub","_setTimeout","register","renew","subscribe","eventFilters","addEventFilters","setEventFilters","concat","_getFullEventFilters","transportType","reset","remove","delete","resubscribe","filters","unsubscribe","channel","event","setInterval","clearInterval","_decrypt","encryptionKey","decrypt","encryptKey","keyEncoding","keyLength","_notify","ssl","subscribe_key","connect","_cacheKey","restore"],"mappings":"CAAA,SAAAA,EAAAC,GACA,gBAAAC,UAAA,gBAAAC,QACAA,OAAAD,QAAAD,EAAAG,QAAAC,QAAAD,QAAAC,QAAAD,QAAAC,SACA,kBAAAC,gBAAAC,IACAD,QAAA,yCAAAL,GACA,gBAAAC,SACAA,QAAA,IAAAD,EAAAG,QAAAC,QAAAD,QAAAC,QAAAD,QAAAC,UAEAL,EAAA,YAAAA,EAAA,gBAAiDA,EAAA,gBAAAC,EAAAD,EAAAK,QAAAL,EAAAK,QAAAL,EAAAK,WAChDG,KAAA,SAAAC,EAAAC,EAAAC,GACD,MCAgB,UAAUC,GCN1B,QAAAC,GAAAC,GAGA,GAAAC,EAAAD,GACA,MAAAC,GAAAD,GAAAZ,OAGA,IAAAC,GAAAY,EAAAD,IACAZ,WACAc,GAAAF,EACAG,QAAA,EAUA,OANAL,GAAAE,GAAAI,KAAAf,EAAAD,QAAAC,IAAAD,QAAAW,GAGAV,EAAAc,QAAA,EAGAd,EAAAD,QAvBA,GAAAa,KAqCA,OATAF,GAAAM,EAAAP,EAGAC,EAAAO,EAAAL,EAGAF,EAAAQ,EAAA,UAGAR,EAAA,KDgBM,SAASV,EAAQD,EAASW,GElBhC,QAAAS,GAAAC,GAGAf,KAAAgB,WAAA,GAAAC,GAAAF,GAGAf,KAAAkB,OAAA,GAAAC,IACAC,UAAApB,KAAAgB,WACAK,OAAAN,EAAAO,cAIAtB,KAAAuB,QAAA,GAAAC,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KAAAqd,UAAA1C,IAQA5Y,EAAAM,UAAAib,QAAA,SAAAxW,GAMA,MAJA9G,MAAA2b,eAAApW,QACAvF,KAAA6b,gBAAA/U,GAGA9G,MAIAL,EAAAD,QAAAqC","file":"ringcentral.min.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory(require(undefined), require(undefined), require(undefined));\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([\"pubnub\", \"es6-promise\", \"fetch-ponyfill\"], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"SDK\"] = factory(require(undefined), require(undefined), require(undefined));\n\telse\n\t\troot[\"RingCentral\"] = root[\"RingCentral\"] || {}, root[\"RingCentral\"][\"SDK\"] = factory(root[undefined], root[undefined], root[undefined]);\n})(this, function(__WEBPACK_EXTERNAL_MODULE_12__, __WEBPACK_EXTERNAL_MODULE_13__, __WEBPACK_EXTERNAL_MODULE_14__) {\nreturn \n\n\n// WEBPACK FOOTER //\n// webpack/universalModuleDefinition","(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory(require(undefined), require(undefined), require(undefined));\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([\"pubnub\", \"es6-promise\", \"fetch-ponyfill\"], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"SDK\"] = factory(require(undefined), require(undefined), require(undefined));\n\telse\n\t\troot[\"RingCentral\"] = root[\"RingCentral\"] || {}, root[\"RingCentral\"][\"SDK\"] = factory(root[undefined], root[undefined], root[undefined]);\n})(this, function(__WEBPACK_EXTERNAL_MODULE_12__, __WEBPACK_EXTERNAL_MODULE_13__, __WEBPACK_EXTERNAL_MODULE_14__) {\nreturn /******/ (function(modules) { // webpackBootstrap\n/******/ \t// The module cache\n/******/ \tvar installedModules = {};\n/******/\n/******/ \t// The require function\n/******/ \tfunction __webpack_require__(moduleId) {\n/******/\n/******/ \t\t// Check if module is in cache\n/******/ \t\tif(installedModules[moduleId])\n/******/ \t\t\treturn installedModules[moduleId].exports;\n/******/\n/******/ \t\t// Create a new module (and put it into the cache)\n/******/ \t\tvar module = installedModules[moduleId] = {\n/******/ \t\t\texports: {},\n/******/ \t\t\tid: moduleId,\n/******/ \t\t\tloaded: false\n/******/ \t\t};\n/******/\n/******/ \t\t// Execute the module function\n/******/ \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n/******/\n/******/ \t\t// Flag the module as loaded\n/******/ \t\tmodule.loaded = true;\n/******/\n/******/ \t\t// Return the exports of the module\n/******/ \t\treturn module.exports;\n/******/ \t}\n/******/\n/******/\n/******/ \t// expose the modules object (__webpack_modules__)\n/******/ \t__webpack_require__.m = modules;\n/******/\n/******/ \t// expose the module cache\n/******/ \t__webpack_require__.c = installedModules;\n/******/\n/******/ \t// __webpack_public_path__\n/******/ \t__webpack_require__.p = \"/build/\";\n/******/\n/******/ \t// Load entry module and return exports\n/******/ \treturn __webpack_require__(0);\n/******/ })\n/************************************************************************/\n/******/ ([\n/* 0 */\n/***/ function(module, exports, __webpack_require__) {\n\n/**\n * @namespace RingCentral\n */\nvar objectAssign = __webpack_require__(1);\nvar Cache = __webpack_require__(2);\nvar Client = __webpack_require__(3);\nvar Externals = __webpack_require__(11);\nvar Platform = __webpack_require__(15);\nvar Subscription = __webpack_require__(18);\nvar CachedSubscription = __webpack_require__(19);\nvar Constants = __webpack_require__(17);\n\n/**\n * @constructor\n * @param {string} options.server\n * @param {string} options.appSecret\n * @param {string} options.appKey\n * @param {string} [options.cachePrefix]\n * @param {string} [options.appName]\n * @param {string} [options.appVersion]\n * @param {string} [options.redirectUri]\n * @param {PubNub} [options.PubNub]\n * @param {function(new:Promise)} [options.Promise]\n * @param {Storage} [options.localStorage]\n * @param {fetch} [options.fetch]\n * @param {function(new:Request)} [options.Request]\n * @param {function(new:Response)} [options.Response]\n * @param {function(new:Headers)} [options.Headers]\n * @param {int} [options.refreshDelayMs]\n * @param {int} [options.refreshHandicapMs]\n * @param {boolean} [options.clearCacheOnRefreshError]\n * @property {Externals} _externals\n * @property {Cache} _cache\n * @property {Client} _client\n * @property {Platform} _platform\n */\nfunction SDK(options) {\n\n /** @private */\n this._externals = new Externals(options);\n\n /** @private */\n this._cache = new Cache({\n externals: this._externals,\n prefix: options.cachePrefix\n });\n\n /** @private */\n this._client = new Client(this._externals);\n\n /** @private */\n this._platform = new Platform(objectAssign({}, options, {\n externals: this._externals,\n client: this._client,\n cache: this._cache\n }));\n\n}\n\nSDK.version = Constants.version;\n\nSDK.server = {\n sandbox: 'https://platform.devtest.ringcentral.com',\n production: 'https://platform.ringcentral.com'\n};\n\n/**\n * @return {Platform}\n */\nSDK.prototype.platform = function() {\n return this._platform;\n};\n\n/**\n * @return {Cache}\n */\nSDK.prototype.cache = function() {\n return this._cache;\n};\n\n/**\n * @param {int} [options.pollInterval]\n * @param {int} [options.renewHandicapMs]\n * @return {Subscription}\n */\nSDK.prototype.createSubscription = function(options) {\n return new Subscription(objectAssign({}, options, {\n externals: this._externals,\n platform: this._platform\n }));\n};\n\n/**\n * @param {string} options.cacheKey\n * @param {int} [options.pollInterval]\n * @param {int} [options.renewHandicapMs]\n * @return {CachedSubscription}\n */\nSDK.prototype.createCachedSubscription = function(options) {\n\n if (typeof arguments[0] == 'string') {\n options = {cacheKey: arguments[0].toString()};\n } else {\n options = options || {};\n }\n\n return new CachedSubscription(objectAssign({}, options, {\n externals: this._externals,\n platform: this._platform,\n cache: this._cache\n }));\n\n};\n\nSDK.handleLoginRedirect = function(origin) {\n\n var response = window.location.hash ? window.location.hash : window.location.search;\n var msg = {};\n msg[Constants.authResponseProperty] = response;\n window.opener.postMessage(msg, origin || window.location.origin);\n\n};\n\nmodule.exports = SDK;\n\n/***/ },\n/* 1 */\n/***/ function(module, exports) {\n\n/*\nobject-assign\n(c) Sindre Sorhus\n@license MIT\n*/\n\n'use strict';\n/* eslint-disable no-unused-vars */\nvar getOwnPropertySymbols = Object.getOwnPropertySymbols;\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\nvar propIsEnumerable = Object.prototype.propertyIsEnumerable;\n\nfunction toObject(val) {\n\tif (val === null || val === undefined) {\n\t\tthrow new TypeError('Object.assign cannot be called with null or undefined');\n\t}\n\n\treturn Object(val);\n}\n\nfunction shouldUseNative() {\n\ttry {\n\t\tif (!Object.assign) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// Detect buggy property enumeration order in older V8 versions.\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=4118\n\t\tvar test1 = new String('abc'); // eslint-disable-line no-new-wrappers\n\t\ttest1[5] = 'de';\n\t\tif (Object.getOwnPropertyNames(test1)[0] === '5') {\n\t\t\treturn false;\n\t\t}\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=3056\n\t\tvar test2 = {};\n\t\tfor (var i = 0; i < 10; i++) {\n\t\t\ttest2['_' + String.fromCharCode(i)] = i;\n\t\t}\n\t\tvar order2 = Object.getOwnPropertyNames(test2).map(function (n) {\n\t\t\treturn test2[n];\n\t\t});\n\t\tif (order2.join('') !== '0123456789') {\n\t\t\treturn false;\n\t\t}\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=3056\n\t\tvar test3 = {};\n\t\t'abcdefghijklmnopqrst'.split('').forEach(function (letter) {\n\t\t\ttest3[letter] = letter;\n\t\t});\n\t\tif (Object.keys(Object.assign({}, test3)).join('') !==\n\t\t\t\t'abcdefghijklmnopqrst') {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t} catch (err) {\n\t\t// We don't expect any of the above to throw, but better to be safe.\n\t\treturn false;\n\t}\n}\n\nmodule.exports = shouldUseNative() ? Object.assign : function (target, source) {\n\tvar from;\n\tvar to = toObject(target);\n\tvar symbols;\n\n\tfor (var s = 1; s < arguments.length; s++) {\n\t\tfrom = Object(arguments[s]);\n\n\t\tfor (var key in from) {\n\t\t\tif (hasOwnProperty.call(from, key)) {\n\t\t\t\tto[key] = from[key];\n\t\t\t}\n\t\t}\n\n\t\tif (getOwnPropertySymbols) {\n\t\t\tsymbols = getOwnPropertySymbols(from);\n\t\t\tfor (var i = 0; i < symbols.length; i++) {\n\t\t\t\tif (propIsEnumerable.call(from, symbols[i])) {\n\t\t\t\t\tto[symbols[i]] = from[symbols[i]];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn to;\n};\n\n\n/***/ },\n/* 2 */\n/***/ function(module, exports) {\n\n/**\n * @param {Externals} options.externals\n * @param {string} [options.prefix]\n * @property {Externals} _externals\n */\nfunction Cache(options) {\n\n /** @private */\n this._prefix = options.prefix || Cache.defaultPrefix;\n\n /** @private */\n this._externals = options.externals;\n\n}\n\nCache.defaultPrefix = 'rc-';\n\nCache.prototype.setItem = function(key, data) {\n this._externals.localStorage[this._prefixKey(key)] = JSON.stringify(data);\n return this;\n};\n\nCache.prototype.removeItem = function(key) {\n delete this._externals.localStorage[this._prefixKey(key)];\n return this;\n};\n\nCache.prototype.getItem = function(key) {\n var item = this._externals.localStorage[this._prefixKey(key)];\n if (!item) return null;\n return JSON.parse(item);\n};\n\nCache.prototype.clean = function() {\n\n for (var key in this._externals.localStorage) {\n\n if (!this._externals.localStorage.hasOwnProperty(key)) continue;\n\n if (key.indexOf(this._prefix) === 0) {\n delete this._externals.localStorage[key];\n }\n\n }\n\n return this;\n\n};\n\nCache.prototype._prefixKey = function(key) {\n return this._prefix + key;\n};\n\nmodule.exports = Cache;\n\n/***/ },\n/* 3 */\n/***/ function(module, exports, __webpack_require__) {\n\nvar isPlainObject = __webpack_require__(4);\nvar EventEmitter = __webpack_require__(6).EventEmitter;\nvar ApiResponse = __webpack_require__(7);\nvar qs = __webpack_require__(8);\n\nfunction findHeaderName(name, headers) {\n name = name.toLowerCase();\n return Object.keys(headers).reduce(function(res, key) {\n if (res) return res;\n if (name == key.toLowerCase()) return key;\n return res;\n }, null);\n}\n\n/**\n * @param {Externals} externals\n * @property {Externals} _externals\n */\nfunction Client(externals) {\n\n EventEmitter.call(this);\n\n /** @private */\n this._externals = externals;\n\n this.events = {\n beforeRequest: 'beforeRequest',\n requestSuccess: 'requestSuccess',\n requestError: 'requestError'\n };\n\n}\n\nClient._allowedMethods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS', 'HEAD'];\n\nClient.prototype = Object.create(EventEmitter.prototype);\n\n/**\n * @param {Request} request\n * @return {Promise}\n */\nClient.prototype.sendRequest = function(request) {\n\n var apiResponse = new ApiResponse({\n externals: this._externals,\n request: request\n });\n\n return (new this._externals.Promise(function(resolve) {\n\n //TODO Stop request if listeners return false\n this.emit(this.events.beforeRequest, apiResponse);\n\n resolve(this._loadResponse(request));\n\n }.bind(this))).then(function(response) {\n\n return apiResponse.receiveResponse(response);\n\n }).then(function() {\n\n if (!apiResponse.ok()) throw new Error('Response has unsuccessful status');\n\n this.emit(this.events.requestSuccess, apiResponse);\n\n return apiResponse;\n\n }.bind(this)).catch(function(e) {\n\n if (!e.apiResponse) e = this.makeError(e, apiResponse);\n\n this.emit(this.events.requestError, e);\n\n throw e;\n\n }.bind(this));\n\n};\n\n/**\n * @param {Request} request\n * @return {Promise}\n * @private\n */\nClient.prototype._loadResponse = function(request) {\n return this._externals.fetch.call(null, request);\n};\n\n/**\n * Wraps the JS Error object with transaction information\n * @param {Error|IApiError} e\n * @param {ApiResponse} apiResponse\n * @return {IApiError}\n */\nClient.prototype.makeError = function(e, apiResponse) {\n\n // Wrap only if regular error\n if (!e.hasOwnProperty('apiResponse') && !e.hasOwnProperty('originalMessage')) {\n\n e.apiResponse = apiResponse;\n e.originalMessage = e.message;\n e.message = (apiResponse && apiResponse.error(true)) || e.originalMessage;\n\n }\n\n return e;\n\n};\n\n/**\n *\n * @param {object} init\n * @param {object} [init.url]\n * @param {object} [init.body]\n * @param {string} [init.method]\n * @param {object} [init.query]\n * @param {object} [init.headers]\n * @param {object} [init.credentials]\n * @param {object} [init.mode]\n * @return {Request}\n */\nClient.prototype.createRequest = function(init) {\n\n init = init || {};\n init.headers = init.headers || {};\n\n // Sanity checks\n if (!init.url) throw new Error('Url is not defined');\n if (!init.method) init.method = 'GET';\n init.method = init.method.toUpperCase();\n if (init.method && Client._allowedMethods.indexOf(init.method) < 0) {\n throw new Error('Method has wrong value: ' + init.method);\n }\n\n // Defaults\n init.credentials = init.credentials || 'include';\n init.mode = init.mode || 'cors';\n\n // Append Query String\n if (init.query) {\n init.url = init.url + (init.url.indexOf('?') > -1 ? '&' : '?') + qs.stringify(init.query);\n }\n\n if (!(findHeaderName('Accept', init.headers))) {\n init.headers.Accept = ApiResponse._jsonContentType;\n }\n\n // Serialize body\n if (isPlainObject(init.body) || !init.body) {\n\n var contentTypeHeaderName = findHeaderName(ApiResponse._contentType, init.headers);\n\n if (!contentTypeHeaderName) {\n contentTypeHeaderName = ApiResponse._contentType;\n init.headers[contentTypeHeaderName] = ApiResponse._jsonContentType;\n }\n\n var contentType = init.headers[contentTypeHeaderName];\n\n // Assign a new encoded body\n if (contentType.indexOf(ApiResponse._jsonContentType) > -1) {\n if ((init.method === 'GET' || init.method === 'HEAD') && !!init.body) {\n // oddly setting body to null still result in TypeError in phantomjs\n init.body = undefined;\n } else {\n init.body = JSON.stringify(init.body);\n }\n\n } else if (contentType.indexOf(ApiResponse._urlencodedContentType) > -1) {\n init.body = qs.stringify(init.body);\n }\n\n }\n\n // Create a request with encoded body\n var req = new this._externals.Request(init.url, init);\n\n // Keep the original body accessible directly (for mocks)\n req.originalBody = init.body;\n\n return req;\n\n};\n\n/**\n * @typedef {object} IApiError\n * @property {string} stack\n * @property {string} originalMessage\n * @property {ApiResponse} apiResponse\n */\n\nmodule.exports = Client;\n\n/***/ },\n/* 4 */\n/***/ function(module, exports, __webpack_require__) {\n\n/*!\n * is-plain-object \n *\n * Copyright (c) 2014-2015, Jon Schlinkert.\n * Licensed under the MIT License.\n */\n\n'use strict';\n\nvar isObject = __webpack_require__(5);\n\nfunction isObjectObject(o) {\n return isObject(o) === true\n && Object.prototype.toString.call(o) === '[object Object]';\n}\n\nmodule.exports = function isPlainObject(o) {\n var ctor,prot;\n \n if (isObjectObject(o) === false) return false;\n \n // If has modified constructor\n ctor = o.constructor;\n if (typeof ctor !== 'function') return false;\n \n // If has modified prototype\n prot = ctor.prototype;\n if (isObjectObject(prot) === false) return false;\n \n // If constructor does not have an Object-specific method\n if (prot.hasOwnProperty('isPrototypeOf') === false) {\n return false;\n }\n \n // Most likely a plain Object\n return true;\n};\n\n\n/***/ },\n/* 5 */\n/***/ function(module, exports) {\n\n/*!\n * isobject \n *\n * Copyright (c) 2014-2015, Jon Schlinkert.\n * Licensed under the MIT License.\n */\n\n'use strict';\n\nmodule.exports = function isObject(val) {\n return val != null && typeof val === 'object'\n && !Array.isArray(val);\n};\n\n\n/***/ },\n/* 6 */\n/***/ function(module, exports) {\n\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nfunction EventEmitter() {\n this._events = this._events || {};\n this._maxListeners = this._maxListeners || undefined;\n}\nmodule.exports = EventEmitter;\n\n// Backwards-compat with node 0.10.x\nEventEmitter.EventEmitter = EventEmitter;\n\nEventEmitter.prototype._events = undefined;\nEventEmitter.prototype._maxListeners = undefined;\n\n// By default EventEmitters will print a warning if more than 10 listeners are\n// added to it. This is a useful default which helps finding memory leaks.\nEventEmitter.defaultMaxListeners = 10;\n\n// Obviously not all Emitters should be limited to 10. This function allows\n// that to be increased. Set to zero for unlimited.\nEventEmitter.prototype.setMaxListeners = function(n) {\n if (!isNumber(n) || n < 0 || isNaN(n))\n throw TypeError('n must be a positive number');\n this._maxListeners = n;\n return this;\n};\n\nEventEmitter.prototype.emit = function(type) {\n var er, handler, len, args, i, listeners;\n\n if (!this._events)\n this._events = {};\n\n // If there is no 'error' event listener then throw.\n if (type === 'error') {\n if (!this._events.error ||\n (isObject(this._events.error) && !this._events.error.length)) {\n er = arguments[1];\n if (er instanceof Error) {\n throw er; // Unhandled 'error' event\n } else {\n // At least give some kind of context to the user\n var err = new Error('Uncaught, unspecified \"error\" event. (' + er + ')');\n err.context = er;\n throw err;\n }\n }\n }\n\n handler = this._events[type];\n\n if (isUndefined(handler))\n return false;\n\n if (isFunction(handler)) {\n switch (arguments.length) {\n // fast cases\n case 1:\n handler.call(this);\n break;\n case 2:\n handler.call(this, arguments[1]);\n break;\n case 3:\n handler.call(this, arguments[1], arguments[2]);\n break;\n // slower\n default:\n args = Array.prototype.slice.call(arguments, 1);\n handler.apply(this, args);\n }\n } else if (isObject(handler)) {\n args = Array.prototype.slice.call(arguments, 1);\n listeners = handler.slice();\n len = listeners.length;\n for (i = 0; i < len; i++)\n listeners[i].apply(this, args);\n }\n\n return true;\n};\n\nEventEmitter.prototype.addListener = function(type, listener) {\n var m;\n\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n if (!this._events)\n this._events = {};\n\n // To avoid recursion in the case that type === \"newListener\"! Before\n // adding it to the listeners, first emit \"newListener\".\n if (this._events.newListener)\n this.emit('newListener', type,\n isFunction(listener.listener) ?\n listener.listener : listener);\n\n if (!this._events[type])\n // Optimize the case of one listener. Don't need the extra array object.\n this._events[type] = listener;\n else if (isObject(this._events[type]))\n // If we've already got an array, just append.\n this._events[type].push(listener);\n else\n // Adding the second element, need to change to array.\n this._events[type] = [this._events[type], listener];\n\n // Check for listener leak\n if (isObject(this._events[type]) && !this._events[type].warned) {\n if (!isUndefined(this._maxListeners)) {\n m = this._maxListeners;\n } else {\n m = EventEmitter.defaultMaxListeners;\n }\n\n if (m && m > 0 && this._events[type].length > m) {\n this._events[type].warned = true;\n console.error('(node) warning: possible EventEmitter memory ' +\n 'leak detected. %d listeners added. ' +\n 'Use emitter.setMaxListeners() to increase limit.',\n this._events[type].length);\n if (typeof console.trace === 'function') {\n // not supported in IE 10\n console.trace();\n }\n }\n }\n\n return this;\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.once = function(type, listener) {\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n var fired = false;\n\n function g() {\n this.removeListener(type, g);\n\n if (!fired) {\n fired = true;\n listener.apply(this, arguments);\n }\n }\n\n g.listener = listener;\n this.on(type, g);\n\n return this;\n};\n\n// emits a 'removeListener' event iff the listener was removed\nEventEmitter.prototype.removeListener = function(type, listener) {\n var list, position, length, i;\n\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n if (!this._events || !this._events[type])\n return this;\n\n list = this._events[type];\n length = list.length;\n position = -1;\n\n if (list === listener ||\n (isFunction(list.listener) && list.listener === listener)) {\n delete this._events[type];\n if (this._events.removeListener)\n this.emit('removeListener', type, listener);\n\n } else if (isObject(list)) {\n for (i = length; i-- > 0;) {\n if (list[i] === listener ||\n (list[i].listener && list[i].listener === listener)) {\n position = i;\n break;\n }\n }\n\n if (position < 0)\n return this;\n\n if (list.length === 1) {\n list.length = 0;\n delete this._events[type];\n } else {\n list.splice(position, 1);\n }\n\n if (this._events.removeListener)\n this.emit('removeListener', type, listener);\n }\n\n return this;\n};\n\nEventEmitter.prototype.removeAllListeners = function(type) {\n var key, listeners;\n\n if (!this._events)\n return this;\n\n // not listening for removeListener, no need to emit\n if (!this._events.removeListener) {\n if (arguments.length === 0)\n this._events = {};\n else if (this._events[type])\n delete this._events[type];\n return this;\n }\n\n // emit removeListener for all listeners on all events\n if (arguments.length === 0) {\n for (key in this._events) {\n if (key === 'removeListener') continue;\n this.removeAllListeners(key);\n }\n this.removeAllListeners('removeListener');\n this._events = {};\n return this;\n }\n\n listeners = this._events[type];\n\n if (isFunction(listeners)) {\n this.removeListener(type, listeners);\n } else if (listeners) {\n // LIFO order\n while (listeners.length)\n this.removeListener(type, listeners[listeners.length - 1]);\n }\n delete this._events[type];\n\n return this;\n};\n\nEventEmitter.prototype.listeners = function(type) {\n var ret;\n if (!this._events || !this._events[type])\n ret = [];\n else if (isFunction(this._events[type]))\n ret = [this._events[type]];\n else\n ret = this._events[type].slice();\n return ret;\n};\n\nEventEmitter.prototype.listenerCount = function(type) {\n if (this._events) {\n var evlistener = this._events[type];\n\n if (isFunction(evlistener))\n return 1;\n else if (evlistener)\n return evlistener.length;\n }\n return 0;\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n return emitter.listenerCount(type);\n};\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\n\n\n/***/ },\n/* 7 */\n/***/ function(module, exports) {\n\n/**\n * @param {Externals} options.externals\n * @param {Request} [options.request]\n * @param {Response} [options.response]\n * @param {string} [options.responseText]\n * @property {Externals} _externals\n * @property {Request} _request\n * @property {Response} _response\n * @property {string} _text\n * @property {object} _json\n * @property {ApiResponse[]} _multipart\n */\nfunction ApiResponse(options) {\n\n /** @private */\n this._externals = options.externals;\n\n /** @private */\n this._request = options.request;\n\n /** @private */\n this._response = options.response;\n\n /** @private */\n this._text = options.responseText || '';\n\n /** @private */\n this._json = null;\n\n /** @private */\n this._multipart = [];\n\n}\n\nApiResponse._contentType = 'Content-Type';\nApiResponse._jsonContentType = 'application/json';\nApiResponse._multipartContentType = 'multipart/mixed';\nApiResponse._urlencodedContentType = 'application/x-www-form-urlencoded';\nApiResponse._headerSeparator = ':';\nApiResponse._bodySeparator = '\\n\\n';\nApiResponse._boundarySeparator = '--';\nApiResponse._unauthorizedStatus = 401;\n\n/**\n * @param {Response} response\n * @return {Promise}\n */\nApiResponse.prototype.receiveResponse = function(response) {\n\n this._response = response;\n\n return (new this._externals.Promise(function(resolve) {\n\n // Ignore if not textual type\n if (!this._isMultipart() && !this._isJson()) return resolve('');\n\n return resolve(this.response().text());\n\n }.bind(this))).then(function(text) {\n\n this._text = text;\n return text;\n\n }.bind(this));\n\n};\n\n/**\n * @return {Response}\n */\nApiResponse.prototype.response = function() {\n return this._response;\n};\n\n/**\n * @return {Request}\n */\nApiResponse.prototype.request = function() {\n return this._request;\n};\n\n/**\n * @return {boolean}\n */\nApiResponse.prototype.ok = function() {\n return this._response && this._response.ok;\n};\n\n/**\n * @return {string}\n */\nApiResponse.prototype.text = function() {\n // Since we read text only in case JSON or Multipart\n if (!this._isJson() && !this._isMultipart()) throw new Error('Response is not text');\n return this._text;\n};\n\n/**\n * @return {object}\n */\nApiResponse.prototype.json = function() {\n if (!this._isJson()) throw new Error('Response is not JSON');\n if (!this._json) {\n this._json = this._text ? JSON.parse(this._text) : null;\n }\n return this._json;\n};\n\n/**\n * @param [skipOKCheck]\n * @return {string}\n */\nApiResponse.prototype.error = function(skipOKCheck) {\n\n if (this.ok() && !skipOKCheck) return null;\n\n var message = (this._response && this._response.status ? this._response.status + ' ' : '') +\n (this._response && this._response.statusText ? this._response.statusText : '');\n\n try {\n\n if (this.json().message) message = this.json().message;\n if (this.json().error_description) message = this.json().error_description;\n if (this.json().description) message = this.json().description;\n\n } catch (e) {}\n\n return message;\n\n};\n\n/**\n * If it is not known upfront what would be the response, client code can treat any response as multipart\n * @return {ApiResponse[]}\n */\nApiResponse.prototype.toMultipart = function() {\n if (!this._isMultipart()) return [this];\n return this.multipart();\n};\n\n/**\n * @return {ApiResponse[]}\n */\nApiResponse.prototype.multipart = function() {\n\n if (!this._isMultipart()) throw new Error('Response is not multipart');\n\n if (!this._multipart.length) {\n\n // Step 1. Split multipart response\n\n var text = this.text();\n\n if (!text) throw new Error('No response body');\n\n var boundary = this._getContentType().match(/boundary=([^;]+)/i)[1];\n\n if (!boundary) throw new Error('Cannot find boundary');\n\n var parts = text.toString().split(ApiResponse._boundarySeparator + boundary);\n\n if (parts[0].trim() === '') parts.shift();\n if (parts[parts.length - 1].trim() == ApiResponse._boundarySeparator) parts.pop();\n\n if (parts.length < 1) throw new Error('No parts in body');\n\n // Step 2. Parse status info\n\n var statusInfo = this._create(parts.shift(), this._response.status, this._response.statusText).json();\n\n // Step 3. Parse all other parts\n\n this._multipart = parts.map(function(part, i) {\n\n var status = statusInfo.response[i].status;\n\n return this._create(part, status);\n\n }.bind(this));\n\n }\n\n return this._multipart;\n\n};\n\n/**\n * @private\n */\nApiResponse.prototype._isContentType = function(contentType) {\n return this._getContentType().indexOf(contentType) > -1;\n};\n\n/**\n * @private\n */\nApiResponse.prototype._getContentType = function() {\n return this._response.headers.get(ApiResponse._contentType) || '';\n};\n\n/**\n * @private\n */\nApiResponse.prototype._isMultipart = function() {\n return this._isContentType(ApiResponse._multipartContentType);\n};\n\n/**\n * @private\n */\nApiResponse.prototype._isJson = function() {\n return this._isContentType(ApiResponse._jsonContentType);\n};\n\n/**\n * Method is used to create ApiResponse object from string parts of multipart/mixed response\n * @param {string} [text]\n * @param {number} [status]\n * @param {string} [statusText]\n * @private\n * @return {ApiResponse}\n */\nApiResponse.prototype._create = function(text, status, statusText) {\n\n text = text || '';\n status = status || 200;\n statusText = statusText || 'OK';\n\n text = text.replace(/\\r/g, '');\n\n var headers = new this._externals.Headers(),\n headersAndBody = text.split(ApiResponse._bodySeparator),\n headersText = (headersAndBody.length > 1) ? headersAndBody.shift() : '';\n\n text = headersAndBody.length > 0 ? headersAndBody.join(ApiResponse._bodySeparator) : null;\n\n (headersText || '')\n .split('\\n')\n .forEach(function(header) {\n\n var split = header.trim().split(ApiResponse._headerSeparator),\n key = split.shift().trim(),\n value = split.join(ApiResponse._headerSeparator).trim();\n\n if (key) headers.append(key, value);\n\n });\n\n var response = new this._externals.Response(text, {\n headers: headers,\n status: status,\n statusText: statusText\n });\n\n return new ApiResponse({\n externals: this._externals,\n request: null,\n response: response,\n responseText: text\n });\n\n};\n\nmodule.exports = ApiResponse;\n\n/***/ },\n/* 8 */\n/***/ function(module, exports, __webpack_require__) {\n\n'use strict';\n\nexports.decode = exports.parse = __webpack_require__(9);\nexports.encode = exports.stringify = __webpack_require__(10);\n\n\n/***/ },\n/* 9 */\n/***/ function(module, exports) {\n\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n// If obj.hasOwnProperty has been overridden, then calling\n// obj.hasOwnProperty(prop) will break.\n// See: https://github.com/joyent/node/issues/1707\nfunction hasOwnProperty(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n\nmodule.exports = function(qs, sep, eq, options) {\n sep = sep || '&';\n eq = eq || '=';\n var obj = {};\n\n if (typeof qs !== 'string' || qs.length === 0) {\n return obj;\n }\n\n var regexp = /\\+/g;\n qs = qs.split(sep);\n\n var maxKeys = 1000;\n if (options && typeof options.maxKeys === 'number') {\n maxKeys = options.maxKeys;\n }\n\n var len = qs.length;\n // maxKeys <= 0 means that we should not limit keys count\n if (maxKeys > 0 && len > maxKeys) {\n len = maxKeys;\n }\n\n for (var i = 0; i < len; ++i) {\n var x = qs[i].replace(regexp, '%20'),\n idx = x.indexOf(eq),\n kstr, vstr, k, v;\n\n if (idx >= 0) {\n kstr = x.substr(0, idx);\n vstr = x.substr(idx + 1);\n } else {\n kstr = x;\n vstr = '';\n }\n\n k = decodeURIComponent(kstr);\n v = decodeURIComponent(vstr);\n\n if (!hasOwnProperty(obj, k)) {\n obj[k] = v;\n } else if (Array.isArray(obj[k])) {\n obj[k].push(v);\n } else {\n obj[k] = [obj[k], v];\n }\n }\n\n return obj;\n};\n\n\n/***/ },\n/* 10 */\n/***/ function(module, exports) {\n\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nvar stringifyPrimitive = function(v) {\n switch (typeof v) {\n case 'string':\n return v;\n\n case 'boolean':\n return v ? 'true' : 'false';\n\n case 'number':\n return isFinite(v) ? v : '';\n\n default:\n return '';\n }\n};\n\nmodule.exports = function(obj, sep, eq, name) {\n sep = sep || '&';\n eq = eq || '=';\n if (obj === null) {\n obj = undefined;\n }\n\n if (typeof obj === 'object') {\n return Object.keys(obj).map(function(k) {\n var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;\n if (Array.isArray(obj[k])) {\n return obj[k].map(function(v) {\n return ks + encodeURIComponent(stringifyPrimitive(v));\n }).join(sep);\n } else {\n return ks + encodeURIComponent(stringifyPrimitive(obj[k]));\n }\n }).join(sep);\n\n }\n\n if (!name) return '';\n return encodeURIComponent(stringifyPrimitive(name)) + eq +\n encodeURIComponent(stringifyPrimitive(obj));\n};\n\n\n/***/ },\n/* 11 */\n/***/ function(module, exports, __webpack_require__) {\n\n/* WEBPACK VAR INJECTION */(function(global) {var pubnub = __webpack_require__(12);\nvar es6Promise = __webpack_require__(13);\nvar FetchPonyfill = __webpack_require__(14);\n\nvar root = (typeof window !== \"undefined\" && window) ||\n (typeof global !== \"undefined\" && global) ||\n (function(){ return this; })();\n\n/**\n * @constructor\n * @param {PubNub} [options.PubNub]\n * @param {function(new:Promise)} [options.Promise]\n * @param {Storage} [options.localStorage]\n * @param {fetch} [options.fetch]\n * @param {function(new:Request)} [options.Request]\n * @param {function(new:Response)} [options.Response]\n * @param {function(new:Headers)} [options.Headers]\n * @property {PubNub} PubNub\n * @property {Storage} localStorage\n * @property {function(new:Promise)} Promise\n * @property {fetch} fetch\n * @property {function(new:Request)} Request\n * @property {function(new:Response)} Response\n * @property {function(new:Headers)} Headers\n */\nfunction Externals(options) {\n\n options = options || {};\n\n this.PubNub = options.PubNub || root.PubNub || pubnub;\n this.localStorage = options.localStorage || ((typeof root.localStorage !== 'undefined') ? root.localStorage : {});\n this.Promise = options.Promise || root.Promise || (es6Promise && es6Promise.Promise);\n\n var fetchPonyfill = FetchPonyfill ? FetchPonyfill({Promise: this.Promise}) : {};\n\n this.fetch = options.fetch || root.fetch || fetchPonyfill.fetch;\n this.Request = options.Request || root.Request || fetchPonyfill.Request;\n this.Response = options.Response || root.Response || fetchPonyfill.Response;\n this.Headers = options.Headers || root.Headers || fetchPonyfill.Headers;\n\n if (!this.fetch || !this.Response || !this.Request || !this.Headers) {\n throw new Error('Fetch API is missing');\n }\n\n if (!this.Promise) {\n throw new Error('Promise is missing');\n }\n\n if (!this.localStorage) {\n throw new Error('LocalStorage is missing');\n }\n\n if (!this.PubNub) {\n throw new Error('PubNub is missing');\n }\n\n}\n\nmodule.exports = Externals;\n\n/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))\n\n/***/ },\n/* 12 */\n/***/ function(module, exports) {\n\nmodule.exports = __WEBPACK_EXTERNAL_MODULE_12__;\n\n/***/ },\n/* 13 */\n/***/ function(module, exports) {\n\nmodule.exports = __WEBPACK_EXTERNAL_MODULE_13__;\n\n/***/ },\n/* 14 */\n/***/ function(module, exports) {\n\nmodule.exports = __WEBPACK_EXTERNAL_MODULE_14__;\n\n/***/ },\n/* 15 */\n/***/ function(module, exports, __webpack_require__) {\n\nvar EventEmitter = __webpack_require__(6).EventEmitter;\nvar qs = __webpack_require__(8);\nvar objectAssign = __webpack_require__(1);\nvar Auth = __webpack_require__(16);\nvar Constants = __webpack_require__(17);\nvar ApiResponse = __webpack_require__(7);\n\n/**\n * @constructor\n * @param {string} options.server\n * @param {string} options.appSecret\n * @param {string} options.appKey\n * @param {string} [options.appName]\n * @param {string} [options.appVersion]\n * @param {string} [options.redirectUri]\n * @param {int} [options.refreshDelayMs]\n * @param {int} [options.refreshHandicapMs]\n * @param {boolean} [options.clearCacheOnRefreshError]\n * @param {Externals} options.externals\n * @param {Cache} options.cache\n * @param {Client} options.client\n * @property {Externals} _externals\n * @property {Cache} _cache\n * @property {Client} _client\n * @property {Promise} _refreshPromise\n * @property {Auth} _auth\n */\nfunction Platform(options) {\n\n EventEmitter.call(this);\n\n this.events = {\n beforeLogin: 'beforeLogin',\n loginSuccess: 'loginSuccess',\n loginError: 'loginError',\n beforeRefresh: 'beforeRefresh',\n refreshSuccess: 'refreshSuccess',\n refreshError: 'refreshError',\n beforeLogout: 'beforeLogout',\n logoutSuccess: 'logoutSuccess',\n logoutError: 'logoutError'\n };\n\n options = options || {};\n\n /** @private */\n this._server = options.server;\n\n /** @private */\n this._appKey = options.appKey;\n\n /** @private */\n this._appSecret = options.appSecret;\n\n /** @private */\n this._redirectUri = options.redirectUri || '';\n\n /** @private */\n this._refreshDelayMs = options.refreshDelayMs || 100;\n\n /** @private */\n this._clearCacheOnRefreshError = typeof options.clearCacheOnRefreshError !== 'undefined' ?\n options.clearCacheOnRefreshError :\n true;\n\n /** @private */\n this._userAgent = (options.appName ?\n (options.appName + (options.appVersion ? '/' + options.appVersion : '')) + ' ' :\n '') + 'RCJSSDK/' + Constants.version;\n\n /** @private */\n this._externals = options.externals;\n\n /** @private */\n this._cache = options.cache;\n\n /** @private */\n this._client = options.client;\n\n /** @private */\n this._refreshPromise = null;\n\n /** @private */\n this._auth = new Auth({\n cache: this._cache,\n cacheId: Platform._cacheId,\n refreshHandicapMs: options.refreshHandicapMs\n });\n\n}\n\nPlatform._urlPrefix = '/restapi';\nPlatform._apiVersion = 'v1.0';\nPlatform._tokenEndpoint = '/restapi/oauth/token';\nPlatform._revokeEndpoint = '/restapi/oauth/revoke';\nPlatform._authorizeEndpoint = '/restapi/oauth/authorize';\nPlatform._cacheId = 'platform';\n\nPlatform.prototype = Object.create(EventEmitter.prototype);\n\nPlatform.prototype.delay = function(timeout) {\n return new this._externals.Promise(function(resolve, reject) {\n setTimeout(function() {\n resolve(null);\n }, timeout);\n });\n};\n\n/**\n * @return {Auth}\n */\nPlatform.prototype.auth = function() {\n return this._auth;\n};\n\n/**\n * @return {Client}\n */\nPlatform.prototype.client = function() {\n return this._client;\n};\n\n/**\n * @param {string} path\n * @param {object} [options]\n * @param {boolean} [options.addServer]\n * @param {string} [options.addMethod]\n * @param {boolean} [options.addToken]\n * @return {string}\n */\nPlatform.prototype.createUrl = function(path, options) {\n\n path = path || '';\n options = options || {};\n\n var builtUrl = '',\n hasHttp = path.indexOf('http://') != -1 || path.indexOf('https://') != -1;\n\n if (options.addServer && !hasHttp) builtUrl += this._server;\n\n if (path.indexOf(Platform._urlPrefix) == -1 && !hasHttp) builtUrl += Platform._urlPrefix + '/' + Platform._apiVersion;\n\n builtUrl += path;\n\n if (options.addMethod || options.addToken) builtUrl += (path.indexOf('?') > -1 ? '&' : '?');\n\n if (options.addMethod) builtUrl += '_method=' + options.addMethod;\n if (options.addToken) builtUrl += (options.addMethod ? '&' : '') + 'access_token=' + this._auth.accessToken();\n\n return builtUrl;\n\n};\n\n/**\n * @param {string} [options.redirectUri] Overrides default RedirectURI\n * @param {string} [options.state]\n * @param {string} [options.brandId]\n * @param {string} [options.display]\n * @param {string} [options.prompt]\n * @param {boolean} [options.implicit] Use Implicit Grant flow\n * @return {string}\n */\nPlatform.prototype.loginUrl = function(options) {\n\n options = options || {};\n\n return this.createUrl(Platform._authorizeEndpoint + '?' + qs.stringify({\n 'response_type': options.implicit ? 'token' : 'code',\n 'redirect_uri': options.redirectUri || this._redirectUri,\n 'client_id': this._appKey,\n 'state': options.state || '',\n 'brand_id': options.brandId || '',\n 'display': options.display || '',\n 'prompt': options.prompt || ''\n }), {addServer: true});\n\n};\n\n/**\n * @param {string} url\n * @return {Object}\n */\nPlatform.prototype.parseLoginRedirect = function(url) {\n\n function getParts(url, separator) {\n return url.split(separator).reverse()[0];\n }\n\n var response = (url.indexOf('#') === 0 && getParts(url, '#')) ||\n (url.indexOf('?') === 0 && getParts(url, '?')) ||\n null;\n\n if (!response) throw new Error('Unable to parse response');\n\n var queryString = qs.parse(response);\n\n if (!queryString) throw new Error('Unable to parse response');\n\n var error = queryString.error_description || queryString.error;\n\n if (error) {\n var e = new Error(error);\n e.error = queryString.error;\n throw e;\n }\n\n return queryString;\n\n};\n\n/**\n * Convenience method to handle 3-legged OAuth\n *\n * Attention! This is an experimental method and it's signature and behavior may change without notice.\n *\n * @experimental\n * @param {string} options.url\n * @param {number} [options.width]\n * @param {number} [options.height]\n * @param {object} [options.login] additional options for login()\n * @param {string} [options.origin]\n * @param {string} [options.property] name of window.postMessage's event data property\n * @param {string} [options.target] target for window.open()\n * @return {Promise}\n */\nPlatform.prototype.loginWindow = function(options) {\n\n return new this._externals.Promise(function(resolve, reject) {\n\n if (typeof window === 'undefined') throw new Error('This method can be used only in browser');\n\n if (!options.url) throw new Error('Missing mandatory URL parameter');\n\n options = options || {};\n options.url = options.url || 400;\n options.width = options.width || 400;\n options.height = options.height || 600;\n options.origin = options.origin || window.location.origin;\n options.property = options.property || Constants.authResponseProperty;\n options.target = options.target || '_blank';\n\n var dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left;\n var dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top;\n\n var width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;\n var height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;\n\n var left = ((width / 2) - (options.width / 2)) + dualScreenLeft;\n var top = ((height / 2) - (options.height / 2)) + dualScreenTop;\n var win = window.open(options.url, '_blank', (options.target == '_blank') ? 'scrollbars=yes, status=yes, width=' + options.width + ', height=' + options.height + ', left=' + left + ', top=' + top : '');\n\n if(!win) {\n throw new Error('Could not open login window. Please allow popups for this site');\n }\n\n if (win.focus) win.focus();\n\n var eventMethod = window.addEventListener ? 'addEventListener' : 'attachEvent';\n var eventRemoveMethod = eventMethod == 'addEventListener' ? 'removeEventListener' : 'detachEvent';\n var messageEvent = eventMethod == 'addEventListener' ? 'message' : 'onmessage';\n\n var eventListener = function(e) {\n\n try {\n\n if (e.origin != options.origin) return;\n if (!e.data || !e.data[options.property]) return; // keep waiting\n\n win.close();\n window[eventRemoveMethod](messageEvent, eventListener);\n\n\n var loginOptions = this.parseLoginRedirect(e.data[options.property]);\n\n if (!loginOptions.code && !loginOptions.access_token) throw new Error('No authorization code or token');\n\n resolve(loginOptions);\n\n /* jshint -W002 */\n } catch (e) {\n reject(e);\n }\n\n }.bind(this);\n\n window[eventMethod](messageEvent, eventListener, false);\n\n }.bind(this));\n\n};\n\n/**\n * @return {Promise}\n */\nPlatform.prototype.loggedIn = function() {\n\n return this.ensureLoggedIn().then(function() {\n return true;\n }).catch(function() {\n return false;\n });\n\n};\n\n/**\n * @param {string} options.username\n * @param {string} options.password\n * @param {string} [options.extension]\n * @param {string} [options.code]\n * @param {string} [options.redirectUri]\n * @param {string} [options.endpointId]\n * @param {string} [options.accessTokenTtl]\n * @param {string} [options.refreshTokenTtl]\n * @param {string} [options.access_token]\n * @returns {Promise}\n */\nPlatform.prototype.login = function(options) {\n\n return (new this._externals.Promise(function(resolve) {\n\n options = options || {};\n\n this.emit(this.events.beforeLogin);\n\n var body = {};\n\n if (options.access_token) {\n\n //TODO Potentially make a request to /oauth/tokeninfo\n return resolve(options);\n\n }\n\n if (!options.code) {\n\n body.grant_type = 'password';\n body.username = options.username;\n body.password = options.password;\n body.extension = options.extension || '';\n\n } else if (options.code) {\n\n body.grant_type = 'authorization_code';\n body.code = options.code;\n body.redirect_uri = options.redirectUri || this._redirectUri;\n //body.client_id = this.getCredentials().key; // not needed\n\n }\n\n if (options.endpointId) body.endpoint_id = options.endpointId;\n if (options.accessTokenTtl) body.accessTokenTtl = options.accessTokenTtl;\n if (options.refreshTokenTtl) body.refreshTokenTtl = options.refreshTokenTtl;\n\n resolve(this._tokenRequest(Platform._tokenEndpoint, body));\n\n }.bind(this))).then(function(res) {\n\n var apiResponse = res.json ? res : null;\n var json = apiResponse && apiResponse.json() || res;\n\n this._auth.setData(json);\n\n this.emit(this.events.loginSuccess, apiResponse);\n\n return apiResponse;\n\n }.bind(this)).catch(function(e) {\n\n if (this._clearCacheOnRefreshError) {\n this._cache.clean();\n }\n\n this.emit(this.events.loginError, e);\n\n throw e;\n\n }.bind(this));\n\n};\n\n/**\n * @returns {Promise}\n * @private\n */\nPlatform.prototype._refresh = function() {\n\n return this.delay(this._refreshDelayMs).then(function() {\n\n this.emit(this.events.beforeRefresh);\n\n // Perform sanity checks\n if (!this._auth.refreshToken()) throw new Error('Refresh token is missing');\n if (!this._auth.refreshTokenValid()) throw new Error('Refresh token has expired');\n\n return this._tokenRequest(Platform._tokenEndpoint, {\n \"grant_type\": \"refresh_token\",\n \"refresh_token\": this._auth.refreshToken(),\n \"access_token_ttl\": this._auth.data().expires_in + 1,\n \"refresh_token_ttl\": this._auth.data().refresh_token_expires_in + 1\n });\n\n }.bind(this)).then(function(/** @type {ApiResponse} */ res) {\n\n var json = res.json();\n\n if (!json.access_token) {\n throw this._client.makeError(new Error('Malformed OAuth response'), res);\n }\n\n this._auth.setData(json);\n\n this.emit(this.events.refreshSuccess, res);\n\n return res;\n\n }.bind(this)).catch(function(e) {\n\n e = this._client.makeError(e);\n\n if (this._clearCacheOnRefreshError) {\n this._cache.clean();\n }\n\n this.emit(this.events.refreshError, e);\n\n throw e;\n\n }.bind(this));\n\n};\n\n/**\n * @returns {Promise}\n */\nPlatform.prototype.refresh = function() {\n\n if (!this._refreshPromise) {\n\n this._refreshPromise = this._refresh()\n .then(function(res) {\n this._refreshPromise = null;\n return res;\n }.bind(this))\n .catch(function(e) {\n this._refreshPromise = null;\n throw e;\n }.bind(this));\n\n }\n\n return this._refreshPromise;\n\n};\n\n/**\n * @returns {Promise}\n */\nPlatform.prototype.logout = function() {\n\n return (new this._externals.Promise(function(resolve) {\n\n this.emit(this.events.beforeLogout);\n\n resolve(this._tokenRequest(Platform._revokeEndpoint, {\n token: this._auth.accessToken()\n }));\n\n }.bind(this))).then(function(res) {\n\n this._cache.clean();\n\n this.emit(this.events.logoutSuccess, res);\n\n return res;\n\n }.bind(this)).catch(function(e) {\n\n this.emit(this.events.logoutError, e);\n\n throw e;\n\n }.bind(this));\n\n};\n\n/**\n * @param {Request} request\n * @param {object} [options]\n * @param {boolean} [options.skipAuthCheck]\n * @return {Promise}\n */\nPlatform.prototype.inflateRequest = function(request, options) {\n\n options = options || {};\n\n if (options.skipAuthCheck) return this._externals.Promise.resolve(request);\n\n return this.ensureLoggedIn().then(function() {\n\n request.headers.set('X-User-Agent', this._userAgent);\n request.headers.set('Client-Id', this._appKey);\n request.headers.set('Authorization', this._authHeader());\n //request.url = this.createUrl(request.url, {addServer: true}); //FIXME Spec prevents this...\n\n return request;\n\n }.bind(this));\n\n};\n\n/**\n * @param {Request} request\n * @param {object} [options]\n * @param {boolean} [options.skipAuthCheck]\n * @param {boolean} [options.retry] Will be set by this method if SDK makes second request\n * @return {Promise}\n */\nPlatform.prototype.sendRequest = function(request, options) {\n\n return this.inflateRequest(request, options).then(function(request) {\n\n options = options || {};\n\n return this._client.sendRequest(request);\n\n }.bind(this)).catch(function(e) {\n\n // Guard is for errors that come from polling\n if (!e.apiResponse || !e.apiResponse.response() ||\n (e.apiResponse.response().status != ApiResponse._unauthorizedStatus) ||\n options.retry) throw e;\n\n this._auth.cancelAccessToken();\n\n options.retry = true;\n\n return this.sendRequest(request, options);\n\n }.bind(this));\n\n};\n\n/**\n * General purpose function to send anything to server\n * @param {string} options.url\n * @param {object} [options.body]\n * @param {string} [options.method]\n * @param {object} [options.query]\n * @param {object} [options.headers]\n * @param {boolean} [options.skipAuthCheck]\n * @return {Promise}\n */\nPlatform.prototype.send = function(options) {\n\n options = options || {};\n\n //FIXME https://github.com/bitinn/node-fetch/issues/43\n options.url = this.createUrl(options.url, {addServer: true});\n\n return this.sendRequest(this._client.createRequest(options), options);\n\n};\n\n/**\n * @param {string} url\n * @param {object} [query]\n * @param {object} [options]\n * @param {object} [options.headers]\n * @param {boolean} [options.skipAuthCheck]\n * @return {Promise}\n */\nPlatform.prototype.get = function(url, query, options) {\n return this.send(objectAssign({}, {method: 'GET', url: url, query: query}, options));\n};\n\n/**\n * @param {string} url\n * @param {object} body\n * @param {object} [query]\n * @param {object} [options]\n * @param {object} [options.headers]\n * @param {boolean} [options.skipAuthCheck]\n * @return {Promise}\n */\nPlatform.prototype.post = function(url, body, query, options) {\n return this.send(objectAssign({}, {method: 'POST', url: url, query: query, body: body}, options));\n};\n\n/**\n * @param {string} url\n * @param {object} [body]\n * @param {object} [query]\n * @param {object} [options]\n * @param {object} [options.headers]\n * @param {boolean} [options.skipAuthCheck]\n * @return {Promise}\n */\nPlatform.prototype.put = function(url, body, query, options) {\n return this.send(objectAssign({}, {method: 'PUT', url: url, query: query, body: body}, options));\n};\n\n/**\n * @param {string} url\n * @param {string} [query]\n * @param {object} [options]\n * @param {object} [options.headers]\n * @param {boolean} [options.skipAuthCheck]\n * @return {Promise}\n */\nPlatform.prototype['delete'] = function(url, query, options) {\n return this.send(objectAssign({}, {method: 'DELETE', url: url, query: query}, options));\n};\n\nPlatform.prototype.ensureLoggedIn = function() {\n if (this._isAccessTokenValid()) return this._externals.Promise.resolve();\n return this.refresh();\n};\n\n/**\n * @param path\n * @param body\n * @return {Promise.}\n * @private\n */\nPlatform.prototype._tokenRequest = function(path, body) {\n\n return this.send({\n url: path,\n skipAuthCheck: true,\n body: body,\n method: 'POST',\n headers: {\n 'Authorization': 'Basic ' + this._apiKey(),\n 'Content-Type': ApiResponse._urlencodedContentType\n }\n });\n\n};\n\n/**\n * @return {boolean}\n * @private\n */\nPlatform.prototype._isAccessTokenValid = function() {\n return this._auth.accessTokenValid();\n};\n\n/**\n * @return {string}\n * @private\n */\nPlatform.prototype._apiKey = function() {\n var apiKey = this._appKey + ':' + this._appSecret;\n return (typeof btoa == 'function') ? btoa(apiKey) : new Buffer(apiKey).toString('base64');\n};\n\n/**\n * @return {string}\n * @private\n */\nPlatform.prototype._authHeader = function() {\n var token = this._auth.accessToken();\n return this._auth.tokenType() + (token ? ' ' + token : '');\n};\n\nmodule.exports = Platform;\n\n/***/ },\n/* 16 */\n/***/ function(module, exports) {\n\n/**\n * @param {Cache} options.cache\n * @param {string} options.cacheId\n * @param {int} [options.refreshHandicapMs]\n * @constructor\n * @property {Cache} _cache\n * @property {int} _refreshHandicapMs\n * @property {string} _cacheId\n */\nfunction Auth(options) {\n\n /** @private */\n this._cache = options.cache;\n\n /** @private */\n this._cacheId = options.cacheId;\n\n /** @private */\n this._refreshHandicapMs = options.refreshHandicapMs || 60 * 1000; // 1 minute\n\n}\n\nAuth.prototype.accessToken = function() {\n return this.data().access_token;\n};\n\nAuth.prototype.refreshToken = function() {\n return this.data().refresh_token;\n};\n\nAuth.prototype.tokenType = function() {\n return this.data().token_type;\n};\n\n/**\n * @return {{token_type: string, access_token: string, expires_in: number, refresh_token: string, refresh_token_expires_in: number}}\n */\nAuth.prototype.data = function() {\n\n return this._cache.getItem(this._cacheId) || {\n token_type: '',\n access_token: '',\n expires_in: 0,\n refresh_token: '',\n refresh_token_expires_in: 0\n };\n\n};\n\n/**\n * @param {object} newData\n * @return {Auth}\n */\nAuth.prototype.setData = function(newData) {\n\n newData = newData || {};\n\n var data = this.data();\n\n Object.keys(newData).forEach(function(key) {\n data[key] = newData[key];\n });\n\n data.expire_time = Date.now() + (data.expires_in * 1000);\n data.refresh_token_expire_time = Date.now() + (data.refresh_token_expires_in * 1000);\n\n this._cache.setItem(this._cacheId, data);\n\n return this;\n\n};\n\n/**\n * Check if there is a valid (not expired) access token\n * @return {boolean}\n */\nAuth.prototype.accessTokenValid = function() {\n\n var authData = this.data();\n return (authData.expire_time - this._refreshHandicapMs > Date.now());\n\n};\n\n/**\n * Check if there is a valid (not expired) access token\n * @return {boolean}\n */\nAuth.prototype.refreshTokenValid = function() {\n\n return (this.data().refresh_token_expire_time > Date.now());\n\n};\n\n/**\n * @return {Auth}\n */\nAuth.prototype.cancelAccessToken = function() {\n\n return this.setData({\n access_token: '',\n expires_in: 0\n });\n\n};\n\nmodule.exports = Auth;\n\n//export interface IAuthData {\n// remember?:boolean;\n// token_type?:string;\n// access_token?:string;\n// expires_in?:number; // actually it's string\n// expire_time?:number;\n// refresh_token?:string;\n// refresh_token_expires_in?:number; // actually it's string\n// refresh_token_expire_time?:number;\n// scope?:string;\n//}\n\n\n/***/ },\n/* 17 */\n/***/ function(module, exports, __webpack_require__) {\n\nvar version = (\"3.1.0\");\n\n// This will become false during the Webpack build, so no traces of package.json will be there\nif (false) {\n version = require('../../package.json').version;\n}\n\nmodule.exports = {\n version: version,\n authResponseProperty: 'RCAuthorizationResponse'\n};\n\n/***/ },\n/* 18 */\n/***/ function(module, exports, __webpack_require__) {\n\nvar EventEmitter = __webpack_require__(6).EventEmitter;\n\n/**\n * @param {Platform} options.platform\n * @param {Externals} options.externals\n * @param {int} [options.pollInterval]\n * @param {int} [options.renewHandicapMs]\n * @property {Externals} _externals\n * @property {Platform} _platform\n * @property {int} _pollInterval\n * @property {int} _renewHandicapMs\n * @property {PUBNUB} _pubnub\n * @property {string} _pubnubLastChannel\n * @property {int} _timeout\n * @property {ISubscription} _subscription\n * @constructor\n */\nfunction Subscription(options) {\n\n EventEmitter.call(this);\n\n options = options || {};\n\n this.events = {\n notification: 'notification',\n removeSuccess: 'removeSuccess',\n removeError: 'removeError',\n renewSuccess: 'renewSuccess',\n renewError: 'renewError',\n subscribeSuccess: 'subscribeSuccess',\n subscribeError: 'subscribeError'\n };\n\n /** @private */\n this._externals = options.externals;\n\n /** @private */\n this._platform = options.platform;\n\n /** @private */\n this._pollInterval = options.pollInterval || 10 * 1000;\n\n /** @private */\n this._renewHandicapMs = options.renewHandicapMs || 2 * 60 * 1000;\n\n /** @private */\n this._pubnub = null;\n\n /** @private */\n this._pubnubLastChannel = null;\n\n /** @private */\n this._timeout = null;\n\n /** @private */\n this._subscription = null;\n\n}\n\nSubscription.prototype = Object.create(EventEmitter.prototype);\n\nSubscription.prototype.subscribed = function() {\n\n var subscription = this.subscription();\n\n return !!(subscription.id &&\n subscription.deliveryMode &&\n subscription.deliveryMode.subscriberKey &&\n subscription.deliveryMode.address);\n\n};\n\n/**\n * @return {boolean}\n */\nSubscription.prototype.alive = function() {\n return this.subscribed() && Date.now() < this.expirationTime();\n};\n\n/**\n * @return {boolean}\n */\nSubscription.prototype.expired = function() {\n if (!this.subscribed()) return true;\n return !this.subscribed() || Date.now() > this.subscription().expirationTime;\n};\n\nSubscription.prototype.expirationTime = function() {\n return new Date(this.subscription().expirationTime || 0).getTime() - this._renewHandicapMs;\n};\n\n/**\n * @param {ISubscription} subscription\n * @return {Subscription}\n */\nSubscription.prototype.setSubscription = function(subscription) {\n\n subscription = subscription || {};\n\n this._clearTimeout();\n this._setSubscription(subscription);\n this._subscribeAtPubnub();\n this._setTimeout();\n\n return this;\n\n};\n\n/**\n * @return {ISubscription}\n */\nSubscription.prototype.subscription = function() {\n return this._subscription || {};\n};\n\n/**\n * Creates or updates subscription if there is an active one\n * @returns {Promise}\n */\nSubscription.prototype.register = function() {\n\n if (this.alive()) {\n return this.renew();\n } else {\n return this.subscribe();\n }\n\n};\n\n/**\n * @return {string[]}\n */\nSubscription.prototype.eventFilters = function() {\n return this.subscription().eventFilters || [];\n};\n\n/**\n * @param {string[]} events\n * @return {Subscription}\n */\nSubscription.prototype.addEventFilters = function(events) {\n this.setEventFilters(this.eventFilters().concat(events));\n return this;\n};\n\n/**\n * @param {string[]} events\n * @return {Subscription}\n */\nSubscription.prototype.setEventFilters = function(events) {\n var subscription = this.subscription();\n subscription.eventFilters = events;\n this._setSubscription(subscription);\n return this;\n};\n\n/**\n * @returns {Promise}\n */\nSubscription.prototype.subscribe = function() {\n\n return (new this._externals.Promise(function(resolve) {\n\n this._clearTimeout();\n\n if (!this.eventFilters().length) throw new Error('Events are undefined');\n\n resolve(this._platform.post('/subscription', {\n eventFilters: this._getFullEventFilters(),\n deliveryMode: {\n transportType: 'PubNub'\n }\n }));\n\n }.bind(this))).then(function(response) {\n\n var json = response.json();\n\n this.setSubscription(json)\n .emit(this.events.subscribeSuccess, response);\n\n return response;\n\n }.bind(this)).catch(function(e) {\n\n e = this._platform.client().makeError(e);\n\n this.reset()\n .emit(this.events.subscribeError, e);\n\n throw e;\n\n }.bind(this));\n\n};\n\n/**\n * @returns {Promise}\n */\nSubscription.prototype.renew = function() {\n\n return (new this._externals.Promise(function(resolve) {\n\n this._clearTimeout();\n\n if (!this.subscribed()) throw new Error('No subscription');\n\n if (!this.eventFilters().length) throw new Error('Events are undefined');\n\n resolve(this._platform.put('/subscription/' + this.subscription().id, {\n eventFilters: this._getFullEventFilters()\n }));\n\n }.bind(this))).then(function(response) {\n\n var json = response.json();\n\n this.setSubscription(json)\n .emit(this.events.renewSuccess, response);\n\n return response;\n\n }.bind(this)).catch(function(e) {\n\n e = this._platform.client().makeError(e);\n\n this.reset()\n .emit(this.events.renewError, e);\n\n throw e;\n\n }.bind(this));\n\n};\n\n/**\n * @returns {Promise}\n */\nSubscription.prototype.remove = function() {\n\n return (new this._externals.Promise(function(resolve) {\n\n if (!this.subscribed()) throw new Error('No subscription');\n\n resolve(this._platform.delete('/subscription/' + this.subscription().id));\n\n }.bind(this))).then(function(response) {\n\n this.reset()\n .emit(this.events.removeSuccess, response);\n\n return response;\n\n }.bind(this)).catch(function(e) {\n\n e = this._platform.client().makeError(e);\n\n this.emit(this.events.removeError, e);\n\n throw e;\n\n }.bind(this));\n\n};\n\n/**\n * @returns {Promise}\n */\nSubscription.prototype.resubscribe = function() {\n var filters = this.eventFilters();\n return this.reset().setEventFilters(filters).subscribe();\n};\n\n/**\n * Remove subscription and disconnect from PubNub\n * This method resets subscription at client side but backend is not notified\n * @return {Subscription}\n */\nSubscription.prototype.reset = function() {\n this._clearTimeout();\n if (this.subscribed() && this._pubnub) this._pubnub.unsubscribe({channel: this.subscription().deliveryMode.address});\n this._setSubscription(null);\n return this;\n};\n\n/**\n * @param subscription\n * @private\n */\nSubscription.prototype._setSubscription = function(subscription) {\n this._subscription = subscription;\n};\n\n/**\n * @return {string[]}\n * @private\n */\nSubscription.prototype._getFullEventFilters = function() {\n\n return this.eventFilters().map(function(event) {\n return this._platform.createUrl(event);\n }.bind(this));\n\n};\n\n/**\n * @return {Subscription}\n * @private\n */\nSubscription.prototype._setTimeout = function() {\n\n this._clearTimeout();\n\n if (!this.alive()) throw new Error('Subscription is not alive');\n\n this._timeout = setInterval(function() {\n\n if (this.alive()) return;\n\n if (this.expired()) {\n this.subscribe();\n } else {\n this.renew();\n }\n\n }.bind(this), this._pollInterval);\n\n return this;\n\n};\n\n/**\n * @return {Subscription}\n * @private\n */\nSubscription.prototype._clearTimeout = function() {\n clearInterval(this._timeout);\n return this;\n};\n\nSubscription.prototype._decrypt = function(message) {\n\n if (!this.subscribed()) throw new Error('No subscription');\n\n if (this.subscription().deliveryMode.encryptionKey) {\n\n message = this._pubnub.decrypt(message, this.subscription().deliveryMode.encryptionKey, {\n encryptKey: false,\n keyEncoding: 'base64',\n keyLength: 128,\n mode: 'ecb'\n });\n\n }\n\n return message;\n\n};\n\n/**\n * @param message\n * @return {Subscription}\n * @private\n */\nSubscription.prototype._notify = function(message) {\n this.emit(this.events.notification, this._decrypt(message));\n return this;\n};\n\n/**\n * @return {Subscription}\n * @private\n */\nSubscription.prototype._subscribeAtPubnub = function() {\n\n if (!this.alive()) throw new Error('Subscription is not alive');\n\n var deliveryMode = this.subscription().deliveryMode;\n\n if (this._pubnub) {\n\n if (this._pubnubLastChannel == deliveryMode.address) { // Nothing to update, keep listening to same channel\n return this;\n } else if (this._pubnubLastChannel) { // Need to subscribe to new channel\n this._pubnub.unsubscribe({channel: this._pubnubLastChannel});\n }\n\n // Re-init for new data\n this._pubnub = this._pubnub.init({\n ssl: true,\n subscribe_key: deliveryMode.subscriberKey\n });\n\n } else {\n\n // Init from scratch\n this._pubnub = new this._externals.PubNub({\n ssl: true,\n subscribe_key: deliveryMode.subscriberKey\n });\n\n }\n\n this._pubnubLastChannel = deliveryMode.address;\n\n this._pubnub.subscribe({\n channel: deliveryMode.address,\n message: this._notify.bind(this),\n connect: function() {}\n });\n\n return this;\n\n};\n\nmodule.exports = Subscription;\n\n/**\n * The complete Triforce, or one or more components of the Triforce.\n * @typedef {Object} ISubscription\n * @property {string} [id]\n * @property {string} [uri]\n * @property {string[]} [eventFilters]\n * @property {string} [expirationTime] Format: 2014-03-12T19:54:35.613Z\n * @property {int} [expiresIn]\n * @property {string} [deliveryMode.transportType]\n * @property {boolean} [deliveryMode.encryption]\n * @property {string} [deliveryMode.address]\n * @property {string} [deliveryMode.subscriberKey]\n * @property {string} [deliveryMode.encryptionKey]\n * @property {string} [deliveryMode.secretKey]\n * @property {string} [creationTime]\n * @property {string} [status] Active\n */\n\n/***/ },\n/* 19 */\n/***/ function(module, exports, __webpack_require__) {\n\nvar Subscription = __webpack_require__(18);\n\n/**\n * @param {Platform} options.platform\n * @param {Externals} options.externals\n * @param {Cache} options.cache\n * @param {string} options.cacheKey\n * @param {int} [options.pollInterval]\n * @param {int} [options.renewHandicapMs]\n * @return {CachedSubscription}\n * @constructor\n * @property {Cache} _cache\n * @extends Subscription\n */\nfunction CachedSubscription(options) {\n\n options = options || {};\n\n if (!options.cacheKey) throw new Error('Cached Subscription requires cacheKey parameter to be defined');\n\n /** @private */\n this._cacheKey = options.cacheKey;\n\n Subscription.call(this, options);\n\n /** @private */\n this._cache = options.cache;\n\n // This is not used in this class\n this._subscription = undefined;\n\n}\n\nCachedSubscription.prototype = Object.create(Subscription.prototype);\n\nCachedSubscription.prototype.subscription = function() {\n return this._cache.getItem(this._cacheKey) || {};\n};\n\nCachedSubscription.prototype._setSubscription = function(subscription) {\n return this._cache.setItem(this._cacheKey, subscription);\n};\n\n/**\n * This function checks whether there are any pre-defined eventFilters in cache and if not -- uses provided as defaults\n * @param {string[]} events\n * @return {CachedSubscription}\n */\nCachedSubscription.prototype.restore = function(events) {\n\n if (!this.eventFilters().length) {\n this.setEventFilters(events);\n }\n\n return this;\n\n};\n\nmodule.exports = CachedSubscription;\n\n/***/ }\n/******/ ])\n});\n;\n\n\n// WEBPACK FOOTER //\n// ringcentral.min.js"," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId])\n \t\t\treturn installedModules[moduleId].exports;\n\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\texports: {},\n \t\t\tid: moduleId,\n \t\t\tloaded: false\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.loaded = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"/build/\";\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(0);\n\n\n\n// WEBPACK FOOTER //\n// webpack/bootstrap c20b2b45729ee57a5332","/**\n * @namespace RingCentral\n */\nvar objectAssign = require('object-assign');\nvar Cache = require(\"./core/Cache\");\nvar Client = require(\"./http/Client\");\nvar Externals = require(\"./core/Externals\");\nvar Platform = require(\"./platform/Platform\");\nvar Subscription = require(\"./subscription/Subscription\");\nvar CachedSubscription = require(\"./subscription/CachedSubscription\");\nvar Constants = require(\"./core/Constants\");\n\n/**\n * @constructor\n * @param {string} options.server\n * @param {string} options.appSecret\n * @param {string} options.appKey\n * @param {string} [options.cachePrefix]\n * @param {string} [options.appName]\n * @param {string} [options.appVersion]\n * @param {string} [options.redirectUri]\n * @param {PubNub} [options.PubNub]\n * @param {function(new:Promise)} [options.Promise]\n * @param {Storage} [options.localStorage]\n * @param {fetch} [options.fetch]\n * @param {function(new:Request)} [options.Request]\n * @param {function(new:Response)} [options.Response]\n * @param {function(new:Headers)} [options.Headers]\n * @param {int} [options.refreshDelayMs]\n * @param {int} [options.refreshHandicapMs]\n * @param {boolean} [options.clearCacheOnRefreshError]\n * @property {Externals} _externals\n * @property {Cache} _cache\n * @property {Client} _client\n * @property {Platform} _platform\n */\nfunction SDK(options) {\n\n /** @private */\n this._externals = new Externals(options);\n\n /** @private */\n this._cache = new Cache({\n externals: this._externals,\n prefix: options.cachePrefix\n });\n\n /** @private */\n this._client = new Client(this._externals);\n\n /** @private */\n this._platform = new Platform(objectAssign({}, options, {\n externals: this._externals,\n client: this._client,\n cache: this._cache\n }));\n\n}\n\nSDK.version = Constants.version;\n\nSDK.server = {\n sandbox: 'https://platform.devtest.ringcentral.com',\n production: 'https://platform.ringcentral.com'\n};\n\n/**\n * @return {Platform}\n */\nSDK.prototype.platform = function() {\n return this._platform;\n};\n\n/**\n * @return {Cache}\n */\nSDK.prototype.cache = function() {\n return this._cache;\n};\n\n/**\n * @param {int} [options.pollInterval]\n * @param {int} [options.renewHandicapMs]\n * @return {Subscription}\n */\nSDK.prototype.createSubscription = function(options) {\n return new Subscription(objectAssign({}, options, {\n externals: this._externals,\n platform: this._platform\n }));\n};\n\n/**\n * @param {string} options.cacheKey\n * @param {int} [options.pollInterval]\n * @param {int} [options.renewHandicapMs]\n * @return {CachedSubscription}\n */\nSDK.prototype.createCachedSubscription = function(options) {\n\n if (typeof arguments[0] == 'string') {\n options = {cacheKey: arguments[0].toString()};\n } else {\n options = options || {};\n }\n\n return new CachedSubscription(objectAssign({}, options, {\n externals: this._externals,\n platform: this._platform,\n cache: this._cache\n }));\n\n};\n\nSDK.handleLoginRedirect = function(origin) {\n\n var response = window.location.hash ? window.location.hash : window.location.search;\n var msg = {};\n msg[Constants.authResponseProperty] = response;\n window.opener.postMessage(msg, origin || window.location.origin);\n\n};\n\nmodule.exports = SDK;\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/SDK.js\n// module id = 0\n// module chunks = 0 1","/*\nobject-assign\n(c) Sindre Sorhus\n@license MIT\n*/\n\n'use strict';\n/* eslint-disable no-unused-vars */\nvar getOwnPropertySymbols = Object.getOwnPropertySymbols;\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\nvar propIsEnumerable = Object.prototype.propertyIsEnumerable;\n\nfunction toObject(val) {\n\tif (val === null || val === undefined) {\n\t\tthrow new TypeError('Object.assign cannot be called with null or undefined');\n\t}\n\n\treturn Object(val);\n}\n\nfunction shouldUseNative() {\n\ttry {\n\t\tif (!Object.assign) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// Detect buggy property enumeration order in older V8 versions.\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=4118\n\t\tvar test1 = new String('abc'); // eslint-disable-line no-new-wrappers\n\t\ttest1[5] = 'de';\n\t\tif (Object.getOwnPropertyNames(test1)[0] === '5') {\n\t\t\treturn false;\n\t\t}\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=3056\n\t\tvar test2 = {};\n\t\tfor (var i = 0; i < 10; i++) {\n\t\t\ttest2['_' + String.fromCharCode(i)] = i;\n\t\t}\n\t\tvar order2 = Object.getOwnPropertyNames(test2).map(function (n) {\n\t\t\treturn test2[n];\n\t\t});\n\t\tif (order2.join('') !== '0123456789') {\n\t\t\treturn false;\n\t\t}\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=3056\n\t\tvar test3 = {};\n\t\t'abcdefghijklmnopqrst'.split('').forEach(function (letter) {\n\t\t\ttest3[letter] = letter;\n\t\t});\n\t\tif (Object.keys(Object.assign({}, test3)).join('') !==\n\t\t\t\t'abcdefghijklmnopqrst') {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t} catch (err) {\n\t\t// We don't expect any of the above to throw, but better to be safe.\n\t\treturn false;\n\t}\n}\n\nmodule.exports = shouldUseNative() ? Object.assign : function (target, source) {\n\tvar from;\n\tvar to = toObject(target);\n\tvar symbols;\n\n\tfor (var s = 1; s < arguments.length; s++) {\n\t\tfrom = Object(arguments[s]);\n\n\t\tfor (var key in from) {\n\t\t\tif (hasOwnProperty.call(from, key)) {\n\t\t\t\tto[key] = from[key];\n\t\t\t}\n\t\t}\n\n\t\tif (getOwnPropertySymbols) {\n\t\t\tsymbols = getOwnPropertySymbols(from);\n\t\t\tfor (var i = 0; i < symbols.length; i++) {\n\t\t\t\tif (propIsEnumerable.call(from, symbols[i])) {\n\t\t\t\t\tto[symbols[i]] = from[symbols[i]];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn to;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/object-assign/index.js\n// module id = 1\n// module chunks = 0 1","/**\n * @param {Externals} options.externals\n * @param {string} [options.prefix]\n * @property {Externals} _externals\n */\nfunction Cache(options) {\n\n /** @private */\n this._prefix = options.prefix || Cache.defaultPrefix;\n\n /** @private */\n this._externals = options.externals;\n\n}\n\nCache.defaultPrefix = 'rc-';\n\nCache.prototype.setItem = function(key, data) {\n this._externals.localStorage[this._prefixKey(key)] = JSON.stringify(data);\n return this;\n};\n\nCache.prototype.removeItem = function(key) {\n delete this._externals.localStorage[this._prefixKey(key)];\n return this;\n};\n\nCache.prototype.getItem = function(key) {\n var item = this._externals.localStorage[this._prefixKey(key)];\n if (!item) return null;\n return JSON.parse(item);\n};\n\nCache.prototype.clean = function() {\n\n for (var key in this._externals.localStorage) {\n\n if (!this._externals.localStorage.hasOwnProperty(key)) continue;\n\n if (key.indexOf(this._prefix) === 0) {\n delete this._externals.localStorage[key];\n }\n\n }\n\n return this;\n\n};\n\nCache.prototype._prefixKey = function(key) {\n return this._prefix + key;\n};\n\nmodule.exports = Cache;\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/core/Cache.js\n// module id = 2\n// module chunks = 0 1","var isPlainObject = require(\"is-plain-object\");\nvar EventEmitter = require(\"events\").EventEmitter;\nvar ApiResponse = require(\"./ApiResponse\");\nvar qs = require(\"querystring\");\n\nfunction findHeaderName(name, headers) {\n name = name.toLowerCase();\n return Object.keys(headers).reduce(function(res, key) {\n if (res) return res;\n if (name == key.toLowerCase()) return key;\n return res;\n }, null);\n}\n\n/**\n * @param {Externals} externals\n * @property {Externals} _externals\n */\nfunction Client(externals) {\n\n EventEmitter.call(this);\n\n /** @private */\n this._externals = externals;\n\n this.events = {\n beforeRequest: 'beforeRequest',\n requestSuccess: 'requestSuccess',\n requestError: 'requestError'\n };\n\n}\n\nClient._allowedMethods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS', 'HEAD'];\n\nClient.prototype = Object.create(EventEmitter.prototype);\n\n/**\n * @param {Request} request\n * @return {Promise}\n */\nClient.prototype.sendRequest = function(request) {\n\n var apiResponse = new ApiResponse({\n externals: this._externals,\n request: request\n });\n\n return (new this._externals.Promise(function(resolve) {\n\n //TODO Stop request if listeners return false\n this.emit(this.events.beforeRequest, apiResponse);\n\n resolve(this._loadResponse(request));\n\n }.bind(this))).then(function(response) {\n\n return apiResponse.receiveResponse(response);\n\n }).then(function() {\n\n if (!apiResponse.ok()) throw new Error('Response has unsuccessful status');\n\n this.emit(this.events.requestSuccess, apiResponse);\n\n return apiResponse;\n\n }.bind(this)).catch(function(e) {\n\n if (!e.apiResponse) e = this.makeError(e, apiResponse);\n\n this.emit(this.events.requestError, e);\n\n throw e;\n\n }.bind(this));\n\n};\n\n/**\n * @param {Request} request\n * @return {Promise}\n * @private\n */\nClient.prototype._loadResponse = function(request) {\n return this._externals.fetch.call(null, request);\n};\n\n/**\n * Wraps the JS Error object with transaction information\n * @param {Error|IApiError} e\n * @param {ApiResponse} apiResponse\n * @return {IApiError}\n */\nClient.prototype.makeError = function(e, apiResponse) {\n\n // Wrap only if regular error\n if (!e.hasOwnProperty('apiResponse') && !e.hasOwnProperty('originalMessage')) {\n\n e.apiResponse = apiResponse;\n e.originalMessage = e.message;\n e.message = (apiResponse && apiResponse.error(true)) || e.originalMessage;\n\n }\n\n return e;\n\n};\n\n/**\n *\n * @param {object} init\n * @param {object} [init.url]\n * @param {object} [init.body]\n * @param {string} [init.method]\n * @param {object} [init.query]\n * @param {object} [init.headers]\n * @param {object} [init.credentials]\n * @param {object} [init.mode]\n * @return {Request}\n */\nClient.prototype.createRequest = function(init) {\n\n init = init || {};\n init.headers = init.headers || {};\n\n // Sanity checks\n if (!init.url) throw new Error('Url is not defined');\n if (!init.method) init.method = 'GET';\n init.method = init.method.toUpperCase();\n if (init.method && Client._allowedMethods.indexOf(init.method) < 0) {\n throw new Error('Method has wrong value: ' + init.method);\n }\n\n // Defaults\n init.credentials = init.credentials || 'include';\n init.mode = init.mode || 'cors';\n\n // Append Query String\n if (init.query) {\n init.url = init.url + (init.url.indexOf('?') > -1 ? '&' : '?') + qs.stringify(init.query);\n }\n\n if (!(findHeaderName('Accept', init.headers))) {\n init.headers.Accept = ApiResponse._jsonContentType;\n }\n\n // Serialize body\n if (isPlainObject(init.body) || !init.body) {\n\n var contentTypeHeaderName = findHeaderName(ApiResponse._contentType, init.headers);\n\n if (!contentTypeHeaderName) {\n contentTypeHeaderName = ApiResponse._contentType;\n init.headers[contentTypeHeaderName] = ApiResponse._jsonContentType;\n }\n\n var contentType = init.headers[contentTypeHeaderName];\n\n // Assign a new encoded body\n if (contentType.indexOf(ApiResponse._jsonContentType) > -1) {\n if ((init.method === 'GET' || init.method === 'HEAD') && !!init.body) {\n // oddly setting body to null still result in TypeError in phantomjs\n init.body = undefined;\n } else {\n init.body = JSON.stringify(init.body);\n }\n\n } else if (contentType.indexOf(ApiResponse._urlencodedContentType) > -1) {\n init.body = qs.stringify(init.body);\n }\n\n }\n\n // Create a request with encoded body\n var req = new this._externals.Request(init.url, init);\n\n // Keep the original body accessible directly (for mocks)\n req.originalBody = init.body;\n\n return req;\n\n};\n\n/**\n * @typedef {object} IApiError\n * @property {string} stack\n * @property {string} originalMessage\n * @property {ApiResponse} apiResponse\n */\n\nmodule.exports = Client;\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/http/Client.js\n// module id = 3\n// module chunks = 0 1","/*!\n * is-plain-object \n *\n * Copyright (c) 2014-2015, Jon Schlinkert.\n * Licensed under the MIT License.\n */\n\n'use strict';\n\nvar isObject = require('isobject');\n\nfunction isObjectObject(o) {\n return isObject(o) === true\n && Object.prototype.toString.call(o) === '[object Object]';\n}\n\nmodule.exports = function isPlainObject(o) {\n var ctor,prot;\n \n if (isObjectObject(o) === false) return false;\n \n // If has modified constructor\n ctor = o.constructor;\n if (typeof ctor !== 'function') return false;\n \n // If has modified prototype\n prot = ctor.prototype;\n if (isObjectObject(prot) === false) return false;\n \n // If constructor does not have an Object-specific method\n if (prot.hasOwnProperty('isPrototypeOf') === false) {\n return false;\n }\n \n // Most likely a plain Object\n return true;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/is-plain-object/index.js\n// module id = 4\n// module chunks = 0 1","/*!\n * isobject \n *\n * Copyright (c) 2014-2015, Jon Schlinkert.\n * Licensed under the MIT License.\n */\n\n'use strict';\n\nmodule.exports = function isObject(val) {\n return val != null && typeof val === 'object'\n && !Array.isArray(val);\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/isobject/index.js\n// module id = 5\n// module chunks = 0 1","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nfunction EventEmitter() {\n this._events = this._events || {};\n this._maxListeners = this._maxListeners || undefined;\n}\nmodule.exports = EventEmitter;\n\n// Backwards-compat with node 0.10.x\nEventEmitter.EventEmitter = EventEmitter;\n\nEventEmitter.prototype._events = undefined;\nEventEmitter.prototype._maxListeners = undefined;\n\n// By default EventEmitters will print a warning if more than 10 listeners are\n// added to it. This is a useful default which helps finding memory leaks.\nEventEmitter.defaultMaxListeners = 10;\n\n// Obviously not all Emitters should be limited to 10. This function allows\n// that to be increased. Set to zero for unlimited.\nEventEmitter.prototype.setMaxListeners = function(n) {\n if (!isNumber(n) || n < 0 || isNaN(n))\n throw TypeError('n must be a positive number');\n this._maxListeners = n;\n return this;\n};\n\nEventEmitter.prototype.emit = function(type) {\n var er, handler, len, args, i, listeners;\n\n if (!this._events)\n this._events = {};\n\n // If there is no 'error' event listener then throw.\n if (type === 'error') {\n if (!this._events.error ||\n (isObject(this._events.error) && !this._events.error.length)) {\n er = arguments[1];\n if (er instanceof Error) {\n throw er; // Unhandled 'error' event\n } else {\n // At least give some kind of context to the user\n var err = new Error('Uncaught, unspecified \"error\" event. (' + er + ')');\n err.context = er;\n throw err;\n }\n }\n }\n\n handler = this._events[type];\n\n if (isUndefined(handler))\n return false;\n\n if (isFunction(handler)) {\n switch (arguments.length) {\n // fast cases\n case 1:\n handler.call(this);\n break;\n case 2:\n handler.call(this, arguments[1]);\n break;\n case 3:\n handler.call(this, arguments[1], arguments[2]);\n break;\n // slower\n default:\n args = Array.prototype.slice.call(arguments, 1);\n handler.apply(this, args);\n }\n } else if (isObject(handler)) {\n args = Array.prototype.slice.call(arguments, 1);\n listeners = handler.slice();\n len = listeners.length;\n for (i = 0; i < len; i++)\n listeners[i].apply(this, args);\n }\n\n return true;\n};\n\nEventEmitter.prototype.addListener = function(type, listener) {\n var m;\n\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n if (!this._events)\n this._events = {};\n\n // To avoid recursion in the case that type === \"newListener\"! Before\n // adding it to the listeners, first emit \"newListener\".\n if (this._events.newListener)\n this.emit('newListener', type,\n isFunction(listener.listener) ?\n listener.listener : listener);\n\n if (!this._events[type])\n // Optimize the case of one listener. Don't need the extra array object.\n this._events[type] = listener;\n else if (isObject(this._events[type]))\n // If we've already got an array, just append.\n this._events[type].push(listener);\n else\n // Adding the second element, need to change to array.\n this._events[type] = [this._events[type], listener];\n\n // Check for listener leak\n if (isObject(this._events[type]) && !this._events[type].warned) {\n if (!isUndefined(this._maxListeners)) {\n m = this._maxListeners;\n } else {\n m = EventEmitter.defaultMaxListeners;\n }\n\n if (m && m > 0 && this._events[type].length > m) {\n this._events[type].warned = true;\n console.error('(node) warning: possible EventEmitter memory ' +\n 'leak detected. %d listeners added. ' +\n 'Use emitter.setMaxListeners() to increase limit.',\n this._events[type].length);\n if (typeof console.trace === 'function') {\n // not supported in IE 10\n console.trace();\n }\n }\n }\n\n return this;\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.once = function(type, listener) {\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n var fired = false;\n\n function g() {\n this.removeListener(type, g);\n\n if (!fired) {\n fired = true;\n listener.apply(this, arguments);\n }\n }\n\n g.listener = listener;\n this.on(type, g);\n\n return this;\n};\n\n// emits a 'removeListener' event iff the listener was removed\nEventEmitter.prototype.removeListener = function(type, listener) {\n var list, position, length, i;\n\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n if (!this._events || !this._events[type])\n return this;\n\n list = this._events[type];\n length = list.length;\n position = -1;\n\n if (list === listener ||\n (isFunction(list.listener) && list.listener === listener)) {\n delete this._events[type];\n if (this._events.removeListener)\n this.emit('removeListener', type, listener);\n\n } else if (isObject(list)) {\n for (i = length; i-- > 0;) {\n if (list[i] === listener ||\n (list[i].listener && list[i].listener === listener)) {\n position = i;\n break;\n }\n }\n\n if (position < 0)\n return this;\n\n if (list.length === 1) {\n list.length = 0;\n delete this._events[type];\n } else {\n list.splice(position, 1);\n }\n\n if (this._events.removeListener)\n this.emit('removeListener', type, listener);\n }\n\n return this;\n};\n\nEventEmitter.prototype.removeAllListeners = function(type) {\n var key, listeners;\n\n if (!this._events)\n return this;\n\n // not listening for removeListener, no need to emit\n if (!this._events.removeListener) {\n if (arguments.length === 0)\n this._events = {};\n else if (this._events[type])\n delete this._events[type];\n return this;\n }\n\n // emit removeListener for all listeners on all events\n if (arguments.length === 0) {\n for (key in this._events) {\n if (key === 'removeListener') continue;\n this.removeAllListeners(key);\n }\n this.removeAllListeners('removeListener');\n this._events = {};\n return this;\n }\n\n listeners = this._events[type];\n\n if (isFunction(listeners)) {\n this.removeListener(type, listeners);\n } else if (listeners) {\n // LIFO order\n while (listeners.length)\n this.removeListener(type, listeners[listeners.length - 1]);\n }\n delete this._events[type];\n\n return this;\n};\n\nEventEmitter.prototype.listeners = function(type) {\n var ret;\n if (!this._events || !this._events[type])\n ret = [];\n else if (isFunction(this._events[type]))\n ret = [this._events[type]];\n else\n ret = this._events[type].slice();\n return ret;\n};\n\nEventEmitter.prototype.listenerCount = function(type) {\n if (this._events) {\n var evlistener = this._events[type];\n\n if (isFunction(evlistener))\n return 1;\n else if (evlistener)\n return evlistener.length;\n }\n return 0;\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n return emitter.listenerCount(type);\n};\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/events/events.js\n// module id = 6\n// module chunks = 0 1","/**\n * @param {Externals} options.externals\n * @param {Request} [options.request]\n * @param {Response} [options.response]\n * @param {string} [options.responseText]\n * @property {Externals} _externals\n * @property {Request} _request\n * @property {Response} _response\n * @property {string} _text\n * @property {object} _json\n * @property {ApiResponse[]} _multipart\n */\nfunction ApiResponse(options) {\n\n /** @private */\n this._externals = options.externals;\n\n /** @private */\n this._request = options.request;\n\n /** @private */\n this._response = options.response;\n\n /** @private */\n this._text = options.responseText || '';\n\n /** @private */\n this._json = null;\n\n /** @private */\n this._multipart = [];\n\n}\n\nApiResponse._contentType = 'Content-Type';\nApiResponse._jsonContentType = 'application/json';\nApiResponse._multipartContentType = 'multipart/mixed';\nApiResponse._urlencodedContentType = 'application/x-www-form-urlencoded';\nApiResponse._headerSeparator = ':';\nApiResponse._bodySeparator = '\\n\\n';\nApiResponse._boundarySeparator = '--';\nApiResponse._unauthorizedStatus = 401;\n\n/**\n * @param {Response} response\n * @return {Promise}\n */\nApiResponse.prototype.receiveResponse = function(response) {\n\n this._response = response;\n\n return (new this._externals.Promise(function(resolve) {\n\n // Ignore if not textual type\n if (!this._isMultipart() && !this._isJson()) return resolve('');\n\n return resolve(this.response().text());\n\n }.bind(this))).then(function(text) {\n\n this._text = text;\n return text;\n\n }.bind(this));\n\n};\n\n/**\n * @return {Response}\n */\nApiResponse.prototype.response = function() {\n return this._response;\n};\n\n/**\n * @return {Request}\n */\nApiResponse.prototype.request = function() {\n return this._request;\n};\n\n/**\n * @return {boolean}\n */\nApiResponse.prototype.ok = function() {\n return this._response && this._response.ok;\n};\n\n/**\n * @return {string}\n */\nApiResponse.prototype.text = function() {\n // Since we read text only in case JSON or Multipart\n if (!this._isJson() && !this._isMultipart()) throw new Error('Response is not text');\n return this._text;\n};\n\n/**\n * @return {object}\n */\nApiResponse.prototype.json = function() {\n if (!this._isJson()) throw new Error('Response is not JSON');\n if (!this._json) {\n this._json = this._text ? JSON.parse(this._text) : null;\n }\n return this._json;\n};\n\n/**\n * @param [skipOKCheck]\n * @return {string}\n */\nApiResponse.prototype.error = function(skipOKCheck) {\n\n if (this.ok() && !skipOKCheck) return null;\n\n var message = (this._response && this._response.status ? this._response.status + ' ' : '') +\n (this._response && this._response.statusText ? this._response.statusText : '');\n\n try {\n\n if (this.json().message) message = this.json().message;\n if (this.json().error_description) message = this.json().error_description;\n if (this.json().description) message = this.json().description;\n\n } catch (e) {}\n\n return message;\n\n};\n\n/**\n * If it is not known upfront what would be the response, client code can treat any response as multipart\n * @return {ApiResponse[]}\n */\nApiResponse.prototype.toMultipart = function() {\n if (!this._isMultipart()) return [this];\n return this.multipart();\n};\n\n/**\n * @return {ApiResponse[]}\n */\nApiResponse.prototype.multipart = function() {\n\n if (!this._isMultipart()) throw new Error('Response is not multipart');\n\n if (!this._multipart.length) {\n\n // Step 1. Split multipart response\n\n var text = this.text();\n\n if (!text) throw new Error('No response body');\n\n var boundary = this._getContentType().match(/boundary=([^;]+)/i)[1];\n\n if (!boundary) throw new Error('Cannot find boundary');\n\n var parts = text.toString().split(ApiResponse._boundarySeparator + boundary);\n\n if (parts[0].trim() === '') parts.shift();\n if (parts[parts.length - 1].trim() == ApiResponse._boundarySeparator) parts.pop();\n\n if (parts.length < 1) throw new Error('No parts in body');\n\n // Step 2. Parse status info\n\n var statusInfo = this._create(parts.shift(), this._response.status, this._response.statusText).json();\n\n // Step 3. Parse all other parts\n\n this._multipart = parts.map(function(part, i) {\n\n var status = statusInfo.response[i].status;\n\n return this._create(part, status);\n\n }.bind(this));\n\n }\n\n return this._multipart;\n\n};\n\n/**\n * @private\n */\nApiResponse.prototype._isContentType = function(contentType) {\n return this._getContentType().indexOf(contentType) > -1;\n};\n\n/**\n * @private\n */\nApiResponse.prototype._getContentType = function() {\n return this._response.headers.get(ApiResponse._contentType) || '';\n};\n\n/**\n * @private\n */\nApiResponse.prototype._isMultipart = function() {\n return this._isContentType(ApiResponse._multipartContentType);\n};\n\n/**\n * @private\n */\nApiResponse.prototype._isJson = function() {\n return this._isContentType(ApiResponse._jsonContentType);\n};\n\n/**\n * Method is used to create ApiResponse object from string parts of multipart/mixed response\n * @param {string} [text]\n * @param {number} [status]\n * @param {string} [statusText]\n * @private\n * @return {ApiResponse}\n */\nApiResponse.prototype._create = function(text, status, statusText) {\n\n text = text || '';\n status = status || 200;\n statusText = statusText || 'OK';\n\n text = text.replace(/\\r/g, '');\n\n var headers = new this._externals.Headers(),\n headersAndBody = text.split(ApiResponse._bodySeparator),\n headersText = (headersAndBody.length > 1) ? headersAndBody.shift() : '';\n\n text = headersAndBody.length > 0 ? headersAndBody.join(ApiResponse._bodySeparator) : null;\n\n (headersText || '')\n .split('\\n')\n .forEach(function(header) {\n\n var split = header.trim().split(ApiResponse._headerSeparator),\n key = split.shift().trim(),\n value = split.join(ApiResponse._headerSeparator).trim();\n\n if (key) headers.append(key, value);\n\n });\n\n var response = new this._externals.Response(text, {\n headers: headers,\n status: status,\n statusText: statusText\n });\n\n return new ApiResponse({\n externals: this._externals,\n request: null,\n response: response,\n responseText: text\n });\n\n};\n\nmodule.exports = ApiResponse;\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/http/ApiResponse.js\n// module id = 7\n// module chunks = 0 1","'use strict';\n\nexports.decode = exports.parse = require('./decode');\nexports.encode = exports.stringify = require('./encode');\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/querystring/index.js\n// module id = 8\n// module chunks = 0 1","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n// If obj.hasOwnProperty has been overridden, then calling\n// obj.hasOwnProperty(prop) will break.\n// See: https://github.com/joyent/node/issues/1707\nfunction hasOwnProperty(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n\nmodule.exports = function(qs, sep, eq, options) {\n sep = sep || '&';\n eq = eq || '=';\n var obj = {};\n\n if (typeof qs !== 'string' || qs.length === 0) {\n return obj;\n }\n\n var regexp = /\\+/g;\n qs = qs.split(sep);\n\n var maxKeys = 1000;\n if (options && typeof options.maxKeys === 'number') {\n maxKeys = options.maxKeys;\n }\n\n var len = qs.length;\n // maxKeys <= 0 means that we should not limit keys count\n if (maxKeys > 0 && len > maxKeys) {\n len = maxKeys;\n }\n\n for (var i = 0; i < len; ++i) {\n var x = qs[i].replace(regexp, '%20'),\n idx = x.indexOf(eq),\n kstr, vstr, k, v;\n\n if (idx >= 0) {\n kstr = x.substr(0, idx);\n vstr = x.substr(idx + 1);\n } else {\n kstr = x;\n vstr = '';\n }\n\n k = decodeURIComponent(kstr);\n v = decodeURIComponent(vstr);\n\n if (!hasOwnProperty(obj, k)) {\n obj[k] = v;\n } else if (Array.isArray(obj[k])) {\n obj[k].push(v);\n } else {\n obj[k] = [obj[k], v];\n }\n }\n\n return obj;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/querystring/decode.js\n// module id = 9\n// module chunks = 0 1","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nvar stringifyPrimitive = function(v) {\n switch (typeof v) {\n case 'string':\n return v;\n\n case 'boolean':\n return v ? 'true' : 'false';\n\n case 'number':\n return isFinite(v) ? v : '';\n\n default:\n return '';\n }\n};\n\nmodule.exports = function(obj, sep, eq, name) {\n sep = sep || '&';\n eq = eq || '=';\n if (obj === null) {\n obj = undefined;\n }\n\n if (typeof obj === 'object') {\n return Object.keys(obj).map(function(k) {\n var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;\n if (Array.isArray(obj[k])) {\n return obj[k].map(function(v) {\n return ks + encodeURIComponent(stringifyPrimitive(v));\n }).join(sep);\n } else {\n return ks + encodeURIComponent(stringifyPrimitive(obj[k]));\n }\n }).join(sep);\n\n }\n\n if (!name) return '';\n return encodeURIComponent(stringifyPrimitive(name)) + eq +\n encodeURIComponent(stringifyPrimitive(obj));\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/querystring/encode.js\n// module id = 10\n// module chunks = 0 1","var pubnub = require(\"pubnub\");\nvar es6Promise = require(\"es6-promise\");\nvar FetchPonyfill = require(\"fetch-ponyfill\");\n\nvar root = (typeof window !== \"undefined\" && window) ||\n (typeof global !== \"undefined\" && global) ||\n (function(){ return this; })();\n\n/**\n * @constructor\n * @param {PubNub} [options.PubNub]\n * @param {function(new:Promise)} [options.Promise]\n * @param {Storage} [options.localStorage]\n * @param {fetch} [options.fetch]\n * @param {function(new:Request)} [options.Request]\n * @param {function(new:Response)} [options.Response]\n * @param {function(new:Headers)} [options.Headers]\n * @property {PubNub} PubNub\n * @property {Storage} localStorage\n * @property {function(new:Promise)} Promise\n * @property {fetch} fetch\n * @property {function(new:Request)} Request\n * @property {function(new:Response)} Response\n * @property {function(new:Headers)} Headers\n */\nfunction Externals(options) {\n\n options = options || {};\n\n this.PubNub = options.PubNub || root.PubNub || pubnub;\n this.localStorage = options.localStorage || ((typeof root.localStorage !== 'undefined') ? root.localStorage : {});\n this.Promise = options.Promise || root.Promise || (es6Promise && es6Promise.Promise);\n\n var fetchPonyfill = FetchPonyfill ? FetchPonyfill({Promise: this.Promise}) : {};\n\n this.fetch = options.fetch || root.fetch || fetchPonyfill.fetch;\n this.Request = options.Request || root.Request || fetchPonyfill.Request;\n this.Response = options.Response || root.Response || fetchPonyfill.Response;\n this.Headers = options.Headers || root.Headers || fetchPonyfill.Headers;\n\n if (!this.fetch || !this.Response || !this.Request || !this.Headers) {\n throw new Error('Fetch API is missing');\n }\n\n if (!this.Promise) {\n throw new Error('Promise is missing');\n }\n\n if (!this.localStorage) {\n throw new Error('LocalStorage is missing');\n }\n\n if (!this.PubNub) {\n throw new Error('PubNub is missing');\n }\n\n}\n\nmodule.exports = Externals;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/core/Externals.js\n// module id = 11\n// module chunks = 0 1","module.exports = __WEBPACK_EXTERNAL_MODULE_12__;\n\n\n//////////////////\n// WEBPACK FOOTER\n// external {\"amd\":\"pubnub\"}\n// module id = 12\n// module chunks = 0 1","module.exports = __WEBPACK_EXTERNAL_MODULE_13__;\n\n\n//////////////////\n// WEBPACK FOOTER\n// external {\"amd\":\"es6-promise\"}\n// module id = 13\n// module chunks = 0 1","module.exports = __WEBPACK_EXTERNAL_MODULE_14__;\n\n\n//////////////////\n// WEBPACK FOOTER\n// external {\"amd\":\"fetch-ponyfill\"}\n// module id = 14\n// module chunks = 0 1","var EventEmitter = require(\"events\").EventEmitter;\nvar qs = require(\"querystring\");\nvar objectAssign = require('object-assign');\nvar Auth = require(\"./Auth\");\nvar Constants = require(\"../core/Constants\");\nvar ApiResponse = require(\"../http/ApiResponse\");\n\n/**\n * @constructor\n * @param {string} options.server\n * @param {string} options.appSecret\n * @param {string} options.appKey\n * @param {string} [options.appName]\n * @param {string} [options.appVersion]\n * @param {string} [options.redirectUri]\n * @param {int} [options.refreshDelayMs]\n * @param {int} [options.refreshHandicapMs]\n * @param {boolean} [options.clearCacheOnRefreshError]\n * @param {Externals} options.externals\n * @param {Cache} options.cache\n * @param {Client} options.client\n * @property {Externals} _externals\n * @property {Cache} _cache\n * @property {Client} _client\n * @property {Promise} _refreshPromise\n * @property {Auth} _auth\n */\nfunction Platform(options) {\n\n EventEmitter.call(this);\n\n this.events = {\n beforeLogin: 'beforeLogin',\n loginSuccess: 'loginSuccess',\n loginError: 'loginError',\n beforeRefresh: 'beforeRefresh',\n refreshSuccess: 'refreshSuccess',\n refreshError: 'refreshError',\n beforeLogout: 'beforeLogout',\n logoutSuccess: 'logoutSuccess',\n logoutError: 'logoutError'\n };\n\n options = options || {};\n\n /** @private */\n this._server = options.server;\n\n /** @private */\n this._appKey = options.appKey;\n\n /** @private */\n this._appSecret = options.appSecret;\n\n /** @private */\n this._redirectUri = options.redirectUri || '';\n\n /** @private */\n this._refreshDelayMs = options.refreshDelayMs || 100;\n\n /** @private */\n this._clearCacheOnRefreshError = typeof options.clearCacheOnRefreshError !== 'undefined' ?\n options.clearCacheOnRefreshError :\n true;\n\n /** @private */\n this._userAgent = (options.appName ?\n (options.appName + (options.appVersion ? '/' + options.appVersion : '')) + ' ' :\n '') + 'RCJSSDK/' + Constants.version;\n\n /** @private */\n this._externals = options.externals;\n\n /** @private */\n this._cache = options.cache;\n\n /** @private */\n this._client = options.client;\n\n /** @private */\n this._refreshPromise = null;\n\n /** @private */\n this._auth = new Auth({\n cache: this._cache,\n cacheId: Platform._cacheId,\n refreshHandicapMs: options.refreshHandicapMs\n });\n\n}\n\nPlatform._urlPrefix = '/restapi';\nPlatform._apiVersion = 'v1.0';\nPlatform._tokenEndpoint = '/restapi/oauth/token';\nPlatform._revokeEndpoint = '/restapi/oauth/revoke';\nPlatform._authorizeEndpoint = '/restapi/oauth/authorize';\nPlatform._cacheId = 'platform';\n\nPlatform.prototype = Object.create(EventEmitter.prototype);\n\nPlatform.prototype.delay = function(timeout) {\n return new this._externals.Promise(function(resolve, reject) {\n setTimeout(function() {\n resolve(null);\n }, timeout);\n });\n};\n\n/**\n * @return {Auth}\n */\nPlatform.prototype.auth = function() {\n return this._auth;\n};\n\n/**\n * @return {Client}\n */\nPlatform.prototype.client = function() {\n return this._client;\n};\n\n/**\n * @param {string} path\n * @param {object} [options]\n * @param {boolean} [options.addServer]\n * @param {string} [options.addMethod]\n * @param {boolean} [options.addToken]\n * @return {string}\n */\nPlatform.prototype.createUrl = function(path, options) {\n\n path = path || '';\n options = options || {};\n\n var builtUrl = '',\n hasHttp = path.indexOf('http://') != -1 || path.indexOf('https://') != -1;\n\n if (options.addServer && !hasHttp) builtUrl += this._server;\n\n if (path.indexOf(Platform._urlPrefix) == -1 && !hasHttp) builtUrl += Platform._urlPrefix + '/' + Platform._apiVersion;\n\n builtUrl += path;\n\n if (options.addMethod || options.addToken) builtUrl += (path.indexOf('?') > -1 ? '&' : '?');\n\n if (options.addMethod) builtUrl += '_method=' + options.addMethod;\n if (options.addToken) builtUrl += (options.addMethod ? '&' : '') + 'access_token=' + this._auth.accessToken();\n\n return builtUrl;\n\n};\n\n/**\n * @param {string} [options.redirectUri] Overrides default RedirectURI\n * @param {string} [options.state]\n * @param {string} [options.brandId]\n * @param {string} [options.display]\n * @param {string} [options.prompt]\n * @param {boolean} [options.implicit] Use Implicit Grant flow\n * @return {string}\n */\nPlatform.prototype.loginUrl = function(options) {\n\n options = options || {};\n\n return this.createUrl(Platform._authorizeEndpoint + '?' + qs.stringify({\n 'response_type': options.implicit ? 'token' : 'code',\n 'redirect_uri': options.redirectUri || this._redirectUri,\n 'client_id': this._appKey,\n 'state': options.state || '',\n 'brand_id': options.brandId || '',\n 'display': options.display || '',\n 'prompt': options.prompt || ''\n }), {addServer: true});\n\n};\n\n/**\n * @param {string} url\n * @return {Object}\n */\nPlatform.prototype.parseLoginRedirect = function(url) {\n\n function getParts(url, separator) {\n return url.split(separator).reverse()[0];\n }\n\n var response = (url.indexOf('#') === 0 && getParts(url, '#')) ||\n (url.indexOf('?') === 0 && getParts(url, '?')) ||\n null;\n\n if (!response) throw new Error('Unable to parse response');\n\n var queryString = qs.parse(response);\n\n if (!queryString) throw new Error('Unable to parse response');\n\n var error = queryString.error_description || queryString.error;\n\n if (error) {\n var e = new Error(error);\n e.error = queryString.error;\n throw e;\n }\n\n return queryString;\n\n};\n\n/**\n * Convenience method to handle 3-legged OAuth\n *\n * Attention! This is an experimental method and it's signature and behavior may change without notice.\n *\n * @experimental\n * @param {string} options.url\n * @param {number} [options.width]\n * @param {number} [options.height]\n * @param {object} [options.login] additional options for login()\n * @param {string} [options.origin]\n * @param {string} [options.property] name of window.postMessage's event data property\n * @param {string} [options.target] target for window.open()\n * @return {Promise}\n */\nPlatform.prototype.loginWindow = function(options) {\n\n return new this._externals.Promise(function(resolve, reject) {\n\n if (typeof window === 'undefined') throw new Error('This method can be used only in browser');\n\n if (!options.url) throw new Error('Missing mandatory URL parameter');\n\n options = options || {};\n options.url = options.url || 400;\n options.width = options.width || 400;\n options.height = options.height || 600;\n options.origin = options.origin || window.location.origin;\n options.property = options.property || Constants.authResponseProperty;\n options.target = options.target || '_blank';\n\n var dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left;\n var dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top;\n\n var width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;\n var height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;\n\n var left = ((width / 2) - (options.width / 2)) + dualScreenLeft;\n var top = ((height / 2) - (options.height / 2)) + dualScreenTop;\n var win = window.open(options.url, '_blank', (options.target == '_blank') ? 'scrollbars=yes, status=yes, width=' + options.width + ', height=' + options.height + ', left=' + left + ', top=' + top : '');\n\n if(!win) {\n throw new Error('Could not open login window. Please allow popups for this site');\n }\n\n if (win.focus) win.focus();\n\n var eventMethod = window.addEventListener ? 'addEventListener' : 'attachEvent';\n var eventRemoveMethod = eventMethod == 'addEventListener' ? 'removeEventListener' : 'detachEvent';\n var messageEvent = eventMethod == 'addEventListener' ? 'message' : 'onmessage';\n\n var eventListener = function(e) {\n\n try {\n\n if (e.origin != options.origin) return;\n if (!e.data || !e.data[options.property]) return; // keep waiting\n\n win.close();\n window[eventRemoveMethod](messageEvent, eventListener);\n\n\n var loginOptions = this.parseLoginRedirect(e.data[options.property]);\n\n if (!loginOptions.code && !loginOptions.access_token) throw new Error('No authorization code or token');\n\n resolve(loginOptions);\n\n /* jshint -W002 */\n } catch (e) {\n reject(e);\n }\n\n }.bind(this);\n\n window[eventMethod](messageEvent, eventListener, false);\n\n }.bind(this));\n\n};\n\n/**\n * @return {Promise}\n */\nPlatform.prototype.loggedIn = function() {\n\n return this.ensureLoggedIn().then(function() {\n return true;\n }).catch(function() {\n return false;\n });\n\n};\n\n/**\n * @param {string} options.username\n * @param {string} options.password\n * @param {string} [options.extension]\n * @param {string} [options.code]\n * @param {string} [options.redirectUri]\n * @param {string} [options.endpointId]\n * @param {string} [options.accessTokenTtl]\n * @param {string} [options.refreshTokenTtl]\n * @param {string} [options.access_token]\n * @returns {Promise}\n */\nPlatform.prototype.login = function(options) {\n\n return (new this._externals.Promise(function(resolve) {\n\n options = options || {};\n\n this.emit(this.events.beforeLogin);\n\n var body = {};\n\n if (options.access_token) {\n\n //TODO Potentially make a request to /oauth/tokeninfo\n return resolve(options);\n\n }\n\n if (!options.code) {\n\n body.grant_type = 'password';\n body.username = options.username;\n body.password = options.password;\n body.extension = options.extension || '';\n\n } else if (options.code) {\n\n body.grant_type = 'authorization_code';\n body.code = options.code;\n body.redirect_uri = options.redirectUri || this._redirectUri;\n //body.client_id = this.getCredentials().key; // not needed\n\n }\n\n if (options.endpointId) body.endpoint_id = options.endpointId;\n if (options.accessTokenTtl) body.accessTokenTtl = options.accessTokenTtl;\n if (options.refreshTokenTtl) body.refreshTokenTtl = options.refreshTokenTtl;\n\n resolve(this._tokenRequest(Platform._tokenEndpoint, body));\n\n }.bind(this))).then(function(res) {\n\n var apiResponse = res.json ? res : null;\n var json = apiResponse && apiResponse.json() || res;\n\n this._auth.setData(json);\n\n this.emit(this.events.loginSuccess, apiResponse);\n\n return apiResponse;\n\n }.bind(this)).catch(function(e) {\n\n if (this._clearCacheOnRefreshError) {\n this._cache.clean();\n }\n\n this.emit(this.events.loginError, e);\n\n throw e;\n\n }.bind(this));\n\n};\n\n/**\n * @returns {Promise}\n * @private\n */\nPlatform.prototype._refresh = function() {\n\n return this.delay(this._refreshDelayMs).then(function() {\n\n this.emit(this.events.beforeRefresh);\n\n // Perform sanity checks\n if (!this._auth.refreshToken()) throw new Error('Refresh token is missing');\n if (!this._auth.refreshTokenValid()) throw new Error('Refresh token has expired');\n\n return this._tokenRequest(Platform._tokenEndpoint, {\n \"grant_type\": \"refresh_token\",\n \"refresh_token\": this._auth.refreshToken(),\n \"access_token_ttl\": this._auth.data().expires_in + 1,\n \"refresh_token_ttl\": this._auth.data().refresh_token_expires_in + 1\n });\n\n }.bind(this)).then(function(/** @type {ApiResponse} */ res) {\n\n var json = res.json();\n\n if (!json.access_token) {\n throw this._client.makeError(new Error('Malformed OAuth response'), res);\n }\n\n this._auth.setData(json);\n\n this.emit(this.events.refreshSuccess, res);\n\n return res;\n\n }.bind(this)).catch(function(e) {\n\n e = this._client.makeError(e);\n\n if (this._clearCacheOnRefreshError) {\n this._cache.clean();\n }\n\n this.emit(this.events.refreshError, e);\n\n throw e;\n\n }.bind(this));\n\n};\n\n/**\n * @returns {Promise}\n */\nPlatform.prototype.refresh = function() {\n\n if (!this._refreshPromise) {\n\n this._refreshPromise = this._refresh()\n .then(function(res) {\n this._refreshPromise = null;\n return res;\n }.bind(this))\n .catch(function(e) {\n this._refreshPromise = null;\n throw e;\n }.bind(this));\n\n }\n\n return this._refreshPromise;\n\n};\n\n/**\n * @returns {Promise}\n */\nPlatform.prototype.logout = function() {\n\n return (new this._externals.Promise(function(resolve) {\n\n this.emit(this.events.beforeLogout);\n\n resolve(this._tokenRequest(Platform._revokeEndpoint, {\n token: this._auth.accessToken()\n }));\n\n }.bind(this))).then(function(res) {\n\n this._cache.clean();\n\n this.emit(this.events.logoutSuccess, res);\n\n return res;\n\n }.bind(this)).catch(function(e) {\n\n this.emit(this.events.logoutError, e);\n\n throw e;\n\n }.bind(this));\n\n};\n\n/**\n * @param {Request} request\n * @param {object} [options]\n * @param {boolean} [options.skipAuthCheck]\n * @return {Promise}\n */\nPlatform.prototype.inflateRequest = function(request, options) {\n\n options = options || {};\n\n if (options.skipAuthCheck) return this._externals.Promise.resolve(request);\n\n return this.ensureLoggedIn().then(function() {\n\n request.headers.set('X-User-Agent', this._userAgent);\n request.headers.set('Client-Id', this._appKey);\n request.headers.set('Authorization', this._authHeader());\n //request.url = this.createUrl(request.url, {addServer: true}); //FIXME Spec prevents this...\n\n return request;\n\n }.bind(this));\n\n};\n\n/**\n * @param {Request} request\n * @param {object} [options]\n * @param {boolean} [options.skipAuthCheck]\n * @param {boolean} [options.retry] Will be set by this method if SDK makes second request\n * @return {Promise}\n */\nPlatform.prototype.sendRequest = function(request, options) {\n\n return this.inflateRequest(request, options).then(function(request) {\n\n options = options || {};\n\n return this._client.sendRequest(request);\n\n }.bind(this)).catch(function(e) {\n\n // Guard is for errors that come from polling\n if (!e.apiResponse || !e.apiResponse.response() ||\n (e.apiResponse.response().status != ApiResponse._unauthorizedStatus) ||\n options.retry) throw e;\n\n this._auth.cancelAccessToken();\n\n options.retry = true;\n\n return this.sendRequest(request, options);\n\n }.bind(this));\n\n};\n\n/**\n * General purpose function to send anything to server\n * @param {string} options.url\n * @param {object} [options.body]\n * @param {string} [options.method]\n * @param {object} [options.query]\n * @param {object} [options.headers]\n * @param {boolean} [options.skipAuthCheck]\n * @return {Promise}\n */\nPlatform.prototype.send = function(options) {\n\n options = options || {};\n\n //FIXME https://github.com/bitinn/node-fetch/issues/43\n options.url = this.createUrl(options.url, {addServer: true});\n\n return this.sendRequest(this._client.createRequest(options), options);\n\n};\n\n/**\n * @param {string} url\n * @param {object} [query]\n * @param {object} [options]\n * @param {object} [options.headers]\n * @param {boolean} [options.skipAuthCheck]\n * @return {Promise}\n */\nPlatform.prototype.get = function(url, query, options) {\n return this.send(objectAssign({}, {method: 'GET', url: url, query: query}, options));\n};\n\n/**\n * @param {string} url\n * @param {object} body\n * @param {object} [query]\n * @param {object} [options]\n * @param {object} [options.headers]\n * @param {boolean} [options.skipAuthCheck]\n * @return {Promise}\n */\nPlatform.prototype.post = function(url, body, query, options) {\n return this.send(objectAssign({}, {method: 'POST', url: url, query: query, body: body}, options));\n};\n\n/**\n * @param {string} url\n * @param {object} [body]\n * @param {object} [query]\n * @param {object} [options]\n * @param {object} [options.headers]\n * @param {boolean} [options.skipAuthCheck]\n * @return {Promise}\n */\nPlatform.prototype.put = function(url, body, query, options) {\n return this.send(objectAssign({}, {method: 'PUT', url: url, query: query, body: body}, options));\n};\n\n/**\n * @param {string} url\n * @param {string} [query]\n * @param {object} [options]\n * @param {object} [options.headers]\n * @param {boolean} [options.skipAuthCheck]\n * @return {Promise}\n */\nPlatform.prototype['delete'] = function(url, query, options) {\n return this.send(objectAssign({}, {method: 'DELETE', url: url, query: query}, options));\n};\n\nPlatform.prototype.ensureLoggedIn = function() {\n if (this._isAccessTokenValid()) return this._externals.Promise.resolve();\n return this.refresh();\n};\n\n/**\n * @param path\n * @param body\n * @return {Promise.}\n * @private\n */\nPlatform.prototype._tokenRequest = function(path, body) {\n\n return this.send({\n url: path,\n skipAuthCheck: true,\n body: body,\n method: 'POST',\n headers: {\n 'Authorization': 'Basic ' + this._apiKey(),\n 'Content-Type': ApiResponse._urlencodedContentType\n }\n });\n\n};\n\n/**\n * @return {boolean}\n * @private\n */\nPlatform.prototype._isAccessTokenValid = function() {\n return this._auth.accessTokenValid();\n};\n\n/**\n * @return {string}\n * @private\n */\nPlatform.prototype._apiKey = function() {\n var apiKey = this._appKey + ':' + this._appSecret;\n return (typeof btoa == 'function') ? btoa(apiKey) : new Buffer(apiKey).toString('base64');\n};\n\n/**\n * @return {string}\n * @private\n */\nPlatform.prototype._authHeader = function() {\n var token = this._auth.accessToken();\n return this._auth.tokenType() + (token ? ' ' + token : '');\n};\n\nmodule.exports = Platform;\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/platform/Platform.js\n// module id = 15\n// module chunks = 0 1","/**\n * @param {Cache} options.cache\n * @param {string} options.cacheId\n * @param {int} [options.refreshHandicapMs]\n * @constructor\n * @property {Cache} _cache\n * @property {int} _refreshHandicapMs\n * @property {string} _cacheId\n */\nfunction Auth(options) {\n\n /** @private */\n this._cache = options.cache;\n\n /** @private */\n this._cacheId = options.cacheId;\n\n /** @private */\n this._refreshHandicapMs = options.refreshHandicapMs || 60 * 1000; // 1 minute\n\n}\n\nAuth.prototype.accessToken = function() {\n return this.data().access_token;\n};\n\nAuth.prototype.refreshToken = function() {\n return this.data().refresh_token;\n};\n\nAuth.prototype.tokenType = function() {\n return this.data().token_type;\n};\n\n/**\n * @return {{token_type: string, access_token: string, expires_in: number, refresh_token: string, refresh_token_expires_in: number}}\n */\nAuth.prototype.data = function() {\n\n return this._cache.getItem(this._cacheId) || {\n token_type: '',\n access_token: '',\n expires_in: 0,\n refresh_token: '',\n refresh_token_expires_in: 0\n };\n\n};\n\n/**\n * @param {object} newData\n * @return {Auth}\n */\nAuth.prototype.setData = function(newData) {\n\n newData = newData || {};\n\n var data = this.data();\n\n Object.keys(newData).forEach(function(key) {\n data[key] = newData[key];\n });\n\n data.expire_time = Date.now() + (data.expires_in * 1000);\n data.refresh_token_expire_time = Date.now() + (data.refresh_token_expires_in * 1000);\n\n this._cache.setItem(this._cacheId, data);\n\n return this;\n\n};\n\n/**\n * Check if there is a valid (not expired) access token\n * @return {boolean}\n */\nAuth.prototype.accessTokenValid = function() {\n\n var authData = this.data();\n return (authData.expire_time - this._refreshHandicapMs > Date.now());\n\n};\n\n/**\n * Check if there is a valid (not expired) access token\n * @return {boolean}\n */\nAuth.prototype.refreshTokenValid = function() {\n\n return (this.data().refresh_token_expire_time > Date.now());\n\n};\n\n/**\n * @return {Auth}\n */\nAuth.prototype.cancelAccessToken = function() {\n\n return this.setData({\n access_token: '',\n expires_in: 0\n });\n\n};\n\nmodule.exports = Auth;\n\n//export interface IAuthData {\n// remember?:boolean;\n// token_type?:string;\n// access_token?:string;\n// expires_in?:number; // actually it's string\n// expire_time?:number;\n// refresh_token?:string;\n// refresh_token_expires_in?:number; // actually it's string\n// refresh_token_expire_time?:number;\n// scope?:string;\n//}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/platform/Auth.js\n// module id = 16\n// module chunks = 0 1","var version = process.env.RCSDK_VERSION;\n\n// This will become false during the Webpack build, so no traces of package.json will be there\nif (!process.env.RCSDK_VERSION) {\n version = require('../../package.json').version;\n}\n\nmodule.exports = {\n version: version,\n authResponseProperty: 'RCAuthorizationResponse'\n};\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/core/Constants.js\n// module id = 17\n// module chunks = 0 1","var EventEmitter = require(\"events\").EventEmitter;\n\n/**\n * @param {Platform} options.platform\n * @param {Externals} options.externals\n * @param {int} [options.pollInterval]\n * @param {int} [options.renewHandicapMs]\n * @property {Externals} _externals\n * @property {Platform} _platform\n * @property {int} _pollInterval\n * @property {int} _renewHandicapMs\n * @property {PUBNUB} _pubnub\n * @property {string} _pubnubLastChannel\n * @property {int} _timeout\n * @property {ISubscription} _subscription\n * @constructor\n */\nfunction Subscription(options) {\n\n EventEmitter.call(this);\n\n options = options || {};\n\n this.events = {\n notification: 'notification',\n removeSuccess: 'removeSuccess',\n removeError: 'removeError',\n renewSuccess: 'renewSuccess',\n renewError: 'renewError',\n subscribeSuccess: 'subscribeSuccess',\n subscribeError: 'subscribeError'\n };\n\n /** @private */\n this._externals = options.externals;\n\n /** @private */\n this._platform = options.platform;\n\n /** @private */\n this._pollInterval = options.pollInterval || 10 * 1000;\n\n /** @private */\n this._renewHandicapMs = options.renewHandicapMs || 2 * 60 * 1000;\n\n /** @private */\n this._pubnub = null;\n\n /** @private */\n this._pubnubLastChannel = null;\n\n /** @private */\n this._timeout = null;\n\n /** @private */\n this._subscription = null;\n\n}\n\nSubscription.prototype = Object.create(EventEmitter.prototype);\n\nSubscription.prototype.subscribed = function() {\n\n var subscription = this.subscription();\n\n return !!(subscription.id &&\n subscription.deliveryMode &&\n subscription.deliveryMode.subscriberKey &&\n subscription.deliveryMode.address);\n\n};\n\n/**\n * @return {boolean}\n */\nSubscription.prototype.alive = function() {\n return this.subscribed() && Date.now() < this.expirationTime();\n};\n\n/**\n * @return {boolean}\n */\nSubscription.prototype.expired = function() {\n if (!this.subscribed()) return true;\n return !this.subscribed() || Date.now() > this.subscription().expirationTime;\n};\n\nSubscription.prototype.expirationTime = function() {\n return new Date(this.subscription().expirationTime || 0).getTime() - this._renewHandicapMs;\n};\n\n/**\n * @param {ISubscription} subscription\n * @return {Subscription}\n */\nSubscription.prototype.setSubscription = function(subscription) {\n\n subscription = subscription || {};\n\n this._clearTimeout();\n this._setSubscription(subscription);\n this._subscribeAtPubnub();\n this._setTimeout();\n\n return this;\n\n};\n\n/**\n * @return {ISubscription}\n */\nSubscription.prototype.subscription = function() {\n return this._subscription || {};\n};\n\n/**\n * Creates or updates subscription if there is an active one\n * @returns {Promise}\n */\nSubscription.prototype.register = function() {\n\n if (this.alive()) {\n return this.renew();\n } else {\n return this.subscribe();\n }\n\n};\n\n/**\n * @return {string[]}\n */\nSubscription.prototype.eventFilters = function() {\n return this.subscription().eventFilters || [];\n};\n\n/**\n * @param {string[]} events\n * @return {Subscription}\n */\nSubscription.prototype.addEventFilters = function(events) {\n this.setEventFilters(this.eventFilters().concat(events));\n return this;\n};\n\n/**\n * @param {string[]} events\n * @return {Subscription}\n */\nSubscription.prototype.setEventFilters = function(events) {\n var subscription = this.subscription();\n subscription.eventFilters = events;\n this._setSubscription(subscription);\n return this;\n};\n\n/**\n * @returns {Promise}\n */\nSubscription.prototype.subscribe = function() {\n\n return (new this._externals.Promise(function(resolve) {\n\n this._clearTimeout();\n\n if (!this.eventFilters().length) throw new Error('Events are undefined');\n\n resolve(this._platform.post('/subscription', {\n eventFilters: this._getFullEventFilters(),\n deliveryMode: {\n transportType: 'PubNub'\n }\n }));\n\n }.bind(this))).then(function(response) {\n\n var json = response.json();\n\n this.setSubscription(json)\n .emit(this.events.subscribeSuccess, response);\n\n return response;\n\n }.bind(this)).catch(function(e) {\n\n e = this._platform.client().makeError(e);\n\n this.reset()\n .emit(this.events.subscribeError, e);\n\n throw e;\n\n }.bind(this));\n\n};\n\n/**\n * @returns {Promise}\n */\nSubscription.prototype.renew = function() {\n\n return (new this._externals.Promise(function(resolve) {\n\n this._clearTimeout();\n\n if (!this.subscribed()) throw new Error('No subscription');\n\n if (!this.eventFilters().length) throw new Error('Events are undefined');\n\n resolve(this._platform.put('/subscription/' + this.subscription().id, {\n eventFilters: this._getFullEventFilters()\n }));\n\n }.bind(this))).then(function(response) {\n\n var json = response.json();\n\n this.setSubscription(json)\n .emit(this.events.renewSuccess, response);\n\n return response;\n\n }.bind(this)).catch(function(e) {\n\n e = this._platform.client().makeError(e);\n\n this.reset()\n .emit(this.events.renewError, e);\n\n throw e;\n\n }.bind(this));\n\n};\n\n/**\n * @returns {Promise}\n */\nSubscription.prototype.remove = function() {\n\n return (new this._externals.Promise(function(resolve) {\n\n if (!this.subscribed()) throw new Error('No subscription');\n\n resolve(this._platform.delete('/subscription/' + this.subscription().id));\n\n }.bind(this))).then(function(response) {\n\n this.reset()\n .emit(this.events.removeSuccess, response);\n\n return response;\n\n }.bind(this)).catch(function(e) {\n\n e = this._platform.client().makeError(e);\n\n this.emit(this.events.removeError, e);\n\n throw e;\n\n }.bind(this));\n\n};\n\n/**\n * @returns {Promise}\n */\nSubscription.prototype.resubscribe = function() {\n var filters = this.eventFilters();\n return this.reset().setEventFilters(filters).subscribe();\n};\n\n/**\n * Remove subscription and disconnect from PubNub\n * This method resets subscription at client side but backend is not notified\n * @return {Subscription}\n */\nSubscription.prototype.reset = function() {\n this._clearTimeout();\n if (this.subscribed() && this._pubnub) this._pubnub.unsubscribe({channel: this.subscription().deliveryMode.address});\n this._setSubscription(null);\n return this;\n};\n\n/**\n * @param subscription\n * @private\n */\nSubscription.prototype._setSubscription = function(subscription) {\n this._subscription = subscription;\n};\n\n/**\n * @return {string[]}\n * @private\n */\nSubscription.prototype._getFullEventFilters = function() {\n\n return this.eventFilters().map(function(event) {\n return this._platform.createUrl(event);\n }.bind(this));\n\n};\n\n/**\n * @return {Subscription}\n * @private\n */\nSubscription.prototype._setTimeout = function() {\n\n this._clearTimeout();\n\n if (!this.alive()) throw new Error('Subscription is not alive');\n\n this._timeout = setInterval(function() {\n\n if (this.alive()) return;\n\n if (this.expired()) {\n this.subscribe();\n } else {\n this.renew();\n }\n\n }.bind(this), this._pollInterval);\n\n return this;\n\n};\n\n/**\n * @return {Subscription}\n * @private\n */\nSubscription.prototype._clearTimeout = function() {\n clearInterval(this._timeout);\n return this;\n};\n\nSubscription.prototype._decrypt = function(message) {\n\n if (!this.subscribed()) throw new Error('No subscription');\n\n if (this.subscription().deliveryMode.encryptionKey) {\n\n message = this._pubnub.decrypt(message, this.subscription().deliveryMode.encryptionKey, {\n encryptKey: false,\n keyEncoding: 'base64',\n keyLength: 128,\n mode: 'ecb'\n });\n\n }\n\n return message;\n\n};\n\n/**\n * @param message\n * @return {Subscription}\n * @private\n */\nSubscription.prototype._notify = function(message) {\n this.emit(this.events.notification, this._decrypt(message));\n return this;\n};\n\n/**\n * @return {Subscription}\n * @private\n */\nSubscription.prototype._subscribeAtPubnub = function() {\n\n if (!this.alive()) throw new Error('Subscription is not alive');\n\n var deliveryMode = this.subscription().deliveryMode;\n\n if (this._pubnub) {\n\n if (this._pubnubLastChannel == deliveryMode.address) { // Nothing to update, keep listening to same channel\n return this;\n } else if (this._pubnubLastChannel) { // Need to subscribe to new channel\n this._pubnub.unsubscribe({channel: this._pubnubLastChannel});\n }\n\n // Re-init for new data\n this._pubnub = this._pubnub.init({\n ssl: true,\n subscribe_key: deliveryMode.subscriberKey\n });\n\n } else {\n\n // Init from scratch\n this._pubnub = new this._externals.PubNub({\n ssl: true,\n subscribe_key: deliveryMode.subscriberKey\n });\n\n }\n\n this._pubnubLastChannel = deliveryMode.address;\n\n this._pubnub.subscribe({\n channel: deliveryMode.address,\n message: this._notify.bind(this),\n connect: function() {}\n });\n\n return this;\n\n};\n\nmodule.exports = Subscription;\n\n/**\n * The complete Triforce, or one or more components of the Triforce.\n * @typedef {Object} ISubscription\n * @property {string} [id]\n * @property {string} [uri]\n * @property {string[]} [eventFilters]\n * @property {string} [expirationTime] Format: 2014-03-12T19:54:35.613Z\n * @property {int} [expiresIn]\n * @property {string} [deliveryMode.transportType]\n * @property {boolean} [deliveryMode.encryption]\n * @property {string} [deliveryMode.address]\n * @property {string} [deliveryMode.subscriberKey]\n * @property {string} [deliveryMode.encryptionKey]\n * @property {string} [deliveryMode.secretKey]\n * @property {string} [creationTime]\n * @property {string} [status] Active\n */\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/subscription/Subscription.js\n// module id = 18\n// module chunks = 0 1","var Subscription = require(\"./Subscription\");\n\n/**\n * @param {Platform} options.platform\n * @param {Externals} options.externals\n * @param {Cache} options.cache\n * @param {string} options.cacheKey\n * @param {int} [options.pollInterval]\n * @param {int} [options.renewHandicapMs]\n * @return {CachedSubscription}\n * @constructor\n * @property {Cache} _cache\n * @extends Subscription\n */\nfunction CachedSubscription(options) {\n\n options = options || {};\n\n if (!options.cacheKey) throw new Error('Cached Subscription requires cacheKey parameter to be defined');\n\n /** @private */\n this._cacheKey = options.cacheKey;\n\n Subscription.call(this, options);\n\n /** @private */\n this._cache = options.cache;\n\n // This is not used in this class\n this._subscription = undefined;\n\n}\n\nCachedSubscription.prototype = Object.create(Subscription.prototype);\n\nCachedSubscription.prototype.subscription = function() {\n return this._cache.getItem(this._cacheKey) || {};\n};\n\nCachedSubscription.prototype._setSubscription = function(subscription) {\n return this._cache.setItem(this._cacheKey, subscription);\n};\n\n/**\n * This function checks whether there are any pre-defined eventFilters in cache and if not -- uses provided as defaults\n * @param {string[]} events\n * @return {CachedSubscription}\n */\nCachedSubscription.prototype.restore = function(events) {\n\n if (!this.eventFilters().length) {\n this.setEventFilters(events);\n }\n\n return this;\n\n};\n\nmodule.exports = CachedSubscription;\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/subscription/CachedSubscription.js\n// module id = 19\n// module chunks = 0 1"],"sourceRoot":""} \ No newline at end of file diff --git a/karma.conf.js b/karma.conf.js index 4f122611..aa0f225d 100644 --- a/karma.conf.js +++ b/karma.conf.js @@ -19,10 +19,10 @@ module.exports = function(config) { files: [ require.resolve('karma-chai-plugins/function-bind-polyfill'), - require.resolve('whatwg-fetch/fetch'), + require.resolve('es6-promise/dist/es6-promise.auto.js'), + require.resolve('whatwg-fetch/fetch'), //FIXME We need to add it manually for fetch-mock require.resolve('fetch-mock/es5/client-browserified'), - require.resolve('es6-promise/dist/es6-promise.js'), - require.resolve('pubnub/modern/dist/pubnub.js') + require.resolve('pubnub/dist/web/pubnub.js') ].concat([ './build/ringcentral.js' ]).concat(specs), diff --git a/package.json b/package.json index 029d5071..7c6ea9f8 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ringcentral", - "version": "3.0.0", + "version": "3.1.0", "scripts": { "clean": "rm -rf build/*", "build": "npm run clean && ./node_modules/.bin/webpack --display-modules --progress --colors --bail", @@ -20,38 +20,38 @@ "hint": "jshint src/**/*.js" }, "dependencies": { - "es6-promise": "^3.0.2", - "fetch-ponyfill": "^3.0.0", + "es6-promise": "^4.0.5", + "fetch-ponyfill": "^3.0.2", "is-plain-object": "^2.0.1", "object-assign": "^4.1.0", - "pubnub": "^3.16.3" + "pubnub": "^4.4.2" }, "devDependencies": { "chai": "^3.5.0", - "fetch-mock": "^5.5.0", + "fetch-mock": "^5.9.3", "http-server": "^0.9.0", - "istanbul": "^0.4.1", + "istanbul": "^0.4.5", "jsdoc-to-markdown": "^2.0.1", "jshint": "^2.9.4", "json-loader": "^0.5.4", - "karma": "^0.13.22", - "karma-chai-plugins": "^0.7.0", - "karma-chrome-launcher": "^0.2.3", - "karma-coverage": "^0.5.3", - "karma-firefox-launcher": "^0.1.7", + "karma": "^1.4.1", + "karma-chai-plugins": "^0.8.0", + "karma-chrome-launcher": "^2.0.0", + "karma-coverage": "^1.1.1", + "karma-firefox-launcher": "^1.0.0", "karma-html-reporter": "^0.2.6", - "karma-mocha": "^0.2.0", - "karma-mocha-reporter": "^2.0.0", - "karma-phantomjs-launcher": "^1.0.0", + "karma-mocha": "^1.3.0", + "karma-mocha-reporter": "^2.2.2", + "karma-phantomjs-launcher": "^1.0.2", "karma-sourcemap-loader": "^0.3.5", - "karma-webpack": "^1.7.0", - "mocha": "^2.4.5", - "phantomjs-prebuilt": "^2.1.7", - "sinon": "^1.17.3", + "karma-webpack": "^2.0.2", + "mocha": "^3.2.0", + "phantomjs-prebuilt": "^2.1.14", + "sinon": "^1.17.7", "sinon-chai": "^2.8.0", - "soap": "^0.13.0", - "webpack": "^1.12.14", - "whatwg-fetch": "^1.0.0" + "soap": "^0.18.0", + "webpack": "^1.14.0", + "whatwg-fetch": "^2.0.2" }, "jsdoc2md": { "separators": true, diff --git a/src/SDK.js b/src/SDK.js index 11759ff2..8f55a1d6 100644 --- a/src/SDK.js +++ b/src/SDK.js @@ -19,7 +19,7 @@ var Constants = require("./core/Constants"); * @param {string} [options.appName] * @param {string} [options.appVersion] * @param {string} [options.redirectUri] - * @param {PUBNUB} [options.PUBNUB] + * @param {PubNub} [options.PubNub] * @param {function(new:Promise)} [options.Promise] * @param {Storage} [options.localStorage] * @param {fetch} [options.fetch] diff --git a/src/core/Externals.js b/src/core/Externals.js index 1c7ffe2f..c16a903b 100644 --- a/src/core/Externals.js +++ b/src/core/Externals.js @@ -8,14 +8,14 @@ var root = (typeof window !== "undefined" && window) || /** * @constructor - * @param {PUBNUB} [options.PUBNUB] + * @param {PubNub} [options.PubNub] * @param {function(new:Promise)} [options.Promise] * @param {Storage} [options.localStorage] * @param {fetch} [options.fetch] * @param {function(new:Request)} [options.Request] * @param {function(new:Response)} [options.Response] * @param {function(new:Headers)} [options.Headers] - * @property {PUBNUB} PUBNUB + * @property {PubNub} PubNub * @property {Storage} localStorage * @property {function(new:Promise)} Promise * @property {fetch} fetch @@ -27,7 +27,7 @@ function Externals(options) { options = options || {}; - this.PUBNUB = options.PUBNUB || root.PUBNUB || pubnub; + this.PubNub = options.PubNub || root.PubNub || pubnub; this.localStorage = options.localStorage || ((typeof root.localStorage !== 'undefined') ? root.localStorage : {}); this.Promise = options.Promise || root.Promise || (es6Promise && es6Promise.Promise); @@ -50,8 +50,8 @@ function Externals(options) { throw new Error('LocalStorage is missing'); } - if (!this.PUBNUB) { - throw new Error('PUBNUB is missing'); + if (!this.PubNub) { + throw new Error('PubNub is missing'); } } diff --git a/src/subscription/Subscription.js b/src/subscription/Subscription.js index 29bcb785..5df95c8b 100644 --- a/src/subscription/Subscription.js +++ b/src/subscription/Subscription.js @@ -272,7 +272,7 @@ Subscription.prototype.resubscribe = function() { }; /** - * Remove subscription and disconnect from PUBNUB + * Remove subscription and disconnect from PubNub * This method resets subscription at client side but backend is not notified * @return {Subscription} */ @@ -344,7 +344,7 @@ Subscription.prototype._decrypt = function(message) { if (this.subscription().deliveryMode.encryptionKey) { - message = this._externals.PUBNUB.crypto_obj.decrypt(message, this.subscription().deliveryMode.encryptionKey, { + message = this._pubnub.decrypt(message, this.subscription().deliveryMode.encryptionKey, { encryptKey: false, keyEncoding: 'base64', keyLength: 128, @@ -394,13 +394,11 @@ Subscription.prototype._subscribeAtPubnub = function() { } else { // Init from scratch - this._pubnub = this._externals.PUBNUB.init({ + this._pubnub = new this._externals.PubNub({ ssl: true, subscribe_key: deliveryMode.subscriberKey }); - this._pubnub.ready(); //TODO This may be not needed anymore - } this._pubnubLastChannel = deliveryMode.address; diff --git a/src/test/test.js b/src/test/test.js index b583f651..d3d2d9a5 100644 --- a/src/test/test.js +++ b/src/test/test.js @@ -12,6 +12,8 @@ if (typeof exports === 'object' && typeof exports.nodeName !== 'string') { + require("es6-promise").polyfill(); //FIXME Needed for Fetch Mock + var chai = require("chai"); var sinon = require("sinon"); var SDK = require("../SDK"); @@ -34,11 +36,6 @@ var expect = chai.expect; var spy = sinon.spy; - var fetchMockOrig = fetchMock.fetchMock; - - fetchMock.fetchMock = function(req) { - return fetchMockOrig(req.url, req); // For some reasons that's needed for TravisCI - }; function apiCall(method, path, json, status, statusText, headers) { @@ -49,14 +46,16 @@ if (isJson && !headers) headers = {'Content-Type': 'application/json'}; - fetchMock.once('http://whatever' + path, { + + fetchMock.mock('http://whatever' + path, { body: isJson ? JSON.stringify(json) : json, status: status, statusText: statusText, headers: headers, sendAsJson: false }, { - method: method + method: method, + times: 1 }); } @@ -186,10 +185,10 @@ server: 'http://whatever', appKey: 'whatever', appSecret: 'whatever', - Headers: fetchMock.Headers, - Request: fetchMock.Request, - Response: fetchMock.Response, - fetch: fetchMock.fetchMock, + Request: fetchMock.constructor.Request, + Response: fetchMock.constructor.Response, + Headers: fetchMock.constructor.Headers, + fetch: fetchMock.fetchMock.bind(fetchMock), refreshDelayMs: 1 }; @@ -237,6 +236,7 @@ clean(); }).catch(function(e) { clean(); + console.error(e.stack); throw e; }); diff --git a/src/typings-custom/pubnub/pubnub.d.ts b/src/typings-custom/pubnub/pubnub.d.ts index e482c13b..8dc0777c 100644 --- a/src/typings-custom/pubnub/pubnub.d.ts +++ b/src/typings-custom/pubnub/pubnub.d.ts @@ -1,45 +1,45 @@ -interface PUBNUB { +interface PubNub { - init(options:PUBNUBInitOptions):PUBNUBInstance; - crypto_obj:PUBNUBCryptoObj; + init(options:PubNubInitOptions):PubNubInstance; + crypto_obj:PubNubCryptoObj; } -interface PUBNUBInstance { +interface PubNubInstance { - crypto_obj:PUBNUBCryptoObj; + crypto_obj:PubNubCryptoObj; ready():void; - subscribe(options:PUBNUBSubscribeOptions); + subscribe(options:PubNubSubscribeOptions); - unsubscribe(options:PUBNUBUnsubscribeOptions); + unsubscribe(options:PubNubUnsubscribeOptions); receiveMessage(message:string, channel:string); //TODO Remove } -interface PUBNUBSubscribeOptions { +interface PubNubSubscribeOptions { channel:string; message?:(message, env, channel) => any; connect?:(...args)=>void } -interface PUBNUBUnsubscribeOptions { +interface PubNubUnsubscribeOptions { channel:string; } -interface PUBNUBInitOptions { +interface PubNubInitOptions { ssl?:boolean; subscribe_key?:string } -interface PUBNUBCryptoObj { - encrypt:(message:string, key:string, options:PUBNUBCryptoOptions)=>string; - decrypt:(message:string, key:string, options:PUBNUBCryptoOptions)=>any; +interface PubNubCryptoObj { + encrypt:(message:string, key:string, options:PubNubCryptoOptions)=>string; + decrypt:(message:string, key:string, options:PubNubCryptoOptions)=>any; } -interface PUBNUBCryptoOptions { +interface PubNubCryptoOptions { encryptKey?:boolean; keyEncoding?:string; keyLength?:number|string; @@ -47,7 +47,7 @@ interface PUBNUBCryptoOptions { } declare module 'pubnub' { - var PUBNUB:PUBNUB; + var PubNub:PubNub; } -declare var PUBNUB:PUBNUB; \ No newline at end of file +declare var PubNub:PubNub; \ No newline at end of file diff --git a/src/typings/chai/chai.d.ts b/src/typings/chai/chai.d.ts deleted file mode 100644 index 8eb09959..00000000 --- a/src/typings/chai/chai.d.ts +++ /dev/null @@ -1,414 +0,0 @@ -// Type definitions for chai 3.4.0 -// Project: http://chaijs.com/ -// Definitions by: Jed Mao , -// Bart van der Schoor , -// Andrew Brown , -// Olivier Chevet , -// Matt Wistrand -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -// - -declare namespace Chai { - - interface ChaiStatic { - expect: ExpectStatic; - should(): Should; - /** - * Provides a way to extend the internals of Chai - */ - use(fn: (chai: any, utils: any) => void): ChaiStatic; - assert: AssertStatic; - config: Config; - AssertionError: typeof AssertionError; - } - - export interface ExpectStatic extends AssertionStatic { - fail(actual?: any, expected?: any, message?: string, operator?: string): void; - } - - export interface AssertStatic extends Assert { - } - - export interface AssertionStatic { - (target: any, message?: string): Assertion; - } - - interface ShouldAssertion { - equal(value1: any, value2: any, message?: string): void; - Throw: ShouldThrow; - throw: ShouldThrow; - exist(value: any, message?: string): void; - } - - interface Should extends ShouldAssertion { - not: ShouldAssertion; - fail(actual: any, expected: any, message?: string, operator?: string): void; - } - - interface ShouldThrow { - (actual: Function): void; - (actual: Function, expected: string|RegExp, message?: string): void; - (actual: Function, constructor: Error|Function, expected?: string|RegExp, message?: string): void; - } - - interface Assertion extends LanguageChains, NumericComparison, TypeComparison { - not: Assertion; - deep: Deep; - any: KeyFilter; - all: KeyFilter; - a: TypeComparison; - an: TypeComparison; - include: Include; - includes: Include; - contain: Include; - contains: Include; - ok: Assertion; - true: Assertion; - false: Assertion; - null: Assertion; - undefined: Assertion; - NaN: Assertion; - exist: Assertion; - empty: Assertion; - arguments: Assertion; - Arguments: Assertion; - equal: Equal; - equals: Equal; - eq: Equal; - eql: Equal; - eqls: Equal; - property: Property; - ownProperty: OwnProperty; - haveOwnProperty: OwnProperty; - ownPropertyDescriptor: OwnPropertyDescriptor; - haveOwnPropertyDescriptor: OwnPropertyDescriptor; - length: Length; - lengthOf: Length; - match: Match; - matches: Match; - string(string: string, message?: string): Assertion; - keys: Keys; - key(string: string): Assertion; - throw: Throw; - throws: Throw; - Throw: Throw; - respondTo: RespondTo; - respondsTo: RespondTo; - itself: Assertion; - satisfy: Satisfy; - satisfies: Satisfy; - closeTo: CloseTo; - approximately: CloseTo; - members: Members; - increase: PropertyChange; - increases: PropertyChange; - decrease: PropertyChange; - decreases: PropertyChange; - change: PropertyChange; - changes: PropertyChange; - extensible: Assertion; - sealed: Assertion; - frozen: Assertion; - oneOf(list: any[], message?: string): Assertion; - } - - interface LanguageChains { - to: Assertion; - be: Assertion; - been: Assertion; - is: Assertion; - that: Assertion; - which: Assertion; - and: Assertion; - has: Assertion; - have: Assertion; - with: Assertion; - at: Assertion; - of: Assertion; - same: Assertion; - } - - interface NumericComparison { - above: NumberComparer; - gt: NumberComparer; - greaterThan: NumberComparer; - least: NumberComparer; - gte: NumberComparer; - below: NumberComparer; - lt: NumberComparer; - lessThan: NumberComparer; - most: NumberComparer; - lte: NumberComparer; - within(start: number, finish: number, message?: string): Assertion; - } - - interface NumberComparer { - (value: number, message?: string): Assertion; - } - - interface TypeComparison { - (type: string, message?: string): Assertion; - instanceof: InstanceOf; - instanceOf: InstanceOf; - } - - interface InstanceOf { - (constructor: Object, message?: string): Assertion; - } - - interface CloseTo { - (expected: number, delta: number, message?: string): Assertion; - } - - interface Deep { - equal: Equal; - include: Include; - property: Property; - members: Members; - } - - interface KeyFilter { - keys: Keys; - } - - interface Equal { - (value: any, message?: string): Assertion; - } - - interface Property { - (name: string, value?: any, message?: string): Assertion; - } - - interface OwnProperty { - (name: string, message?: string): Assertion; - } - - interface OwnPropertyDescriptor { - (name: string, descriptor: PropertyDescriptor, message?: string): Assertion; - (name: string, message?: string): Assertion; - } - - interface Length extends LanguageChains, NumericComparison { - (length: number, message?: string): Assertion; - } - - interface Include { - (value: Object, message?: string): Assertion; - (value: string, message?: string): Assertion; - (value: number, message?: string): Assertion; - keys: Keys; - members: Members; - any: KeyFilter; - all: KeyFilter; - } - - interface Match { - (regexp: RegExp|string, message?: string): Assertion; - } - - interface Keys { - (...keys: string[]): Assertion; - (keys: any[]): Assertion; - (keys: Object): Assertion; - } - - interface Throw { - (): Assertion; - (expected: string, message?: string): Assertion; - (expected: RegExp, message?: string): Assertion; - (constructor: Error, expected?: string, message?: string): Assertion; - (constructor: Error, expected?: RegExp, message?: string): Assertion; - (constructor: Function, expected?: string, message?: string): Assertion; - (constructor: Function, expected?: RegExp, message?: string): Assertion; - } - - interface RespondTo { - (method: string, message?: string): Assertion; - } - - interface Satisfy { - (matcher: Function, message?: string): Assertion; - } - - interface Members { - (set: any[], message?: string): Assertion; - } - - interface PropertyChange { - (object: Object, prop: string, msg?: string): Assertion; - } - - export interface Assert { - /** - * @param expression Expression to test for truthiness. - * @param message Message to display on error. - */ - (expression: any, message?: string): void; - - fail(actual?: any, expected?: any, msg?: string, operator?: string): void; - - ok(val: any, msg?: string): void; - isOk(val: any, msg?: string): void; - notOk(val: any, msg?: string): void; - isNotOk(val: any, msg?: string): void; - - equal(act: any, exp: any, msg?: string): void; - notEqual(act: any, exp: any, msg?: string): void; - - strictEqual(act: any, exp: any, msg?: string): void; - notStrictEqual(act: any, exp: any, msg?: string): void; - - deepEqual(act: any, exp: any, msg?: string): void; - notDeepEqual(act: any, exp: any, msg?: string): void; - - isTrue(val: any, msg?: string): void; - isFalse(val: any, msg?: string): void; - - isNotTrue(val: any, msg?: string): void; - isNotFalse(val: any, msg?: string): void; - - isNull(val: any, msg?: string): void; - isNotNull(val: any, msg?: string): void; - - isUndefined(val: any, msg?: string): void; - isDefined(val: any, msg?: string): void; - - isNaN(val: any, msg?: string): void; - isNotNaN(val: any, msg?: string): void; - - isAbove(val: number, abv: number, msg?: string): void; - isBelow(val: number, blw: number, msg?: string): void; - - isAtLeast(val: number, atlst: number, msg?: string): void; - isAtMost(val: number, atmst: number, msg?: string): void; - - isFunction(val: any, msg?: string): void; - isNotFunction(val: any, msg?: string): void; - - isObject(val: any, msg?: string): void; - isNotObject(val: any, msg?: string): void; - - isArray(val: any, msg?: string): void; - isNotArray(val: any, msg?: string): void; - - isString(val: any, msg?: string): void; - isNotString(val: any, msg?: string): void; - - isNumber(val: any, msg?: string): void; - isNotNumber(val: any, msg?: string): void; - - isBoolean(val: any, msg?: string): void; - isNotBoolean(val: any, msg?: string): void; - - typeOf(val: any, type: string, msg?: string): void; - notTypeOf(val: any, type: string, msg?: string): void; - - instanceOf(val: any, type: Function, msg?: string): void; - notInstanceOf(val: any, type: Function, msg?: string): void; - - include(exp: string, inc: any, msg?: string): void; - include(exp: any[], inc: any, msg?: string): void; - - notInclude(exp: string, inc: any, msg?: string): void; - notInclude(exp: any[], inc: any, msg?: string): void; - - match(exp: any, re: RegExp, msg?: string): void; - notMatch(exp: any, re: RegExp, msg?: string): void; - - property(obj: Object, prop: string, msg?: string): void; - notProperty(obj: Object, prop: string, msg?: string): void; - deepProperty(obj: Object, prop: string, msg?: string): void; - notDeepProperty(obj: Object, prop: string, msg?: string): void; - - propertyVal(obj: Object, prop: string, val: any, msg?: string): void; - propertyNotVal(obj: Object, prop: string, val: any, msg?: string): void; - - deepPropertyVal(obj: Object, prop: string, val: any, msg?: string): void; - deepPropertyNotVal(obj: Object, prop: string, val: any, msg?: string): void; - - lengthOf(exp: any, len: number, msg?: string): void; - //alias frenzy - throw(fn: Function, msg?: string): void; - throw(fn: Function, regExp: RegExp): void; - throw(fn: Function, errType: Function, msg?: string): void; - throw(fn: Function, errType: Function, regExp: RegExp): void; - - throws(fn: Function, msg?: string): void; - throws(fn: Function, regExp: RegExp): void; - throws(fn: Function, errType: Function, msg?: string): void; - throws(fn: Function, errType: Function, regExp: RegExp): void; - - Throw(fn: Function, msg?: string): void; - Throw(fn: Function, regExp: RegExp): void; - Throw(fn: Function, errType: Function, msg?: string): void; - Throw(fn: Function, errType: Function, regExp: RegExp): void; - - doesNotThrow(fn: Function, msg?: string): void; - doesNotThrow(fn: Function, regExp: RegExp): void; - doesNotThrow(fn: Function, errType: Function, msg?: string): void; - doesNotThrow(fn: Function, errType: Function, regExp: RegExp): void; - - operator(val: any, operator: string, val2: any, msg?: string): void; - closeTo(act: number, exp: number, delta: number, msg?: string): void; - approximately(act: number, exp: number, delta: number, msg?: string): void; - - sameMembers(set1: any[], set2: any[], msg?: string): void; - sameDeepMembers(set1: any[], set2: any[], msg?: string): void; - includeMembers(superset: any[], subset: any[], msg?: string): void; - - ifError(val: any, msg?: string): void; - - isExtensible(obj: {}, msg?: string): void; - extensible(obj: {}, msg?: string): void; - isNotExtensible(obj: {}, msg?: string): void; - notExtensible(obj: {}, msg?: string): void; - - isSealed(obj: {}, msg?: string): void; - sealed(obj: {}, msg?: string): void; - isNotSealed(obj: {}, msg?: string): void; - notSealed(obj: {}, msg?: string): void; - - isFrozen(obj: Object, msg?: string): void; - frozen(obj: Object, msg?: string): void; - isNotFrozen(obj: Object, msg?: string): void; - notFrozen(obj: Object, msg?: string): void; - - oneOf(inList: any, list: any[], msg?: string): void; - } - - export interface Config { - /** - * Default: false - */ - includeStack: boolean; - - /** - * Default: true - */ - showDiff: boolean; - - /** - * Default: 40 - */ - truncateThreshold: number; - } - - export class AssertionError { - constructor(message: string, _props?: any, ssf?: Function); - name: string; - message: string; - showDiff: boolean; - stack: string; - } -} - -declare var chai: Chai.ChaiStatic; - -declare module "chai" { - export = chai; -} - -interface Object { - should: Chai.Assertion; -} diff --git a/src/typings/es6-promise/es6-promise.d.ts b/src/typings/es6-promise/es6-promise.d.ts deleted file mode 100644 index 4af46edf..00000000 --- a/src/typings/es6-promise/es6-promise.d.ts +++ /dev/null @@ -1,84 +0,0 @@ -// Type definitions for es6-promise -// Project: https://github.com/jakearchibald/ES6-Promise -// Definitions by: François de Campredon , vvakame -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -interface Thenable { - then(onFulfilled?: (value: T) => U | Thenable, onRejected?: (error: any) => U | Thenable): Thenable; - then(onFulfilled?: (value: T) => U | Thenable, onRejected?: (error: any) => void): Thenable; -} - -declare class Promise implements Thenable { - /** - * If you call resolve in the body of the callback passed to the constructor, - * your promise is fulfilled with result object passed to resolve. - * If you call reject your promise is rejected with the object passed to reject. - * For consistency and debugging (eg stack traces), obj should be an instanceof Error. - * Any errors thrown in the constructor callback will be implicitly passed to reject(). - */ - constructor(callback: (resolve : (value?: T | Thenable) => void, reject: (error?: any) => void) => void); - - /** - * onFulfilled is called when/if "promise" resolves. onRejected is called when/if "promise" rejects. - * Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called. - * Both callbacks have a single parameter , the fulfillment value or rejection reason. - * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve. - * If an error is thrown in the callback, the returned promise rejects with that error. - * - * @param onFulfilled called when/if "promise" resolves - * @param onRejected called when/if "promise" rejects - */ - then(onFulfilled?: (value: T) => U | Thenable, onRejected?: (error: any) => U | Thenable): Promise; - then(onFulfilled?: (value: T) => U | Thenable, onRejected?: (error: any) => void): Promise; - - /** - * Sugar for promise.then(undefined, onRejected) - * - * @param onRejected called when/if "promise" rejects - */ - catch(onRejected?: (error: any) => U | Thenable): Promise; -} - -declare namespace Promise { - /** - * Make a new promise from the thenable. - * A thenable is promise-like in as far as it has a "then" method. - */ - function resolve(value?: T | Thenable): Promise; - - /** - * Make a promise that rejects to obj. For consistency and debugging (eg stack traces), obj should be an instanceof Error - */ - function reject(error: any): Promise; - function reject(error: T): Promise; - - /** - * Make a promise that fulfills when every item in the array fulfills, and rejects if (and when) any item rejects. - * the array passed to all can be a mixture of promise-like objects and other objects. - * The fulfillment value is an array (in order) of fulfillment values. The rejection value is the first rejection value. - */ - function all(values: [T1 | Thenable, T2 | Thenable, T3 | Thenable, T4 | Thenable , T5 | Thenable, T6 | Thenable, T7 | Thenable, T8 | Thenable, T9 | Thenable, T10 | Thenable]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; - function all(values: [T1 | Thenable, T2 | Thenable, T3 | Thenable, T4 | Thenable , T5 | Thenable, T6 | Thenable, T7 | Thenable, T8 | Thenable, T9 | Thenable]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; - function all(values: [T1 | Thenable, T2 | Thenable, T3 | Thenable, T4 | Thenable , T5 | Thenable, T6 | Thenable, T7 | Thenable, T8 | Thenable]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>; - function all(values: [T1 | Thenable, T2 | Thenable, T3 | Thenable, T4 | Thenable , T5 | Thenable, T6 | Thenable, T7 | Thenable]): Promise<[T1, T2, T3, T4, T5, T6, T7]>; - function all(values: [T1 | Thenable, T2 | Thenable, T3 | Thenable, T4 | Thenable , T5 | Thenable, T6 | Thenable]): Promise<[T1, T2, T3, T4, T5, T6]>; - function all(values: [T1 | Thenable, T2 | Thenable, T3 | Thenable, T4 | Thenable , T5 | Thenable]): Promise<[T1, T2, T3, T4, T5]>; - function all(values: [T1 | Thenable, T2 | Thenable, T3 | Thenable, T4 | Thenable ]): Promise<[T1, T2, T3, T4]>; - function all(values: [T1 | Thenable, T2 | Thenable, T3 | Thenable]): Promise<[T1, T2, T3]>; - function all(values: [T1 | Thenable, T2 | Thenable]): Promise<[T1, T2]>; - function all(values: (T | Thenable)[]): Promise; - - /** - * Make a Promise that fulfills when any item fulfills, and rejects if any item rejects. - */ - function race(promises: (T | Thenable)[]): Promise; -} - -declare module 'es6-promise' { - var foo: typeof Promise; // Temp variable to reference Promise in local context - namespace rsvp { - export var Promise: typeof foo; - export function polyfill(): void; - } - export = rsvp; -} diff --git a/src/typings/fetch-mock/fetch-mock.d.ts b/src/typings/fetch-mock/fetch-mock.d.ts deleted file mode 100644 index 47c31e4c..00000000 --- a/src/typings/fetch-mock/fetch-mock.d.ts +++ /dev/null @@ -1,277 +0,0 @@ -// Type definitions for fetch-mock 5.0.0 -// Project: https://github.com/wheresrhys/fetch-mock -// Definitions by: Alexey Svetliakov , Tamir Duberstein -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - -declare module "fetch-mock" { - type MockRequest = Request | RequestInit; - - /** - * Mock matcher function - * @param url - * @param opts - */ - type MockMatcherFunction = (url: string, opts: MockRequest) => boolean - /** - * Mock matcher. Can be one of following: - * string: Either - * an exact url to match e.g. 'http://www.site.com/page.html' - * if the string begins with a `^`, the string following the `^` must - begin the url e.g. '^http://www.site.com' would match - 'http://www.site.com' or 'http://www.site.com/page.html' - * '*' to match any url - * RegExp: A regular expression to test the url against - * Function(url, opts): A function (returning a Boolean) that is passed the - url and opts fetch() is called with (or, if fetch() was called with one, - the Request instance) - */ - type MockMatcher = string | RegExp | MockMatcherFunction; - - /** - * Mock response object - */ - interface MockResponseObject { - /** - * Set the response body - */ - body?: string | {}; - /** - * Set the response status - * @default 200 - */ - status?: number; - /** - * Set the response headers. - */ - headers?: { [key: string]: string }; - /** - * If this property is present then a Promise rejected with the value - of throws is returned - */ - throws?: boolean; - /** - * This property determines whether or not the request body should be - JSON.stringified before being sent - * @default true - */ - sendAsJson?: boolean; - } - /** - * Response: A Response instance - will be used unaltered - * number: Creates a response with this status - * string: Creates a 200 response with the string as the response body - * object: As long as the object is not a MockResponseObject it is - converted into a json string and returned as the body of a 200 response - * If MockResponseObject was given then it's used to configure response - * Function(url, opts): A function that is passed the url and opts fetch() - is called with and that returns any of the responses listed above - */ - type MockResponse = Response | Promise - | number | Promise - | string | Promise - | Object | Promise - | MockResponseObject | Promise; - /** - * Mock response function - * @param url - * @param opts - */ - type MockResponseFunction = (url: string, opts: MockRequest) => MockResponse; - - /** - * Mock options object - */ - interface MockOptions { - /** - * A unique string naming the route. Used to subsequently retrieve - references to the calls, grouped by name. - * @default matcher.toString() - * - * Note: If a non-unique name is provided no error will be thrown - (because names are optional, auto-generated ones may legitimately - clash) - */ - name?: string; - /** - * http method to match - */ - method?: string; - /** - * as specified above - */ - matcher?: MockMatcher; - /** - * as specified above - */ - response?: MockResponse | MockResponseFunction; - } - - type MockCall = [string, MockRequest]; - - interface MatchedRoutes { - matched: Array; - unmatched: Array; - } - - interface MockOptionsMethodGet extends MockOptions { - method: 'GET' - } - - interface MockOptionsMethodPost extends MockOptions { - method: 'POST' - } - - interface MockOptionsMethodPut extends MockOptions { - method: 'PUT' - } - - interface MockOptionsMethodDelete extends MockOptions { - method: 'DELETE' - } - - interface MockOptionsMethodHead extends MockOptions { - method: 'HEAD' - } - - interface FetchMockStatic { - /** - * Replaces fetch() with a stub which records its calls, grouped by - route, and optionally returns a mocked Response object or passes the - call through to fetch(). Calls to .mock() can be chained. - * @param matcher Condition for selecting which requests to mock - * @param response Configures the http response returned by the mock - */ - mock(matcher: MockMatcher, response: MockResponse | MockResponseFunction): this; - /** - * Replaces fetch() with a stub which records its calls, grouped by - route, and optionally returns a mocked Response object or passes the - call through to fetch(). Calls to .mock() can be chained. - * @param matcher Condition for selecting which requests to mock - * @param response Configures the http response returned by the mock - * @param options Additional properties defining the route to mock - */ - mock(matcher: MockMatcher, response: MockResponse | MockResponseFunction, options: MockOptions): this; - /** - * Replaces fetch() with a stub which records its calls, grouped by - route, and optionally returns a mocked Response object or passes the - call through to fetch(). Calls to .mock() can be chained. - * @param options The route to mock - */ - mock(options: MockOptions): this; - /** - * Replaces fetch() with a stub which records its calls, grouped by - route, and optionally returns a mocked Response object or passes the - call through to fetch(). Shorthand for mock() restricted to the GET - method. Calls to .mock() can be chained. - * @param matcher Condition for selecting which requests to mock - * @param response Configures the http response returned by the mock - * @param [options] Additional properties defining the route to mock - */ - get(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodGet): this; - /** - * Replaces fetch() with a stub which records its calls, grouped by - route, and optionally returns a mocked Response object or passes the - call through to fetch(). Shorthand for mock() restricted to the POST - method. Calls to .mock() can be chained. - * @param matcher Condition for selecting which requests to mock - * @param response Configures the http response returned by the mock - * @param [options] Additional properties defining the route to mock - */ - post(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodPost): this; - /** - * Replaces fetch() with a stub which records its calls, grouped by - route, and optionally returns a mocked Response object or passes the - call through to fetch(). Shorthand for mock() restricted to the PUT - method. Calls to .mock() can be chained. - * @param matcher Condition for selecting which requests to mock - * @param response Configures the http response returned by the mock - * @param [options] Additional properties defining the route to mock - */ - put(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodPut): this; - /** - * Replaces fetch() with a stub which records its calls, grouped by - route, and optionally returns a mocked Response object or passes the - call through to fetch(). Shorthand for mock() restricted to the - DELETE method. Calls to .mock() can be chained. - * @param matcher Condition for selecting which requests to mock - * @param response Configures the http response returned by the mock - * @param [options] Additional properties defining the route to mock - */ - delete(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodDelete): this; - /** - * Replaces fetch() with a stub which records its calls, grouped by - route, and optionally returns a mocked Response object or passes the - call through to fetch(). Shorthand for mock() restricted to the HEAD - method. Calls to .mock() can be chained. - * @param matcher Condition for selecting which requests to mock - * @param response Configures the http response returned by the mock - * @param [options] Additional properties defining the route to mock - */ - head(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodHead): this; - /** - * Chainable method that restores fetch() to its unstubbed state and - clears all data recorded for its calls. - */ - restore(): this; - /** - * Chainable method that clears all data recorded for fetch()'s calls - */ - reset(): this; - /** - * Returns all calls to fetch, grouped by whether fetch-mock matched - them or not. - */ - calls(): MatchedRoutes; - /** - * Returns all calls to fetch matching matcherName. - */ - calls(matcherName?: string): Array; - /** - * Returns a Boolean indicating whether fetch was called and a route - was matched. - */ - called(): boolean; - /** - * Returns a Boolean indicating whether fetch was called and a route - named matcherName was matched. - */ - called(matcherName?: string): boolean; - /** - * Returns the arguments for the last matched call to fetch - */ - lastCall(): MockCall; - /** - * Returns the arguments for the last call to fetch matching - matcherName - */ - lastCall(matcherName?: string): MockCall; - /** - * Returns the url for the last matched call to fetch - */ - lastUrl(): string; - /** - * Returns the url for the last call to fetch matching matcherName - */ - lastUrl(matcherName?: string): string; - /** - * Returns the options for the last matched call to fetch - */ - lastOptions(): MockRequest; - /** - * Returns the options for the last call to fetch matching matcherName - */ - lastOptions(matcherName?: string): MockRequest; - /** - * Set some global config options, which include - * sendAsJson [default `true`] - by default fetchMock will - convert objects to JSON before sending. This is overrideable - for each call but for some scenarios, e.g. when dealing with a - lot of array buffers, it can be useful to default to `false` - */ - configure(opts: Object): void; - } - - var fetchMock: FetchMockStatic; - export = fetchMock; -} diff --git a/src/typings/globals/karma/index.d.ts b/src/typings/globals/karma/index.d.ts new file mode 100644 index 00000000..992e7479 --- /dev/null +++ b/src/typings/globals/karma/index.d.ts @@ -0,0 +1,399 @@ +// Generated by typings +// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/568ec4378d010bb901a61bd9686be49077e54d5f/karma/karma.d.ts +declare module 'karma' { + // See Karma public API https://karma-runner.github.io/0.13/dev/public-api.html + import Promise = require('bluebird'); + import https = require('https'); + import log4js = require('log4js'); + + namespace karma { + interface Karma { + /** + * `start` method is deprecated since 0.13. It will be removed in 0.14. + * Please use + * + * server = new Server(config, [done]) + * server.start() + * + * instead. + */ + server: DeprecatedServer; + Server: Server; + runner: Runner; + stopper: Stopper; + launcher: Launcher; + VERSION: string; + } + + interface LauncherStatic { + generateId(): string; + //TODO: injector should be of type `di.Injector` + new (emitter: NodeJS.EventEmitter, injector: any): Launcher; + } + + interface Launcher { + Launcher: LauncherStatic; + //TODO: Can this return value ever be typified? + launch(names: string[], protocol: string, hostname: string, port: number, urlRoot: string): any[]; + kill(id: string, callback: Function): boolean; + restart(id: string): boolean; + killAll(callback: Function): void; + areAllCaptured(): boolean; + markCaptured(id: string): void; + } + + interface DeprecatedServer { + start(options?: any, callback?: ServerCallback): void; + } + + interface Runner { + run(options?: ConfigOptions | ConfigFile, callback?: ServerCallback): void; + } + + + interface Stopper { + /** + * This function will signal a running server to stop. The equivalent of karma stop. + */ + stop(options?: ConfigOptions, callback?: ServerCallback): void; + } + + + interface TestResults { + disconnected: boolean; + error: boolean; + exitCode: number; + failed: number; + success: number; + } + + interface Server extends NodeJS.EventEmitter { + new (options?: ConfigOptions | ConfigFile, callback?: ServerCallback): Server; + /** + * Start the server + */ + start(): void; + /** + * Get properties from the injector + * @param token + */ + get(token: string): any; + /** + * Force a refresh of the file list + */ + refreshFiles(): Promise; + + on(event: string, listener: Function): this; + + /** + * Listen to the 'run_complete' event. + */ + on(event: 'run_complete', listener: (browsers: any, results: TestResults ) => void): this; + + ///** + // * Backward-compatibility with karma-intellij bundled with WebStorm. + // * Deprecated since version 0.13, to be removed in 0.14 + // */ + //static start(): void; + } + + interface ServerCallback { + (exitCode: number): void; + } + + interface Config { + set: (config: ConfigOptions) => void; + LOG_DISABLE: string; + LOG_ERROR: string; + LOG_WARN: string; + LOG_INFO: string; + LOG_DEBUG: string; + } + + interface ConfigFile { + configFile: string; + } + + interface ConfigOptions { + /** + * @description Enable or disable watching files and executing the tests whenever one of these files changes. + * @default true + */ + autoWatch?: boolean; + /** + * @description When Karma is watching the files for changes, it tries to batch multiple changes into a single run + * so that the test runner doesn't try to start and restart running tests more than it should. + * The configuration setting tells Karma how long to wait (in milliseconds) after any changes have occurred + * before starting the test process again. + * @default 250 + */ + autoWatchBatchDelay?: number; + /** + * @default '' + * @description The root path location that will be used to resolve all relative paths defined in files and exclude. + * If the basePath configuration is a relative path then it will be resolved to + * the __dirname of the configuration file. + */ + basePath?: string; + /** + * @default 2000 + * @description How long does Karma wait for a browser to reconnect (in ms). + *

+ * With a flaky connection it is pretty common that the browser disconnects, + * but the actual test execution is still running without any problems. Karma does not treat a disconnection + * as immediate failure and will wait browserDisconnectTimeout (ms). + * If the browser reconnects during that time, everything is fine. + *

+ */ + browserDisconnectTimeout?: number; + /** + * @default 0 + * @description The number of disconnections tolerated. + *

+ * The disconnectTolerance value represents the maximum number of tries a browser will attempt + * in the case of a disconnection. Usually any disconnection is considered a failure, + * but this option allows you to define a tolerance level when there is a flaky network link between + * the Karma server and the browsers. + *

+ */ + browserDisconnectTolerance?: number; + /** + * @default 10000 + * @description How long will Karma wait for a message from a browser before disconnecting from it (in ms). + *

+ * If, during test execution, Karma does not receive any message from a browser within + * browserNoActivityTimeout (ms), it will disconnect from the browser + *

+ */ + browserNoActivityTimeout?: number; + /** + * @default [] + * Possible Values: + *
    + *
  • Chrome (launcher comes installed with Karma)
  • + *
  • ChromeCanary (launcher comes installed with Karma)
  • + *
  • PhantomJS (launcher comes installed with Karma)
  • + *
  • Firefox (launcher requires karma-firefox-launcher plugin)
  • + *
  • Opera (launcher requires karma-opera-launcher plugin)
  • + *
  • Internet Explorer (launcher requires karma-ie-launcher plugin)
  • + *
  • Safari (launcher requires karma-safari-launcher plugin)
  • + *
+ * @description A list of browsers to launch and capture. When Karma starts up, it will also start up each browser + * which is placed within this setting. Once Karma is shut down, it will shut down these browsers as well. + * You can capture any browser manually by opening the browser and visiting the URL where + * the Karma web server is listening (by default it is http://localhost:9876/). + */ + browsers?: string[]; + /** + * @default 60000 + * @description Timeout for capturing a browser (in ms). + *

+ * The captureTimeout value represents the maximum boot-up time allowed for a + * browser to start and connect to Karma. If any browser does not get captured within the timeout, Karma + * will kill it and try to launch it again and, after three attempts to capture it, Karma will give up. + *

+ */ + captureTimeout?: number; + client?: ClientOptions; + /** + * @default true + * @description Enable or disable colors in the output (reporters and logs). + */ + colors?: boolean; + /** + * @default [] + * @description List of files/patterns to exclude from loaded files. + */ + exclude?: string[]; + /** + * @default [] + * @description List of files/patterns to load in the browser. + */ + files?: (FilePattern | string)[]; + /** + * @default [] + * @description List of test frameworks you want to use. Typically, you will set this to ['jasmine'], ['mocha'] or ['qunit']... + * Please note just about all frameworks in Karma require an additional plugin/framework library to be installed (via NPM). + */ + frameworks?: string[]; + /** + * @default 'localhost' + * @description Hostname to be used when capturing browsers. + */ + hostname?: string; + /** + * @default {} + * @description Options object to be used by Node's https class. + * Object description can be found in the + * [NodeJS.org API docs](https://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener) + */ + httpsServerOptions?: https.ServerOptions; + /** + * @default config.LOG_INFO + * Possible values: + *
    + *
  • config.LOG_DISABLE
  • + *
  • config.LOG_ERROR
  • + *
  • config.LOG_WARN
  • + *
  • config.LOG_INFO
  • + *
  • config.LOG_DEBUG
  • + *
+ * @description Level of logging. + */ + logLevel?: string; + /** + * @default [{type: 'console'}] + * @description A list of log appenders to be used. See the documentation for [log4js] for more information. + */ + loggers?: log4js.AppenderConfigBase[]; + /** + * @default ['karma-*'] + * @description List of plugins to load. A plugin can be a string (in which case it will be required + * by Karma) or an inlined plugin - Object. + * By default, Karma loads all sibling NPM modules which have a name starting with karma-*. + * Note: Just about all plugins in Karma require an additional library to be installed (via NPM). + */ + plugins?: any[]; + /** + * @default 9876 + * @description The port where the web server will be listening. + */ + port?: number; + /** + * @default {'**\/*.coffee': 'coffee'} + * @description A map of preprocessors to use. + * + * Preprocessors can be loaded through [plugins]. + * + * Note: Just about all preprocessors in Karma (other than CoffeeScript and some other defaults) + * require an additional library to be installed (via NPM). + * + * Be aware that preprocessors may be transforming the files and file types that are available at run time. For instance, + * if you are using the "coverage" preprocessor on your source files, if you then attempt to interactively debug + * your tests, you'll discover that your expected source code is completely changed from what you expected. Because + * of that, you'll want to engineer this so that your automated builds use the coverage entry in the "reporters" list, + * but your interactive debugging does not. + * + */ + preprocessors?: { [name: string]: string | string[] } + /** + * @default 'http:' + * Possible Values: + *
    + *
  • http:
  • + *
  • https:
  • + *
+ * @description Protocol used for running the Karma webserver. + * Determines the use of the Node http or https class. + * Note: Using 'https:' requires you to specify httpsServerOptions. + */ + protocol?: string; + /** + * @default {} + * @description A map of path-proxy pairs. + */ + proxies?: { [path: string]: string } + /** + * @default true + * @description Whether or not Karma or any browsers should raise an error when an inavlid SSL certificate is found. + */ + proxyValidateSSL?: boolean; + /** + * @default 0 + * @description Karma will report all the tests that are slower than given time limit (in ms). + * This is disabled by default (since the default value is 0). + */ + reportSlowerThan?: number; + /** + * @default ['progress'] + * Possible Values: + *
    + *
  • dots
  • + *
  • progress
  • + *
+ * @description A list of reporters to use. + * Additional reporters, such as growl, junit, teamcity or coverage can be loaded through plugins. + * Note: Just about all additional reporters in Karma (other than progress) require an additional library to be installed (via NPM). + */ + reporters?: string[]; + /** + * @default false + * @description Continuous Integration mode. + * If true, Karma will start and capture all configured browsers, run tests and then exit with an exit code of 0 or 1 depending + * on whether all tests passed or any tests failed. + */ + singleRun?: boolean; + /** + * @default ['polling', 'websocket'] + * @description An array of allowed transport methods between the browser and testing server. This configuration setting + * is handed off to [socket.io](http://socket.io/) (which manages the communication + * between browsers and the testing server). + */ + transports?: string[]; + /** + * @default '/' + * @description The base url, where Karma runs. + * All of Karma's urls get prefixed with the urlRoot. This is helpful when using proxies, as + * sometimes you might want to proxy a url that is already taken by Karma. + */ + urlRoot?: string; + } + + interface ClientOptions { + /** + * @default undefined + * @description When karma run is passed additional arguments on the command-line, they + * are passed through to the test adapter as karma.config.args (an array of strings). + * The client.args option allows you to set this value for actions other than run. + * How this value is used is up to your test adapter - you should check your adapter's + * documentation to see how (and if) it uses this value. + */ + args?: string[]; + /** + * @default true + * @description Run the tests inside an iFrame or a new window + * If true, Karma runs the tests inside an iFrame. If false, Karma runs the tests in a new window. Some tests may not run in an + * iFrame and may need a new window to run. + */ + useIframe?: boolean; + /** + * @default true + * @description Capture all console output and pipe it to the terminal. + */ + captureConsole?: boolean; + } + + interface FilePattern { + /** + * The pattern to use for matching. This property is mandatory. + */ + pattern: string; + /** + * @default true + * @description If autoWatch is true all files that have set watched to true will be watched + * for changes. + */ + watched?: boolean; + /** + * @default true + * @description Should the files be included in the browser using