PageSourceSearch

https://websiteoss.ecoflow.com/_next/static/chunks/47ccb81c.a1bf200d781e8a1a.js

js ecoflow.com collected 2026-09-24 08:31:53 UTC 171,486 bytes, 1 lines download raw bytes

1"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[69268],{230181:function(t,e,n){var o=n(348764).Buffer;function i(t){return t&&"object"==typeof t&&"default"in t?t.default:t}var r=i(n(709133)),s=i(n(65498)),c=i(n(617667)),a=i(n(120365)),u="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==n.g?n.g:"undefined"!=typeof self?self:{};function h(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function d(t,e){return t(e={exports:{}},e.exports),e.exports}var l=d(function(t,e){t.exports=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=1)}([function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.Timespan=e.toJson=e.fetchWithTimeout=void 0,e.fetchWithTimeout=function(t,e){var n,o=new Promise(function(e,o){fetch(t).then(function(t){void 0!==n&&clearTimeout(n),e(t)}).catch(function(t){void 0!==n&&clearTimeout(n),o(t)})});return 0!==e?Promise.race([o,new Promise(function(o,i){n=setTimeout(i,e,Error("Fetch for '".concat(t.url,"' timed out")))})]):o},e.toJson=function(t){try{return JSON.stringify(t)}catch(e){return"Unable to serialize object of type ".concat(typeof t)}};var o=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=o},function(t,e,n){var o,i=this&&this.__extends||(o=function(t,e){return(o=Object.setPrototypeOf||({__proto__:[]})instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])})(t,e)},function(t,e){function n(){this.constructor=t}if("function"!=typeof e&&null!==e)throw TypeError("Class extends value "+String(e)+" is not a constructor or null");o(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}),r=this&&this.__assign||function(){return(r=Object.assign||function(t){for(var e,n=1,o=arguments.length;n<o;n++)for(var i in e=arguments[n])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t}).apply(this,arguments)},s=this&&this.__awaiter||function(t,e,n,o){return new(n||(n=Promise))(function(i,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){var e;t.done?i(t.value):((e=t.value)instanceof n?e:new n(function(t){t(e)})).then(s,c)}a((o=o.apply(t,e||[])).next())})},c=this&&this.__generator||function(t,e){function n(n){return function(a){return function(n){if(o)throw TypeError("Generator is already executing.");for(;s&&(s=0,n[0]&&(c=0)),c;)try{if(o=1,i&&(r=2&n[0]?i.return:n[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,n[1])).done)return r;switch(i=0,r&&(n=[2&n[0],r.value]),n[0]){case 0:case 1:r=n;break;case 4:return c.label++,{value:n[1],done:!1};case 5:c.label++,i=n[1],n=[0];continue;case 7:n=c.ops.pop(),c.trys.pop();continue;default:if(!(r=(r=c.trys).length>0&&r[r.length-1])&&(6===n[0]||2===n[0])){c=0;continue}if(3===n[0]&&(!r||n[1]>r[0]&&n[1]<r[3])){c.label=n[1];break}if(6===n[0]&&c.label<r[1]){c.label=r[1],r=n;break}if(r&&c.label<r[2]){c.label=r[2],c.ops.push(n);break}r[2]&&c.ops.pop(),c.trys.pop();continue}n=e.call(t,c)}catch(t){n=[6,t],i=0}finally{o=r=0}if(5&n[0])throw n[1];return{value:n[0]?n[1]:void 0,done:!0}}([n,a])}}var o,i,r,s,c={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:n(0),throw:n(1),return:n(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s};
1Object.defineProperty(e,"__esModule",{value:!0}),e.createRegistrarClient=e.RegistrarClient=void 0;var a=n(0),u=["skype","aad","cae"],h=function(t){function e(e){var n=t.call(this,e)||this;return n.name="CancelationError",n}return i(e,t),e}(Error),d=function(){function t(e,n,o){this.logger=e,this.maxBackoffInMs=n,this.initialDelay=o,this.backoffCount=0,this.id=++t.idCounter}return t.prototype.delay=function(t){var e=this;if(void 0!==this.timerHandle)throw Error("Retry sequence logical failure");if(-1===this.backoffCount)return new Promise(function(t,e){e(new h("Cancelled"))});var n=this.calculateNextBackoffMs();return this.backoffCount++,this.logger.info("[RegistrarClient] Backing off ".concat(t," for ").concat(n," milliseconds with ID ").concat(this.id)),new Promise(function(o,i){e.cancelFunc=i,e.timerHandle=setTimeout(function(){e.logger.info("[RegistrarClient] Back off for ".concat(t," with ID ").concat(e.id," complete")),e.timerHandle=void 0,o()},n)})},t.prototype.cancel=function(){void 0!==this.timerHandle&&(this.logger.debug("Resetting back off"),clearTimeout(this.timerHandle),void 0!==this.cancelFunc&&this.cancelFunc(new h("Cancelled"))),this.backoffCount=-1},t.prototype.calculateNextBackoffMs=function(){var t=this.initialDelay*Math.pow(2,this.backoffCount)*(1+.4*(Math.random()-.5));return t=Math.round(t),Math.min(this.maxBackoffInMs,t)},t.idCounter=0,t}(),l=function(){function t(t,e,n){var o;this.logger=t,this.tokenProvider=e,this.options=n,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===n.maxRetriesForGetToken||null===n.maxRetriesForGetToken?this.DEFAULT_MAX_RETRIES_FOR_GET_TOKEN:n.maxRetriesForGetToken,this.proxyUrlRewrite=null!==(o=n.proxyUrlRewrite)&&void 0!==o?o: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 c(this,function(n){switch(n.label){case 0:return[4,this.performRegistration(t,e,"pr_set_registration")];case 1:return n.sent(),this.cachedRegistrationParams=[t,e],[2]}})})},t.prototype.unregister=function(){return s(this,void 0,void 0,function(){var t;return c(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(r(r({},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 c(this,function(t){switch(t.label){case 0:if(!this.cachedRegistrationParams)throw 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,n){return s(this,void 0,void 0,function(){var o,i;return c(this,function(s){switch(s.label){case 0:return this.logger.info("[RegistrarClient] Sending register request"),o={clientDescription:t,registrationId:this.options.registrationId,nodeId:"",transports:e},i=new Request(this.proxyUrlRewrite(this.options.registrarUrl),{method:"POST",mode:"cors",headers:new Headers(r(r({},this.options.extraRegistrationHeaders),{"content-type":"application/json",accept:"application/json, text/javascript"})),body:(0,a.toJson)(o)}),[4,this.callRegistrar(i,n)];case 1:return s.sent(),[2]}})})},t.prototype.startBackoff=function(){var t=new d(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,n,o,i,r,s,a;return c(this,function(c){switch(c.label){case 0:e=this.startBackoff(),n=0,c.label=1;case 1:return c.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"})];
1case 2:return o=c.sent(),this.stopBackoff(e),[2,o];case 3:i=c.sent(),c.label=4;case 4:return c.trys.push([4,6,,7]),(n++,r=JSON.stringify(i),n>this.maxRetriesForGetToken)?(s="[RegistrarClient] getToken retry limit hit. Will not retry now. Error: ".concat(r),this.logger.error(s),this.stopBackoff(e),[2,Promise.reject(s)]):(this.logger.warn("[RegistrarClient] Retrying for a new token. Retry Count: ".concat(n," Error: ").concat(r)),[4,e.delay("Fetching a new token")]);case 5:return c.sent(),[3,8];case 6:throw a=c.sent(),this.stopBackoff(e),a;case 7:return[3,8];case 8:return[3,1];case 9:return[2]}})})},t.prototype.callRegistrar=function(t,e){var n,o,i;return s(this,void 0,void 0,function(){var r,s,h,d,l,p,g,f,v,m,y,T,S,k,w,b;return c(this,function(c){switch(c.label){case 0:return r=this.startBackoff(),[4,this.tokenProvider({needFresh:!1,supportedTokenTypes:u,wwwAuthenticateHeader:void 0,purpose:"registrar"})];case 1:s=c.sent(),this.setTokenHeader(t,s),h=new a.Timespan,d=0,c.label=2;case 2:l=void 0,c.label=3;case 3:return c.trys.push([3,10,15,16]),p=t.clone(),[4,(0,a.fetchWithTimeout)(p,this.options.requestTimeoutMs)];case 4:return 401!==(l=c.sent()).status?[3,8]:++d>this.maxRetriesForGetToken?(g="[RegistrarClient] getSkypeToken retry limit hit. Will not retry now. Request '".concat(t.url,"' failed with ").concat(l.status," ").concat(l.statusText),this.logger.error(g),this.stopBackoff(r),[2,Promise.reject(g)]):(this.logger.warn("[RegistrarClient] Retry Count ".concat(d,". Request '").concat(t.url,"' failed with ").concat(l.status," ").concat(l.statusText)),f=null!==(o=null===(n=l.headers)||void 0===n?void 0:n.get("www-authenticate"))&&void 0!==o?o:void 0,v=this.setTokenHeader,m=[t],[4,this.getToken(f)]);case 5:return v.apply(this,m.concat([c.sent()])),d>1?[4,r.delay("Registrar call retry after 401")]:[3,7];case 6:c.sent(),c.label=7;case 7:return[3,22];case 8:if(l.status>=500&&l.status<600)throw Error("Fetch for '".concat(t.url,"' failed with ").concat(l.status," ").concat(l.statusText));c.label=9;case 9:return[3,16];case 10:y=c.sent(),this.logger.error("[RegistrarClient] Request failed with ".concat(y)),c.label=11;case 11:return c.trys.push([11,13,,14]),[4,r.delay("Registrar call retry")];case 12:return c.sent(),[3,22];case 13:throw T=c.sent(),this.logger.error("[RegistrarClient] Request cancelled"),this.stopBackoff(r),T;case 14:return[3,16];case 15:return this.sendTelemetryEvent(e,t,l,h),[7];case 16:return this.stopBackoff(r),l.ok?[2,l]:[3,17];case 17:S=void 0,c.label=18;case 18:return c.trys.push([18,20,,21]),w=(k=JSON).stringify,[4,l.json()];case 19:return S=w.apply(k,[c.sent()]),[3,21];case 20:return c.sent(),S="no details",[3,21];case 21:throw b="Fetch for '".concat(t.url,"' failed with ").concat(l.status," ").concat(l.statusText," (").concat(S,", MS-CV: ").concat(null===(i=l.headers)||void 0===i?void 0:i.get("MS-CV"),")"),this.logger.error("[RegistrarClient] ".concat(b)),Error(b);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 Error("unsupported token type: ".concat(e.tokenType))}!1===this.options.usingLegacyTokenApi&&t.headers.set("X-MS-Migration","True")},t.prototype.sendTelemetryEvent=function(t,e,n,o){if(void 0!==this.eventLogger){var i={name:t,properties:{url:{value:e.url},result_code:{value:void 0!==n?n.status:0},begin_timestamp:{value:o.startTime},elapsed:{value:o.duration}}};this.eventLogger.logEvent(i)}},t}();e.RegistrarClient=l,e.createRegistrarClient=function(t,e,n){return new l(t,e,n)}}])});h(l);var p=d(function(t,e){t.exports=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)}
1([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){var o,i,r,s;Object.defineProperty(e,"__esModule",{value:!0}),e.TrouterState=e.UserActivityState=void 0,(r=o||(e.UserActivityState=o={}))[r.Unknown=0]="Unknown",r[r.Active=1]="Active",r[r.Inactive=2]="Inactive",(s=i||(e.TrouterState=i={}))[s.Unknown=0]="Unknown",s[s.Connected=2]="Connected",s[s.Disconnected=3]="Disconnected",s[s.Switching=9]="Switching"},function(t,e,n){var o=this&&this.__awaiter||function(t,e,n,o){return new(n||(n=Promise))(function(i,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){var e;t.done?i(t.value):((e=t.value)instanceof n?e:new n(function(t){t(e)})).then(s,c)}a((o=o.apply(t,e||[])).next())})},i=this&&this.__generator||function(t,e){function n(n){return function(a){return function(n){if(o)throw TypeError("Generator is already executing.");for(;s&&(s=0,n[0]&&(c=0)),c;)try{if(o=1,i&&(r=2&n[0]?i.return:n[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,n[1])).done)return r;switch(i=0,r&&(n=[2&n[0],r.value]),n[0]){case 0:case 1:r=n;break;case 4:return c.label++,{value:n[1],done:!1};case 5:c.label++,i=n[1],n=[0];continue;case 7:n=c.ops.pop(),c.trys.pop();continue;default:if(!(r=(r=c.trys).length>0&&r[r.length-1])&&(6===n[0]||2===n[0])){c=0;continue}if(3===n[0]&&(!r||n[1]>r[0]&&n[1]<r[3])){c.label=n[1];break}if(6===n[0]&&c.label<r[1]){c.label=r[1],r=n;break}if(r&&c.label<r[2]){c.label=r[2],c.ops.push(n);break}r[2]&&c.ops.pop(),c.trys.pop();continue}n=e.call(t,c)}catch(t){n=[6,t],i=0}finally{o=r=0}if(5&n[0])throw n[1];return{value:n[0]?n[1]:void 0,done:!0}}([n,a])}}var o,i,r,s,c={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:n(0),throw:n(1),return:n(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s};Object.defineProperty(e,"__esModule",{value:!0}),e.Timespan=e.CorrelationVector=e.fetchWithTimeout=e.calculateExpireTsInSec=e.calculateTtlInSec=e.toJson=void 0,e.toJson=function(t){try{return JSON.stringify(t)}catch(e){return"Unable to serialize object of type ".concat(typeof t)}},e.calculateTtlInSec=function(t){var e=Math.round((new Date).getTime()/1e3);return void 0!==t&&t>e?t-e:0},e.calculateExpireTsInSec=function(t){return Math.round((new Date).getTime()/1e3)+t},e.fetchWithTimeout=function(t,e){return o(this,void 0,void 0,function(){var n,o;return i(this,function(i){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?[2,Promise.race([o,new Promise(function(o,i){var r=new URL(t.url);n=setTimeout(i,e,Error("".concat(t.method," ").concat(r.origin).concat(r.pathname," timed out")))})])]:[2,o]})})};var r=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=r;var s=function(){function t(){this.start=Date.now()}return Object.defineProperty(t.prototype,"duration",{get:function(){return Date.now()-this.start}
1,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=s},function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.TrouterManagerState=e.UserActivityEventReason=e.ServerState=void 0;var o,i,r,s,c=n(3),a=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,c.calculateTtlInSec)(this.expirationTsSec)},t}();e.ServerState=a,(o=r||(e.UserActivityEventReason=r={}))[o.Unknown=0]="Unknown",o[o.Modified=1]="Modified",o[o.Snapshot=2]="Snapshot",o[o.Connected=3]="Connected",(i=s||(e.TrouterManagerState=s={}))[i.Unknown=0]="Unknown",i[i.Connected=2]="Connected",i[i.Disconnected=3]="Disconnected",i[i.Switching=9]="Switching",i[i.TerminalError=10]="TerminalError"},function(t,e,n){var o=this&&this.__assign||function(){return(o=Object.assign||function(t){for(var e,n=1,o=arguments.length;n<o;n++)for(var i in e=arguments[n])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t}).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=function(t,e){var n;return"skype"===t&&"1"!==("string"==typeof(n=null==e?void 0:e.scae)?n:"number"==typeof n?n.toString():void 0)?"v4a":"v4c"},e.usedProtocolAfterFallback=function(t,e){return"v4c-websocket-failure"===(null==e?void 0:e.kind)?"v4a":t},e.isV4ConnectEvent=function(t){return Object.prototype.hasOwnProperty.call(t,"connectparams")},e.adaptUrl=function(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://")},e.reconnectParamsWithoutUrls=function(t){if(void 0!==t)return o(o({},t),{reconnectUrl:void 0,serviceUrl:void 0})},e.ensureNumber=function(t){return"string"==typeof t?parseInt(t,10):t},e.redirectUrlIfPresent=function(t){if("redirect"===(null==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}}},function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.TrouterFsm=e.State=void 0;var o,i,r,s,c=n(4),a=n(0),u=n(5);(o=s||(e.State=s={}))[o.Initial=0]="Initial",o[o.RetrievingToken=1]="RetrievingToken",o[o.Allocating=2]="Allocating",o[o.Handshaking=3]="Handshaking",o[o.Connecting=4]="Connecting",o[o.AnonymousConnecting=5]="AnonymousConnecting",o[o.WebsocketAuthenticating=6]="WebsocketAuthenticating",o[o.Connected=7]="Connected",o[o.Unregistering=8]="Unregistering",o[o.TerminalError=9]="TerminalError",(i=r||(r={}))[i.Initial=0]="Initial",i[i.Registering=1]="Registering",i[i.RegisteringButResendPending=2]="RegisteringButResendPending",i[i.Retrying=3]="Retrying",i[i.Registered=4]="Registered",i[i.RegistrationDisabled=5]="RegistrationDisabled";var h=function(){function t(t,e,n,o){this.worker=e,this.incallModeEnabled=n,this.protocolSelector=o,this.state=s.Initial,this.autoReconnect=!0,this.logger=new a.Logger("ConnectionFsm",t),this.registrationState=r.Initial}return t.prototype.getState=function(){return this.state},t.prototype.isActive=function(){return this.state===s.Allocating||this.state===s.Connected||this.state===s.Handshaking||this.state===s.Connecting||this.state===s.RetrievingToken||this.state===s.AnonymousConnecting||this.state===s.WebsocketAuthenticating},t.prototype.isConnecting=function(){return this.state===s.Allocating||this.state===s.Handshaking||this.state===s.Connecting||this.state===s.AnonymousConnecting},t.prototype.start=function(){return this.state===s.Initial?(this.setState(s.RetrievingToken),this.worker.getToken(!0,!1,void 0),!0):(this.showIgnored("start"),!1)},t.prototype.stop=function(t,e){t&&(this.registrationState=r.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===s.Connected&&this.worker.sendDisconnectTelemetryEvent("connection stopped"),this.registrationState!==r.Registered&&this.registrationState!==r.Registering&&this.registrationState!==r.RegisteringButResendPending||this.state===s.Unregistering?e?(this.setState(s.TerminalError),this.worker.dispatchTerminalError()):(this.setState(s.Initial),this.worker.dispatchDisconnected()):(this.registrationState=r.Initial,this.setState(s.Unregistering),this.worker.sendUnregisterRequest
1())},t.prototype.onTokenReceived=function(t,e,n){this.state===s.RetrievingToken?"v4c"===(0,u.usedProtocolAfterFallback)(this.protocolSelector(t.tokenType,n),e)?(this.setState(s.AnonymousConnecting),this.worker.startConnectionTimer(),this.worker.connectV4c(t,e)):(this.setState(s.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===s.Allocating&&this.registrationState===r.Registered&&this.worker.dispatchUnregistered(),this.state===s.Allocating?(this.setState(s.Handshaking),this.registrationState=r.Initial,this.worker.startSocketIo(t),!0):(this.showIgnored("onAllocationSucceed"),!1)},t.prototype.onAllocationFailed=function(t,e){this.state===s.Allocating?this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!t,claimsChallenge:e}):this.showIgnored("onAllocationFailed")},t.prototype.onV4cException=function(){this.state!==s.AnonymousConnecting&&this.state!==s.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===s.Allocating||this.state===s.Connecting||this.state===s.Handshaking||this.state===s.AnonymousConnecting||this.state===s.WebsocketAuthenticating?this.cleanUpAndInitiateReconnect({backoff:!1,allowCachedToken:!0}):this.showIgnored("onConnectingTimeout")},t.prototype.onConnecting=function(){this.state===s.Handshaking?this.setState(s.Connecting):this.showIgnored("onConnecting")},t.prototype.onSocketConnect=function(t){this.state===s.AnonymousConnecting?(this.setState(s.WebsocketAuthenticating),this.worker.sendV4cAuthenticationEvent(t)):this.showIgnored("onSocketConnect")},t.prototype.onConnectingFailed=function(){this.state===s.Connecting?this.onConnectingTimeout():this.state===s.Handshaking?(this.logger.error("Unexpected error in Socket.io - no valid transports"),this.onConnectingTimeout()):this.state===s.AnonymousConnecting||this.state===s.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===s.Handshaking||this.state===s.Connected||this.state===s.WebsocketAuthenticating?(this.state===s.Connected&&this.worker.sendDisconnectTelemetryEvent(null==t?void 0:t.toTelemetryString()),this.state===s.WebsocketAuthenticating&&this.worker.countDisconnectBeforeConnectionEstablishment(),"skypetoken-deprecated"===(null==t?void 0:t.reason)?(this.logger.error("Skypetoken deprecated response, not retrying any further"),this.onTerminalError()):this.cleanUpAndInitiateReconnect({backoff:this.state!==s.Connected&&"dup"!==(null==t?void 0:t.reason),allowCachedToken:"unauthorized"!==(null==t?void 0:t.reason),claimsChallenge:null==t?void 0:t.claims})):this.showIgnored("onSocketDisconnect")},t.prototype.onTrouterConnected=function(){this.state===s.Connecting||this.state===s.WebsocketAuthenticating?(this.setState(s.Connected),this.worker.resetTokenBackoff(),this.worker.stopConnectionTimer(),this.worker.sendUserActivityState(c.UserActivityEventReason.Connected,!0),this.worker.startPingTimer(),this.worker.dispatchConnected(),this.worker.shouldSkipRegistration()?(this.registrationState=r.RegistrationDisabled,this.worker.dispatchRegistered()):(this.registrationState=r.Registering,this.worker.sendRegisterRequest())):this.showIgnored("onTrouterConnected")},t.prototype.onReconnectRequired=function(t,e,n){this.state===s.AnonymousConnecting||this.state===s.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.target," ").concat(null==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===s.Connected?(this.switchToIncallModeIfEnabled(),this.worker.dispatchDownstreamRequest
1(t)):this.showIgnored("onDownstreamRequest")},t.prototype.onTrouterMessageLost=function(t){this.state===s.Connected?this.worker.dispatchTrouterMessageLost(t):this.showIgnored("onTrouterMessageLost")},t.prototype.onPingInterval=function(){this.state===s.Connected?this.worker.sendPingRequest():this.showIgnored("onPingInterval")},t.prototype.onPingResponseTimeout=function(){this.onMissedResponse("onPingResponseTimeout")},t.prototype.onPingResponse=function(){this.state===s.Connected||this.showIgnored("onPingResponse")},t.prototype.onRegistrationFailed=function(){this.state===s.Connected&&this.registrationState===r.Registering?(this.worker.dispatchUnregistered(),this.registrationState=r.Retrying,this.worker.startRegistrationRetryTimer()):this.state===s.Connected&&this.registrationState===r.RegisteringButResendPending?(this.registrationState=r.Registering,this.worker.sendRegisterRequest()):this.showIgnored("onRegistrationFailed")},t.prototype.onRetryRegistration=function(){this.state===s.Connected&&this.registrationState===r.Retrying?(this.registrationState=r.Registering,this.worker.sendRegisterRequest()):this.showIgnored("onRetryRegistration")},t.prototype.onRegistrationSucceeded=function(){this.state===s.Connected&&this.registrationState===r.Registering?(this.registrationState=r.Registered,this.worker.dispatchRegistered(),this.worker.startRegistrationTimer()):this.state===s.Connected&&this.registrationState===r.RegisteringButResendPending?(this.registrationState=r.Registering,this.worker.sendRegisterRequest()):this.showIgnored("onRegistrationSucceeded")},t.prototype.onRegistrationNearExpiry=function(){this.state===s.Connected&&this.registrationState===r.Registered?(this.registrationState=r.Registering,this.worker.sendRegisterRequest()):this.showIgnored("onRegistrationNearExpiry")},t.prototype.onUnregistrationDone=function(){this.state===s.Unregistering?(this.setState(s.Initial),this.worker.dispatchUnregistered(),this.worker.dispatchDisconnected()):this.showIgnored("onUnregistrationDone")},t.prototype.onResendRegistration=function(){this.worker.dispatchUnregistered(),this.state===s.Connected&&this.registrationState===r.Registered?(this.registrationState=r.Registering,this.worker.stopRegistrationTimer(),this.worker.sendRegisterRequest()):this.state===s.Connected&&this.registrationState===r.Registering&&(this.registrationState=r.RegisteringButResendPending)},t.prototype.onIncallModeTimer=function(){this.worker.exitIncallMode(),this.state===s.Connected?(this.worker.stopPingTimer(),this.worker.startPingTimer()):this.showIgnored("onIncallModeTimer")},t.prototype.onSetNewUserActivityState=function(){this.worker.sendUserActivityState(c.UserActivityEventReason.Modified,this.state===s.Connected)},t.prototype.onActivityStateResponseTimeout=function(){this.onMissedResponse("onActivityStateResponseTimeout")},t.prototype.forceReconnect=function(t){this.state===s.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(s[this.state],"' to ").concat(s[s.TerminalError])),this.stop(!0,!0),this.setState(s.TerminalError)},t.prototype.onMissedResponse=function(t){this.state===s.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(s[this.state],"'"))},t.prototype.setState=function(t){if(this.logger.info("Switching from state '".concat(s[this.state],"' to state '").concat(s[t],"'")),this.state===t)return void this.logger.error("Attempt to switch to the current state '".concat(s[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(s.RetrievingToken),this.worker.dispatchReconnecting(),this.worker.getToken(t.allowCachedToken,t.backoff,t.claimsChallenge,t.fallbackReason)},t}();e.TrouterFsm=h},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 Error("unsupported token type: ".concat(t.tokenType))}}function i(t){return"object"==typeof t&&null!==t&&void 0!==t.stack?(0,l.toJson)(t.stack):'"(no error.stack)"'}function r(t){return"object"==typeof t&&null!==t&&"string"==typeof t.message?t.message:"(no error.message)"}var s,c=this&&this.__assign||function(){return(c=Object.assign||function(t){for(var e,n=1,o=arguments.length;n<o;n++)for(var i in e=arguments[n])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t}).apply(this,arguments)},a=this&&this.__awaiter||function(t,e,n,o){return new(n||(n=Prom
1ise))(function(i,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){var e;t.done?i(t.value):((e=t.value)instanceof n?e:new n(function(t){t(e)})).then(s,c)}a((o=o.apply(t,e||[])).next())})},u=this&&this.__generator||function(t,e){function n(n){return function(a){return function(n){if(o)throw TypeError("Generator is already executing.");for(;s&&(s=0,n[0]&&(c=0)),c;)try{if(o=1,i&&(r=2&n[0]?i.return:n[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,n[1])).done)return r;switch(i=0,r&&(n=[2&n[0],r.value]),n[0]){case 0:case 1:r=n;break;case 4:return c.label++,{value:n[1],done:!1};case 5:c.label++,i=n[1],n=[0];continue;case 7:n=c.ops.pop(),c.trys.pop();continue;default:if(!(r=(r=c.trys).length>0&&r[r.length-1])&&(6===n[0]||2===n[0])){c=0;continue}if(3===n[0]&&(!r||n[1]>r[0]&&n[1]<r[3])){c.label=n[1];break}if(6===n[0]&&c.label<r[1]){c.label=r[1],r=n;break}if(r&&c.label<r[2]){c.label=r[2],c.ops.push(n);break}r[2]&&c.ops.pop(),c.trys.pop();continue}n=e.call(t,c)}catch(t){n=[6,t],i=0}finally{o=r=0}if(5&n[0])throw n[1];return{value:n[0]?n[1]:void 0,done:!0}}([n,a])}}var o,i,r,s,c={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:n(0),throw:n(1),return:n(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s};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(){this.cv=g.CLIENT_VERSION,this.ua="",this.hr="",this.v=""},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&&Object.prototype.hasOwnProperty.call(t,e)){if("number"==typeof t[e])return t[e];if("string"==typeof t[e])return parseFloat(t[e]);null===(o=this.logger)||void 0===o||o.warn("unexpected type of '".concat(e,"': ").concat(typeof t[e]))}return n},t.prototype.safeJsonString=function(t,e,n){var o;if(null!=t&&Object.prototype.hasOwnProperty.call(t,e)){if("string"==typeof t[e])return t[e];null===(o=this.logger)||void 0===o||o.warn("unexpected type of '".concat(e,"': ").concat(typeof t[e]))}return n},t.prototype.safeJsonRecord=function(t,e,n){var o;if(null!=t&&Object.prototype.hasOwnProperty.call(t,e)){if("object"==typeof t[e])return t[e];null===(o=this.logger)||void 0===o||o.warn("unexpected type of '".concat(e,"': ").concat(typeof t[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(t){this.name=t,this.args={},this.timeoutTimerId=0};(s=h||(e.ReconnectReason=h={}))[s.Configuration=0]="Configuration",s[s.ServerInitiated=1]="ServerInitiated";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.C
1onnectionTracker(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}
1,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 Error("Trouter Client not configured to handle registrations");return this.fsm.onResendRegistration(),Promise.resolve()},t.prototype.buildSocketIoUrlParams=function(t,e){if(!this.allocateResult)throw 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){if(this.logger.debug("Starting socket io"),this.connectionTracker.trackStart("connectSocket"),!this.allocateResult)throw Error("Allocate result is undefined in startSocketIo()");var e,n,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 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(i(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)});
1this.manager.onDownstreamRequest(this,t,n)}catch(t){this.logger.error("exception in socket.on message. Error : ".concat(i(t)))}},t.prototype.dispatchReconnecting=function(){this.logger.info("dispatching reconnecting"),this.manager.onReconnecting(this)},t.prototype.dispatchReconnectIsRequired=function(t,e){this.logger.info("dispatching reconnect is required by server"),this.manager.onReconnectIsRequired(this,t,e)},t.prototype.dispatchDisconnected=function(){this.logger.info("dispatching disconnected"),this.manager.onDisconnected(this)},t.prototype.dispatchTerminalError=function(){this.logger.info("dispatching terminal error"),this.manager.onTerminalError(this)},t.prototype.dispatchTrouterMessageLost=function(t){this.logger.info("dispatching trouter message lost"),this.manager.onTrouterMessageLost(t)},t.prototype.countDisconnectBeforeConnectionEstablishment=function(){this.logger.warn("counting disconnect before connection was fully established as a connection failure"),++this.connectingErrorsInRow>=this.connectingErrorsThreshold&&this.resetReconnectParamsOnErrorThreshold()},t.prototype.sendProcessedDroppedIndicators=function(t){var e=this;try{this.logger.debug("emitting processed flow tags to the server");var n=new A("trouter.processed_message_loss");n.args={droppedIndicators:t},this.sendDownstreamEvent(n,function(){e.logger.info("emitted processed flow tags to the server")})}catch(t){var o=i(t);this.logger.error("unable to send processed message loss event. Error: ".concat(o)),this.connectionTracker.trackError("trouter.processed_message_loss",o,!1)}},t.prototype.sendAllocateRequest=function(t){var e=this;this.connectionAttempt++,this.connectionTracker.trackNewConnection();var n,i=this.options.trouterUrl,r=this.reconnectParams,s="string"==typeof(null==r?void 0:r.se)?parseInt(r.se,10):"number"==typeof(null==r?void 0:r.se)?r.se:void 0;s&&s<=Date.now()+36e5&&(this.logger.warn("Dropping expired cached connection parameters: ".concat(new Date(s))),this.reconnectParams=r=void 0),r&&r.serviceUrl!==i&&(this.logger.warn("Dropping cached connection parameters for a different environment (".concat(r.serviceUrl,", now ").concat(i,")")),this.reconnectParams=r=void 0),(null==r?void 0:r.reconnectUrl)&&(i=r.reconnectUrl),n=r?c(c({},r),{serviceUrl:void 0,reconnectUrl:void 0}):null,i=(0,S.adaptUrl)(i,"v4a"),i=this.appendCorrelationIds(i,!1),i=this.appendEndpointId(i,!1),n&&(i+="&".concat(this.buildQuery(n)),n.v||(i+="&v=".concat("v4"))),i=this.options.rewriteUrlForProxy(i);var a=new Request(i,{method:"POST",mode:"cors",headers:new Headers(c(c({"Content-Type":"text/plain"},this.options.extraConnectionHeaders),o(t,this.usingLegacyTokenApi)))});this.logger.info("sendAllocateRequest: POST ".concat(i)),this.connectionTracker.trackStart("allocation");var u,h=Date.now(),d=-1,p=!1;(0,l.fetchWithTimeout)(a,this.timeoutOptions.fetchTimeoutMs).then(function(t){if(d=t.status,!t.ok)throw u=null!==(n=t.headers.get("www-authenticate"))&&void 0!==n?n:void 0,p="1"===t.headers.get("x-trouter-skypetoken-deprecated"),e.logger.warn("Allocation request got response status ".concat(t.status,", www-authenticate header was ").concat(u?"not empty":"empty")),Error(t.statusText);var n,o=t.headers.get("content-type");if(!o||"application/json"!==o&&!o.startsWith("application/json;"))throw Error("Content-type '".concat(o,"' is unexpected"));return e.connectionTracker.trackEnd("allocation"),t.json()}).then(function(n){e.unauthorizedErrorCount=0,e.onAllocationResponse(n,t)}).catch(function(t){e.connectingErrorsInRow++;var n="".concat(t).concat(d>=0?", status code ".concat(d):"");if(e.logger.error("".concat(e.connectingErrorsInRow," failed connecting attempt(s) in a row. ").concat(n)),e.connectionTracker.trackError("allocation",n),p){var o="Skypetoken deprecated response, not retrying any further";return e.logger.error(o),e.connectionTracker.trackError("allocation",o),void e.fsm.onTerminalError()}if(401===d&&e.unauthorizedErrorCount++,!e.canRetryTokenFetchRequest(e.unauthorizedErrorCount)){var o="getToken retry limit hit, reached terminal error state";return e.connectionTracker.trackError("allocation",o),void e.fsm.onTerminalError()}
1if(-1!==d||e.isNavigatorOnline){if(e.reconnectParams&&e.connectingErrorsInRow>=e.connectingErrorsThreshold){if(d>=400&&d<=599)e.resetReconnectParamsOnErrorThreshold();else if(e.reconnectParams.reconnectUrl&&e.connectingErrorsInRow%3==0){e.logger.warn("".concat(e.connectingErrorsInRow," connection attempts, testing nominal service URL"));var i=Math.min(e.timeoutOptions.connectionTimeoutMs-(Date.now()-h)-500,e.timeoutOptions.fetchTimeoutMs);return void e.testNominalUrlConnectivity(i).then(function(t){e.connectionTracker.trackProgress("nomcheck",t?"ok":"failed"),t?(e.logger.warn("Nominal service URL is reachable, erasing cached reconnect URL"),e.reconnectParams&&delete e.reconnectParams.reconnectUrl):e.logger.warn("Nominal service URL is not reachable either, keeping cached reconnect URL"),e.fsm.onAllocationFailed(!1,void 0)},function(){e.fsm.onAllocationFailed(!1,void 0)})}}}else e.logger.info("Expected failure, the browser says it is not online at the moment");e.fsm.onAllocationFailed(401===d,u)})},t.prototype.testNominalUrlConnectivity=function(t){var e,n=this;if(t<1e3)return this.logger.warn("There is no time left to reasonably perform the nominal service URL connectivity check (".concat(t," ms), falling back to assuming that the connectivity is fine")),Promise.resolve(!0);try{var o=new URL(this.options.trouterUrl);o.pathname="/",o.search="?"+this.buildQuery({check:Date.now(),cor_id:encodeURIComponent(this.options.clientCorrelationID),epid:encodeURIComponent(this.options.endpointId?this.options.endpointId:""),tc:encodeURIComponent((0,l.toJson)(this.clientInfo))}),e=new Request(this.options.rewriteUrlForProxy(o.toString()),{method:"GET",headers:{Accept:"text/plain"}})}catch(t){return this.logger.warn("Nominal service URL connectivity test request could not be created (".concat(t,"), falling back to assuming that the connectivity is fine")),Promise.resolve(!0)}return(0,l.fetchWithTimeout)(e,t).then(function(t){if(200!==t.status)throw Error("Not 200 OK: ".concat(t.status," ").concat(t.statusText));return t.text()}).then(function(t){if("Trouter"!==t)throw Error('Not "Trouter": '.concat(t.substring(0,16)).concat(t.length>16?"...":""));return!0}).catch(function(t){return n.logger.error("Nominal service URL connectivity test failed: ".concat(t)),!1})},t.prototype.sendPingRequest=function(){var t=this;if(this.socket&&void 0===this.pingResponseTimerId)try{this.logger.debug("emitting ping event");var e=!1;this.socket.emit("ping",function(){!0!==e&&t.onPingResponse()}),this.pingResponseTimerId=setTimeout(function(){t.logger.error("Ping response timeout is fired"),e=!0,t.clearPingResponseTimer(),t.fsm.onPingResponseTimeout()},this.timeoutOptions.pongTimeoutMs)}catch(t){var n=i(t);this.logger.error("unable to send ping. Error: ".concat(n)),this.connectionTracker.trackError("ping",n,!1)}},t.prototype.connectV4c=function(t,e){var n,o,i,r,s,a,u=this.options.ioOptions?c({},this.options.ioOptions):new R;u["force new connection"]=!0,u.reconnect=!1,(null===(n=this.reconnectParams)||void 0===n?void 0:n.serviceUrl)&&(0,S.adaptUrl)(this.reconnectParams.serviceUrl,"v4c")!==(0,S.adaptUrl)(this.options.trouterUrl,"v4c")&&(this.logger.warn("Dropping cached connection parameters for a different environment (".concat(this.reconnectParams.serviceUrl,", now ").concat(this.options.trouterUrl,")")),this.reconnectParams=void 0);var h=null!==(r=null!==(o=(0,S.redirectUrlIfPresent)(e))&&void 0!==o?o:"redirect-no-host"!==(null==e?void 0:e.kind)?null===(i=this.reconnectParams)||void 0===i?void 0:i.reconnectUrl:void 0)&&void 0!==r?r:this.options.trouterUrl,d=(0,S.adaptUrl)(h,"v4c");u["skipped handshake data"]={timeout:70,websocketUrl:d},u.query=this.buildV4cUrlParams(),u.rewriteUrlForProxy=this.options.rewriteUrlForProxy;try{if(this.stopSocketIo(),this.transportTypeName="websocket",this.socket=(null!==(s=this.options.io)&&void 0!==s?s:w).connect(this.options.trouterUrl,u),void 0===this.socket)throw Error("failed to create Socket.io object");var l=null===(a=this.audienceSubscriptionState)||void 0===a?void 0:a.increaseCvAndGetEventObject();this.attachSocketIoHandlers(this.socket,t,void 0,l)}catch(t){this.logger.error("".concat(t)),this.connectionTracker.trackError("v4c","".concat(t)),this.fsm.onV4cException()}},t.prototype.sendV4cAuthenticationEvent=function(t){var e,n={headers:c(c({},this.options.extraConnectionHeaders),o(t,this.usingLegacyTokenApi)),connectparams:(0,S.reconnectParam
1sWithoutUrls)(this.reconnectParams)};null===(e=this.socket)||void 0===e||e.emit(g.USER_AUTHENTICATE_EVENT_NAME,n)},t.prototype.setUserActivityState=function(t){var e=t.state!==this.userActivityState.state;this.userActivityState=t,e?(this.logger.info("Changing user activity state to '".concat(t.toEventJSON(),"'")),this.fsm.onSetNewUserActivityState()):(this.logger.debug("Not changing the same user activity state '".concat(t.toEventJSON(),"'")),this.manager.onUserActivityStateAccepted(t.correlationVector.value()))},t.prototype.sendUserActivityState=function(t,e){this.userActivityState.state!==m.UserActivityState.Unknown&&("websocket"===this.transportTypeName&&e?t===y.UserActivityEventReason.Connected?this.sendUserActivityStateMultiple(2):this.sendUserActivityStateMultiple(1):"xhr-polling"===this.transportTypeName&&t===y.UserActivityEventReason.Modified&&this.fsm.forceReconnect("user activity/force reconnect"))},t.prototype.setAudienceSubscriptionsAsync=function(t,e){var n=this.audienceSubscriptionState;if(this.audienceSubscriptionState=t,this.transportTypeName===this.WEBSOCKET_TRANSPORT_NAME)return this.setAudienceSubscriptionsInternalAsync(t.increaseCvAndGetEventObject(),e);if(this.transportTypeName===this.XHR_POLLING_TRANSPORT_NAME){var o=this.setAudienceSubscriptionsLongpollInternalAsync(t.increaseCvAndGetEventObject(),e,n);return this.fsm.forceReconnect("set audience subscription force reconnect"),o}throw Error("set audience subscription executed on an unknown transport")},t.prototype.setAudienceSubscriptionsUnsafeAsync=function(t){if(t)return this.transportTypeName===this.WEBSOCKET_TRANSPORT_NAME?this.setAudienceSubscriptionsInternalAsync(t,15e3):void 0},t.prototype.setAudienceSubscriptionsInternalAsync=function(t,e){return a(this,void 0,void 0,function(){var n,o,i=this;return u(this,function(r){switch(r.label){case 0:return this.logger.info("[WebSocket] Audience subscription set requested."),(n=new A("audience.subscribe")).args=t,[4,new Promise(function(o){var r=!1,s=setTimeout(function(){return r=!0,o(i.buildAudienceSubscriptionsTimeoutResponse(t))},e);i.sendDownstreamEvent(n,function(t,e){r||(clearTimeout(s),i.logger.debug("[Websocket] Audience subscription response: ".concat(e)),i.pendingAudienceSubscription&&i.onAudienceSubscriptionResult(e),o(e))})})];case 1:return o=r.sent(),this.manager.onAudiencesSetResolved(o,t.cv),[2,o]}})})},t.prototype.setAudienceSubscriptionsLongpollInternalAsync=function(t,e,n){var o;return a(this,void 0,void 0,function(){var i,r,s,c,a,h,d=this;return u(this,function(u){switch(u.label){case 0:return this.logger.info("[XHR Polling] Audience subscription set requested."),this.pendingAudienceSubscription&&(this.logger.error("Racing audience subscriptions occured. This situation resolves into undefined scenario and/or nasal demons."),clearTimeout(this.pendingAudienceSubscription.timeoutId)),0===t.audiences.length?[2,this.handleAudienceUnsubscribeLongpoll(t.cv,n)]:[4,new Promise(function(n){var o=setTimeout(function(){return d.pendingAudienceSubscription=void 0,n(d.buildAudienceSubscriptionsTimeoutResponse(t))},e);d.pendingAudienceSubscription={audienceSetResolve:n,timeoutId:o}})];case 1:return i=u.sent(),this.manager.getState()===m.TrouterState.Unknown||this.transportTypeName===this.WEBSOCKET_TRANSPORT_NAME||((null==(r=i.responses[0])?void 0:r.result.audienceSubscriptionState)===this.AUDIENCE_SUBSCRIPTION_RESULT_BAD_REQUEST?this.clearAudienceSubscriptionStateQueryParam():(null==(s=i.responses.find(function(e){return e.audienceId===t.audiences[0].id}))?void 0:s.result.audienceSubscriptionState)===this.AUDIENCE_SUBSCRIPTION_RESULT_ERROR?this.clearAudienceSubscriptionStateQueryParam():(c=(null===(o=null==n?void 0:n.audienceSubscriptionModel.audienceSubscriptions[0])||void 0===o?void 0:o.id)!==(null==r?void 0:r.audienceId),n&&c&&(a=this.mapToSyntheticAudienceSubscriptionResponses(n.audienceSubscriptionModel.audienceSubscriptions,this.AUDIENCE_SUBSCRIPTION_RESULT_UNSUBSCRIBED,200),(h=i.responses).push.apply(h,a))),this.manager.onAudiencesSetResolved(i,t.cv)),[2,i]}})})},t.prototype.clearAudienceSubscriptionStateQueryParam=function(){var t,e,n;(null===(n=null===(e=null===(t=this.socket)||void 0===t?void 0:t.socket)||void 0===e?void 0:e.options)||void 0===n?void 0:n.query)&&(this.socket.socket.options.query=this.socket.socket.options.query.replace(this.AUDIENCE_SUBSCRIPTION_STATE_QUERY_PARAM_REGEX,""))},t.prototype.handleAudienceUnsubscribeLongpoll=function(t,e){this.audienceSubscriptionState=void 0;var n,o={responses:[]};if(e){var i=this.mapToSyntheticAudienceSubscriptionResponses(e.audienceSubscriptionModel.audie
1nceSubscriptions,this.AUDIENCE_SUBSCRIPTION_RESULT_UNSUBSCRIBED,200);(n=o.responses).push.apply(n,i)}return this.manager.onAudiencesSetResolved(o,t),o},t.prototype.buildAudienceSubscriptionsTimeoutResponse=function(t){return this.logger.error("Audience subscription attempt has timed out."),{responses:this.mapToSyntheticAudienceSubscriptionResponses(t.audiences,this.AUDIENCE_SUBSCRIPTION_RESULT_TIMEOUT)}},t.prototype.mapToSyntheticAudienceSubscriptionResponses=function(t,e,n){return t.map(function(t){return{audienceId:t.id,result:{audienceSubscriptionState:e,responseStatus:n}}})},t.prototype.expediteBackoff=function(){this.tokenBackoff.expediteIfPending()},t.prototype.sendRegisterRequest=function(){var t=this;if(!this.options.registration||!this.registrarClient)throw Error("Internal error - options.registration is undefined");if(!this.allocateResult)throw Error("Allocate result is undefined in sendRegisterRequest()");this.logger.info("sending register request");var e=new l.Timespan;this.connectionTracker.trackStart("registration");var n=this.getRegistrationTtl()[0];this.registrarClient.register({appId:this.options.registration.pnhAppId,aesKey:"",languageId:"en-US",platform:this.options.registration.platform,templateKey:this.options.registration.pnhTemplateKey,platformUIVersion:this.options.registration.platformUIVersion,productContext:this.options.registration.productContext},{TROUTER:[{context:this.options.registration.context,path:this.allocateResult.surl,ttl:n}]}).then(function(){t.logger.info("Register request successful"),t.connectionTracker.trackEnd("registration"),t.fsm.onRegistrationSucceeded(),t.connectionTracker.sendTelemetry(p.ClientEventName.Registration,{duration:e.duration},[])}).catch(function(n){t.logger.error("Register request failed. Error: ".concat(n)),t.connectionTracker.trackError("registration",r(n)),t.fsm.onRegistrationFailed(),t.connectionTracker.sendTelemetry(p.ClientEventName.Registration,{duration:e.duration},[])})},t.prototype.sendUnregisterRequest=function(){var t=this;this.logger.info("sending unregister request");var e=new l.Timespan;if(!this.options.registration||!this.registrarClient)throw Error("Internal error - options.registration is undefined");this.connectionTracker.trackStart("unregistration"),this.registrarClient.unregister().then(function(){t.logger.info("Unregister request successful"),t.connectionTracker.trackEnd("unregistration"),t.fsm.onUnregistrationDone(),t.connectionTracker.sendTelemetry(p.ClientEventName.Unregistration,{duration:e.duration},[])}).catch(function(n){t.logger.error("Unregister request failed. Error: ".concat(n)),t.connectionTracker.trackError("unregistration",r(n)),t.fsm.onUnregistrationDone(),t.connectionTracker.sendTelemetry(p.ClientEventName.Unregistration,{duration:e.duration},[])})},t.prototype.resetTokenBackoff=function(){this.tokenBackoff.reset()},t.prototype.cancelPendingRegistrationRequests=function(){this.registrarClient&&this.registrarClient.cancelPendingRequests()},t.prototype.clearSentEventTimers=function(){var t=Object.keys(this.pendingSentEventTimers);if(t.length>0){this.logger.debug("Clearing all pending downstream events related timers");for(var e=0;e<t.length;e++){var n=t[e];this.clearSentEventTimer(Number(n))}}},t.prototype.restartIncallModeTimer=function(){var t=this;this.clearIncallModeTimerId(),this.logger.debug("Restarting incall mode timer"),this.incallModeTimerId=setTimeout(function(){t.logger.info("Call mode timer fired"),t.fsm.onIncallModeTimer()},this.options.incallModeTimeoutMs)},t.prototype.enterIncallMode=function(){this.logger.info("Entering incall mode"),this.timeoutOptions=this.options.incallTimeoutOptions,this.tokenBackoff.setMaxBackoffMs(this.timeoutOptions.maxBackoffMs),this.inIncallMode=!0},t.prototype.exitIncallMode=function(){this.logger.info("Exiting incall mode"),this.clearIncallModeTimerId(),this.timeoutOptions=this.options.timeoutOptions,this.tokenBackoff.setMaxBackoffMs(this.timeoutOptions.maxBackoffMs),this.inIncallMode=!1},t.prototype.isIncallMode=function(){return this.inIncallMode},t.prototype.sendDisconnectTelemetryEvent=function(t){var e={reason:t,serverClosed:!this.fsm.isActive()};this.connectionTracker.trackDisconnected(e),this.connectionTracker.clearConnectedInfo()},t.prototype.forceReconnectDueToNoRegistration=function(){this.fsm.forceReconnect("force reconnect due to no registration")}
1,t.prototype.resetReconnectParamsOnErrorThreshold=function(){this.logger.warn("".concat(this.connectingErrorsInRow," connection attempts, server-side failure: erasing cached connection parameters")),this.reconnectParams=void 0},t.prototype.onSocketConnecting=function(t){this.logger.info("onSocketConnecting(".concat(t,")")),this.transportTypeName=t,this.connectionTracker.trackProgress("connecting",this.transportTypeName),this.fsm.onConnecting()},t.prototype.onSocketConnect=function(t){this.logger.info("onSocketConnect"),this.fsm.onSocketConnect(t)},t.prototype.onSocketConnectFailed=function(t){this.logger.error("onSocketConnectFailed"),this.connectionTracker.trackError("connect_failed",t,!0,this.transportTypeName?this.transportTypeName:this.UNKNOWN_TRANSPORT),this.fsm.onConnectingFailed()},t.prototype.onSocketDisconnect=function(t){var e=this.connectionTracker.getSessionLength()||0,n=f.DisconnectReason.fromRawReason(t);this.logger.error("onSocketDisconnect, reason: ".concat(n.reason)),"dup"===n.reason&&"dup"===this.lastDisconnectReason&&e<this.options.duplicateDisconnectThresholdMs&&(this.logger.warn("Socket was closed by server as Duplicate for the second time in a row "+"after ".concat(e," ms which is below the threshold of ")+"".concat(this.options.duplicateDisconnectThresholdMs," ms. Resetting cached ")+"connection parameters and making a new allocation."),this.reconnectParams=void 0),this.lastDisconnectReason=n.reason,this.fsm.onSocketDisconnect(n),this.connectionExpireTimestampInSecs=void 0},t.prototype.onSocketReconnect=function(){this.logger.error("onSocketReconnect"),this.fsm.onTrouterConnected()},t.prototype.onSocketReconnectFailed=function(t){this.logger.error("onSocketReconnectFailed with '".concat(t,"'")),this.fsm.onSocketDisconnect(f.DisconnectReason.fromSocketIoEventData("reconnecterror",t))},t.prototype.onSocketReconnecting=function(){this.logger.error("onSocketReconnecting")},t.prototype.onSocketError=function(t){this.logger.error("onSocketError with '".concat((0,l.toJson)(t),"'")),this.fsm.isConnecting()&&++this.connectingErrorsInRow>=this.connectingErrorsThreshold&&this.resetReconnectParamsOnErrorThreshold(),this.connectionTracker.trackError("connectSocket",null!=t&&"function"==typeof t.toString?t.toString():"[".concat(typeof t,"]")),this.fsm.onSocketDisconnect(f.DisconnectReason.fromSocketIoEventData("socketerror",t))},t.prototype.onSocketMessage=function(t){var e,n,o=this;this.logger.debug("onSocketMessage");try{e=new E(t,this.logger);var s=null===(n=e.headers)||void 0===n?void 0:n["X-Microsoft-Skype-Chain-ID"],c=s?" Chain-Id ".concat(s):"";this.logger.info("Received request N ".concat(e.id).concat(c," CV ").concat(e.correlationVector," to '").concat(e.url,"'")),e.startTS=Date.now(),e.url&&this.urlPath&&e.url.startsWith(this.urlPath)&&(e.shortUrl=e.url.substring(this.urlPath.length))}catch(t){var a=i(t);return this.logger.error("unable to parse request. Error: ".concat(a)),this.connectionTracker.trackRequest(void 0,a),void this.connectionTracker.sendResponseError("unable to parse request, error: ".concat(t))}e.timeoutTimerId=setTimeout(function(){if(!e.replied){o.logger.error("Request ".concat(e.id," timed out"));var t=new p.ResponseData(e.id);t.status=504,t.headers={"Trouter-Responder":"ClientLib"},o.sendResponse(e,t),e.timedout=!0}},this.timeoutOptions.requestTimeoutMs);try{this.connectionTracker.trackRequest(e),this.fsm.onDownstreamRequest(e)}catch(t){this.logger.error("exception in socket.on message. Error: ".concat(i(t))),this.connectionTracker.sendResponseError(r(t),e,void 0)}},t.prototype.onTrouterConnected=function(t,e,n){var o,i,r,s,a=this;if((0,S.isV4ConnectEvent)(t))this.allocateResult=c(c({},t),{ttl:t.ttl.toString()}),this.populateAndCacheReconnectParams(t,t.reconnectUrl),this.populateConnectionStateFields(t);else if(!this.allocateResult)return void this.logger.error("Invalid internal state - received onTrouterConnected while allocateResult is not set");this.connectingErrorsInRow=0,this.logger.info("onTrouterConnected: ".concat(this.allocateResult.url)),"xhr-polling"===this.transportTypeName&&e&&this.manager.onUserActivityStateAccepted(e.cv),(null===(r=null===(i=null===(o=this.socket)||void 0===o?void 0:o.socket)||void 0===i?void 0:i.options)||void 0===r?void 0:r.query)&&(this.socket.socket.options.query+="&connected=true"),this.urlPath=this.allocateResult.url.replace(/https?:\/\/([A-z0-9\:\$\-\_\.\+\!\*\"\(\)\,]*)\//,"/");var u=this.connectedUrl!==this.allocateResult.url;this.connectedUrl=this.allocateResult.url,this.connectionExpireTimestampInSecs=(0,l.calculateExpireTsInSec)((0,S.ensureNumber)(t.ttl)),this.connectionTracker.trackEnd("connectSocket"),this.connectionTracker.trackConnected(u,this.transportTypeName?this.transportTypeName:this.UNKNOWN_TRANSPORT),null===(s=this.setAudienceSubscriptionsUnsafeAsync(n))||void 0===s||s.catch(function(t){return a.logger.error("Re-subscribe to audie
1nces has failed with ".concat(t))}),this.fsm.onTrouterConnected()},t.prototype.onTrouterReconnect=function(t){var e=t.target;this.logger.info("onTrouterReconnect target: ".concat(e)),"self"===e?this.fsm.onReconnectRequired(!0,h.ServerInitiated):this.fsm.onReconnectRequired(!1,h.ServerInitiated,t)},t.prototype.onTrouterMessageLoss=function(t){this.logger.debug("onTrouterMessageLoss"),this.fsm.onTrouterMessageLost(t.droppedIndicators)},t.prototype.onAudienceSubscriptionResult=function(t){this.logger.info("onAudienceSubscriptionResult"),this.pendingAudienceSubscription&&(clearTimeout(this.pendingAudienceSubscription.timeoutId),this.pendingAudienceSubscription.audienceSetResolve(t),this.pendingAudienceSubscription=void 0)},t.prototype.buildV4cUrlParams=function(){var t={};return t.tc=encodeURI((0,l.toJson)(this.clientInfo)),t.timeout=Math.floor(this.timeoutOptions.pingTimeoutMs/1e3),this.options.endpointId&&(t.epid=this.options.endpointId),this.appendConnectedClientIds(this.buildQuery(t),!0)},t.prototype.attachSocketIoHandlers=function(t,e,n,o){var i=this;t.on("connecting",function(t){i.onSocketConnecting(t)}),t.on("connect",function(){i.onSocketConnect(e)}),t.on("connect_failed",function(t){i.onSocketConnectFailed(t)}),t.on("close_during_connecting",function(t){i.onSocketConnectFailed(t)}),t.on("disconnect",function(t){i.onSocketDisconnect(t)}),t.on("reconnect",function(){i.onSocketReconnect()}),t.on("reconnect_failed",function(t){i.onSocketReconnectFailed(t)}),t.on("reconnecting",function(){i.onSocketReconnecting()}),t.on("error",function(t){i.onSocketError(t)}),t.on("message",function(t){i.onSocketMessage(t)}),t.on("trouter.connected",function(t){i.onTrouterConnected(t,n,o)}),t.on("trouter.reconnect",function(t){i.onTrouterReconnect(t)}),t.on("trouter.message_loss",function(t){i.onTrouterMessageLoss(t)}),t.on("audience.subscriptionresult",function(t,e){i.onAudienceSubscriptionResult(e)})},t.prototype.onNavigatorOnlineStatusUpdate=function(){var t=window.navigator.onLine;this.logger.debug("Browser online status update - new state: ".concat(t,", previously: ").concat(this.isNavigatorOnline)),t&&!this.isNavigatorOnline?(this.isNavigatorOnline=!0,this.tokenBackoff.expediteIfPending(),this.connectionTracker.trackProgress("browserNet","online")):!t&&this.isNavigatorOnline&&(this.isNavigatorOnline=!1,this.connectionTracker.trackProgress("browserNet","offline"))},t.prototype.onAllocationResponse=function(t,e){this.logger.info("Received allocation response ".concat(JSON.stringify(t))),this.allocateResult=t,this.populateAndCacheReconnectParams(this.allocateResult,"".concat(this.allocateResult.socketio,"v4/a")),this.populateConnectionStateFields(this.allocateResult),this.fsm.onAllocationSucceed(e)},t.prototype.populateAndCacheReconnectParams=function(t,e){this.reconnectParams=c({serviceUrl:this.options.trouterUrl,reconnectUrl:e},t.connectparams),this.manager.onConnectionParametersUpdated(this.reconnectParams)},t.prototype.populateConnectionStateFields=function(t){var e,n,o="string"==typeof t.ttl?parseInt(t.ttl,10):t.ttl;if(this.connectionExpireTimestampInSecs=(0,l.calculateExpireTsInSec)(o),this.connectionId=null!==(e=t.id)&&void 0!==e?e:"",this.connectedClientId=t.ccid,this.logger.debug("connected client id set {connectedClientId:".concat(this.connectedClientId,"}")),this.c2cUrlBase=null!==(n=t.curlb)&&void 0!==n?n:"",""===this.c2cUrlBase){var i=t.surl.indexOf("://");i>=0&&(i=t.surl.indexOf("/",i+3))>=5&&":3443"===t.surl.substr(i-5,5)&&(this.c2cUrlBase=t.surl.substr(0,i-5))}},t.prototype.onPingResponse=function(){this.logger.debug("onPingResponse"),this.connectionTracker.increasePingResponseCount(),this.clearPingResponseTimer(),this.fsm.onPingResponse()},t.prototype.clearPingResponseTimer=function(){void 0!==this.pingResponseTimerId&&(clearTimeout(this.pingResponseTimerId),this.pingResponseTimerId=void 0)},t.prototype.buildQuery=function(t){for(var e=[],n=0,o=Object.keys(t);n<o.length;n++){var i=o[n];void 0!==t[i]&&e.push("".concat(i,"=").concat(t[i]))}return e.join("&")},t.prototype.appendConnectedClientIds=function(t,e){var n="";t.includes("ccid=")||(n="ccid=".concat(this.connectedClientId,"&")),this.domId&&(n+="dom=".concat(this.domId,"&")),n.length>0&&(n=n.slice(0,-1));var o=e||t.includes("?")?"&":"?";return this.appendCorrelationIds(t+o+n,e)},t.prototype.appendEndpointId=function(t,e){var n=e||t.includes("?")?"&":"?";return!t.includes("epid")&&this.options.endpointId?"".concat(t).concat(n,"epid=").concat(this.options.endpointId):t},t.prototype.appendCorrelationIds=function(t,e){var n=e||t.includes("?")?"&":"?";return t.includes("cor_id")?t:"".concat(t).concat(n,"cor_id=").concat(this.options.clientCorrelationID)+"&con_num=".concat(this.clientID,"_").concat(this.connectionAttempt)},t.prototype.safeString=function(t){return"string"==typeof t?t:""},t.prototype.sendResponse=function(t,e){if(t.timedout)return this.logger.error("Request ".concat(t.id," already timed out")),1;if(t.replied)return this.logger.error("Response for request ".concat(t.id," already sent")),2;clearTimeout(t.timeoutTimerId),t.timeoutTimerId=void 0,t.replied=!0,e.headers=null!==(n=e.headers)&&void 0!==n?n:{};var n,o,r,s=t.correlationVector;this.logger.info("Sending response N ".concat(t.id," CV ").concat(s," with status ").concat(e.status)),s&&(e.headers[C]=s),(null===(o=t.headers)||void 0===o?void 0:o["trouter-request"])&&(e.headers["trouter-request"]=t.headers["trouter-request"]);var c=Date.now()-t.startTS;if(e.headers["trouter-client"]=(0,l.toJson)({cd:c}),(null===(r=t.headers)||void 0===r?void 0:r["trouter-is-broadcast"])&&(e.headers["trouter-is-broadcast"]=t.headers["trouter-is-broadcast"]),this.logger.debug("response: ".concat((0,l.toJson)(e))),!this.socket)return this.connectionTracker.sendResponseError("no socket",t,e),4;try{return this.socket.send((0,l.toJson)(e)),e.sentTS=Date.now(),t.incrementCorrelationVector(),this.connectionTracker.trackResponse(t,c,e),"websocket"===this.transportTypeName&&this.sendPingRequest(),0}catch(n){var a="unable to send data on response.end. Error: ".concat(i(n));return this.logger.error(a),this.connectionTracker.sendResponseError(a,t,e),4}},t.prototype.sendUserActivityStateMultiple=function(t){var e=this,n=new A("user.activity"),o=this.userActivityState.increaseCvAndGetEventObject();n.args=o,this.logger.debug("Sending user activity '".concat(this.userActivityState.toEventJSON(),"', remaining ").concat(t-1));var i=!1;this.sendDownstreamEvent(n,function(){if(!0!==i&&(e.logger.info("User activity state: ".concat(o.state,", cv: ").concat(o.cv," accepted")),e.manager.onUserActivityStateAccepted(o.cv),e.clearSentEventTimer(n.timeoutTimerId),t>1)){var r=setTimeout(function(){e.clearSentEventTimer(r),e.sendUserActivityStateMultiple(t-1)},e.options.userActivitySecondResendDelayMs);e.registerSentEventTimer(r,"user.activity/resend")}}),n.timeoutTimerId=setTimeout(function(){e.logger.error("Activity state response timeout is fired"),i=!0,e.fsm.onActivityStateResponseTimeout(),e.clearSentEventTimer(n.timeoutTimerId)},this.timeoutOptions.userActivityResponseTimeoutMs),this.registerSentEventTimer(n.timeoutTimerId,"user.activity/response")},t.prototype.sendDownstreamEvent=function(t,e){this.logger.debug("Sending downstream event ".concat(t.name)),this.socket&&this.socket.emit(t.name,t.args,e)},t.prototype.registerSentEventTimer=function(t,e){this.logger.debug("registering timer ".concat(t," -> ").concat(e)),this.pendingSentEventTimers[t]=e},t.prototype.clearSentEventTimer=function(t){var e=this.pendingSentEventTimers[t];this.logger.debug("clearing timer ".concat(t," -> ").concat(e)),delete this.pendingSentEventTimers[t],clearTimeout(t)},t.prototype.getRegistrationTtl=function(){var t,e,n=(0,l.calculateTtlInSec)(this.connectionExpireTimestampInSecs);if(this.logger.debug("Current connectionID will expire in ".concat(n," seconds")),(null===(t=this.options.registration)||void 0===t?void 0:t.registrarTtlSec)&&n>0){var o=this.options.registration.registrarTtlSec<n;return[Math.min(this.options.registration.registrarTtlSec,n),o]}return(null===(e=this.options.registration)||void 0===e?void 0:e.registrarTtlSec)?[this.options.registration.registrarTtlSec,!1]:n>0?[n,!1]:[3600,!1]},t.prototype.clearIncallModeTimerId=function(){void 0!==this.incallModeTimerId&&(this.logger.debug("Clearing in-call mode timer"),clearTimeout(this.incallModeTimerId),this.incallModeTimerId=void 0)},t.prototype.applyConnectionTrackerOptions=function(t){try{t.eventLogger&&"function"==typeof t.eventLogger.logEvent?(this.connectionTracker.mergeSettings(t.telemetrySettings),this.connectionTracker.enable(t.eventLogger)):this.logger.warn("Trouter client event logging disabled due to invali
1d configuration.")}catch(t){this.logger.warn("Trouter client event logging disabled. Error: ".concat(i(t))),this.connectionTracker.disable()}},t.prototype.canRetryTokenFetchRequest=function(t){var e=this.options.retryLimitOnTokenFetch;return null==e||t<e||(this.logger.warn("Reached limit on maximum number of token fetch request. Current count: ".concat(t,", retry limit: ").concat(e)),!1)},t}();e.TrouterConnection=U},function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.MessageHandlerRegistry=void 0;var o=n(1),i=n(0),r=function(){function t(t){this.messageHandlers=[],this.logger=new i.Logger("MessageHandlers",t)}return t.prototype.register=function(t){if(this.messageHandlers.some(function(e){return e===t}))throw Error("Registering the same handler twice is not allowed");this.messageHandlers.push(t)},t.prototype.clear=function(){this.logger.debug("Clearing message handlers"),this.messageHandlers=[]},t.prototype.active=function(){return this.messageHandlers.length>0},t.prototype.handleMessage=function(t){for(var e={resultCode:o.UNHANDLED_MESSAGE_ACK,isHandled:!1},n=0,i=this.messageHandlers;n<i.length;n++){var r=i[n],s=this.safeExecuteHandle(r,t);if(void 0!==s&&(void 0===s.isHandled||s.isHandled))return void 0===s.resultCode&&(s.resultCode=o.HANDLED_MESSAGE_ACK),s}return e},t.prototype.safeExecuteHandle=function(t,e){try{return t.handleMessage(e)}catch(t){return void this.logger.warn("Trouter message handler threw an exception: ".concat(t))}},t}();e.MessageHandlerRegistry=r},function(t,e,n){var o=this&&this.__awaiter||function(t,e,n,o){return new(n||(n=Promise))(function(i,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){var e;t.done?i(t.value):((e=t.value)instanceof n?e:new n(function(t){t(e)})).then(s,c)}a((o=o.apply(t,e||[])).next())})},i=this&&this.__generator||function(t,e){function n(n){return function(a){return function(n){if(o)throw TypeError("Generator is already executing.");for(;s&&(s=0,n[0]&&(c=0)),c;)try{if(o=1,i&&(r=2&n[0]?i.return:n[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,n[1])).done)return r;switch(i=0,r&&(n=[2&n[0],r.value]),n[0]){case 0:case 1:r=n;break;case 4:return c.label++,{value:n[1],done:!1};case 5:c.label++,i=n[1],n=[0];continue;case 7:n=c.ops.pop(),c.trys.pop();continue;default:if(!(r=(r=c.trys).length>0&&r[r.length-1])&&(6===n[0]||2===n[0])){c=0;continue}if(3===n[0]&&(!r||n[1]>r[0]&&n[1]<r[3])){c.label=n[1];break}if(6===n[0]&&c.label<r[1]){c.label=r[1],r=n;break}if(r&&c.label<r[2]){c.label=r[2],c.ops.push(n);break}r[2]&&c.ops.pop(),c.trys.pop();continue}n=e.call(t,c)}catch(t){n=[6,t],i=0}finally{o=r=0}if(5&n[0])throw n[1];return{value:n[0]?n[1]:void 0,done:!0}}([n,a])}}var o,i,r,s,c={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:n(0),throw:n(1),return:n(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s};Object.defineProperty(e,"__esModule",{value:!0}),e.addCacheAsBackupTo=void 0,e.addCacheAsBackupTo=function(t){var e,n=this;return function(r){return o(n,void 0,void 0,function(){return i(this,function(n){return r&&(e=void 0),[2,new Promise(function(n,o){t(r).then(function(t){e=t,n(t)}).catch(function(t){void 0!==e&&e.length>0&&n(e),o(t)})})]})})}}},function(t,e,n){var o=this&&this.__awaiter||function(t,e,n,o){return new(n||(n=Promise))(function(i,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){var e;t.done?i(t.value):((e=t.value)instanceof n?e:new n(function(t){t(e)})).then(s,c)}a((o=o.apply(t,e||[])).next())})},i=this&&this.__generator||function(t,e){function n(n){return function(a){return function(n){if(o)throw TypeError("Generator is already executing.");for(;s&&(s=0,n[0]&&(c=0)),c;)try{if(o=1,i&&(r=2&n[0]?i.return:n[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,n[1])).done)return r;switch(i=0,r&&(n=[2&n[0],r.value]),n[0]){case 0:case 1:r=n;break;case 4:return c.label++,{value:n[1],done:!1};case 5:c.label++,i=n[1],n=[0];continue;case 7:n=c.ops.pop(),c.trys.pop();continue;default:if(!(r=(r=c.trys).length>0&&r[r.length-1])&&(6===n[0]||2===n[0])){c=0;continue}if(3===n[0]&&(!r||n[1]>r[0]&&n[1]<r[3])){c.label=n[1];break}if(6===n[0]&&c.label<r[1]){c.label=r[1],r=n;break}if(r&&c.label<r[2]){c.label=r[2],c.ops.push(n);break}r[2]&&c.ops.pop(),c.trys.pop();continue}n=e.call(t,c)}catch(t){n=[6,t],i=0}finally{o=r=0}if(5&n[0])throw n[1];return{value:n[0]?n[1]:void 0,done:!0}}([n,a])}}var o,i,r,s,c={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]}
1,trys:[],ops:[]};return s={next:n(0),throw:n(1),return:n(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s};Object.defineProperty(e,"__esModule",{value:!0}),e.TrouterManager=e.AudienceSubscriptionState=e.UserActivityObject=void 0;var r=n(3),s=n(2),c=n(4),a=n(0),u=n(5),h=n(18),d=n(7),l=n(6),p=n(19),g=function(){function t(t,e){this.state=t,this.correlationVector=void 0!==e?e:r.CorrelationVector.extend()}return t.prototype.getStateString=function(){switch(this.state){case s.UserActivityState.Active:return"active";case s.UserActivityState.Inactive:return"inactive";case s.UserActivityState.Unknown:return"unknown";default:return"undefined"}},t.prototype.increaseCvAndGetEventObject=function(){return this.correlationVector.increase(),this.toEventObject()},t.prototype.toEventObject=function(){return{state:this.getStateString(),cv:this.correlationVector.value()}},t.prototype.toEventJSON=function(){return(0,r.toJson)(this.toEventObject())},t}();e.UserActivityObject=g;var f=function(){function t(t,e){void 0===e&&(e=r.CorrelationVector.extend()),this.audienceSubscriptionModel=t,this.correlationVector=e}return t.prototype.increaseCvAndGetEventObject=function(){return this.correlationVector.increase(),this.toEventObject()},t.prototype.toEventObject=function(){return{audiences:this.audienceSubscriptionModel.audienceSubscriptions,cv:this.correlationVector.value()}},t.prototype.toEventJSON=function(){return(0,r.toJson)(this.toEventObject())},t}();e.AudienceSubscriptionState=f;var v=function(){function t(t,e,n,o,i,c){var h=this;this.logFunc=t,this.options=e,this.tokenProvider=n,this.usingLegacyTokenApi=o,this.listener=i,this.tokenTypeProtocolSelector=function(t,e){return h.options.forceV4aProtocol?"v4a":(0,u.usedProtocol)(t,e)},this.logger=new a.Logger("Manager",t),this.logger.info("Created TrouterManager with options ".concat((0,r.toJson)(this.options))),this.fsm=new p.TrouterManagerFsm(t,this),this.baseEndpointUrl="",this.processedMessageLoss={},this.userActivityObject=new g(s.UserActivityState.Unknown),this.protocolSelector=null!=c?c:this.tokenTypeProtocolSelector.bind(this)}return t.prototype.start=function(){this.fsm.start()},t.prototype.stop=function(t){this.fsm.stop(t)},t.prototype.configure=function(t){this.options=t,void 0!==this.firstConnection&&this.firstConnection.configure(t),void 0!==this.secondConnection&&this.secondConnection.configure(t),this.logger.info("Reconfigured TrouterManager with options ".concat((0,r.toJson)(this.options)))},t.prototype.checkConnection=function(t){void 0!==this.firstConnection&&this.firstConnection.checkConnection(t),void 0!==this.secondConnection&&this.secondConnection.checkConnection(t)},t.prototype.resendRegistration=function(){return o(this,void 0,void 0,function(){return i(this,function(t){return void 0!==this.secondConnection?(this.logger.info("Resending registration on the second/new connection"),[2,this.secondConnection.resendRegistration()]):void 0!==this.firstConnection?(this.logger.info("Resending registration on the first/current connection"),[2,this.firstConnection.resendRegistration()]):(this.logger.info("No connection to resend registration on, will be done upon (re)connect"),[2])})})},t.prototype.getServerState=function(){if(void 0!==this.firstConnection)return this.firstConnection.getServerState()},t.prototype.getState=function(){return this.fsm.getState()},t.prototype.isInTerminalState=function(){return this.fsm.getInternalState()===c.TrouterManagerState.TerminalError},t.prototype.reportStateInfo=function(){var t=this.firstConnection?l.State[this.firstConnection.getState()]:"Unknown",e=c.TrouterManagerState[this.fsm.getInternalState()];if(this.secondConnection){var n=l.State[this.secondConnection.getState()];return"Manager ".concat(e,"; 1st ").concat(t,"; 2nd ").concat(n)}return"Manager ".concat(e,"; Connection ").concat(t)},t.prototype.startFirstConnection=function(){var t=new d.TrouterConnection(this.logFunc,this.options,this.configuredTrouterManager(),this.tokenProvider,this.usingLegacyTokenApi,this.userActivityObject,this.protocolSelector,this.audienceSubscriptionState);this.firstConnection=t,this.getConnectionCache().then(function(e){t.start(e)}).catch(function(){})},t.prototype.startSecondConnection=function(t){var e=new d.TrouterConnection(this.logFunc,this.options,this.configuredTrouterManager(),this.tokenProvider,this.usingLegacyTokenApi,this.userActivityObject,this.protocolSelector,this.audienceSubscriptionState);this.secondConnection=e,void 0!==this.firstConnection&&this.firstConnection.disableRegistrationsAndAutoReconnect(),t?this.getConnectionCache().then(function(t){e.start(t)}).catch(function(){}):e.start()}
1,t.prototype.stopFirstConnection=function(t){void 0!==this.firstConnection&&(this.storedFirstConnection=this.firstConnection,this.firstConnection.stop(t),this.firstConnection=void 0)},t.prototype.stopSecondConnection=function(t){void 0!==this.secondConnection&&(this.secondConnection.stop(t),this.secondConnection=void 0)},t.prototype.stopSecondConnectionDelayed=function(){if(void 0!==this.secondConnection){var t=this.secondConnection;this.secondConnection=void 0,this.logger.info("Closing an inactive connection in ".concat(Math.round(this.options.lingeringConnectionDelayMs/1e3),"s")),setTimeout(function(){t.stop(!0)},this.options.lingeringConnectionDelayMs)}},t.prototype.forceStopLingeringConnection=function(){this.storedFirstConnection&&(this.storedFirstConnection.stop(!1),this.storedFirstConnection=void 0)},t.prototype.switchConnections=function(){var t=this.firstConnection;this.firstConnection=this.secondConnection,this.secondConnection=t},t.prototype.doesSecondConnectionExist=function(){return void 0!==this.secondConnection},t.prototype.dispatchConnected=function(){if(void 0!==this.firstConnection){var t=this.firstConnection.getServerState(),e=t.url.endsWith("/")?t.url.slice(0,-1):t.url,n={baseEndpointUrl:e,newEndpointUrl:e!==this.baseEndpointUrl,c2cUrlBase:t.c2cUrlBase,clientId:t.connectedClientId,connectionId:t.connectionId,connectionTtlSec:t.getRemainingTtlInSec()};this.baseEndpointUrl=e,this.listener.onTrouterConnected(t.url,n)}},t.prototype.dispatchDisconnected=function(){this.listener.onTrouterDisconnected&&this.listener.onTrouterDisconnected()},t.prototype.dispatchTerminalError=function(){this.listener.onTrouterDisconnected&&this.listener.onTrouterDisconnected()},t.prototype.dispatchRegistrationState=function(t){this.options.registrationStateCallback&&this.options.registrationStateCallback(t)},t.prototype.expediteBackoffOnConnections=function(){var t;if(void 0!==this.lastExpediteBackoffCallAt&&Date.now()-this.lastExpediteBackoffCallAt<(null!==(t=this.options.expediteBackoffOnStartMinimumDelayMs)&&void 0!==t?t:1e4))return void this.logger.info("Expedite backoff due to start() too frequent, skipping");this.lastExpediteBackoffCallAt=Date.now(),void 0!==this.firstConnection&&this.firstConnection.expediteBackoff(),void 0!==this.secondConnection&&this.secondConnection.expediteBackoff()},t.prototype.onDownstreamRequest=function(t,e,n){var o={id:e.id,method:e.method,path:"/".concat(e.shortUrl),body:e.body,headers:e.headers},i={id:e.id,status:0,headers:{},body:"",send:function(){return i.status<=100||i.status>=999?3:(n.writeHead(i.status,i.headers),n.end(i.body))}};this.listener.onTrouterRequest(o,i)},t.prototype.onConnected=function(t){this.fsm.onConnected(t===this.firstConnection)},t.prototype.onRegistered=function(t){this.fsm.onRegistered(t===this.firstConnection)},t.prototype.onUnregistered=function(t){this.fsm.onUnregistered(t===this.firstConnection||t===this.storedFirstConnection)},t.prototype.onReconnecting=function(t){this.fsm.onReconnecting(t===this.firstConnection)},t.prototype.onReconnectIsRequired=function(t,e,n){this.fsm.onReconnectionRequired(t===this.firstConnection,e,n)},t.prototype.onDisconnected=function(t){this.fsm.onDisconnected(t===this.firstConnection||t==this.storedFirstConnection),this.storedFirstConnection=void 0},t.prototype.onTerminalError=function(){this.fsm.onTerminalError(),this.storedFirstConnection=void 0},t.prototype.onUserActivityStateAccepted=function(t){this.listener.onTrouterUserActivityStateAccepted&&this.listener.onTrouterUserActivityStateAccepted(t)},t.prototype.onAudiencesSetResolved=function(t,e){var n,o;null===(o=(n=this.listener).onAudiencesSetResolved)||void 0===o||o.call(n,t,e)},t.prototype.onConnectionParametersUpdated=function(t){this.setConnectionCache(t)},t.prototype.setUserActivityState=function(t,e){return this.userActivityObject=new g(t,r.CorrelationVector.extend(e)),void 0!==this.secondConnection?(this.logger.info("Setting user activity ".concat(this.userActivityObject.toEventJSON()," on the second/new connection")),void this.secondConnection.setUserActivityState(this.userActivityObject)):void 0!==this.firstConnection?(this.logger.info("Setting user activity ".concat(this.userActivityObject.toEventJSON()," on the first/current connection")),void this.firstConnection.setUserActivityState(this.userActivityObject)):void 0},t.prototype.setAudienceSubscriptionsAsync=function(t,e,n){if(this.audienceSubscriptionState=new f(t,r.CorrelationVector.extend(n)),this.secondConnection)return this.logger.info("Setting audience subscriptions ".concat(this.audienceSubscriptionState.toEventJSON()," on second/new connection")),this.secondConnection.setAudienceSubscriptionsAsync(this.audienceSubscriptionState,e);if(this.firstConnection)return this.logger.info("Setting audience subscriptions ".concat(this.audienceSubscriptionState.toEventJSON()," on first/current connection")),this.firstConnection.setAudienceSubscriptionsAsync(this.audienceSubscriptionState,e);throw Error("No connection found")},t.prototype.onTrouterMessageLost=function(t){var e=this;if(this.listener.onTrouterMessageLoss){if(null==t?void 0:t.length){var n=t.filter(function(t){return void 0!==e.processedMessageLoss["".concat(t.tag,"-").concat(t.etag)]});if(n.length&&(this.logger.info("onTrouterMessageLoss - immediately acknowledging ".concat(n.length," seen dropped indicators")),this.sendProcessedDroppedIndicators(n),!(t=t.filter(function(t){return void 0===e.processedMessageLoss["".concat(t.tag,"-").concat(t.etag)]})).length))return void this.logger.info("onTrouterMessageLoss - all declared dropped indicators have been seen before");if(!this.listener.onTrouterMessageLoss(t.map(function(t){return t.tag})))return void this.logger.warn("onTrouterMessageLoss - some flow tag(s) have not been processed by listeners");t.forEach(function(t){e.processedMessageLoss["".concat(t.tag,"-").concat(t.etag)]=""}),this.sendProcessedDroppedIndicators(t)}else this.logger.warn("onTrouterMessageLoss - no flow tags have been provided")}},t.prototype.getConnectionCache=function(){var t=this;return this.options.connectionCache?(this.logger.debug("Querying host's connection cache"),this.options.connectionCache.onGetTrouterConnectionCache().then(function(t){var e=t?JSON.parse(t):void 0;return"object"==typeof e?e:void 0}).catch(function(e){return t.logger.warn("Invalid connection cache content provided: ".concat(e)),t.connectionCache})):Promise.resolve(this.connectionCache)},t.prototype.setConnectionCache=function(t){if(this.connectionCache=t,this.options.connectionCache)try{this.options.connectionCache.onSetTrouterConnectionCache(JSON.stringify(t))}
1catch(t){this.logger.warn("Error setting external connection cache: ".concat(t))}},t.prototype.sendProcessedDroppedIndicators=function(t){return void 0!==this.firstConnection?void this.firstConnection.sendProcessedDroppedIndicators(t):void 0!==this.secondConnection?void this.secondConnection.sendProcessedDroppedIndicators(t):void 0},t.prototype.configuredTrouterManager=function(){return new h.RegistrationEnforcer(this,this.options.connectionDependsOnRegistration,this.options.delayEventsUntilRegistered)},t}();e.TrouterManager=v},function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.TrouterUrlPromise=void 0;var o=n(0),i=function(){function t(t){this.logger=new o.Logger("UrlPromise",t)}return t.prototype.getPromise=function(){var t=this;return void 0!==this.url?(this.logger.debug("returning previously resolved url: ".concat(this.url)),Promise.resolve(this.url)):(void 0===this.pendingPromise?(this.logger.debug("creating and returning promise"),this.pendingPromise=new Promise(function(e,n){t.pendingPromiseResolveRef=e,t.pendingPromiseRejectRef=n})):this.logger.debug("returning existing promise"),this.pendingPromise)},t.prototype.resolveUrl=function(t){this.url=t,this.logger.debug("got url: ".concat(this.url));var e=this.pendingPromiseResolveRef;this.pendingPromise=void 0,this.pendingPromiseResolveRef=void 0,this.pendingPromiseRejectRef=void 0,void 0!==e&&(this.logger.debug("resolving promise"),e(t))},t.prototype.rejectUrl=function(t){this.logger.debug("aborting");var e=this.pendingPromiseRejectRef;this.url=void 0,this.pendingPromise=void 0,this.pendingPromiseResolveRef=void 0,this.pendingPromiseRejectRef=void 0,void 0!==e&&(this.logger.debug("rejecting promise"),e(t))},t.prototype.resetUrl=function(){this.logger.debug("resetting url"),this.url=void 0},t}();e.TrouterUrlPromise=i},function(t,e,n){(function(t,n){o=n.exports,i=void 0===t?window:t,o.version="0.9.6",o.protocol=1,o.transports=[],o.j=[],o.sockets={},o.connect=function(t,e){var n,r,s=o.util.parseUri(t);i&&i.location&&(s.protocol=s.protocol||i.location.protocol.slice(0,-1),s.host=s.host||(i.document?i.document.domain:i.location.hostname),s.port=s.port||i.location.port),n=o.util.uniqueUri(s);var c={host:s.host,secure:"https"==s.protocol,port:s.port||("https"==s.protocol?443:80),query:s.query||""};return o.util.merge(c,e),!c["force new connection"]&&o.sockets[n]||(r=new o.Socket(c)),!c["force new connection"]&&r&&(o.sockets[n]=r),r=r||o.sockets[n],c["skipped handshake data"]?r.of(""):r.of(s.path.length>1?s.path:"")};var o,i,r,s,c,a,u,h,d,l,p,g,f,v,m,y,T,S=n.exports;r=void 0!==S?S:n.exports,s=void 0===t?window:t,c=r.util={},a=/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,u=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],c.parseUri=function(t){for(var e=a.exec(t||""),n={},o=14;o--;)n[u[o]]=e[o]||"";return n},c.uniqueUri=function(t){var e=t.protocol,n=t.host,o=t.port;return"document"in s?(n=n||document.domain,o=o||("https"==e&&"https:"!==document.location.protocol?443:document.location.port)):(n=n||"localhost",o||"https"!=e||(o=443)),(e||"http")+"://"+n+":"+(o||80)},c.query=function(t,e){var n=c.chunkQuery(t||""),o=[];for(var i in c.merge(n,c.chunkQuery(e||"")),n)n.hasOwnProperty(i)&&o.push(i+"="+n[i]);return o.length?"?"+o.join("&"):""},c.chunkQuery=function(t){for(var e,n={},o=t.split("&"),i=0,r=o.length;i<r;++i)(e=o[i].split("="))[0]&&(n[e[0]]=e[1]);return n},h=!1,c.load=function(t){if("document"in s&&"complete"===document.readyState||h)return t();c.on(s,"load",t,!1)},c.on=function(t,e,n,o){t.attachEvent?t.attachEvent("on"+e,n):t.addEventListener&&t.addEventListener(e,n,o)},c.request=function(t){if(t&&"undefined"!=typeof XDomainRequest)return new XDomainRequest;if("undefined"!=typeof XMLHttpRequest&&(!t||c.ua.hasCORS))return new XMLHttpRequest;if(!t)try{return new window[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch(t){}return null},"undefined"!=typeof window&&c.load(function(){h=!0}),c.defer=function(t){if(!c.ua.webkit||"undefined"!=typeof importScripts)return t();c.load(function(){setTimeout(t,100)})},c.merge=function(t,e,n,o){var i,r=o||[],s=void 0===n?2:n;for(i in e)e.hasOwnProperty(i)&&0>c.indexOf(r,i)&&("object"==typeof t[i]&&s?c.merge(t[i],e[i],s-1,r):(t[i]=e[i],r.push(e[i])));return t},c.mixin=function(t,e){c.merge(t.prototype,e.prototype)},c.inherit=function(t,e){function n(){}n.prototype=e.prototype,t.prototype=new n},c.isArray=Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)},c.intersect=function(t,e){for(var n=[],o=t.length>e.length?t:e,i=t.length>e.length?e:t,r=0,s=i.length;r<s;r++)~c.indexOf(o,i[r])&&n.push(i[r]);return n},c.indexOf=function(t,e,n){for(var o=t.length,n=n<0?n+o<0?0:n+o:n||0;n<o&&t[n]!==e;n++);return o<=n?-1:n},c.toArray=function(t){for(var e=[],n=0,o=t.length;n<o;n++)e.push(t[n]);return e},c.ua={},c.ua.hasCORS="undefined"!=typeof XMLHttpRequest&&function(){try{var t=new XMLHttpRequest}catch(t){return!1}return void 0!=t.withCredentials}(),c.ua.webkit="undefined"!=typeof navigator&&/webkit/i.test(navigator.userAgent),function(t,e){function n(){}t.EventEmitter=n,n.prototype.on=function(t,n){return this.$events||(this.$events={}),this.$events[t]?e.util.isArray(this.$events[t])?this.$events[t].push(n):this.$events[t]=[this.$events[t],n]:this.$events[t]=n,this},n.prototype.addListener=n.prototype.on,n.prototype.once=function(t,e){function n(){o.removeListener(t,n),e.apply(this,arguments)}var o=this;return n.listener=e,this.on(t,n),this},n.prototype.removeListener=function(t,n){if(this.$events&&this.$events[t]){var o=this.$events[t];if(e.util.isArray(o)){for(var i=-1,r=0,s=o.length;r<s;r++)if(o[r]===n||o[r].listener&&o[r].listener===n){i=r;break}if(i<0)return this;o.splice(i,1),o.length||delete this.$events[t]}else(o===n||o.listener&&o.listener===n)&&delete this.$events[t]}return this},n.prototype.removeAllListeners=function(t){return this.$events&&this.$events[t]&&(this.$events[t]=null),this},n.prototype.listeners=function(t){return this.$events||(this.$events={}),this.$events[t]||(this.$events[t]=[]),e.util.isArray(this.$events[t])||(this.$events[t]=[this.$events[t]]
1),this.$events[t]},n.prototype.emit=function(t){if(!this.$events)return!1;var n=this.$events[t];if(!n)return!1;var o=Array.prototype.slice.call(arguments,1);if("function"==typeof n)n.apply(this,o);else{if(!e.util.isArray(n))return!1;for(var i=n.slice(),r=0,s=i.length;r<s;r++)i[r].apply(this,o)}return!0}}(void 0!==S?S:n.exports,void 0!==S?S:n.parent.exports),function(t,e){if(e&&e.parse)return t.JSON={parse:e.parse,stringify:e.stringify};throw Error("JSON not available")}(void 0!==S?S:n.exports,"undefined"!=typeof JSON?JSON:void 0),d=void 0!==S?S:n.exports,l=void 0!==S?S:n.parent.exports,g=(p=d.parser={}).packets=["disconnect","connect","heartbeat","message","json","event","ack","error","noop"],f=p.reasons=["transport not supported","client not handshaken","unauthorized"],v=p.advice=["reconnect"],m=l.JSON,y=l.util.indexOf,p.encodePacket=function(t){var e=y(g,t.type),n=t.id||"",o=t.endpoint||"",i=t.ack,r=null;switch(t.type){case"error":var s=t.reason?y(f,t.reason):"",c=t.advice?y(v,t.advice):"";""===s&&""===c||(r=s+(""!==c?"+"+c:""));break;case"message":""!==t.data&&(r=t.data);break;case"event":var a={name:t.name};t.args&&t.args.length&&(a.args=t.args),r=m.stringify(a);break;case"json":r=m.stringify(t.data);break;case"connect":t.qs&&(r=t.qs);break;case"ack":r=t.ackId+(t.args&&t.args.length?"+"+m.stringify(t.args):"")}var u=[e,n+("data"==i?"+":""),o];return null!=r&&u.push(r),u.join(":")},p.encodePayload=function(t){var e="";if(1==t.length)return t[0];for(var n=0,o=t.length;n<o;n++)e+="�"+t[n].length+"�"+t[n];return e},T=/([^:]+):([0-9]+)?(\+)?:([^:]+)?:?([\s\S]*)?/,p.decodePacket=function(t){var e=t.match(T);if(!e)return{};var n=e[2]||"",t=e[5]||"",o={type:g[e[1]],endpoint:e[4]||""};switch(n&&(o.id=n,e[3]?o.ack="data":o.ack=!0),o.type){case"error":var e=t.split("+");o.reason=f[e[0]]||"",o.advice=v[e[1]]||"";break;case"message":o.data=t||"";break;case"event":try{var i=m.parse(t);o.name=i.name,o.args=i.args}catch(t){}o.args=o.args||[];break;case"json":try{o.data=m.parse(t)}catch(t){}break;case"connect":o.qs=t||"";break;case"ack":var e=t.match(/^([0-9]+)(\+)?(.*)/);if(e&&(o.ackId=e[1],o.args=[],e[3]))try{o.args=e[3]?m.parse(e[3]):[]}catch(t){}break;case"disconnect":o.reason=t}return o},p.decodePayload=function(t){if("�"==t.charAt(0)){for(var e=[],n=1,o="";n<t.length;n++)"�"==t.charAt(n)?(e.push(p.decodePacket(t.substr(n+1).substr(0,o))),n+=Number(o)+1,o=""):o+=t.charAt(n);return e}return[p.decodePacket(t)]},function(t,e){function n(t,e){this.socket=t,this.sessid=e,this.connectErrorCallback=void 0,this.isOpened=!1}t.Transport=n,e.util.mixin(n,e.EventEmitter),n.prototype.onData=function(t){if(this.clearCloseTimeout(),(this.socket.connected||this.socket.connecting||this.socket.reconnecting)&&this.setCloseTimeout(),""!==t){var n=e.parser.decodePayload(t);if(n&&n.length)for(var o=0,i=n.length;o<i;o++)this.onPacket(n[o])}return this},n.prototype.onPacket=function(t){return this.socket.setHeartbeatTimeout(),"heartbeat"==t.type?this.onHeartbeat():("connect"==t.type&&""==t.endpoint&&this.onConnect(),"error"==t.type&&"reconnect"==t.advice&&(this.isOpened=!1),this.socket.onPacket(t),this)},n.prototype.setCloseTimeout=function(){if(!this.closeTimeout){var t=this;this.closeTimeout=setTimeout(function(){t.onDisconnect()},this.socket.closeTimeout)}},n.prototype.onDisconnect=function(){return this.close&&this.isOpened&&this.close(),this.clearTimeouts(),this.socket.onDisconnect(),this},n.prototype.onConnect=function(){return this.socket.onConnect(),this.connectErrorCallback=void 0,this},n.prototype.clearCloseTimeout=function(){this.closeTimeout&&(clearTimeout(this.closeTimeout),this.closeTimeout=null)},n.prototype.clearTimeouts=function(){this.clearCloseTimeout(),this.reopenTimeout&&clearTimeout(this.reopenTimeout)},n.prototype.packet=function(t){this.send(e.parser.encodePacket(t))},n.prototype.onHeartbeat=function(t){this.packet({type:"heartbeat"})},n.prototype.onOpen=function(){this.isOpened=!0,this.clearCloseTimeout(),this.socket.onOpen()},n.prototype.onClose=function(){this.isOpened=!1,this.socket.onClose(),this.onDisconnect()},n.prototype.prepareUrl=function(t){var n=this.socket.options;if(n["skipped handshake data"])return n.rewriteUrlForProxy(n["skipped handshake data"].websocketUrl+(t||""));var o=this.scheme()+"://"+n.host+":"+n.port+"/"+n.resource+"/"+e.protocol+"/"+this.name+"/"+this.sessid+(t||"");return n.rewriteUrlForProxy(o)},n.prototype.ready=function(t,e){e.call(this)},n.prototype.clearEventHandlers=function(){return this}}(void 0!==S?S:n.exports,void 0!==S?S:n.parent.exports),function(t,e,n){function o(t){if(this.options={port:80,secure:!1,document:"document"in n&&document,resource:"socket.io",transports:e.transports.slice(),"connect timeout":1e4,"try multiple transports":!0,reconnect:!0,"reconnection delay":500,"reconnection limit":1/0,"reopen delay":3e3,"max reconnection attempts":10,"sync disconnect on unload":!0,"auto connect":!0,"flash policy port":10843},e.util.merge(this.options,t),this.connected=!1,this.open=!1,this.connecting=!1,this.reconnecting=!1,this.namespaces={},this.buffer=[],this.doBuffer=!1,this.disconnected=!1,this.options["sync disconnect on unload"]&&(!this.isXDomain()||e.util.ua.hasCORS)){var o=this;e.util.on(n,"unload",function(){o.disconnectSync()},!1)}this.options["auto connect"]&&this.connect()}function i(){}t.Socket=o,e.util.mixin(o,e.EventEmitter),o.prototype.of=function(t){return this.namespaces[t]||(this.namespaces[t]=new e.SocketNamespace(this,t),""!==t&&this.namespaces[t].packet({type:"connect"})),this.namespaces[t]},o.prototype.publish=function(){var t;for(var e in this.emit.apply(this,arguments),this.namespaces)this.namespaces.hasOwnProperty(e)&&(t=this.of(e)).$emit.apply(t,arguments)},o.prototype.handshake=function(t){function n(e){e instanceof Error?o.onError(e.message):t.a
1pply(null,e.split(":"))}var o=this,r=this.options;if(!o.disconnected){var s=r.rewriteUrlForProxy(["http"+(r.secure?"s":"")+":/",r.host+":"+r.port,r.resource,e.protocol,e.util.query(this.options.query,"t="+ +new Date)].join("/"));if(this.isXDomain()&&!e.util.ua.hasCORS){var c=document.getElementsByTagName("script")[0],a=document.createElement("script");a.src=s+"&jsonp="+e.j.length,c.parentNode.insertBefore(a,c),e.j.push(function(t){n(t),a.parentNode.removeChild(a)})}else{var u=e.util.request();u.open("GET",s,!0);var h=this.options.requestHeaders;void 0!==h&&Object.keys(h).forEach(function(t){u.setRequestHeader(t,h[t])}),u.onreadystatechange=function(){4!=u.readyState||(u.onreadystatechange=i,200==u.status?n(u.responseText):o.reconnecting||o.onError(u.responseText))},u.send(null)}}},o.prototype.getTransport=function(t){for(var n,o=t||this.transports,i=0;n=o[i];i++)if(e.Transport[n]&&e.Transport[n].check(this)&&(!this.isXDomain()||e.Transport[n].xdomainCheck()))return new e.Transport[n](this,this.sessionid);return null},o.prototype.connect=function(t){if(this.connecting||this.disconnected)return this;var n=this,o=function(o,i,r,s){function c(){if(!n.connected&&!n.disconnected){if(n.connecting=!1,clearTimeout(n.connectTimeoutTimer),n.options["try multiple transports"]){for(;n.remainingTransports.length>0&&n.remainingTransports.splice(0,1)[0]!=n.transport.name;);n.remainingTransports.length?a(n.remainingTransports):n.publish("connect_failed")}else n.publish("connect_failed")}}function a(t){if(n.transport&&(n.transport.clearTimeouts(),n.transport.clearEventHandlers()),n.transport=n.getTransport(t),!n.transport||n.disconnected)return n.publish("connect_failed");n.transport.ready(n,function(){n.connecting=!0,n.publish("connecting",n.transport.name),n.transport.open(c),n.options["connect timeout"]&&(n.connectTimeoutTimer=setTimeout(function(){c()},n.options["connect timeout"]))})}n.sessionid=o,n.closeTimeout=1e3*r+2e3,n.heartbeatTimeout=1e3*i+2e3,n.transports=s?e.util.intersect(s.split(","),n.options.transports):n.options.transports,n.setHeartbeatTimeout(),n.remainingTransports=n.transports.slice(0),a(n.transports),n.once("connect",function(){clearTimeout(n.connectTimeoutTimer),t&&"function"==typeof t&&t()})};if(this.options["skipped handshake data"]){var i=this.options["skipped handshake data"];o("v4c-"+(new Date).getTime(),i.timeout,i.timeout,"websocket")}else this.handshake(o);return this},o.prototype.setHeartbeatTimeout=function(){clearTimeout(this.heartbeatTimeoutTimer);var t=this;this.heartbeatTimeoutTimer=setTimeout(function(){t.transport.onClose()},this.heartbeatTimeout)},o.prototype.packet=function(t){return this.connected&&!this.doBuffer?this.transport.packet(t):this.buffer.push(t),this},o.prototype.setBuffer=function(t){this.doBuffer=t,!t&&this.connected&&this.buffer.length&&(this.transport.payload(this.buffer),this.buffer=[])},o.prototype.disconnect=function(){return(this.connected||this.connecting)&&(this.open&&this.of("").packet({type:"disconnect"}),this.onDisconnect("booted")),this.disconnected=!0,this},o.prototype.disconnectSync=function(){var t=e.util.request(),n=this.resource+"/"+e.protocol+"/"+this.sessionid;t.open("GET",n,!0),this.onDisconnect("booted")},o.prototype.isXDomain=function(){var t=n.location.port||("https:"==n.location.protocol?443:80);return this.options.host!==n.location.hostname||this.options.port!=t},o.prototype.onConnect=function(){this.connected||(this.connected=!0,this.connecting=!1,this.doBuffer||this.setBuffer(!1),this.emit("connect"))},o.prototype.onOpen=function(){this.open=!0},o.prototype.onClose=function(){this.open=!1,clearTimeout(this.heartbeatTimeoutTimer)},o.prototype.onPacket=function(t){this.of(t.endpoint).onPacket(t)},o.prototype.onError=function(t){t&&t.advice&&"reconnect"===t.advice&&(this.connected||this.connecting)&&(this.disconnect(),this.options.reconnect&&this.reconnect()),this.publish("error",t&&t.reason?t.reason:t)},o.prototype.onDisconnect=function(t){var e=this.connected,n=this.connecting;this.connected=!1,this.connecting=!1,this.open=!1,(e||n)&&(this.transport.close(),this.transport.clearTimeouts(),e?(this.publish("disconnect",t),"booted"!=t&&this.options.reconnect&&!this.reconnecting&&this.reconnect()):this.publish("close_during_connecting",t))},o.prototype.reconnect=function(){function t(){if(n.connected){for(var t in n.namespaces)n.namespaces.hasOwnProperty(t)&&""!==t&&n.namespaces[t].packet({type:"connect"});n.publish("reconnect",n.transport.name,n.reconnectionAttempts)}clearTimeout(n.reconnectionTimer),n.removeListener("connect_failed",e),n.removeListener("connect",e),n.reconnecting=!1,delete n.reconnectionAttempts,delete n.reconnectionDelay,delete n.reconnectionTimer,delete n.redoTransports,n.options["try multiple transports"]=i}function e(){if(n.reconnecting)return n.connected?t():n.connecting&&n.reconnecting?n.reconnectionTimer=setTimeout(e,1e3):void(n.reconnectionAttempts++>=o?n.redoTransports?(n.publish("reconnect_failed"),t()):(n.on("connect_failed",e),n.options["try multiple transports"]=!0,n.transport=n.getTransport(),n.redoTransports=!0,n.connect()):(n.reconnectionDelay<r&&(n.reconnectionDelay*=2),n.c
1onnect(),n.publish("reconnecting",n.reconnectionDelay,n.reconnectionAttempts),n.reconnectionTimer=setTimeout(e,n.reconnectionDelay)))}this.reconnecting=!0,this.reconnectionAttempts=0,this.reconnectionDelay=this.options["reconnection delay"];var n=this,o=this.options["max reconnection attempts"],i=this.options["try multiple transports"],r=this.options["reconnection limit"];this.options["try multiple transports"]=!1,this.reconnectionTimer=setTimeout(e,this.reconnectionDelay),this.on("connect",e)}}(void 0!==S?S:n.exports,void 0!==S?S:n.parent.exports,void 0===t?window:t),function(t,e){function n(t,e){this.socket=t,this.name=e||"",this.flags={},this.json=new o(this,"json"),this.ackPackets=0,this.acks={}}function o(t,e){this.namespace=t,this.name=e}t.SocketNamespace=n,e.util.mixin(n,e.EventEmitter),n.prototype.$emit=e.EventEmitter.prototype.emit,n.prototype.of=function(){return this.socket.of.apply(this.socket,arguments)},n.prototype.packet=function(t){return t.endpoint=this.name,this.socket.packet(t),this.flags={},this},n.prototype.send=function(t,e){var n={type:this.flags.json?"json":"message",data:t};return"function"==typeof e&&(n.id=++this.ackPackets,n.ack=!0,this.acks[n.id]=e),this.packet(n)},n.prototype.emit=function(t){var e=Array.prototype.slice.call(arguments,1),n=e[e.length-1],o={type:"event",name:t};return"function"==typeof n&&(o.id=++this.ackPackets,o.ack="data",this.acks[o.id]=n,e=e.slice(0,e.length-1)),o.args=e,this.packet(o)},n.prototype.disconnect=function(){return""===this.name?this.socket.disconnect():(this.packet({type:"disconnect"}),this.$emit("disconnect")),this},n.prototype.onPacket=function(t){function n(){o.packet({type:"ack",args:e.util.toArray(arguments),ackId:t.id})}var o=this;switch(t.type){case"connect":this.$emit("connect");break;case"disconnect":""===this.name?this.socket.onDisconnect(t.reason||"booted"):this.$emit("disconnect",t.reason||"");break;case"message":case"json":var i=["message",t.data];"data"==t.ack?i.push(n):t.ack&&this.packet({type:"ack",ackId:t.id}),this.$emit.apply(this,i);break;case"event":var i=[t.name].concat(t.args);"data"==t.ack&&i.push(n),this.$emit.apply(this,i);break;case"ack":this.acks[t.ackId]&&(this.acks[t.ackId].apply(this,t.args),delete this.acks[t.ackId]);break;case"error":t.advice?this.socket.onError(t):"unauthorized"==t.reason?this.$emit("connect_failed",t.reason):this.$emit("error",t.reason)}},o.prototype.send=function(){this.namespace.flags[this.name]=!0,this.namespace.send.apply(this.namespace,arguments)},o.prototype.emit=function(){this.namespace.flags[this.name]=!0,this.namespace.emit.apply(this.namespace,arguments)}}(void 0!==S?S:n.exports,void 0!==S?S:n.parent.exports),function(t,e,n){function o(t){e.Transport.apply(this,arguments)}function i(){}t.websocket=o,e.util.inherit(o,e.Transport),o.prototype.name="websocket",o.prototype.open=function(t){var o,i=e.util.query(this.socket.options.query),r=this;return this.connectErrorCallback=t,o||(o=n.MozWebSocket||n.WebSocket),this.websocket=new o(this.prepareUrl(i)),this.websocket.onopen=function(){r.onOpen(),r.socket.setBuffer(!1)},this.websocket.onmessage=function(t){r.onData(t.data)},this.websocket.onclose=function(){r.onClose(),r.socket.setBuffer(!0)},this.websocket.onerror=function(t){r.onError(t)},this},o.prototype.send=function(t){return this.websocket.send(t),this},o.prototype.payload=function(t){for(var e=0,n=t.length;e<n;e++)this.packet(t[e]);return this},o.prototype.close=function(){return this.websocket.close(),this},o.prototype.onError=function(t){void 0!==this.connectErrorCallback&&(this.connectErrorCallback(),this.connectErrorCallback=void 0),this.socket.onError(t)},o.prototype.scheme=function(){return this.socket.options.secure?"wss":"ws"},o.check=function(){return"WebSocket"in n&&!("__addTask"in WebSocket)||"MozWebSocket"in n},o.xdomainCheck=function(){return!0},o.prototype.clearEventHandlers=function(){return this.websocket&&(this.websocket.onopen=this.websocket.onmessage=this.websocket.onclose=this.websocket.onerror=i),this},e.transports.push("websocket")}(void 0!==S?S.Transport:n.exports,void 0!==S?S:n.parent.exports,void 0===t?window:t),function(t,e,n){function o(t){t&&e.Transport.apply(this,arguments)}function i(){}t.XHR=o,e.util.inherit(o,e.Transport),o.prototype.open=function(){return this.socket.setBuffer(!1),this.onOpen(),this.get(),this.setCloseTimeout(),this},o.prototype.payload=function(t){for(var n=[],o=0,i=t.length;o<i;o++)n.push(e.parser.encodePacket(t[o]));this.send(e.parser.encodePayload(n))},o.prototype.send=function(t){return this.post(t),this},o.prototype.post=function(t){var e=this;
1this.socket.setBuffer(!0),this.sendXHR=this.request("POST"),n.XDomainRequest&&this.sendXHR instanceof XDomainRequest?this.sendXHR.onload=this.sendXHR.onerror=function(){this.onload=i,e.socket.setBuffer(!1)}:this.sendXHR.onreadystatechange=function(){4==this.readyState&&(this.onreadystatechange=i,200==this.status?(clearTimeout(this.ackTimeoutTimer),e.socket.setBuffer(!1)):e.onClose())},this.sendXHR.send(t),e.sendXHR.ackTimeoutTimer=setTimeout(function(){e.onClose()},e.socket.options.ackTimeoutMs)},o.prototype.close=function(){return this.onClose(),this},o.prototype.request=function(t){var n=e.util.request(this.socket.isXDomain()),o=e.util.query(this.socket.options.query,"t="+ +new Date);n.open(t||"GET",this.prepareUrl(o),!0);var i=this.socket.options.requestHeaders;if(void 0!==i&&Object.keys(i).forEach(function(t){n.setRequestHeader(t,i[t])}),"POST"==t)try{n.setRequestHeader?n.setRequestHeader("Content-type","text/plain;charset=UTF-8"):n.contentType="text/plain"}catch(t){}return n},o.prototype.scheme=function(){return this.socket.options.secure?"https":"http"},o.check=function(t,o){try{var i=e.util.request(o),r=n.XDomainRequest&&i instanceof XDomainRequest,s=(t&&t.options&&t.options.secure?"https:":"http:")!=n.location.protocol;if(i&&(!r||!s))return!0}catch(t){}return!1},o.xdomainCheck=function(){return o.check(null,!0)},o.prototype.clearEventHandlers=function(){return this.sendXHR&&(this.sendXH
1R.onreadystatechange=this.sendXHR.onload=i),this}}(void 0!==S?S.Transport:n.exports,void 0!==S?S:n.parent.exports,void 0===t?window:t),function(t,e,n){function o(){e.Transport.XHR.apply(this,arguments)}function i(){}t["xhr-polling"]=o,e.util.inherit(o,e.Transport.XHR),e.util.merge(o,e.Transport.XHR),o.prototype.name="xhr-polling",o.prototype.open=function(t){return this.connectErrorCallback=t,e.Transport.XHR.prototype.open.call(this),!1},o.prototype.get=function(){if(this.isOpened){var t=this;this.xhr=this.request(),n.XDomainRequest&&this.xhr instanceof XDomainRequest?(this.xhr.onload=function(){t.connectErrorCallback=void 0,this.onload=i,this.onerror=i,t.onData(this.responseText),t.get()},this.xhr.onerror=function(){t.onClose(),void 0!==t.connectErrorCallback&&(t.connectErrorCallback(),t.connectErrorCallback=void 0)}):this.xhr.onreadystatechange=function(){4==this.readyState&&(this.onreadystatechange=i,200==this.status?(t.connectErrorCallback=void 0,t.onData(this.responseText),t.get()):(t.onClose(),void 0!==t.connectErrorCallback&&(t.connectErrorCallback(),t.connectErrorCallback=void 0)))},this.xhr.send(null)}},o.prototype.onClose=function(){if(e.Transport.XHR.prototype.onClose.call(this),this.xhr){this.xhr.onreadystatechange=this.xhr.onload=this.xhr.onerror=i;try{this.xhr.abort()}catch(t){}this.xhr=null}},o.prototype.ready=function(t,n){var o=this;e.util.defer(function(){n.call(o)})},o.prototype.clearEventHandlers=function(){return e.Transport.XHR.prototype.clearEventHandlers.call(this),this.xhr&&(this.xhr.onreadystatechange=this.xhr.onload=this.xhr.onerror=i),this},e.transports.push("xhr-polling")}(void 0!==S?S.Transport:n.exports,void 0!==S?S:n.parent.exports,void 0===t?window:t),e.io=S}).call(e,n(13),n(14)(t))},function(t,e){var n;n=function(){return this}();try{n=n||Function("return this")()||(0,eval)("this")}catch(t){"object"==typeof window&&(n=window)}t.exports=n},function(t,e){t.exports=function(t){return t.webpackPolyfill||(t.deprecate=function(){},t.paths=[],t.children||(t.children=[]),Object.defineProperty(t,"loaded",{enumerable:!0,get:function(){return t.l}}),Object.defineProperty(t,"id",{enumerable:!0,get:function(){return t.i}}),t.webpackPolyfill=1),t}},function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.ConnectionTracker=e.Properties=e.TrackerStep=e.ClientEventName=e.ResponseData=void 0;var o,i,r=n(3),s=n(1),c=n(0);e.ResponseData=function(t){this.id=t,this.status=200,this.headers={},this.body=""},(o=i||(e.ClientEventName=i={})).Connected="trouter_js_client_connected",o.Disconnected="trouter_js_client_disconnected",o.Error="trouter_js_client_error",o.Progress="trouter_js_client_progress",o.Response="trouter_js_client_response",o.Request="trouter_js_client_request",o.CheckConnection="trouter_js_client_check_connection",o.Registration="trouter_js_client_registration",o.Unregistration="trouter_js_client_unregistration";var a=function(t,e,n,o,i){this.stepName=t,this.operation=e,this.delta=n,this.ts=o,this.error=i};e.TrackerStep=a,e.Properties=function(){};var u=function(){this.numberOfPingReplies=0,this.connectedTimestamp=0,this.isNewUrl=!1,this.transportType="",this.connectionNumber=0},h=function(){this.enabled=!1,this.numberOfStepsToMaintain=40,this.logHealthCheckError=!1,this.sendProgressTimeoutSecs=55,this.logSendPingError=!1,this.maxBackoffInMs=12e4,this.trouter_js_client_connected=!1,this.trouter_js_client_disconnected=!1,this.trouter_js_client_error=!1,this.trouter_js_client_progress=!1,this.trouter_js_client_response=!1,this.trouter_js_client_request=!1,this.trouter_js_client_registration=!1,this.trouter_js_client_unregistration=!1,this.trouter_js_client_check_connection=!0},d=function(){function t(t,e,n,o,i,s,a){this.clientId=e,this.clientInfo=n,this.getServerState=o,this.endpointId=i,this.clientCorrelationID=s,this.environment=a,this.logger=new c.Logger("ConnectionTracker",t),this.clientCorrelationID=void 0!==s?s:"",this.steps=[],this.connectionAttempt=0,this.totalStepCount=0,this.beginTimestamp=new r.Timespan,this.eventLogSettings=new h,this.connectedInfo=new u}return t.prototype.enable=function(t){this.eventLogSettings.enabled=!0,this.eventLogger=t},t.prototype.disable=function(){this.eventLogSettings.enabled=!1},t.prototype.sendProgress=function(t){this.steps.length>0&&this.sendTelemetry(i.Progress,t,this.steps)},t.prototype.cancelProgressTimer=function(){void 0!==this.progressTimeout&&(clearTimeout(this.progressTimeout),this.progressTimeout=void 0)},t.prototype.resetProgressSendTimer=function(){var t=this;this.cancelProgressTimer(),void 0!==this.eventLogSettings.sendProgressTimeoutSecs&&this.eventLogSettings.sendProgressTimeoutSecs>0&&(this.progressTimeout=setTimeout(function(){t.sendProgress({reason:"timeout",timeoutSecs:t.eventLogSettings.sendProgressTimeoutSecs})},1e3*this.eventLogSettings.sendProgressTimeoutSecs))},t.prototype.setConnectedInfo=function(t,e){this.connectedInfo.numberOfPingReplies=0,this.connectedInfo.connectedTimestamp=Date.now(),this.connectedInfo.isNewUrl=t,this.connectedInfo.transportType=e,++this.connectedInfo.connectionNumber},t.prototype.clearConnectedInfo=function(){this.connectedInfo.numberOfPingReplies=0,this.connectedInfo.connectedTimestamp=0,this.connectedInfo.isNewUrl=!0,this.connectedInfo.transportType=""},t.prototype.copyProperties=function(t,e){for(var n=0,o=Object.keys(e);n<o.length;n++){var i=o[n];
1void 0!==e[i]&&(t[i.replace(/-/g,"_")]={value:e[i]})}},t.prototype.increasePingResponseCount=function(){++this.connectedInfo.numberOfPingReplies},t.prototype.sendTelemetry=function(t,e,n){try{if(!0===this.eventLogSettings.enabled&&!0===this.eventLogSettings[t]&&void 0!==this.eventLogger){var o=this.getServerState(),i={name:t,properties:{connectionAttempt:{value:this.connectionAttempt},epid:{value:this.endpointId},clientCorrelationID:{value:this.clientCorrelationID},steps:{value:(0,r.toJson)(n)},clientID:{value:this.clientId},eventVersion:{value:3},environment:{value:this.environment},cv:{value:s.CLIENT_VERSION},ua:{value:this.clientInfo.ua},connectionId:{value:o.connectionId},connectedClientId:{value:o.connectedClientId},domId:{value:o.domId},url:{value:o.unsecureUrl},surl:{value:o.url},ttlInSecs:{value:o.getRemainingTtlInSec()},numberOfPingReplies:{value:this.connectedInfo.numberOfPingReplies},connectedTimestamp:{value:this.connectedInfo.connectedTimestamp},isNewUrl:{value:this.connectedInfo.isNewUrl},transportType:{value:this.connectedInfo.transportType},connectionNumber:{value:this.connectedInfo.connectionNumber}}};this.copyProperties(i.properties,e),this.eventLogger.logEvent(i)}}catch(e){this.logger.warn("error in sending event ".concat(t,": ").concat((0,r.toJson)(e)))}},t.prototype.createStep=function(t,e,n){return new a(t,e,this.beginTimestamp.duration,Date.now(),n)},t.prototype.addStep=function(t,e,n){if(!1!==this.eventLogSettings.enabled&&(0===this.steps.length&&this.beginTimestamp.reset(),this.steps.push(this.createStep(t,e,n)),++this.totalStepCount,void 0!==this.eventLogSettings.numberOfStepsToMaintain&&this.steps.length>this.eventLogSettings.numberOfStepsToMaintain)){var o=this.steps.slice(0);this.steps.length=0,this.sendTelemetry(i.Progress,{reason:"flush"},o)}},t.prototype.trackStart=function(t){this.addStep(t,"start")},t.prototype.trackEnd=function(t){this.addStep(t,"end")},t.prototype.trackError=function(t,e,n,o){void 0===n&&(n=!0),"health"===t&&!0!==this.eventLogSettings.logHealthCheckError||"ping"===t&&!1===this.eventLogSettings.logSendPingError||(void 0===o&&(o="error"),!0===n&&this.addStep(t,o,e),this.sendTelemetry(i.Error,{},[this.createStep(t,o,e)]))},t.prototype.trackProgress=function(t,e){this.addStep(t,e)},t.prototype.trackConnected=function(t,e){this.setConnectedInfo(t,e);var n=this.steps.slice(0),o=this.totalStepCount,r=this.beginTimestamp.duration;this.steps.length=0,this.totalStepCount=0,this.sendTelemetry(i.Connected,{stepCount:n.length,totalStepCount:o,connectionEstablishmentMs_Total:r},n),this.cancelProgressTimer()},t.prototype.getSessionLength=function(){return Date.now()-this.connectedInfo.connectedTimestamp},t.prototype.trackDisconnected=function(t){t.sessionLengthMS=this.getSessionLength(),this.sendTelemetry(i.Disconnected,t,[]),this.resetProgressSendTimer()},t.prototype.trackNewConnection=function(){++this.connectionAttempt},t.prototype.trackRequest=function(t,e){var n={};void 0!==e&&(n.hasError=!0,n.error=e);try{if(t){n.requestID=t.id,n.httpMethod=t.method,n.url=t.url,n.bodyLength=t.body.length,n.shortUrl=t.shortUrl,n.requestTimeStamp=t.startTS,n.correlationVector=t.correlationVector;for(var o=t.headers,s=0,c=Object.keys(o);s<c.length;s++){var a=c[s];n[a]=o[a]}}}catch(t){n.hasError=!0,n.error="".concat(n.error," error creating request context ").concat((0,r.toJson)(t))}this.sendTelemetry(i.Request,n,[])},t.prototype.trackResponse=function(t,e,n,o){var s={};void 0!==o&&(s.hasError=!0,s.error=o);try{if(s.responseTimestamp=void 0!==n?n.sentTS:Date.now(),t){s.requestID=t.id,s.httpMethod=t.method,s.shortUrl=t.shortUrl,s.correlationVector=t.correlationVector;for(var c=t.headers,a=0,u=Object.keys(c);a<u.length;a++){var h=u[a];s[h]=c[h]}}n&&(s.latencyMS=e,s.responseCode=n.status,s.responseLength=n.body.length)}catch(t){s.hasError=!0,s.error="".concat(s.error," error creating response context ").concat((0,r.toJson)(t))}this.sendTelemetry(i.Response,s,[])},t.prototype.sendResponseError=function(t,e,n){this.trackResponse(e,void 0,n,t)},t.prototype.close=function(){this.sendProgress({reason:"closed"}),this.steps.length=0,this.cancelProgressTimer()},t.prototype.mergeSettings=function(t){if(t){this.eventLogSettings.numberOfStepsToMaintain=Math.min(40,Math.max(10,void 0!==t.numberOfStepsToMaintain?t.numberOfStepsToMaintain:0));var e=Math.min(3600,Math.max(55,void 0!==t.sendProgressTimeoutSecs?t.sendProgressTimeoutSecs:0));this.eventLogSettings.logHealthCheckError=t.logHealthCheckError,this.eventLogSettings.logSendPingError=t.logSendPingError;for(var n=0,o=Object.keys(i).map(function(t){return i[t]});n<o.length;n++){var r=o[n];void 0!==t[r]&&(this.eventLogSettings[r]=t[r])}this.eventLogSettings.sendProgressTimeoutSecs!==e&&(this.eventLogSettings.sendProgressTimeoutSecs=e,this.resetProgressSendTimer())}},t}();e.ConnectionTracker=d}
1,function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.DisconnectReason=void 0;var o=function(){function t(t,e,n){this.reason=t,this.claims=e,this.details=n}return t.fromRawReason=function(e,n){if(""===e||"dup"===e)return new t(e);try{var o=JSON.parse(e);return"object"!=typeof o||void 0===o.reason?(null==n||n.error("invalid disconnect reason format"),new t("unknown",void 0,e)):new t(o.reason,o.claims,o.details)}catch(n){return new t("disconnect",void 0,e)}},t.fromSocketIoEventData=function(e,n){return"string"==typeof n?new t(e,void 0,n):void 0},t.prototype.toTelemetryString=function(){return"socketerror"===this.reason||"reconnecterror"===this.reason||"disconnect"===this.reason?this.details:this.reason},t}();e.DisconnectReason=o},function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.ExponentialBackoff=void 0;var o=function(){function t(t,e,n){void 0===n&&(n={tolerance:2,minimumWaitMs:1e4}),this.logger=t,this.maxBackoffInMs=e,this.gapDetectionSettings=n,this.backoffId=0,this.backoffCount=0}return t.calculateNextBackoffMs=function(t,e){var n=1e3*Math.pow(2,t)*(1+.4*(Math.random()-.5));return Math.min(e,n=Math.round(n))},t.prototype.setMaxBackoffMs=function(t){this.maxBackoffInMs=t},t.prototype.backoff=function(e,n){var o=this;if(void 0!==this.timerHandle&&(this.logger.debug("Clearing current back off"),clearTimeout(this.timerHandle),this.timerHandle=void 0),void 0!==this.previousCompleteTime){var i=Date.now()-this.previousCompleteTime;i>this.maxBackoffInMs*this.gapDetectionSettings.tolerance&&i>this.gapDetectionSettings.minimumWaitMs&&(this.logger.info("Back off for ".concat(e," with ID ").concat(this.backoffId," will be reset due to a lot of time having passed since the previous backoff (").concat(i," ms)")),this.backoffCount=0,this.previousCompleteTime=void 0)}var r=t.calculateNextBackoffMs(this.backoffCount,this.maxBackoffInMs);this.backoffId++,this.backoffCount++,this.logger.info("Backing off ".concat(e," for ").concat(r," milliseconds with ID ").concat(this.backoffId)),this.callback=function(t,i){(function(t,e,n){if(void 0===t||void 0===e)return!1;var o=Date.now()-t;return o>e*n.tolerance&&o>n.minimumWaitMs})(t,i,o.gapDetectionSettings)&&(o.logger.info("Back off for ".concat(e," with ID ").concat(o.backoffId," will be reset due to the wait (").concat(Date.now()-(null!=t?t:0)," ms) being longer than expected (").concat(i," ms)")),o.backoffCount=0),o.logger.info("Back off for ".concat(e," with ID ").concat(o.backoffId," complete, invoking handler")),o.timerHandle=void 0,o.callback=void 0,o.previousCompleteTime=Date.now(),n()};var s=Date.now();this.timerHandle=setTimeout(function(){var t;return null===(t=o.callback)||void 0===t?void 0:t.call(o,s,r)},r)},t.prototype.reset=function(){void 0!==this.timerHandle&&(this.logger.debug("Resetting back off with ID ".concat(this.backoffId)),clearTimeout(this.timerHandle),this.timerHandle=void 0,this.callback=void 0),this.backoffCount=0},t.prototype.expediteIfPending=function(){if(this.backoffCount=0,void 0!==this.timerHandle){this.logger.debug("Expediting back off with ID ".concat(this.backoffId)),clearTimeout(this.timerHandle),this.timerHandle=void 0;var t=this.callback;this.callback=void 0,t&&t()}},t}();e.ExponentialBackoff=o},function(t,e,n){var o=this&&this.__spreadArray||function(t,e,n){if(n||2==arguments.length)for(var o,i=0,r=e.length;i<r;i++)!o&&i in e||(o||(o=Array.prototype.slice.call(e,0,i)),o[i]=e[i]);return t.concat(o||Array.prototype.slice.call(e))};Object.defineProperty(e,"__esModule",{value:!0}),e.LoggingManagerConsumer=e.RegistrationEnforcer=void 0;var i=n(6),r=function(){function t(t,e,n){this.wrapped=t,this.shouldConnectionDependOnRegistration=e,this.shouldHoldBackEvents=n,this.isRegistered=!1,this.heldBackEvents=[]}return t.prototype.onDownstreamRequest=function(t,e,n){this.passIfRegisteredOrNotNeeded("onDownstreamRequest",t,e,n)},t.prototype.onConnected=function(t){this.passIfRegisteredOrNotNeeded("onConnected",t)},t.prototype.onRegistered=function(t){this.isRegistered=!0,this.wrapped.onRegistered(t),this.fireHeldBackEvents()},t.prototype.onUnregistered=function(t){this.isRegistered=!1,this.wrapped.onUnregistered(t),t.getState()===i.State.Connected&&this.shouldConnectionDependOnRegistration()&&t.forceReconnectDueToNoRegistration()},t.prototype.onReconnecting=function(t){this.wrapped.onReconnecting(t)},t.prototype.onReconnectIsRequired=function(t,e,n){this.wrapped.onReconnectIsRequired(t,e,n)},t.prototype.onDisconnected=function(t){this.isRegistered=!1,this.dropHeldBackEvents(),this.wrapped.onDisconnected(t)},t.prototype.onTerminalError=function(t){this.wrapped.onTerminalError(t)},t.prototype.onConnectionParametersUpdated=function(t){this.wrapped.onConnectionParametersUpdated(t)},t.prototype.onTrouterMessageLost=function(t){this.passIfRegisteredOrNotNeeded("onTrouterMessageLost",t)},t.prototype.onUserActivityStateAccepted=function(t){this.passIfRegisteredOrNotNeeded("onUserActivityStateAccepted",t)},t.prototype.onAudiencesSetResolved=function(t,e){this.passIfRegisteredOrNotNeeded("onAudiencesSetResolved",t,e)},t.prototype.getState=function(){return this.wrapped.getState()},t.prototype.holdBackEvent=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];this.heldBackEvents.push({kind:t,args:e})},t.prototype.passIfRegisteredOrNotNeeded=function(t){for(var e,n=[],i=1;i<arguments.length;i++)n[i-1]=arguments[i];var r=this.shouldConnectionDependOnRegistration(),s=this.shouldHoldBackEvents();r&&s||this.fireHeldBackEvents(r?function(t){return"onConnected"!==t.kind}:void 0),this.isRegistered||!r||!1===s&&"onConnected"!==t?(e=this.wrapped)[t].apply(e,n):this.holdBackEvent.apply(this,o([t],n,!1))},t.prototype.fireHeldBackEvents=function(t){for(var e,n=0,o=this.heldBackEvents;n<o.length;n++){var i=o[n];(void 0===t||t(i))&&(e=this.wrapped)[i.kind].apply(e,i.args)}this.heldBackEvents=void 0===t?[]:this.heldBackEvents.filter(function(e){return!t(e)})},t.prototype.dropHeldBackEvents=function(){this.heldBackEvents=[]},t}();e.RegistrationEnforcer=r;var s=function(){function t(t,e,n,o){this.wrapped=t,this.prefix=e,this.logger=n,this.onEventAction=o}return t.prototype.onEvent=function(t,e){var n;void 0!==this.onEventAction?this.onEventAction(t,e):(null!==(n=this.logger)&&void 0!==n?n:console).log("".concat(this.prefix," TracingEnforcer: ").concat(t,"(").concat(e,")"))},t.prototype.onDownstreamRequest=function(t,e,n){this.onEvent("onDownstreamRequest",JSON.stringify({request:e,response:n}
1)),this.wrapped.onDownstreamRequest(t,e,n)},t.prototype.onConnected=function(t){this.onEvent("onConnected",t.getState().toString()),this.wrapped.onConnected(t)},t.prototype.onRegistered=function(t){this.onEvent("onRegistered",t.getState().toString()),this.wrapped.onRegistered(t)},t.prototype.onUnregistered=function(t){this.onEvent("onUnregistered",t.getState().toString()),this.wrapped.onUnregistered(t)},t.prototype.onReconnecting=function(t){this.onEvent("onReconnecting",t.getState().toString()),this.wrapped.onReconnecting(t)},t.prototype.onReconnectIsRequired=function(t,e,n){this.onEvent("onReconnectIsRequired",JSON.stringify({connection:t.getState().toString(),useConnectParamsFromCache:e,reason:n})),this.wrapped.onReconnectIsRequired(t,e,n)},t.prototype.onDisconnected=function(t){this.onEvent("onDisconnected",t.getState().toString()),this.wrapped.onDisconnected(t)},t.prototype.onTerminalError=function(t){this.onEvent("onTerminalError",JSON.stringify({connection:t})),this.wrapped.onTerminalError(t)},t.prototype.onConnectionParametersUpdated=function(t){this.onEvent("onConnectionParametersUpdated",JSON.stringify({connectParams:t})),this.wrapped.onConnectionParametersUpdated(t)},t.prototype.onTrouterMessageLost=function(t){this.onEvent("onTrouterMessageLost",JSON.stringify({flowTags:t})),this.wrapped.onTrouterMessageLost(t)},t.prototype.onUserActivityStateAccepted=function(t){this.onEvent("onUserActivityStateAccepted",JSON.stringify({cv:t})),this.wrapped.onUserActivityStateAccepted(t)},t.prototype.onAudiencesSetResolved=function(t,e){this.onEvent("onAudiencesSetResolved",JSON.stringify({audienceSubscriptionsResponse:t,cv:e})),this.wrapped.onAudiencesSetResolved(t,e)},t.prototype.getState=function(){return this.wrapped.getState()},t}();e.LoggingManagerConsumer=s},function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.TrouterManagerFsm=void 0;var o=n(2),i=n(4),r=n(0),s=n(7),c=function(){function t(t,e){this.worker=e,this.state=i.TrouterManagerState.Unknown,this.logger=new r.Logger("ManagerFsm",t)}return t.prototype.start=function(){this.state===i.TrouterManagerState.Unknown?(this.setState(i.TrouterManagerState.Disconnected),this.worker.forceStopLingeringConnection(),this.worker.startFirstConnection()):(this.logger.info("start called in state '".concat(i.TrouterManagerState[this.state],"', expediting pending backoffs, if any")),this.worker.expediteBackoffOnConnections())},t.prototype.stop=function(t){this.state!==i.TrouterManagerState.Unknown?(this.setState(i.TrouterManagerState.Unknown),this.worker.stopFirstC
1onnection(!0===t),this.worker.stopSecondConnection(!0===t)):this.showIgnored("stop")},t.prototype.getState=function(){switch(this.state){case i.TrouterManagerState.Unknown:case i.TrouterManagerState.Connected:case i.TrouterManagerState.Disconnected:case i.TrouterManagerState.Switching:return this.state;case i.TrouterManagerState.TerminalError:return o.TrouterState.Disconnected}},t.prototype.getInternalState=function(){return this.state},t.prototype.onConnected=function(t){this.state===i.TrouterManagerState.Disconnected&&t?this.worker.doesSecondConnectionExist()?this.setState(i.TrouterManagerState.Switching):(this.setState(i.TrouterManagerState.Connected),this.worker.dispatchConnected()):this.showIgnored("onConnected(".concat(t,")"))},t.prototype.onRegistered=function(t){this.state!==i.TrouterManagerState.Disconnected||t?this.state!==i.TrouterManagerState.Switching||t?this.state===i.TrouterManagerState.Disconnected&&t&&(this.setState(i.TrouterManagerState.Connected),this.worker.dispatchConnected()):(this.setState(i.TrouterManagerState.Connected),this.worker.switchConnections(),this.worker.stopSecondConnectionDelayed(),this.worker.dispatchConnected()):(this.setState(i.TrouterManagerState.Connected),this.worker.switchConnections(),this.worker.stopSecondConnection(!0),this.worker.dispatchConnected()),this.worker.dispatchRegistrationState(!0)},t.prototype.onUnregistered=function(t){t&&this.worker.dispatchRegistrationState(!1)},t.prototype.onReconnecting=function(t){(this.state===i.TrouterManagerState.Connected||this.state===i.TrouterManagerState.Switching)&&t?(this.setState(i.TrouterManagerState.Disconnected),this.worker.dispatchDisconnected()):this.showIgnored("onReconnecting(".concat(t,")"))},t.prototype.onReconnectionRequired=function(t,e,n){this.state===i.TrouterManagerState.Connected&&t?(this.setState(i.TrouterManagerState.Switching),this.worker.startSecondConnection(e)):this.state===i.TrouterManagerState.Disconnected&&t?this.worker.startSecondConnection(e):this.state===i.TrouterManagerState.Switching&&t&&n===s.ReconnectReason.Configuration?(this.logger.debug("onReconnectionRequired: switch requested while already in Switching state"),this.worker.stopSecondConnection(!0),this.worker.startSecondConnection(e)):this.showIgnored("onReconnectionRequired(".concat(t,")"))},t.prototype.onDisconnected=function(t){this.state==i.TrouterManagerState.Unknown&&t?this.worker.dispatchDisconnected():this.state==i.TrouterManagerState.Switching&&t?(this.worker.switchConnections(),this.worker.stopSecondConnection(!1),this.setState(i.TrouterManagerState.Disconnected),this.worker.dispatchDisconnected()):this.showIgnored("onDisconnected(".concat(t,")"))},t.prototype.onTerminalError=function(){this.setState(i.TrouterManagerState.TerminalError),this.worker.dispatchTerminalError()},t.prototype.showIgnored=function(t){this.logger.info("Ignoring event '".concat(t,"' in state '").concat(i.TrouterManagerState[this.state],"'"))},t.prototype.setState=function(t){if(this.logger.info("Switching from state '".concat(i.TrouterManagerState[this.state],"' to state '").concat(i.TrouterManagerState[t],"'")),this.state===t)return void this.logger.error("Attempt to switch to the current state '".concat(i.TrouterManagerState[t],"'"));this.state=t},t}();e.TrouterManagerFsm=c},function(t,e,n){function o(t,e,n){var o,r,s,c,a,u,h,d,l,p,g=function(n){return t.proxyUrlRewrite?(e.info("Using rewritten URL for proxy"),t.proxyUrlRewrite(n)):n};return{clientInfo:{ua:t.trouterSettings.productName,v:t.trouterSettings.version},ioOptions:{ackTimeoutMs:5e3,rewriteUrlForProxy:g},clientCorrelationID:t.trouterSettings.sessionId,environment:t.trouterSettings.environment,telemetrySettings:function(t,e){if(!e)return t;var n=i(i({},t),{enabled:e.TelemetryEnabled});return void 0!==e.ClientTelemetryEventEnabled&&(n=i(i({},n),e.ClientTelemetryEventEnabled)),n}(t.telemetryConfig.settings,n),eventLogger:t.telemetryConfig.eventLogger,endpointId:t.trouterSettings.registrationId,trouterUrl:(null==n?void 0:n.TrouterConnectionUrl)||t.trouterSettings.trouterServiceUrl,registration:t.trouterSettings.registrarServiceUrl?{registrarUrl:t.trouterSettings.registrarServiceUrl,registrationId:null!==(o=t.trouterSettings.registrationId)&&void 0!==o?o:"",pnhAppId:null!==(r=t.trouterSettings.pnhAppId)&&void 0!==r?r:"",platform:null!==(s=t.trouterSettings.platform)&&void 0!==s?s:"",pnhTemplateKey:null!==(c=t.trouterSettings.pnhTemplate)&&void 0!==c?c:"",platformUIVersion:null!==(a=t.trouterSettings.platformUIVersion)&&void 0!==a?a:"",productC
1ontext:t.trouterSettings.pnhProductContext||void 0,context:null!==(u=t.trouterSettings.pnhContext)&&void 0!==u?u:"",registrarTtlSec:(null!==(h=t.trouterSettings.maxRegistrationTimeInMs)&&void 0!==h?h:0)/1e3}:void 0,connectionDependsOnRegistration:void 0===t.trouterSettings.registrarServiceUrl?function(){return!1}:null!==(d=t.trouterSettings.connectionDependsOnRegistration)&&void 0!==d?d:function(){return!1},delayEventsUntilRegistered:null!==(l=t.trouterSettings.delayEventsUntilRegistered)&&void 0!==l?l:function(){return!1},timeoutOptions:i({connectionTimeoutMs:t.trouterSettings.trouterConnectTimeoutInMs||3e4,fetchTimeoutMs:1e4,pingTimeoutMs:4e4,pongTimeoutMs:5e3,maxBackoffMs:"TeamsCDL"===t.trouterSettings.productName?3e5:3e4,requestTimeoutMs:5e3,userActivityResponseTimeoutMs:1e4},t.trouterSettings.timeoutOptions),incallTimeoutOptions:i({connectionTimeoutMs:1e4,fetchTimeoutMs:5e3,pingTimeoutMs:5e3,pongTimeoutMs:2e3,maxBackoffMs:"TeamsCDL"===t.trouterSettings.productName?3e5:1e4,requestTimeoutMs:5e3,userActivityResponseTimeoutMs:1e4},t.trouterSettings.incallTimeoutOptions),incallModeTimeoutMs:null!==(p=t.trouterSettings.incallModeTimeoutMs)&&void 0!==p?p:0,lingeringConnectionDelayMs:6e4,userActivitySecondResendDelayMs:t.trouterSettings.userActivitySecondResendDelayMs||1e4,duplicateDisconnectThresholdMs:1e4,connectionCache:t.connectionCache,registrationStateCallback:t.registrationStateCallbackForAcsDoNotUse,rewriteUrlForProxy:g,retryLimitOnTokenFetch:t.trouterSettings.retryLimitOnTokenFetch,extraConnectionHeaders:t.trouterSettings.extraConnectionHeaders,expediteBackoffOnStartMinimumDelayMs:1e4,toJSON:function(){return i(i({},this),{connectionCache:this.connectionCache?{}:this.connectionCache})}}}var i=this&&this.__assign||function(){return(i=Object.assign||function(t){for(var e,n=1,o=arguments.length;n<o;n++)for(var i in e=arguments[n])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t}).apply(this,arguments)},r=this&&this.__awaiter||function(t,e,n,o){return new(n||(n=Promise))(function(i,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){var e;t.done?i(t.value):((e=t.value)instanceof n?e:new n(function(t){t(e)})).then(s,c)}a((o=o.apply(t,e||[])).next())})},s=this&&this.__generator||function(t,e){function n(n){return function(a){return function(n){if(o)throw TypeError("Generator is already executing.");for(;s&&(s=0,n[0]&&(c=0)),c;)try{if(o=1,i&&(r=2&n[0]?i.return:n[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,n[1])).done)return r;switch(i=0,r&&(n=[2&n[0],r.value]),n[0]){case 0:case 1:r=n;break;case 4:return c.label++,{value:n[1],done:!1};case 5:c.label++,i=n[1],n=[0];continue;case 7:n=c.ops.pop(),c.trys.pop();continue;default:if(!(r=(r=c.trys).length>0&&r[r.length-1])&&(6===n[0]||2===n[0])){c=0;continue}if(3===n[0]&&(!r||n[1]>r[0]&&n[1]<r[3])){c.label=n[1];break}if(6===n[0]&&c.label<r[1]){c.label=r[1],r=n;break}if(r&&c.label<r[2]){c.label=r[2],c.ops.push(n);break}r[2]&&c.ops.pop(),c.trys.pop();continue}n=e.call(t,c)}catch(t){n=[6,t],i=0}finally{o=r=0}if(5&n[0])throw n[1];return{value:n[0]?n[1]:void 0,done:!0}}([n,a])}}var o,i,r,s,c={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:n(0),throw:n(1),return:n(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s};Object.defineProperty(e,"__esModule",{value:!0}),e.replaceTrouterUrlBase=e.getTrouterServiceVersion=e.createTrouterService=e.TrouterService=e.UserActivityState=e.TrouterState=void 0;var c=n(1),a=n(2);Object.defineProperty(e,"TrouterState",{enumerable:!0,get:function(){return a.TrouterState}}),Object.defineProperty(e,"UserActivityState",{enumerable:!0,get:function(){return a.UserActivityState}});var u=n(0),h=n(8),d=n(9),l=n(10),p=n(11),g=function(){function t(t){this.logProvider=t,this.stateChangedListeners=[],this.logger=new u.Logger("Trouter",t),this.trouterUrlPromise=new p.TrouterUrlPromise(t),this.messageHandlers=new h.MessageHandlerRegistry(t),this.listeners={},this.connectionInfo=null,this.logger.info("Created TrouterService version ".concat(c.CLIENT_VERSION))}return t.prototype.start=function(t){if(this.logger.info("Start"),!t.skypeTokenProvider&&!t.authTokenProvider)throw Error("no token provider has been configured, either skypeTokenProvider or authTokenProvider must be populated");t.skypeTokenProvider&&!t.trouterSettings.disableInternalSkypeTokenCache&&(t.skypeTokenProvider=(0,d.addCacheAsBackupTo)(t.skypeTokenProvider)),this.trouterCfg=t;var e,n=o(t,this.logger,this.ecsCfg);!1===t.internalEnableV4cProtocol&&(n.forceV4aProtocol=!0);var i=function(t,e){var n,o=this;return function(i){return r(o,void 0,void 0,function(){var o,r,c;return s(this,function(s){switch(s.label){case 0:o=new Date,r=setInterval(function(){var e=Math.round((Date.now()-o.getTime())/6e4);t.warn("Note: Trouter auth token request promise from ".concat(o.toISOString()," has not been resolved for ").concat(e," minutes. The client is blocked from operating properly"))},3e5),s.label=1;case 1:return s.trys.push([1,,3,4]),[4,e(i)];case 2:return c=s.sent(),i.needFresh&&c.token===n&&t.error("API violation: Trouter auth token provider got a request with needRefresh=true, but returned the same token as last time anyway. Please fix the host app"),n=c.token,[2,c];case 3:return clearInterval(r),[7];case 4:return[2]}})})}}(this.logger,null!==(e=t.authTokenProvider)&&void 0!==e?e:function(t){var e=this;return function(n){return r(e,void 0,void 0,function(){var e;return s(this,function(o){switch(o.label){case 0:return e={},[4,t(n.needFresh)];case 1:return[2,(e.token=o.sent(),e.tokenType="skype",e)]}})})}}(t.skypeTokenProvider));void 0===this.trouterServer&&(this.trouterServer=new l.TrouterManager(this.logProvider,n,i,void 0===t.authTokenProvider,this)),void 0!==this.pendingActivityState&&(this.trouterServer.setUserActivityState(this.pendingActivityState[0],this.pendingActivityState[1]),this.pendingActivityState=void 0),this.trouterServer.start()},t.prototype.stop=function(t){this.logger.info("close connection"),this.trouterUrlPromise.rejectUrl(Error("TrouterService is stopped")),void 0!==this.trouterServer&&this.trouterServer.stop(t)},t.prototype.setEcsConfig=function(t){return r(this,void 0,void 0,function(){var e=this;return s(this,function(n){return[2,new Promise(function(n){if(e.ecsCfg=t.TrouterJScriptClient,e.logger.info("Setting ECS configuration to ".concat(JSON.stringify(e.ecsCfg))),void 0!==e.trouterServer&&void 0!==e.trouterCfg){var i=o(e.trouterCfg,e.logger,e.ecsCfg);e.trouterServer.configure(i)}n()})]})})},t.prototype.checkConnection=function(t){void 0!==this.trouterServer&&this.trouterServer.checkConnection(null!=t&&t)},t.prototype.resendRegistration=function(){return r(this,void 0,void 0,function(){return s(this,function(t){if(!this.trouterServer)throw Error("resendRegistration called too early");return[2,this.trouterServer.resendRegistration()]})})},t.prototype.registerListener=function(t,e){return""===e||!e.startsWith("/")||e.includes("?")||e.includes("#")?(this.logger.error("Listener path '".concat(e,"' is not val
1id")),!1):this.listeners[e]?(this.logger.error("Another listener is already registered for path '".concat(e,"'")),!1):(this.listeners[e]=t,this.logger.debug("Listener for path '".concat(e,"' registered")),this.connectionInfo&&t.onTrouterConnected(this.connectionInfo.baseEndpointUrl+e,this.connectionInfo),!0)},t.prototype.unregisterListener=function(t){for(var e=[],n=0,o=Object.keys(this.listeners);n<o.length;n++){var i=o[n];this.listeners[i]===t&&e.push(i)}if(0===e.length)return!1;for(var r=0;r<e.length;r++){var i=e[r];delete this.listeners[i]}return this.logger.debug("Listener for path(s) '".concat(e.join("', '"),"' unregistered")),!0},t.prototype.onTrouterConnected=function(t,e){this.logger.debug("Trouter is now connected");for(var n=0,o=Object.keys(this.listeners);n<o.length;n++){var i=o[n];try{this.listeners[i].onTrouterConnected(e.baseEndpointUrl+i,e)}catch(t){this.logger.error("Listener '".concat(i,"' threw an exception from onTrouterConnected(): ").concat(t))}}this.connectionInfo=e,this.trouterUrlPromise.resolveUrl(t),this.notifyStateChanged(a.TrouterState.Connected,{url:t,getRemainingTtlInSec:function(){return e.connectionTtlSec}})},t.prototype.onTrouterDisconnected=function(){this.logger.debug("Trouter is now disconnected"),this.connectionInfo=null;for(var t=0,e=Object.keys(this.listeners);t<e.length;t++){var n=e[t],o=this.listeners[n];if(o.onTrouterDisconnected)try{o.onTrouterDisconnected()}catch(t){this.logger.error("Listener '".concat(n,"' threw an exception from onTrouterDisconnected(): ").concat(t))}}this.notifyStateChanged(a.TrouterState.Disconnected)},t.prototype.onTrouterRequest=function(t,e){for(var n="",o=0,i=Object.keys(this.listeners);o<i.length;o++){var r=i[o];t.path.startsWith(r)&&r.length>n.length&&(n=r)}if(""===n)this.tryMessageHandlers(t,e)||(e.status=404,e.headers={"Trouter-Responder":"ClientLib"},e.send());else try{this.listeners[n].onTrouterRequest(t,e)}catch(t){this.logger.error("Listener '".concat(n,"' threw an exception from onTrouterRequest(): ").concat(t)),e.status=500,e.headers={"Trouter-Responder":"ClientLib"},e.send()}},t.prototype.onTrouterMessageLoss=function(t){this.logger.info("onTrouterMessageLoss called with tags [".concat(t,"]"));for(var e=!0,n=0,o=Object.keys(this.listeners);n<o.length;n++){var i=o[n],r=this.listeners[i];if(r.onTrouterMessageLoss)try{e=r.onTrouterMessageLoss(t)&&e,void 0===e&&(this.logger.error("Listener '".concat(i,"' did not return a boolean value from onTrouterMessageLoss()")),e=!1)}catch(t){this.logger.error("Listener '".concat(i,"' threw an exception from onTrouterMessageLoss(): ").concat(t)),e=!1}}return e},t.prototype.onTrouterUserActivityStateAccepted=function(t){this.logger.debug("onTrouterUserActivityStateAccepted cv: ".concat(t));for(var e=0,n=Object.keys(this.listeners);e<n.length;e++){var o=n[e],i=this.listeners[o];if(i.onTrouterUserActivityStateAccepted)try{i.onTrouterUserActivityStateAccepted(t)}catch(t){this.logger.error("Listener '".concat(o,"' threw an exception from onTrouterUserActivityStateAccepted(): ").concat(t))}}},t.prototype.onAudiencesSetResolved=function(t,e){this.logger.debug("onAudiencesSetResolved cv: ".concat(e));for(var n=0,o=Object.keys(this.listeners);n<o.length;n++){var i=o[n],r=this.listeners[i];if(r.onAudiencesSetResolved)try{r.onAudiencesSetResolved(t,e)}catch(t){this.logger.error("Listener '".concat(i,"' threw an exception from onAudienceSubscribed(): ").concat(t))}}},t.prototype.setUserActivityState=function(t,e){if(t!==a.UserActivityState.Active&&t!==a.UserActivityState.Inactive)throw Error("setUserActivityState called with unsupported value ".concat(t));this.logger.info("setUserActivityState called with value ".concat(a.UserActivityState[t])),this.trouterServer&&this.state()!==a.TrouterState.Unknown?this.trouterServer.setUserActivityState(t,e):(this.pendingActivityState=[t,e],this.logger.warn("setUserActivityState called before start() or after stop()"))},t.prototype.setAudienceSubscriptions=function(t,e){if(t.audienceSubscriptions.length>1)throw Error("Only singular audience subscription is supported");if(this.trouterServer&&this.state()!==a.TrouterState.Unknown)return this.trouterServer.setAudienceSubscriptionsAsync(t,15e3,e);throw Error("audience subscribe called before start() or after stop()")},t.prototype.state=function(){return void 0!==this.trouterServer?this.trouterServer.getState():a.TrouterState.Unknown},t.prototype.isInTerminalState=function(){return void 0!==this.trouterServer&&this.trouterServer.isInTerminalState()},t.prototype.reportStateInfo=function(){return void 0===this.trouterServer?"":this.trouterServer.reportStateInfo()},t.prototype.getServerState=function(){if(void 0!==this.trouterServer)return this.trouterServer.getServerState()},t.prototype.getTrouterUrlAsync=function(){return void 0!==this.trouterServer?this.trouterUrlPromise.getPromise():Promise.reject(Error("TrouterService has not been started"))},t.prototype.onStateChanged=function(t){if(this.logger.info("onStateChanged called"),void 0===t)this.stateChangedListeners=this.stateChangedListeners.filter(function(t){return void 0===t.wrappedCallback});else{this.offStateChanged(t);var e=function(e,n){t(e,n?n.url:"")};e.wrappedCallback=t,this.stateChangedListeners.push(e)}},t.prototype.offStateChanged=function(t){this.logger.info("offStateChanged called");var e=this.stateChangedListeners.length;return this.stateChangedListeners=this.stateChangedListeners.filter(function(e){return e.wrappedCallback!==t}),e>this.stateChangedListeners.length},t.prototype.addCallback=function(t){this.logger.info("addListener called"),-1===this.stateChangedListeners.indexOf(t,0)&&void 0!==t&&this.stateChangedListeners.push(t)},t.prototype.removeCallback=function(t){this.logger.info("removeListener called");var e=this.stateChangedListeners.indexOf(t,0);return e>-1&&(this.stateChangedListeners.splice(e,1),!0)},t.prototype.registerMessageHandler=function(t){this.logger.info("registerMessageHandler is called"),this.messageHandlers.register(t)},t.prototype.clearMessageHandlers=function(){this.logger.info("clearMessageHandlers is called"),this.messageHandlers.clear()},t.prototype.notifyStateChanged=function(t,e){var n=this;this.logger.info("notifyStateChanged called, will forward to ".concat(this.stateChangedListeners.length," listeners")),this.stateChangedListeners.forEac
1h(function(o){try{o(t,e)}catch(t){n.logger.error("Error in callback ".concat(t))}})},t.prototype.tryMessageHandlers=function(t,e){if(!this.messageHandlers.active())return!1;var n,o=null;try{o=(n=JSON.parse(t.body))&&(n.evt||n.eventId)||null}catch(t){}var i={eventId:o,url:(this.connectionInfo?this.connectionInfo.baseEndpointUrl:"")+t.path,body:n,rawBody:t.body,headers:t.headers},r=this.messageHandlers.handleMessage(i);return!!r.isHandled&&(e.status=r.resultCode,r.responseHeaders&&(e.headers=r.responseHeaders),r.responseBody&&(e.body=r.responseBody),e.send(),!0)},t}();e.TrouterService=g,e.createTrouterService=function(t){return new g(t)},e.getTrouterServiceVersion=function(){return c.CLIENT_VERSION},e.replaceTrouterUrlBase=function(t,e){var n=t.indexOf("://");if(n>=0){var o=t.indexOf("/",n+3);if(o>=0)return e+t.substr(o)}return""}},function(t,e){t.exports=l}])});h(p);var g=d(function(t,e){var n,o,i,r;Object.defineProperty(e,"__esModule",{value:!0}),e.PACKAGE_VERSION=e.CONFIG_API_VERSION=e.EudbCountries=e.CloudPrefix=e.CloudType=e.MAX_NUMBER_OF_TOKEN_FETCH_RETRIES=void 0,e.MAX_NUMBER_OF_TOKEN_FETCH_RETRIES=3,(i=n||(e.CloudType=n={})).Public="Public",i.GccHigh="GCC High",i.Dod="DoD",(r=o||(e.CloudPrefix=o={})).OrgId="orgid",r.Acs="acs",r.Spool="spool",r.GccHigh="gcch",r.GccHighAcs="gcch-acs",r.Dod="dod",r.DodAcs="dod-acs",e.EudbCountries=["europe","france","germany","norway","switzerland","sweden"],e.CONFIG_API_VERSION="2024-09-01",e.PACKAGE_VERSION="1.0.0-beta.29"});h(g),g.PACKAGE_VERSION,g.CONFIG_API_VERSION,g.EudbCountries,g.CloudPrefix,g.CloudType,g.MAX_NUMBER_OF_TOKEN_FETCH_RETRIES;var f=d(function(t,e){var n=u&&u.__awaiter||function(t,e,n,o){return new(n||(n=Promise))(function(i,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){var e;t.done?i(t.value):((e=t.value)instanceof n?e:new n(function(t){t(e)})).then(s,c)}a((o=o.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0}),e.isEudbLocation=e.parseTokenCredential=e.base64decode=e.toTelemetrySender=e.toLogProvider=e.toMessageHandler=void 0,e.generateUuid=function(){return(0,r.v4)()};let i=new Map([["chatMessageReceived",200],["typingIndicatorReceived",245],["readReceiptReceived",246],["chatMessageEdited",247],["chatMessageDeleted",248],["chatThreadCreated",257],["chatThreadPropertiesUpdated",258],["chatThreadDeleted",259],["participantsAdded",260],["participantsRemoved",261]]),c="8:orgid:",a="8:dod:",h="8:gcch:",d="8:teamsvisitor:";e.toMessageHandler=(t,e,n,o)=>{let r=i.get(t);return{handleMessage(i){let s=null;if((null==i?void 0:i.rawBody)&&(s=JSON.parse(i.rawBody)),null===s||s.eventId!==r)return;let c=l(t,s,n,o);if(null!==c)return e(c),{isHandled:!0,resultCode:200}}}};let l=(t,e,n,o)=>{if("chatMessageReceived"===t){let t={threadId:e.groupId,sender:p(e.senderId),senderDisplayName:e.senderDisplayName,recipient:p(e.recipientMri),id:e.messageId,createdOn:new Date(e.originalArrivalTime),version:e.version,type:e.messageType,message:e.messageBody,metadata:f(e.acsChatMessageMetadata)||{},attachments:y(f(e.attachments)||[],n,o)};return t}if("chatMessageEdited"===t){let t={threadId:e.groupId,sender:p(e.senderId),senderDisplayName:e.senderDisplayName,recipient:p(e.recipientMri),id:e.messageId,createdOn:new Date(e.originalArrivalTime),version:e.version,message:e.messageBody,editedOn:new Date(e.edittime),type:e.messageType,metadata:f(e.acsChatMessageMetadata)||{},attachments:y(f(e.attachments)||[],n,o)};return t}if("chatMessageDeleted"===t){let t={threadId:e.groupId,sender:p(e.senderId),senderDisplayName:e.senderDisplayName,recipient:p(e.recipientMri),id:e.messageId,createdOn:new Date(e.originalArrivalTime),version:e.version,deletedOn:new Date(e.deletetime),type:e.messageType};return t}if("typingIndicatorReceived"===t){let t={threadId:e.groupId,sender:p(e.senderId),senderDisplayName:e.senderDisplayName,recipient:p(e.recipientMri),version:e.version,receivedOn:new Date(e.originalArrivalTime)};return t}if("readReceiptReceived"===t){let t=JSON.parse(e.messageBody),n=t.consumptionhorizon.split(";"),o={threadId:e.groupId,sender:p(e.senderId),senderDisplayName:"",recipient:p(e.recipientMri),chatMessageId:e.messageId,readOn:new Date(+n[1])};return o}if("chatThreadCreated"===t){let t=JSON.parse(unescape(e.createdBy)),n=JSON.parse(unescape(e.members)),o=JSON.parse(unescape(e.properties)),i={id:p(t.participantId),displayName:t.displayName},r=n.map(t=>({id:p(t.participantId),displayName:t.displayName})),s={threadId:e.threadId,createdOn:new Date(e.createTime),createdBy:i,version:e.version,participants:r,properties:o};return s}if("chatThreadPropertiesUpdated"===t){let t=JSON.parse(unescape(e.editedBy)),n=JSON.parse(unescape(e.properties)),o={id:p(t.participantId),displayName:t.displayName},i={threadId:e.threadId,updatedOn:new Date(e.editTime),updatedBy:o,version:e.version,properties:n};return i}if("chatThreadDeleted"===t){let t=JSON.parse(unescape(e.deletedBy)),n={id:p(t.participantId),displayName:t.displayName},o={threadId:e.threadId,deletedOn:new Date(e.deleteTime),deletedBy:n,version:e.version};return o}if("participantsAdded"===t){let t=JSON.parse(unescape(e.addedBy)),n=JSON.parse(unescape(e.participantsAdded)),o={id:p(t.participantId),displayName:t.displayName},i=n.map(t=>({id:p(t.participantId),displayName:t.displayName,shareHistoryTime:new Date(t.shareHistoryTime)})),r={threadId:e.threadId,addedOn:new Date(e.time),addedBy:o,version:e.version,participantsAdded:i};return r}if("participantsRemoved"===t){let t=JSON.parse(unescape(e.removedBy)),n=JSON.parse(unescape(e.participantsRemoved)),o={id:p(t.participantId),displayName:t.displayName},i=n.map(t=>({id:p(t.participantId),displayName:t.displayName,shareHistoryTime:new Date(t.shareHistoryTime)})),r={threadId:e.threadId,removedOn:new Date(e.time),removedBy:o,version:e.version,participantsRemoved:i};return r}return null};e.toLogProvider=t=>({log:(...e)=>t.info(e),warn:(...e)=>t.warning(e),error:(...e)=>t.error(e),debug:(...e)=>t.verbose(e),info:(...e)=>t.verbose(e)}),e.toTelemetrySender=t=>({logEvent:e=>t.info(e)});let p=t=>t.startsWith(c)?{kind:"microsoftTeamsUser",rawId:t,microsoftTeamsUserId:t.substring(c.length),isA
1nonymous:!1,cloud:"public"}:t.startsWith(a)?{kind:"microsoftTeamsUser",rawId:t,microsoftTeamsUserId:t.substring(a.length),isAnonymous:!1,cloud:"dod"}:t.startsWith(h)?{kind:"microsoftTeamsUser",rawId:t,microsoftTeamsUserId:t.substring(h.length),isAnonymous:!1,cloud:"gcch"}:t.startsWith(d)?{kind:"microsoftTeamsUser",rawId:t,microsoftTeamsUserId:t.substring(d.length),isAnonymous:!0}:t.startsWith("4:")?{kind:"phoneNumber",rawId:t,phoneNumber:t.substring(2)}:t.startsWith("8:acs:")||t.startsWith("8:gcch-acs:")||t.startsWith("8:dod-acs:")||t.startsWith("8:spool:")?{kind:"communicationUser",communicationUserId:t}:{kind:"unknown",id:t},f=t=>{if(null!=t&&""!==t&&"null"!==t&&"{}"!==t&&"[]"!==t)return JSON.parse(t)},v=(t,e,n)=>{let o;try{o=new URL(t),("http:"===o.protocol||"https:"===o.protocol)&&(o=new URL(o.pathname,e))}catch(n){try{o=new URL(t,e)}catch(e){return t}}return o.searchParams.set("api-version",n),o.toString()},m=t=>{let e;try{e=new URL(t)}catch(t){return!1}return"http:"===e.protocol||"https:"===e.protocol},y=(t,e,n)=>(null!=e&&""!==e&&m(e)&&t.filter(t=>"image"===t.attachmentType.toLowerCase()).map(t=>{t.previewUrl&&(t.previewUrl=v(t.previewUrl,e,n)),t.url&&(t.url=v(t.url,e,n))}),t);e.base64decode=t=>s.isNodeLike?o.from(t,"base64").toString():atob(t);let T=t=>{let[,n]=null==t?void 0:t.split(".");if(void 0===n)throw Error("Invalid token");return n=n.replace(/-/g,"+").replace(/_/g,"/"),JSON.parse(decodeURIComponent(escape((0,e.base64decode)(n))))};e.parseTokenCredential=t=>n(void 0,void 0,void 0,function*(){let e=yield t.getToken(),n=null==e?void 0:e.token,o=T(n),i=o.skypeid,r=o.resourceId,s=function(t){let e=t.substring(0,t.indexOf(":"));switch(e){case g.CloudPrefix.OrgId:case g.CloudPrefix.Acs:case g.CloudPrefix.Spool:return g.CloudType.Public;case g.CloudPrefix.GccHigh:case g.CloudPrefix.GccHighAcs:return g.CloudType.GccHigh;case g.CloudPrefix.Dod:case g.CloudPrefix.DodAcs:return g.CloudType.Dod;default:return g.CloudType.Public}}(i),c=o.resourceLocation||"";return{jwtToken:n,acsResourceId:r,identityMri:i,cloudType:s,resourceLocation:c}}),e.isEudbLocation=t=>!!t&&!!g.EudbCountries.find(e=>e===t)});h(f),f.isEudbLocation,f.parseTokenCredential,f.base64decode,f.toTelemetrySender,f.toLogProvider,f.toMessageHandler,f.generateUuid;var v=d(function(t,e){var n=u&&u.__createBinding||(Object.create?function(t,e,n,o){void 0===o&&(o=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,o,i)}:function(t,e,n,o){void 0===o&&(o=n),t[o]=e[n]}),o=u&&u.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),i=u&&u.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var i in t)"default"!==i&&Object.prototype.hasOwnProperty.call(t,i)&&n(e,t,i);return o(e,t),e},r=u&&u.__awaiter||function(t,e,n,o){return new(n||(n=Promise))(function(i,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){var e;t.done?i(t.value):((e=t.value)instanceof n?e:new n(function(t){t(e)})).then(s,c)}a((o=o.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0}),e.RealTimeNotificationConfiguration=e.TrouterConfigClient=void 0;let s=i(c);class h extends s.ServiceClient{constructor(t,e){e||(e={});let n=`azsdk-js-communication-signaling/${g.PACKAGE_VERSION}`,o=e.userAgentOptions&&e.userAgentOptions.userAgentPrefix?`${e.userAgentOptions.userAgentPrefix} ${n}`:`${n}`,i=Object.assign(Object.assign({},e),{userAgentOptions:{userAgentPrefix:o},additionalPolicies:e.additionalPolicies});super(i),this.apiVersion=g.CONFIG_API_VERSION,this.endpoint=t,this.httpClient=(0,a.createDefaultHttpClient)()}fetchServiceUrls(t){return r(this,void 0,void 0,function*(){try{let e=(yield t.getToken()).token,n=(0,a.createPipelineRequest)({url:`${this.endpoint}/chat/config/realTimeNotifications?api-version=${this.apiVersion}`,method:"GET",headers:(0,a.createHttpHeaders)({Authorization:`Bearer ${e}`})}),o=yield this.pipeline.sendRequest(this.httpClient,n);if(200!==o.status||!o.bodyAsText)throw Error(`Failed to fetch service URLs. Status: ${o.status}, Body: ${o.bodyAsText||"No response body"}`);let i=JSON.parse(o.bodyAsText);if(!i.trouterServiceUrl||!i.registrarServiceUrl||!i.cloudType)throw Error("One or more required fields are missing in the response data");return new d(i.trouterServiceUrl,i.registrarServiceUrl,i.cloudType)}catch(t){throw Error(`Error fetching real-time notification configuration from Chat Gateway: ${t.message}`)}})}}e.TrouterConfigClient=h;class d{constructor(t,e,n){this.trouterServiceUrl=t,this.registrarServiceUrl=e,this.cloudType=n}}e.RealTimeNotificationConfiguration=d});h(v),v.RealTimeNotificationConfiguration,v.TrouterConfigClient;var m=d(function(t,e){var n=u&&u.__awaiter||function(t,e,n,o){return new(n||(n=Prom
1ise))(function(i,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){var e;t.done?i(t.value):((e=t.value)instanceof n?e:new n(function(t){t(e)})).then(s,c)}a((o=o.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0}),e.defaultTelemetrySettings=e.createSettings=void 0;let o={version:"1.0.0",registrationId:"",sessionId:"",pnhAppId:"AcsWeb",pnhTemplate:"AcsWeb_Chat_1.8",platform:"SPOOL",platformUIVersion:"0.0.0",environment:"",productName:"acs-chat-web",trouterServiceUrl:"",registrarServiceUrl:"",registrarRefreshTimeoutInMs:35e4,timeoutOptions:{connectionTimeoutMs:2e4,fetchTimeoutMs:1e4,pingTimeoutMs:4e4,pongTimeoutMs:5e3,maxBackoffMs:5e4,requestTimeoutMs:5e3},maxRegistrationTimeInMs:72e5};e.createSettings=(t,e)=>n(void 0,void 0,void 0,function*(){var n;let i=null==e?void 0:e.resourceEndpoint;if(void 0===i)throw Error("'endpoint' cannot be null");let r=Object.assign({},o);r.registrationId=(0,f.generateUuid)(),r.sessionId=(0,f.generateUuid)();let s=new v.TrouterConfigClient(i,e),c=yield s.fetchServiceUrls(t);return r.trouterServiceUrl=`${c.trouterServiceUrl}/v4/a`,r.registrarServiceUrl=`${c.registrarServiceUrl}/v3/registrations`,"int"===c.cloudType&&(r.pnhAppId="cns-e2e-test",r.pnhTemplate="cns-e2e-test:1.8"),r.maxRegistrationTimeInMs=null!==(n=null==e?void 0:e.registrationTimeInMs)&&void 0!==n?n:o.maxRegistrationTimeInMs,r}),e.defaultTelemetrySettings={enabled:!1}});h(m),m.defaultTelemetrySettings,m.createSettings;var y=d(function(t,e){var n,o,i=u&&u.__awaiter||function(t,e,n,o){return new(n||(n=Promise))(function(i,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){var e;t.done?i(t.value):((e=t.value)instanceof n?e:new n(function(t){t(e)})).then(s,c)}a((o=o.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0}),e.CommunicationSignalingClient=e.ConnectionState=void 0,(n=o||(e.ConnectionState=o={}))[n.Unknown=0]="Unknown",n[n.Connected=2]="Connected",n[n.Disconnected=3]="Disconnected",n[n.Switching=9]="Switching",e.CommunicationSignalingClient=class{constructor(t,e,n){this.credential=t,this.logger=e,this.options=n,this.stateChangedListener=null,this.tokenFetchRetries=0,this.trouter=(0,p.createTrouterService)((0,f.toLogProvider)(e))}start(){return i(this,void 0,void 0,function*(){var t,e;if(this.resourceEndpoint=null===(t=this.options)||void 0===t?void 0:t.resourceEndpoint,void 0===this.resourceEndpoint)throw Error("'endpoint' cannot be null");this.gatewayApiVersion=(null===(e=this.options)||void 0===e?void 0:e.gatewayApiVersion)||"2024-03-07",void 0===this.config&&(this.config={trouterSettings:yield(0,m.createSettings)(this.credential,this.options),skypeTokenProvider:t=>i(this,void 0,void 0,function*(){if(t){if(this.tokenFetchRetries+=1,this.tokenFetchRetries>g.MAX_NUMBER_OF_TOKEN_FETCH_RETRIES)throw yield this.stop(!0),Error(`Access token is expired and failed to fetch a valid one after ${g.MAX_NUMBER_OF_TOKEN_FETCH_RETRIES} retries`)}else this.tokenFetchRetries=0;return Promise.resolve((yield this.credential.getToken()).token)}),telemetryConfig:{eventLogger:(0,f.toTelemetrySender)(this.logger),settings:m.defaultTelemetrySettings}}),this.trouter.start(this.config),this.trouter.setUserActivityState(p.UserActivityState.Active)})}stop(t){return i(this,void 0,void 0,function*(){this.trouter.offStateChanged(this.stateChangedListener),this.trouter.clearMessageHandlers(),this.trouter.stop(null!=t?t:this.tokenFetchRetries>g.MAX_NUMBER_OF_TOKEN_FETCH_RETRIES)})}on(t,e){if("connectionChanged"===t){this.trouter.offStateChanged(this.stateChangedListener),this.stateChangedListener=(t,n)=>e(t),this.trouter.onStateChanged(this.stateChangedListener);return}this.trouter.registerMessageHandler((0,f.toMessageHandler)(t,e,this.resourceEndpoint,this.gatewayApiVersion))}}});h(y),y.CommunicationSignalingClient,y.ConnectionState;var T=h(d(function(t,e){var n=u&&u.__createBinding||(Object.create?function(t,e,n,o){void 0===o&&(o=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,o,i)}:function(t,e,n,o){void 0===o&&(o=n),t[o]=e[n]}),o=u&&u.__exportStar||function(t,e){for(var o in t)"default"===o||Object.prototype.hasOwnProperty.call(e,o)||n(e,t,o)};
1Object.defineProperty(e,"__esModule",{value:!0}),o(y,e)}));t.exports=T}}]);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.