UNPKG

@azure/communication-signaling

Version:

Azure Communication Signaling Client

33 lines (23 loc) 194 kB
'use strict'; var uuid = require('uuid'); var coreUtil = require('@azure/core-util'); var coreClient = require('@azure/core-client'); var coreRestPipeline = require('@azure/core-rest-pipeline'); function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } var uuid__default = /*#__PURE__*/_interopDefaultLegacy(uuid); var coreUtil__default = /*#__PURE__*/_interopDefaultLegacy(coreUtil); var coreClient__default = /*#__PURE__*/_interopDefaultLegacy(coreClient); var coreRestPipeline__default = /*#__PURE__*/_interopDefaultLegacy(coreRestPipeline); var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function unwrapExports (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } var tsregistrar = createCommonjsModule(function (module, exports) { !function(t,e){module.exports=e();}(commonjsGlobal,function(){return function(t){function e(n){if(r[n])return r[n].exports;var o=r[n]={i:n,l:!1,exports:{}};return t[n].call(o.exports,o,o.exports,e),o.l=!0,o.exports}var r={};return e.m=t,e.c=r,e.i=function(t){return t},e.d=function(t,r,n){e.o(t,r)||Object.defineProperty(t,r,{configurable:!1,enumerable:!0,get:n});},e.n=function(t){var r=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(r,"a",r),r},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=1)}([function(t,e,r){function n(t,e){var r,n=new Promise(function(e,n){fetch(t).then(function(t){void 0!==r&&clearTimeout(r),e(t);}).catch(function(t){void 0!==r&&clearTimeout(r),n(t);});});if(0!==e){var o=new Promise(function(n,o){r=setTimeout(o,e,new Error("Fetch for '".concat(t.url,"' timed out")));});return Promise.race([n,o])}return n}function o(t){try{return JSON.stringify(t)}catch(e){return "Unable to serialize object of type ".concat(typeof t)}}Object.defineProperty(e,"__esModule",{value:!0}),e.Timespan=e.toJson=e.fetchWithTimeout=void 0,e.fetchWithTimeout=n,e.toJson=o;var i=function(){function t(){this.start=Date.now();}return Object.defineProperty(t.prototype,"duration",{get:function(){return Date.now()-this.start},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"startTime",{get:function(){return this.start},enumerable:!1,configurable:!0}),t.prototype.reset=function(){this.start=Date.now();},t}();e.Timespan=i;},function(t,e,r){function n(t,e,r){return new h(t,e,r)}var o=this&&this.__extends||function(){var t=function(e,r){return (t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e;}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);})(e,r)};return function(e,r){function n(){this.constructor=e;}if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r),e.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n);}}(),i=this&&this.__assign||function(){return i=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++){e=arguments[r];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);}return t},i.apply(this,arguments)},s=this&&this.__awaiter||function(t,e,r,n){function o(t){return t instanceof r?t:new r(function(e){e(t);})}return new(r||(r=Promise))(function(r,i){function s(t){try{c(n.next(t));}catch(t){i(t);}}function a(t){try{c(n.throw(t));}catch(t){i(t);}}function c(t){t.done?r(t.value):o(t.value).then(s,a);}c((n=n.apply(t,e||[])).next());})},a=this&&this.__generator||function(t,e){function r(t){return function(e){return n([t,e])}}function n(r){if(o)throw new TypeError("Generator is already executing.");for(;a&&(a=0,r[0]&&(c=0)),c;)try{if(o=1,i&&(s=2&r[0]?i.return:r[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,r[1])).done)return s;switch(i=0,s&&(r=[2&r[0],s.value]),r[0]){case 0:case 1:s=r;break;case 4:return c.label++,{value:r[1],done:!1};case 5:c.label++,i=r[1],r=[0];continue;case 7:r=c.ops.pop(),c.trys.pop();continue;default:if(s=c.trys,!(s=s.length>0&&s[s.length-1])&&(6===r[0]||2===r[0])){c=0;continue}if(3===r[0]&&(!s||r[1]>s[0]&&r[1]<s[3])){c.label=r[1];break}if(6===r[0]&&c.label<s[1]){c.label=s[1],s=r;break}if(s&&c.label<s[2]){c.label=s[2],c.ops.push(r);break}s[2]&&c.ops.pop(),c.trys.pop();continue}r=e.call(t,c);}catch(t){r=[6,t],i=0;}finally{o=s=0;}if(5&r[0])throw r[1];return {value:r[0]?r[1]:void 0,done:!0}}var o,i,s,a,c={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return a={next:r(0),throw:r(1),return:r(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a};Object.defineProperty(e,"__esModule",{value:!0}),e.createRegistrarClient=e.RegistrarClient=void 0;var c=r(0),u=["skype","aad","cae"],l=function(t){function e(e){var r=t.call(this,e)||this;return r.name="CancelationError",r}return o(e,t),e}(Error),f=function(){function t(e,r,n){this.logger=e,this.maxBackoffInMs=r,this.initialDelay=n,this.backoffCount=0,this.id=++t.idCounter;}return t.prototype.delay=function(t){var e=this;if(void 0!==this.timerHandle)throw new Error("Retry sequence logical failure");if(-1===this.backoffCount)return new Promise(function(t,e){e(new l("Cancelled"));});var r=this.calculateNextBackoffMs();return this.backoffCount++,this.logger.info("[RegistrarClient] Backing off ".concat(t," for ").concat(r," milliseconds with ID ").concat(this.id)),new Promise(function(n,o){e.cancelFunc=o,e.timerHandle=setTimeout(function(){e.logger.info("[RegistrarClient] Back off for ".concat(t," with ID ").concat(e.id," complete")),e.timerHandle=void 0,n();},r);})},t.prototype.cancel=function(){void 0!==this.timerHandle&&(this.logger.debug("Resetting back off"),clearTimeout(this.timerHandle),void 0!==this.cancelFunc&&this.cancelFunc(new l("Cancelled"))),this.backoffCount=-1;},t.prototype.calculateNextBackoffMs=function(){var t=1+.4*(Math.random()-.5),e=this.initialDelay*Math.pow(2,this.backoffCount)*t;return e=Math.round(e),Math.min(this.maxBackoffInMs,e)},t.idCounter=0,t}(),h=function(){function t(t,e,r){var n;this.logger=t,this.tokenProvider=e,this.options=r,this.DEFAULT_MAX_RETRIES_FOR_GET_TOKEN=15,this.DEFAULT_MAX_BACKOFF_TIME_IN_MS=3e5,this.backoffs={},this.maxBackOffTime=this.options.maxRetryDelayMs>0?this.options.maxRetryDelayMs:this.DEFAULT_MAX_BACKOFF_TIME_IN_MS,this.maxRetriesForGetToken=void 0===r.maxRetriesForGetToken||null===r.maxRetriesForGetToken?this.DEFAULT_MAX_RETRIES_FOR_GET_TOKEN:r.maxRetriesForGetToken,this.proxyUrlRewrite=null!==(n=r.proxyUrlRewrite)&&void 0!==n?n:function(t){return t};}return t.prototype.setTelemetryLogger=function(t){this.eventLogger=t;},t.prototype.register=function(t,e){return s(this,void 0,void 0,function(){return a(this,function(r){switch(r.label){case 0:return [4,this.performRegistration(t,e,"pr_set_registration")];case 1:return r.sent(),this.cachedRegistrationParams=[t,e],[2]}})})},t.prototype.unregister=function(){return s(this,void 0,void 0,function(){var t;return a(this,function(e){switch(e.label){case 0:return this.logger.info("[RegistrarClient] sending unregister request"),t=new Request(this.proxyUrlRewrite("".concat(this.options.registrarUrl,"/").concat(this.options.registrationId)),{method:"DELETE",mode:"cors",headers:new Headers(i(i({},this.options.extraRegistrationHeaders),{accept:"application/json, text/javascript"}))}),[4,this.callRegistrar(t,"pr_delete_registration")];case 1:return e.sent(),[2]}})})},t.prototype.cancelPendingRequests=function(){var t=this;Object.keys(this.backoffs).forEach(function(e){t.backoffs[e].cancel();}),this.backoffs={};},t.prototype.resendRegistration=function(){return s(this,void 0,void 0,function(){return a(this,function(t){switch(t.label){case 0:if(!this.cachedRegistrationParams)throw new Error("Re-registration failed because there is no registration parameters cached");return [4,this.performRegistration(this.cachedRegistrationParams[0],this.cachedRegistrationParams[1],"pr_resend_registration")];case 1:return t.sent(),[2]}})})},t.prototype.performRegistration=function(t,e,r){return s(this,void 0,void 0,function(){var n,o;return a(this,function(s){switch(s.label){case 0:return this.logger.info("[RegistrarClient] Sending register request"),n={clientDescription:t,registrationId:this.options.registrationId,nodeId:"",transports:e},o=new Request(this.proxyUrlRewrite(this.options.registrarUrl),{method:"POST",mode:"cors",headers:new Headers(i(i({},this.options.extraRegistrationHeaders),{"content-type":"application/json",accept:"application/json, text/javascript"})),body:(0, c.toJson)(n)}),[4,this.callRegistrar(o,r)];case 1:return s.sent(),[2]}})})},t.prototype.startBackoff=function(){var t=new f(this.logger,this.maxBackOffTime,this.options.initialRetryDelayMs);return this.backoffs[t.id]=t,t},t.prototype.stopBackoff=function(t){t.cancel(),delete this.backoffs[t.id];},t.prototype.getToken=function(t){return s(this,void 0,void 0,function(){var e,r,n,o,i,s,c;return a(this,function(a){switch(a.label){case 0:e=this.startBackoff(),r=0,a.label=1;case 1:return a.trys.push([1,3,,8]),this.logger.info("[RegistrarClient] Asking for a new token"),[4,this.tokenProvider({needFresh:!0,supportedTokenTypes:u,wwwAuthenticateHeader:t,purpose:"registrar"})];case 2:return n=a.sent(),this.stopBackoff(e),[2,n];case 3:o=a.sent(),a.label=4;case 4:return a.trys.push([4,6,,7]),(r++,i=JSON.stringify(o),r>this.maxRetriesForGetToken)?(s="[RegistrarClient] getToken retry limit hit. Will not retry now. Error: ".concat(i),this.logger.error(s),this.stopBackoff(e),[2,Promise.reject(s)]):(this.logger.warn("[RegistrarClient] Retrying for a new token. Retry Count: ".concat(r," Error: ").concat(i)),[4,e.delay("Fetching a new token")]);case 5:return a.sent(),[3,8];case 6:throw c=a.sent(),this.stopBackoff(e),c;case 7:return [3,8];case 8:return [3,1];case 9:return [2]}})})},t.prototype.callRegistrar=function(t,e){var r,n,o;return s(this,void 0,void 0,function(){var i,s,l,f,h,p,d,g,y,v,w,k,m,b,R,_;return a(this,function(a){switch(a.label){case 0:return i=this.startBackoff(),[4,this.tokenProvider({needFresh:!1,supportedTokenTypes:u,wwwAuthenticateHeader:void 0,purpose:"registrar"})];case 1:s=a.sent(),this.setTokenHeader(t,s),l=new c.Timespan,f=0,a.label=2;case 2:h=void 0,a.label=3;case 3:return a.trys.push([3,10,15,16]),p=t.clone(),[4,(0, c.fetchWithTimeout)(p,this.options.requestTimeoutMs)];case 4:return h=a.sent(),401!==h.status?[3,8]:++f>this.maxRetriesForGetToken?(d="[RegistrarClient] getSkypeToken retry limit hit. Will not retry now. Request '".concat(t.url,"' failed with ").concat(h.status," ").concat(h.statusText),this.logger.error(d),this.stopBackoff(i),[2,Promise.reject(d)]):(this.logger.warn("[RegistrarClient] Retry Count ".concat(f,". Request '").concat(t.url,"' failed with ").concat(h.status," ").concat(h.statusText)),g=null!==(n=null===(r=h.headers)||void 0===r?void 0:r.get("www-authenticate"))&&void 0!==n?n:void 0,y=this.setTokenHeader,v=[t],[4,this.getToken(g)]);case 5:return y.apply(this,v.concat([a.sent()])),f>1?[4,i.delay("Registrar call retry after 401")]:[3,7];case 6:a.sent(),a.label=7;case 7:return [3,22];case 8:if(h.status>=500&&h.status<600)throw new Error("Fetch for '".concat(t.url,"' failed with ").concat(h.status," ").concat(h.statusText));a.label=9;case 9:return [3,16];case 10:w=a.sent(),this.logger.error("[RegistrarClient] Request failed with ".concat(w)),a.label=11;case 11:return a.trys.push([11,13,,14]),[4,i.delay("Registrar call retry")];case 12:return a.sent(),[3,22];case 13:throw k=a.sent(),this.logger.error("[RegistrarClient] Request cancelled"),this.stopBackoff(i),k;case 14:return [3,16];case 15:return this.sendTelemetryEvent(e,t,h,l),[7];case 16:return this.stopBackoff(i),h.ok?[2,h]:[3,17];case 17:m=void 0,a.label=18;case 18:return a.trys.push([18,20,,21]),R=(b=JSON).stringify,[4,h.json()];case 19:return m=R.apply(b,[a.sent()]),[3,21];case 20:return a.sent(),m="no details",[3,21];case 21:throw _="Fetch for '".concat(t.url,"' failed with ").concat(h.status," ").concat(h.statusText," (").concat(m,", MS-CV: ").concat(null===(o=h.headers)||void 0===o?void 0:o.get("MS-CV"),")"),this.logger.error("[RegistrarClient] ".concat(_)),new Error(_);case 22:return [3,2];case 23:return [2]}})})},t.prototype.setTokenHeader=function(t,e){switch(t.headers.delete("X-Skypetoken"),t.headers.delete("Authorization"),t.headers.delete("X-MS-Migration"),e.tokenType.toLowerCase()){case"skype":t.headers.set("X-Skypetoken",e.token);break;case"aad":case"cae":t.headers.set("Authorization","Bearer ".concat(e.token));break;default:throw new Error("unsupported token type: ".concat(e.tokenType))}!1===this.options.usingLegacyTokenApi&&t.headers.set("X-MS-Migration","True");},t.prototype.sendTelemetryEvent=function(t,e,r,n){if(void 0!==this.eventLogger){var o={name:t,properties:{url:{value:e.url},result_code:{value:void 0!==r?r.status:0},begin_timestamp:{value:n.startTime},elapsed:{value:n.duration}}};this.eventLogger.logEvent(o);}},t}();e.RegistrarClient=h,e.createRegistrarClient=n;}])}); }); unwrapExports(tsregistrar); var tstrouter = createCommonjsModule(function (module, exports) { !function(t,e){module.exports=e(tsregistrar);}(commonjsGlobal,function(t){return function(t){function e(o){if(n[o])return n[o].exports;var i=n[o]={i:o,l:!1,exports:{}};return t[o].call(i.exports,i,i.exports,e),i.l=!0,i.exports}var n={};return e.m=t,e.c=n,e.i=function(t){return t},e.d=function(t,n,o){e.o(t,n)||Object.defineProperty(t,n,{configurable:!1,enumerable:!0,get:o});},e.n=function(t){var n=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(n,"a",n),n},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=20)}([function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.Logger=void 0;var o=function(){function t(t,e){this.name=t,this.logger=e;}return t.prototype.debug=function(t){this.logger.debug("[".concat(this.name,"] ").concat(t));},t.prototype.info=function(t){this.logger.info("[".concat(this.name,"] ").concat(t));},t.prototype.warn=function(t){this.logger.warn("[".concat(this.name,"] ").concat(t));},t.prototype.error=function(t){this.logger.error("[".concat(this.name,"] ").concat(t));},t}();e.Logger=o;},function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.USER_AUTHENTICATE_EVENT_NAME=e.SUPPORTED_TOKEN_TYPES=e.FAILED_MESSAGE_ACK=e.UNHANDLED_MESSAGE_ACK=e.HANDLED_MESSAGE_ACK=e.CLIENT_VERSION=e.constants=void 0,e.constants={TROUTER_INIT:"trouterinit",TROUTER_READY_EVENT:"trouterReadyEvent",TROUTER_READY_TIMEOUT:"trouterReadyTimeout",TROUTER_TOKEN_REQUEST:"trouterTokenRequest",TROUTER_TOKEN_GET_SUCCEEDED:"trouterTokenGetSucceeded",TROUTER_TOKEN_GET_FAILED:"trouterTokenGetFailed",TROUTER_RECONNECTING:"trouterReconnecting",RENEWAL:"renewal",NEW_CONNECTION:"newConnection",ENDPOINT_REGISTRATION_FAILED:"endpointRegistrationFailed"},e.CLIENT_VERSION="2024.14.01.55",e.HANDLED_MESSAGE_ACK=200,e.UNHANDLED_MESSAGE_ACK=404,e.FAILED_MESSAGE_ACK=500,e.SUPPORTED_TOKEN_TYPES=["skype","aad","cae"],e.USER_AUTHENTICATE_EVENT_NAME="user.authenticate";},function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.TrouterState=e.UserActivityState=void 0;var o;!function(t){t[t.Unknown=0]="Unknown",t[t.Active=1]="Active",t[t.Inactive=2]="Inactive";}(o||(e.UserActivityState=o={}));var i;!function(t){t[t.Unknown=0]="Unknown",t[t.Connected=2]="Connected",t[t.Disconnected=3]="Disconnected",t[t.Switching=9]="Switching";}(i||(e.TrouterState=i={}));},function(t,e,n){function o(t){try{return JSON.stringify(t)}catch(e){return "Unable to serialize object of type ".concat(typeof t)}}function i(t){var e=Math.round((new Date).getTime()/1e3);return void 0!==t&&t>e?t-e:0}function r(t){return Math.round((new Date).getTime()/1e3)+t}function s(t,e){return c(this,void 0,void 0,function(){var n,o,i;return a(this,function(r){return o=new Promise(function(e,o){fetch(t).then(function(t){clearTimeout(n),e(t);}).catch(function(t){clearTimeout(n),o(t);});}),0!==e?(i=new Promise(function(o,i){var r=new URL(t.url),s=new Error("".concat(t.method," ").concat(r.origin).concat(r.pathname," timed out"));n=setTimeout(i,e,s);}),[2,Promise.race([o,i])]):[2,o]})})}var c=this&&this.__awaiter||function(t,e,n,o){function i(t){return t instanceof n?t:new n(function(e){e(t);})}return new(n||(n=Promise))(function(n,r){function s(t){try{a(o.next(t));}catch(t){r(t);}}function c(t){try{a(o.throw(t));}catch(t){r(t);}}function a(t){t.done?n(t.value):i(t.value).then(s,c);}a((o=o.apply(t,e||[])).next());})},a=this&&this.__generator||function(t,e){function n(t){return function(e){return o([t,e])}}function o(n){if(i)throw new TypeError("Generator is already executing.");for(;c&&(c=0,n[0]&&(a=0)),a;)try{if(i=1,r&&(s=2&n[0]?r.return:n[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,n[1])).done)return s;switch(r=0,s&&(n=[2&n[0],s.value]),n[0]){case 0:case 1:s=n;break;case 4:return a.label++,{value:n[1],done:!1};case 5:a.label++,r=n[1],n=[0];continue;case 7:n=a.ops.pop(),a.trys.pop();continue;default:if(s=a.trys,!(s=s.length>0&&s[s.length-1])&&(6===n[0]||2===n[0])){a=0;continue}if(3===n[0]&&(!s||n[1]>s[0]&&n[1]<s[3])){a.label=n[1];break}if(6===n[0]&&a.label<s[1]){a.label=s[1],s=n;break}if(s&&a.label<s[2]){a.label=s[2],a.ops.push(n);break}s[2]&&a.ops.pop(),a.trys.pop();continue}n=e.call(t,a);}catch(t){n=[6,t],r=0;}finally{i=s=0;}if(5&n[0])throw n[1];return {value:n[0]?n[1]:void 0,done:!0}}var i,r,s,c,a={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return c={next:n(0),throw:n(1),return:n(2)},"function"==typeof Symbol&&(c[Symbol.iterator]=function(){return this}),c};Object.defineProperty(e,"__esModule",{value:!0}),e.Timespan=e.CorrelationVector=e.fetchWithTimeout=e.calculateExpireTsInSec=e.calculateTtlInSec=e.toJson=void 0,e.toJson=o,e.calculateTtlInSec=i,e.calculateExpireTsInSec=r,e.fetchWithTimeout=s;var u=function(){function t(t){this.base=void 0!==t?t:this.createCorrelationVectorBase(),this.extension=0;}return t.extend=function(e){return new t(e)},t.prototype.increase=function(){this.extension++;},t.prototype.value=function(){return "".concat(this.base,".").concat(this.extension)},t.prototype.createCorrelationVectorBase=function(){for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0987654321/+",e="AQgw",n="",o=0;o<21;o++)n+=t.charAt(Math.floor(Math.random()*t.length));return n+=e.charAt(Math.floor(Math.random()*e.length))},t}();e.CorrelationVector=u;var h=function(){function t(){this.start=Date.now();}return Object.defineProperty(t.prototype,"duration",{get:function(){return Date.now()-this.start},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"startTime",{get:function(){return this.start},enumerable:!1,configurable:!0}),t.prototype.reset=function(){this.start=Date.now();},t}();e.Timespan=h;},function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.TrouterManagerState=e.UserActivityEventReason=e.ServerState=void 0;var o=n(3),i=function(){function t(t,e,n,o,i,r,s){this.connectionId=t,this.connectedClientId=e,this.domId=n,this.unsecureUrl=o,this.url=i,this.c2cUrlBase=r,this.expirationTsSec=s;}return t.prototype.getRemainingTtlInSec=function(){return (0, o.calculateTtlInSec)(this.expirationTsSec)},t}();e.ServerState=i;var r;!function(t){t[t.Unknown=0]="Unknown",t[t.Modified=1]="Modified",t[t.Snapshot=2]="Snapshot",t[t.Connected=3]="Connected";}(r||(e.UserActivityEventReason=r={}));var s;!function(t){t[t.Unknown=0]="Unknown",t[t.Connected=2]="Connected",t[t.Disconnected=3]="Disconnected",t[t.Switching=9]="Switching",t[t.TerminalError=10]="TerminalError";}(s||(e.TrouterManagerState=s={}));},function(t,e,n){function o(t,e){return "skype"===t&&"1"!==i(null===e||void 0===e?void 0:e.scae)?"v4a":"v4c"}function i(t){return "string"==typeof t?t:"number"==typeof t?t.toString():void 0}function r(t,e){return "v4c-websocket-failure"===(null===e||void 0===e?void 0:e.kind)?"v4a":t}function s(t){return Object.prototype.hasOwnProperty.call(t,"connectparams")}function c(t,e){return "v4a"===e?t.replace(/\/v4\/c\b/,"/v4/a").replace("wss://","https://").replace("ws://","http://"):t.replace(/\/v4\/a\b/,"/v4/c").replace("https://","wss://").replace("http://","ws://")}function a(t){if(void 0!==t)return d(d({},t),{reconnectUrl:void 0,serviceUrl:void 0})}function u(t){return "string"==typeof t?parseInt(t,10):t}function h(t){if("redirect"===(null===t||void 0===t?void 0:t.kind)&&void 0!==t.host){var e=t.host;return e.endsWith("/")&&(e=e.substring(0,e.length-1)),e.endsWith("/v4/c")||e.endsWith("/v4/a")||(e+="/v4/c"),e}}var d=this&&this.__assign||function(){return d=Object.assign||function(t){for(var e,n=1,o=arguments.length;n<o;n++){e=arguments[n];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);}return t},d.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0}),e.redirectUrlIfPresent=e.ensureNumber=e.reconnectParamsWithoutUrls=e.adaptUrl=e.isV4ConnectEvent=e.usedProtocolAfterFallback=e.usedProtocol=void 0,e.usedProtocol=o,e.usedProtocolAfterFallback=r,e.isV4ConnectEvent=s,e.adaptUrl=c,e.reconnectParamsWithoutUrls=a,e.ensureNumber=u,e.redirectUrlIfPresent=h;},function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.TrouterFsm=e.State=void 0;var o,i=n(4),r=n(0),s=n(5);!function(t){t[t.Initial=0]="Initial",t[t.RetrievingToken=1]="RetrievingToken",t[t.Allocating=2]="Allocating",t[t.Handshaking=3]="Handshaking",t[t.Connecting=4]="Connecting",t[t.AnonymousConnecting=5]="AnonymousConnecting",t[t.WebsocketAuthenticating=6]="WebsocketAuthenticating",t[t.Connected=7]="Connected",t[t.Unregistering=8]="Unregistering",t[t.TerminalError=9]="TerminalError";}(o||(e.State=o={}));var c;!function(t){t[t.Initial=0]="Initial",t[t.Registering=1]="Registering",t[t.RegisteringButResendPending=2]="RegisteringButResendPending",t[t.Retrying=3]="Retrying",t[t.Registered=4]="Registered",t[t.RegistrationDisabled=5]="RegistrationDisabled";}(c||(c={}));var a=function(){function t(t,e,n,i){this.worker=e,this.incallModeEnabled=n,this.protocolSelector=i,this.state=o.Initial,this.autoReconnect=!0,this.logger=new r.Logger("ConnectionFsm",t),this.registrationState=c.Initial;}return t.prototype.getState=function(){return this.state},t.prototype.isActive=function(){return this.state===o.Allocating||this.state===o.Connected||this.state===o.Handshaking||this.state===o.Connecting||this.state===o.RetrievingToken||this.state===o.AnonymousConnecting||this.state===o.WebsocketAuthenticating},t.prototype.isConnecting=function(){return this.state===o.Allocating||this.state===o.Handshaking||this.state===o.Connecting||this.state===o.AnonymousConnecting},t.prototype.start=function(){return this.state===o.Initial?(this.setState(o.RetrievingToken),this.worker.getToken(!0,!1,void 0),!0):(this.showIgnored("start"),!1)},t.prototype.stop=function(t,e){t&&(this.registrationState=c.Initial),this.worker.isIncallMode()&&this.worker.exitIncallMode(),this.worker.resetTokenBackoff(),this.worker.cancelPendingRegistrationRequests(),this.worker.stopConnectionTimer(),this.worker.stopPingTimer(),this.worker.clearSentEventTimers(),this.worker.stopRegistrationTimer(),this.worker.stopSocketIo(),this.state===o.Connected&&this.worker.sendDisconnectTelemetryEvent("connection stopped"),this.registrationState!==c.Registered&&this.registrationState!==c.Registering&&this.registrationState!==c.RegisteringButResendPending||this.state===o.Unregistering?e?(this.setState(o.TerminalError),this.worker.dispatchTerminalError()):(this.setState(o.Initial),this.worker.dispatchDisconnected()):(this.registrationState=c.Initial,this.setState(o.Unregistering),this.worker.sendUnregisterRequest());},t.prototype.onTokenReceived=function(t,e,n){this.state===o.RetrievingToken?"v4c"===(0, s.usedProtocolAfterFallback)(this.protocolSelector(t.tokenType,n),e)?(this.setState(o.AnonymousConnecting),this.worker.startConnectionTimer(),this.worker.connectV4c(t,e)):(this.setState(o.Allocating),this.worker.startConnectionTimer(),this.worker.sendAllocateRequest(t)):this.showIgnored("onTokenReceived");},t.prototype.checkConnection=function(t){t&&this.onPingInterval();},t.prototype.onAllocationSucceed=function(t){return this.state===o.Allocating&&this.registrationState===c.Registered&&this.worker.dispatchUnregistered(),this.state===o.Allocating?(this.setState(o.Handshaking),this.registrationState=c.Initial,this.worker.startSocketIo(t),!0):(this.showIgnored("onAllocationSucceed"),!1)},t.prototype.onAllocationFailed=function(t,e){this.state===o.Allocating?this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!t,claimsChallenge:e}):this.showIgnored("onAllocationFailed");},t.prototype.onV4cException=function(){this.state!==o.AnonymousConnecting&&this.state!==o.WebsocketAuthenticating||(this.logger.error("v4c exception, falling back to longpoll"),this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!0,fallbackReason:{kind:"v4c-websocket-failure"}}));},t.prototype.onConnectingTimeout=function(){this.state===o.Allocating||this.state===o.Connecting||this.state===o.Handshaking||this.state===o.AnonymousConnecting||this.state===o.WebsocketAuthenticating?this.cleanUpAndInitiateReconnect({backoff:!1,allowCachedToken:!0}):this.showIgnored("onConnectingTimeout");},t.prototype.onConnecting=function(){this.state===o.Handshaking?this.setState(o.Connecting):this.showIgnored("onConnecting");},t.prototype.onSocketConnect=function(t){this.state===o.AnonymousConnecting?(this.setState(o.WebsocketAuthenticating),this.worker.sendV4cAuthenticationEvent(t)):this.showIgnored("onSocketConnect");},t.prototype.onConnectingFailed=function(){this.state===o.Connecting?this.onConnectingTimeout():this.state===o.Handshaking?(this.logger.error("Unexpected error in Socket.io - no valid transports"),this.onConnectingTimeout()):this.state===o.AnonymousConnecting||this.state===o.WebsocketAuthenticating?(this.logger.info("/v4/c falling back to longpoll"),this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!0,fallbackReason:{kind:"v4c-websocket-failure"}})):this.showIgnored("onConnectingFailed");},t.prototype.onSocketDisconnect=function(t){this.state===o.Handshaking||this.state===o.Connected||this.state===o.WebsocketAuthenticating?(this.state===o.Connected&&this.worker.sendDisconnectTelemetryEvent(null===t||void 0===t?void 0:t.toTelemetryString()),this.state===o.WebsocketAuthenticating&&this.worker.countDisconnectBeforeConnectionEstablishment(),"skypetoken-deprecated"===(null===t||void 0===t?void 0:t.reason)?(this.logger.error("Skypetoken deprecated response, not retrying any further"),this.onTerminalError()):this.cleanUpAndInitiateReconnect({backoff:this.state!==o.Connected&&"dup"!==(null===t||void 0===t?void 0:t.reason),allowCachedToken:"unauthorized"!==(null===t||void 0===t?void 0:t.reason),claimsChallenge:null===t||void 0===t?void 0:t.claims})):this.showIgnored("onSocketDisconnect");},t.prototype.onTrouterConnected=function(){this.state===o.Connecting||this.state===o.WebsocketAuthenticating?(this.setState(o.Connected),this.worker.resetTokenBackoff(),this.worker.stopConnectionTimer(),this.worker.sendUserActivityState(i.UserActivityEventReason.Connected,!0),this.worker.startPingTimer(),this.worker.dispatchConnected(),this.worker.shouldSkipRegistration()?(this.registrationState=c.RegistrationDisabled,this.worker.dispatchRegistered()):(this.registrationState=c.Registering,this.worker.sendRegisterRequest())):this.showIgnored("onTrouterConnected");},t.prototype.onReconnectRequired=function(t,e,n){this.state===o.AnonymousConnecting||this.state===o.WebsocketAuthenticating?void 0===n||"host"!==n.target||void 0===n.url||""===n.url?(this.logger.error("unexpected reconnect arguments: ".concat(null===n||void 0===n?void 0:n.target," ").concat(null===n||void 0===n?void 0:n.url,", reconnecting without cache")),this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!0,fallbackReason:{kind:"redirect-no-host"}})):this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!0,fallbackReason:{kind:"redirect",host:n.url}}):this.worker.dispatchReconnectIsRequired(t,e);},t.prototype.disableAutoReconnect=function(){this.autoReconnect=!1;},t.prototype.onDownstreamRequest=function(t){this.state===o.Connected?(this.switchToIncallModeIfEnabled(),this.worker.dispatchDownstreamRequest(t)):this.showIgnored("onDownstreamRequest");},t.prototype.onTrouterMessageLost=function(t){this.state===o.Connected?this.worker.dispatchTrouterMessageLost(t):this.showIgnored("onTrouterMessageLost");},t.prototype.onPingInterval=function(){this.state===o.Connected?this.worker.sendPingRequest():this.showIgnored("onPingInterval");},t.prototype.onPingResponseTimeout=function(){this.onMissedResponse("onPingResponseTimeout");},t.prototype.onPingResponse=function(){this.state===o.Connected||this.showIgnored("onPingResponse");},t.prototype.onRegistrationFailed=function(){this.state===o.Connected&&this.registrationState===c.Registering?(this.worker.dispatchUnregistered(),this.registrationState=c.Retrying,this.worker.startRegistrationRetryTimer()):this.state===o.Connected&&this.registrationState===c.RegisteringButResendPending?(this.registrationState=c.Registering,this.worker.sendRegisterRequest()):this.showIgnored("onRegistrationFailed");},t.prototype.onRetryRegistration=function(){this.state===o.Connected&&this.registrationState===c.Retrying?(this.registrationState=c.Registering,this.worker.sendRegisterRequest()):this.showIgnored("onRetryRegistration");},t.prototype.onRegistrationSucceeded=function(){this.state===o.Connected&&this.registrationState===c.Registering?(this.registrationState=c.Registered,this.worker.dispatchRegistered(),this.worker.startRegistrationTimer()):this.state===o.Connected&&this.registrationState===c.RegisteringButResendPending?(this.registrationState=c.Registering,this.worker.sendRegisterRequest()):this.showIgnored("onRegistrationSucceeded");},t.prototype.onRegistrationNearExpiry=function(){this.state===o.Connected&&this.registrationState===c.Registered?(this.registrationState=c.Registering,this.worker.sendRegisterRequest()):this.showIgnored("onRegistrationNearExpiry");},t.prototype.onUnregistrationDone=function(){this.state===o.Unregistering?(this.setState(o.Initial),this.worker.dispatchUnregistered(),this.worker.dispatchDisconnected()):this.showIgnored("onUnregistrationDone");},t.prototype.onResendRegistration=function(){this.worker.dispatchUnregistered(),this.state===o.Connected&&this.registrationState===c.Registered?(this.registrationState=c.Registering,this.worker.stopRegistrationTimer(),this.worker.sendRegisterRequest()):this.state===o.Connected&&this.registrationState===c.Registering&&(this.registrationState=c.RegisteringButResendPending);},t.prototype.onIncallModeTimer=function(){this.worker.exitIncallMode(),this.state===o.Connected?(this.worker.stopPingTimer(),this.worker.startPingTimer()):this.showIgnored("onIncallModeTimer");},t.prototype.onSetNewUserActivityState=function(){this.worker.sendUserActivityState(i.UserActivityEventReason.Modified,this.state===o.Connected);},t.prototype.onActivityStateResponseTimeout=function(){this.onMissedResponse("onActivityStateResponseTimeout");},t.prototype.forceReconnect=function(t){this.state===o.Connected&&this.worker.sendDisconnectTelemetryEvent(t),this.worker.resetTokenBackoff(),this.cleanUpAndInitiateReconnect({backoff:!1,allowCachedToken:!0});},t.prototype.onTerminalError=function(){this.logger.error("Cannot proceed, reached terminal state. Switching from state '".concat(o[this.state],"' to ").concat(o[o.TerminalError])),this.stop(!0,!0),this.setState(o.TerminalError);},t.prototype.onMissedResponse=function(t){this.state===o.Connected?(this.worker.sendDisconnectTelemetryEvent(t),this.cleanUpAndInitiateReconnect({backoff:!1,allowCachedToken:!0})):this.showIgnored(t);},t.prototype.showIgnored=function(t){this.logger.debug("Ignoring event '".concat(t,"' in state '").concat(o[this.state],"'"));},t.prototype.setState=function(t){if(this.logger.info("Switching from state '".concat(o[this.state],"' to state '").concat(o[t],"'")),this.state===t)return void this.logger.error("Attempt to switch to the current state '".concat(o[t],"'"));this.state=t;},t.prototype.switchToIncallModeIfEnabled=function(){this.incallModeEnabled&&(this.worker.isIncallMode()||(this.worker.enterIncallMode(),this.worker.stopPingTimer(),this.worker.startPingTimer()),this.worker.restartIncallModeTimer());},t.prototype.cleanUpAndInitiateReconnect=function(t){if(!this.autoReconnect)return this.logger.info("Automatic reconnect is disabled, stopping this connection"),void this.stop(!0);this.worker.cancelPendingRegistrationRequests(),this.worker.stopConnectionTimer(),this.worker.stopPingTimer(),this.worker.clearSentEventTimers(),this.worker.stopRegistrationTimer(),this.worker.stopSocketIo(),this.setState(o.RetrievingToken),this.worker.dispatchReconnecting(),this.worker.getToken(t.allowCachedToken,t.backoff,t.claimsChallenge,t.fallbackReason);},t}();e.TrouterFsm=a;},function(t,e,n){function o(t,e){var n=e?void 0:{"X-MS-Migration":"True"};switch(t.tokenType.toLowerCase()){case"skype":return c({"X-Skypetoken":t.token},n);case"aad":case"cae":return c({Authorization:"Bearer ".concat(t.token)},n);default:throw new Error("unsupported token type: ".concat(t.tokenType))}}function i(t){return void 0!==t&&null!==t&&"function"==typeof t.toString?t.toString():"[".concat(typeof t,"]")}function r(t){return "object"==typeof t&&null!==t&&void 0!==t.stack?(0, l.toJson)(t.stack):'"(no error.stack)"'}function s(t){return "object"==typeof t&&null!==t&&"string"==typeof t.message?t.message:"(no error.message)"}var c=this&&this.__assign||function(){return c=Object.assign||function(t){for(var e,n=1,o=arguments.length;n<o;n++){e=arguments[n];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);}return t},c.apply(this,arguments)},a=this&&this.__awaiter||function(t,e,n,o){function i(t){return t instanceof n?t:new n(function(e){e(t);})}return new(n||(n=Promise))(function(n,r){function s(t){try{a(o.next(t));}catch(t){r(t);}}function c(t){try{a(o.throw(t));}catch(t){r(t);}}function a(t){t.done?n(t.value):i(t.value).then(s,c);}a((o=o.apply(t,e||[])).next());})},u=this&&this.__generator||function(t,e){function n(t){return function(e){return o([t,e])}}function o(n){if(i)throw new TypeError("Generator is already executing.");for(;c&&(c=0,n[0]&&(a=0)),a;)try{if(i=1,r&&(s=2&n[0]?r.return:n[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,n[1])).done)return s;switch(r=0,s&&(n=[2&n[0],s.value]),n[0]){case 0:case 1:s=n;break;case 4:return a.label++,{value:n[1],done:!1};case 5:a.label++,r=n[1],n=[0];continue;case 7:n=a.ops.pop(),a.trys.pop();continue;default:if(s=a.trys,!(s=s.length>0&&s[s.length-1])&&(6===n[0]||2===n[0])){a=0;continue}if(3===n[0]&&(!s||n[1]>s[0]&&n[1]<s[3])){a.label=n[1];break}if(6===n[0]&&a.label<s[1]){a.label=s[1],s=n;break}if(s&&a.label<s[2]){a.label=s[2],a.ops.push(n);break}s[2]&&a.ops.pop(),a.trys.pop();continue}n=e.call(t,a);}catch(t){n=[6,t],r=0;}finally{i=s=0;}if(5&n[0])throw n[1];return {value:n[0]?n[1]:void 0,done:!0}}var i,r,s,c,a={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return c={next:n(0),throw:n(1),return:n(2)},"function"==typeof Symbol&&(c[Symbol.iterator]=function(){return this}),c};Object.defineProperty(e,"__esModule",{value:!0}),e.TrouterConnection=e.ReconnectReason=void 0;var h,d=n(21),l=n(3),p=n(15),g=n(1),f=n(16),v=n(17),m=n(2),y=n(4),T=n(0),S=n(5),k=n(6),w=n(12),b=function(){function t(){this.cv=g.CLIENT_VERSION,this.ua="",this.hr="",this.v="";}return t}(),R=function(){function t(){this["force new connection"]=!0,this.reconnect=!1,this.query="",this.ackTimeoutMs=5e3;}return t.prototype.rewriteUrlForProxy=function(t){return t},t}(),C="MS-CV",E=function(){function t(t,e){this.logger=e,this.cvCounter=0;var n=JSON.parse(t);this.startTS=this.safeJsonNumber(n,"startTS",0),this.url=this.safeJsonString(n,"url",""),this.shortUrl=this.safeJsonString(n,"shortUrl",""),this.body=this.safeJsonString(n,"body",""),this.headers=this.safeJsonRecord(n,"headers",{}),this.id=this.safeJsonNumber(n,"id",-1),this.method=this.safeJsonString(n,"method",""),this.replied=!1,this.timedout=!1,this.receivedCv=this.headers[C],this.updateCvHeader();}return Object.defineProperty(t.prototype,"correlationVector",{get:function(){return this.receivedCv?"".concat(this.receivedCv,".").concat(this.cvCounter):""},enumerable:!1,configurable:!0}),t.prototype.on=function(t,e){"data"===t?this.dataCallback=e:"end"===t&&("function"==typeof this.dataCallback&&this.dataCallback(this.body),e());},t.prototype.incrementCorrelationVector=function(){++this.cvCounter,this.updateCvHeader();},t.prototype.updateCvHeader=function(){var t=this.correlationVector;t&&(this.headers[C]=t);},t.prototype.safeJsonNumber=function(t,e,n){var o;if(null!==t&&void 0!==t&&Object.prototype.hasOwnProperty.call(t,e)){var i=t;if("number"==typeof i[e])return i[e];if("string"==typeof i[e])return parseFloat(i[e]);null===(o=this.logger)||void 0===o||o.warn("unexpected type of '".concat(e,"': ").concat(typeof i[e]));}return n},t.prototype.safeJsonString=function(t,e,n){var o;if(null!==t&&void 0!==t&&Object.prototype.hasOwnProperty.call(t,e)){var i=t;if("string"==typeof i[e])return i[e];null===(o=this.logger)||void 0===o||o.warn("unexpected type of '".concat(e,"': ").concat(typeof i[e]));}return n},t.prototype.safeJsonRecord=function(t,e,n){var o;if(null!==t&&void 0!==t&&Object.prototype.hasOwnProperty.call(t,e)){var i=t;if("object"==typeof i[e])return i[e];null===(o=this.logger)||void 0===o||o.warn("unexpected type of '".concat(e,"': ").concat(typeof i[e]));}return n},t}(),I=function(){function t(t,e,n){this.request=t,this.responseData=e,this.sendResponse=n;}return t.prototype.writeHead=function(t,e){this.responseData.status=t,this.responseData.headers=e;},t.prototype.write=function(t){this.responseData.body+=t;},t.prototype.end=function(t){return t&&(this.responseData.body+=t),this.sendResponse(this.request,this.responseData)},t}(),A=function(){function t(t){this.name=t,this.args={},this.timeoutTimerId=0;}return t}();!function(t){t[t.Configuration=0]="Configuration",t[t.ServerInitiated=1]="ServerInitiated";}(h||(e.ReconnectReason=h={}));var U=function(){function t(t,e,n,o,i,r,s,c){var a,u=this;this.options=e,this.manager=n,this.tokenProvider=o,this.usingLegacyTokenApi=i,this.protocolSelector=s,this.audienceSubscriptionState=c,this.WEBSOCKET_TRANSPORT_NAME="websocket",this.XHR_POLLING_TRANSPORT_NAME="xhr-polling",this.AUDIENCE_SUBSCRIPTION_RESULT_ERROR="Error",this.AUDIENCE_SUBSCRIPTION_RESULT_UNSUBSCRIBED="Unsubscribed",this.AUDIENCE_SUBSCRIPTION_RESULT_TIMEOUT="Timeout",this.AUDIENCE_SUBSCRIPTION_RESULT_BAD_REQUEST="BadRequest",this.AUDIENCE_SUBSCRIPTION_STATE_QUERY_PARAM_REGEX=/&audienceSubscriptionState=[^&]*|^audienceSubscriptionState=[^&]*&?/,this.connectionId="",this.inIncallMode=!1,this.connectionAttempt=0,this.connectedClientId="",this.isNavigatorOnline=!0,this.onNavigatorOnlineStatusUpdateBound=this.onNavigatorOnlineStatusUpdate.bind(this),this.c2cUrlBase="",this.connectingErrorsInRow=0,this.unauthorizedErrorCount=0,this.pendingSentEventTimers={},this.lastDisconnectReason="",this.UNKNOWN_TRANSPORT="unknown_transport",this.connectingErrorsThreshold=3,this.pendingAudienceSubscription=void 0,this.logger=new T.Logger("Connection",t),this.timeoutOptions=this.options.timeoutOptions,this.tokenBackoff=new v.ExponentialBackoff(this.logger,this.timeoutOptions.maxBackoffMs),this.clientID=Date.now(),"undefined"!=typeof window&&window.location&&(this.domId=window.location.hostname);var h=new b;h.cv=g.CLIENT_VERSION,h.ua="",(null===(a=this.options)||void 0===a?void 0:a.clientInfo)&&(h.ua=this.safeString(this.options.clientInfo.ua),h.v=this.safeString(this.options.clientInfo.v)),this.clientInfo=h,this.connectionTracker=new p.ConnectionTracker(t,this.clientID,this.clientInfo,function(){return u.getServerState()},this.options.endpointId,this.options.clientCorrelationID,this.options.environment),this.applyConnectionTrackerOptions(e);var l=this.options.incallModeTimeoutMs>0;if(this.fsm=new k.TrouterFsm(t,this,l,this.protocolSelector),e.registration){var f={registrarUrl:e.registration.registrarUrl,proxyUrlRewrite:e.rewriteUrlForProxy,registrationId:e.registration.registrationId,requestTimeoutMs:e.timeoutOptions.fetchTimeoutMs,initialRetryDelayMs:1e3,maxRetryDelayMs:e.timeoutOptions.maxBackoffMs,usingLegacyTokenApi:this.usingLegacyTokenApi,maxRetriesForGetToken:e.retryLimitOnTokenFetch,extraRegistrationHeaders:e.extraConnectionHeaders};this.registrarClient=(0, d.createRegistrarClient)(t,this.tokenProvider,f);}this.userActivityState=r;}return t.prototype.start=function(t){this.logger.info("Starting"),this.reconnectParams=t,"undefined"!=typeof window&&window.navigator&&window.addEventListener?(this.isNavigatorOnline=window.navigator.onLine,window.addEventListener("online",this.onNavigatorOnlineStatusUpdateBound),window.addEventListener("offline",this.onNavigatorOnlineStatusUpdateBound),this.logger.debug("Registered for browser online notifications - current state: ".concat(this.isNavigatorOnline))):this.isNavigatorOnline=!0,this.fsm.start();},t.prototype.stop=function(t){this.logger.info("Stopping"),"undefined"!=typeof window&&window.navigator&&(window.removeEventListener("online",this.onNavigatorOnlineStatusUpdateBound),window.removeEventListener("offline",this.onNavigatorOnlineStatusUpdateBound)),this.fsm.stop(t),this.connectionTracker.close();},t.prototype.configure=function(t){var e=this.options.trouterUrl!==t.trouterUrl;this.options=t,this.applyConnectionTrackerOptions(t),e&&(this.logger.info("Configuration changed. Reconnection required."),this.fsm.onReconnectRequired(!1,h.Configuration));},t.prototype.checkConnection=function(t){this.logger.info("checkConnection called with ".concat(t)),this.fsm.checkConnection(t),t&&this.connectionTracker.sendTelemetry(p.ClientEventName.CheckConnection,{disconnectDetected:t},[]);},t.prototype.disableRegistrationsAndAutoReconnect=function(){this.stopRegistrationTimer(),this.cancelPendingRegistrationRequests(),this.fsm.disableAutoReconnect();},t.prototype.getServerState=function(){return new y.ServerState(this.connectionId,this.connectedClientId,this.domId?this.domId:"",this.allocateResult?this.allocateResult.url:"",this.allocateResult?this.allocateResult.surl:"",this.c2cUrlBase,this.connectionExpireTimestampInSecs)},t.prototype.getState=function(){return this.fsm.getState()},t.prototype.getToken=function(t,e,n,o,i){var r=this;void 0===i&&(i=0),this.logger.info("Getting token ".concat(e?"with backoff":"without backoff"));var s=function(){r.connectionTracker.trackStart("token");var e={needFresh:!t,wwwAuthenticateHeader:n,supportedTokenTypes:g.SUPPORTED_TOKEN_TYPES,purpose:"trouter"};r.logger.info("Requesting token: needFresh=".concat(e.needFresh," ")+"types=[".concat(g.SUPPORTED_TOKEN_TYPES,"], ")+"wwwAuthenticateHeader is ".concat(e.wwwAuthenticateHeader?"non empty":"empty")),r.tokenProvider(e).then(function(t){r.logger.debug("".concat(t.tokenType," token is received")),r.connectionTracker.trackEnd("token"),r.fsm.onTokenReceived(t,o,r.reconnectParams);}).catch(function(e){var s=(0, l.toJson)(e.stack);if(r.logger.error("Getting token failed, will retry after timeout. Error: ".concat(s)),r.connectionTracker.trackError("token",s),!r.canRetryTokenFetchRequest(i+r.unauthorizedErrorCount)){return r.connectionTracker.trackError("token","getToken retry limit hit, reached terminal error state"),r.resetTokenBackoff(),void r.fsm.onTerminalError()}r.getToken(t,!0,n,o,i+1);});};e?this.tokenBackoff.backoff("getting token",s):(this.resetTokenBackoff(),s());},t.prototype.startConnectionTimer=function(){var t=this;this.stopConnectionTimer(),this.logger.debug("Starting connection timeout for ".concat(this.timeoutOptions.connectionTimeoutMs," ms")),this.connectionTimeoutId=setTimeout(function(){t.logger.info("Connection timeout is fired"),t.fsm.onConnectingTimeout();},this.timeoutOptions.connectionTimeoutMs);},t.prototype.stopConnectionTimer=function(){this.connectionTimeoutId&&(this.logger.debug("Stopping connection timeout"),clearTimeout(this.connectionTimeoutId),this.connectionTimeoutId=void 0);},t.prototype.startPingTimer=function(){var t=this;"websocket"===this.transportTypeName?(this.logger.debug("Starting ping timeout for ".concat(this.timeoutOptions.pingTimeoutMs," ms")),this.pingTimerId=setInterval(function(){t.logger.info("Ping interval fired"),t.fsm.onPingInterval();},this.timeoutOptions.pingTimeoutMs)):this.logger.debug("Not starting ping for transport ".concat(this.transportTypeName));},t.prototype.stopPingTimer=function(){this.pingTimerId&&(this.logger.debug("Stopping ping timeout"),this.clearPingResponseTimer(),clearInterval(this.pingTimerId),this.pingTimerId=void 0);},t.prototype.shouldSkipRegistration=function(){return void 0===this.options.registration},t.prototype.hasCustomRegistrationTtl=function(){var t,e;return void 0!==(null===(t=this.options.registration)||void 0===t?void 0:t.registrarTtlSec)&&0!==(null===(e=this.options.registration)||void 0===e?void 0:e.registrarTtlSec)},t.prototype.startRegistrationTimer=function(){var t=this;this.stopRegistrationTimer();var e=this.getRegistrationTtl(),n=e[0],o=e[1];if(n<=30||!o)return this.logger.debug("Starting registration expiration timer (TTL ".concat(n," sec)")),void(this.registrationTimerId=setTimeout(function(){t.registrationTimerId=void 0,t.logger.warn("Registration expired but the connection is still alive. Should never happen"),t.dispatchUnregistered();},1e3*n));var i=n-30;this.logger.debug("Starting registration extension timer for ".concat(i," sec")),this.registrationTimerId=setTimeout(function(){t.logger.info("Registration extension timer fired"),t.registrationTimerId=setTimeout(function(){t.registrationTimerId=void 0,t.logger.debug("Registration extension did not happen in time"),t.dispatchUnregistered();},3e4),t.fsm.onRegistrationNearExpiry();},1e3*i);},t.prototype.startRegistrationRetryTimer=function(){var t=this;this.stopRegistrationTimer();this.registrationTimerId=setTimeout(function(){t.registrationTimerId=void 0,t.fsm.onRetryRegistration();},123e3);},t.prototype.stopRegistrationTimer=function(){this.registrationTimerId&&(this.logger.debug("Stopping registration timeout"),clearTimeout(this.registrationTimerId),this.registrationTimerId=void 0);},t.prototype.resendRegistration=function(){if(!this.registrarClient)throw new Error("Trouter Client not configured to handle registrations");return this.fsm.onResendRegistration(),Promise.resolve()},t.prototype.buildSocketIoUrlParams=function(t,e){if(!this.allocateResult)throw new Error("Allocate result is undefined in buildSocketIoUrlParams()");for(var n={},o=this.allocateResult.connectparams,i=0,r=Object.keys(o);i<r.length;i++){var s=r[i];if(void 0!==o[s]){var c=o[s];"string"==typeof c||"number"==typeof c?n[s]=c:this.logger.error("signatureData[".concat(s,"] has unsupported type ").concat(typeof c));}}return n.v="v4",n.tc=encodeURI((0, l.toJson)(this.clientInfo)),n.timeout=this.timeoutOptions.pingTimeoutMs/1e3,n.auth="true",this.options.endpointId&&(n.epid=this.options.endpointId),t&&(n.userActivity=encodeURI((0, l.toJson)(t))),e&&(n.audienceSubscriptionState=encodeURIComponent((0, l.toJson)(e))),this.appendConnectedClientIds(this.buildQuery(n),!0)},t.prototype.startSocketIo=function(t){var e,n;if(this.logger.debug("Starting socket io"),this.connectionTracker.trackStart("connectSocket"),!this.allocateResult)throw new Error("Allocate result is undefined in startSocketIo()");var i=this.options.ioOptions?c({},this.options.ioOptions):new R,r=this.userActivityState.state!==m.UserActivityState.Unknown?this.userActivityState.increaseCvAndGetEventObject():void 0,s=null===(e=this.audienceSubscriptionState)||void 0===e?void 0:e.increaseCvAndGetEventObject();if(i["force new connection"]=!0,i.reconnect=!1,i.rewriteUrlForProxy=this.options.rewriteUrlForProxy,i.requestHeaders=c(c({},this.options.extraConnectionHeaders),o(t,this.usingLegacyTokenApi)),i.query=this.buildSocketIoUrlParams(r,s),this.logger.info("connecting to ".concat(this.allocateResult.socketio,"?").concat(i.query)),this.stopSocketIo(),this.socket=(null!==(n=this.options.io)&&void 0!==n?n:w).connect(this.allocateResult.socketio,i),void 0===this.socket)throw new Error("Can't create Socket.io object");this.attachSocketIoHandlers(this.socket,t,r,s);},t.prototype.stopSocketIo=function(){if(this.socket){this.logger.debug("clearing socket.io");try{for(var t=0,e=["connecting","connect","connect_failed","close_during_connecting","disconnect","reconnect","reconnect_failed","reconnecting","error","message","trouter.connected","trouter.reconnect","trouter.message_loss"];t<e.length;t++){var n=e[t];this.socket.removeAllListeners(n);}this.socket.disconnect(),this.logger.debug("cleared socket"),this.socket=void 0;}catch(t){this.logger.error("exception in disconnecting previous socket. Error: ".concat(r(t)));}}},t.prototype.dispatchConnected=function(){this.logger.info("dispatching connected"),this.manager.onConnected(this);},t.prototype.dispatchRegistered=function(){this.logger.info("dispatching registered"),this.manager.onRegistered(this);},t.prototype.dispatchUnregistered=function(){this.logger.info("dispatching unregistered"),this.manager.onUnregistered(this);},t.prototype.dispatchDownstreamRequest=function(t){var e=this;this.logger.debug("dispatching downstream request");try{var n=new I(t,new p.ResponseData(t.id),function(t,n){return e.logger.debug("sending response to downstream"),e.sendResponse(t,n)});this.manager.onDownstreamRequest(this,t,n);}catch(t){this.logger.error("exception in socket.on message. Error : ".concat(r(t)));}},t.prototype.dispatchReconnecting=function(){this.logger.info("dispatching reconnecting"),thi