UNPKG

@azure/communication-signaling

Version:

Azure Communication Signaling Client

8,987 lines 509 kB
(function (global, factory) {
	typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('crypto'), require('node:util'), require('node:os'), require('node:process'), require('node:stream'), require('net'), require('tls'), require('assert'), require('http'), require('https'), require('url'), require('node:http'), require('node:https'), require('node:zlib')) :
	typeof define === 'function' && define.amd ? define(['crypto', 'node:util', 'node:os', 'node:process', 'node:stream', 'net', 'tls', 'assert', 'http', 'https', 'url', 'node:http', 'node:https', 'node:zlib'], factory) :
	(global = typeof globalThis !== 'undefined' ? globalThis : global || self, (global.Azure = global.Azure || {}, global.Azure.CommmunicationServices = global.Azure.CommmunicationServices || {}, global.Azure.CommmunicationServices.Signaling = factory(global.crypto$1, global.util, global.os, global.process$1, global.node_stream, global.net, global.tls, global.assert, global.http, global.https, global.url, global.http$1, global.https$1, global.zlib)));
})(this, (function (crypto$1, util, os, process$1, node_stream, net, tls, assert, http, https, url, http$1, https$1, zlib) { 'use strict';

	function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

	function _interopNamespace(e) {
		if (e && e.__esModule) return e;
		var n = Object.create(null);
		if (e) {
			Object.keys(e).forEach(function (k) {
				if (k !== 'default') {
					var d = Object.getOwnPropertyDescriptor(e, k);
					Object.defineProperty(n, k, d.get ? d : {
						enumerable: true,
						get: function () { return e[k]; }
					});
				}
			});
		}
		n["default"] = e;
		return Object.freeze(n);
	}

	var util__default = /*#__PURE__*/_interopDefaultLegacy(util);
	var os__namespace = /*#__PURE__*/_interopNamespace(os);
	var process__namespace = /*#__PURE__*/_interopNamespace(process$1);
	var net__default = /*#__PURE__*/_interopDefaultLegacy(net);
	var tls__default = /*#__PURE__*/_interopDefaultLegacy(tls);
	var assert__default = /*#__PURE__*/_interopDefaultLegacy(assert);
	var http__default = /*#__PURE__*/_interopDefaultLegacy(http);
	var https__default = /*#__PURE__*/_interopDefaultLegacy(https);
	var url__default = /*#__PURE__*/_interopDefaultLegacy(url);
	var http__namespace = /*#__PURE__*/_interopNamespace(http$1);
	var https__namespace = /*#__PURE__*/_interopNamespace(https$1);
	var zlib__namespace = /*#__PURE__*/_interopNamespace(zlib);

	var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};

	function unwrapExports (x) {
		return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
	}

	function createCommonjsModule(fn, module) {
		return module = { exports: {} }, fn(module, module.exports), module.exports;
	}

	var tsregistrar = createCommonjsModule(function (module, exports) {
	!function(t,e){module.exports=e();}(commonjsGlobal,function(){return function(t){function e(n){if(r[n])return r[n].exports;var o=r[n]={i:n,l:!1,exports:{}};return t[n].call(o.exports,o,o.exports,e),o.l=!0,o.exports}var r={};return e.m=t,e.c=r,e.i=function(t){return t},e.d=function(t,r,n){e.o(t,r)||Object.defineProperty(t,r,{configurable:!1,enumerable:!0,get:n});},e.n=function(t){var r=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(r,"a",r),r},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=1)}([function(t,e,r){function n(t,e){var r,n=new Promise(function(e,n){fetch(t).then(function(t){void 0!==r&&clearTimeout(r),e(t);}).catch(function(t){void 0!==r&&clearTimeout(r),n(t);});});if(0!==e){var o=new Promise(function(n,o){r=setTimeout(o,e,new Error("Fetch for '".concat(t.url,"' timed out")));});return Promise.race([n,o])}return n}function o(t){try{return JSON.stringify(t)}catch(e){return "Unable to serialize object of type ".concat(typeof t)}}Object.defineProperty(e,"__esModule",{value:!0}),e.Timespan=e.toJson=e.fetchWithTimeout=void 0,e.fetchWithTimeout=n,e.toJson=o;var i=function(){function t(){this.start=Date.now();}return Object.defineProperty(t.prototype,"duration",{get:function(){return Date.now()-this.start},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"startTime",{get:function(){return this.start},enumerable:!1,configurable:!0}),t.prototype.reset=function(){this.start=Date.now();},t}();e.Timespan=i;},function(t,e,r){function n(t,e,r){return new h(t,e,r)}var o=this&&this.__extends||function(){var t=function(e,r){return (t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e;}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);})(e,r)};return function(e,r){function n(){this.constructor=e;}if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r),e.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n);}}(),i=this&&this.__assign||function(){return i=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++){e=arguments[r];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);}return t},i.apply(this,arguments)},s=this&&this.__awaiter||function(t,e,r,n){function o(t){return t instanceof r?t:new r(function(e){e(t);})}return new(r||(r=Promise))(function(r,i){function s(t){try{c(n.next(t));}catch(t){i(t);}}function a(t){try{c(n.throw(t));}catch(t){i(t);}}function c(t){t.done?r(t.value):o(t.value).then(s,a);}c((n=n.apply(t,e||[])).next());})},a=this&&this.__generator||function(t,e){function r(t){return function(e){return n([t,e])}}function n(r){if(o)throw new TypeError("Generator is already executing.");for(;a&&(a=0,r[0]&&(c=0)),c;)try{if(o=1,i&&(s=2&r[0]?i.return:r[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,r[1])).done)return s;switch(i=0,s&&(r=[2&r[0],s.value]),r[0]){case 0:case 1:s=r;break;case 4:return c.label++,{value:r[1],done:!1};case 5:c.label++,i=r[1],r=[0];continue;case 7:r=c.ops.pop(),c.trys.pop();continue;default:if(s=c.trys,!(s=s.length>0&&s[s.length-1])&&(6===r[0]||2===r[0])){c=0;continue}if(3===r[0]&&(!s||r[1]>s[0]&&r[1]<s[3])){c.label=r[1];break}if(6===r[0]&&c.label<s[1]){c.label=s[1],s=r;break}if(s&&c.label<s[2]){c.label=s[2],c.ops.push(r);break}s[2]&&c.ops.pop(),c.trys.pop();continue}r=e.call(t,c);}catch(t){r=[6,t],i=0;}finally{o=s=0;}if(5&r[0])throw r[1];return {value:r[0]?r[1]:void 0,done:!0}}var o,i,s,a,c={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return a={next:r(0),throw:r(1),return:r(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a};Object.defineProperty(e,"__esModule",{value:!0}),e.createRegistrarClient=e.RegistrarClient=void 0;var c=r(0),u=["skype","aad","cae"],l=function(t){function e(e){var r=t.call(this,e)||this;return r.name="CancelationError",r}return o(e,t),e}(Error),f=function(){function t(e,r,n){this.logger=e,this.maxBackoffInMs=r,this.initialDelay=n,this.backoffCount=0,this.id=++t.idCounter;}return t.prototype.delay=function(t){var e=this;if(void 0!==this.timerHandle)throw new Error("Retry sequence logical failure");if(-1===this.backoffCount)return new Promise(function(t,e){e(new l("Cancelled"));});var r=this.calculateNextBackoffMs();return this.backoffCount++,this.logger.info("[RegistrarClient] Backing off ".concat(t," for ").concat(r," milliseconds with ID ").concat(this.id)),new Promise(function(n,o){e.cancelFunc=o,e.timerHandle=setTimeout(function(){e.logger.info("[RegistrarClient] Back off for ".concat(t," with ID ").concat(e.id," complete")),e.timerHandle=void 0,n();},r);})},t.prototype.cancel=function(){void 0!==this.timerHandle&&(this.logger.debug("Resetting back off"),clearTimeout(this.timerHandle),void 0!==this.cancelFunc&&this.cancelFunc(new l("Cancelled"))),this.backoffCount=-1;},t.prototype.calculateNextBackoffMs=function(){var t=1+.4*(Math.random()-.5),e=this.initialDelay*Math.pow(2,this.backoffCount)*t;return e=Math.round(e),Math.min(this.maxBackoffInMs,e)},t.idCounter=0,t}(),h=function(){function t(t,e,r){var n;this.logger=t,this.tokenProvider=e,this.options=r,this.DEFAULT_MAX_RETRIES_FOR_GET_TOKEN=15,this.DEFAULT_MAX_BACKOFF_TIME_IN_MS=3e5,this.backoffs={},this.maxBackOffTime=this.options.maxRetryDelayMs>0?this.options.maxRetryDelayMs:this.DEFAULT_MAX_BACKOFF_TIME_IN_MS,this.maxRetriesForGetToken=void 0===r.maxRetriesForGetToken||null===r.maxRetriesForGetToken?this.DEFAULT_MAX_RETRIES_FOR_GET_TOKEN:r.maxRetriesForGetToken,this.proxyUrlRewrite=null!==(n=r.proxyUrlRewrite)&&void 0!==n?n:function(t){return t};}return t.prototype.setTelemetryLogger=function(t){this.eventLogger=t;},t.prototype.register=function(t,e){return s(this,void 0,void 0,function(){return a(this,function(r){switch(r.label){case 0:return [4,this.performRegistration(t,e,"pr_set_registration")];case 1:return r.sent(),this.cachedRegistrationParams=[t,e],[2]}})})},t.prototype.unregister=function(){return s(this,void 0,void 0,function(){var t;return a(this,function(e){switch(e.label){case 0:return this.logger.info("[RegistrarClient] sending unregister request"),t=new Request(this.proxyUrlRewrite("".concat(this.options.registrarUrl,"/").concat(this.options.registrationId)),{method:"DELETE",mode:"cors",headers:new Headers(i(i({},this.options.extraRegistrationHeaders),{accept:"application/json, text/javascript"}))}),[4,this.callRegistrar(t,"pr_delete_registration")];case 1:return e.sent(),[2]}})})},t.prototype.cancelPendingRequests=function(){var t=this;Object.keys(this.backoffs).forEach(function(e){t.backoffs[e].cancel();}),this.backoffs={};},t.prototype.resendRegistration=function(){return s(this,void 0,void 0,function(){return a(this,function(t){switch(t.label){case 0:if(!this.cachedRegistrationParams)throw new Error("Re-registration failed because there is no registration parameters cached");return [4,this.performRegistration(this.cachedRegistrationParams[0],this.cachedRegistrationParams[1],"pr_resend_registration")];case 1:return t.sent(),[2]}})})},t.prototype.performRegistration=function(t,e,r){return s(this,void 0,void 0,function(){var n,o;return a(this,function(s){switch(s.label){case 0:return this.logger.info("[RegistrarClient] Sending register request"),n={clientDescription:t,registrationId:this.options.registrationId,nodeId:"",transports:e},o=new Request(this.proxyUrlRewrite(this.options.registrarUrl),{method:"POST",mode:"cors",headers:new Headers(i(i({},this.options.extraRegistrationHeaders),{"content-type":"application/json",accept:"application/json, text/javascript"})),body:(0, c.toJson)(n)}),[4,this.callRegistrar(o,r)];case 1:return s.sent(),[2]}})})},t.prototype.startBackoff=function(){var t=new f(this.logger,this.maxBackOffTime,this.options.initialRetryDelayMs);return this.backoffs[t.id]=t,t},t.prototype.stopBackoff=function(t){t.cancel(),delete this.backoffs[t.id];},t.prototype.getToken=function(t){return s(this,void 0,void 0,function(){var e,r,n,o,i,s,c;return a(this,function(a){switch(a.label){case 0:e=this.startBackoff(),r=0,a.label=1;case 1:return a.trys.push([1,3,,8]),this.logger.info("[RegistrarClient] Asking for a new token"),[4,this.tokenProvider({needFresh:!0,supportedTokenTypes:u,wwwAuthenticateHeader:t,purpose:"registrar"})];case 2:return n=a.sent(),this.stopBackoff(e),[2,n];case 3:o=a.sent(),a.label=4;case 4:return a.trys.push([4,6,,7]),(r++,i=JSON.stringify(o),r>this.maxRetriesForGetToken)?(s="[RegistrarClient] getToken retry limit hit. Will not retry now. Error: ".concat(i),this.logger.error(s),this.stopBackoff(e),[2,Promise.reject(s)]):(this.logger.warn("[RegistrarClient] Retrying for a new token. Retry Count: ".concat(r," Error: ").concat(i)),[4,e.delay("Fetching a new token")]);case 5:return a.sent(),[3,8];case 6:throw c=a.sent(),this.stopBackoff(e),c;case 7:return [3,8];case 8:return [3,1];case 9:return [2]}})})},t.prototype.callRegistrar=function(t,e){var r,n,o;return s(this,void 0,void 0,function(){var i,s,l,f,h,p,d,g,y,v,w,k,m,b,R,_;return a(this,function(a){switch(a.label){case 0:return i=this.startBackoff(),[4,this.tokenProvider({needFresh:!1,supportedTokenTypes:u,wwwAuthenticateHeader:void 0,purpose:"registrar"})];case 1:s=a.sent(),this.setTokenHeader(t,s),l=new c.Timespan,f=0,a.label=2;case 2:h=void 0,a.label=3;case 3:return a.trys.push([3,10,15,16]),p=t.clone(),[4,(0, c.fetchWithTimeout)(p,this.options.requestTimeoutMs)];case 4:return h=a.sent(),401!==h.status?[3,8]:++f>this.maxRetriesForGetToken?(d="[RegistrarClient] getSkypeToken retry limit hit. Will not retry now. Request '".concat(t.url,"' failed with ").concat(h.status," ").concat(h.statusText),this.logger.error(d),this.stopBackoff(i),[2,Promise.reject(d)]):(this.logger.warn("[RegistrarClient] Retry Count ".concat(f,". Request '").concat(t.url,"' failed with ").concat(h.status," ").concat(h.statusText)),g=null!==(n=null===(r=h.headers)||void 0===r?void 0:r.get("www-authenticate"))&&void 0!==n?n:void 0,y=this.setTokenHeader,v=[t],[4,this.getToken(g)]);case 5:return y.apply(this,v.concat([a.sent()])),f>1?[4,i.delay("Registrar call retry after 401")]:[3,7];case 6:a.sent(),a.label=7;case 7:return [3,22];case 8:if(h.status>=500&&h.status<600)throw new Error("Fetch for '".concat(t.url,"' failed with ").concat(h.status," ").concat(h.statusText));a.label=9;case 9:return [3,16];case 10:w=a.sent(),this.logger.error("[RegistrarClient] Request failed with ".concat(w)),a.label=11;case 11:return a.trys.push([11,13,,14]),[4,i.delay("Registrar call retry")];case 12:return a.sent(),[3,22];case 13:throw k=a.sent(),this.logger.error("[RegistrarClient] Request cancelled"),this.stopBackoff(i),k;case 14:return [3,16];case 15:return this.sendTelemetryEvent(e,t,h,l),[7];case 16:return this.stopBackoff(i),h.ok?[2,h]:[3,17];case 17:m=void 0,a.label=18;case 18:return a.trys.push([18,20,,21]),R=(b=JSON).stringify,[4,h.json()];case 19:return m=R.apply(b,[a.sent()]),[3,21];case 20:return a.sent(),m="no details",[3,21];case 21:throw _="Fetch for '".concat(t.url,"' failed with ").concat(h.status," ").concat(h.statusText," (").concat(m,", MS-CV: ").concat(null===(o=h.headers)||void 0===o?void 0:o.get("MS-CV"),")"),this.logger.error("[RegistrarClient] ".concat(_)),new Error(_);case 22:return [3,2];case 23:return [2]}})})},t.prototype.setTokenHeader=function(t,e){switch(t.headers.delete("X-Skypetoken"),t.headers.delete("Authorization"),t.headers.delete("X-MS-Migration"),e.tokenType.toLowerCase()){case"skype":t.headers.set("X-Skypetoken",e.token);break;case"aad":case"cae":t.headers.set("Authorization","Bearer ".concat(e.token));break;default:throw new Error("unsupported token type: ".concat(e.tokenType))}!1===this.options.usingLegacyTokenApi&&t.headers.set("X-MS-Migration","True");},t.prototype.sendTelemetryEvent=function(t,e,r,n){if(void 0!==this.eventLogger){var o={name:t,properties:{url:{value:e.url},result_code:{value:void 0!==r?r.status:0},begin_timestamp:{value:n.startTime},elapsed:{value:n.duration}}};this.eventLogger.logEvent(o);}},t}();e.RegistrarClient=h,e.createRegistrarClient=n;}])});

	});

	unwrapExports(tsregistrar);

	var tstrouter = createCommonjsModule(function (module, exports) {
	!function(t,e){module.exports=e(tsregistrar);}(commonjsGlobal,function(t){return function(t){function e(o){if(n[o])return n[o].exports;var i=n[o]={i:o,l:!1,exports:{}};return t[o].call(i.exports,i,i.exports,e),i.l=!0,i.exports}var n={};return e.m=t,e.c=n,e.i=function(t){return t},e.d=function(t,n,o){e.o(t,n)||Object.defineProperty(t,n,{configurable:!1,enumerable:!0,get:o});},e.n=function(t){var n=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(n,"a",n),n},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=20)}([function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.Logger=void 0;var o=function(){function t(t,e){this.name=t,this.logger=e;}return t.prototype.debug=function(t){this.logger.debug("[".concat(this.name,"] ").concat(t));},t.prototype.info=function(t){this.logger.info("[".concat(this.name,"] ").concat(t));},t.prototype.warn=function(t){this.logger.warn("[".concat(this.name,"] ").concat(t));},t.prototype.error=function(t){this.logger.error("[".concat(this.name,"] ").concat(t));},t}();e.Logger=o;},function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.USER_AUTHENTICATE_EVENT_NAME=e.SUPPORTED_TOKEN_TYPES=e.FAILED_MESSAGE_ACK=e.UNHANDLED_MESSAGE_ACK=e.HANDLED_MESSAGE_ACK=e.CLIENT_VERSION=e.constants=void 0,e.constants={TROUTER_INIT:"trouterinit",TROUTER_READY_EVENT:"trouterReadyEvent",TROUTER_READY_TIMEOUT:"trouterReadyTimeout",TROUTER_TOKEN_REQUEST:"trouterTokenRequest",TROUTER_TOKEN_GET_SUCCEEDED:"trouterTokenGetSucceeded",TROUTER_TOKEN_GET_FAILED:"trouterTokenGetFailed",TROUTER_RECONNECTING:"trouterReconnecting",RENEWAL:"renewal",NEW_CONNECTION:"newConnection",ENDPOINT_REGISTRATION_FAILED:"endpointRegistrationFailed"},e.CLIENT_VERSION="2024.14.01.55",e.HANDLED_MESSAGE_ACK=200,e.UNHANDLED_MESSAGE_ACK=404,e.FAILED_MESSAGE_ACK=500,e.SUPPORTED_TOKEN_TYPES=["skype","aad","cae"],e.USER_AUTHENTICATE_EVENT_NAME="user.authenticate";},function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.TrouterState=e.UserActivityState=void 0;var o;!function(t){t[t.Unknown=0]="Unknown",t[t.Active=1]="Active",t[t.Inactive=2]="Inactive";}(o||(e.UserActivityState=o={}));var i;!function(t){t[t.Unknown=0]="Unknown",t[t.Connected=2]="Connected",t[t.Disconnected=3]="Disconnected",t[t.Switching=9]="Switching";}(i||(e.TrouterState=i={}));},function(t,e,n){function o(t){try{return JSON.stringify(t)}catch(e){return "Unable to serialize object of type ".concat(typeof t)}}function i(t){var e=Math.round((new Date).getTime()/1e3);return void 0!==t&&t>e?t-e:0}function r(t){return Math.round((new Date).getTime()/1e3)+t}function s(t,e){return c(this,void 0,void 0,function(){var n,o,i;return a(this,function(r){return o=new Promise(function(e,o){fetch(t).then(function(t){clearTimeout(n),e(t);}).catch(function(t){clearTimeout(n),o(t);});}),0!==e?(i=new Promise(function(o,i){var r=new URL(t.url),s=new Error("".concat(t.method," ").concat(r.origin).concat(r.pathname," timed out"));n=setTimeout(i,e,s);}),[2,Promise.race([o,i])]):[2,o]})})}var c=this&&this.__awaiter||function(t,e,n,o){function i(t){return t instanceof n?t:new n(function(e){e(t);})}return new(n||(n=Promise))(function(n,r){function s(t){try{a(o.next(t));}catch(t){r(t);}}function c(t){try{a(o.throw(t));}catch(t){r(t);}}function a(t){t.done?n(t.value):i(t.value).then(s,c);}a((o=o.apply(t,e||[])).next());})},a=this&&this.__generator||function(t,e){function n(t){return function(e){return o([t,e])}}function o(n){if(i)throw new TypeError("Generator is already executing.");for(;c&&(c=0,n[0]&&(a=0)),a;)try{if(i=1,r&&(s=2&n[0]?r.return:n[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,n[1])).done)return s;switch(r=0,s&&(n=[2&n[0],s.value]),n[0]){case 0:case 1:s=n;break;case 4:return a.label++,{value:n[1],done:!1};case 5:a.label++,r=n[1],n=[0];continue;case 7:n=a.ops.pop(),a.trys.pop();continue;default:if(s=a.trys,!(s=s.length>0&&s[s.length-1])&&(6===n[0]||2===n[0])){a=0;continue}if(3===n[0]&&(!s||n[1]>s[0]&&n[1]<s[3])){a.label=n[1];break}if(6===n[0]&&a.label<s[1]){a.label=s[1],s=n;break}if(s&&a.label<s[2]){a.label=s[2],a.ops.push(n);break}s[2]&&a.ops.pop(),a.trys.pop();continue}n=e.call(t,a);}catch(t){n=[6,t],r=0;}finally{i=s=0;}if(5&n[0])throw n[1];return {value:n[0]?n[1]:void 0,done:!0}}var i,r,s,c,a={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return c={next:n(0),throw:n(1),return:n(2)},"function"==typeof Symbol&&(c[Symbol.iterator]=function(){return this}),c};Object.defineProperty(e,"__esModule",{value:!0}),e.Timespan=e.CorrelationVector=e.fetchWithTimeout=e.calculateExpireTsInSec=e.calculateTtlInSec=e.toJson=void 0,e.toJson=o,e.calculateTtlInSec=i,e.calculateExpireTsInSec=r,e.fetchWithTimeout=s;var u=function(){function t(t){this.base=void 0!==t?t:this.createCorrelationVectorBase(),this.extension=0;}return t.extend=function(e){return new t(e)},t.prototype.increase=function(){this.extension++;},t.prototype.value=function(){return "".concat(this.base,".").concat(this.extension)},t.prototype.createCorrelationVectorBase=function(){for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0987654321/+",e="AQgw",n="",o=0;o<21;o++)n+=t.charAt(Math.floor(Math.random()*t.length));return n+=e.charAt(Math.floor(Math.random()*e.length))},t}();e.CorrelationVector=u;var h=function(){function t(){this.start=Date.now();}return Object.defineProperty(t.prototype,"duration",{get:function(){return Date.now()-this.start},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"startTime",{get:function(){return this.start},enumerable:!1,configurable:!0}),t.prototype.reset=function(){this.start=Date.now();},t}();e.Timespan=h;},function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.TrouterManagerState=e.UserActivityEventReason=e.ServerState=void 0;var o=n(3),i=function(){function t(t,e,n,o,i,r,s){this.connectionId=t,this.connectedClientId=e,this.domId=n,this.unsecureUrl=o,this.url=i,this.c2cUrlBase=r,this.expirationTsSec=s;}return t.prototype.getRemainingTtlInSec=function(){return (0, o.calculateTtlInSec)(this.expirationTsSec)},t}();e.ServerState=i;var r;!function(t){t[t.Unknown=0]="Unknown",t[t.Modified=1]="Modified",t[t.Snapshot=2]="Snapshot",t[t.Connected=3]="Connected";}(r||(e.UserActivityEventReason=r={}));var s;!function(t){t[t.Unknown=0]="Unknown",t[t.Connected=2]="Connected",t[t.Disconnected=3]="Disconnected",t[t.Switching=9]="Switching",t[t.TerminalError=10]="TerminalError";}(s||(e.TrouterManagerState=s={}));},function(t,e,n){function o(t,e){return "skype"===t&&"1"!==i(null===e||void 0===e?void 0:e.scae)?"v4a":"v4c"}function i(t){return "string"==typeof t?t:"number"==typeof t?t.toString():void 0}function r(t,e){return "v4c-websocket-failure"===(null===e||void 0===e?void 0:e.kind)?"v4a":t}function s(t){return Object.prototype.hasOwnProperty.call(t,"connectparams")}function c(t,e){return "v4a"===e?t.replace(/\/v4\/c\b/,"/v4/a").replace("wss://","https://").replace("ws://","http://"):t.replace(/\/v4\/a\b/,"/v4/c").replace("https://","wss://").replace("http://","ws://")}function a(t){if(void 0!==t)return d(d({},t),{reconnectUrl:void 0,serviceUrl:void 0})}function u(t){return "string"==typeof t?parseInt(t,10):t}function h(t){if("redirect"===(null===t||void 0===t?void 0:t.kind)&&void 0!==t.host){var e=t.host;return e.endsWith("/")&&(e=e.substring(0,e.length-1)),e.endsWith("/v4/c")||e.endsWith("/v4/a")||(e+="/v4/c"),e}}var d=this&&this.__assign||function(){return d=Object.assign||function(t){for(var e,n=1,o=arguments.length;n<o;n++){e=arguments[n];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);}return t},d.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0}),e.redirectUrlIfPresent=e.ensureNumber=e.reconnectParamsWithoutUrls=e.adaptUrl=e.isV4ConnectEvent=e.usedProtocolAfterFallback=e.usedProtocol=void 0,e.usedProtocol=o,e.usedProtocolAfterFallback=r,e.isV4ConnectEvent=s,e.adaptUrl=c,e.reconnectParamsWithoutUrls=a,e.ensureNumber=u,e.redirectUrlIfPresent=h;},function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.TrouterFsm=e.State=void 0;var o,i=n(4),r=n(0),s=n(5);!function(t){t[t.Initial=0]="Initial",t[t.RetrievingToken=1]="RetrievingToken",t[t.Allocating=2]="Allocating",t[t.Handshaking=3]="Handshaking",t[t.Connecting=4]="Connecting",t[t.AnonymousConnecting=5]="AnonymousConnecting",t[t.WebsocketAuthenticating=6]="WebsocketAuthenticating",t[t.Connected=7]="Connected",t[t.Unregistering=8]="Unregistering",t[t.TerminalError=9]="TerminalError";}(o||(e.State=o={}));var c;!function(t){t[t.Initial=0]="Initial",t[t.Registering=1]="Registering",t[t.RegisteringButResendPending=2]="RegisteringButResendPending",t[t.Retrying=3]="Retrying",t[t.Registered=4]="Registered",t[t.RegistrationDisabled=5]="RegistrationDisabled";}(c||(c={}));var a=function(){function t(t,e,n,i){this.worker=e,this.incallModeEnabled=n,this.protocolSelector=i,this.state=o.Initial,this.autoReconnect=!0,this.logger=new r.Logger("ConnectionFsm",t),this.registrationState=c.Initial;}return t.prototype.getState=function(){return this.state},t.prototype.isActive=function(){return this.state===o.Allocating||this.state===o.Connected||this.state===o.Handshaking||this.state===o.Connecting||this.state===o.RetrievingToken||this.state===o.AnonymousConnecting||this.state===o.WebsocketAuthenticating},t.prototype.isConnecting=function(){return this.state===o.Allocating||this.state===o.Handshaking||this.state===o.Connecting||this.state===o.AnonymousConnecting},t.prototype.start=function(){return this.state===o.Initial?(this.setState(o.RetrievingToken),this.worker.getToken(!0,!1,void 0),!0):(this.showIgnored("start"),!1)},t.prototype.stop=function(t,e){t&&(this.registrationState=c.Initial),this.worker.isIncallMode()&&this.worker.exitIncallMode(),this.worker.resetTokenBackoff(),this.worker.cancelPendingRegistrationRequests(),this.worker.stopConnectionTimer(),this.worker.stopPingTimer(),this.worker.clearSentEventTimers(),this.worker.stopRegistrationTimer(),this.worker.stopSocketIo(),this.state===o.Connected&&this.worker.sendDisconnectTelemetryEvent("connection stopped"),this.registrationState!==c.Registered&&this.registrationState!==c.Registering&&this.registrationState!==c.RegisteringButResendPending||this.state===o.Unregistering?e?(this.setState(o.TerminalError),this.worker.dispatchTerminalError()):(this.setState(o.Initial),this.worker.dispatchDisconnected()):(this.registrationState=c.Initial,this.setState(o.Unregistering),this.worker.sendUnregisterRequest());},t.prototype.onTokenReceived=function(t,e,n){this.state===o.RetrievingToken?"v4c"===(0, s.usedProtocolAfterFallback)(this.protocolSelector(t.tokenType,n),e)?(this.setState(o.AnonymousConnecting),this.worker.startConnectionTimer(),this.worker.connectV4c(t,e)):(this.setState(o.Allocating),this.worker.startConnectionTimer(),this.worker.sendAllocateRequest(t)):this.showIgnored("onTokenReceived");},t.prototype.checkConnection=function(t){t&&this.onPingInterval();},t.prototype.onAllocationSucceed=function(t){return this.state===o.Allocating&&this.registrationState===c.Registered&&this.worker.dispatchUnregistered(),this.state===o.Allocating?(this.setState(o.Handshaking),this.registrationState=c.Initial,this.worker.startSocketIo(t),!0):(this.showIgnored("onAllocationSucceed"),!1)},t.prototype.onAllocationFailed=function(t,e){this.state===o.Allocating?this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!t,claimsChallenge:e}):this.showIgnored("onAllocationFailed");},t.prototype.onV4cException=function(){this.state!==o.AnonymousConnecting&&this.state!==o.WebsocketAuthenticating||(this.logger.error("v4c exception, falling back to longpoll"),this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!0,fallbackReason:{kind:"v4c-websocket-failure"}}));},t.prototype.onConnectingTimeout=function(){this.state===o.Allocating||this.state===o.Connecting||this.state===o.Handshaking||this.state===o.AnonymousConnecting||this.state===o.WebsocketAuthenticating?this.cleanUpAndInitiateReconnect({backoff:!1,allowCachedToken:!0}):this.showIgnored("onConnectingTimeout");},t.prototype.onConnecting=function(){this.state===o.Handshaking?this.setState(o.Connecting):this.showIgnored("onConnecting");},t.prototype.onSocketConnect=function(t){this.state===o.AnonymousConnecting?(this.setState(o.WebsocketAuthenticating),this.worker.sendV4cAuthenticationEvent(t)):this.showIgnored("onSocketConnect");},t.prototype.onConnectingFailed=function(){this.state===o.Connecting?this.onConnectingTimeout():this.state===o.Handshaking?(this.logger.error("Unexpected error in Socket.io - no valid transports"),this.onConnectingTimeout()):this.state===o.AnonymousConnecting||this.state===o.WebsocketAuthenticating?(this.logger.info("/v4/c falling back to longpoll"),this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!0,fallbackReason:{kind:"v4c-websocket-failure"}})):this.showIgnored("onConnectingFailed");},t.prototype.onSocketDisconnect=function(t){this.state===o.Handshaking||this.state===o.Connected||this.state===o.WebsocketAuthenticating?(this.state===o.Connected&&this.worker.sendDisconnectTelemetryEvent(null===t||void 0===t?void 0:t.toTelemetryString()),this.state===o.WebsocketAuthenticating&&this.worker.countDisconnectBeforeConnectionEstablishment(),"skypetoken-deprecated"===(null===t||void 0===t?void 0:t.reason)?(this.logger.error("Skypetoken deprecated response, not retrying any further"),this.onTerminalError()):this.cleanUpAndInitiateReconnect({backoff:this.state!==o.Connected&&"dup"!==(null===t||void 0===t?void 0:t.reason),allowCachedToken:"unauthorized"!==(null===t||void 0===t?void 0:t.reason),claimsChallenge:null===t||void 0===t?void 0:t.claims})):this.showIgnored("onSocketDisconnect");},t.prototype.onTrouterConnected=function(){this.state===o.Connecting||this.state===o.WebsocketAuthenticating?(this.setState(o.Connected),this.worker.resetTokenBackoff(),this.worker.stopConnectionTimer(),this.worker.sendUserActivityState(i.UserActivityEventReason.Connected,!0),this.worker.startPingTimer(),this.worker.dispatchConnected(),this.worker.shouldSkipRegistration()?(this.registrationState=c.RegistrationDisabled,this.worker.dispatchRegistered()):(this.registrationState=c.Registering,this.worker.sendRegisterRequest())):this.showIgnored("onTrouterConnected");},t.prototype.onReconnectRequired=function(t,e,n){this.state===o.AnonymousConnecting||this.state===o.WebsocketAuthenticating?void 0===n||"host"!==n.target||void 0===n.url||""===n.url?(this.logger.error("unexpected reconnect arguments: ".concat(null===n||void 0===n?void 0:n.target," ").concat(null===n||void 0===n?void 0:n.url,", reconnecting without cache")),this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!0,fallbackReason:{kind:"redirect-no-host"}})):this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!0,fallbackReason:{kind:"redirect",host:n.url}}):this.worker.dispatchReconnectIsRequired(t,e);},t.prototype.disableAutoReconnect=function(){this.autoReconnect=!1;},t.prototype.onDownstreamRequest=function(t){this.state===o.Connected?(this.switchToIncallModeIfEnabled(),this.worker.dispatchDownstreamRequest(t)):this.showIgnored("onDownstreamRequest");},t.prototype.onTrouterMessageLost=function(t){this.state===o.Connected?this.worker.dispatchTrouterMessageLost(t):this.showIgnored("onTrouterMessageLost");},t.prototype.onPingInterval=function(){this.state===o.Connected?this.worker.sendPingRequest():this.showIgnored("onPingInterval");},t.prototype.onPingResponseTimeout=function(){this.onMissedResponse("onPingResponseTimeout");},t.prototype.onPingResponse=function(){this.state===o.Connected||this.showIgnored("onPingResponse");},t.prototype.onRegistrationFailed=function(){this.state===o.Connected&&this.registrationState===c.Registering?(this.worker.dispatchUnregistered(),this.registrationState=c.Retrying,this.worker.startRegistrationRetryTimer()):this.state===o.Connected&&this.registrationState===c.RegisteringButResendPending?(this.registrationState=c.Registering,this.worker.sendRegisterRequest()):this.showIgnored("onRegistrationFailed");},t.prototype.onRetryRegistration=function(){this.state===o.Connected&&this.registrationState===c.Retrying?(this.registrationState=c.Registering,this.worker.sendRegisterRequest()):this.showIgnored("onRetryRegistration");},t.prototype.onRegistrationSucceeded=function(){this.state===o.Connected&&this.registrationState===c.Registering?(this.registrationState=c.Registered,this.worker.dispatchRegistered(),this.worker.startRegistrationTimer()):this.state===o.Connected&&this.registrationState===c.RegisteringButResendPending?(this.registrationState=c.Registering,this.worker.sendRegisterRequest()):this.showIgnored("onRegistrationSucceeded");},t.prototype.onRegistrationNearExpiry=function(){this.state===o.Connected&&this.registrationState===c.Registered?(this.registrationState=c.Registering,this.worker.sendRegisterRequest()):this.showIgnored("onRegistrationNearExpiry");},t.prototype.onUnregistrationDone=function(){this.state===o.Unregistering?(this.setState(o.Initial),this.worker.dispatchUnregistered(),this.worker.dispatchDisconnected()):this.showIgnored("onUnregistrationDone");},t.prototype.onResendRegistration=function(){this.worker.dispatchUnregistered(),this.state===o.Connected&&this.registrationState===c.Registered?(this.registrationState=c.Registering,this.worker.stopRegistrationTimer(),this.worker.sendRegisterRequest()):this.state===o.Connected&&this.registrationState===c.Registering&&(this.registrationState=c.RegisteringButResendPending);},t.prototype.onIncallModeTimer=function(){this.worker.exitIncallMode(),this.state===o.Connected?(this.worker.stopPingTimer(),this.worker.startPingTimer()):this.showIgnored("onIncallModeTimer");},t.prototype.onSetNewUserActivityState=function(){this.worker.sendUserActivityState(i.UserActivityEventReason.Modified,this.state===o.Connected);},t.prototype.onActivityStateResponseTimeout=function(){this.onMissedResponse("onActivityStateResponseTimeout");},t.prototype.forceReconnect=function(t){this.state===o.Connected&&this.worker.sendDisconnectTelemetryEvent(t),this.worker.resetTokenBackoff(),this.cleanUpAndInitiateReconnect({backoff:!1,allowCachedToken:!0});},t.prototype.onTerminalError=function(){this.logger.error("Cannot proceed, reached terminal state. Switching from state '".concat(o[this.state],"' to ").concat(o[o.TerminalError])),this.stop(!0,!0),this.setState(o.TerminalError);},t.prototype.onMissedResponse=function(t){this.state===o.Connected?(this.worker.sendDisconnectTelemetryEvent(t),this.cleanUpAndInitiateReconnect({backoff:!1,allowCachedToken:!0})):this.showIgnored(t);},t.prototype.showIgnored=function(t){this.logger.debug("Ignoring event '".concat(t,"' in state '").concat(o[this.state],"'"));},t.prototype.setState=function(t){if(this.logger.info("Switching from state '".concat(o[this.state],"' to state '").concat(o[t],"'")),this.state===t)return void this.logger.error("Attempt to switch to the current state '".concat(o[t],"'"));this.state=t;},t.prototype.switchToIncallModeIfEnabled=function(){this.incallModeEnabled&&(this.worker.isIncallMode()||(this.worker.enterIncallMode(),this.worker.stopPingTimer(),this.worker.startPingTimer()),this.worker.restartIncallModeTimer());},t.prototype.cleanUpAndInitiateReconnect=function(t){if(!this.autoReconnect)return this.logger.info("Automatic reconnect is disabled, stopping this connection"),void this.stop(!0);this.worker.cancelPendingRegistrationRequests(),this.worker.stopConnectionTimer(),this.worker.stopPingTimer(),this.worker.clearSentEventTimers(),this.worker.stopRegistrationTimer(),this.worker.stopSocketIo(),this.setState(o.RetrievingToken),this.worker.dispatchReconnecting(),this.worker.getToken(t.allowCachedToken,t.backoff,t.claimsChallenge,t.fallbackReason);},t}();e.TrouterFsm=a;},function(t,e,n){function o(t,e){var n=e?void 0:{"X-MS-Migration":"True"};switch(t.tokenType.toLowerCase()){case"skype":return c({"X-Skypetoken":t.token},n);case"aad":case"cae":return c({Authorization:"Bearer ".concat(t.token)},n);default:throw new Error("unsupported token type: ".concat(t.tokenType))}}function i(t){return void 0!==t&&null!==t&&"function"==typeof t.toString?t.toString():"[".concat(typeof t,"]")}function r(t){return "object"==typeof t&&null!==t&&void 0!==t.stack?(0, l.toJson)(t.stack):'"(no error.stack)"'}function s(t){return "object"==typeof t&&null!==t&&"string"==typeof t.message?t.message:"(no error.message)"}var c=this&&this.__assign||function(){return c=Object.assign||function(t){for(var e,n=1,o=arguments.length;n<o;n++){e=arguments[n];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);}return t},c.apply(this,arguments)},a=this&&this.__awaiter||function(t,e,n,o){function i(t){return t instanceof n?t:new n(function(e){e(t);})}return new(n||(n=Promise))(function(n,r){function s(t){try{a(o.next(t));}catch(t){r(t);}}function c(t){try{a(o.throw(t));}catch(t){r(t);}}function a(t){t.done?n(t.value):i(t.value).then(s,c);}a((o=o.apply(t,e||[])).next());})},u=this&&this.__generator||function(t,e){function n(t){return function(e){return o([t,e])}}function o(n){if(i)throw new TypeError("Generator is already executing.");for(;c&&(c=0,n[0]&&(a=0)),a;)try{if(i=1,r&&(s=2&n[0]?r.return:n[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,n[1])).done)return s;switch(r=0,s&&(n=[2&n[0],s.value]),n[0]){case 0:case 1:s=n;break;case 4:return a.label++,{value:n[1],done:!1};case 5:a.label++,r=n[1],n=[0];continue;case 7:n=a.ops.pop(),a.trys.pop();continue;default:if(s=a.trys,!(s=s.length>0&&s[s.length-1])&&(6===n[0]||2===n[0])){a=0;continue}if(3===n[0]&&(!s||n[1]>s[0]&&n[1]<s[3])){a.label=n[1];break}if(6===n[0]&&a.label<s[1]){a.label=s[1],s=n;break}if(s&&a.label<s[2]){a.label=s[2],a.ops.push(n);break}s[2]&&a.ops.pop(),a.trys.pop();continue}n=e.call(t,a);}catch(t){n=[6,t],r=0;}finally{i=s=0;}if(5&n[0])throw n[1];return {value:n[0]?n[1]:void 0,done:!0}}var i,r,s,c,a={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return c={next:n(0),throw:n(1),return:n(2)},"function"==typeof Symbol&&(c[Symbol.iterator]=function(){return this}),c};Object.defineProperty(e,"__esModule",{value:!0}),e.TrouterConnection=e.ReconnectReason=void 0;var h,d=n(21),l=n(3),p=n(15),g=n(1),f=n(16),v=n(17),m=n(2),y=n(4),T=n(0),S=n(5),k=n(6),w=n(12),b=function(){function t(){this.cv=g.CLIENT_VERSION,this.ua="",this.hr="",this.v="";}return t}(),R=function(){function t(){this["force new connection"]=!0,this.reconnect=!1,this.query="",this.ackTimeoutMs=5e3;}return t.prototype.rewriteUrlForProxy=function(t){return t},t}(),C="MS-CV",E=function(){function t(t,e){this.logger=e,this.cvCounter=0;var n=JSON.parse(t);this.startTS=this.safeJsonNumber(n,"startTS",0),this.url=this.safeJsonString(n,"url",""),this.shortUrl=this.safeJsonString(n,"shortUrl",""),this.body=this.safeJsonString(n,"body",""),this.headers=this.safeJsonRecord(n,"headers",{}),this.id=this.safeJsonNumber(n,"id",-1),this.method=this.safeJsonString(n,"method",""),this.replied=!1,this.timedout=!1,this.receivedCv=this.headers[C],this.updateCvHeader();}return Object.defineProperty(t.prototype,"correlationVector",{get:function(){return this.receivedCv?"".concat(this.receivedCv,".").concat(this.cvCounter):""},enumerable:!1,configurable:!0}),t.prototype.on=function(t,e){"data"===t?this.dataCallback=e:"end"===t&&("function"==typeof this.dataCallback&&this.dataCallback(this.body),e());},t.prototype.incrementCorrelationVector=function(){++this.cvCounter,this.updateCvHeader();},t.prototype.updateCvHeader=function(){var t=this.correlationVector;t&&(this.headers[C]=t);},t.prototype.safeJsonNumber=function(t,e,n){var o;if(null!==t&&void 0!==t&&Object.prototype.hasOwnProperty.call(t,e)){var i=t;if("number"==typeof i[e])return i[e];if("string"==typeof i[e])return parseFloat(i[e]);null===(o=this.logger)||void 0===o||o.warn("unexpected type of '".concat(e,"': ").concat(typeof i[e]));}return n},t.prototype.safeJsonString=function(t,e,n){var o;if(null!==t&&void 0!==t&&Object.prototype.hasOwnProperty.call(t,e)){var i=t;if("string"==typeof i[e])return i[e];null===(o=this.logger)||void 0===o||o.warn("unexpected type of '".concat(e,"': ").concat(typeof i[e]));}return n},t.prototype.safeJsonRecord=function(t,e,n){var o;if(null!==t&&void 0!==t&&Object.prototype.hasOwnProperty.call(t,e)){var i=t;if("object"==typeof i[e])return i[e];null===(o=this.logger)||void 0===o||o.warn("unexpected type of '".concat(e,"': ").concat(typeof i[e]));}return n},t}(),I=function(){function t(t,e,n){this.request=t,this.responseData=e,this.sendResponse=n;}return t.prototype.writeHead=function(t,e){this.responseData.status=t,this.responseData.headers=e;},t.prototype.write=function(t){this.responseData.body+=t;},t.prototype.end=function(t){return t&&(this.responseData.body+=t),this.sendResponse(this.request,this.responseData)},t}(),A=function(){function t(t){this.name=t,this.args={},this.timeoutTimerId=0;}return t}();!function(t){t[t.Configuration=0]="Configuration",t[t.ServerInitiated=1]="ServerInitiated";}(h||(e.ReconnectReason=h={}));var U=function(){function t(t,e,n,o,i,r,s,c){var a,u=this;this.options=e,this.manager=n,this.tokenProvider=o,this.usingLegacyTokenApi=i,this.protocolSelector=s,this.audienceSubscriptionState=c,this.WEBSOCKET_TRANSPORT_NAME="websocket",this.XHR_POLLING_TRANSPORT_NAME="xhr-polling",this.AUDIENCE_SUBSCRIPTION_RESULT_ERROR="Error",this.AUDIENCE_SUBSCRIPTION_RESULT_UNSUBSCRIBED="Unsubscribed",this.AUDIENCE_SUBSCRIPTION_RESULT_TIMEOUT="Timeout",this.AUDIENCE_SUBSCRIPTION_RESULT_BAD_REQUEST="BadRequest",this.AUDIENCE_SUBSCRIPTION_STATE_QUERY_PARAM_REGEX=/&audienceSubscriptionState=[^&]*|^audienceSubscriptionState=[^&]*&?/,this.connectionId="",this.inIncallMode=!1,this.connectionAttempt=0,this.connectedClientId="",this.isNavigatorOnline=!0,this.onNavigatorOnlineStatusUpdateBound=this.onNavigatorOnlineStatusUpdate.bind(this),this.c2cUrlBase="",this.connectingErrorsInRow=0,this.unauthorizedErrorCount=0,this.pendingSentEventTimers={},this.lastDisconnectReason="",this.UNKNOWN_TRANSPORT="unknown_transport",this.connectingErrorsThreshold=3,this.pendingAudienceSubscription=void 0,this.logger=new T.Logger("Connection",t),this.timeoutOptions=this.options.timeoutOptions,this.tokenBackoff=new v.ExponentialBackoff(this.logger,this.timeoutOptions.maxBackoffMs),this.clientID=Date.now(),"undefined"!=typeof window&&window.location&&(this.domId=window.location.hostname);var h=new b;h.cv=g.CLIENT_VERSION,h.ua="",(null===(a=this.options)||void 0===a?void 0:a.clientInfo)&&(h.ua=this.safeString(this.options.clientInfo.ua),h.v=this.safeString(this.options.clientInfo.v)),this.clientInfo=h,this.connectionTracker=new p.ConnectionTracker(t,this.clientID,this.clientInfo,function(){return u.getServerState()},this.options.endpointId,this.options.clientCorrelationID,this.options.environment),this.applyConnectionTrackerOptions(e);var l=this.options.incallModeTimeoutMs>0;if(this.fsm=new k.TrouterFsm(t,this,l,this.protocolSelector),e.registration){var f={registrarUrl:e.registration.registrarUrl,proxyUrlRewrite:e.rewriteUrlForProxy,registrationId:e.registration.registrationId,requestTimeoutMs:e.timeoutOptions.fetchTimeoutMs,initialRetryDelayMs:1e3,maxRetryDelayMs:e.timeoutOptions.maxBackoffMs,usingLegacyTokenApi:this.usingLegacyTokenApi,maxRetriesForGetToken:e.retryLimitOnTokenFetch,extraRegistrationHeaders:e.extraConnectionHeaders};this.registrarClient=(0, d.createRegistrarClient)(t,this.tokenProvider,f);}this.userActivityState=r;}return t.prototype.start=function(t){this.logger.info("Starting"),this.reconnectParams=t,"undefined"!=typeof window&&window.navigator&&window.addEventListener?(this.isNavigatorOnline=window.navigator.onLine,window.addEventListener("online",this.onNavigatorOnlineStatusUpdateBound),window.addEventListener("offline",this.onNavigatorOnlineStatusUpdateBound),this.logger.debug("Registered for browser online notifications - current state: ".concat(this.isNavigatorOnline))):this.isNavigatorOnline=!0,this.fsm.start();},t.prototype.stop=function(t){this.logger.info("Stopping"),"undefined"!=typeof window&&window.navigator&&(window.removeEventListener("online",this.onNavigatorOnlineStatusUpdateBound),window.removeEventListener("offline",this.onNavigatorOnlineStatusUpdateBound)),this.fsm.stop(t),this.connectionTracker.close();},t.prototype.configure=function(t){var e=this.options.trouterUrl!==t.trouterUrl;this.options=t,this.applyConnectionTrackerOptions(t),e&&(this.logger.info("Configuration changed. Reconnection required."),this.fsm.onReconnectRequired(!1,h.Configuration));},t.prototype.checkConnection=function(t){this.logger.info("checkConnection called with ".concat(t)),this.fsm.checkConnection(t),t&&this.connectionTracker.sendTelemetry(p.ClientEventName.CheckConnection,{disconnectDetected:t},[]);},t.prototype.disableRegistrationsAndAutoReconnect=function(){this.stopRegistrationTimer(),this.cancelPendingRegistrationRequests(),this.fsm.disableAutoReconnect();},t.prototype.getServerState=function(){return new y.ServerState(this.connectionId,this.connectedClientId,this.domId?this.domId:"",this.allocateResult?this.allocateResult.url:"",this.allocateResult?this.allocateResult.surl:"",this.c2cUrlBase,this.connectionExpireTimestampInSecs)},t.prototype.getState=function(){return this.fsm.getState()},t.prototype.getToken=function(t,e,n,o,i){var r=this;void 0===i&&(i=0),this.logger.info("Getting token ".concat(e?"with backoff":"without backoff"));var s=function(){r.connectionTracker.trackStart("token");var e={needFresh:!t,wwwAuthenticateHeader:n,supportedTokenTypes:g.SUPPORTED_TOKEN_TYPES,purpose:"trouter"};r.logger.info("Requesting token: needFresh=".concat(e.needFresh," ")+"types=[".concat(g.SUPPORTED_TOKEN_TYPES,"], ")+"wwwAuthenticateHeader is ".concat(e.wwwAuthenticateHeader?"non empty":"empty")),r.tokenProvider(e).then(function(t){r.logger.debug("".concat(t.tokenType," token is received")),r.connectionTracker.trackEnd("token"),r.fsm.onTokenReceived(t,o,r.reconnectParams);}).catch(function(e){var s=(0, l.toJson)(e.stack);if(r.logger.error("Getting token failed, will retry after timeout. Error: ".concat(s)),r.connectionTracker.trackError("token",s),!r.canRetryTokenFetchRequest(i+r.unauthorizedErrorCount)){return r.connectionTracker.trackError("token","getToken retry limit hit, reached terminal error state"),r.resetTokenBackoff(),void r.fsm.onTerminalError()}r.getToken(t,!0,n,o,i+1);});};e?this.tokenBackoff.backoff("getting token",s):(this.resetTokenBackoff(),s());},t.prototype.startConnectionTimer=function(){var t=this;this.stopConnectionTimer(),this.logger.debug("Starting connection timeout for ".concat(this.timeoutOptions.connectionTimeoutMs," ms")),this.connectionTimeoutId=setTimeout(function(){t.logger.info("Connection timeout is fired"),t.fsm.onConnectingTimeout();},this.timeoutOptions.connectionTimeoutMs);},t.prototype.stopConnectionTimer=function(){this.connectionTimeoutId&&(this.logger.debug("Stopping connection timeout"),clearTimeout(this.connectionTimeoutId),this.connectionTimeoutId=void 0);},t.prototype.startPingTimer=function(){var t=this;"websocket"===this.transportTypeName?(this.logger.debug("Starting ping timeout for ".concat(this.timeoutOptions.pingTimeoutMs," ms")),this.pingTimerId=setInterval(function(){t.logger.info("Ping interval fired"),t.fsm.onPingInterval();},this.timeoutOptions.pingTimeoutMs)):this.logger.debug("Not starting ping for transport ".concat(this.transportTypeName));},t.prototype.stopPingTimer=function(){this.pingTimerId&&(this.logger.debug("Stopping ping timeout"),this.clearPingResponseTimer(),clearInterval(this.pingTimerId),this.pingTimerId=void 0);},t.prototype.shouldSkipRegistration=function(){return void 0===this.options.registration},t.prototype.hasCustomRegistrationTtl=function(){var t,e;return void 0!==(null===(t=this.options.registration)||void 0===t?void 0:t.registrarTtlSec)&&0!==(null===(e=this.options.registration)||void 0===e?void 0:e.registrarTtlSec)},t.prototype.startRegistrationTimer=function(){var t=this;this.stopRegistrationTimer();var e=this.getRegistrationTtl(),n=e[0],o=e[1];if(n<=30||!o)return this.logger.debug("Starting registration expiration timer (TTL ".concat(n," sec)")),void(this.registrationTimerId=setTimeout(function(){t.registrationTimerId=void 0,t.logger.warn("Registration expired but the connection is still alive. Should never happen"),t.dispatchUnregistered();},1e3*n));var i=n-30;this.logger.debug("Starting registration extension timer for ".concat(i," sec")),this.registrationTimerId=setTimeout(function(){t.logger.info("Registration extension timer fired"),t.registrationTimerId=setTimeout(function(){t.registrationTimerId=void 0,t.logger.debug("Registration extension did not happen in time"),t.dispatchUnregistered();},3e4),t.fsm.onRegistrationNearExpiry();},1e3*i);},t.prototype.startRegistrationRetryTimer=function(){var t=this;this.stopRegistrationTimer();this.registrationTimerId=setTimeout(function(){t.registrationTimerId=void 0,t.fsm.onRetryRegistration();},123e3);},t.prototype.stopRegistrationTimer=function(){this.registrationTimerId&&(this.logger.debug("Stopping registration timeout"),clearTimeout(this.registrationTimerId),this.registrationTimerId=void 0);},t.prototype.resendRegistration=function(){if(!this.registrarClient)throw new Error("Trouter Client not configured to handle registrations");return this.fsm.onResendRegistration(),Promise.resolve()},t.prototype.buildSocketIoUrlParams=function(t,e){if(!this.allocateResult)throw new Error("Allocate result is undefined in buildSocketIoUrlParams()");for(var n={},o=this.allocateResult.connectparams,i=0,r=Object.keys(o);i<r.length;i++){var s=r[i];if(void 0!==o[s]){var c=o[s];"string"==typeof c||"number"==typeof c?n[s]=c:this.logger.error("signatureData[".concat(s,"] has unsupported type ").concat(typeof c));}}return n.v="v4",n.tc=encodeURI((0, l.toJson)(this.clientInfo)),n.timeout=this.timeoutOptions.pingTimeoutMs/1e3,n.auth="true",this.options.endpointId&&(n.epid=this.options.endpointId),t&&(n.userActivity=encodeURI((0, l.toJson)(t))),e&&(n.audienceSubscriptionState=encodeURIComponent((0, l.toJson)(e))),this.appendConnectedClientIds(this.buildQuery(n),!0)},t.prototype.startSocketIo=function(t){var e,n;if(this.logger.debug("Starting socket io"),this.connectionTracker.trackStart("connectSocket"),!this.allocateResult)throw new Error("Allocate result is undefined in startSocketIo()");var i=this.options.ioOptions?c({},this.options.ioOptions):new R,r=this.userActivityState.state!==m.UserActivityState.Unknown?this.userActivityState.increaseCvAndGetEventObject():void 0,s=null===(e=this.audienceSubscriptionState)||void 0===e?void 0:e.increaseCvAndGetEventObject();if(i["force new connection"]=!0,i.reconnect=!1,i.rewriteUrlForProxy=this.options.rewriteUrlForProxy,i.requestHeaders=c(c({},this.options.extraConnectionHeaders),o(t,this.usingLegacyTokenApi)),i.query=this.buildSocketIoUrlParams(r,s),this.logger.info("connecting to ".concat(this.allocateResult.socketio,"?").concat(i.query)),this.stopSocketIo(),this.socket=(null!==(n=this.options.io)&&void 0!==n?n:w).connect(this.allocateResult.socketio,i),void 0===this.socket)throw new Error("Can't create Socket.io object");this.attachSocketIoHandlers(this.socket,t,r,s);},t.prototype.stopSocketIo=function(){if(this.socket){this.logger.debug("clearing socket.io");try{for(var t=0,e=["connecting","connect","connect_failed","close_during_connecting","disconnect","reconnect","reconnect_failed","reconnecting","error","message","trouter.connected","trouter.reconnect","trouter.message_loss"];t<e.length;t++){var n=e[t];this.socket.removeAllListeners(n);}this.socket.disconnect(),this.logger.debug("cleared socket"),this.socket=void 0;}catch(t){this.logger.error("exception in disconnecting previous socket. Error: ".concat(r(t)));}}},t.prototype.dispatchConnected=function(){this.logger.info("dispatching connected"),this.manager.onConnected(this);},t.prototype.dispatchRegistered=function(){this.logger.info("dispatching registered"),this.manager.onRegistered(this);},t.prototype.dispatchUnregistered=function(){this.logger.info("dispatching unregistered"),this.manager.onUnregistered(this);},t.prototype.dispatchDownstreamRequest=function(t){var e=this;this.logger.debug("dispatching downstream request");try{var n=new I(t,new p.ResponseData(t.id),function(t,n){return e.logger.debug("sending response to downstream"),e.sendResponse(t,n)});this.manager.onDownstreamRequest(this,t,n);}catch(t){this.logger.error("exception in socket.on message. Error : ".concat(r(t)));}},t.prototype.dispatchReconnecting=function(){this.logger.info("dispatching reconnecting"),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=r(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?void 0:r.se)?parseInt(r.se,10):"number"==typeof(null===r||void 0===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?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){var n;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")),new Error(t.statusText);var o=t.headers.get("content-type");if(!o||"application/json"!==o&&!o.startsWith("application/json;"))throw new 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()}if(-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=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);var n;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))}),n=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)(n,t).then(function(t){if(200!==t.status)throw new Error("Not 200 OK: ".concat(t.status," ").concat(t.statusText));return t.text()}).then(function(t){if("Trouter"!==t)throw new Error('Not "Trouter": '.concat(t.substring(0,16)).concat(t.length>16?"...":""));return !0}).catch(function(t){return e.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=r(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?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 new 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.reconnectParamsWithoutUrls)(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 new 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"),n.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?[2,i]:(r=i.responses[0],(null===r||void 0===r?void 0:r.result.audienceSubscriptionState)===this.AUDIENCE_SUBSCRIPTION_RESULT_BAD_REQUEST?(this.clearAudienceSubscriptionStateQueryParam(),this.manager.onAudiencesSetResolved(i,t.cv),[2,i]):(s=i.responses.find(function(e){return e.audienceId===t.audiences[0].id}),(null===s||void 0===s?void 0:s.result.audienceSubscriptionState)===this.AUDIENCE_SUBSCRIPTION_RESULT_ERROR?(this.clearAudienceSubscriptionStateQueryParam(),this.manager.onAudiencesSetResolved(i,t.cv),[2,i]):(c=(null===(o=null===n||void 0===n?void 0:n.audienceSubscriptionModel.audienceSubscriptions[0])||void 0===o?void 0:o.id)!==(null===r||void 0===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){var n;this.audienceSubscriptionState=void 0;var o={responses:[]};if(e){var i=this.mapToSyntheticAudienceSubscriptionResponses(e.audienceSubscriptionModel.audienceSubscriptions,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 new Error("Internal error - options.registration is undefined");if(!this.allocateResult)throw new 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",s(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 new 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",s(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,n=t;e<n.length;e++){var o=n[e];this.clearSentEventTimer(Number(o));}}},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");},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",i(t)),this.fsm.onSocketDisconnect(f.DisconnectReason.fromSocketIoEventData("socketerror",t));},t.prototype.onSocketMessage=function(t){var e,n=this;this.logger.debug("onSocketMessage");var o;try{o=new E(t,this.logger);var i=null===(e=o.headers)||void 0===e?void 0:e["X-Microsoft-Skype-Chain-ID"],c=i?" Chain-Id ".concat(i):"";this.logger.info("Received request N ".concat(o.id).concat(c," CV ").concat(o.correlationVector," to '").concat(o.url,"'")),o.startTS=Date.now(),o.url&&this.urlPath&&o.url.startsWith(this.urlPath)&&(o.shortUrl=o.url.substring(this.urlPath.length));}catch(t){var a=r(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))}o.timeoutTimerId=setTimeout(function(){if(!o.replied){n.logger.error("Request ".concat(o.id," timed out"));var t=new p.ResponseData(o.id);t.status=504,t.headers={"Trouter-Responder":"ClientLib"},n.sendResponse(o,t),o.timedout=!0;}},this.timeoutOptions.requestTimeoutMs);try{this.connectionTracker.trackRequest(o),this.fsm.onDownstreamRequest(o);}catch(t){this.logger.error("exception in socket.on message. Error: ".concat(r(t))),this.connectionTracker.sendResponseError(s(t),o,void 0);}},t.prototype.onTrouterConnected=function(t,e,n){var o,i,r,s,a=this;if((0, S.isV4ConnectEvent)(t)){var u=t;this.allocateResult=c(c({},u),{ttl:t.ttl.toString()}),this.populateAndCacheReconnectParams(u,u.reconnectUrl),this.populateConnectionStateFields(u);}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 h=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(h,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 audiences 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){var n,o,i;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 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===(i=t.headers)||void 0===i?void 0:i["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(r(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 invalid configuration.");}catch(t){this.logger.warn("Trouter client event logging disabled. Error: ".concat(r(t))),this.connectionTracker.disable();}},t.prototype.canRetryTokenFetchRequest=function(t){var e=this.options.retryLimitOnTokenFetch;return null===e||void 0===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 new 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){function o(t){var e,n=this;return function(o){return i(n,void 0,void 0,function(){return r(this,function(n){return o&&(e=void 0),[2,new Promise(function(n,i){t(o).then(function(t){e=t,n(t);}).catch(function(t){void 0!==e&&e.length>0&&n(e),i(t);});})]})})}}var i=this&&this.__awaiter||function(t,e,n,o){function i(t){return t instanceof n?t:new n(function(e){e(t);})}return new(n||(n=Promise))(function(n,r){function s(t){try{a(o.next(t));}catch(t){r(t);}}function c(t){try{a(o.throw(t));}catch(t){r(t);}}function a(t){t.done?n(t.value):i(t.value).then(s,c);}a((o=o.apply(t,e||[])).next());})},r=this&&this.__generator||function(t,e){function n(t){return function(e){return o([t,e])}}function o(n){if(i)throw new TypeError("Generator is already executing.");for(;c&&(c=0,n[0]&&(a=0)),a;)try{if(i=1,r&&(s=2&n[0]?r.return:n[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,n[1])).done)return s;switch(r=0,s&&(n=[2&n[0],s.value]),n[0]){case 0:case 1:s=n;break;case 4:return a.label++,{value:n[1],done:!1};case 5:a.label++,r=n[1],n=[0];continue;case 7:n=a.ops.pop(),a.trys.pop();continue;default:if(s=a.trys,!(s=s.length>0&&s[s.length-1])&&(6===n[0]||2===n[0])){a=0;continue}if(3===n[0]&&(!s||n[1]>s[0]&&n[1]<s[3])){a.label=n[1];break}if(6===n[0]&&a.label<s[1]){a.label=s[1],s=n;break}if(s&&a.label<s[2]){a.label=s[2],a.ops.push(n);break}s[2]&&a.ops.pop(),a.trys.pop();continue}n=e.call(t,a);}catch(t){n=[6,t],r=0;}finally{i=s=0;}if(5&n[0])throw n[1];return {value:n[0]?n[1]:void 0,done:!0}}var i,r,s,c,a={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return c={next:n(0),throw:n(1),return:n(2)},"function"==typeof Symbol&&(c[Symbol.iterator]=function(){return this}),c};Object.defineProperty(e,"__esModule",{value:!0}),e.addCacheAsBackupTo=void 0,e.addCacheAsBackupTo=o;},function(t,e,n){var o=this&&this.__awaiter||function(t,e,n,o){function i(t){return t instanceof n?t:new n(function(e){e(t);})}return new(n||(n=Promise))(function(n,r){function s(t){try{a(o.next(t));}catch(t){r(t);}}function c(t){try{a(o.throw(t));}catch(t){r(t);}}function a(t){t.done?n(t.value):i(t.value).then(s,c);}a((o=o.apply(t,e||[])).next());})},i=this&&this.__generator||function(t,e){function n(t){return function(e){return o([t,e])}}function o(n){if(i)throw new TypeError("Generator is already executing.");for(;c&&(c=0,n[0]&&(a=0)),a;)try{if(i=1,r&&(s=2&n[0]?r.return:n[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,n[1])).done)return s;switch(r=0,s&&(n=[2&n[0],s.value]),n[0]){case 0:case 1:s=n;break;case 4:return a.label++,{value:n[1],done:!1};case 5:a.label++,r=n[1],n=[0];continue;case 7:n=a.ops.pop(),a.trys.pop();continue;default:if(s=a.trys,!(s=s.length>0&&s[s.length-1])&&(6===n[0]||2===n[0])){a=0;continue}if(3===n[0]&&(!s||n[1]>s[0]&&n[1]<s[3])){a.label=n[1];break}if(6===n[0]&&a.label<s[1]){a.label=s[1],s=n;break}if(s&&a.label<s[2]){a.label=s[2],a.ops.push(n);break}s[2]&&a.ops.pop(),a.trys.pop();continue}n=e.call(t,a);}catch(t){n=[6,t],r=0;}finally{i=s=0;}if(5&n[0])throw n[1];return {value:n[0]?n[1]:void 0,done:!0}}var i,r,s,c,a={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return c={next:n(0),throw:n(1),return:n(2)},"function"==typeof Symbol&&(c[Symbol.iterator]=function(){return this}),c};Object.defineProperty(e,"__esModule",{value:!0}),e.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&&void 0!==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();},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 new Error("No connection found")},t.prototype.onTrouterMessageLost=function(t){var e=this;if(this.listener.onTrouterMessageLoss)if(null===t||void 0===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)]}),!t.length))return void this.logger.info("onTrouterMessageLoss - all declared dropped indicators have been seen before");var o=this.listener.onTrouterMessageLoss(t.map(function(t){return t.tag}));if(!o)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));}catch(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){!function(t,e){var n=t;n.version="0.9.6",n.protocol=1,n.transports=[],n.j=[],n.sockets={},n.connect=function(t,o){var i,r,s=n.util.parseUri(t);e&&e.location&&(s.protocol=s.protocol||e.location.protocol.slice(0,-1),s.host=s.host||(e.document?e.document.domain:e.location.hostname),s.port=s.port||e.location.port),i=n.util.uniqueUri(s);var c={host:s.host,secure:"https"==s.protocol,port:s.port||("https"==s.protocol?443:80),query:s.query||""};return n.util.merge(c,o),!c["force new connection"]&&n.sockets[i]||(r=new n.Socket(c)),!c["force new connection"]&&r&&(n.sockets[i]=r),r=r||n.sockets[i],c["skipped handshake data"]?r.of(""):r.of(s.path.length>1?s.path:"")};}(n.exports,void 0===t?window:t);var o=n.exports;!function(t,e){var n=t.util={},o=/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,i=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];n.parseUri=function(t){for(var e=o.exec(t||""),n={},r=14;r--;)n[i[r]]=e[r]||"";return n},n.uniqueUri=function(t){var n=t.protocol,o=t.host,i=t.port;return "document"in e?(o=o||document.domain,i=i||("https"==n&&"https:"!==document.location.protocol?443:document.location.port)):(o=o||"localhost",i||"https"!=n||(i=443)),(n||"http")+"://"+o+":"+(i||80)},n.query=function(t,e){var o=n.chunkQuery(t||""),i=[];n.merge(o,n.chunkQuery(e||""));for(var r in o)o.hasOwnProperty(r)&&i.push(r+"="+o[r]);return i.length?"?"+i.join("&"):""},n.chunkQuery=function(t){for(var e,n={},o=t.split("&"),i=0,r=o.length;i<r;++i)e=o[i].split("="),e[0]&&(n[e[0]]=e[1]);return n};var r=!1;n.load=function(t){if("document"in e&&"complete"===document.readyState||r)return t();n.on(e,"load",t,!1);},n.on=function(t,e,n,o){t.attachEvent?t.attachEvent("on"+e,n):t.addEventListener&&t.addEventListener(e,n,o);},n.request=function(t){if(t&&"undefined"!=typeof XDomainRequest)return new XDomainRequest;if("undefined"!=typeof XMLHttpRequest&&(!t||n.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&&n.load(function(){r=!0;}),n.defer=function(t){if(!n.ua.webkit||"undefined"!=typeof importScripts)return t();n.load(function(){setTimeout(t,100);});},n.merge=function(t,e,o,i){var r,s=i||[],c=void 0===o?2:o;for(r in e)e.hasOwnProperty(r)&&n.indexOf(s,r)<0&&("object"==typeof t[r]&&c?n.merge(t[r],e[r],c-1,s):(t[r]=e[r],s.push(e[r])));return t},n.mixin=function(t,e){n.merge(t.prototype,e.prototype);},n.inherit=function(t,e){function n(){}n.prototype=e.prototype,t.prototype=new n;},n.isArray=Array.isArray||function(t){return "[object Array]"===Object.prototype.toString.call(t)},n.intersect=function(t,e){for(var o=[],i=t.length>e.length?t:e,r=t.length>e.length?e:t,s=0,c=r.length;s<c;s++)~n.indexOf(i,r[s])&&o.push(r[s]);return o},n.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},n.toArray=function(t){for(var e=[],n=0,o=t.length;n<o;n++)e.push(t[n]);return e},n.ua={},n.ua.hasCORS="undefined"!=typeof XMLHttpRequest&&function(){try{var t=new XMLHttpRequest;}catch(t){return !1}return void 0!=t.withCredentials}(),n.ua.webkit="undefined"!=typeof navigator&&/webkit/i.test(navigator.userAgent);}(void 0!==o?o:n.exports,void 0===t?window:t),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]]),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!==o?o:n.exports,void 0!==o?o:n.parent.exports),function(t,e){if(e&&e.parse)return t.JSON={parse:e.parse,stringify:e.stringify};throw new Error("JSON not available")}(void 0!==o?o:n.exports,"undefined"!=typeof JSON?JSON:void 0),function(t,e){var n=t.parser={},o=n.packets=["disconnect","connect","heartbeat","message","json","event","ack","error","noop"],i=n.reasons=["transport not supported","client not handshaken","unauthorized"],r=n.advice=["reconnect"],s=e.JSON,c=e.util.indexOf;n.encodePacket=function(t){var e=c(o,t.type),n=t.id||"",a=t.endpoint||"",u=t.ack,h=null;switch(t.type){case"error":var d=t.reason?c(i,t.reason):"",l=t.advice?c(r,t.advice):"";""===d&&""===l||(h=d+(""!==l?"+"+l:""));break;case"message":""!==t.data&&(h=t.data);break;case"event":var p={name:t.name};t.args&&t.args.length&&(p.args=t.args),h=s.stringify(p);break;case"json":h=s.stringify(t.data);break;case"connect":t.qs&&(h=t.qs);break;case"ack":h=t.ackId+(t.args&&t.args.length?"+"+s.stringify(t.args):"");}var g=[e,n+("data"==u?"+":""),a];return null!==h&&void 0!==h&&g.push(h),g.join(":")},n.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};var a=/([^:]+):([0-9]+)?(\+)?:([^:]+)?:?([\s\S]*)?/;n.decodePacket=function(t){var e=t.match(a);if(!e)return {};var n=e[2]||"",t=e[5]||"",c={type:o[e[1]],endpoint:e[4]||""};switch(n&&(c.id=n,e[3]?c.ack="data":c.ack=!0),c.type){case"error":var e=t.split("+");c.reason=i[e[0]]||"",c.advice=r[e[1]]||"";break;case"message":c.data=t||"";break;case"event":try{var u=s.parse(t);c.name=u.name,c.args=u.args;}catch(t){}c.args=c.args||[];break;case"json":try{c.data=s.parse(t);}catch(t){}break;case"connect":c.qs=t||"";break;case"ack":var e=t.match(/^([0-9]+)(\+)?(.*)/);if(e&&(c.ackId=e[1],c.args=[],e[3]))try{c.args=e[3]?s.parse(e[3]):[];}catch(t){}break;case"disconnect":c.reason=t;}return c},n.decodePayload=function(t){if("�"==t.charAt(0)){for(var e=[],o=1,i="";o<t.length;o++)"�"==t.charAt(o)?(e.push(n.decodePacket(t.substr(o+1).substr(0,i))),o+=Number(i)+1,i=""):i+=t.charAt(o);return e}return [n.decodePacket(t)]};}(void 0!==o?o:n.exports,void 0!==o?o:n.parent.exports),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!==o?o:n.exports,void 0!==o?o: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(){this.emit.apply(this,arguments);var t;for(var e in this.namespaces)this.namespaces.hasOwnProperty(e)&&(t=this.of(e),t.$emit.apply(t,arguments));},o.prototype.handshake=function(t){function n(e){e instanceof Error?o.onError(e.message):t.apply(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.connect(),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!==o?o:n.exports,void 0!==o?o: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!==o?o:n.exports,void 0!==o?o: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!==o?o.Transport:n.exports,void 0!==o?o: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){function e(){4==this.readyState&&(this.onreadystatechange=i,200==this.status?(clearTimeout(this.ackTimeoutTimer),r.socket.setBuffer(!1)):r.onClose());}function o(){this.onload=i,r.socket.setBuffer(!1);}var r=this;this.socket.setBuffer(!0),this.sendXHR=this.request("POST"),n.XDomainRequest&&this.sendXHR instanceof XDomainRequest?this.sendXHR.onload=this.sendXHR.onerror=o:this.sendXHR.onreadystatechange=e,this.sendXHR.send(t),r.sendXHR.ackTimeoutTimer=setTimeout(function(){r.onClose();},r.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:",c=s!=n.location.protocol;if(i&&(!r||!c))return !0}catch(t){}return !1},o.xdomainCheck=function(){return o.check(null,!0)},o.prototype.clearEventHandlers=function(){return this.sendXHR&&(this.sendXHR.onreadystatechange=this.sendXHR.onload=i),this};}(void 0!==o?o.Transport:n.exports,void 0!==o?o: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){var n=this;return n.connectErrorCallback=t,e.Transport.XHR.prototype.open.call(n),!1},o.prototype.get=function(){function t(){4==this.readyState&&(this.onreadystatechange=i,200==this.status?(r.connectErrorCallback=void 0,r.onData(this.responseText),r.get()):(r.onClose(),void 0!==r.connectErrorCallback&&(r.connectErrorCallback(),r.connectErrorCallback=void 0)));}function e(){r.connectErrorCallback=void 0,this.onload=i,this.onerror=i,r.onData(this.responseText),r.get();}function o(){r.onClose(),void 0!==r.connectErrorCallback&&(r.connectErrorCallback(),r.connectErrorCallback=void 0);}if(this.isOpened){var r=this;this.xhr=this.request(),n.XDomainRequest&&this.xhr instanceof XDomainRequest?(this.xhr.onload=e,this.xhr.onerror=o):this.xhr.onreadystatechange=t,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!==o?o.Transport:n.exports,void 0!==o?o:n.parent.exports,void 0===t?window:t),e.io=o;}).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=n(3),i=n(1),r=n(0),s=function(){function t(t){this.id=t,this.status=200,this.headers={},this.body="";}return t}();e.ResponseData=s;var c;!function(t){t.Connected="trouter_js_client_connected",t.Disconnected="trouter_js_client_disconnected",t.Error="trouter_js_client_error",t.Progress="trouter_js_client_progress",t.Response="trouter_js_client_response",t.Request="trouter_js_client_request",t.CheckConnection="trouter_js_client_check_connection",t.Registration="trouter_js_client_registration",t.Unregistration="trouter_js_client_unregistration";}(c||(e.ClientEventName=c={}));var a=function(){function t(t,e,n,o,i){this.stepName=t,this.operation=e,this.delta=n,this.ts=o,this.error=i;}return t}();e.TrackerStep=a;var u=function(){function t(){}return t}();e.Properties=u;var h=function(){function t(){this.numberOfPingReplies=0,this.connectedTimestamp=0,this.isNewUrl=!1,this.transportType="",this.connectionNumber=0;}return t}(),d=function(){function t(){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;}return t}(),l=function(){function t(t,e,n,i,s,c,a){this.clientId=e,this.clientInfo=n,this.getServerState=i,this.endpointId=s,this.clientCorrelationID=c,this.environment=a,this.logger=new r.Logger("ConnectionTracker",t),this.clientCorrelationID=void 0!==c?c:"",this.steps=[],this.connectionAttempt=0,this.totalStepCount=0,this.beginTimestamp=new o.Timespan,this.eventLogSettings=new d,this.connectedInfo=new h;}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(c.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];void 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 r=this.getServerState(),s={name:t,properties:{connectionAttempt:{value:this.connectionAttempt},epid:{value:this.endpointId},clientCorrelationID:{value:this.clientCorrelationID},steps:{value:(0,o.toJson)(n)},clientID:{value:this.clientId},eventVersion:{value:3},environment:{value:this.environment},cv:{value:i.CLIENT_VERSION},ua:{value:this.clientInfo.ua},connectionId:{value:r.connectionId},connectedClientId:{value:r.connectedClientId},domId:{value:r.domId},url:{value:r.unsecureUrl},surl:{value:r.url},ttlInSecs:{value:r.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(s.properties,e),this.eventLogger.logEvent(s);}}catch(e){this.logger.warn("error in sending event ".concat(t,": ").concat((0, o.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(c.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(c.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,i=this.beginTimestamp.duration;this.steps.length=0,this.totalStepCount=0,this.sendTelemetry(c.Connected,{stepCount:n.length,totalStepCount:o,connectionEstablishmentMs_Total:i},n),this.cancelProgressTimer();},t.prototype.getSessionLength=function(){return Date.now()-this.connectedInfo.connectedTimestamp},t.prototype.trackDisconnected=function(t){t.sessionLengthMS=this.getSessionLength(),this.sendTelemetry(c.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 i=t.headers,r=0,s=Object.keys(i);r<s.length;r++){var a=s[r];n[a]=i[a];}}}catch(t){n.hasError=!0,n.error="".concat(n.error," error creating request context ").concat((0, o.toJson)(t));}this.sendTelemetry(c.Request,n,[]);},t.prototype.trackResponse=function(t,e,n,i){var r={};void 0!==i&&(r.hasError=!0,r.error=i);try{if(r.responseTimestamp=void 0!==n?n.sentTS:Date.now(),t){r.requestID=t.id,r.httpMethod=t.method,r.shortUrl=t.shortUrl,r.correlationVector=t.correlationVector;for(var s=t.headers,a=0,u=Object.keys(s);a<u.length;a++){var h=u[a];r[h]=s[h];}}n&&(r.latencyMS=e,r.responseCode=n.status,r.responseLength=n.body.length);}catch(t){r.hasError=!0,r.error="".concat(r.error," error creating response context ").concat((0, o.toJson)(t));}this.sendTelemetry(c.Response,r,[]);},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(c).map(function(t){return c[t]});n<o.length;n++){var i=o[n];void 0!==t[i]&&(this.eventLogSettings[i]=t[i]);}this.eventLogSettings.sendProgressTimeoutSecs!==e&&(this.eventLogSettings.sendProgressTimeoutSecs=e,this.resetProgressSendTimer());}},t}();e.ConnectionTracker=l;},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||void 0===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){function o(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}Object.defineProperty(e,"__esModule",{value:!0}),e.ExponentialBackoff=void 0;var i=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=1+.4*(Math.random()-.5),o=1e3*Math.pow(2,t)*n;return o=Math.round(o),Math.min(e,o)},t.prototype.setMaxBackoffMs=function(t){this.maxBackoffInMs=t;},t.prototype.backoff=function(e,n){var i=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 r=Date.now()-this.previousCompleteTime;r>this.maxBackoffInMs*this.gapDetectionSettings.tolerance&&r>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(r," ms)")),this.backoffCount=0,this.previousCompleteTime=void 0);}var s=t.calculateNextBackoffMs(this.backoffCount,this.maxBackoffInMs);this.backoffId++,this.backoffCount++,this.logger.info("Backing off ".concat(e," for ").concat(s," milliseconds with ID ").concat(this.backoffId)),this.callback=function(t,r){o(t,r,i.gapDetectionSettings)&&(i.logger.info("Back off for ".concat(e," with ID ").concat(i.backoffId," will be reset due to the wait (").concat(Date.now()-(null!==t&&void 0!==t?t:0)," ms) being longer than expected (").concat(r," ms)")),i.backoffCount=0),i.logger.info("Back off for ".concat(e," with ID ").concat(i.backoffId," complete, invoking handler")),i.timerHandle=void 0,i.callback=void 0,i.previousCompleteTime=Date.now(),n();};var c=Date.now();this.timerHandle=setTimeout(function(){var t;return null===(t=i.callback)||void 0===t?void 0:t.call(i,c,s)},s);},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=i;},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})),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.stopFirstConnection(!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.showIgnored("onReconnecting(".concat(t,")")):(this.setState(i.TrouterManagerState.Disconnected),this.worker.dispatchDisconnected());},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){if(!e)return t;var n=h(h({},t),{enabled:e.TelemetryEnabled});return void 0!==e.ClientTelemetryEventEnabled&&(n=h(h({},n),e.ClientTelemetryEventEnabled)),n}function i(t,e,n){var i,r,s,c,a,u,d,l,p,g,f=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:f},clientCorrelationID:t.trouterSettings.sessionId,environment:t.trouterSettings.environment,telemetrySettings:o(t.telemetryConfig.settings,n),eventLogger:t.telemetryConfig.eventLogger,endpointId:t.trouterSettings.registrationId,trouterUrl:(null===n||void 0===n?void 0:n.TrouterConnectionUrl)||t.trouterSettings.trouterServiceUrl,registration:t.trouterSettings.registrarServiceUrl?{registrarUrl:t.trouterSettings.registrarServiceUrl,registrationId:null!==(i=t.trouterSettings.registrationId)&&void 0!==i?i:"",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:"",productContext:t.trouterSettings.pnhProductContext||void 0,context:null!==(u=t.trouterSettings.pnhContext)&&void 0!==u?u:"",registrarTtlSec:(null!==(d=t.trouterSettings.maxRegistrationTimeInMs)&&void 0!==d?d:0)/1e3}:void 0,connectionDependsOnRegistration:void 0===t.trouterSettings.registrarServiceUrl?function(){return !1}:null!==(l=t.trouterSettings.connectionDependsOnRegistration)&&void 0!==l?l:function(){return !1},delayEventsUntilRegistered:null!==(p=t.trouterSettings.delayEventsUntilRegistered)&&void 0!==p?p:function(){return !1},timeoutOptions:h({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:h({connectionTimeoutMs:1e4,fetchTimeoutMs:5e3,pingTimeoutMs:5e3,pongTimeoutMs:2e3,maxBackoffMs:"TeamsCDL"===t.trouterSettings.productName?3e5:1e4,requestTimeoutMs:5e3,userActivityResponseTimeoutMs:1e4},t.trouterSettings.incallTimeoutOptions),incallModeTimeoutMs:null!==(g=t.trouterSettings.incallModeTimeoutMs)&&void 0!==g?g:0,lingeringConnectionDelayMs:6e4,userActivitySecondResendDelayMs:t.trouterSettings.userActivitySecondResendDelayMs||1e4,duplicateDisconnectThresholdMs:1e4,connectionCache:t.connectionCache,registrationStateCallback:t.registrationStateCallbackForAcsDoNotUse,rewriteUrlForProxy:f,retryLimitOnTokenFetch:t.trouterSettings.retryLimitOnTokenFetch,extraConnectionHeaders:t.trouterSettings.extraConnectionHeaders,expediteBackoffOnStartMinimumDelayMs:1e4,toJSON:function(){return h(h({},this),{connectionCache:this.connectionCache?{}:this.connectionCache})}}}function r(t){return new S(t)}function s(){return p.CLIENT_VERSION}function c(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 a(t){var e=this;return function(n){return d(e,void 0,void 0,function(){var e;return l(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)]}})})}}function u(t,e){var n,o=this;return function(i){return d(o,void 0,void 0,function(){var o,r,s;return l(this,function(c){switch(c.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),c.label=1;case 1:return c.trys.push([1,,3,4]),[4,e(i)];case 2:return s=c.sent(),i.needFresh&&s.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=s.token,[2,s];case 3:return clearInterval(r),[7];case 4:return [2]}})})}}var h=this&&this.__assign||function(){return h=Object.assign||function(t){for(var e,n=1,o=arguments.length;n<o;n++){e=arguments[n];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);}return t},h.apply(this,arguments)},d=this&&this.__awaiter||function(t,e,n,o){function i(t){return t instanceof n?t:new n(function(e){e(t);})}return new(n||(n=Promise))(function(n,r){function s(t){try{a(o.next(t));}catch(t){r(t);}}function c(t){try{a(o.throw(t));}catch(t){r(t);}}function a(t){t.done?n(t.value):i(t.value).then(s,c);}a((o=o.apply(t,e||[])).next());})},l=this&&this.__generator||function(t,e){function n(t){return function(e){return o([t,e])}}function o(n){if(i)throw new TypeError("Generator is already executing.");for(;c&&(c=0,n[0]&&(a=0)),a;)try{if(i=1,r&&(s=2&n[0]?r.return:n[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,n[1])).done)return s;switch(r=0,s&&(n=[2&n[0],s.value]),n[0]){case 0:case 1:s=n;break;case 4:return a.label++,{value:n[1],done:!1};case 5:a.label++,r=n[1],n=[0];continue;case 7:n=a.ops.pop(),a.trys.pop();continue;default:if(s=a.trys,!(s=s.length>0&&s[s.length-1])&&(6===n[0]||2===n[0])){a=0;continue}if(3===n[0]&&(!s||n[1]>s[0]&&n[1]<s[3])){a.label=n[1];break}if(6===n[0]&&a.label<s[1]){a.label=s[1],s=n;break}if(s&&a.label<s[2]){a.label=s[2],a.ops.push(n);break}s[2]&&a.ops.pop(),a.trys.pop();continue}n=e.call(t,a);}catch(t){n=[6,t],r=0;}finally{i=s=0;}if(5&n[0])throw n[1];return {value:n[0]?n[1]:void 0,done:!0}}var i,r,s,c,a={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return c={next:n(0),throw:n(1),return:n(2)},"function"==typeof Symbol&&(c[Symbol.iterator]=function(){return this}),c};Object.defineProperty(e,"__esModule",{value:!0}),e.replaceTrouterUrlBase=e.getTrouterServiceVersion=e.createTrouterService=e.TrouterService=e.UserActivityState=e.TrouterState=void 0;var p=n(1),g=n(2);Object.defineProperty(e,"TrouterState",{enumerable:!0,get:function(){return g.TrouterState}}),Object.defineProperty(e,"UserActivityState",{enumerable:!0,get:function(){return g.UserActivityState}});var f=n(0),v=n(8),m=n(9),y=n(10),T=n(11),S=function(){function t(t){this.logProvider=t,this.stateChangedListeners=[],this.logger=new f.Logger("Trouter",t),this.trouterUrlPromise=new T.TrouterUrlPromise(t),this.messageHandlers=new v.MessageHandlerRegistry(t),this.listeners={},this.connectionInfo=null,this.logger.info("Created TrouterService version ".concat(p.CLIENT_VERSION));}return t.prototype.start=function(t){var e;if(this.logger.info("Start"),!t.skypeTokenProvider&&!t.authTokenProvider)throw new Error("no token provider has been configured, either skypeTokenProvider or authTokenProvider must be populated");t.skypeTokenProvider&&!t.trouterSettings.disableInternalSkypeTokenCache&&(t.skypeTokenProvider=(0, m.addCacheAsBackupTo)(t.skypeTokenProvider)),this.trouterCfg=t;var n=i(t,this.logger,this.ecsCfg);!1===t.internalEnableV4cProtocol&&(n.forceV4aProtocol=!0);var o=u(this.logger,null!==(e=t.authTokenProvider)&&void 0!==e?e:a(t.skypeTokenProvider));void 0===this.trouterServer&&(this.trouterServer=new y.TrouterManager(this.logProvider,n,o,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(new Error("TrouterService is stopped")),void 0!==this.trouterServer&&this.trouterServer.stop(t);},t.prototype.setEcsConfig=function(t){return d(this,void 0,void 0,function(){var e=this;return l(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 o=i(e.trouterCfg,e.logger,e.ecsCfg);e.trouterServer.configure(o);}n();})]})})},t.prototype.checkConnection=function(t){void 0!==this.trouterServer&&this.trouterServer.checkConnection(null!==t&&void 0!==t&&t);},t.prototype.resendRegistration=function(){return d(this,void 0,void 0,function(){return l(this,function(t){if(!this.trouterServer)throw new 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 valid")),!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,s=e;r<s.length;r++){var i=s[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(g.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(g.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!==g.UserActivityState.Active&&t!==g.UserActivityState.Inactive)throw new Error("setUserActivityState called with unsupported value ".concat(t));this.logger.info("setUserActivityState called with value ".concat(g.UserActivityState[t])),this.trouterServer&&this.state()!==g.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 new Error("Only singular audience subscription is supported");if(this.trouterServer&&this.state()!==g.TrouterState.Unknown)return this.trouterServer.setAudienceSubscriptionsAsync(t,15e3,e);throw new Error("audience subscribe called before start() or after stop()")},t.prototype.state=function(){return void 0!==this.trouterServer?this.trouterServer.getState():g.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(new 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.forEach(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{n=JSON.parse(t.body),o=n&&(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=S,e.createTrouterService=r,e.getTrouterServiceVersion=s,e.replaceTrouterUrlBase=c;},function(e,n){e.exports=t;}])});

	});

	unwrapExports(tstrouter);

	// Unique ID creation requires a high quality random # generator. In the browser we therefore
	// require the crypto API and do not support built-in fallback to lower quality random number
	// generators (like Math.random()).
	var getRandomValues;
	var rnds8 = new Uint8Array(16);
	function rng() {
	  // lazy load so that environments that need to polyfill have a chance to do so
	  if (!getRandomValues) {
	    // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also,
	    // find the complete implementation of crypto (msCrypto) on IE11.
	    getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);

	    if (!getRandomValues) {
	      throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
	    }
	  }

	  return getRandomValues(rnds8);
	}

	var REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;

	function validate(uuid) {
	  return typeof uuid === 'string' && REGEX.test(uuid);
	}

	/**
	 * Convert array of 16 byte values to UUID string format of the form:
	 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
	 */

	var byteToHex = [];

	for (var i = 0; i < 256; ++i) {
	  byteToHex.push((i + 0x100).toString(16).substr(1));
	}

	function stringify(arr) {
	  var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
	  // Note: Be careful editing this code!  It's been tuned for performance
	  // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
	  var uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID.  If this throws, it's likely due to one
	  // of the following:
	  // - One or more input array values don't map to a hex octet (leading to
	  // "undefined" in the uuid)
	  // - Invalid input values for the RFC `version` or `variant` fields

	  if (!validate(uuid)) {
	    throw TypeError('Stringified UUID is invalid');
	  }

	  return uuid;
	}

	//
	// Inspired by https://github.com/LiosK/UUID.js
	// and http://docs.python.org/library/uuid.html

	var _nodeId;

	var _clockseq; // Previous uuid creation time


	var _lastMSecs = 0;
	var _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details

	function v1(options, buf, offset) {
	  var i = buf && offset || 0;
	  var b = buf || new Array(16);
	  options = options || {};
	  var node = options.node || _nodeId;
	  var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not
	  // specified.  We do this lazily to minimize issues related to insufficient
	  // system entropy.  See #189

	  if (node == null || clockseq == null) {
	    var seedBytes = options.random || (options.rng || rng)();

	    if (node == null) {
	      // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
	      node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];
	    }

	    if (clockseq == null) {
	      // Per 4.2.2, randomize (14 bit) clockseq
	      clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
	    }
	  } // UUID timestamps are 100 nano-second units since the Gregorian epoch,
	  // (1582-10-15 00:00).  JSNumbers aren't precise enough for this, so
	  // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
	  // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.


	  var msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock
	  // cycle to simulate higher resolution clock

	  var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs)

	  var dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression

	  if (dt < 0 && options.clockseq === undefined) {
	    clockseq = clockseq + 1 & 0x3fff;
	  } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
	  // time interval


	  if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
	    nsecs = 0;
	  } // Per 4.2.1.2 Throw error if too many uuids are requested


	  if (nsecs >= 10000) {
	    throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");
	  }

	  _lastMSecs = msecs;
	  _lastNSecs = nsecs;
	  _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch

	  msecs += 12219292800000; // `time_low`

	  var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
	  b[i++] = tl >>> 24 & 0xff;
	  b[i++] = tl >>> 16 & 0xff;
	  b[i++] = tl >>> 8 & 0xff;
	  b[i++] = tl & 0xff; // `time_mid`

	  var tmh = msecs / 0x100000000 * 10000 & 0xfffffff;
	  b[i++] = tmh >>> 8 & 0xff;
	  b[i++] = tmh & 0xff; // `time_high_and_version`

	  b[i++] = tmh >>> 24 & 0xf | 0x10; // include version

	  b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)

	  b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low`

	  b[i++] = clockseq & 0xff; // `node`

	  for (var n = 0; n < 6; ++n) {
	    b[i + n] = node[n];
	  }

	  return buf || stringify(b);
	}

	function parse$2(uuid) {
	  if (!validate(uuid)) {
	    throw TypeError('Invalid UUID');
	  }

	  var v;
	  var arr = new Uint8Array(16); // Parse ########-....-....-....-............

	  arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;
	  arr[1] = v >>> 16 & 0xff;
	  arr[2] = v >>> 8 & 0xff;
	  arr[3] = v & 0xff; // Parse ........-####-....-....-............

	  arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;
	  arr[5] = v & 0xff; // Parse ........-....-####-....-............

	  arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;
	  arr[7] = v & 0xff; // Parse ........-....-....-####-............

	  arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;
	  arr[9] = v & 0xff; // Parse ........-....-....-....-############
	  // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes)

	  arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;
	  arr[11] = v / 0x100000000 & 0xff;
	  arr[12] = v >>> 24 & 0xff;
	  arr[13] = v >>> 16 & 0xff;
	  arr[14] = v >>> 8 & 0xff;
	  arr[15] = v & 0xff;
	  return arr;
	}

	function stringToBytes(str) {
	  str = unescape(encodeURIComponent(str)); // UTF8 escape

	  var bytes = [];

	  for (var i = 0; i < str.length; ++i) {
	    bytes.push(str.charCodeAt(i));
	  }

	  return bytes;
	}

	var DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
	var URL$1 = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
	function v35 (name, version, hashfunc) {
	  function generateUUID(value, namespace, buf, offset) {
	    if (typeof value === 'string') {
	      value = stringToBytes(value);
	    }

	    if (typeof namespace === 'string') {
	      namespace = parse$2(namespace);
	    }

	    if (namespace.length !== 16) {
	      throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');
	    } // Compute hash of namespace and value, Per 4.3
	    // Future: Use spread syntax when supported on all platforms, e.g. `bytes =
	    // hashfunc([...namespace, ... value])`


	    var bytes = new Uint8Array(16 + value.length);
	    bytes.set(namespace);
	    bytes.set(value, namespace.length);
	    bytes = hashfunc(bytes);
	    bytes[6] = bytes[6] & 0x0f | version;
	    bytes[8] = bytes[8] & 0x3f | 0x80;

	    if (buf) {
	      offset = offset || 0;

	      for (var i = 0; i < 16; ++i) {
	        buf[offset + i] = bytes[i];
	      }

	      return buf;
	    }

	    return stringify(bytes);
	  } // Function#name is not settable on some platforms (#270)


	  try {
	    generateUUID.name = name; // eslint-disable-next-line no-empty
	  } catch (err) {} // For CommonJS default export support


	  generateUUID.DNS = DNS;
	  generateUUID.URL = URL$1;
	  return generateUUID;
	}

	/*
	 * Browser-compatible JavaScript MD5
	 *
	 * Modification of JavaScript MD5
	 * https://github.com/blueimp/JavaScript-MD5
	 *
	 * Copyright 2011, Sebastian Tschan
	 * https://blueimp.net
	 *
	 * Licensed under the MIT license:
	 * https://opensource.org/licenses/MIT
	 *
	 * Based on
	 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
	 * Digest Algorithm, as defined in RFC 1321.
	 * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
	 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
	 * Distributed under the BSD License
	 * See http://pajhome.org.uk/crypt/md5 for more info.
	 */
	function md5(bytes) {
	  if (typeof bytes === 'string') {
	    var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape

	    bytes = new Uint8Array(msg.length);

	    for (var i = 0; i < msg.length; ++i) {
	      bytes[i] = msg.charCodeAt(i);
	    }
	  }

	  return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8));
	}
	/*
	 * Convert an array of little-endian words to an array of bytes
	 */


	function md5ToHexEncodedArray(input) {
	  var output = [];
	  var length32 = input.length * 32;
	  var hexTab = '0123456789abcdef';

	  for (var i = 0; i < length32; i += 8) {
	    var x = input[i >> 5] >>> i % 32 & 0xff;
	    var hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16);
	    output.push(hex);
	  }

	  return output;
	}
	/**
	 * Calculate output length with padding and bit length
	 */


	function getOutputLength(inputLength8) {
	  return (inputLength8 + 64 >>> 9 << 4) + 14 + 1;
	}
	/*
	 * Calculate the MD5 of an array of little-endian words, and a bit length.
	 */


	function wordsToMd5(x, len) {
	  /* append padding */
	  x[len >> 5] |= 0x80 << len % 32;
	  x[getOutputLength(len) - 1] = len;
	  var a = 1732584193;
	  var b = -271733879;
	  var c = -1732584194;
	  var d = 271733878;

	  for (var i = 0; i < x.length; i += 16) {
	    var olda = a;
	    var oldb = b;
	    var oldc = c;
	    var oldd = d;
	    a = md5ff(a, b, c, d, x[i], 7, -680876936);
	    d = md5ff(d, a, b, c, x[i + 1], 12, -389564586);
	    c = md5ff(c, d, a, b, x[i + 2], 17, 606105819);
	    b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330);
	    a = md5ff(a, b, c, d, x[i + 4], 7, -176418897);
	    d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426);
	    c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341);
	    b = md5ff(b, c, d, a, x[i + 7], 22, -45705983);
	    a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416);
	    d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417);
	    c = md5ff(c, d, a, b, x[i + 10], 17, -42063);
	    b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162);
	    a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682);
	    d = md5ff(d, a, b, c, x[i + 13], 12, -40341101);
	    c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290);
	    b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329);
	    a = md5gg(a, b, c, d, x[i + 1], 5, -165796510);
	    d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632);
	    c = md5gg(c, d, a, b, x[i + 11], 14, 643717713);
	    b = md5gg(b, c, d, a, x[i], 20, -373897302);
	    a = md5gg(a, b, c, d, x[i + 5], 5, -701558691);
	    d = md5gg(d, a, b, c, x[i + 10], 9, 38016083);
	    c = md5gg(c, d, a, b, x[i + 15], 14, -660478335);
	    b = md5gg(b, c, d, a, x[i + 4], 20, -405537848);
	    a = md5gg(a, b, c, d, x[i + 9], 5, 568446438);
	    d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690);
	    c = md5gg(c, d, a, b, x[i + 3], 14, -187363961);
	    b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501);
	    a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467);
	    d = md5gg(d, a, b, c, x[i + 2], 9, -51403784);
	    c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473);
	    b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734);
	    a = md5hh(a, b, c, d, x[i + 5], 4, -378558);
	    d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463);
	    c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562);
	    b = md5hh(b, c, d, a, x[i + 14], 23, -35309556);
	    a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060);
	    d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353);
	    c = md5hh(c, d, a, b, x[i + 7], 16, -155497632);
	    b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640);
	    a = md5hh(a, b, c, d, x[i + 13], 4, 681279174);
	    d = md5hh(d, a, b, c, x[i], 11, -358537222);
	    c = md5hh(c, d, a, b, x[i + 3], 16, -722521979);
	    b = md5hh(b, c, d, a, x[i + 6], 23, 76029189);
	    a = md5hh(a, b, c, d, x[i + 9], 4, -640364487);
	    d = md5hh(d, a, b, c, x[i + 12], 11, -421815835);
	    c = md5hh(c, d, a, b, x[i + 15], 16, 530742520);
	    b = md5hh(b, c, d, a, x[i + 2], 23, -995338651);
	    a = md5ii(a, b, c, d, x[i], 6, -198630844);
	    d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415);
	    c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905);
	    b = md5ii(b, c, d, a, x[i + 5], 21, -57434055);
	    a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571);
	    d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606);
	    c = md5ii(c, d, a, b, x[i + 10], 15, -1051523);
	    b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799);
	    a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359);
	    d = md5ii(d, a, b, c, x[i + 15], 10, -30611744);
	    c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380);
	    b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649);
	    a = md5ii(a, b, c, d, x[i + 4], 6, -145523070);
	    d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379);
	    c = md5ii(c, d, a, b, x[i + 2], 15, 718787259);
	    b = md5ii(b, c, d, a, x[i + 9], 21, -343485551);
	    a = safeAdd(a, olda);
	    b = safeAdd(b, oldb);
	    c = safeAdd(c, oldc);
	    d = safeAdd(d, oldd);
	  }

	  return [a, b, c, d];
	}
	/*
	 * Convert an array bytes to an array of little-endian words
	 * Characters >255 have their high-byte silently ignored.
	 */


	function bytesToWords(input) {
	  if (input.length === 0) {
	    return [];
	  }

	  var length8 = input.length * 8;
	  var output = new Uint32Array(getOutputLength(length8));

	  for (var i = 0; i < length8; i += 8) {
	    output[i >> 5] |= (input[i / 8] & 0xff) << i % 32;
	  }

	  return output;
	}
	/*
	 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
	 * to work around bugs in some JS interpreters.
	 */


	function safeAdd(x, y) {
	  var lsw = (x & 0xffff) + (y & 0xffff);
	  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
	  return msw << 16 | lsw & 0xffff;
	}
	/*
	 * Bitwise rotate a 32-bit number to the left.
	 */


	function bitRotateLeft(num, cnt) {
	  return num << cnt | num >>> 32 - cnt;
	}
	/*
	 * These functions implement the four basic operations the algorithm uses.
	 */


	function md5cmn(q, a, b, x, s, t) {
	  return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b);
	}

	function md5ff(a, b, c, d, x, s, t) {
	  return md5cmn(b & c | ~b & d, a, b, x, s, t);
	}

	function md5gg(a, b, c, d, x, s, t) {
	  return md5cmn(b & d | c & ~d, a, b, x, s, t);
	}

	function md5hh(a, b, c, d, x, s, t) {
	  return md5cmn(b ^ c ^ d, a, b, x, s, t);
	}

	function md5ii(a, b, c, d, x, s, t) {
	  return md5cmn(c ^ (b | ~d), a, b, x, s, t);
	}

	var v3 = v35('v3', 0x30, md5);
	var v3$1 = v3;

	function v4(options, buf, offset) {
	  options = options || {};
	  var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`

	  rnds[6] = rnds[6] & 0x0f | 0x40;
	  rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided

	  if (buf) {
	    offset = offset || 0;

	    for (var i = 0; i < 16; ++i) {
	      buf[offset + i] = rnds[i];
	    }

	    return buf;
	  }

	  return stringify(rnds);
	}

	// Adapted from Chris Veness' SHA1 code at
	// http://www.movable-type.co.uk/scripts/sha1.html
	function f(s, x, y, z) {
	  switch (s) {
	    case 0:
	      return x & y ^ ~x & z;

	    case 1:
	      return x ^ y ^ z;

	    case 2:
	      return x & y ^ x & z ^ y & z;

	    case 3:
	      return x ^ y ^ z;
	  }
	}

	function ROTL(x, n) {
	  return x << n | x >>> 32 - n;
	}

	function sha1(bytes) {
	  var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];
	  var H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];

	  if (typeof bytes === 'string') {
	    var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape

	    bytes = [];

	    for (var i = 0; i < msg.length; ++i) {
	      bytes.push(msg.charCodeAt(i));
	    }
	  } else if (!Array.isArray(bytes)) {
	    // Convert Array-like to Array
	    bytes = Array.prototype.slice.call(bytes);
	  }

	  bytes.push(0x80);
	  var l = bytes.length / 4 + 2;
	  var N = Math.ceil(l / 16);
	  var M = new Array(N);

	  for (var _i = 0; _i < N; ++_i) {
	    var arr = new Uint32Array(16);

	    for (var j = 0; j < 16; ++j) {
	      arr[j] = bytes[_i * 64 + j * 4] << 24 | bytes[_i * 64 + j * 4 + 1] << 16 | bytes[_i * 64 + j * 4 + 2] << 8 | bytes[_i * 64 + j * 4 + 3];
	    }

	    M[_i] = arr;
	  }

	  M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32);
	  M[N - 1][14] = Math.floor(M[N - 1][14]);
	  M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff;

	  for (var _i2 = 0; _i2 < N; ++_i2) {
	    var W = new Uint32Array(80);

	    for (var t = 0; t < 16; ++t) {
	      W[t] = M[_i2][t];
	    }

	    for (var _t = 16; _t < 80; ++_t) {
	      W[_t] = ROTL(W[_t - 3] ^ W[_t - 8] ^ W[_t - 14] ^ W[_t - 16], 1);
	    }

	    var a = H[0];
	    var b = H[1];
	    var c = H[2];
	    var d = H[3];
	    var e = H[4];

	    for (var _t2 = 0; _t2 < 80; ++_t2) {
	      var s = Math.floor(_t2 / 20);
	      var T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[_t2] >>> 0;
	      e = d;
	      d = c;
	      c = ROTL(b, 30) >>> 0;
	      b = a;
	      a = T;
	    }

	    H[0] = H[0] + a >>> 0;
	    H[1] = H[1] + b >>> 0;
	    H[2] = H[2] + c >>> 0;
	    H[3] = H[3] + d >>> 0;
	    H[4] = H[4] + e >>> 0;
	  }

	  return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff];
	}

	var v5 = v35('v5', 0x50, sha1);
	var v5$1 = v5;

	var nil = '00000000-0000-0000-0000-000000000000';

	function version(uuid) {
	  if (!validate(uuid)) {
	    throw TypeError('Invalid UUID');
	  }

	  return parseInt(uuid.substr(14, 1), 16);
	}

	var esmBrowser = /*#__PURE__*/Object.freeze({
		__proto__: null,
		v1: v1,
		v3: v3$1,
		v4: v4,
		v5: v5$1,
		NIL: nil,
		version: version,
		validate: validate,
		stringify: stringify,
		parse: parse$2
	});

	var chat = createCommonjsModule(function (module, exports) {
	// Copyright (c) Microsoft Corporation.
	// Licensed under the MIT license.
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.DeleteReason = void 0;
	var DeleteReason;
	(function (DeleteReason) {
	    DeleteReason["DeletedByPolicy"] = "deletedByPolicy";
	    DeleteReason["DeletedByUser"] = "deletedByUser";
	})(DeleteReason || (exports.DeleteReason = DeleteReason = {}));
	});

	unwrapExports(chat);
	chat.DeleteReason;

	// Copyright (c) Microsoft Corporation.
	// Licensed under the MIT license.
	/**
	 * This error is thrown when an asynchronous operation has been aborted.
	 * Check for this error by testing the `name` that the name property of the
	 * error matches `"AbortError"`.
	 *
	 * @example
	 * ```ts
	 * const controller = new AbortController();
	 * controller.abort();
	 * try {
	 *   doAsyncWork(controller.signal)
	 * } catch (e) {
	 *   if (e.name === 'AbortError') {
	 *     // handle abort error here.
	 *   }
	 * }
	 * ```
	 */
	class AbortError extends Error {
	    constructor(message) {
	        super(message);
	        this.name = "AbortError";
	    }
	}

	// Copyright (c) Microsoft Corporation.
	/**
	 * Creates an abortable promise.
	 * @param buildPromise - A function that takes the resolve and reject functions as parameters.
	 * @param options - The options for the abortable promise.
	 * @returns A promise that can be aborted.
	 */
	function createAbortablePromise(buildPromise, options) {
	    const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {};
	    return new Promise((resolve, reject) => {
	        function rejectOnAbort() {
	            reject(new AbortError(abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : "The operation was aborted."));
	        }
	        function removeListeners() {
	            abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.removeEventListener("abort", onAbort);
	        }
	        function onAbort() {
	            cleanupBeforeAbort === null || cleanupBeforeAbort === void 0 ? void 0 : cleanupBeforeAbort();
	            removeListeners();
	            rejectOnAbort();
	        }
	        if (abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.aborted) {
	            return rejectOnAbort();
	        }
	        try {
	            buildPromise((x) => {
	                removeListeners();
	                resolve(x);
	            }, (x) => {
	                removeListeners();
	                reject(x);
	            });
	        }
	        catch (err) {
	            reject(err);
	        }
	        abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.addEventListener("abort", onAbort);
	    });
	}

	// Copyright (c) Microsoft Corporation.
	const StandardAbortMessage$1 = "The delay was aborted.";
	/**
	 * A wrapper for setTimeout that resolves a promise after timeInMs milliseconds.
	 * @param timeInMs - The number of milliseconds to be delayed.
	 * @param options - The options for delay - currently abort options
	 * @returns Promise that is resolved after timeInMs
	 */
	function delay$1(timeInMs, options) {
	    let token;
	    const { abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {};
	    return createAbortablePromise((resolve) => {
	        token = setTimeout(resolve, timeInMs);
	    }, {
	        cleanupBeforeAbort: () => clearTimeout(token),
	        abortSignal,
	        abortErrorMsg: abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : StandardAbortMessage$1,
	    });
	}

	// Copyright (c) Microsoft Corporation.
	// Licensed under the MIT license.
	/**
	 * promise.race() wrapper that aborts rest of promises as soon as the first promise settles.
	 */
	async function cancelablePromiseRace(abortablePromiseBuilders, options) {
	    var _a, _b;
	    const aborter = new AbortController();
	    function abortHandler() {
	        aborter.abort();
	    }
	    (_a = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _a === void 0 ? void 0 : _a.addEventListener("abort", abortHandler);
	    try {
	        return await Promise.race(abortablePromiseBuilders.map((p) => p({ abortSignal: aborter.signal })));
	    }
	    finally {
	        aborter.abort();
	        (_b = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _b === void 0 ? void 0 : _b.removeEventListener("abort", abortHandler);
	    }
	}

	// Copyright (c) Microsoft Corporation.
	// Licensed under the MIT license.
	/**
	 * Returns a random integer value between a lower and upper bound,
	 * inclusive of both bounds.
	 * Note that this uses Math.random and isn't secure. If you need to use
	 * this for any kind of security purpose, find a better source of random.
	 * @param min - The smallest integer value allowed.
	 * @param max - The largest integer value allowed.
	 */
	function getRandomIntegerInclusive(min, max) {
	    // Make sure inputs are integers.
	    min = Math.ceil(min);
	    max = Math.floor(max);
	    // Pick a random offset from zero to the size of the range.
	    // Since Math.random() can never return 1, we have to make the range one larger
	    // in order to be inclusive of the maximum value after we take the floor.
	    const offset = Math.floor(Math.random() * (max - min + 1));
	    return offset + min;
	}

	// Copyright (c) Microsoft Corporation.
	// Licensed under the MIT license.
	/**
	 * Helper to determine when an input is a generic JS object.
	 * @returns true when input is an object type that is not null, Array, RegExp, or Date.
	 */
	function isObject(input) {
	    return (typeof input === "object" &&
	        input !== null &&
	        !Array.isArray(input) &&
	        !(input instanceof RegExp) &&
	        !(input instanceof Date));
	}

	// Copyright (c) Microsoft Corporation.
	/**
	 * Typeguard for an error object shape (has name and message)
	 * @param e - Something caught by a catch clause.
	 */
	function isError(e) {
	    if (isObject(e)) {
	        const hasName = typeof e.name === "string";
	        const hasMessage = typeof e.message === "string";
	        return hasName && hasMessage;
	    }
	    return false;
	}
	/**
	 * Given what is thought to be an error object, return the message if possible.
	 * If the message is missing, returns a stringified version of the input.
	 * @param e - Something thrown from a try block
	 * @returns The error message or a string of the input
	 */
	function getErrorMessage(e) {
	    if (isError(e)) {
	        return e.message;
	    }
	    else {
	        let stringified;
	        try {
	            if (typeof e === "object" && e) {
	                stringified = JSON.stringify(e);
	            }
	            else {
	                stringified = String(e);
	            }
	        }
	        catch (err) {
	            stringified = "[unable to stringify input]";
	        }
	        return `Unknown error ${stringified}`;
	    }
	}

	// Copyright (c) Microsoft Corporation.
	/**
	 * Generates a SHA-256 HMAC signature.
	 * @param key - The HMAC key represented as a base64 string, used to generate the cryptographic HMAC hash.
	 * @param stringToSign - The data to be signed.
	 * @param encoding - The textual encoding to use for the returned HMAC digest.
	 */
	async function computeSha256Hmac(key, stringToSign, encoding) {
	    const decodedKey = Buffer.from(key, "base64");
	    return crypto$1.createHmac("sha256", decodedKey).update(stringToSign).digest(encoding);
	}
	/**
	 * Generates a SHA-256 hash.
	 * @param content - The data to be included in the hash.
	 * @param encoding - The textual encoding to use for the returned hash.
	 */
	async function computeSha256Hash(content, encoding) {
	    return crypto$1.createHash("sha256").update(content).digest(encoding);
	}

	// Copyright (c) Microsoft Corporation.
	// Licensed under the MIT license.
	/**
	 * Helper TypeGuard that checks if something is defined or not.
	 * @param thing - Anything
	 */
	function isDefined(thing) {
	    return typeof thing !== "undefined" && thing !== null;
	}
	/**
	 * Helper TypeGuard that checks if the input is an object with the specified properties.
	 * @param thing - Anything.
	 * @param properties - The name of the properties that should appear in the object.
	 */
	function isObjectWithProperties(thing, properties) {
	    if (!isDefined(thing) || typeof thing !== "object") {
	        return false;
	    }
	    for (const property of properties) {
	        if (!objectHasProperty(thing, property)) {
	            return false;
	        }
	    }
	    return true;
	}
	/**
	 * Helper TypeGuard that checks if the input is an object with the specified property.
	 * @param thing - Any object.
	 * @param property - The name of the property that should appear in the object.
	 */
	function objectHasProperty(thing, property) {
	    return (isDefined(thing) && typeof thing === "object" && property in thing);
	}

	// Copyright (c) Microsoft Corporation.
	// Licensed under the MIT license.
	var _a$1;
	// NOTE: This is a workaround until we can use `globalThis.crypto.randomUUID` in Node.js 19+.
	const uuidFunction = typeof ((_a$1 = globalThis === null || globalThis === void 0 ? void 0 : globalThis.crypto) === null || _a$1 === void 0 ? void 0 : _a$1.randomUUID) === "function"
	    ? globalThis.crypto.randomUUID.bind(globalThis.crypto)
	    : crypto$1.randomUUID;
	/**
	 * Generated Universally Unique Identifier
	 *
	 * @returns RFC4122 v4 UUID.
	 */
	function randomUUID() {
	    return uuidFunction();
	}

	// Copyright (c) Microsoft Corporation.
	// Licensed under the MIT license.
	var _a, _b, _c, _d;
	/**
	 * A constant that indicates whether the environment the code is running is a Web Browser.
	 */
	// eslint-disable-next-line @azure/azure-sdk/ts-no-window
	const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined";
	/**
	 * A constant that indicates whether the environment the code is running is a Web Worker.
	 */
	const isWebWorker = typeof self === "object" &&
	    typeof (self === null || self === void 0 ? void 0 : self.importScripts) === "function" &&
	    (((_a = self.constructor) === null || _a === void 0 ? void 0 : _a.name) === "DedicatedWorkerGlobalScope" ||
	        ((_b = self.constructor) === null || _b === void 0 ? void 0 : _b.name) === "ServiceWorkerGlobalScope" ||
	        ((_c = self.constructor) === null || _c === void 0 ? void 0 : _c.name) === "SharedWorkerGlobalScope");
	/**
	 * A constant that indicates whether the environment the code is running is Deno.
	 */
	const isDeno = typeof Deno !== "undefined" &&
	    typeof Deno.version !== "undefined" &&
	    typeof Deno.version.deno !== "undefined";
	/**
	 * A constant that indicates whether the environment the code is running is Bun.sh.
	 */
	const isBun = typeof Bun !== "undefined" && typeof Bun.version !== "undefined";
	/**
	 * A constant that indicates whether the environment the code is running is a Node.js compatible environment.
	 */
	const isNodeLike = typeof globalThis.process !== "undefined" &&
	    Boolean(globalThis.process.version) &&
	    Boolean((_d = globalThis.process.versions) === null || _d === void 0 ? void 0 : _d.node);
	/**
	 * A constant that indicates whether the environment the code is running is a Node.js compatible environment.
	 * @deprecated Use `isNodeLike` instead.
	 */
	const isNode = isNodeLike;
	/**
	 * A constant that indicates whether the environment the code is running is Node.JS.
	 */
	const isNodeRuntime = isNodeLike && !isBun && !isDeno;
	/**
	 * A constant that indicates whether the environment the code is running is in React-Native.
	 */
	// https://github.com/facebook/react-native/blob/main/packages/react-native/Libraries/Core/setUpNavigator.js
	const isReactNative = typeof navigator !== "undefined" && (navigator === null || navigator === void 0 ? void 0 : navigator.product) === "ReactNative";

	// Copyright (c) Microsoft Corporation.
	// Licensed under the MIT license.
	/**
	 * The helper that transforms bytes with specific character encoding into string
	 * @param bytes - the uint8array bytes
	 * @param format - the format we use to encode the byte
	 * @returns a string of the encoded string
	 */
	function uint8ArrayToString(bytes, format) {
	    return Buffer.from(bytes).toString(format);
	}
	/**
	 * The helper that transforms string to specific character encoded bytes array.
	 * @param value - the string to be converted
	 * @param format - the format we use to decode the value
	 * @returns a uint8array
	 */
	function stringToUint8Array(value, format) {
	    return Buffer.from(value, format);
	}

	// Copyright (c) Microsoft Corporation.

	var esm$1 = /*#__PURE__*/Object.freeze({
		__proto__: null,
		delay: delay$1,
		cancelablePromiseRace: cancelablePromiseRace,
		createAbortablePromise: createAbortablePromise,
		getRandomIntegerInclusive: getRandomIntegerInclusive,
		isObject: isObject,
		isError: isError,
		getErrorMessage: getErrorMessage,
		computeSha256Hash: computeSha256Hash,
		computeSha256Hmac: computeSha256Hmac,
		isDefined: isDefined,
		isObjectWithProperties: isObjectWithProperties,
		objectHasProperty: objectHasProperty,
		randomUUID: randomUUID,
		isBrowser: isBrowser,
		isBun: isBun,
		isNode: isNode,
		isNodeLike: isNodeLike,
		isNodeRuntime: isNodeRuntime,
		isDeno: isDeno,
		isReactNative: isReactNative,
		isWebWorker: isWebWorker,
		uint8ArrayToString: uint8ArrayToString,
		stringToUint8Array: stringToUint8Array
	});

	var constants = createCommonjsModule(function (module, exports) {
	// Copyright (c) Microsoft Corporation.
	// Licensed under the MIT license.
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.PACKAGE_VERSION = exports.CONFIG_API_VERSION = exports.EudbCountries = exports.CloudPrefix = exports.CloudType = exports.MAX_NUMBER_OF_TOKEN_FETCH_RETRIES = void 0;
	exports.MAX_NUMBER_OF_TOKEN_FETCH_RETRIES = 3;
	// Gov cloud types
	var CloudType;
	(function (CloudType) {
	    CloudType["Public"] = "Public";
	    CloudType["GccHigh"] = "GCC High";
	    CloudType["Dod"] = "DoD";
	})(CloudType || (exports.CloudType = CloudType = {}));
	var CloudPrefix;
	(function (CloudPrefix) {
	    CloudPrefix["OrgId"] = "orgid";
	    CloudPrefix["Acs"] = "acs";
	    CloudPrefix["Spool"] = "spool";
	    CloudPrefix["GccHigh"] = "gcch";
	    CloudPrefix["GccHighAcs"] = "gcch-acs";
	    CloudPrefix["Dod"] = "dod";
	    CloudPrefix["DodAcs"] = "dod-acs";
	})(CloudPrefix || (exports.CloudPrefix = CloudPrefix = {}));
	exports.EudbCountries = ["europe", "france", "germany", "norway", "switzerland", "sweden"];
	exports.CONFIG_API_VERSION = "2024-09-01";
	exports.PACKAGE_VERSION = "1.0.0-beta.34";
	});

	unwrapExports(constants);
	constants.PACKAGE_VERSION;
	constants.CONFIG_API_VERSION;
	constants.EudbCountries;
	constants.CloudPrefix;
	constants.CloudType;
	constants.MAX_NUMBER_OF_TOKEN_FETCH_RETRIES;

	var chat_1 = chat;

	var constants_1 = constants;

	var TrouterUtils = createCommonjsModule(function (module, exports) {
	// Copyright (c) Microsoft Corporation.
	// Licensed under the MIT license.
	var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
	    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
	    return new (P || (P = Promise))(function (resolve, reject) {
	        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
	        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
	        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
	        step((generator = generator.apply(thisArg, _arguments || [])).next());
	    });
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.isEudbLocation = exports.parseTokenCredential = exports.base64decode = exports.toTelemetrySender = exports.toLogProvider = exports.toMessageHandler = void 0;
	exports.generateUuid = generateUuid;




	const eventIds = new Map([
	    ["chatMessageReceived", 200],
	    ["typingIndicatorReceived", 245],
	    ["readReceiptReceived", 246],
	    ["chatMessageEdited", 247],
	    ["chatMessageDeleted", 248],
	    ["chatThreadCreated", 257],
	    ["chatThreadPropertiesUpdated", 258],
	    ["chatThreadDeleted", 259],
	    ["participantsAdded", 260],
	    ["participantsRemoved", 261],
	]);
	const publicTeamsUserPrefix = "8:orgid:";
	const dodTeamsUserPrefix = "8:dod:";
	const gcchTeamsUserPrefix = "8:gcch:";
	const teamsVisitorUserPrefix = "8:teamsvisitor:";
	const phoneNumberPrefix = "4:";
	const acsUserPrefix = "8:acs:";
	const acsGcchUserPrefix = "8:gcch-acs:";
	const acsDodUserPrefix = "8:dod-acs:";
	const spoolUserPrefix = "8:spool:";
	const toMessageHandler = (event, listener, resourceEndpoint, gatewayApiVersion) => {
	    const eventId = eventIds.get(event);
	    return {
	        handleMessage(message) {
	            let genericPayload = null;
	            if (message === null || message === void 0 ? void 0 : message.rawBody) {
	                genericPayload = JSON.parse(message.rawBody);
	            }
	            if (genericPayload === null || genericPayload.eventId !== eventId) {
	                return undefined;
	            }
	            const eventPayload = toEventPayload(event, genericPayload, resourceEndpoint, gatewayApiVersion);
	            if (eventPayload === null) {
	                return undefined;
	            }
	            listener(eventPayload);
	            return { isHandled: true, resultCode: 200 };
	        },
	    };
	};
	exports.toMessageHandler = toMessageHandler;
	function toChatMessageReceivedEvent(payload, resourceEndpoint, gatewayApiVersion) {
	    return {
	        threadId: payload.groupId,
	        sender: constructIdentifierKindFromMri(payload.senderId),
	        senderDisplayName: payload.senderDisplayName,
	        recipient: constructIdentifierKindFromMri(payload.recipientMri),
	        id: payload.messageId,
	        createdOn: new Date(payload.originalArrivalTime),
	        version: payload.version,
	        type: payload.messageType,
	        message: payload.messageBody,
	        metadata: parseJsonString(payload.acsChatMessageMetadata) || {},
	        attachments: transformEndpoint(parseJsonString(payload.attachments) || [], resourceEndpoint, gatewayApiVersion),
	    };
	}
	function toChatMessageEditedEvent(payload, resourceEndpoint, gatewayApiVersion) {
	    return Object.assign(Object.assign({}, toChatMessageReceivedEvent(payload, resourceEndpoint, gatewayApiVersion)), { editedOn: new Date(payload.edittime) });
	}
	const toEventPayload = (event, genericPayload, resourceEndpoint, gatewayApiVersion) => {
	    if (event === "chatMessageReceived") {
	        const payload = genericPayload;
	        return toChatMessageReceivedEvent(payload, resourceEndpoint, gatewayApiVersion);
	    }
	    if (event === "chatMessageEdited") {
	        const payload = genericPayload;
	        return toChatMessageEditedEvent(payload, resourceEndpoint, gatewayApiVersion);
	    }
	    if (event === "chatMessageDeleted") {
	        const payload = genericPayload;
	        const eventPayload = {
	            threadId: payload.groupId,
	            sender: constructIdentifierKindFromMri(payload.senderId),
	            senderDisplayName: payload.senderDisplayName,
	            recipient: constructIdentifierKindFromMri(payload.recipientMri),
	            id: payload.messageId,
	            createdOn: new Date(payload.originalArrivalTime),
	            version: payload.version,
	            deletedOn: new Date(payload.deletetime),
	            type: payload.messageType,
	        };
	        return eventPayload;
	    }
	    if (event === "typingIndicatorReceived") {
	        const payload = genericPayload;
	        const eventPayload = {
	            threadId: payload.groupId,
	            sender: constructIdentifierKindFromMri(payload.senderId),
	            senderDisplayName: payload.senderDisplayName,
	            recipient: constructIdentifierKindFromMri(payload.recipientMri),
	            version: payload.version,
	            receivedOn: new Date(payload.originalArrivalTime),
	        };
	        return eventPayload;
	    }
	    if (event === "readReceiptReceived") {
	        const payload = genericPayload;
	        const readReceiptMessageBody = JSON.parse(payload.messageBody);
	        const consumptionHorizon = readReceiptMessageBody.consumptionhorizon.split(";");
	        const eventPayload = {
	            threadId: payload.groupId,
	            sender: constructIdentifierKindFromMri(payload.senderId),
	            senderDisplayName: "",
	            recipient: constructIdentifierKindFromMri(payload.recipientMri),
	            chatMessageId: payload.messageId,
	            readOn: new Date(+consumptionHorizon[1]),
	        };
	        return eventPayload;
	    }
	    if (event === "chatThreadCreated") {
	        const payload = genericPayload;
	        const createdByPayload = JSON.parse(unescape(payload.createdBy));
	        const membersPayload = JSON.parse(unescape(payload.members));
	        const createdBy = toChatParticipant(createdByPayload);
	        const chatParticipants = membersPayload.map((m) => {
	            return toChatParticipant(m);
	        });
	        const eventPayload = {
	            threadId: payload.threadId,
	            createdOn: new Date(payload.createTime),
	            createdBy: createdBy,
	            version: payload.version,
	            participants: chatParticipants,
	            properties: toThreadProperties(JSON.parse(unescape(payload.properties))),
	            retentionPolicy: getRetentionPolicy(JSON.parse(unescape(payload.properties))),
	        };
	        return eventPayload;
	    }
	    if (event === "chatThreadPropertiesUpdated") {
	        const payload = genericPayload;
	        const updatedByPayload = JSON.parse(unescape(payload.editedBy));
	        const updatedBy = toChatParticipant(updatedByPayload);
	        const eventPayload = {
	            threadId: payload.threadId,
	            updatedOn: new Date(payload.editTime),
	            updatedBy: updatedBy,
	            version: payload.version,
	            properties: toThreadProperties(JSON.parse(unescape(payload.properties))),
	            retentionPolicy: getRetentionPolicy(JSON.parse(unescape(payload.properties))),
	        };
	        return eventPayload;
	    }
	    if (event === "chatThreadDeleted") {
	        const payload = genericPayload;
	        const deletedBy = genericPayload.reason == chat_1.DeleteReason.DeletedByPolicy
	            ? null
	            : toChatParticipant(JSON.parse(unescape(payload.deletedBy)));
	        const eventPayload = {
	            threadId: payload.threadId,
	            deletedOn: new Date(payload.deleteTime),
	            deletedBy: deletedBy,
	            version: payload.version,
	            reason: payload.reason,
	        };
	        return eventPayload;
	    }
	    if (event === "participantsAdded") {
	        const payload = genericPayload;
	        const addedByPayload = JSON.parse(unescape(payload.addedBy));
	        const participantsAddedPayload = JSON.parse(unescape(payload.participantsAdded));
	        const addedBy = toChatParticipant(addedByPayload);
	        const chatParticipants = participantsAddedPayload.map((m) => {
	            return toChatParticipant(m);
	        });
	        const eventPayload = {
	            threadId: payload.threadId,
	            addedOn: new Date(payload.time),
	            addedBy: addedBy,
	            version: payload.version,
	            participantsAdded: chatParticipants,
	        };
	        return eventPayload;
	    }
	    if (event === "participantsRemoved") {
	        const payload = genericPayload;
	        const removedByPayload = JSON.parse(unescape(payload.removedBy));
	        const participantsRemovedPayload = JSON.parse(unescape(payload.participantsRemoved));
	        const removedBy = toChatParticipant(removedByPayload);
	        const chatParticipants = participantsRemovedPayload.map((m) => {
	            return toChatParticipant(m);
	        });
	        const eventPayload = {
	            threadId: payload.threadId,
	            removedOn: new Date(payload.time),
	            removedBy: removedBy,
	            version: payload.version,
	            participantsRemoved: chatParticipants,
	        };
	        return eventPayload;
	    }
	    return null;
	};
	const toChatParticipant = (payload) => {
	    var _a;
	    const participant = {
	        id: constructIdentifierKindFromMri(payload.participantId),
	        displayName: payload.displayName,
	        metadata: parseJsonString((_a = payload.memberMetaData) !== null && _a !== void 0 ? _a : "") || {},
	    };
	    if (payload.shareHistoryTime) {
	        participant.shareHistoryTime = new Date(payload.shareHistoryTime);
	    }
	    return participant;
	};
	const toThreadProperties = (payload) => {
	    var _a;
	    return {
	        topic: payload.topic,
	        metadata: parseJsonString((_a = payload.acsChatThreadMetadata) !== null && _a !== void 0 ? _a : "") || {},
	    };
	};
	const getRetentionPolicy = (payload) => {
	    const raw = payload.retentionPolicy;
	    // No policy string ⇒ “none”
	    if (!raw) {
	        return { kind: "none" };
	    }
	    let parsed;
	    try {
	        parsed = JSON.parse(raw);
	    }
	    catch (_a) {
	        return { kind: "none" };
	    }
	    // Expected executeAfter format dd.hh:mm:ss if more than 1 day. Or hh:mm:ss if less than one day.
	    if (parsed.retentionPolicyType === "DeleteAfterCreationTime" &&
	        typeof parsed.executeAfter === "string") {
	        // Handle sign, spaces
	        const s = parsed.executeAfter.trim().replace(/^[+-]/, "");
	        // only take the part before the dot, otherwise 0
	        const daysPart = s.includes(".") ? s.split(".")[0] : "0";
	        const days = parseInt(daysPart, 10);
	        return {
	            kind: "threadCreationDate",
	            deleteThreadAfterDays: isNaN(days) ? 0 : days,
	        };
	    }
	    return { kind: "none" };
	};
	const toLogProvider = (logger) => {
	    return {
	        log: (...message) => logger.info(message),
	        warn: (...message) => logger.warning(message),
	        error: (...message) => logger.error(message),
	        debug: (...message) => logger.verbose(message),
	        info: (...message) => logger.verbose(message),
	    };
	};
	exports.toLogProvider = toLogProvider;
	const toTelemetrySender = (logger) => {
	    return {
	        logEvent: (clientEvent) => logger.info(clientEvent),
	    };
	};
	exports.toTelemetrySender = toTelemetrySender;
	const constructIdentifierKindFromMri = (mri) => {
	    if (mri.startsWith(publicTeamsUserPrefix)) {
	        return {
	            kind: "microsoftTeamsUser",
	            rawId: mri,
	            microsoftTeamsUserId: mri.substring(publicTeamsUserPrefix.length),
	            isAnonymous: false,
	            cloud: "public",
	        };
	    }
	    else if (mri.startsWith(dodTeamsUserPrefix)) {
	        return {
	            kind: "microsoftTeamsUser",
	            rawId: mri,
	            microsoftTeamsUserId: mri.substring(dodTeamsUserPrefix.length),
	            isAnonymous: false,
	            cloud: "dod",
	        };
	    }
	    else if (mri.startsWith(gcchTeamsUserPrefix)) {
	        return {
	            kind: "microsoftTeamsUser",
	            rawId: mri,
	            microsoftTeamsUserId: mri.substring(gcchTeamsUserPrefix.length),
	            isAnonymous: false,
	            cloud: "gcch",
	        };
	    }
	    else if (mri.startsWith(teamsVisitorUserPrefix)) {
	        return {
	            kind: "microsoftTeamsUser",
	            rawId: mri,
	            microsoftTeamsUserId: mri.substring(teamsVisitorUserPrefix.length),
	            isAnonymous: true,
	        };
	    }
	    else if (mri.startsWith(phoneNumberPrefix)) {
	        return {
	            kind: "phoneNumber",
	            rawId: mri,
	            phoneNumber: mri.substring(phoneNumberPrefix.length),
	        };
	    }
	    else if (mri.startsWith(acsUserPrefix) ||
	        mri.startsWith(acsGcchUserPrefix) ||
	        mri.startsWith(acsDodUserPrefix) ||
	        mri.startsWith(spoolUserPrefix)) {
	        return { kind: "communicationUser", communicationUserId: mri };
	    }
	    else {
	        return { kind: "unknown", id: mri };
	    }
	};
	const parseJsonString = (str) => {
	    if (str === undefined ||
	        str === null ||
	        str === "" ||
	        str === "null" ||
	        str === "{}" ||
	        str === "[]") {
	        return undefined;
	    }
	    return JSON.parse(str);
	};
	const createMediaUrlString = (urlString, resourceEndpoint, gatewayApiVersion) => {
	    let url;
	    try {
	        url = new URL(urlString);
	        if (url.protocol === "http:" || url.protocol === "https:") {
	            // If its already a full url, substitute the origin
	            url = new URL(url.pathname, resourceEndpoint);
	        }
	    }
	    catch (_) {
	        // urlString is a likely a relative URL, so create a new one with the resourceEndpoint as base
	        try {
	            url = new URL(urlString, resourceEndpoint);
	        }
	        catch (_) {
	            // If we get here, then the urlString passed in is likely incorrect, so just pass it along
	            // As there's nothing we can do at this point.
	            return urlString;
	        }
	    }
	    // Append api-version query and return string
	    url.searchParams.set("api-version", gatewayApiVersion);
	    return url.toString();
	};
	const isValidURL = (str) => {
	    let url;
	    try {
	        url = new URL(str);
	    }
	    catch (_) {
	        return false;
	    }
	    return url.protocol === "http:" || url.protocol === "https:";
	};
	const transformEndpoint = (attachments, resourceEndpoint, gatewayApiVersion) => {
	    if (resourceEndpoint === undefined ||
	        resourceEndpoint === null ||
	        resourceEndpoint === "" ||
	        !isValidURL(resourceEndpoint)) {
	        return attachments;
	    }
	    attachments
	        .filter((e) => e.attachmentType.toLowerCase() === "image".toLowerCase())
	        .map((attachment) => {
	        if (attachment.previewUrl) {
	            attachment.previewUrl = createMediaUrlString(attachment.previewUrl, resourceEndpoint, gatewayApiVersion);
	        }
	        if (attachment.url) {
	            attachment.url = createMediaUrlString(attachment.url, resourceEndpoint, gatewayApiVersion);
	        }
	    });
	    return attachments;
	};
	const base64decode = (encodedString) => !esm$1.isNodeLike ? atob(encodedString) : Buffer.from(encodedString, "base64").toString();
	exports.base64decode = base64decode;
	const parseJWT = (token) => {
	    let [, payload] = token === null || token === void 0 ? void 0 : token.split(".");
	    if (payload === undefined) {
	        throw new Error("Invalid token");
	    }
	    payload = payload.replace(/-/g, "+").replace(/_/g, "/");
	    return JSON.parse(decodeURIComponent(escape((0, exports.base64decode)(payload))));
	};
	const parseTokenCredential = (credential) => __awaiter(void 0, void 0, void 0, function* () {
	    const accessToken = yield credential.getToken();
	    const jwtToken = accessToken === null || accessToken === void 0 ? void 0 : accessToken.token;
	    const parsedJwtToken = parseJWT(jwtToken);
	    const identityMri = parsedJwtToken.skypeid;
	    const acsResourceId = parsedJwtToken.resourceId;
	    const cloudType = getCloudTypeFromSkypeId(identityMri);
	    const resourceLocation = parsedJwtToken.resourceLocation || "";
	    return { jwtToken, acsResourceId, identityMri, cloudType, resourceLocation };
	});
	exports.parseTokenCredential = parseTokenCredential;
	/**
	 * Generated Universally Unique Identifier
	 *
	 * @returns RFC4122 v4 UUID.
	 * @internal
	 */
	function generateUuid() {
	    return (0, esmBrowser.v4)();
	}
	const isEudbLocation = (location) => !!location && !!constants_1.EudbCountries.find((euLocation) => euLocation === location);
	exports.isEudbLocation = isEudbLocation;
	function getCloudTypeFromSkypeId(skypeId) {
	    const cloudPrefix = skypeId.substring(0, skypeId.indexOf(":"));
	    switch (cloudPrefix) {
	        case constants_1.CloudPrefix.OrgId:
	        case constants_1.CloudPrefix.Acs:
	        case constants_1.CloudPrefix.Spool: {
	            return constants_1.CloudType.Public;
	        }
	        case constants_1.CloudPrefix.GccHigh:
	        case constants_1.CloudPrefix.GccHighAcs: {
	            return constants_1.CloudType.GccHigh;
	        }
	        case constants_1.CloudPrefix.Dod:
	        case constants_1.CloudPrefix.DodAcs: {
	            return constants_1.CloudType.Dod;
	        }
	        default: {
	            return constants_1.CloudType.Public;
	        }
	    }
	}
	});

	unwrapExports(TrouterUtils);
	TrouterUtils.isEudbLocation;
	TrouterUtils.parseTokenCredential;
	TrouterUtils.base64decode;
	TrouterUtils.toTelemetrySender;
	TrouterUtils.toLogProvider;
	TrouterUtils.toMessageHandler;
	TrouterUtils.generateUuid;

	// Copyright (c) Microsoft Corporation.
	/**
	 * Encodes a byte array in base64 format.
	 * @param value - the Uint8Aray to encode
	 * @internal
	 */
	function encodeByteArray(value) {
	    let str = "";
	    for (let i = 0; i < value.length; i++) {
	        str += String.fromCharCode(value[i]);
	    }
	    return btoa(str);
	}
	/**
	 * Decodes a base64 string into a byte array.
	 * @param value - the base64 string to decode
	 * @internal
	 */
	function decodeString(value) {
	    const byteString = atob(value);
	    const arr = new Uint8Array(byteString.length);
	    for (let i = 0; i < byteString.length; i++) {
	        arr[i] = byteString.charCodeAt(i);
	    }
	    return arr;
	}
	/**
	 * Decodes a base64 string into a string.
	 * @param value - the base64 string to decode
	 * @internal
	 */
	function decodeStringToString(value) {
	    return atob(value);
	}

	// Copyright (c) Microsoft Corporation.
	// Licensed under the MIT license.
	/**
	 * Default key used to access the XML attributes.
	 */
	const XML_ATTRKEY = "$";
	/**
	 * Default key used to access the XML value content.
	 */
	const XML_CHARKEY = "_";

	// Copyright (c) Microsoft Corporation.
	// Licensed under the MIT license.
	/**
	 * A type guard for a primitive response body.
	 * @param value - Value to test
	 *
	 * @internal
	 */
	function isPrimitiveBody(value, mapperTypeName) {
	    return (mapperTypeName !== "Composite" &&
	        mapperTypeName !== "Dictionary" &&
	        (typeof value === "string" ||
	            typeof value === "number" ||
	            typeof value === "boolean" ||
	            (mapperTypeName === null || mapperTypeName === void 0 ? void 0 : mapperTypeName.match(/^(Date|DateTime|DateTimeRfc1123|UnixTime|ByteArray|Base64Url)$/i)) !==
	                null ||
	            value === undefined ||
	            value === null));
	}
	const validateISODuration = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;
	/**
	 * Returns true if the given string is in ISO 8601 format.
	 * @param value - The value to be validated for ISO 8601 duration format.
	 * @internal
	 */
	function isDuration(value) {
	    return validateISODuration.test(value);
	}
	const validUuidRegex = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/i;
	/**
	 * Returns true if the provided uuid is valid.
	 *
	 * @param uuid - The uuid that needs to be validated.
	 *
	 * @internal
	 */
	function isValidUuid(uuid) {
	    return validUuidRegex.test(uuid);
	}
	/**
	 * Maps the response as follows:
	 * - wraps the response body if needed (typically if its type is primitive).
	 * - returns null if the combination of the headers and the body is empty.
	 * - otherwise, returns the combination of the headers and the body.
	 *
	 * @param responseObject - a representation of the parsed response
	 * @returns the response that will be returned to the user which can be null and/or wrapped
	 *
	 * @internal
	 */
	function handleNullableResponseAndWrappableBody(responseObject) {
	    const combinedHeadersAndBody = Object.assign(Object.assign({}, responseObject.headers), responseObject.body);
	    if (responseObject.hasNullableType &&
	        Object.getOwnPropertyNames(combinedHeadersAndBody).length === 0) {
	        return responseObject.shouldWrapBody ? { body: null } : null;
	    }
	    else {
	        return responseObject.shouldWrapBody
	            ? Object.assign(Object.assign({}, responseObject.headers), { body: responseObject.body }) : combinedHeadersAndBody;
	    }
	}
	/**
	 * Take a `FullOperationResponse` and turn it into a flat
	 * response object to hand back to the consumer.
	 * @param fullResponse - The processed response from the operation request
	 * @param responseSpec - The response map from the OperationSpec
	 *
	 * @internal
	 */
	function flattenResponse(fullResponse, responseSpec) {
	    var _a, _b;
	    const parsedHeaders = fullResponse.parsedHeaders;
	    // head methods never have a body, but we return a boolean set to body property
	    // to indicate presence/absence of the resource
	    if (fullResponse.request.method === "HEAD") {
	        return Object.assign(Object.assign({}, parsedHeaders), { body: fullResponse.parsedBody });
	    }
	    const bodyMapper = responseSpec && responseSpec.bodyMapper;
	    const isNullable = Boolean(bodyMapper === null || bodyMapper === void 0 ? void 0 : bodyMapper.nullable);
	    const expectedBodyTypeName = bodyMapper === null || bodyMapper === void 0 ? void 0 : bodyMapper.type.name;
	    /** If the body is asked for, we look at the expected body type to handle it */
	    if (expectedBodyTypeName === "Stream") {
	        return Object.assign(Object.assign({}, parsedHeaders), { blobBody: fullResponse.blobBody, readableStreamBody: fullResponse.readableStreamBody });
	    }
	    const modelProperties = (expectedBodyTypeName === "Composite" &&
	        bodyMapper.type.modelProperties) ||
	        {};
	    const isPageableResponse = Object.keys(modelProperties).some((k) => modelProperties[k].serializedName === "");
	    if (expectedBodyTypeName === "Sequence" || isPageableResponse) {
	        const arrayResponse = (_a = fullResponse.parsedBody) !== null && _a !== void 0 ? _a : [];
	        for (const key of Object.keys(modelProperties)) {
	            if (modelProperties[key].serializedName) {
	                arrayResponse[key] = (_b = fullResponse.parsedBody) === null || _b === void 0 ? void 0 : _b[key];
	            }
	        }
	        if (parsedHeaders) {
	            for (const key of Object.keys(parsedHeaders)) {
	                arrayResponse[key] = parsedHeaders[key];
	            }
	        }
	        return isNullable &&
	            !fullResponse.parsedBody &&
	            !parsedHeaders &&
	            Object.getOwnPropertyNames(modelProperties).length === 0
	            ? null
	            : arrayResponse;
	    }
	    return handleNullableResponseAndWrappableBody({
	        body: fullResponse.parsedBody,
	        headers: parsedHeaders,
	        hasNullableType: isNullable,
	        shouldWrapBody: isPrimitiveBody(fullResponse.parsedBody, expectedBodyTypeName),
	    });
	}

	// Copyright (c) Microsoft Corporation.
	class SerializerImpl {
	    constructor(modelMappers = {}, isXML = false) {
	        this.modelMappers = modelMappers;
	        this.isXML = isXML;
	    }
	    /**
	     * @deprecated Removing the constraints validation on client side.
	     */
	    validateConstraints(mapper, value, objectName) {
	        const failValidation = (constraintName, constraintValue) => {
	            throw new Error(`"${objectName}" with value "${value}" should satisfy the constraint "${constraintName}": ${constraintValue}.`);
	        };
	        if (mapper.constraints && value !== undefined && value !== null) {
	            const { ExclusiveMaximum, ExclusiveMinimum, InclusiveMaximum, InclusiveMinimum, MaxItems, MaxLength, MinItems, MinLength, MultipleOf, Pattern, UniqueItems, } = mapper.constraints;
	            if (ExclusiveMaximum !== undefined && value >= ExclusiveMaximum) {
	                failValidation("ExclusiveMaximum", ExclusiveMaximum);
	            }
	            if (ExclusiveMinimum !== undefined && value <= ExclusiveMinimum) {
	                failValidation("ExclusiveMinimum", ExclusiveMinimum);
	            }
	            if (InclusiveMaximum !== undefined && value > InclusiveMaximum) {
	                failValidation("InclusiveMaximum", InclusiveMaximum);
	            }
	            if (InclusiveMinimum !== undefined && value < InclusiveMinimum) {
	                failValidation("InclusiveMinimum", InclusiveMinimum);
	            }
	            if (MaxItems !== undefined && value.length > MaxItems) {
	                failValidation("MaxItems", MaxItems);
	            }
	            if (MaxLength !== undefined && value.length > MaxLength) {
	                failValidation("MaxLength", MaxLength);
	            }
	            if (MinItems !== undefined && value.length < MinItems) {
	                failValidation("MinItems", MinItems);
	            }
	            if (MinLength !== undefined && value.length < MinLength) {
	                failValidation("MinLength", MinLength);
	            }
	            if (MultipleOf !== undefined && value % MultipleOf !== 0) {
	                failValidation("MultipleOf", MultipleOf);
	            }
	            if (Pattern) {
	                const pattern = typeof Pattern === "string" ? new RegExp(Pattern) : Pattern;
	                if (typeof value !== "string" || value.match(pattern) === null) {
	                    failValidation("Pattern", Pattern);
	                }
	            }
	            if (UniqueItems &&
	                value.some((item, i, ar) => ar.indexOf(item) !== i)) {
	                failValidation("UniqueItems", UniqueItems);
	            }
	        }
	    }
	    /**
	     * Serialize the given object based on its metadata defined in the mapper
	     *
	     * @param mapper - The mapper which defines the metadata of the serializable object
	     *
	     * @param object - A valid Javascript object to be serialized
	     *
	     * @param objectName - Name of the serialized object
	     *
	     * @param options - additional options to serialization
	     *
	     * @returns A valid serialized Javascript object
	     */
	    serialize(mapper, object, objectName, options = { xml: {} }) {
	        var _a, _b, _c;
	        const updatedOptions = {
	            xml: {
	                rootName: (_a = options.xml.rootName) !== null && _a !== void 0 ? _a : "",
	                includeRoot: (_b = options.xml.includeRoot) !== null && _b !== void 0 ? _b : false,
	                xmlCharKey: (_c = options.xml.xmlCharKey) !== null && _c !== void 0 ? _c : XML_CHARKEY,
	            },
	        };
	        let payload = {};
	        const mapperType = mapper.type.name;
	        if (!objectName) {
	            objectName = mapper.serializedName;
	        }
	        if (mapperType.match(/^Sequence$/i) !== null) {
	            payload = [];
	        }
	        if (mapper.isConstant) {
	            object = mapper.defaultValue;
	        }
	        // This table of allowed values should help explain
	        // the mapper.required and mapper.nullable properties.
	        // X means "neither undefined or null are allowed".
	        //           || required
	        //           || true      | false
	        //  nullable || ==========================
	        //      true || null      | undefined/null
	        //     false || X         | undefined
	        // undefined || X         | undefined/null
	        const { required, nullable } = mapper;
	        if (required && nullable && object === undefined) {
	            throw new Error(`${objectName} cannot be undefined.`);
	        }
	        if (required && !nullable && (object === undefined || object === null)) {
	            throw new Error(`${objectName} cannot be null or undefined.`);
	        }
	        if (!required && nullable === false && object === null) {
	            throw new Error(`${objectName} cannot be null.`);
	        }
	        if (object === undefined || object === null) {
	            payload = object;
	        }
	        else {
	            if (mapperType.match(/^any$/i) !== null) {
	                payload = object;
	            }
	            else if (mapperType.match(/^(Number|String|Boolean|Object|Stream|Uuid)$/i) !== null) {
	                payload = serializeBasicTypes(mapperType, objectName, object);
	            }
	            else if (mapperType.match(/^Enum$/i) !== null) {
	                const enumMapper = mapper;
	                payload = serializeEnumType(objectName, enumMapper.type.allowedValues, object);
	            }
	            else if (mapperType.match(/^(Date|DateTime|TimeSpan|DateTimeRfc1123|UnixTime)$/i) !== null) {
	                payload = serializeDateTypes(mapperType, object, objectName);
	            }
	            else if (mapperType.match(/^ByteArray$/i) !== null) {
	                payload = serializeByteArrayType(objectName, object);
	            }
	            else if (mapperType.match(/^Base64Url$/i) !== null) {
	                payload = serializeBase64UrlType(objectName, object);
	            }
	            else if (mapperType.match(/^Sequence$/i) !== null) {
	                payload = serializeSequenceType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions);
	            }
	            else if (mapperType.match(/^Dictionary$/i) !== null) {
	                payload = serializeDictionaryType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions);
	            }
	            else if (mapperType.match(/^Composite$/i) !== null) {
	                payload = serializeCompositeType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions);
	            }
	        }
	        return payload;
	    }
	    /**
	     * Deserialize the given object based on its metadata defined in the mapper
	     *
	     * @param mapper - The mapper which defines the metadata of the serializable object
	     *
	     * @param responseBody - A valid Javascript entity to be deserialized
	     *
	     * @param objectName - Name of the deserialized object
	     *
	     * @param options - Controls behavior of XML parser and builder.
	     *
	     * @returns A valid deserialized Javascript object
	     */
	    deserialize(mapper, responseBody, objectName, options = { xml: {} }) {
	        var _a, _b, _c, _d;
	        const updatedOptions = {
	            xml: {
	                rootName: (_a = options.xml.rootName) !== null && _a !== void 0 ? _a : "",
	                includeRoot: (_b = options.xml.includeRoot) !== null && _b !== void 0 ? _b : false,
	                xmlCharKey: (_c = options.xml.xmlCharKey) !== null && _c !== void 0 ? _c : XML_CHARKEY,
	            },
	            ignoreUnknownProperties: (_d = options.ignoreUnknownProperties) !== null && _d !== void 0 ? _d : false,
	        };
	        if (responseBody === undefined || responseBody === null) {
	            if (this.isXML && mapper.type.name === "Sequence" && !mapper.xmlIsWrapped) {
	                // Edge case for empty XML non-wrapped lists. xml2js can't distinguish
	                // between the list being empty versus being missing,
	                // so let's do the more user-friendly thing and return an empty list.
	                responseBody = [];
	            }
	            // specifically check for undefined as default value can be a falsey value `0, "", false, null`
	            if (mapper.defaultValue !== undefined) {
	                responseBody = mapper.defaultValue;
	            }
	            return responseBody;
	        }
	        let payload;
	        const mapperType = mapper.type.name;
	        if (!objectName) {
	            objectName = mapper.serializedName;
	        }
	        if (mapperType.match(/^Composite$/i) !== null) {
	            payload = deserializeCompositeType(this, mapper, responseBody, objectName, updatedOptions);
	        }
	        else {
	            if (this.isXML) {
	                const xmlCharKey = updatedOptions.xml.xmlCharKey;
	                /**
	                 * If the mapper specifies this as a non-composite type value but the responseBody contains
	                 * both header ("$" i.e., XML_ATTRKEY) and body ("#" i.e., XML_CHARKEY) properties,
	                 * then just reduce the responseBody value to the body ("#" i.e., XML_CHARKEY) property.
	                 */
	                if (responseBody[XML_ATTRKEY] !== undefined && responseBody[xmlCharKey] !== undefined) {
	                    responseBody = responseBody[xmlCharKey];
	                }
	            }
	            if (mapperType.match(/^Number$/i) !== null) {
	                payload = parseFloat(responseBody);
	                if (isNaN(payload)) {
	                    payload = responseBody;
	                }
	            }
	            else if (mapperType.match(/^Boolean$/i) !== null) {
	                if (responseBody === "true") {
	                    payload = true;
	                }
	                else if (responseBody === "false") {
	                    payload = false;
	                }
	                else {
	                    payload = responseBody;
	                }
	            }
	            else if (mapperType.match(/^(String|Enum|Object|Stream|Uuid|TimeSpan|any)$/i) !== null) {
	                payload = responseBody;
	            }
	            else if (mapperType.match(/^(Date|DateTime|DateTimeRfc1123)$/i) !== null) {
	                payload = new Date(responseBody);
	            }
	            else if (mapperType.match(/^UnixTime$/i) !== null) {
	                payload = unixTimeToDate(responseBody);
	            }
	            else if (mapperType.match(/^ByteArray$/i) !== null) {
	                payload = decodeString(responseBody);
	            }
	            else if (mapperType.match(/^Base64Url$/i) !== null) {
	                payload = base64UrlToByteArray(responseBody);
	            }
	            else if (mapperType.match(/^Sequence$/i) !== null) {
	                payload = deserializeSequenceType(this, mapper, responseBody, objectName, updatedOptions);
	            }
	            else if (mapperType.match(/^Dictionary$/i) !== null) {
	                payload = deserializeDictionaryType(this, mapper, responseBody, objectName, updatedOptions);
	            }
	        }
	        if (mapper.isConstant) {
	            payload = mapper.defaultValue;
	        }
	        return payload;
	    }
	}
	/**
	 * Method that creates and returns a Serializer.
	 * @param modelMappers - Known models to map
	 * @param isXML - If XML should be supported
	 */
	function createSerializer(modelMappers = {}, isXML = false) {
	    return new SerializerImpl(modelMappers, isXML);
	}
	function trimEnd(str, ch) {
	    let len = str.length;
	    while (len - 1 >= 0 && str[len - 1] === ch) {
	        --len;
	    }
	    return str.substr(0, len);
	}
	function bufferToBase64Url(buffer) {
	    if (!buffer) {
	        return undefined;
	    }
	    if (!(buffer instanceof Uint8Array)) {
	        throw new Error(`Please provide an input of type Uint8Array for converting to Base64Url.`);
	    }
	    // Uint8Array to Base64.
	    const str = encodeByteArray(buffer);
	    // Base64 to Base64Url.
	    return trimEnd(str, "=").replace(/\+/g, "-").replace(/\//g, "_");
	}
	function base64UrlToByteArray(str) {
	    if (!str) {
	        return undefined;
	    }
	    if (str && typeof str.valueOf() !== "string") {
	        throw new Error("Please provide an input of type string for converting to Uint8Array");
	    }
	    // Base64Url to Base64.
	    str = str.replace(/-/g, "+").replace(/_/g, "/");
	    // Base64 to Uint8Array.
	    return decodeString(str);
	}
	function splitSerializeName(prop) {
	    const classes = [];
	    let partialclass = "";
	    if (prop) {
	        const subwords = prop.split(".");
	        for (const item of subwords) {
	            if (item.charAt(item.length - 1) === "\\") {
	                partialclass += item.substr(0, item.length - 1) + ".";
	            }
	            else {
	                partialclass += item;
	                classes.push(partialclass);
	                partialclass = "";
	            }
	        }
	    }
	    return classes;
	}
	function dateToUnixTime(d) {
	    if (!d) {
	        return undefined;
	    }
	    if (typeof d.valueOf() === "string") {
	        d = new Date(d);
	    }
	    return Math.floor(d.getTime() / 1000);
	}
	function unixTimeToDate(n) {
	    if (!n) {
	        return undefined;
	    }
	    return new Date(n * 1000);
	}
	function serializeBasicTypes(typeName, objectName, value) {
	    if (value !== null && value !== undefined) {
	        if (typeName.match(/^Number$/i) !== null) {
	            if (typeof value !== "number") {
	                throw new Error(`${objectName} with value ${value} must be of type number.`);
	            }
	        }
	        else if (typeName.match(/^String$/i) !== null) {
	            if (typeof value.valueOf() !== "string") {
	                throw new Error(`${objectName} with value "${value}" must be of type string.`);
	            }
	        }
	        else if (typeName.match(/^Uuid$/i) !== null) {
	            if (!(typeof value.valueOf() === "string" && isValidUuid(value))) {
	                throw new Error(`${objectName} with value "${value}" must be of type string and a valid uuid.`);
	            }
	        }
	        else if (typeName.match(/^Boolean$/i) !== null) {
	            if (typeof value !== "boolean") {
	                throw new Error(`${objectName} with value ${value} must be of type boolean.`);
	            }
	        }
	        else if (typeName.match(/^Stream$/i) !== null) {
	            const objectType = typeof value;
	            if (objectType !== "string" &&
	                typeof value.pipe !== "function" && // NodeJS.ReadableStream
	                typeof value.tee !== "function" && // browser ReadableStream
	                !(value instanceof ArrayBuffer) &&
	                !ArrayBuffer.isView(value) &&
	                // File objects count as a type of Blob, so we want to use instanceof explicitly
	                !((typeof Blob === "function" || typeof Blob === "object") && value instanceof Blob) &&
	                objectType !== "function") {
	                throw new Error(`${objectName} must be a string, Blob, ArrayBuffer, ArrayBufferView, ReadableStream, or () => ReadableStream.`);
	            }
	        }
	    }
	    return value;
	}
	function serializeEnumType(objectName, allowedValues, value) {
	    if (!allowedValues) {
	        throw new Error(`Please provide a set of allowedValues to validate ${objectName} as an Enum Type.`);
	    }
	    const isPresent = allowedValues.some((item) => {
	        if (typeof item.valueOf() === "string") {
	            return item.toLowerCase() === value.toLowerCase();
	        }
	        return item === value;
	    });
	    if (!isPresent) {
	        throw new Error(`${value} is not a valid value for ${objectName}. The valid values are: ${JSON.stringify(allowedValues)}.`);
	    }
	    return value;
	}
	function serializeByteArrayType(objectName, value) {
	    if (value !== undefined && value !== null) {
	        if (!(value instanceof Uint8Array)) {
	            throw new Error(`${objectName} must be of type Uint8Array.`);
	        }
	        value = encodeByteArray(value);
	    }
	    return value;
	}
	function serializeBase64UrlType(objectName, value) {
	    if (value !== undefined && value !== null) {
	        if (!(value instanceof Uint8Array)) {
	            throw new Error(`${objectName} must be of type Uint8Array.`);
	        }
	        value = bufferToBase64Url(value);
	    }
	    return value;
	}
	function serializeDateTypes(typeName, value, objectName) {
	    if (value !== undefined && value !== null) {
	        if (typeName.match(/^Date$/i) !== null) {
	            if (!(value instanceof Date ||
	                (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
	                throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`);
	            }
	            value =
	                value instanceof Date
	                    ? value.toISOString().substring(0, 10)
	                    : new Date(value).toISOString().substring(0, 10);
	        }
	        else if (typeName.match(/^DateTime$/i) !== null) {
	            if (!(value instanceof Date ||
	                (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
	                throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`);
	            }
	            value = value instanceof Date ? value.toISOString() : new Date(value).toISOString();
	        }
	        else if (typeName.match(/^DateTimeRfc1123$/i) !== null) {
	            if (!(value instanceof Date ||
	                (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
	                throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123 format.`);
	            }
	            value = value instanceof Date ? value.toUTCString() : new Date(value).toUTCString();
	        }
	        else if (typeName.match(/^UnixTime$/i) !== null) {
	            if (!(value instanceof Date ||
	                (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
	                throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123/ISO8601 format ` +
	                    `for it to be serialized in UnixTime/Epoch format.`);
	            }
	            value = dateToUnixTime(value);
	        }
	        else if (typeName.match(/^TimeSpan$/i) !== null) {
	            if (!isDuration(value)) {
	                throw new Error(`${objectName} must be a string in ISO 8601 format. Instead was "${value}".`);
	            }
	        }
	    }
	    return value;
	}
	function serializeSequenceType(serializer, mapper, object, objectName, isXml, options) {
	    var _a;
	    if (!Array.isArray(object)) {
	        throw new Error(`${objectName} must be of type Array.`);
	    }
	    let elementType = mapper.type.element;
	    if (!elementType || typeof elementType !== "object") {
	        throw new Error(`element" metadata for an Array must be defined in the ` +
	            `mapper and it must of type "object" in ${objectName}.`);
	    }
	    // Quirk: Composite mappers referenced by `element` might
	    // not have *all* properties declared (like uberParent),
	    // so let's try to look up the full definition by name.
	    if (elementType.type.name === "Composite" && elementType.type.className) {
	        elementType = (_a = serializer.modelMappers[elementType.type.className]) !== null && _a !== void 0 ? _a : elementType;
	    }
	    const tempArray = [];
	    for (let i = 0; i < object.length; i++) {
	        const serializedValue = serializer.serialize(elementType, object[i], objectName, options);
	        if (isXml && elementType.xmlNamespace) {
	            const xmlnsKey = elementType.xmlNamespacePrefix
	                ? `xmlns:${elementType.xmlNamespacePrefix}`
	                : "xmlns";
	            if (elementType.type.name === "Composite") {
	                tempArray[i] = Object.assign({}, serializedValue);
	                tempArray[i][XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace };
	            }
	            else {
	                tempArray[i] = {};
	                tempArray[i][options.xml.xmlCharKey] = serializedValue;
	                tempArray[i][XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace };
	            }
	        }
	        else {
	            tempArray[i] = serializedValue;
	        }
	    }
	    return tempArray;
	}
	function serializeDictionaryType(serializer, mapper, object, objectName, isXml, options) {
	    if (typeof object !== "object") {
	        throw new Error(`${objectName} must be of type object.`);
	    }
	    const valueType = mapper.type.value;
	    if (!valueType || typeof valueType !== "object") {
	        throw new Error(`"value" metadata for a Dictionary must be defined in the ` +
	            `mapper and it must of type "object" in ${objectName}.`);
	    }
	    const tempDictionary = {};
	    for (const key of Object.keys(object)) {
	        const serializedValue = serializer.serialize(valueType, object[key], objectName, options);
	        // If the element needs an XML namespace we need to add it within the $ property
	        tempDictionary[key] = getXmlObjectValue(valueType, serializedValue, isXml, options);
	    }
	    // Add the namespace to the root element if needed
	    if (isXml && mapper.xmlNamespace) {
	        const xmlnsKey = mapper.xmlNamespacePrefix ? `xmlns:${mapper.xmlNamespacePrefix}` : "xmlns";
	        const result = tempDictionary;
	        result[XML_ATTRKEY] = { [xmlnsKey]: mapper.xmlNamespace };
	        return result;
	    }
	    return tempDictionary;
	}
	/**
	 * Resolves the additionalProperties property from a referenced mapper
	 * @param serializer - the serializer containing the entire set of mappers
	 * @param mapper - the composite mapper to resolve
	 * @param objectName - name of the object being serialized
	 */
	function resolveAdditionalProperties(serializer, mapper, objectName) {
	    const additionalProperties = mapper.type.additionalProperties;
	    if (!additionalProperties && mapper.type.className) {
	        const modelMapper = resolveReferencedMapper(serializer, mapper, objectName);
	        return modelMapper === null || modelMapper === void 0 ? void 0 : modelMapper.type.additionalProperties;
	    }
	    return additionalProperties;
	}
	/**
	 * Finds the mapper referenced by className
	 * @param serializer - the serializer containing the entire set of mappers
	 * @param mapper - the composite mapper to resolve
	 * @param objectName - name of the object being serialized
	 */
	function resolveReferencedMapper(serializer, mapper, objectName) {
	    const className = mapper.type.className;
	    if (!className) {
	        throw new Error(`Class name for model "${objectName}" is not provided in the mapper "${JSON.stringify(mapper, undefined, 2)}".`);
	    }
	    return serializer.modelMappers[className];
	}
	/**
	 * Resolves a composite mapper's modelProperties.
	 * @param serializer - the serializer containing the entire set of mappers
	 * @param mapper - the composite mapper to resolve
	 */
	function resolveModelProperties(serializer, mapper, objectName) {
	    let modelProps = mapper.type.modelProperties;
	    if (!modelProps) {
	        const modelMapper = resolveReferencedMapper(serializer, mapper, objectName);
	        if (!modelMapper) {
	            throw new Error(`mapper() cannot be null or undefined for model "${mapper.type.className}".`);
	        }
	        modelProps = modelMapper === null || modelMapper === void 0 ? void 0 : modelMapper.type.modelProperties;
	        if (!modelProps) {
	            throw new Error(`modelProperties cannot be null or undefined in the ` +
	                `mapper "${JSON.stringify(modelMapper)}" of type "${mapper.type.className}" for object "${objectName}".`);
	        }
	    }
	    return modelProps;
	}
	function serializeCompositeType(serializer, mapper, object, objectName, isXml, options) {
	    if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) {
	        mapper = getPolymorphicMapper(serializer, mapper, object, "clientName");
	    }
	    if (object !== undefined && object !== null) {
	        const payload = {};
	        const modelProps = resolveModelProperties(serializer, mapper, objectName);
	        for (const key of Object.keys(modelProps)) {
	            const propertyMapper = modelProps[key];
	            if (propertyMapper.readOnly) {
	                continue;
	            }
	            let propName;
	            let parentObject = payload;
	            if (serializer.isXML) {
	                if (propertyMapper.xmlIsWrapped) {
	                    propName = propertyMapper.xmlName;
	                }
	                else {
	                    propName = propertyMapper.xmlElementName || propertyMapper.xmlName;
	                }
	            }
	            else {
	                const paths = splitSerializeName(propertyMapper.serializedName);
	                propName = paths.pop();
	                for (const pathName of paths) {
	                    const childObject = parentObject[pathName];
	                    if ((childObject === undefined || childObject === null) &&
	                        ((object[key] !== undefined && object[key] !== null) ||
	                            propertyMapper.defaultValue !== undefined)) {
	                        parentObject[pathName] = {};
	                    }
	                    parentObject = parentObject[pathName];
	                }
	            }
	            if (parentObject !== undefined && parentObject !== null) {
	                if (isXml && mapper.xmlNamespace) {
	                    const xmlnsKey = mapper.xmlNamespacePrefix
	                        ? `xmlns:${mapper.xmlNamespacePrefix}`
	                        : "xmlns";
	                    parentObject[XML_ATTRKEY] = Object.assign(Object.assign({}, parentObject[XML_ATTRKEY]), { [xmlnsKey]: mapper.xmlNamespace });
	                }
	                const propertyObjectName = propertyMapper.serializedName !== ""
	                    ? objectName + "." + propertyMapper.serializedName
	                    : objectName;
	                let toSerialize = object[key];
	                const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper);
	                if (polymorphicDiscriminator &&
	                    polymorphicDiscriminator.clientName === key &&
	                    (toSerialize === undefined || toSerialize === null)) {
	                    toSerialize = mapper.serializedName;
	                }
	                const serializedValue = serializer.serialize(propertyMapper, toSerialize, propertyObjectName, options);
	                if (serializedValue !== undefined && propName !== undefined && propName !== null) {
	                    const value = getXmlObjectValue(propertyMapper, serializedValue, isXml, options);
	                    if (isXml && propertyMapper.xmlIsAttribute) {
	                        // XML_ATTRKEY, i.e., $ is the key attributes are kept under in xml2js.
	                        // This keeps things simple while preventing name collision
	                        // with names in user documents.
	                        parentObject[XML_ATTRKEY] = parentObject[XML_ATTRKEY] || {};
	                        parentObject[XML_ATTRKEY][propName] = serializedValue;
	                    }
	                    else if (isXml && propertyMapper.xmlIsWrapped) {
	                        parentObject[propName] = { [propertyMapper.xmlElementName]: value };
	                    }
	                    else {
	                        parentObject[propName] = value;
	                    }
	                }
	            }
	        }
	        const additionalPropertiesMapper = resolveAdditionalProperties(serializer, mapper, objectName);
	        if (additionalPropertiesMapper) {
	            const propNames = Object.keys(modelProps);
	            for (const clientPropName in object) {
	                const isAdditionalProperty = propNames.every((pn) => pn !== clientPropName);
	                if (isAdditionalProperty) {
	                    payload[clientPropName] = serializer.serialize(additionalPropertiesMapper, object[clientPropName], objectName + '["' + clientPropName + '"]', options);
	                }
	            }
	        }
	        return payload;
	    }
	    return object;
	}
	function getXmlObjectValue(propertyMapper, serializedValue, isXml, options) {
	    if (!isXml || !propertyMapper.xmlNamespace) {
	        return serializedValue;
	    }
	    const xmlnsKey = propertyMapper.xmlNamespacePrefix
	        ? `xmlns:${propertyMapper.xmlNamespacePrefix}`
	        : "xmlns";
	    const xmlNamespace = { [xmlnsKey]: propertyMapper.xmlNamespace };
	    if (["Composite"].includes(propertyMapper.type.name)) {
	        if (serializedValue[XML_ATTRKEY]) {
	            return serializedValue;
	        }
	        else {
	            const result = Object.assign({}, serializedValue);
	            result[XML_ATTRKEY] = xmlNamespace;
	            return result;
	        }
	    }
	    const result = {};
	    result[options.xml.xmlCharKey] = serializedValue;
	    result[XML_ATTRKEY] = xmlNamespace;
	    return result;
	}
	function isSpecialXmlProperty(propertyName, options) {
	    return [XML_ATTRKEY, options.xml.xmlCharKey].includes(propertyName);
	}
	function deserializeCompositeType(serializer, mapper, responseBody, objectName, options) {
	    var _a, _b;
	    const xmlCharKey = (_a = options.xml.xmlCharKey) !== null && _a !== void 0 ? _a : XML_CHARKEY;
	    if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) {
	        mapper = getPolymorphicMapper(serializer, mapper, responseBody, "serializedName");
	    }
	    const modelProps = resolveModelProperties(serializer, mapper, objectName);
	    let instance = {};
	    const handledPropertyNames = [];
	    for (const key of Object.keys(modelProps)) {
	        const propertyMapper = modelProps[key];
	        const paths = splitSerializeName(modelProps[key].serializedName);
	        handledPropertyNames.push(paths[0]);
	        const { serializedName, xmlName, xmlElementName } = propertyMapper;
	        let propertyObjectName = objectName;
	        if (serializedName !== "" && serializedName !== undefined) {
	            propertyObjectName = objectName + "." + serializedName;
	        }
	        const headerCollectionPrefix = propertyMapper.headerCollectionPrefix;
	        if (headerCollectionPrefix) {
	            const dictionary = {};
	            for (const headerKey of Object.keys(responseBody)) {
	                if (headerKey.startsWith(headerCollectionPrefix)) {
	                    dictionary[headerKey.substring(headerCollectionPrefix.length)] = serializer.deserialize(propertyMapper.type.value, responseBody[headerKey], propertyObjectName, options);
	                }
	                handledPropertyNames.push(headerKey);
	            }
	            instance[key] = dictionary;
	        }
	        else if (serializer.isXML) {
	            if (propertyMapper.xmlIsAttribute && responseBody[XML_ATTRKEY]) {
	                instance[key] = serializer.deserialize(propertyMapper, responseBody[XML_ATTRKEY][xmlName], propertyObjectName, options);
	            }
	            else if (propertyMapper.xmlIsMsText) {
	                if (responseBody[xmlCharKey] !== undefined) {
	                    instance[key] = responseBody[xmlCharKey];
	                }
	                else if (typeof responseBody === "string") {
	                    // The special case where xml parser parses "<Name>content</Name>" into JSON of
	                    //   `{ name: "content"}` instead of `{ name: { "_": "content" }}`
	                    instance[key] = responseBody;
	                }
	            }
	            else {
	                const propertyName = xmlElementName || xmlName || serializedName;
	                if (propertyMapper.xmlIsWrapped) {
	                    /* a list of <xmlElementName> wrapped by <xmlName>
	                      For the xml example below
	                        <Cors>
	                          <CorsRule>...</CorsRule>
	                          <CorsRule>...</CorsRule>
	                        </Cors>
	                      the responseBody has
	                        {
	                          Cors: {
	                            CorsRule: [{...}, {...}]
	                          }
	                        }
	                      xmlName is "Cors" and xmlElementName is"CorsRule".
	                    */
	                    const wrapped = responseBody[xmlName];
	                    const elementList = (_b = wrapped === null || wrapped === void 0 ? void 0 : wrapped[xmlElementName]) !== null && _b !== void 0 ? _b : [];
	                    instance[key] = serializer.deserialize(propertyMapper, elementList, propertyObjectName, options);
	                    handledPropertyNames.push(xmlName);
	                }
	                else {
	                    const property = responseBody[propertyName];
	                    instance[key] = serializer.deserialize(propertyMapper, property, propertyObjectName, options);
	                    handledPropertyNames.push(propertyName);
	                }
	            }
	        }
	        else {
	            // deserialize the property if it is present in the provided responseBody instance
	            let propertyInstance;
	            let res = responseBody;
	            // traversing the object step by step.
	            let steps = 0;
	            for (const item of paths) {
	                if (!res)
	                    break;
	                steps++;
	                res = res[item];
	            }
	            // only accept null when reaching the last position of object otherwise it would be undefined
	            if (res === null && steps < paths.length) {
	                res = undefined;
	            }
	            propertyInstance = res;
	            const polymorphicDiscriminator = mapper.type.polymorphicDiscriminator;
	            // checking that the model property name (key)(ex: "fishtype") and the
	            // clientName of the polymorphicDiscriminator {metadata} (ex: "fishtype")
	            // instead of the serializedName of the polymorphicDiscriminator (ex: "fish.type")
	            // is a better approach. The generator is not consistent with escaping '\.' in the
	            // serializedName of the property (ex: "fish\.type") that is marked as polymorphic discriminator
	            // and the serializedName of the metadata polymorphicDiscriminator (ex: "fish.type"). However,
	            // the clientName transformation of the polymorphicDiscriminator (ex: "fishtype") and
	            // the transformation of model property name (ex: "fishtype") is done consistently.
	            // Hence, it is a safer bet to rely on the clientName of the polymorphicDiscriminator.
	            if (polymorphicDiscriminator &&
	                key === polymorphicDiscriminator.clientName &&
	                (propertyInstance === undefined || propertyInstance === null)) {
	                propertyInstance = mapper.serializedName;
	            }
	            let serializedValue;
	            // paging
	            if (Array.isArray(responseBody[key]) && modelProps[key].serializedName === "") {
	                propertyInstance = responseBody[key];
	                const arrayInstance = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options);
	                // Copy over any properties that have already been added into the instance, where they do
	                // not exist on the newly de-serialized array
	                for (const [k, v] of Object.entries(instance)) {
	                    if (!Object.prototype.hasOwnProperty.call(arrayInstance, k)) {
	                        arrayInstance[k] = v;
	                    }
	                }
	                instance = arrayInstance;
	            }
	            else if (propertyInstance !== undefined || propertyMapper.defaultValue !== undefined) {
	                serializedValue = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options);
	                instance[key] = serializedValue;
	            }
	        }
	    }
	    const additionalPropertiesMapper = mapper.type.additionalProperties;
	    if (additionalPropertiesMapper) {
	        const isAdditionalProperty = (responsePropName) => {
	            for (const clientPropName in modelProps) {
	                const paths = splitSerializeName(modelProps[clientPropName].serializedName);
	                if (paths[0] === responsePropName) {
	                    return false;
	                }
	            }
	            return true;
	        };
	        for (const responsePropName in responseBody) {
	            if (isAdditionalProperty(responsePropName)) {
	                instance[responsePropName] = serializer.deserialize(additionalPropertiesMapper, responseBody[responsePropName], objectName + '["' + responsePropName + '"]', options);
	            }
	        }
	    }
	    else if (responseBody && !options.ignoreUnknownProperties) {
	        for (const key of Object.keys(responseBody)) {
	            if (instance[key] === undefined &&
	                !handledPropertyNames.includes(key) &&
	                !isSpecialXmlProperty(key, options)) {
	                instance[key] = responseBody[key];
	            }
	        }
	    }
	    return instance;
	}
	function deserializeDictionaryType(serializer, mapper, responseBody, objectName, options) {
	    /* jshint validthis: true */
	    const value = mapper.type.value;
	    if (!value || typeof value !== "object") {
	        throw new Error(`"value" metadata for a Dictionary must be defined in the ` +
	            `mapper and it must of type "object" in ${objectName}`);
	    }
	    if (responseBody) {
	        const tempDictionary = {};
	        for (const key of Object.keys(responseBody)) {
	            tempDictionary[key] = serializer.deserialize(value, responseBody[key], objectName, options);
	        }
	        return tempDictionary;
	    }
	    return responseBody;
	}
	function deserializeSequenceType(serializer, mapper, responseBody, objectName, options) {
	    var _a;
	    let element = mapper.type.element;
	    if (!element || typeof element !== "object") {
	        throw new Error(`element" metadata for an Array must be defined in the ` +
	            `mapper and it must of type "object" in ${objectName}`);
	    }
	    if (responseBody) {
	        if (!Array.isArray(responseBody)) {
	            // xml2js will interpret a single element array as just the element, so force it to be an array
	            responseBody = [responseBody];
	        }
	        // Quirk: Composite mappers referenced by `element` might
	        // not have *all* properties declared (like uberParent),
	        // so let's try to look up the full definition by name.
	        if (element.type.name === "Composite" && element.type.className) {
	            element = (_a = serializer.modelMappers[element.type.className]) !== null && _a !== void 0 ? _a : element;
	        }
	        const tempArray = [];
	        for (let i = 0; i < responseBody.length; i++) {
	            tempArray[i] = serializer.deserialize(element, responseBody[i], `${objectName}[${i}]`, options);
	        }
	        return tempArray;
	    }
	    return responseBody;
	}
	function getIndexDiscriminator(discriminators, discriminatorValue, typeName) {
	    const typeNamesToCheck = [typeName];
	    while (typeNamesToCheck.length) {
	        const currentName = typeNamesToCheck.shift();
	        const indexDiscriminator = discriminatorValue === currentName
	            ? discriminatorValue
	            : currentName + "." + discriminatorValue;
	        if (Object.prototype.hasOwnProperty.call(discriminators, indexDiscriminator)) {
	            return discriminators[indexDiscriminator];
	        }
	        else {
	            for (const [name, mapper] of Object.entries(discriminators)) {
	                if (name.startsWith(currentName + ".") &&
	                    mapper.type.uberParent === currentName &&
	                    mapper.type.className) {
	                    typeNamesToCheck.push(mapper.type.className);
	                }
	            }
	        }
	    }
	    return undefined;
	}
	function getPolymorphicMapper(serializer, mapper, object, polymorphicPropertyName) {
	    var _a;
	    const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper);
	    if (polymorphicDiscriminator) {
	        let discriminatorName = polymorphicDiscriminator[polymorphicPropertyName];
	        if (discriminatorName) {
	            // The serializedName might have \\, which we just want to ignore
	            if (polymorphicPropertyName === "serializedName") {
	                discriminatorName = discriminatorName.replace(/\\/gi, "");
	            }
	            const discriminatorValue = object[discriminatorName];
	            const typeName = (_a = mapper.type.uberParent) !== null && _a !== void 0 ? _a : mapper.type.className;
	            if (typeof discriminatorValue === "string" && typeName) {
	                const polymorphicMapper = getIndexDiscriminator(serializer.modelMappers.discriminators, discriminatorValue, typeName);
	                if (polymorphicMapper) {
	                    mapper = polymorphicMapper;
	                }
	            }
	        }
	    }
	    return mapper;
	}
	function getPolymorphicDiscriminatorRecursively(serializer, mapper) {
	    return (mapper.type.polymorphicDiscriminator ||
	        getPolymorphicDiscriminatorSafely(serializer, mapper.type.uberParent) ||
	        getPolymorphicDiscriminatorSafely(serializer, mapper.type.className));
	}
	function getPolymorphicDiscriminatorSafely(serializer, typeName) {
	    return (typeName &&
	        serializer.modelMappers[typeName] &&
	        serializer.modelMappers[typeName].type.polymorphicDiscriminator);
	}
	/**
	 * Known types of Mappers
	 */
	const MapperTypeNames = {
	    Base64Url: "Base64Url",
	    Boolean: "Boolean",
	    ByteArray: "ByteArray",
	    Composite: "Composite",
	    Date: "Date",
	    DateTime: "DateTime",
	    DateTimeRfc1123: "DateTimeRfc1123",
	    Dictionary: "Dictionary",
	    Enum: "Enum",
	    Number: "Number",
	    Object: "Object",
	    Sequence: "Sequence",
	    String: "String",
	    Stream: "Stream",
	    TimeSpan: "TimeSpan",
	    UnixTime: "UnixTime",
	};

	// Copyright (c) Microsoft Corporation.
	// Licensed under the MIT License.
	const ValidPhaseNames = new Set(["Deserialize", "Serialize", "Retry", "Sign"]);
	/**
	 * A private implementation of Pipeline.
	 * Do not export this class from the package.
	 * @internal
	 */
	class HttpPipeline {
	    constructor(policies) {
	        var _a;
	        this._policies = [];
	        this._policies = (_a = policies === null || policies === void 0 ? void 0 : policies.slice(0)) !== null && _a !== void 0 ? _a : [];
	        this._orderedPolicies = undefined;
	    }
	    addPolicy(policy, options = {}) {
	        if (options.phase && options.afterPhase) {
	            throw new Error("Policies inside a phase cannot specify afterPhase.");
	        }
	        if (options.phase && !ValidPhaseNames.has(options.phase)) {
	            throw new Error(`Invalid phase name: ${options.phase}`);
	        }
	        if (options.afterPhase && !ValidPhaseNames.has(options.afterPhase)) {
	            throw new Error(`Invalid afterPhase name: ${options.afterPhase}`);
	        }
	        this._policies.push({
	            policy,
	            options,
	        });
	        this._orderedPolicies = undefined;
	    }
	    removePolicy(options) {
	        const removedPolicies = [];
	        this._policies = this._policies.filter((policyDescriptor) => {
	            if ((options.name && policyDescriptor.policy.name === options.name) ||
	                (options.phase && policyDescriptor.options.phase === options.phase)) {
	                removedPolicies.push(policyDescriptor.policy);
	                return false;
	            }
	            else {
	                return true;
	            }
	        });
	        this._orderedPolicies = undefined;
	        return removedPolicies;
	    }
	    sendRequest(httpClient, request) {
	        const policies = this.getOrderedPolicies();
	        const pipeline = policies.reduceRight((next, policy) => {
	            return (req) => {
	                return policy.sendRequest(req, next);
	            };
	        }, (req) => httpClient.sendRequest(req));
	        return pipeline(request);
	    }
	    getOrderedPolicies() {
	        if (!this._orderedPolicies) {
	            this._orderedPolicies = this.orderPolicies();
	        }
	        return this._orderedPolicies;
	    }
	    clone() {
	        return new HttpPipeline(this._policies);
	    }
	    static create() {
	        return new HttpPipeline();
	    }
	    orderPolicies() {
	        /**
	         * The goal of this method is to reliably order pipeline policies
	         * based on their declared requirements when they were added.
	         *
	         * Order is first determined by phase:
	         *
	         * 1. Serialize Phase
	         * 2. Policies not in a phase
	         * 3. Deserialize Phase
	         * 4. Retry Phase
	         * 5. Sign Phase
	         *
	         * Within each phase, policies are executed in the order
	         * they were added unless they were specified to execute
	         * before/after other policies or after a particular phase.
	         *
	         * To determine the final order, we will walk the policy list
	         * in phase order multiple times until all dependencies are
	         * satisfied.
	         *
	         * `afterPolicies` are the set of policies that must be
	         * executed before a given policy. This requirement is
	         * considered satisfied when each of the listed policies
	         * have been scheduled.
	         *
	         * `beforePolicies` are the set of policies that must be
	         * executed after a given policy. Since this dependency
	         * can be expressed by converting it into a equivalent
	         * `afterPolicies` declarations, they are normalized
	         * into that form for simplicity.
	         *
	         * An `afterPhase` dependency is considered satisfied when all
	         * policies in that phase have scheduled.
	         *
	         */
	        const result = [];
	        // Track all policies we know about.
	        const policyMap = new Map();
	        function createPhase(name) {
	            return {
	                name,
	                policies: new Set(),
	                hasRun: false,
	                hasAfterPolicies: false,
	            };
	        }
	        // Track policies for each phase.
	        const serializePhase = createPhase("Serialize");
	        const noPhase = createPhase("None");
	        const deserializePhase = createPhase("Deserialize");
	        const retryPhase = createPhase("Retry");
	        const signPhase = createPhase("Sign");
	        // a list of phases in order
	        const orderedPhases = [serializePhase, noPhase, deserializePhase, retryPhase, signPhase];
	        // Small helper function to map phase name to each Phase
	        function getPhase(phase) {
	            if (phase === "Retry") {
	                return retryPhase;
	            }
	            else if (phase === "Serialize") {
	                return serializePhase;
	            }
	            else if (phase === "Deserialize") {
	                return deserializePhase;
	            }
	            else if (phase === "Sign") {
	                return signPhase;
	            }
	            else {
	                return noPhase;
	            }
	        }
	        // First walk each policy and create a node to track metadata.
	        for (const descriptor of this._policies) {
	            const policy = descriptor.policy;
	            const options = descriptor.options;
	            const policyName = policy.name;
	            if (policyMap.has(policyName)) {
	                throw new Error("Duplicate policy names not allowed in pipeline");
	            }
	            const node = {
	                policy,
	                dependsOn: new Set(),
	                dependants: new Set(),
	            };
	            if (options.afterPhase) {
	                node.afterPhase = getPhase(options.afterPhase);
	                node.afterPhase.hasAfterPolicies = true;
	            }
	            policyMap.set(policyName, node);
	            const phase = getPhase(options.phase);
	            phase.policies.add(node);
	        }
	        // Now that each policy has a node, connect dependency references.
	        for (const descriptor of this._policies) {
	            const { policy, options } = descriptor;
	            const policyName = policy.name;
	            const node = policyMap.get(policyName);
	            if (!node) {
	                throw new Error(`Missing node for policy ${policyName}`);
	            }
	            if (options.afterPolicies) {
	                for (const afterPolicyName of options.afterPolicies) {
	                    const afterNode = policyMap.get(afterPolicyName);
	                    if (afterNode) {
	                        // Linking in both directions helps later
	                        // when we want to notify dependants.
	                        node.dependsOn.add(afterNode);
	                        afterNode.dependants.add(node);
	                    }
	                }
	            }
	            if (options.beforePolicies) {
	                for (const beforePolicyName of options.beforePolicies) {
	                    const beforeNode = policyMap.get(beforePolicyName);
	                    if (beforeNode) {
	                        // To execute before another node, make it
	                        // depend on the current node.
	                        beforeNode.dependsOn.add(node);
	                        node.dependants.add(beforeNode);
	                    }
	                }
	            }
	        }
	        function walkPhase(phase) {
	            phase.hasRun = true;
	            // Sets iterate in insertion order
	            for (const node of phase.policies) {
	                if (node.afterPhase && (!node.afterPhase.hasRun || node.afterPhase.policies.size)) {
	                    // If this node is waiting on a phase to complete,
	                    // we need to skip it for now.
	                    // Even if the phase is empty, we should wait for it
	                    // to be walked to avoid re-ordering policies.
	                    continue;
	                }
	                if (node.dependsOn.size === 0) {
	                    // If there's nothing else we're waiting for, we can
	                    // add this policy to the result list.
	                    result.push(node.policy);
	                    // Notify anything that depends on this policy that
	                    // the policy has been scheduled.
	                    for (const dependant of node.dependants) {
	                        dependant.dependsOn.delete(node);
	                    }
	                    policyMap.delete(node.policy.name);
	                    phase.policies.delete(node);
	                }
	            }
	        }
	        function walkPhases() {
	            for (const phase of orderedPhases) {
	                walkPhase(phase);
	                // if the phase isn't complete
	                if (phase.policies.size > 0 && phase !== noPhase) {
	                    if (!noPhase.hasRun) {
	                        // Try running noPhase to see if that unblocks this phase next tick.
	                        // This can happen if a phase that happens before noPhase
	                        // is waiting on a noPhase policy to complete.
	                        walkPhase(noPhase);
	                    }
	                    // Don't proceed to the next phase until this phase finishes.
	                    return;
	                }
	                if (phase.hasAfterPolicies) {
	                    // Run any policies unblocked by this phase
	                    walkPhase(noPhase);
	                }
	            }
	        }
	        // Iterate until we've put every node in the result list.
	        let iteration = 0;
	        while (policyMap.size > 0) {
	            iteration++;
	            const initialResultLength = result.length;
	            // Keep walking each phase in order until we can order every node.
	            walkPhases();
	            // The result list *should* get at least one larger each time
	            // after the first full pass.
	            // Otherwise, we're going to loop forever.
	            if (result.length <= initialResultLength && iteration > 1) {
	                throw new Error("Cannot satisfy policy dependencies due to requirements cycle.");
	            }
	        }
	        return result;
	    }
	}
	/**
	 * Creates a totally empty pipeline.
	 * Useful for testing or creating a custom one.
	 */
	function createEmptyPipeline() {
	    return HttpPipeline.create();
	}

	// Copyright (c) Microsoft Corporation.
	function log(message, ...args) {
	    process__namespace.stderr.write(`${util__default["default"].format(message, ...args)}${os.EOL}`);
	}

	// Copyright (c) Microsoft Corporation.
	const debugEnvVariable = (typeof process !== "undefined" && process.env && process.env.DEBUG) || undefined;
	let enabledString;
	let enabledNamespaces = [];
	let skippedNamespaces = [];
	const debuggers = [];
	if (debugEnvVariable) {
	    enable(debugEnvVariable);
	}
	const debugObj = Object.assign((namespace) => {
	    return createDebugger(namespace);
	}, {
	    enable,
	    enabled,
	    disable,
	    log,
	});
	function enable(namespaces) {
	    enabledString = namespaces;
	    enabledNamespaces = [];
	    skippedNamespaces = [];
	    const wildcard = /\*/g;
	    const namespaceList = namespaces.split(",").map((ns) => ns.trim().replace(wildcard, ".*?"));
	    for (const ns of namespaceList) {
	        if (ns.startsWith("-")) {
	            skippedNamespaces.push(new RegExp(`^${ns.substr(1)}$`));
	        }
	        else {
	            enabledNamespaces.push(new RegExp(`^${ns}$`));
	        }
	    }
	    for (const instance of debuggers) {
	        instance.enabled = enabled(instance.namespace);
	    }
	}
	function enabled(namespace) {
	    if (namespace.endsWith("*")) {
	        return true;
	    }
	    for (const skipped of skippedNamespaces) {
	        if (skipped.test(namespace)) {
	            return false;
	        }
	    }
	    for (const enabledNamespace of enabledNamespaces) {
	        if (enabledNamespace.test(namespace)) {
	            return true;
	        }
	    }
	    return false;
	}
	function disable() {
	    const result = enabledString || "";
	    enable("");
	    return result;
	}
	function createDebugger(namespace) {
	    const newDebugger = Object.assign(debug, {
	        enabled: enabled(namespace),
	        destroy,
	        log: debugObj.log,
	        namespace,
	        extend,
	    });
	    function debug(...args) {
	        if (!newDebugger.enabled) {
	            return;
	        }
	        if (args.length > 0) {
	            args[0] = `${namespace} ${args[0]}`;
	        }
	        newDebugger.log(...args);
	    }
	    debuggers.push(newDebugger);
	    return newDebugger;
	}
	function destroy() {
	    const index = debuggers.indexOf(this);
	    if (index >= 0) {
	        debuggers.splice(index, 1);
	        return true;
	    }
	    return false;
	}
	function extend(namespace) {
	    const newDebugger = createDebugger(`${this.namespace}:${namespace}`);
	    newDebugger.log = this.log;
	    return newDebugger;
	}
	var debug = debugObj;

	// Copyright (c) Microsoft Corporation.
	const registeredLoggers = new Set();
	const logLevelFromEnv = (typeof process !== "undefined" && process.env && process.env.AZURE_LOG_LEVEL) || undefined;
	let azureLogLevel;
	/**
	 * The AzureLogger provides a mechanism for overriding where logs are output to.
	 * By default, logs are sent to stderr.
	 * Override the `log` method to redirect logs to another location.
	 */
	const AzureLogger = debug("azure");
	AzureLogger.log = (...args) => {
	    debug.log(...args);
	};
	const AZURE_LOG_LEVELS = ["verbose", "info", "warning", "error"];
	if (logLevelFromEnv) {
	    // avoid calling setLogLevel because we don't want a mis-set environment variable to crash
	    if (isAzureLogLevel(logLevelFromEnv)) {
	        setLogLevel(logLevelFromEnv);
	    }
	    else {
	        console.error(`AZURE_LOG_LEVEL set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${AZURE_LOG_LEVELS.join(", ")}.`);
	    }
	}
	/**
	 * Immediately enables logging at the specified log level. If no level is specified, logging is disabled.
	 * @param level - The log level to enable for logging.
	 * Options from most verbose to least verbose are:
	 * - verbose
	 * - info
	 * - warning
	 * - error
	 */
	function setLogLevel(level) {
	    if (level && !isAzureLogLevel(level)) {
	        throw new Error(`Unknown log level '${level}'. Acceptable values: ${AZURE_LOG_LEVELS.join(",")}`);
	    }
	    azureLogLevel = level;
	    const enabledNamespaces = [];
	    for (const logger of registeredLoggers) {
	        if (shouldEnable(logger)) {
	            enabledNamespaces.push(logger.namespace);
	        }
	    }
	    debug.enable(enabledNamespaces.join(","));
	}
	const levelMap = {
	    verbose: 400,
	    info: 300,
	    warning: 200,
	    error: 100,
	};
	/**
	 * Creates a logger for use by the Azure SDKs that inherits from `AzureLogger`.
	 * @param namespace - The name of the SDK package.
	 * @hidden
	 */
	function createClientLogger(namespace) {
	    const clientRootLogger = AzureLogger.extend(namespace);
	    patchLogMethod(AzureLogger, clientRootLogger);
	    return {
	        error: createLogger(clientRootLogger, "error"),
	        warning: createLogger(clientRootLogger, "warning"),
	        info: createLogger(clientRootLogger, "info"),
	        verbose: createLogger(clientRootLogger, "verbose"),
	    };
	}
	function patchLogMethod(parent, child) {
	    child.log = (...args) => {
	        parent.log(...args);
	    };
	}
	function createLogger(parent, level) {
	    const logger = Object.assign(parent.extend(level), {
	        level,
	    });
	    patchLogMethod(parent, logger);
	    if (shouldEnable(logger)) {
	        const enabledNamespaces = debug.disable();
	        debug.enable(enabledNamespaces + "," + logger.namespace);
	    }
	    registeredLoggers.add(logger);
	    return logger;
	}
	function shouldEnable(logger) {
	    return Boolean(azureLogLevel && levelMap[logger.level] <= levelMap[azureLogLevel]);
	}
	function isAzureLogLevel(logLevel) {
	    return AZURE_LOG_LEVELS.includes(logLevel);
	}

	// Copyright (c) Microsoft Corporation.
	const logger$1 = createClientLogger("core-rest-pipeline");

	// Copyright (c) Microsoft Corporation.
	const RedactedString = "REDACTED";
	// Make sure this list is up-to-date with the one under core/logger/Readme#Keyconcepts
	const defaultAllowedHeaderNames = [
	    "x-ms-client-request-id",
	    "x-ms-return-client-request-id",
	    "x-ms-useragent",
	    "x-ms-correlation-request-id",
	    "x-ms-request-id",
	    "client-request-id",
	    "ms-cv",
	    "return-client-request-id",
	    "traceparent",
	    "Access-Control-Allow-Credentials",
	    "Access-Control-Allow-Headers",
	    "Access-Control-Allow-Methods",
	    "Access-Control-Allow-Origin",
	    "Access-Control-Expose-Headers",
	    "Access-Control-Max-Age",
	    "Access-Control-Request-Headers",
	    "Access-Control-Request-Method",
	    "Origin",
	    "Accept",
	    "Accept-Encoding",
	    "Cache-Control",
	    "Connection",
	    "Content-Length",
	    "Content-Type",
	    "Date",
	    "ETag",
	    "Expires",
	    "If-Match",
	    "If-Modified-Since",
	    "If-None-Match",
	    "If-Unmodified-Since",
	    "Last-Modified",
	    "Pragma",
	    "Request-Id",
	    "Retry-After",
	    "Server",
	    "Transfer-Encoding",
	    "User-Agent",
	    "WWW-Authenticate",
	];
	const defaultAllowedQueryParameters = ["api-version"];
	/**
	 * @internal
	 */
	class Sanitizer {
	    constructor({ additionalAllowedHeaderNames: allowedHeaderNames = [], additionalAllowedQueryParameters: allowedQueryParameters = [], } = {}) {
	        allowedHeaderNames = defaultAllowedHeaderNames.concat(allowedHeaderNames);
	        allowedQueryParameters = defaultAllowedQueryParameters.concat(allowedQueryParameters);
	        this.allowedHeaderNames = new Set(allowedHeaderNames.map((n) => n.toLowerCase()));
	        this.allowedQueryParameters = new Set(allowedQueryParameters.map((p) => p.toLowerCase()));
	    }
	    sanitize(obj) {
	        const seen = new Set();
	        return JSON.stringify(obj, (key, value) => {
	            // Ensure Errors include their interesting non-enumerable members
	            if (value instanceof Error) {
	                return Object.assign(Object.assign({}, value), { name: value.name, message: value.message });
	            }
	            if (key === "headers") {
	                return this.sanitizeHeaders(value);
	            }
	            else if (key === "url") {
	                return this.sanitizeUrl(value);
	            }
	            else if (key === "query") {
	                return this.sanitizeQuery(value);
	            }
	            else if (key === "body") {
	                // Don't log the request body
	                return undefined;
	            }
	            else if (key === "response") {
	                // Don't log response again
	                return undefined;
	            }
	            else if (key === "operationSpec") {
	                // When using sendOperationRequest, the request carries a massive
	                // field with the autorest spec. No need to log it.
	                return undefined;
	            }
	            else if (Array.isArray(value) || isObject(value)) {
	                if (seen.has(value)) {
	                    return "[Circular]";
	                }
	                seen.add(value);
	            }
	            return value;
	        }, 2);
	    }
	    sanitizeUrl(value) {
	        if (typeof value !== "string" || value === null || value === "") {
	            return value;
	        }
	        const url = new URL(value);
	        if (!url.search) {
	            return value;
	        }
	        for (const [key] of url.searchParams) {
	            if (!this.allowedQueryParameters.has(key.toLowerCase())) {
	                url.searchParams.set(key, RedactedString);
	            }
	        }
	        return url.toString();
	    }
	    sanitizeHeaders(obj) {
	        const sanitized = {};
	        for (const key of Object.keys(obj)) {
	            if (this.allowedHeaderNames.has(key.toLowerCase())) {
	                sanitized[key] = obj[key];
	            }
	            else {
	                sanitized[key] = RedactedString;
	            }
	        }
	        return sanitized;
	    }
	    sanitizeQuery(value) {
	        if (typeof value !== "object" || value === null) {
	            return value;
	        }
	        const sanitized = {};
	        for (const k of Object.keys(value)) {
	            if (this.allowedQueryParameters.has(k.toLowerCase())) {
	                sanitized[k] = value[k];
	            }
	            else {
	                sanitized[k] = RedactedString;
	            }
	        }
	        return sanitized;
	    }
	}

	// Copyright (c) Microsoft Corporation.
	/**
	 * The programmatic identifier of the logPolicy.
	 */
	const logPolicyName = "logPolicy";
	/**
	 * A policy that logs all requests and responses.
	 * @param options - Options to configure logPolicy.
	 */
	function logPolicy(options = {}) {
	    var _a;
	    const logger = (_a = options.logger) !== null && _a !== void 0 ? _a : logger$1.info;
	    const sanitizer = new Sanitizer({
	        additionalAllowedHeaderNames: options.additionalAllowedHeaderNames,
	        additionalAllowedQueryParameters: options.additionalAllowedQueryParameters,
	    });
	    return {
	        name: logPolicyName,
	        async sendRequest(request, next) {
	            if (!logger.enabled) {
	                return next(request);
	            }
	            logger(`Request: ${sanitizer.sanitize(request)}`);
	            const response = await next(request);
	            logger(`Response status code: ${response.status}`);
	            logger(`Headers: ${sanitizer.sanitize(response.headers)}`);
	            return response;
	        },
	    };
	}

	// Copyright (c) Microsoft Corporation.
	// Licensed under the MIT License.
	/**
	 * The programmatic identifier of the redirectPolicy.
	 */
	const redirectPolicyName = "redirectPolicy";
	/**
	 * Methods that are allowed to follow redirects 301 and 302
	 */
	const allowedRedirect = ["GET", "HEAD"];
	/**
	 * A policy to follow Location headers from the server in order
	 * to support server-side redirection.
	 * In the browser, this policy is not used.
	 * @param options - Options to control policy behavior.
	 */
	function redirectPolicy(options = {}) {
	    const { maxRetries = 20 } = options;
	    return {
	        name: redirectPolicyName,
	        async sendRequest(request, next) {
	            const response = await next(request);
	            return handleRedirect(next, response, maxRetries);
	        },
	    };
	}
	async function handleRedirect(next, response, maxRetries, currentRetries = 0) {
	    const { request, status, headers } = response;
	    const locationHeader = headers.get("location");
	    if (locationHeader &&
	        (status === 300 ||
	            (status === 301 && allowedRedirect.includes(request.method)) ||
	            (status === 302 && allowedRedirect.includes(request.method)) ||
	            (status === 303 && request.method === "POST") ||
	            status === 307) &&
	        currentRetries < maxRetries) {
	        const url = new URL(locationHeader, request.url);
	        request.url = url.toString();
	        // POST request with Status code 303 should be converted into a
	        // redirected GET request if the redirect url is present in the location header
	        if (status === 303) {
	            request.method = "GET";
	            request.headers.delete("Content-Length");
	            delete request.body;
	        }
	        request.headers.delete("Authorization");
	        const res = await next(request);
	        return handleRedirect(next, res, maxRetries, currentRetries + 1);
	    }
	    return response;
	}

	// Copyright (c) Microsoft Corporation.
	/**
	 * @internal
	 */
	function getHeaderName() {
	    return "User-Agent";
	}
	/**
	 * @internal
	 */
	async function setPlatformSpecificData(map) {
	    if (process__namespace && process__namespace.versions) {
	        const versions = process__namespace.versions;
	        if (versions.bun) {
	            map.set("Bun", versions.bun);
	        }
	        else if (versions.deno) {
	            map.set("Deno", versions.deno);
	        }
	        else if (versions.node) {
	            map.set("Node", versions.node);
	        }
	    }
	    map.set("OS", `(${os__namespace.arch()}-${os__namespace.type()}-${os__namespace.release()})`);
	}

	// Copyright (c) Microsoft Corporation.
	// Licensed under the MIT License.
	const SDK_VERSION = "1.17.0";
	const DEFAULT_RETRY_POLICY_COUNT = 3;

	// Copyright (c) Microsoft Corporation.
	function getUserAgentString(telemetryInfo) {
	    const parts = [];
	    for (const [key, value] of telemetryInfo) {
	        const token = value ? `${key}/${value}` : key;
	        parts.push(token);
	    }
	    return parts.join(" ");
	}
	/**
	 * @internal
	 */
	function getUserAgentHeaderName() {
	    return getHeaderName();
	}
	/**
	 * @internal
	 */
	async function getUserAgentValue(prefix) {
	    const runtimeInfo = new Map();
	    runtimeInfo.set("core-rest-pipeline", SDK_VERSION);
	    await setPlatformSpecificData(runtimeInfo);
	    const defaultAgent = getUserAgentString(runtimeInfo);
	    const userAgentValue = prefix ? `${prefix} ${defaultAgent}` : defaultAgent;
	    return userAgentValue;
	}

	// Copyright (c) Microsoft Corporation.
	const UserAgentHeaderName = getUserAgentHeaderName();
	/**
	 * The programmatic identifier of the userAgentPolicy.
	 */
	const userAgentPolicyName = "userAgentPolicy";
	/**
	 * A policy that sets the User-Agent header (or equivalent) to reflect
	 * the library version.
	 * @param options - Options to customize the user agent value.
	 */
	function userAgentPolicy(options = {}) {
	    const userAgentValue = getUserAgentValue(options.userAgentPrefix);
	    return {
	        name: userAgentPolicyName,
	        async sendRequest(request, next) {
	            if (!request.headers.has(UserAgentHeaderName)) {
	                request.headers.set(UserAgentHeaderName, await userAgentValue);
	            }
	            return next(request);
	        },
	    };
	}

	/******************************************************************************
	Copyright (c) Microsoft Corporation.

	Permission to use, copy, modify, and/or distribute this software for any
	purpose with or without fee is hereby granted.

	THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
	REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
	AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
	INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
	LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
	OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
	PERFORMANCE OF THIS SOFTWARE.
	***************************************************************************** */

	function __values(o) {
	    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
	    if (m) return m.call(o);
	    if (o && typeof o.length === "number") return {
	        next: function () {
	            if (o && i >= o.length) o = void 0;
	            return { value: o && o[i++], done: !o };
	        }
	    };
	    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
	}

	function __await(v) {
	    return this instanceof __await ? (this.v = v, this) : new __await(v);
	}

	function __asyncGenerator(thisArg, _arguments, generator) {
	    if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
	    var g = generator.apply(thisArg, _arguments || []), i, q = [];
	    return i = {}, verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
	    function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
	    function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
	    function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
	    function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
	    function fulfill(value) { resume("next", value); }
	    function reject(value) { resume("throw", value); }
	    function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
	}

	function __asyncValues(o) {
	    if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
	    var m = o[Symbol.asyncIterator], i;
	    return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
	    function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
	    function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
	}

	typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
	    var e = new Error(message);
	    return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
	};

	// Copyright (c) Microsoft Corporation.
	// Licensed under the MIT License.
	function isNodeReadableStream(x) {
	    return Boolean(x && typeof x["pipe"] === "function");
	}
	function isBlob(x) {
	    return typeof x.stream === "function";
	}

	// Copyright (c) Microsoft Corporation.
	const unimplementedMethods = {
	    arrayBuffer: () => {
	        throw new Error("Not implemented");
	    },
	    slice: () => {
	        throw new Error("Not implemented");
	    },
	    text: () => {
	        throw new Error("Not implemented");
	    },
	};
	/**
	 * Private symbol used as key on objects created using createFile containing the
	 * original source of the file object.
	 *
	 * This is used in Node to access the original Node stream without using Blob#stream, which
	 * returns a web stream. This is done to avoid a couple of bugs to do with Blob#stream and
	 * Readable#to/fromWeb in Node versions we support:
	 * - https://github.com/nodejs/node/issues/42694 (fixed in Node 18.14)
	 * - https://github.com/nodejs/node/issues/48916 (fixed in Node 20.6)
	 *
	 * Once these versions are no longer supported, we may be able to stop doing this.
	 *
	 * @internal
	 */
	const rawContent = Symbol("rawContent");
	function hasRawContent(x) {
	    return typeof x[rawContent] === "function";
	}
	/**
	 * Extract the raw content from a given blob-like object. If the input was created using createFile
	 * or createFileFromStream, the exact content passed into createFile/createFileFromStream will be used.
	 * For true instances of Blob and File, returns the blob's content as a Web ReadableStream<Uint8Array>.
	 *
	 * @internal
	 */
	function getRawContent(blob) {
	    if (hasRawContent(blob)) {
	        return blob[rawContent]();
	    }
	    else {
	        return blob.stream();
	    }
	}
	/**
	 * Create an object that implements the File interface. This object is intended to be
	 * passed into RequestBodyType.formData, and is not guaranteed to work as expected in
	 * other situations.
	 *
	 * Use this function to:
	 * - Create a File object for use in RequestBodyType.formData in environments where the
	 *   global File object is unavailable.
	 * - Create a File-like object from a readable stream without reading the stream into memory.
	 *
	 * @param stream - the content of the file as a callback returning a stream. When a File object made using createFile is
	 *                  passed in a request's form data map, the stream will not be read into memory
	 *                  and instead will be streamed when the request is made. In the event of a retry, the
	 *                  stream needs to be read again, so this callback SHOULD return a fresh stream if possible.
	 * @param name - the name of the file.
	 * @param options - optional metadata about the file, e.g. file name, file size, MIME type.
	 */
	function createFileFromStream(stream, name, options = {}) {
	    var _a, _b, _c, _d;
	    return Object.assign(Object.assign({}, unimplementedMethods), { type: (_a = options.type) !== null && _a !== void 0 ? _a : "", lastModified: (_b = options.lastModified) !== null && _b !== void 0 ? _b : new Date().getTime(), webkitRelativePath: (_c = options.webkitRelativePath) !== null && _c !== void 0 ? _c : "", size: (_d = options.size) !== null && _d !== void 0 ? _d : -1, name, stream: () => {
	            const s = stream();
	            if (isNodeReadableStream(s)) {
	                throw new Error("Not supported: a Node stream was provided as input to createFileFromStream.");
	            }
	            return s;
	        }, [rawContent]: stream });
	}
	/**
	 * Create an object that implements the File interface. This object is intended to be
	 * passed into RequestBodyType.formData, and is not guaranteed to work as expected in
	 * other situations.
	 *
	 * Use this function create a File object for use in RequestBodyType.formData in environments where the global File object is unavailable.
	 *
	 * @param content - the content of the file as a Uint8Array in memory.
	 * @param name - the name of the file.
	 * @param options - optional metadata about the file, e.g. file name, file size, MIME type.
	 */
	function createFile(content, name, options = {}) {
	    var _a, _b, _c;
	    if (isNodeLike) {
	        return Object.assign(Object.assign({}, unimplementedMethods), { type: (_a = options.type) !== null && _a !== void 0 ? _a : "", lastModified: (_b = options.lastModified) !== null && _b !== void 0 ? _b : new Date().getTime(), webkitRelativePath: (_c = options.webkitRelativePath) !== null && _c !== void 0 ? _c : "", size: content.byteLength, name, arrayBuffer: async () => content.buffer, stream: () => new Blob([content]).stream(), [rawContent]: () => content });
	    }
	    else {
	        return new File([content], name, options);
	    }
	}

	// Copyright (c) Microsoft Corporation.
	function streamAsyncIterator() {
	    return __asyncGenerator(this, arguments, function* streamAsyncIterator_1() {
	        const reader = this.getReader();
	        try {
	            while (true) {
	                const { done, value } = yield __await(reader.read());
	                if (done) {
	                    return yield __await(void 0);
	                }
	                yield yield __await(value);
	            }
	        }
	        finally {
	            reader.releaseLock();
	        }
	    });
	}
	function makeAsyncIterable(webStream) {
	    if (!webStream[Symbol.asyncIterator]) {
	        webStream[Symbol.asyncIterator] = streamAsyncIterator.bind(webStream);
	    }
	    if (!webStream.values) {
	        webStream.values = streamAsyncIterator.bind(webStream);
	    }
	}
	function ensureNodeStream(stream) {
	    if (stream instanceof ReadableStream) {
	        makeAsyncIterable(stream);
	        return node_stream.Readable.fromWeb(stream);
	    }
	    else {
	        return stream;
	    }
	}
	function toStream(source) {
	    if (source instanceof Uint8Array) {
	        return node_stream.Readable.from(Buffer.from(source));
	    }
	    else if (isBlob(source)) {
	        return toStream(getRawContent(source));
	    }
	    else {
	        return ensureNodeStream(source);
	    }
	}
	/**
	 * Utility function that concatenates a set of binary inputs into one combined output.
	 *
	 * @param sources - array of sources for the concatenation
	 * @returns - in Node, a (() =\> NodeJS.ReadableStream) which, when read, produces a concatenation of all the inputs.
	 *           In browser, returns a `Blob` representing all the concatenated inputs.
	 *
	 * @internal
	 */
	async function concat(sources) {
	    return function () {
	        const streams = sources.map((x) => (typeof x === "function" ? x() : x)).map(toStream);
	        return node_stream.Readable.from((function () {
	            return __asyncGenerator(this, arguments, function* () {
	                var _a, e_1, _b, _c;
	                for (const stream of streams) {
	                    try {
	                        for (var _d = true, stream_1 = (e_1 = void 0, __asyncValues(stream)), stream_1_1; stream_1_1 = yield __await(stream_1.next()), _a = stream_1_1.done, !_a; _d = true) {
	                            _c = stream_1_1.value;
	                            _d = false;
	                            const chunk = _c;
	                            yield yield __await(chunk);
	                        }
	                    }
	                    catch (e_1_1) { e_1 = { error: e_1_1 }; }
	                    finally {
	                        try {
	                            if (!_d && !_a && (_b = stream_1.return)) yield __await(_b.call(stream_1));
	                        }
	                        finally { if (e_1) throw e_1.error; }
	                    }
	                }
	            });
	        })());
	    };
	}

	// Copyright (c) Microsoft Corporation.
	function generateBoundary() {
	    return `----AzSDKFormBoundary${randomUUID()}`;
	}
	function encodeHeaders(headers) {
	    let result = "";
	    for (const [key, value] of headers) {
	        result += `${key}: ${value}\r\n`;
	    }
	    return result;
	}
	function getLength(source) {
	    if (source instanceof Uint8Array) {
	        return source.byteLength;
	    }
	    else if (isBlob(source)) {
	        // if was created using createFile then -1 means we have an unknown size
	        return source.size === -1 ? undefined : source.size;
	    }
	    else {
	        return undefined;
	    }
	}
	function getTotalLength(sources) {
	    let total = 0;
	    for (const source of sources) {
	        const partLength = getLength(source);
	        if (partLength === undefined) {
	            return undefined;
	        }
	        else {
	            total += partLength;
	        }
	    }
	    return total;
	}
	async function buildRequestBody(request, parts, boundary) {
	    const sources = [
	        stringToUint8Array(`--${boundary}`, "utf-8"),
	        ...parts.flatMap((part) => [
	            stringToUint8Array("\r\n", "utf-8"),
	            stringToUint8Array(encodeHeaders(part.headers), "utf-8"),
	            stringToUint8Array("\r\n", "utf-8"),
	            part.body,
	            stringToUint8Array(`\r\n--${boundary}`, "utf-8"),
	        ]),
	        stringToUint8Array("--\r\n\r\n", "utf-8"),
	    ];
	    const contentLength = getTotalLength(sources);
	    if (contentLength) {
	        request.headers.set("Content-Length", contentLength);
	    }
	    request.body = await concat(sources);
	}
	/**
	 * Name of multipart policy
	 */
	const multipartPolicyName = "multipartPolicy";
	const maxBoundaryLength = 70;
	const validBoundaryCharacters = new Set(`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'()+,-./:=?`);
	function assertValidBoundary(boundary) {
	    if (boundary.length > maxBoundaryLength) {
	        throw new Error(`Multipart boundary "${boundary}" exceeds maximum length of 70 characters`);
	    }
	    if (Array.from(boundary).some((x) => !validBoundaryCharacters.has(x))) {
	        throw new Error(`Multipart boundary "${boundary}" contains invalid characters`);
	    }
	}
	/**
	 * Pipeline policy for multipart requests
	 */
	function multipartPolicy() {
	    return {
	        name: multipartPolicyName,
	        async sendRequest(request, next) {
	            var _a;
	            if (!request.multipartBody) {
	                return next(request);
	            }
	            if (request.body) {
	                throw new Error("multipartBody and regular body cannot be set at the same time");
	            }
	            let boundary = request.multipartBody.boundary;
	            const contentTypeHeader = (_a = request.headers.get("Content-Type")) !== null && _a !== void 0 ? _a : "multipart/mixed";
	            const parsedHeader = contentTypeHeader.match(/^(multipart\/[^ ;]+)(?:; *boundary=(.+))?$/);
	            if (!parsedHeader) {
	                throw new Error(`Got multipart request body, but content-type header was not multipart: ${contentTypeHeader}`);
	            }
	            const [, contentType, parsedBoundary] = parsedHeader;
	            if (parsedBoundary && boundary && parsedBoundary !== boundary) {
	                throw new Error(`Multipart boundary was specified as ${parsedBoundary} in the header, but got ${boundary} in the request body`);
	            }
	            boundary !== null && boundary !== void 0 ? boundary : (boundary = parsedBoundary);
	            if (boundary) {
	                assertValidBoundary(boundary);
	            }
	            else {
	                boundary = generateBoundary();
	            }
	            request.headers.set("Content-Type", `${contentType}; boundary=${boundary}`);
	            await buildRequestBody(request, request.multipartBody.parts, boundary);
	            request.multipartBody = undefined;
	            return next(request);
	        },
	    };
	}

	// Copyright (c) Microsoft Corporation.
	// Licensed under the MIT License.
	/**
	 * The programmatic identifier of the decompressResponsePolicy.
	 */
	const decompressResponsePolicyName = "decompressResponsePolicy";
	/**
	 * A policy to enable response decompression according to Accept-Encoding header
	 * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding
	 */
	function decompressResponsePolicy() {
	    return {
	        name: decompressResponsePolicyName,
	        async sendRequest(request, next) {
	            // HEAD requests have no body
	            if (request.method !== "HEAD") {
	                request.headers.set("Accept-Encoding", "gzip,deflate");
	            }
	            return next(request);
	        },
	    };
	}

	// Copyright (c) Microsoft Corporation.
	const StandardAbortMessage = "The operation was aborted.";
	/**
	 * A wrapper for setTimeout that resolves a promise after delayInMs milliseconds.
	 * @param delayInMs - The number of milliseconds to be delayed.
	 * @param value - The value to be resolved with after a timeout of t milliseconds.
	 * @param options - The options for delay - currently abort options
	 *                  - abortSignal - The abortSignal associated with containing operation.
	 *                  - abortErrorMsg - The abort error message associated with containing operation.
	 * @returns Resolved promise
	 */
	function delay(delayInMs, value, options) {
	    return new Promise((resolve, reject) => {
	        let timer = undefined;
	        let onAborted = undefined;
	        const rejectOnAbort = () => {
	            return reject(new AbortError((options === null || options === void 0 ? void 0 : options.abortErrorMsg) ? options === null || options === void 0 ? void 0 : options.abortErrorMsg : StandardAbortMessage));
	        };
	        const removeListeners = () => {
	            if ((options === null || options === void 0 ? void 0 : options.abortSignal) && onAborted) {
	                options.abortSignal.removeEventListener("abort", onAborted);
	            }
	        };
	        onAborted = () => {
	            if (timer) {
	                clearTimeout(timer);
	            }
	            removeListeners();
	            return rejectOnAbort();
	        };
	        if ((options === null || options === void 0 ? void 0 : options.abortSignal) && options.abortSignal.aborted) {
	            return rejectOnAbort();
	        }
	        timer = setTimeout(() => {
	            removeListeners();
	            resolve(value);
	        }, delayInMs);
	        if (options === null || options === void 0 ? void 0 : options.abortSignal) {
	            options.abortSignal.addEventListener("abort", onAborted);
	        }
	    });
	}
	/**
	 * @internal
	 * @returns the parsed value or undefined if the parsed value is invalid.
	 */
	function parseHeaderValueAsNumber(response, headerName) {
	    const value = response.headers.get(headerName);
	    if (!value)
	        return;
	    const valueAsNum = Number(value);
	    if (Number.isNaN(valueAsNum))
	        return;
	    return valueAsNum;
	}

	// Copyright (c) Microsoft Corporation.
	/**
	 * The header that comes back from Azure services representing
	 * the amount of time (minimum) to wait to retry (in seconds or timestamp after which we can retry).
	 */
	const RetryAfterHeader = "Retry-After";
	/**
	 * The headers that come back from Azure services representing
	 * the amount of time (minimum) to wait to retry.
	 *
	 * "retry-after-ms", "x-ms-retry-after-ms" : milliseconds
	 * "Retry-After" : seconds or timestamp
	 */
	const AllRetryAfterHeaders = ["retry-after-ms", "x-ms-retry-after-ms", RetryAfterHeader];
	/**
	 * A response is a throttling retry response if it has a throttling status code (429 or 503),
	 * as long as one of the [ "Retry-After" or "retry-after-ms" or "x-ms-retry-after-ms" ] headers has a valid value.
	 *
	 * Returns the `retryAfterInMs` value if the response is a throttling retry response.
	 * If not throttling retry response, returns `undefined`.
	 *
	 * @internal
	 */
	function getRetryAfterInMs(response) {
	    if (!(response && [429, 503].includes(response.status)))
	        return undefined;
	    try {
	        // Headers: "retry-after-ms", "x-ms-retry-after-ms", "Retry-After"
	        for (const header of AllRetryAfterHeaders) {
	            const retryAfterValue = parseHeaderValueAsNumber(response, header);
	            if (retryAfterValue === 0 || retryAfterValue) {
	                // "Retry-After" header ==> seconds
	                // "retry-after-ms", "x-ms-retry-after-ms" headers ==> milli-seconds
	                const multiplyingFactor = header === RetryAfterHeader ? 1000 : 1;
	                return retryAfterValue * multiplyingFactor; // in milli-seconds
	            }
	        }
	        // RetryAfterHeader ("Retry-After") has a special case where it might be formatted as a date instead of a number of seconds
	        const retryAfterHeader = response.headers.get(RetryAfterHeader);
	        if (!retryAfterHeader)
	            return;
	        const date = Date.parse(retryAfterHeader);
	        const diff = date - Date.now();
	        // negative diff would mean a date in the past, so retry asap with 0 milliseconds
	        return Number.isFinite(diff) ? Math.max(0, diff) : undefined;
	    }
	    catch (_a) {
	        return undefined;
	    }
	}
	/**
	 * A response is a retry response if it has a throttling status code (429 or 503),
	 * as long as one of the [ "Retry-After" or "retry-after-ms" or "x-ms-retry-after-ms" ] headers has a valid value.
	 */
	function isThrottlingRetryResponse(response) {
	    return Number.isFinite(getRetryAfterInMs(response));
	}
	function throttlingRetryStrategy() {
	    return {
	        name: "throttlingRetryStrategy",
	        retry({ response }) {
	            const retryAfterInMs = getRetryAfterInMs(response);
	            if (!Number.isFinite(retryAfterInMs)) {
	                return { skipStrategy: true };
	            }
	            return {
	                retryAfterInMs,
	            };
	        },
	    };
	}

	// Copyright (c) Microsoft Corporation.
	// intervals are in milliseconds
	const DEFAULT_CLIENT_RETRY_INTERVAL = 1000;
	const DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 64;
	/**
	 * A retry strategy that retries with an exponentially increasing delay in these two cases:
	 * - When there are errors in the underlying transport layer (e.g. DNS lookup failures).
	 * - Or otherwise if the outgoing request fails (408, greater or equal than 500, except for 501 and 505).
	 */
	function exponentialRetryStrategy(options = {}) {
	    var _a, _b;
	    const retryInterval = (_a = options.retryDelayInMs) !== null && _a !== void 0 ? _a : DEFAULT_CLIENT_RETRY_INTERVAL;
	    const maxRetryInterval = (_b = options.maxRetryDelayInMs) !== null && _b !== void 0 ? _b : DEFAULT_CLIENT_MAX_RETRY_INTERVAL;
	    let retryAfterInMs = retryInterval;
	    return {
	        name: "exponentialRetryStrategy",
	        retry({ retryCount, response, responseError }) {
	            const matchedSystemError = isSystemError(responseError);
	            const ignoreSystemErrors = matchedSystemError && options.ignoreSystemErrors;
	            const isExponential = isExponentialRetryResponse(response);
	            const ignoreExponentialResponse = isExponential && options.ignoreHttpStatusCodes;
	            const unknownResponse = response && (isThrottlingRetryResponse(response) || !isExponential);
	            if (unknownResponse || ignoreExponentialResponse || ignoreSystemErrors) {
	                return { skipStrategy: true };
	            }
	            if (responseError && !matchedSystemError && !isExponential) {
	                return { errorToThrow: responseError };
	            }
	            // Exponentially increase the delay each time
	            const exponentialDelay = retryAfterInMs * Math.pow(2, retryCount);
	            // Don't let the delay exceed the maximum
	            const clampedExponentialDelay = Math.min(maxRetryInterval, exponentialDelay);
	            // Allow the final value to have some "jitter" (within 50% of the delay size) so
	            // that retries across multiple clients don't occur simultaneously.
	            retryAfterInMs =
	                clampedExponentialDelay / 2 + getRandomIntegerInclusive(0, clampedExponentialDelay / 2);
	            return { retryAfterInMs };
	        },
	    };
	}
	/**
	 * A response is a retry response if it has status codes:
	 * - 408, or
	 * - Greater or equal than 500, except for 501 and 505.
	 */
	function isExponentialRetryResponse(response) {
	    return Boolean(response &&
	        response.status !== undefined &&
	        (response.status >= 500 || response.status === 408) &&
	        response.status !== 501 &&
	        response.status !== 505);
	}
	/**
	 * Determines whether an error from a pipeline response was triggered in the network layer.
	 */
	function isSystemError(err) {
	    if (!err) {
	        return false;
	    }
	    return (err.code === "ETIMEDOUT" ||
	        err.code === "ESOCKETTIMEDOUT" ||
	        err.code === "ECONNREFUSED" ||
	        err.code === "ECONNRESET" ||
	        err.code === "ENOENT" ||
	        err.code === "ENOTFOUND");
	}

	// Copyright (c) Microsoft Corporation.
	const retryPolicyLogger = createClientLogger("core-rest-pipeline retryPolicy");
	/**
	 * The programmatic identifier of the retryPolicy.
	 */
	const retryPolicyName = "retryPolicy";
	/**
	 * retryPolicy is a generic policy to enable retrying requests when certain conditions are met
	 */
	function retryPolicy(strategies, options = { maxRetries: DEFAULT_RETRY_POLICY_COUNT }) {
	    const logger = options.logger || retryPolicyLogger;
	    return {
	        name: retryPolicyName,
	        async sendRequest(request, next) {
	            var _a, _b;
	            let response;
	            let responseError;
	            let retryCount = -1;
	            // eslint-disable-next-line no-constant-condition
	            retryRequest: while (true) {
	                retryCount += 1;
	                response = undefined;
	                responseError = undefined;
	                try {
	                    logger.info(`Retry ${retryCount}: Attempting to send request`, request.requestId);
	                    response = await next(request);
	                    logger.info(`Retry ${retryCount}: Received a response from request`, request.requestId);
	                }
	                catch (e) {
	                    logger.error(`Retry ${retryCount}: Received an error from request`, request.requestId);
	                    // RestErrors are valid targets for the retry strategies.
	                    // If none of the retry strategies can work with them, they will be thrown later in this policy.
	                    // If the received error is not a RestError, it is immediately thrown.
	                    responseError = e;
	                    if (!e || responseError.name !== "RestError") {
	                        throw e;
	                    }
	                    response = responseError.response;
	                }
	                if ((_a = request.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) {
	                    logger.error(`Retry ${retryCount}: Request aborted.`);
	                    const abortError = new AbortError();
	                    throw abortError;
	                }
	                if (retryCount >= ((_b = options.maxRetries) !== null && _b !== void 0 ? _b : DEFAULT_RETRY_POLICY_COUNT)) {
	                    logger.info(`Retry ${retryCount}: Maximum retries reached. Returning the last received response, or throwing the last received error.`);
	                    if (responseError) {
	                        throw responseError;
	                    }
	                    else if (response) {
	                        return response;
	                    }
	                    else {
	                        throw new Error("Maximum retries reached with no response or error to throw");
	                    }
	                }
	                logger.info(`Retry ${retryCount}: Processing ${strategies.length} retry strategies.`);
	                strategiesLoop: for (const strategy of strategies) {
	                    const strategyLogger = strategy.logger || retryPolicyLogger;
	                    strategyLogger.info(`Retry ${retryCount}: Processing retry strategy ${strategy.name}.`);
	                    const modifiers = strategy.retry({
	                        retryCount,
	                        response,
	                        responseError,
	                    });
	                    if (modifiers.skipStrategy) {
	                        strategyLogger.info(`Retry ${retryCount}: Skipped.`);
	                        continue strategiesLoop;
	                    }
	                    const { errorToThrow, retryAfterInMs, redirectTo } = modifiers;
	                    if (errorToThrow) {
	                        strategyLogger.error(`Retry ${retryCount}: Retry strategy ${strategy.name} throws error:`, errorToThrow);
	                        throw errorToThrow;
	                    }
	                    if (retryAfterInMs || retryAfterInMs === 0) {
	                        strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} retries after ${retryAfterInMs}`);
	                        await delay(retryAfterInMs, undefined, { abortSignal: request.abortSignal });
	                        continue retryRequest;
	                    }
	                    if (redirectTo) {
	                        strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} redirects to ${redirectTo}`);
	                        request.url = redirectTo;
	                        continue retryRequest;
	                    }
	                }
	                if (responseError) {
	                    logger.info(`None of the retry strategies could work with the received error. Throwing it.`);
	                    throw responseError;
	                }
	                if (response) {
	                    logger.info(`None of the retry strategies could work with the received response. Returning it.`);
	                    return response;
	                }
	                // If all the retries skip and there's no response,
	                // we're still in the retry loop, so a new request will be sent
	                // until `maxRetries` is reached.
	            }
	        },
	    };
	}

	// Copyright (c) Microsoft Corporation.
	/**
	 * Name of the {@link defaultRetryPolicy}
	 */
	const defaultRetryPolicyName = "defaultRetryPolicy";
	/**
	 * A policy that retries according to three strategies:
	 * - When the server sends a 429 response with a Retry-After header.
	 * - When there are errors in the underlying transport layer (e.g. DNS lookup failures).
	 * - Or otherwise if the outgoing request fails, it will retry with an exponentially increasing delay.
	 */
	function defaultRetryPolicy(options = {}) {
	    var _a;
	    return {
	        name: defaultRetryPolicyName,
	        sendRequest: retryPolicy([throttlingRetryStrategy(), exponentialRetryStrategy(options)], {
	            maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : DEFAULT_RETRY_POLICY_COUNT,
	        }).sendRequest,
	    };
	}

	// Copyright (c) Microsoft Corporation.
	// Licensed under the MIT License.
	function normalizeName(name) {
	    return name.toLowerCase();
	}
	function* headerIterator(map) {
	    for (const entry of map.values()) {
	        yield [entry.name, entry.value];
	    }
	}
	class HttpHeadersImpl {
	    constructor(rawHeaders) {
	        this._headersMap = new Map();
	        if (rawHeaders) {
	            for (const headerName of Object.keys(rawHeaders)) {
	                this.set(headerName, rawHeaders[headerName]);
	            }
	        }
	    }
	    /**
	     * Set a header in this collection with the provided name and value. The name is
	     * case-insensitive.
	     * @param name - The name of the header to set. This value is case-insensitive.
	     * @param value - The value of the header to set.
	     */
	    set(name, value) {
	        this._headersMap.set(normalizeName(name), { name, value: String(value).trim() });
	    }
	    /**
	     * Get the header value for the provided header name, or undefined if no header exists in this
	     * collection with the provided name.
	     * @param name - The name of the header. This value is case-insensitive.
	     */
	    get(name) {
	        var _a;
	        return (_a = this._headersMap.get(normalizeName(name))) === null || _a === void 0 ? void 0 : _a.value;
	    }
	    /**
	     * Get whether or not this header collection contains a header entry for the provided header name.
	     * @param name - The name of the header to set. This value is case-insensitive.
	     */
	    has(name) {
	        return this._headersMap.has(normalizeName(name));
	    }
	    /**
	     * Remove the header with the provided headerName.
	     * @param name - The name of the header to remove.
	     */
	    delete(name) {
	        this._headersMap.delete(normalizeName(name));
	    }
	    /**
	     * Get the JSON object representation of this HTTP header collection.
	     */
	    toJSON(options = {}) {
	        const result = {};
	        if (options.preserveCase) {
	            for (const entry of this._headersMap.values()) {
	                result[entry.name] = entry.value;
	            }
	        }
	        else {
	            for (const [normalizedName, entry] of this._headersMap) {
	                result[normalizedName] = entry.value;
	            }
	        }
	        return result;
	    }
	    /**
	     * Get the string representation of this HTTP header collection.
	     */
	    toString() {
	        return JSON.stringify(this.toJSON({ preserveCase: true }));
	    }
	    /**
	     * Iterate over tuples of header [name, value] pairs.
	     */
	    [Symbol.iterator]() {
	        return headerIterator(this._headersMap);
	    }
	}
	/**
	 * Creates an object that satisfies the `HttpHeaders` interface.
	 * @param rawHeaders - A simple object representing initial headers
	 */
	function createHttpHeaders(rawHeaders) {
	    return new HttpHeadersImpl(rawHeaders);
	}

	// Copyright (c) Microsoft Corporation.
	/**
	 * The programmatic identifier of the formDataPolicy.
	 */
	const formDataPolicyName = "formDataPolicy";
	function formDataToFormDataMap(formData) {
	    var _a;
	    const formDataMap = {};
	    for (const [key, value] of formData.entries()) {
	        (_a = formDataMap[key]) !== null && _a !== void 0 ? _a : (formDataMap[key] = []);
	        formDataMap[key].push(value);
	    }
	    return formDataMap;
	}
	/**
	 * A policy that encodes FormData on the request into the body.
	 */
	function formDataPolicy() {
	    return {
	        name: formDataPolicyName,
	        async sendRequest(request, next) {
	            if (isNodeLike && typeof FormData !== "undefined" && request.body instanceof FormData) {
	                request.formData = formDataToFormDataMap(request.body);
	                request.body = undefined;
	            }
	            if (request.formData) {
	                const contentType = request.headers.get("Content-Type");
	                if (contentType && contentType.indexOf("application/x-www-form-urlencoded") !== -1) {
	                    request.body = wwwFormUrlEncode(request.formData);
	                }
	                else {
	                    await prepareFormData(request.formData, request);
	                }
	                request.formData = undefined;
	            }
	            return next(request);
	        },
	    };
	}
	function wwwFormUrlEncode(formData) {
	    const urlSearchParams = new URLSearchParams();
	    for (const [key, value] of Object.entries(formData)) {
	        if (Array.isArray(value)) {
	            for (const subValue of value) {
	                urlSearchParams.append(key, subValue.toString());
	            }
	        }
	        else {
	            urlSearchParams.append(key, value.toString());
	        }
	    }
	    return urlSearchParams.toString();
	}
	async function prepareFormData(formData, request) {
	    // validate content type (multipart/form-data)
	    const contentType = request.headers.get("Content-Type");
	    if (contentType && !contentType.startsWith("multipart/form-data")) {
	        // content type is specified and is not multipart/form-data. Exit.
	        return;
	    }
	    request.headers.set("Content-Type", contentType !== null && contentType !== void 0 ? contentType : "multipart/form-data");
	    // set body to MultipartRequestBody using content from FormDataMap
	    const parts = [];
	    for (const [fieldName, values] of Object.entries(formData)) {
	        for (const value of Array.isArray(values) ? values : [values]) {
	            if (typeof value === "string") {
	                parts.push({
	                    headers: createHttpHeaders({
	                        "Content-Disposition": `form-data; name="${fieldName}"`,
	                    }),
	                    body: stringToUint8Array(value, "utf-8"),
	                });
	            }
	            else if (value === undefined || value === null || typeof value !== "object") {
	                throw new Error(`Unexpected value for key ${fieldName}: ${value}. Value should be serialized to string first.`);
	            }
	            else {
	                // using || instead of ?? here since if value.name is empty we should create a file name
	                const fileName = value.name || "blob";
	                const headers = createHttpHeaders();
	                headers.set("Content-Disposition", `form-data; name="${fieldName}"; filename="${fileName}"`);
	                // again, || is used since an empty value.type means the content type is unset
	                headers.set("Content-Type", value.type || "application/octet-stream");
	                parts.push({
	                    headers,
	                    body: value,
	                });
	            }
	        }
	    }
	    request.multipartBody = { parts };
	}

	/**
	 * Helpers.
	 */

	var s = 1000;
	var m = s * 60;
	var h = m * 60;
	var d = h * 24;
	var w = d * 7;
	var y = d * 365.25;

	/**
	 * Parse or format the given `val`.
	 *
	 * Options:
	 *
	 *  - `long` verbose formatting [false]
	 *
	 * @param {String|Number} val
	 * @param {Object} [options]
	 * @throws {Error} throw an error if val is not a non-empty string or a number
	 * @return {String|Number}
	 * @api public
	 */

	var ms = function(val, options) {
	  options = options || {};
	  var type = typeof val;
	  if (type === 'string' && val.length > 0) {
	    return parse$1(val);
	  } else if (type === 'number' && isFinite(val)) {
	    return options.long ? fmtLong(val) : fmtShort(val);
	  }
	  throw new Error(
	    'val is not a non-empty string or a valid number. val=' +
	      JSON.stringify(val)
	  );
	};

	/**
	 * Parse the given `str` and return milliseconds.
	 *
	 * @param {String} str
	 * @return {Number}
	 * @api private
	 */

	function parse$1(str) {
	  str = String(str);
	  if (str.length > 100) {
	    return;
	  }
	  var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
	    str
	  );
	  if (!match) {
	    return;
	  }
	  var n = parseFloat(match[1]);
	  var type = (match[2] || 'ms').toLowerCase();
	  switch (type) {
	    case 'years':
	    case 'year':
	    case 'yrs':
	    case 'yr':
	    case 'y':
	      return n * y;
	    case 'weeks':
	    case 'week':
	    case 'w':
	      return n * w;
	    case 'days':
	    case 'day':
	    case 'd':
	      return n * d;
	    case 'hours':
	    case 'hour':
	    case 'hrs':
	    case 'hr':
	    case 'h':
	      return n * h;
	    case 'minutes':
	    case 'minute':
	    case 'mins':
	    case 'min':
	    case 'm':
	      return n * m;
	    case 'seconds':
	    case 'second':
	    case 'secs':
	    case 'sec':
	    case 's':
	      return n * s;
	    case 'milliseconds':
	    case 'millisecond':
	    case 'msecs':
	    case 'msec':
	    case 'ms':
	      return n;
	    default:
	      return undefined;
	  }
	}

	/**
	 * Short format for `ms`.
	 *
	 * @param {Number} ms
	 * @return {String}
	 * @api private
	 */

	function fmtShort(ms) {
	  var msAbs = Math.abs(ms);
	  if (msAbs >= d) {
	    return Math.round(ms / d) + 'd';
	  }
	  if (msAbs >= h) {
	    return Math.round(ms / h) + 'h';
	  }
	  if (msAbs >= m) {
	    return Math.round(ms / m) + 'm';
	  }
	  if (msAbs >= s) {
	    return Math.round(ms / s) + 's';
	  }
	  return ms + 'ms';
	}

	/**
	 * Long format for `ms`.
	 *
	 * @param {Number} ms
	 * @return {String}
	 * @api private
	 */

	function fmtLong(ms) {
	  var msAbs = Math.abs(ms);
	  if (msAbs >= d) {
	    return plural(ms, msAbs, d, 'day');
	  }
	  if (msAbs >= h) {
	    return plural(ms, msAbs, h, 'hour');
	  }
	  if (msAbs >= m) {
	    return plural(ms, msAbs, m, 'minute');
	  }
	  if (msAbs >= s) {
	    return plural(ms, msAbs, s, 'second');
	  }
	  return ms + ' ms';
	}

	/**
	 * Pluralization helper.
	 */

	function plural(ms, msAbs, n, name) {
	  var isPlural = msAbs >= n * 1.5;
	  return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
	}

	/**
	 * This is the common logic for both the Node.js and web browser
	 * implementations of `debug()`.
	 */

	function setup(env) {
		createDebug.debug = createDebug;
		createDebug.default = createDebug;
		createDebug.coerce = coerce;
		createDebug.disable = disable;
		createDebug.enable = enable;
		createDebug.enabled = enabled;
		createDebug.humanize = ms;
		createDebug.destroy = destroy;

		Object.keys(env).forEach(key => {
			createDebug[key] = env[key];
		});

		/**
		* The currently active debug mode names, and names to skip.
		*/

		createDebug.names = [];
		createDebug.skips = [];

		/**
		* Map of special "%n" handling functions, for the debug "format" argument.
		*
		* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
		*/
		createDebug.formatters = {};

		/**
		* Selects a color for a debug namespace
		* @param {String} namespace The namespace string for the debug instance to be colored
		* @return {Number|String} An ANSI color code for the given namespace
		* @api private
		*/
		function selectColor(namespace) {
			let hash = 0;

			for (let i = 0; i < namespace.length; i++) {
				hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
				hash |= 0; // Convert to 32bit integer
			}

			return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
		}
		createDebug.selectColor = selectColor;

		/**
		* Create a debugger with the given `namespace`.
		*
		* @param {String} namespace
		* @return {Function}
		* @api public
		*/
		function createDebug(namespace) {
			let prevTime;
			let enableOverride = null;
			let namespacesCache;
			let enabledCache;

			function debug(...args) {
				// Disabled?
				if (!debug.enabled) {
					return;
				}

				const self = debug;

				// Set `diff` timestamp
				const curr = Number(new Date());
				const ms = curr - (prevTime || curr);
				self.diff = ms;
				self.prev = prevTime;
				self.curr = curr;
				prevTime = curr;

				args[0] = createDebug.coerce(args[0]);

				if (typeof args[0] !== 'string') {
					// Anything else let's inspect with %O
					args.unshift('%O');
				}

				// Apply any `formatters` transformations
				let index = 0;
				args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
					// If we encounter an escaped % then don't increase the array index
					if (match === '%%') {
						return '%';
					}
					index++;
					const formatter = createDebug.formatters[format];
					if (typeof formatter === 'function') {
						const val = args[index];
						match = formatter.call(self, val);

						// Now we need to remove `args[index]` since it's inlined in the `format`
						args.splice(index, 1);
						index--;
					}
					return match;
				});

				// Apply env-specific formatting (colors, etc.)
				createDebug.formatArgs.call(self, args);

				const logFn = self.log || createDebug.log;
				logFn.apply(self, args);
			}

			debug.namespace = namespace;
			debug.useColors = createDebug.useColors();
			debug.color = createDebug.selectColor(namespace);
			debug.extend = extend;
			debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.

			Object.defineProperty(debug, 'enabled', {
				enumerable: true,
				configurable: false,
				get: () => {
					if (enableOverride !== null) {
						return enableOverride;
					}
					if (namespacesCache !== createDebug.namespaces) {
						namespacesCache = createDebug.namespaces;
						enabledCache = createDebug.enabled(namespace);
					}

					return enabledCache;
				},
				set: v => {
					enableOverride = v;
				}
			});

			// Env-specific initialization logic for debug instances
			if (typeof createDebug.init === 'function') {
				createDebug.init(debug);
			}

			return debug;
		}

		function extend(namespace, delimiter) {
			const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
			newDebug.log = this.log;
			return newDebug;
		}

		/**
		* Enables a debug mode by namespaces. This can include modes
		* separated by a colon and wildcards.
		*
		* @param {String} namespaces
		* @api public
		*/
		function enable(namespaces) {
			createDebug.save(namespaces);
			createDebug.namespaces = namespaces;

			createDebug.names = [];
			createDebug.skips = [];

			let i;
			const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
			const len = split.length;

			for (i = 0; i < len; i++) {
				if (!split[i]) {
					// ignore empty strings
					continue;
				}

				namespaces = split[i].replace(/\*/g, '.*?');

				if (namespaces[0] === '-') {
					createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));
				} else {
					createDebug.names.push(new RegExp('^' + namespaces + '$'));
				}
			}
		}

		/**
		* Disable debug output.
		*
		* @return {String} namespaces
		* @api public
		*/
		function disable() {
			const namespaces = [
				...createDebug.names.map(toNamespace),
				...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
			].join(',');
			createDebug.enable('');
			return namespaces;
		}

		/**
		* Returns true if the given mode name is enabled, false otherwise.
		*
		* @param {String} name
		* @return {Boolean}
		* @api public
		*/
		function enabled(name) {
			if (name[name.length - 1] === '*') {
				return true;
			}

			let i;
			let len;

			for (i = 0, len = createDebug.skips.length; i < len; i++) {
				if (createDebug.skips[i].test(name)) {
					return false;
				}
			}

			for (i = 0, len = createDebug.names.length; i < len; i++) {
				if (createDebug.names[i].test(name)) {
					return true;
				}
			}

			return false;
		}

		/**
		* Convert regexp to namespace
		*
		* @param {RegExp} regxep
		* @return {String} namespace
		* @api private
		*/
		function toNamespace(regexp) {
			return regexp.toString()
				.substring(2, regexp.toString().length - 2)
				.replace(/\.\*\?$/, '*');
		}

		/**
		* Coerce `val`.
		*
		* @param {Mixed} val
		* @return {Mixed}
		* @api private
		*/
		function coerce(val) {
			if (val instanceof Error) {
				return val.stack || val.message;
			}
			return val;
		}

		/**
		* XXX DO NOT USE. This is a temporary stub function.
		* XXX It WILL be removed in the next major release.
		*/
		function destroy() {
			console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
		}

		createDebug.enable(createDebug.load());

		return createDebug;
	}

	var common = setup;

	var browser$1 = createCommonjsModule(function (module, exports) {
	/* eslint-env browser */

	/**
	 * This is the web browser implementation of `debug()`.
	 */

	exports.formatArgs = formatArgs;
	exports.save = save;
	exports.load = load;
	exports.useColors = useColors;
	exports.storage = localstorage();
	exports.destroy = (() => {
		let warned = false;

		return () => {
			if (!warned) {
				warned = true;
				console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
			}
		};
	})();

	/**
	 * Colors.
	 */

	exports.colors = [
		'#0000CC',
		'#0000FF',
		'#0033CC',
		'#0033FF',
		'#0066CC',
		'#0066FF',
		'#0099CC',
		'#0099FF',
		'#00CC00',
		'#00CC33',
		'#00CC66',
		'#00CC99',
		'#00CCCC',
		'#00CCFF',
		'#3300CC',
		'#3300FF',
		'#3333CC',
		'#3333FF',
		'#3366CC',
		'#3366FF',
		'#3399CC',
		'#3399FF',
		'#33CC00',
		'#33CC33',
		'#33CC66',
		'#33CC99',
		'#33CCCC',
		'#33CCFF',
		'#6600CC',
		'#6600FF',
		'#6633CC',
		'#6633FF',
		'#66CC00',
		'#66CC33',
		'#9900CC',
		'#9900FF',
		'#9933CC',
		'#9933FF',
		'#99CC00',
		'#99CC33',
		'#CC0000',
		'#CC0033',
		'#CC0066',
		'#CC0099',
		'#CC00CC',
		'#CC00FF',
		'#CC3300',
		'#CC3333',
		'#CC3366',
		'#CC3399',
		'#CC33CC',
		'#CC33FF',
		'#CC6600',
		'#CC6633',
		'#CC9900',
		'#CC9933',
		'#CCCC00',
		'#CCCC33',
		'#FF0000',
		'#FF0033',
		'#FF0066',
		'#FF0099',
		'#FF00CC',
		'#FF00FF',
		'#FF3300',
		'#FF3333',
		'#FF3366',
		'#FF3399',
		'#FF33CC',
		'#FF33FF',
		'#FF6600',
		'#FF6633',
		'#FF9900',
		'#FF9933',
		'#FFCC00',
		'#FFCC33'
	];

	/**
	 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
	 * and the Firebug extension (any Firefox version) are known
	 * to support "%c" CSS customizations.
	 *
	 * TODO: add a `localStorage` variable to explicitly enable/disable colors
	 */

	// eslint-disable-next-line complexity
	function useColors() {
		// NB: In an Electron preload script, document will be defined but not fully
		// initialized. Since we know we're in Chrome, we'll just detect this case
		// explicitly
		if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
			return true;
		}

		// Internet Explorer and Edge do not support colors.
		if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
			return false;
		}

		let m;

		// Is webkit? http://stackoverflow.com/a/16459606/376773
		// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
		return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
			// Is firebug? http://stackoverflow.com/a/398120/376773
			(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
			// Is firefox >= v31?
			// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
			(typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31) ||
			// Double check webkit in userAgent just in case we are in a worker
			(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
	}

	/**
	 * Colorize log arguments if enabled.
	 *
	 * @api public
	 */

	function formatArgs(args) {
		args[0] = (this.useColors ? '%c' : '') +
			this.namespace +
			(this.useColors ? ' %c' : ' ') +
			args[0] +
			(this.useColors ? '%c ' : ' ') +
			'+' + module.exports.humanize(this.diff);

		if (!this.useColors) {
			return;
		}

		const c = 'color: ' + this.color;
		args.splice(1, 0, c, 'color: inherit');

		// The final "%c" is somewhat tricky, because there could be other
		// arguments passed either before or after the %c, so we need to
		// figure out the correct index to insert the CSS into
		let index = 0;
		let lastC = 0;
		args[0].replace(/%[a-zA-Z%]/g, match => {
			if (match === '%%') {
				return;
			}
			index++;
			if (match === '%c') {
				// We only are interested in the *last* %c
				// (the user may have provided their own)
				lastC = index;
			}
		});

		args.splice(lastC, 0, c);
	}

	/**
	 * Invokes `console.debug()` when available.
	 * No-op when `console.debug` is not a "function".
	 * If `console.debug` is not available, falls back
	 * to `console.log`.
	 *
	 * @api public
	 */
	exports.log = console.debug || console.log || (() => {});

	/**
	 * Save `namespaces`.
	 *
	 * @param {String} namespaces
	 * @api private
	 */
	function save(namespaces) {
		try {
			if (namespaces) {
				exports.storage.setItem('debug', namespaces);
			} else {
				exports.storage.removeItem('debug');
			}
		} catch (error) {
			// Swallow
			// XXX (@Qix-) should we be logging these?
		}
	}

	/**
	 * Load `namespaces`.
	 *
	 * @return {String} returns the previously persisted debug modes
	 * @api private
	 */
	function load() {
		let r;
		try {
			r = exports.storage.getItem('debug');
		} catch (error) {
			// Swallow
			// XXX (@Qix-) should we be logging these?
		}

		// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
		if (!r && typeof process !== 'undefined' && 'env' in process) {
			r = process.env.DEBUG;
		}

		return r;
	}

	/**
	 * Localstorage attempts to return the localstorage.
	 *
	 * This is necessary because safari throws
	 * when a user disables cookies/localstorage
	 * and you attempt to access it.
	 *
	 * @return {LocalStorage}
	 * @api private
	 */

	function localstorage() {
		try {
			// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
			// The Browser also has localStorage in the global context.
			return localStorage;
		} catch (error) {
			// Swallow
			// XXX (@Qix-) should we be logging these?
		}
	}

	module.exports = common(exports);

	const {formatters} = module.exports;

	/**
	 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
	 */

	formatters.j = function (v) {
		try {
			return JSON.stringify(v);
		} catch (error) {
			return '[UnexpectedJSONParseError]: ' + error.message;
		}
	};
	});
	browser$1.formatArgs;
	browser$1.save;
	browser$1.load;
	browser$1.useColors;
	browser$1.storage;
	browser$1.destroy;
	browser$1.colors;
	browser$1.log;

	var helpers = createCommonjsModule(function (module, exports) {
	var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
	    if (k2 === undefined) k2 = k;
	    var desc = Object.getOwnPropertyDescriptor(m, k);
	    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
	      desc = { enumerable: true, get: function() { return m[k]; } };
	    }
	    Object.defineProperty(o, k2, desc);
	}) : (function(o, m, k, k2) {
	    if (k2 === undefined) k2 = k;
	    o[k2] = m[k];
	}));
	var __setModuleDefault = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
	    Object.defineProperty(o, "default", { enumerable: true, value: v });
	}) : function(o, v) {
	    o["default"] = v;
	});
	var __importStar = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
	    if (mod && mod.__esModule) return mod;
	    var result = {};
	    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
	    __setModuleDefault(result, mod);
	    return result;
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.req = exports.json = exports.toBuffer = void 0;
	const http = __importStar(http__default["default"]);
	const https = __importStar(https__default["default"]);
	async function toBuffer(stream) {
	    let length = 0;
	    const chunks = [];
	    for await (const chunk of stream) {
	        length += chunk.length;
	        chunks.push(chunk);
	    }
	    return Buffer.concat(chunks, length);
	}
	exports.toBuffer = toBuffer;
	// eslint-disable-next-line @typescript-eslint/no-explicit-any
	async function json(stream) {
	    const buf = await toBuffer(stream);
	    const str = buf.toString('utf8');
	    try {
	        return JSON.parse(str);
	    }
	    catch (_err) {
	        const err = _err;
	        err.message += ` (input: ${str})`;
	        throw err;
	    }
	}
	exports.json = json;
	function req(url, opts = {}) {
	    const href = typeof url === 'string' ? url : url.href;
	    const req = (href.startsWith('https:') ? https : http).request(url, opts);
	    const promise = new Promise((resolve, reject) => {
	        req
	            .once('response', resolve)
	            .once('error', reject)
	            .end();
	    });
	    req.then = promise.then.bind(promise);
	    return req;
	}
	exports.req = req;

	});

	unwrapExports(helpers);
	helpers.req;
	helpers.json;
	helpers.toBuffer;

	var dist$2 = createCommonjsModule(function (module, exports) {
	var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
	    if (k2 === undefined) k2 = k;
	    var desc = Object.getOwnPropertyDescriptor(m, k);
	    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
	      desc = { enumerable: true, get: function() { return m[k]; } };
	    }
	    Object.defineProperty(o, k2, desc);
	}) : (function(o, m, k, k2) {
	    if (k2 === undefined) k2 = k;
	    o[k2] = m[k];
	}));
	var __setModuleDefault = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
	    Object.defineProperty(o, "default", { enumerable: true, value: v });
	}) : function(o, v) {
	    o["default"] = v;
	});
	var __importStar = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
	    if (mod && mod.__esModule) return mod;
	    var result = {};
	    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
	    __setModuleDefault(result, mod);
	    return result;
	};
	var __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m, exports) {
	    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.Agent = void 0;
	const net = __importStar(net__default["default"]);
	const http = __importStar(http__default["default"]);

	__exportStar(helpers, exports);
	const INTERNAL = Symbol('AgentBaseInternalState');
	class Agent extends http.Agent {
	    constructor(opts) {
	        super(opts);
	        this[INTERNAL] = {};
	    }
	    /**
	     * Determine whether this is an `http` or `https` request.
	     */
	    isSecureEndpoint(options) {
	        if (options) {
	            // First check the `secureEndpoint` property explicitly, since this
	            // means that a parent `Agent` is "passing through" to this instance.
	            // eslint-disable-next-line @typescript-eslint/no-explicit-any
	            if (typeof options.secureEndpoint === 'boolean') {
	                return options.secureEndpoint;
	            }
	            // If no explicit `secure` endpoint, check if `protocol` property is
	            // set. This will usually be the case since using a full string URL
	            // or `URL` instance should be the most common usage.
	            if (typeof options.protocol === 'string') {
	                return options.protocol === 'https:';
	            }
	        }
	        // Finally, if no `protocol` property was set, then fall back to
	        // checking the stack trace of the current call stack, and try to
	        // detect the "https" module.
	        const { stack } = new Error();
	        if (typeof stack !== 'string')
	            return false;
	        return stack
	            .split('\n')
	            .some((l) => l.indexOf('(https.js:') !== -1 ||
	            l.indexOf('node:https:') !== -1);
	    }
	    // In order to support async signatures in `connect()` and Node's native
	    // connection pooling in `http.Agent`, the array of sockets for each origin
	    // has to be updated synchronously. This is so the length of the array is
	    // accurate when `addRequest()` is next called. We achieve this by creating a
	    // fake socket and adding it to `sockets[origin]` and incrementing
	    // `totalSocketCount`.
	    incrementSockets(name) {
	        // If `maxSockets` and `maxTotalSockets` are both Infinity then there is no
	        // need to create a fake socket because Node.js native connection pooling
	        // will never be invoked.
	        if (this.maxSockets === Infinity && this.maxTotalSockets === Infinity) {
	            return null;
	        }
	        // All instances of `sockets` are expected TypeScript errors. The
	        // alternative is to add it as a private property of this class but that
	        // will break TypeScript subclassing.
	        if (!this.sockets[name]) {
	            // @ts-expect-error `sockets` is readonly in `@types/node`
	            this.sockets[name] = [];
	        }
	        const fakeSocket = new net.Socket({ writable: false });
	        this.sockets[name].push(fakeSocket);
	        // @ts-expect-error `totalSocketCount` isn't defined in `@types/node`
	        this.totalSocketCount++;
	        return fakeSocket;
	    }
	    decrementSockets(name, socket) {
	        if (!this.sockets[name] || socket === null) {
	            return;
	        }
	        const sockets = this.sockets[name];
	        const index = sockets.indexOf(socket);
	        if (index !== -1) {
	            sockets.splice(index, 1);
	            // @ts-expect-error  `totalSocketCount` isn't defined in `@types/node`
	            this.totalSocketCount--;
	            if (sockets.length === 0) {
	                // @ts-expect-error `sockets` is readonly in `@types/node`
	                delete this.sockets[name];
	            }
	        }
	    }
	    // In order to properly update the socket pool, we need to call `getName()` on
	    // the core `https.Agent` if it is a secureEndpoint.
	    getName(options) {
	        const secureEndpoint = typeof options.secureEndpoint === 'boolean'
	            ? options.secureEndpoint
	            : this.isSecureEndpoint(options);
	        if (secureEndpoint) {
	            // @ts-expect-error `getName()` isn't defined in `@types/node`
	            return https__default["default"].Agent.prototype.getName.call(this, options);
	        }
	        // @ts-expect-error `getName()` isn't defined in `@types/node`
	        return super.getName(options);
	    }
	    createSocket(req, options, cb) {
	        const connectOpts = {
	            ...options,
	            secureEndpoint: this.isSecureEndpoint(options),
	        };
	        const name = this.getName(connectOpts);
	        const fakeSocket = this.incrementSockets(name);
	        Promise.resolve()
	            .then(() => this.connect(req, connectOpts))
	            .then((socket) => {
	            this.decrementSockets(name, fakeSocket);
	            if (socket instanceof http.Agent) {
	                // @ts-expect-error `addRequest()` isn't defined in `@types/node`
	                return socket.addRequest(req, connectOpts);
	            }
	            this[INTERNAL].currentSocket = socket;
	            // @ts-expect-error `createSocket()` isn't defined in `@types/node`
	            super.createSocket(req, options, cb);
	        }, (err) => {
	            this.decrementSockets(name, fakeSocket);
	            cb(err);
	        });
	    }
	    createConnection() {
	        const socket = this[INTERNAL].currentSocket;
	        this[INTERNAL].currentSocket = undefined;
	        if (!socket) {
	            throw new Error('No socket was returned in the `connect()` function');
	        }
	        return socket;
	    }
	    get defaultPort() {
	        return (this[INTERNAL].defaultPort ??
	            (this.protocol === 'https:' ? 443 : 80));
	    }
	    set defaultPort(v) {
	        if (this[INTERNAL]) {
	            this[INTERNAL].defaultPort = v;
	        }
	    }
	    get protocol() {
	        return (this[INTERNAL].protocol ??
	            (this.isSecureEndpoint() ? 'https:' : 'http:'));
	    }
	    set protocol(v) {
	        if (this[INTERNAL]) {
	            this[INTERNAL].protocol = v;
	        }
	    }
	}
	exports.Agent = Agent;

	});

	unwrapExports(dist$2);
	dist$2.Agent;

	var parseProxyResponse_1 = createCommonjsModule(function (module, exports) {
	var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
	    return (mod && mod.__esModule) ? mod : { "default": mod };
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.parseProxyResponse = void 0;
	const debug_1 = __importDefault(browser$1);
	const debug = (0, debug_1.default)('https-proxy-agent:parse-proxy-response');
	function parseProxyResponse(socket) {
	    return new Promise((resolve, reject) => {
	        // we need to buffer any HTTP traffic that happens with the proxy before we get
	        // the CONNECT response, so that if the response is anything other than an "200"
	        // response code, then we can re-play the "data" events on the socket once the
	        // HTTP parser is hooked up...
	        let buffersLength = 0;
	        const buffers = [];
	        function read() {
	            const b = socket.read();
	            if (b)
	                ondata(b);
	            else
	                socket.once('readable', read);
	        }
	        function cleanup() {
	            socket.removeListener('end', onend);
	            socket.removeListener('error', onerror);
	            socket.removeListener('readable', read);
	        }
	        function onend() {
	            cleanup();
	            debug('onend');
	            reject(new Error('Proxy connection ended before receiving CONNECT response'));
	        }
	        function onerror(err) {
	            cleanup();
	            debug('onerror %o', err);
	            reject(err);
	        }
	        function ondata(b) {
	            buffers.push(b);
	            buffersLength += b.length;
	            const buffered = Buffer.concat(buffers, buffersLength);
	            const endOfHeaders = buffered.indexOf('\r\n\r\n');
	            if (endOfHeaders === -1) {
	                // keep buffering
	                debug('have not received end of HTTP headers yet...');
	                read();
	                return;
	            }
	            const headerParts = buffered
	                .slice(0, endOfHeaders)
	                .toString('ascii')
	                .split('\r\n');
	            const firstLine = headerParts.shift();
	            if (!firstLine) {
	                socket.destroy();
	                return reject(new Error('No header received from proxy CONNECT response'));
	            }
	            const firstLineParts = firstLine.split(' ');
	            const statusCode = +firstLineParts[1];
	            const statusText = firstLineParts.slice(2).join(' ');
	            const headers = {};
	            for (const header of headerParts) {
	                if (!header)
	                    continue;
	                const firstColon = header.indexOf(':');
	                if (firstColon === -1) {
	                    socket.destroy();
	                    return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`));
	                }
	                const key = header.slice(0, firstColon).toLowerCase();
	                const value = header.slice(firstColon + 1).trimStart();
	                const current = headers[key];
	                if (typeof current === 'string') {
	                    headers[key] = [current, value];
	                }
	                else if (Array.isArray(current)) {
	                    current.push(value);
	                }
	                else {
	                    headers[key] = value;
	                }
	            }
	            debug('got proxy server response: %o %o', firstLine, headers);
	            cleanup();
	            resolve({
	                connect: {
	                    statusCode,
	                    statusText,
	                    headers,
	                },
	                buffered,
	            });
	        }
	        socket.on('error', onerror);
	        socket.on('end', onend);
	        read();
	    });
	}
	exports.parseProxyResponse = parseProxyResponse;

	});

	unwrapExports(parseProxyResponse_1);
	parseProxyResponse_1.parseProxyResponse;

	var dist$1 = createCommonjsModule(function (module, exports) {
	var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
	    if (k2 === undefined) k2 = k;
	    var desc = Object.getOwnPropertyDescriptor(m, k);
	    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
	      desc = { enumerable: true, get: function() { return m[k]; } };
	    }
	    Object.defineProperty(o, k2, desc);
	}) : (function(o, m, k, k2) {
	    if (k2 === undefined) k2 = k;
	    o[k2] = m[k];
	}));
	var __setModuleDefault = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
	    Object.defineProperty(o, "default", { enumerable: true, value: v });
	}) : function(o, v) {
	    o["default"] = v;
	});
	var __importStar = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
	    if (mod && mod.__esModule) return mod;
	    var result = {};
	    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
	    __setModuleDefault(result, mod);
	    return result;
	};
	var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
	    return (mod && mod.__esModule) ? mod : { "default": mod };
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.HttpsProxyAgent = void 0;
	const net = __importStar(net__default["default"]);
	const tls = __importStar(tls__default["default"]);
	const assert_1 = __importDefault(assert__default["default"]);
	const debug_1 = __importDefault(browser$1);



	const debug = (0, debug_1.default)('https-proxy-agent');
	/**
	 * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to
	 * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests.
	 *
	 * Outgoing HTTP requests are first tunneled through the proxy server using the
	 * `CONNECT` HTTP request method to establish a connection to the proxy server,
	 * and then the proxy server connects to the destination target and issues the
	 * HTTP request from the proxy server.
	 *
	 * `https:` requests have their socket connection upgraded to TLS once
	 * the connection to the proxy server has been established.
	 */
	class HttpsProxyAgent extends dist$2.Agent {
	    constructor(proxy, opts) {
	        super(opts);
	        this.options = { path: undefined };
	        this.proxy = typeof proxy === 'string' ? new url__default["default"].URL(proxy) : proxy;
	        this.proxyHeaders = opts?.headers ?? {};
	        debug('Creating new HttpsProxyAgent instance: %o', this.proxy.href);
	        // Trim off the brackets from IPv6 addresses
	        const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, '');
	        const port = this.proxy.port
	            ? parseInt(this.proxy.port, 10)
	            : this.proxy.protocol === 'https:'
	                ? 443
	                : 80;
	        this.connectOpts = {
	            // Attempt to negotiate http/1.1 for proxy servers that support http/2
	            ALPNProtocols: ['http/1.1'],
	            ...(opts ? omit(opts, 'headers') : null),
	            host,
	            port,
	        };
	    }
	    /**
	     * Called when the node-core HTTP client library is creating a
	     * new HTTP request.
	     */
	    async connect(req, opts) {
	        const { proxy } = this;
	        if (!opts.host) {
	            throw new TypeError('No "host" provided');
	        }
	        // Create a socket connection to the proxy server.
	        let socket;
	        if (proxy.protocol === 'https:') {
	            debug('Creating `tls.Socket`: %o', this.connectOpts);
	            const servername = this.connectOpts.servername || this.connectOpts.host;
	            socket = tls.connect({
	                ...this.connectOpts,
	                servername,
	            });
	        }
	        else {
	            debug('Creating `net.Socket`: %o', this.connectOpts);
	            socket = net.connect(this.connectOpts);
	        }
	        const headers = typeof this.proxyHeaders === 'function'
	            ? this.proxyHeaders()
	            : { ...this.proxyHeaders };
	        const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host;
	        let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r\n`;
	        // Inject the `Proxy-Authorization` header if necessary.
	        if (proxy.username || proxy.password) {
	            const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;
	            headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`;
	        }
	        headers.Host = `${host}:${opts.port}`;
	        if (!headers['Proxy-Connection']) {
	            headers['Proxy-Connection'] = this.keepAlive
	                ? 'Keep-Alive'
	                : 'close';
	        }
	        for (const name of Object.keys(headers)) {
	            payload += `${name}: ${headers[name]}\r\n`;
	        }
	        const proxyResponsePromise = (0, parseProxyResponse_1.parseProxyResponse)(socket);
	        socket.write(`${payload}\r\n`);
	        const { connect, buffered } = await proxyResponsePromise;
	        req.emit('proxyConnect', connect);
	        this.emit('proxyConnect', connect, req);
	        if (connect.statusCode === 200) {
	            req.once('socket', resume);
	            if (opts.secureEndpoint) {
	                // The proxy is connecting to a TLS server, so upgrade
	                // this socket connection to a TLS connection.
	                debug('Upgrading socket connection to TLS');
	                const servername = opts.servername || opts.host;
	                return tls.connect({
	                    ...omit(opts, 'host', 'path', 'port'),
	                    socket,
	                    servername,
	                });
	            }
	            return socket;
	        }
	        // Some other status code that's not 200... need to re-play the HTTP
	        // header "data" events onto the socket once the HTTP machinery is
	        // attached so that the node core `http` can parse and handle the
	        // error status code.
	        // Close the original socket, and a new "fake" socket is returned
	        // instead, so that the proxy doesn't get the HTTP request
	        // written to it (which may contain `Authorization` headers or other
	        // sensitive data).
	        //
	        // See: https://hackerone.com/reports/541502
	        socket.destroy();
	        const fakeSocket = new net.Socket({ writable: false });
	        fakeSocket.readable = true;
	        // Need to wait for the "socket" event to re-play the "data" events.
	        req.once('socket', (s) => {
	            debug('Replaying proxy buffer for failed request');
	            (0, assert_1.default)(s.listenerCount('data') > 0);
	            // Replay the "buffered" Buffer onto the fake `socket`, since at
	            // this point the HTTP module machinery has been hooked up for
	            // the user.
	            s.push(buffered);
	            s.push(null);
	        });
	        return fakeSocket;
	    }
	}
	HttpsProxyAgent.protocols = ['http', 'https'];
	exports.HttpsProxyAgent = HttpsProxyAgent;
	function resume(socket) {
	    socket.resume();
	}
	function omit(obj, ...keys) {
	    const ret = {};
	    let key;
	    for (key in obj) {
	        if (!keys.includes(key)) {
	            ret[key] = obj[key];
	        }
	    }
	    return ret;
	}

	});

	unwrapExports(dist$1);
	var dist_1$1 = dist$1.HttpsProxyAgent;

	// Copyright Joyent, Inc. and other Node contributors.

	var R = typeof Reflect === 'object' ? Reflect : null;
	var ReflectApply = R && typeof R.apply === 'function'
	  ? R.apply
	  : function ReflectApply(target, receiver, args) {
	    return Function.prototype.apply.call(target, receiver, args);
	  };

	var ReflectOwnKeys;
	if (R && typeof R.ownKeys === 'function') {
	  ReflectOwnKeys = R.ownKeys;
	} else if (Object.getOwnPropertySymbols) {
	  ReflectOwnKeys = function ReflectOwnKeys(target) {
	    return Object.getOwnPropertyNames(target)
	      .concat(Object.getOwnPropertySymbols(target));
	  };
	} else {
	  ReflectOwnKeys = function ReflectOwnKeys(target) {
	    return Object.getOwnPropertyNames(target);
	  };
	}

	function ProcessEmitWarning(warning) {
	  if (console && console.warn) console.warn(warning);
	}

	var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
	  return value !== value;
	};

	function EventEmitter() {
	  EventEmitter.init.call(this);
	}
	var events = EventEmitter;
	var once_1 = once;

	// Backwards-compat with node 0.10.x
	EventEmitter.EventEmitter = EventEmitter;

	EventEmitter.prototype._events = undefined;
	EventEmitter.prototype._eventsCount = 0;
	EventEmitter.prototype._maxListeners = undefined;

	// By default EventEmitters will print a warning if more than 10 listeners are
	// added to it. This is a useful default which helps finding memory leaks.
	var defaultMaxListeners = 10;

	function checkListener(listener) {
	  if (typeof listener !== 'function') {
	    throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
	  }
	}

	Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
	  enumerable: true,
	  get: function() {
	    return defaultMaxListeners;
	  },
	  set: function(arg) {
	    if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
	      throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
	    }
	    defaultMaxListeners = arg;
	  }
	});

	EventEmitter.init = function() {

	  if (this._events === undefined ||
	      this._events === Object.getPrototypeOf(this)._events) {
	    this._events = Object.create(null);
	    this._eventsCount = 0;
	  }

	  this._maxListeners = this._maxListeners || undefined;
	};

	// Obviously not all Emitters should be limited to 10. This function allows
	// that to be increased. Set to zero for unlimited.
	EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
	  if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
	    throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
	  }
	  this._maxListeners = n;
	  return this;
	};

	function _getMaxListeners(that) {
	  if (that._maxListeners === undefined)
	    return EventEmitter.defaultMaxListeners;
	  return that._maxListeners;
	}

	EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
	  return _getMaxListeners(this);
	};

	EventEmitter.prototype.emit = function emit(type) {
	  var args = [];
	  for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
	  var doError = (type === 'error');

	  var events = this._events;
	  if (events !== undefined)
	    doError = (doError && events.error === undefined);
	  else if (!doError)
	    return false;

	  // If there is no 'error' event listener then throw.
	  if (doError) {
	    var er;
	    if (args.length > 0)
	      er = args[0];
	    if (er instanceof Error) {
	      // Note: The comments on the `throw` lines are intentional, they show
	      // up in Node's output if this results in an unhandled exception.
	      throw er; // Unhandled 'error' event
	    }
	    // At least give some kind of context to the user
	    var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
	    err.context = er;
	    throw err; // Unhandled 'error' event
	  }

	  var handler = events[type];

	  if (handler === undefined)
	    return false;

	  if (typeof handler === 'function') {
	    ReflectApply(handler, this, args);
	  } else {
	    var len = handler.length;
	    var listeners = arrayClone(handler, len);
	    for (var i = 0; i < len; ++i)
	      ReflectApply(listeners[i], this, args);
	  }

	  return true;
	};

	function _addListener(target, type, listener, prepend) {
	  var m;
	  var events;
	  var existing;

	  checkListener(listener);

	  events = target._events;
	  if (events === undefined) {
	    events = target._events = Object.create(null);
	    target._eventsCount = 0;
	  } else {
	    // To avoid recursion in the case that type === "newListener"! Before
	    // adding it to the listeners, first emit "newListener".
	    if (events.newListener !== undefined) {
	      target.emit('newListener', type,
	                  listener.listener ? listener.listener : listener);

	      // Re-assign `events` because a newListener handler could have caused the
	      // this._events to be assigned to a new object
	      events = target._events;
	    }
	    existing = events[type];
	  }

	  if (existing === undefined) {
	    // Optimize the case of one listener. Don't need the extra array object.
	    existing = events[type] = listener;
	    ++target._eventsCount;
	  } else {
	    if (typeof existing === 'function') {
	      // Adding the second element, need to change to array.
	      existing = events[type] =
	        prepend ? [listener, existing] : [existing, listener];
	      // If we've already got an array, just append.
	    } else if (prepend) {
	      existing.unshift(listener);
	    } else {
	      existing.push(listener);
	    }

	    // Check for listener leak
	    m = _getMaxListeners(target);
	    if (m > 0 && existing.length > m && !existing.warned) {
	      existing.warned = true;
	      // No error code for this since it is a Warning
	      // eslint-disable-next-line no-restricted-syntax
	      var w = new Error('Possible EventEmitter memory leak detected. ' +
	                          existing.length + ' ' + String(type) + ' listeners ' +
	                          'added. Use emitter.setMaxListeners() to ' +
	                          'increase limit');
	      w.name = 'MaxListenersExceededWarning';
	      w.emitter = target;
	      w.type = type;
	      w.count = existing.length;
	      ProcessEmitWarning(w);
	    }
	  }

	  return target;
	}

	EventEmitter.prototype.addListener = function addListener(type, listener) {
	  return _addListener(this, type, listener, false);
	};

	EventEmitter.prototype.on = EventEmitter.prototype.addListener;

	EventEmitter.prototype.prependListener =
	    function prependListener(type, listener) {
	      return _addListener(this, type, listener, true);
	    };

	function onceWrapper() {
	  if (!this.fired) {
	    this.target.removeListener(this.type, this.wrapFn);
	    this.fired = true;
	    if (arguments.length === 0)
	      return this.listener.call(this.target);
	    return this.listener.apply(this.target, arguments);
	  }
	}

	function _onceWrap(target, type, listener) {
	  var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
	  var wrapped = onceWrapper.bind(state);
	  wrapped.listener = listener;
	  state.wrapFn = wrapped;
	  return wrapped;
	}

	EventEmitter.prototype.once = function once(type, listener) {
	  checkListener(listener);
	  this.on(type, _onceWrap(this, type, listener));
	  return this;
	};

	EventEmitter.prototype.prependOnceListener =
	    function prependOnceListener(type, listener) {
	      checkListener(listener);
	      this.prependListener(type, _onceWrap(this, type, listener));
	      return this;
	    };

	// Emits a 'removeListener' event if and only if the listener was removed.
	EventEmitter.prototype.removeListener =
	    function removeListener(type, listener) {
	      var list, events, position, i, originalListener;

	      checkListener(listener);

	      events = this._events;
	      if (events === undefined)
	        return this;

	      list = events[type];
	      if (list === undefined)
	        return this;

	      if (list === listener || list.listener === listener) {
	        if (--this._eventsCount === 0)
	          this._events = Object.create(null);
	        else {
	          delete events[type];
	          if (events.removeListener)
	            this.emit('removeListener', type, list.listener || listener);
	        }
	      } else if (typeof list !== 'function') {
	        position = -1;

	        for (i = list.length - 1; i >= 0; i--) {
	          if (list[i] === listener || list[i].listener === listener) {
	            originalListener = list[i].listener;
	            position = i;
	            break;
	          }
	        }

	        if (position < 0)
	          return this;

	        if (position === 0)
	          list.shift();
	        else {
	          spliceOne(list, position);
	        }

	        if (list.length === 1)
	          events[type] = list[0];

	        if (events.removeListener !== undefined)
	          this.emit('removeListener', type, originalListener || listener);
	      }

	      return this;
	    };

	EventEmitter.prototype.off = EventEmitter.prototype.removeListener;

	EventEmitter.prototype.removeAllListeners =
	    function removeAllListeners(type) {
	      var listeners, events, i;

	      events = this._events;
	      if (events === undefined)
	        return this;

	      // not listening for removeListener, no need to emit
	      if (events.removeListener === undefined) {
	        if (arguments.length === 0) {
	          this._events = Object.create(null);
	          this._eventsCount = 0;
	        } else if (events[type] !== undefined) {
	          if (--this._eventsCount === 0)
	            this._events = Object.create(null);
	          else
	            delete events[type];
	        }
	        return this;
	      }

	      // emit removeListener for all listeners on all events
	      if (arguments.length === 0) {
	        var keys = Object.keys(events);
	        var key;
	        for (i = 0; i < keys.length; ++i) {
	          key = keys[i];
	          if (key === 'removeListener') continue;
	          this.removeAllListeners(key);
	        }
	        this.removeAllListeners('removeListener');
	        this._events = Object.create(null);
	        this._eventsCount = 0;
	        return this;
	      }

	      listeners = events[type];

	      if (typeof listeners === 'function') {
	        this.removeListener(type, listeners);
	      } else if (listeners !== undefined) {
	        // LIFO order
	        for (i = listeners.length - 1; i >= 0; i--) {
	          this.removeListener(type, listeners[i]);
	        }
	      }

	      return this;
	    };

	function _listeners(target, type, unwrap) {
	  var events = target._events;

	  if (events === undefined)
	    return [];

	  var evlistener = events[type];
	  if (evlistener === undefined)
	    return [];

	  if (typeof evlistener === 'function')
	    return unwrap ? [evlistener.listener || evlistener] : [evlistener];

	  return unwrap ?
	    unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
	}

	EventEmitter.prototype.listeners = function listeners(type) {
	  return _listeners(this, type, true);
	};

	EventEmitter.prototype.rawListeners = function rawListeners(type) {
	  return _listeners(this, type, false);
	};

	EventEmitter.listenerCount = function(emitter, type) {
	  if (typeof emitter.listenerCount === 'function') {
	    return emitter.listenerCount(type);
	  } else {
	    return listenerCount.call(emitter, type);
	  }
	};

	EventEmitter.prototype.listenerCount = listenerCount;
	function listenerCount(type) {
	  var events = this._events;

	  if (events !== undefined) {
	    var evlistener = events[type];

	    if (typeof evlistener === 'function') {
	      return 1;
	    } else if (evlistener !== undefined) {
	      return evlistener.length;
	    }
	  }

	  return 0;
	}

	EventEmitter.prototype.eventNames = function eventNames() {
	  return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
	};

	function arrayClone(arr, n) {
	  var copy = new Array(n);
	  for (var i = 0; i < n; ++i)
	    copy[i] = arr[i];
	  return copy;
	}

	function spliceOne(list, index) {
	  for (; index + 1 < list.length; index++)
	    list[index] = list[index + 1];
	  list.pop();
	}

	function unwrapListeners(arr) {
	  var ret = new Array(arr.length);
	  for (var i = 0; i < ret.length; ++i) {
	    ret[i] = arr[i].listener || arr[i];
	  }
	  return ret;
	}

	function once(emitter, name) {
	  return new Promise(function (resolve, reject) {
	    function errorListener(err) {
	      emitter.removeListener(name, resolver);
	      reject(err);
	    }

	    function resolver() {
	      if (typeof emitter.removeListener === 'function') {
	        emitter.removeListener('error', errorListener);
	      }
	      resolve([].slice.call(arguments));
	    }
	    eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });
	    if (name !== 'error') {
	      addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });
	    }
	  });
	}

	function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
	  if (typeof emitter.on === 'function') {
	    eventTargetAgnosticAddListener(emitter, 'error', handler, flags);
	  }
	}

	function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
	  if (typeof emitter.on === 'function') {
	    if (flags.once) {
	      emitter.once(name, listener);
	    } else {
	      emitter.on(name, listener);
	    }
	  } else if (typeof emitter.addEventListener === 'function') {
	    // EventTarget does not have `error` event semantics like Node
	    // EventEmitters, we do not listen for `error` events here.
	    emitter.addEventListener(name, function wrapListener(arg) {
	      // IE does not have builtin `{ once: true }` support so we
	      // have to do it manually.
	      if (flags.once) {
	        emitter.removeEventListener(name, wrapListener);
	      }
	      listener(arg);
	    });
	  } else {
	    throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter);
	  }
	}
	events.EventEmitter;
	events.once = once_1;

	var dist = createCommonjsModule(function (module, exports) {
	var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
	    if (k2 === undefined) k2 = k;
	    var desc = Object.getOwnPropertyDescriptor(m, k);
	    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
	      desc = { enumerable: true, get: function() { return m[k]; } };
	    }
	    Object.defineProperty(o, k2, desc);
	}) : (function(o, m, k, k2) {
	    if (k2 === undefined) k2 = k;
	    o[k2] = m[k];
	}));
	var __setModuleDefault = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
	    Object.defineProperty(o, "default", { enumerable: true, value: v });
	}) : function(o, v) {
	    o["default"] = v;
	});
	var __importStar = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
	    if (mod && mod.__esModule) return mod;
	    var result = {};
	    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
	    __setModuleDefault(result, mod);
	    return result;
	};
	var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
	    return (mod && mod.__esModule) ? mod : { "default": mod };
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.HttpProxyAgent = void 0;
	const net = __importStar(net__default["default"]);
	const tls = __importStar(tls__default["default"]);
	const debug_1 = __importDefault(browser$1);



	const debug = (0, debug_1.default)('http-proxy-agent');
	/**
	 * The `HttpProxyAgent` implements an HTTP Agent subclass that connects
	 * to the specified "HTTP proxy server" in order to proxy HTTP requests.
	 */
	class HttpProxyAgent extends dist$2.Agent {
	    constructor(proxy, opts) {
	        super(opts);
	        this.proxy = typeof proxy === 'string' ? new url__default["default"].URL(proxy) : proxy;
	        this.proxyHeaders = opts?.headers ?? {};
	        debug('Creating new HttpProxyAgent instance: %o', this.proxy.href);
	        // Trim off the brackets from IPv6 addresses
	        const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, '');
	        const port = this.proxy.port
	            ? parseInt(this.proxy.port, 10)
	            : this.proxy.protocol === 'https:'
	                ? 443
	                : 80;
	        this.connectOpts = {
	            ...(opts ? omit(opts, 'headers') : null),
	            host,
	            port,
	        };
	    }
	    addRequest(req, opts) {
	        req._header = null;
	        this.setRequestProps(req, opts);
	        // @ts-expect-error `addRequest()` isn't defined in `@types/node`
	        super.addRequest(req, opts);
	    }
	    setRequestProps(req, opts) {
	        const { proxy } = this;
	        const protocol = opts.secureEndpoint ? 'https:' : 'http:';
	        const hostname = req.getHeader('host') || 'localhost';
	        const base = `${protocol}//${hostname}`;
	        const url = new url__default["default"].URL(req.path, base);
	        if (opts.port !== 80) {
	            url.port = String(opts.port);
	        }
	        // Change the `http.ClientRequest` instance's "path" field
	        // to the absolute path of the URL that will be requested.
	        req.path = String(url);
	        // Inject the `Proxy-Authorization` header if necessary.
	        const headers = typeof this.proxyHeaders === 'function'
	            ? this.proxyHeaders()
	            : { ...this.proxyHeaders };
	        if (proxy.username || proxy.password) {
	            const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;
	            headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`;
	        }
	        if (!headers['Proxy-Connection']) {
	            headers['Proxy-Connection'] = this.keepAlive
	                ? 'Keep-Alive'
	                : 'close';
	        }
	        for (const name of Object.keys(headers)) {
	            const value = headers[name];
	            if (value) {
	                req.setHeader(name, value);
	            }
	        }
	    }
	    async connect(req, opts) {
	        req._header = null;
	        if (!req.path.includes('://')) {
	            this.setRequestProps(req, opts);
	        }
	        // At this point, the http ClientRequest's internal `_header` field
	        // might have already been set. If this is the case then we'll need
	        // to re-generate the string since we just changed the `req.path`.
	        let first;
	        let endOfHeaders;
	        debug('Regenerating stored HTTP header string for request');
	        req._implicitHeader();
	        if (req.outputData && req.outputData.length > 0) {
	            debug('Patching connection write() output buffer with updated header');
	            first = req.outputData[0].data;
	            endOfHeaders = first.indexOf('\r\n\r\n') + 4;
	            req.outputData[0].data =
	                req._header + first.substring(endOfHeaders);
	            debug('Output buffer: %o', req.outputData[0].data);
	        }
	        // Create a socket connection to the proxy server.
	        let socket;
	        if (this.proxy.protocol === 'https:') {
	            debug('Creating `tls.Socket`: %o', this.connectOpts);
	            socket = tls.connect(this.connectOpts);
	        }
	        else {
	            debug('Creating `net.Socket`: %o', this.connectOpts);
	            socket = net.connect(this.connectOpts);
	        }
	        // Wait for the socket's `connect` event, so that this `callback()`
	        // function throws instead of the `http` request machinery. This is
	        // important for i.e. `PacProxyAgent` which determines a failed proxy
	        // connection via the `callback()` function throwing.
	        await (0, events.once)(socket, 'connect');
	        return socket;
	    }
	}
	HttpProxyAgent.protocols = ['http', 'https'];
	exports.HttpProxyAgent = HttpProxyAgent;
	function omit(obj, ...keys) {
	    const ret = {};
	    let key;
	    for (key in obj) {
	        if (!keys.includes(key)) {
	            ret[key] = obj[key];
	        }
	    }
	    return ret;
	}

	});

	unwrapExports(dist);
	var dist_1 = dist.HttpProxyAgent;

	// Copyright (c) Microsoft Corporation.
	const HTTPS_PROXY = "HTTPS_PROXY";
	const HTTP_PROXY = "HTTP_PROXY";
	const ALL_PROXY = "ALL_PROXY";
	const NO_PROXY = "NO_PROXY";
	/**
	 * The programmatic identifier of the proxyPolicy.
	 */
	const proxyPolicyName = "proxyPolicy";
	/**
	 * Stores the patterns specified in NO_PROXY environment variable.
	 * @internal
	 */
	const globalNoProxyList = [];
	let noProxyListLoaded = false;
	/** A cache of whether a host should bypass the proxy. */
	const globalBypassedMap = new Map();
	function getEnvironmentValue(name) {
	    if (process.env[name]) {
	        return process.env[name];
	    }
	    else if (process.env[name.toLowerCase()]) {
	        return process.env[name.toLowerCase()];
	    }
	    return undefined;
	}
	function loadEnvironmentProxyValue() {
	    if (!process) {
	        return undefined;
	    }
	    const httpsProxy = getEnvironmentValue(HTTPS_PROXY);
	    const allProxy = getEnvironmentValue(ALL_PROXY);
	    const httpProxy = getEnvironmentValue(HTTP_PROXY);
	    return httpsProxy || allProxy || httpProxy;
	}
	/**
	 * Check whether the host of a given `uri` matches any pattern in the no proxy list.
	 * If there's a match, any request sent to the same host shouldn't have the proxy settings set.
	 * This implementation is a port of https://github.com/Azure/azure-sdk-for-net/blob/8cca811371159e527159c7eb65602477898683e2/sdk/core/Azure.Core/src/Pipeline/Internal/HttpEnvironmentProxy.cs#L210
	 */
	function isBypassed(uri, noProxyList, bypassedMap) {
	    if (noProxyList.length === 0) {
	        return false;
	    }
	    const host = new URL(uri).hostname;
	    if (bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.has(host)) {
	        return bypassedMap.get(host);
	    }
	    let isBypassedFlag = false;
	    for (const pattern of noProxyList) {
	        if (pattern[0] === ".") {
	            // This should match either domain it self or any subdomain or host
	            // .foo.com will match foo.com it self or *.foo.com
	            if (host.endsWith(pattern)) {
	                isBypassedFlag = true;
	            }
	            else {
	                if (host.length === pattern.length - 1 && host === pattern.slice(1)) {
	                    isBypassedFlag = true;
	                }
	            }
	        }
	        else {
	            if (host === pattern) {
	                isBypassedFlag = true;
	            }
	        }
	    }
	    bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.set(host, isBypassedFlag);
	    return isBypassedFlag;
	}
	function loadNoProxy() {
	    const noProxy = getEnvironmentValue(NO_PROXY);
	    noProxyListLoaded = true;
	    if (noProxy) {
	        return noProxy
	            .split(",")
	            .map((item) => item.trim())
	            .filter((item) => item.length);
	    }
	    return [];
	}
	/**
	 * This method converts a proxy url into `ProxySettings` for use with ProxyPolicy.
	 * If no argument is given, it attempts to parse a proxy URL from the environment
	 * variables `HTTPS_PROXY` or `HTTP_PROXY`.
	 * @param proxyUrl - The url of the proxy to use. May contain authentication information.
	 * @deprecated - Internally this method is no longer necessary when setting proxy information.
	 */
	function getDefaultProxySettings(proxyUrl) {
	    if (!proxyUrl) {
	        proxyUrl = loadEnvironmentProxyValue();
	        if (!proxyUrl) {
	            return undefined;
	        }
	    }
	    const parsedUrl = new URL(proxyUrl);
	    const schema = parsedUrl.protocol ? parsedUrl.protocol + "//" : "";
	    return {
	        host: schema + parsedUrl.hostname,
	        port: Number.parseInt(parsedUrl.port || "80"),
	        username: parsedUrl.username,
	        password: parsedUrl.password,
	    };
	}
	/**
	 * This method attempts to parse a proxy URL from the environment
	 * variables `HTTPS_PROXY` or `HTTP_PROXY`.
	 */
	function getDefaultProxySettingsInternal() {
	    const envProxy = loadEnvironmentProxyValue();
	    return envProxy ? new URL(envProxy) : undefined;
	}
	function getUrlFromProxySettings(settings) {
	    let parsedProxyUrl;
	    try {
	        parsedProxyUrl = new URL(settings.host);
	    }
	    catch (_a) {
	        throw new Error(`Expecting a valid host string in proxy settings, but found "${settings.host}".`);
	    }
	    parsedProxyUrl.port = String(settings.port);
	    if (settings.username) {
	        parsedProxyUrl.username = settings.username;
	    }
	    if (settings.password) {
	        parsedProxyUrl.password = settings.password;
	    }
	    return parsedProxyUrl;
	}
	function setProxyAgentOnRequest(request, cachedAgents, proxyUrl) {
	    // Custom Agent should take precedence so if one is present
	    // we should skip to avoid overwriting it.
	    if (request.agent) {
	        return;
	    }
	    const url = new URL(request.url);
	    const isInsecure = url.protocol !== "https:";
	    if (request.tlsSettings) {
	        logger$1.warning("TLS settings are not supported in combination with custom Proxy, certificates provided to the client will be ignored.");
	    }
	    const headers = request.headers.toJSON();
	    if (isInsecure) {
	        if (!cachedAgents.httpProxyAgent) {
	            cachedAgents.httpProxyAgent = new dist_1(proxyUrl, { headers });
	        }
	        request.agent = cachedAgents.httpProxyAgent;
	    }
	    else {
	        if (!cachedAgents.httpsProxyAgent) {
	            cachedAgents.httpsProxyAgent = new dist_1$1(proxyUrl, { headers });
	        }
	        request.agent = cachedAgents.httpsProxyAgent;
	    }
	}
	/**
	 * A policy that allows one to apply proxy settings to all requests.
	 * If not passed static settings, they will be retrieved from the HTTPS_PROXY
	 * or HTTP_PROXY environment variables.
	 * @param proxySettings - ProxySettings to use on each request.
	 * @param options - additional settings, for example, custom NO_PROXY patterns
	 */
	function proxyPolicy(proxySettings, options) {
	    if (!noProxyListLoaded) {
	        globalNoProxyList.push(...loadNoProxy());
	    }
	    const defaultProxy = proxySettings
	        ? getUrlFromProxySettings(proxySettings)
	        : getDefaultProxySettingsInternal();
	    const cachedAgents = {};
	    return {
	        name: proxyPolicyName,
	        async sendRequest(request, next) {
	            var _a;
	            if (!request.proxySettings &&
	                defaultProxy &&
	                !isBypassed(request.url, (_a = options === null || options === void 0 ? void 0 : options.customNoProxyList) !== null && _a !== void 0 ? _a : globalNoProxyList, (options === null || options === void 0 ? void 0 : options.customNoProxyList) ? undefined : globalBypassedMap)) {
	                setProxyAgentOnRequest(request, cachedAgents, defaultProxy);
	            }
	            else if (request.proxySettings) {
	                setProxyAgentOnRequest(request, cachedAgents, getUrlFromProxySettings(request.proxySettings));
	            }
	            return next(request);
	        },
	    };
	}

	// Copyright (c) Microsoft Corporation.
	// Licensed under the MIT License.
	/**
	 * The programmatic identifier of the setClientRequestIdPolicy.
	 */
	const setClientRequestIdPolicyName = "setClientRequestIdPolicy";
	/**
	 * Each PipelineRequest gets a unique id upon creation.
	 * This policy passes that unique id along via an HTTP header to enable better
	 * telemetry and tracing.
	 * @param requestIdHeaderName - The name of the header to pass the request ID to.
	 */
	function setClientRequestIdPolicy(requestIdHeaderName = "x-ms-client-request-id") {
	    return {
	        name: setClientRequestIdPolicyName,
	        async sendRequest(request, next) {
	            if (!request.headers.has(requestIdHeaderName)) {
	                request.headers.set(requestIdHeaderName, request.requestId);
	            }
	            return next(request);
	        },
	    };
	}

	// Copyright (c) Microsoft Corporation.
	// Licensed under the MIT License.
	/**
	 * Name of the TLS Policy
	 */
	const tlsPolicyName = "tlsPolicy";
	/**
	 * Gets a pipeline policy that adds the client certificate to the HttpClient agent for authentication.
	 */
	function tlsPolicy(tlsSettings) {
	    return {
	        name: tlsPolicyName,
	        sendRequest: async (req, next) => {
	            // Users may define a request tlsSettings, honor those over the client level one
	            if (!req.tlsSettings) {
	                req.tlsSettings = tlsSettings;
	            }
	            return next(req);
	        },
	    };
	}

	// Copyright (c) Microsoft Corporation.
	// Licensed under the MIT license.
	/** @internal */
	const knownContextKeys = {
	    span: Symbol.for("@azure/core-tracing span"),
	    namespace: Symbol.for("@azure/core-tracing namespace"),
	};
	/**
	 * Creates a new {@link TracingContext} with the given options.
	 * @param options - A set of known keys that may be set on the context.
	 * @returns A new {@link TracingContext} with the given options.
	 *
	 * @internal
	 */
	function createTracingContext(options = {}) {
	    let context = new TracingContextImpl(options.parentContext);
	    if (options.span) {
	        context = context.setValue(knownContextKeys.span, options.span);
	    }
	    if (options.namespace) {
	        context = context.setValue(knownContextKeys.namespace, options.namespace);
	    }
	    return context;
	}
	/** @internal */
	class TracingContextImpl {
	    constructor(initialContext) {
	        this._contextMap =
	            initialContext instanceof TracingContextImpl
	                ? new Map(initialContext._contextMap)
	                : new Map();
	    }
	    setValue(key, value) {
	        const newContext = new TracingContextImpl(this);
	        newContext._contextMap.set(key, value);
	        return newContext;
	    }
	    getValue(key) {
	        return this._contextMap.get(key);
	    }
	    deleteValue(key) {
	        const newContext = new TracingContextImpl(this);
	        newContext._contextMap.delete(key);
	        return newContext;
	    }
	}

	// Copyright (c) Microsoft Corporation.
	// Licensed under the MIT license.
	/**
	 * Browser-only implementation of the module's state. The browser esm variant will not load the commonjs state, so we do not need to share state between the two.
	 */
	const state$1 = {
	    instrumenterImplementation: undefined,
	};

	// Copyright (c) Microsoft Corporation.
	function createDefaultTracingSpan() {
	    return {
	        end: () => {
	            // noop
	        },
	        isRecording: () => false,
	        recordException: () => {
	            // noop
	        },
	        setAttribute: () => {
	            // noop
	        },
	        setStatus: () => {
	            // noop
	        },
	    };
	}
	function createDefaultInstrumenter() {
	    return {
	        createRequestHeaders: () => {
	            return {};
	        },
	        parseTraceparentHeader: () => {
	            return undefined;
	        },
	        startSpan: (_name, spanOptions) => {
	            return {
	                span: createDefaultTracingSpan(),
	                tracingContext: createTracingContext({ parentContext: spanOptions.tracingContext }),
	            };
	        },
	        withContext(_context, callback, ...callbackArgs) {
	            return callback(...callbackArgs);
	        },
	    };
	}
	/**
	 * Gets the currently set instrumenter, a No-Op instrumenter by default.
	 *
	 * @returns The currently set instrumenter
	 */
	function getInstrumenter() {
	    if (!state$1.instrumenterImplementation) {
	        state$1.instrumenterImplementation = createDefaultInstrumenter();
	    }
	    return state$1.instrumenterImplementation;
	}

	// Copyright (c) Microsoft Corporation.
	/**
	 * Creates a new tracing client.
	 *
	 * @param options - Options used to configure the tracing client.
	 * @returns - An instance of {@link TracingClient}.
	 */
	function createTracingClient(options) {
	    const { namespace, packageName, packageVersion } = options;
	    function startSpan(name, operationOptions, spanOptions) {
	        var _a;
	        const startSpanResult = getInstrumenter().startSpan(name, Object.assign(Object.assign({}, spanOptions), { packageName: packageName, packageVersion: packageVersion, tracingContext: (_a = operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions) === null || _a === void 0 ? void 0 : _a.tracingContext }));
	        let tracingContext = startSpanResult.tracingContext;
	        const span = startSpanResult.span;
	        if (!tracingContext.getValue(knownContextKeys.namespace)) {
	            tracingContext = tracingContext.setValue(knownContextKeys.namespace, namespace);
	        }
	        span.setAttribute("az.namespace", tracingContext.getValue(knownContextKeys.namespace));
	        const updatedOptions = Object.assign({}, operationOptions, {
	            tracingOptions: Object.assign(Object.assign({}, operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions), { tracingContext }),
	        });
	        return {
	            span,
	            updatedOptions,
	        };
	    }
	    async function withSpan(name, operationOptions, callback, spanOptions) {
	        const { span, updatedOptions } = startSpan(name, operationOptions, spanOptions);
	        try {
	            const result = await withContext(updatedOptions.tracingOptions.tracingContext, () => Promise.resolve(callback(updatedOptions, span)));
	            span.setStatus({ status: "success" });
	            return result;
	        }
	        catch (err) {
	            span.setStatus({ status: "error", error: err });
	            throw err;
	        }
	        finally {
	            span.end();
	        }
	    }
	    function withContext(context, callback, ...callbackArgs) {
	        return getInstrumenter().withContext(context, callback, ...callbackArgs);
	    }
	    /**
	     * Parses a traceparent header value into a span identifier.
	     *
	     * @param traceparentHeader - The traceparent header to parse.
	     * @returns An implementation-specific identifier for the span.
	     */
	    function parseTraceparentHeader(traceparentHeader) {
	        return getInstrumenter().parseTraceparentHeader(traceparentHeader);
	    }
	    /**
	     * Creates a set of request headers to propagate tracing information to a backend.
	     *
	     * @param tracingContext - The context containing the span to serialize.
	     * @returns The set of headers to add to a request.
	     */
	    function createRequestHeaders(tracingContext) {
	        return getInstrumenter().createRequestHeaders(tracingContext);
	    }
	    return {
	        startSpan,
	        withSpan,
	        withContext,
	        parseTraceparentHeader,
	        createRequestHeaders,
	    };
	}

	// Copyright (c) Microsoft Corporation.
	const custom = util.inspect.custom;

	// Copyright (c) Microsoft Corporation.
	const errorSanitizer = new Sanitizer();
	/**
	 * A custom error type for failed pipeline requests.
	 */
	class RestError extends Error {
	    constructor(message, options = {}) {
	        super(message);
	        this.name = "RestError";
	        this.code = options.code;
	        this.statusCode = options.statusCode;
	        // The request and response may contain sensitive information in the headers or body.
	        // To help prevent this sensitive information being accidentally logged, the request and response
	        // properties are marked as non-enumerable here. This prevents them showing up in the output of
	        // JSON.stringify and console.log.
	        Object.defineProperty(this, "request", { value: options.request, enumerable: false });
	        Object.defineProperty(this, "response", { value: options.response, enumerable: false });
	        Object.setPrototypeOf(this, RestError.prototype);
	    }
	    /**
	     * Logging method for util.inspect in Node
	     */
	    [custom]() {
	        // Extract non-enumerable properties and add them back. This is OK since in this output the request and
	        // response get sanitized.
	        return `RestError: ${this.message} \n ${errorSanitizer.sanitize(Object.assign(Object.assign({}, this), { request: this.request, response: this.response }))}`;
	    }
	}
	/**
	 * Something went wrong when making the request.
	 * This means the actual request failed for some reason,
	 * such as a DNS issue or the connection being lost.
	 */
	RestError.REQUEST_SEND_ERROR = "REQUEST_SEND_ERROR";
	/**
	 * This means that parsing the response from the server failed.
	 * It may have been malformed.
	 */
	RestError.PARSE_ERROR = "PARSE_ERROR";
	/**
	 * Typeguard for RestError
	 * @param e - Something caught by a catch clause.
	 */
	function isRestError(e) {
	    if (e instanceof RestError) {
	        return true;
	    }
	    return isError(e) && e.name === "RestError";
	}

	// Copyright (c) Microsoft Corporation.
	/**
	 * The programmatic identifier of the tracingPolicy.
	 */
	const tracingPolicyName = "tracingPolicy";
	/**
	 * A simple policy to create OpenTelemetry Spans for each request made by the pipeline
	 * that has SpanOptions with a parent.
	 * Requests made without a parent Span will not be recorded.
	 * @param options - Options to configure the telemetry logged by the tracing policy.
	 */
	function tracingPolicy(options = {}) {
	    const userAgentPromise = getUserAgentValue(options.userAgentPrefix);
	    const sanitizer = new Sanitizer({
	        additionalAllowedQueryParameters: options.additionalAllowedQueryParameters,
	    });
	    const tracingClient = tryCreateTracingClient();
	    return {
	        name: tracingPolicyName,
	        async sendRequest(request, next) {
	            var _a;
	            if (!tracingClient) {
	                return next(request);
	            }
	            const userAgent = await userAgentPromise;
	            const spanAttributes = {
	                "http.url": sanitizer.sanitizeUrl(request.url),
	                "http.method": request.method,
	                "http.user_agent": userAgent,
	                requestId: request.requestId,
	            };
	            if (userAgent) {
	                spanAttributes["http.user_agent"] = userAgent;
	            }
	            const { span, tracingContext } = (_a = tryCreateSpan(tracingClient, request, spanAttributes)) !== null && _a !== void 0 ? _a : {};
	            if (!span || !tracingContext) {
	                return next(request);
	            }
	            try {
	                const response = await tracingClient.withContext(tracingContext, next, request);
	                tryProcessResponse(span, response);
	                return response;
	            }
	            catch (err) {
	                tryProcessError(span, err);
	                throw err;
	            }
	        },
	    };
	}
	function tryCreateTracingClient() {
	    try {
	        return createTracingClient({
	            namespace: "",
	            packageName: "@azure/core-rest-pipeline",
	            packageVersion: SDK_VERSION,
	        });
	    }
	    catch (e) {
	        logger$1.warning(`Error when creating the TracingClient: ${getErrorMessage(e)}`);
	        return undefined;
	    }
	}
	function tryCreateSpan(tracingClient, request, spanAttributes) {
	    try {
	        // As per spec, we do not need to differentiate between HTTP and HTTPS in span name.
	        const { span, updatedOptions } = tracingClient.startSpan(`HTTP ${request.method}`, { tracingOptions: request.tracingOptions }, {
	            spanKind: "client",
	            spanAttributes,
	        });
	        // If the span is not recording, don't do any more work.
	        if (!span.isRecording()) {
	            span.end();
	            return undefined;
	        }
	        // set headers
	        const headers = tracingClient.createRequestHeaders(updatedOptions.tracingOptions.tracingContext);
	        for (const [key, value] of Object.entries(headers)) {
	            request.headers.set(key, value);
	        }
	        return { span, tracingContext: updatedOptions.tracingOptions.tracingContext };
	    }
	    catch (e) {
	        logger$1.warning(`Skipping creating a tracing span due to an error: ${getErrorMessage(e)}`);
	        return undefined;
	    }
	}
	function tryProcessError(span, error) {
	    try {
	        span.setStatus({
	            status: "error",
	            error: isError(error) ? error : undefined,
	        });
	        if (isRestError(error) && error.statusCode) {
	            span.setAttribute("http.status_code", error.statusCode);
	        }
	        span.end();
	    }
	    catch (e) {
	        logger$1.warning(`Skipping tracing span processing due to an error: ${getErrorMessage(e)}`);
	    }
	}
	function tryProcessResponse(span, response) {
	    try {
	        span.setAttribute("http.status_code", response.status);
	        const serviceRequestId = response.headers.get("x-ms-request-id");
	        if (serviceRequestId) {
	            span.setAttribute("serviceRequestId", serviceRequestId);
	        }
	        span.setStatus({
	            status: "success",
	        });
	        span.end();
	    }
	    catch (e) {
	        logger$1.warning(`Skipping tracing span processing due to an error: ${getErrorMessage(e)}`);
	    }
	}

	// Copyright (c) Microsoft Corporation.
	/**
	 * Create a new pipeline with a default set of customizable policies.
	 * @param options - Options to configure a custom pipeline.
	 */
	function createPipelineFromOptions(options) {
	    var _a;
	    const pipeline = createEmptyPipeline();
	    if (isNodeLike) {
	        if (options.tlsOptions) {
	            pipeline.addPolicy(tlsPolicy(options.tlsOptions));
	        }
	        pipeline.addPolicy(proxyPolicy(options.proxyOptions));
	        pipeline.addPolicy(decompressResponsePolicy());
	    }
	    pipeline.addPolicy(formDataPolicy(), { beforePolicies: [multipartPolicyName] });
	    pipeline.addPolicy(userAgentPolicy(options.userAgentOptions));
	    pipeline.addPolicy(setClientRequestIdPolicy((_a = options.telemetryOptions) === null || _a === void 0 ? void 0 : _a.clientRequestIdHeaderName));
	    // The multipart policy is added after policies with no phase, so that
	    // policies can be added between it and formDataPolicy to modify
	    // properties (e.g., making the boundary constant in recorded tests).
	    pipeline.addPolicy(multipartPolicy(), { afterPhase: "Deserialize" });
	    pipeline.addPolicy(defaultRetryPolicy(options.retryOptions), { phase: "Retry" });
	    pipeline.addPolicy(tracingPolicy(Object.assign(Object.assign({}, options.userAgentOptions), options.loggingOptions)), {
	        afterPhase: "Retry",
	    });
	    if (isNodeLike) {
	        // Both XHR and Fetch expect to handle redirects automatically,
	        // so only include this policy when we're in Node.
	        pipeline.addPolicy(redirectPolicy(options.redirectOptions), { afterPhase: "Retry" });
	    }
	    pipeline.addPolicy(logPolicy(options.loggingOptions), { afterPhase: "Sign" });
	    return pipeline;
	}

	// Copyright (c) Microsoft Corporation.
	const DEFAULT_TLS_SETTINGS = {};
	function isReadableStream(body) {
	    return body && typeof body.pipe === "function";
	}
	function isStreamComplete(stream) {
	    return new Promise((resolve) => {
	        const handler = () => {
	            resolve();
	            stream.removeListener("close", handler);
	            stream.removeListener("end", handler);
	            stream.removeListener("error", handler);
	        };
	        stream.on("close", handler);
	        stream.on("end", handler);
	        stream.on("error", handler);
	    });
	}
	function isArrayBuffer(body) {
	    return body && typeof body.byteLength === "number";
	}
	class ReportTransform extends node_stream.Transform {
	    // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
	    _transform(chunk, _encoding, callback) {
	        this.push(chunk);
	        this.loadedBytes += chunk.length;
	        try {
	            this.progressCallback({ loadedBytes: this.loadedBytes });
	            callback();
	        }
	        catch (e) {
	            callback(e);
	        }
	    }
	    constructor(progressCallback) {
	        super();
	        this.loadedBytes = 0;
	        this.progressCallback = progressCallback;
	    }
	}
	/**
	 * A HttpClient implementation that uses Node's "https" module to send HTTPS requests.
	 * @internal
	 */
	class NodeHttpClient {
	    constructor() {
	        this.cachedHttpsAgents = new WeakMap();
	    }
	    /**
	     * Makes a request over an underlying transport layer and returns the response.
	     * @param request - The request to be made.
	     */
	    async sendRequest(request) {
	        var _a, _b, _c;
	        const abortController = new AbortController();
	        let abortListener;
	        if (request.abortSignal) {
	            if (request.abortSignal.aborted) {
	                throw new AbortError("The operation was aborted.");
	            }
	            abortListener = (event) => {
	                if (event.type === "abort") {
	                    abortController.abort();
	                }
	            };
	            request.abortSignal.addEventListener("abort", abortListener);
	        }
	        if (request.timeout > 0) {
	            setTimeout(() => {
	                abortController.abort();
	            }, request.timeout);
	        }
	        const acceptEncoding = request.headers.get("Accept-Encoding");
	        const shouldDecompress = (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("gzip")) || (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("deflate"));
	        let body = typeof request.body === "function" ? request.body() : request.body;
	        if (body && !request.headers.has("Content-Length")) {
	            const bodyLength = getBodyLength(body);
	            if (bodyLength !== null) {
	                request.headers.set("Content-Length", bodyLength);
	            }
	        }
	        let responseStream;
	        try {
	            if (body && request.onUploadProgress) {
	                const onUploadProgress = request.onUploadProgress;
	                const uploadReportStream = new ReportTransform(onUploadProgress);
	                uploadReportStream.on("error", (e) => {
	                    logger$1.error("Error in upload progress", e);
	                });
	                if (isReadableStream(body)) {
	                    body.pipe(uploadReportStream);
	                }
	                else {
	                    uploadReportStream.end(body);
	                }
	                body = uploadReportStream;
	            }
	            const res = await this.makeRequest(request, abortController, body);
	            const headers = getResponseHeaders(res);
	            const status = (_a = res.statusCode) !== null && _a !== void 0 ? _a : 0;
	            const response = {
	                status,
	                headers,
	                request,
	            };
	            // Responses to HEAD must not have a body.
	            // If they do return a body, that body must be ignored.
	            if (request.method === "HEAD") {
	                // call resume() and not destroy() to avoid closing the socket
	                // and losing keep alive
	                res.resume();
	                return response;
	            }
	            responseStream = shouldDecompress ? getDecodedResponseStream(res, headers) : res;
	            const onDownloadProgress = request.onDownloadProgress;
	            if (onDownloadProgress) {
	                const downloadReportStream = new ReportTransform(onDownloadProgress);
	                downloadReportStream.on("error", (e) => {
	                    logger$1.error("Error in download progress", e);
	                });
	                responseStream.pipe(downloadReportStream);
	                responseStream = downloadReportStream;
	            }
	            if (
	            // Value of POSITIVE_INFINITY in streamResponseStatusCodes is considered as any status code
	            ((_b = request.streamResponseStatusCodes) === null || _b === void 0 ? void 0 : _b.has(Number.POSITIVE_INFINITY)) ||
	                ((_c = request.streamResponseStatusCodes) === null || _c === void 0 ? void 0 : _c.has(response.status))) {
	                response.readableStreamBody = responseStream;
	            }
	            else {
	                response.bodyAsText = await streamToText(responseStream);
	            }
	            return response;
	        }
	        finally {
	            // clean up event listener
	            if (request.abortSignal && abortListener) {
	                let uploadStreamDone = Promise.resolve();
	                if (isReadableStream(body)) {
	                    uploadStreamDone = isStreamComplete(body);
	                }
	                let downloadStreamDone = Promise.resolve();
	                if (isReadableStream(responseStream)) {
	                    downloadStreamDone = isStreamComplete(responseStream);
	                }
	                Promise.all([uploadStreamDone, downloadStreamDone])
	                    .then(() => {
	                    var _a;
	                    // eslint-disable-next-line promise/always-return
	                    if (abortListener) {
	                        (_a = request.abortSignal) === null || _a === void 0 ? void 0 : _a.removeEventListener("abort", abortListener);
	                    }
	                })
	                    .catch((e) => {
	                    logger$1.warning("Error when cleaning up abortListener on httpRequest", e);
	                });
	            }
	        }
	    }
	    makeRequest(request, abortController, body) {
	        var _a;
	        const url = new URL(request.url);
	        const isInsecure = url.protocol !== "https:";
	        if (isInsecure && !request.allowInsecureConnection) {
	            throw new Error(`Cannot connect to ${request.url} while allowInsecureConnection is false.`);
	        }
	        const agent = (_a = request.agent) !== null && _a !== void 0 ? _a : this.getOrCreateAgent(request, isInsecure);
	        const options = {
	            agent,
	            hostname: url.hostname,
	            path: `${url.pathname}${url.search}`,
	            port: url.port,
	            method: request.method,
	            headers: request.headers.toJSON({ preserveCase: true }),
	        };
	        return new Promise((resolve, reject) => {
	            const req = isInsecure ? http__namespace.request(options, resolve) : https__namespace.request(options, resolve);
	            req.once("error", (err) => {
	                var _a;
	                reject(new RestError(err.message, { code: (_a = err.code) !== null && _a !== void 0 ? _a : RestError.REQUEST_SEND_ERROR, request }));
	            });
	            abortController.signal.addEventListener("abort", () => {
	                const abortError = new AbortError("The operation was aborted.");
	                req.destroy(abortError);
	                reject(abortError);
	            });
	            if (body && isReadableStream(body)) {
	                body.pipe(req);
	            }
	            else if (body) {
	                if (typeof body === "string" || Buffer.isBuffer(body)) {
	                    req.end(body);
	                }
	                else if (isArrayBuffer(body)) {
	                    req.end(ArrayBuffer.isView(body) ? Buffer.from(body.buffer) : Buffer.from(body));
	                }
	                else {
	                    logger$1.error("Unrecognized body type", body);
	                    reject(new RestError("Unrecognized body type"));
	                }
	            }
	            else {
	                // streams don't like "undefined" being passed as data
	                req.end();
	            }
	        });
	    }
	    getOrCreateAgent(request, isInsecure) {
	        var _a;
	        const disableKeepAlive = request.disableKeepAlive;
	        // Handle Insecure requests first
	        if (isInsecure) {
	            if (disableKeepAlive) {
	                // keepAlive:false is the default so we don't need a custom Agent
	                return http__namespace.globalAgent;
	            }
	            if (!this.cachedHttpAgent) {
	                // If there is no cached agent create a new one and cache it.
	                this.cachedHttpAgent = new http__namespace.Agent({ keepAlive: true });
	            }
	            return this.cachedHttpAgent;
	        }
	        else {
	            if (disableKeepAlive && !request.tlsSettings) {
	                // When there are no tlsSettings and keepAlive is false
	                // we don't need a custom agent
	                return https__namespace.globalAgent;
	            }
	            // We use the tlsSettings to index cached clients
	            const tlsSettings = (_a = request.tlsSettings) !== null && _a !== void 0 ? _a : DEFAULT_TLS_SETTINGS;
	            // Get the cached agent or create a new one with the
	            // provided values for keepAlive and tlsSettings
	            let agent = this.cachedHttpsAgents.get(tlsSettings);
	            if (agent && agent.options.keepAlive === !disableKeepAlive) {
	                return agent;
	            }
	            logger$1.info("No cached TLS Agent exist, creating a new Agent");
	            agent = new https__namespace.Agent(Object.assign({ 
	                // keepAlive is true if disableKeepAlive is false.
	                keepAlive: !disableKeepAlive }, tlsSettings));
	            this.cachedHttpsAgents.set(tlsSettings, agent);
	            return agent;
	        }
	    }
	}
	function getResponseHeaders(res) {
	    const headers = createHttpHeaders();
	    for (const header of Object.keys(res.headers)) {
	        const value = res.headers[header];
	        if (Array.isArray(value)) {
	            if (value.length > 0) {
	                headers.set(header, value[0]);
	            }
	        }
	        else if (value) {
	            headers.set(header, value);
	        }
	    }
	    return headers;
	}
	function getDecodedResponseStream(stream, headers) {
	    const contentEncoding = headers.get("Content-Encoding");
	    if (contentEncoding === "gzip") {
	        const unzip = zlib__namespace.createGunzip();
	        stream.pipe(unzip);
	        return unzip;
	    }
	    else if (contentEncoding === "deflate") {
	        const inflate = zlib__namespace.createInflate();
	        stream.pipe(inflate);
	        return inflate;
	    }
	    return stream;
	}
	function streamToText(stream) {
	    return new Promise((resolve, reject) => {
	        const buffer = [];
	        stream.on("data", (chunk) => {
	            if (Buffer.isBuffer(chunk)) {
	                buffer.push(chunk);
	            }
	            else {
	                buffer.push(Buffer.from(chunk));
	            }
	        });
	        stream.on("end", () => {
	            resolve(Buffer.concat(buffer).toString("utf8"));
	        });
	        stream.on("error", (e) => {
	            if (e && (e === null || e === void 0 ? void 0 : e.name) === "AbortError") {
	                reject(e);
	            }
	            else {
	                reject(new RestError(`Error reading response as text: ${e.message}`, {
	                    code: RestError.PARSE_ERROR,
	                }));
	            }
	        });
	    });
	}
	/** @internal */
	function getBodyLength(body) {
	    if (!body) {
	        return 0;
	    }
	    else if (Buffer.isBuffer(body)) {
	        return body.length;
	    }
	    else if (isReadableStream(body)) {
	        return null;
	    }
	    else if (isArrayBuffer(body)) {
	        return body.byteLength;
	    }
	    else if (typeof body === "string") {
	        return Buffer.from(body).length;
	    }
	    else {
	        return null;
	    }
	}
	/**
	 * Create a new HttpClient instance for the NodeJS environment.
	 * @internal
	 */
	function createNodeHttpClient() {
	    return new NodeHttpClient();
	}

	// Copyright (c) Microsoft Corporation.
	/**
	 * Create the correct HttpClient for the current environment.
	 */
	function createDefaultHttpClient() {
	    return createNodeHttpClient();
	}

	// Copyright (c) Microsoft Corporation.
	class PipelineRequestImpl {
	    constructor(options) {
	        var _a, _b, _c, _d, _e, _f, _g;
	        this.url = options.url;
	        this.body = options.body;
	        this.headers = (_a = options.headers) !== null && _a !== void 0 ? _a : createHttpHeaders();
	        this.method = (_b = options.method) !== null && _b !== void 0 ? _b : "GET";
	        this.timeout = (_c = options.timeout) !== null && _c !== void 0 ? _c : 0;
	        this.multipartBody = options.multipartBody;
	        this.formData = options.formData;
	        this.disableKeepAlive = (_d = options.disableKeepAlive) !== null && _d !== void 0 ? _d : false;
	        this.proxySettings = options.proxySettings;
	        this.streamResponseStatusCodes = options.streamResponseStatusCodes;
	        this.withCredentials = (_e = options.withCredentials) !== null && _e !== void 0 ? _e : false;
	        this.abortSignal = options.abortSignal;
	        this.tracingOptions = options.tracingOptions;
	        this.onUploadProgress = options.onUploadProgress;
	        this.onDownloadProgress = options.onDownloadProgress;
	        this.requestId = options.requestId || randomUUID();
	        this.allowInsecureConnection = (_f = options.allowInsecureConnection) !== null && _f !== void 0 ? _f : false;
	        this.enableBrowserStreams = (_g = options.enableBrowserStreams) !== null && _g !== void 0 ? _g : false;
	    }
	}
	/**
	 * Creates a new pipeline request with the given options.
	 * This method is to allow for the easy setting of default values and not required.
	 * @param options - The options to create the request with.
	 */
	function createPipelineRequest(options) {
	    return new PipelineRequestImpl(options);
	}

	// Copyright (c) Microsoft Corporation.
	/**
	 * The programmatic identifier of the exponentialRetryPolicy.
	 */
	const exponentialRetryPolicyName = "exponentialRetryPolicy";
	/**
	 * A policy that attempts to retry requests while introducing an exponentially increasing delay.
	 * @param options - Options that configure retry logic.
	 */
	function exponentialRetryPolicy(options = {}) {
	    var _a;
	    return retryPolicy([
	        exponentialRetryStrategy(Object.assign(Object.assign({}, options), { ignoreSystemErrors: true })),
	    ], {
	        maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : DEFAULT_RETRY_POLICY_COUNT,
	    });
	}

	// Copyright (c) Microsoft Corporation.
	/**
	 * Name of the {@link systemErrorRetryPolicy}
	 */
	const systemErrorRetryPolicyName = "systemErrorRetryPolicy";
	/**
	 * A retry policy that specifically seeks to handle errors in the
	 * underlying transport layer (e.g. DNS lookup failures) rather than
	 * retryable error codes from the server itself.
	 * @param options - Options that customize the policy.
	 */
	function systemErrorRetryPolicy(options = {}) {
	    var _a;
	    return {
	        name: systemErrorRetryPolicyName,
	        sendRequest: retryPolicy([
	            exponentialRetryStrategy(Object.assign(Object.assign({}, options), { ignoreHttpStatusCodes: true })),
	        ], {
	            maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : DEFAULT_RETRY_POLICY_COUNT,
	        }).sendRequest,
	    };
	}

	// Copyright (c) Microsoft Corporation.
	/**
	 * Name of the {@link throttlingRetryPolicy}
	 */
	const throttlingRetryPolicyName = "throttlingRetryPolicy";
	/**
	 * A policy that retries when the server sends a 429 response with a Retry-After header.
	 *
	 * To learn more, please refer to
	 * https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-request-limits,
	 * https://docs.microsoft.com/en-us/azure/azure-subscription-service-limits and
	 * https://docs.microsoft.com/en-us/azure/virtual-machines/troubleshooting/troubleshooting-throttling-errors
	 *
	 * @param options - Options that configure retry logic.
	 */
	function throttlingRetryPolicy(options = {}) {
	    var _a;
	    return {
	        name: throttlingRetryPolicyName,
	        sendRequest: retryPolicy([throttlingRetryStrategy()], {
	            maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : DEFAULT_RETRY_POLICY_COUNT,
	        }).sendRequest,
	    };
	}

	// Copyright (c) Microsoft Corporation.
	// Default options for the cycler if none are provided
	const DEFAULT_CYCLER_OPTIONS = {
	    forcedRefreshWindowInMs: 1000, // Force waiting for a refresh 1s before the token expires
	    retryIntervalInMs: 3000, // Allow refresh attempts every 3s
	    refreshWindowInMs: 1000 * 60 * 2, // Start refreshing 2m before expiry
	};
	/**
	 * Converts an an unreliable access token getter (which may resolve with null)
	 * into an AccessTokenGetter by retrying the unreliable getter in a regular
	 * interval.
	 *
	 * @param getAccessToken - A function that produces a promise of an access token that may fail by returning null.
	 * @param retryIntervalInMs - The time (in milliseconds) to wait between retry attempts.
	 * @param refreshTimeout - The timestamp after which the refresh attempt will fail, throwing an exception.
	 * @returns - A promise that, if it resolves, will resolve with an access token.
	 */
	async function beginRefresh(getAccessToken, retryIntervalInMs, refreshTimeout) {
	    // This wrapper handles exceptions gracefully as long as we haven't exceeded
	    // the timeout.
	    async function tryGetAccessToken() {
	        if (Date.now() < refreshTimeout) {
	            try {
	                return await getAccessToken();
	            }
	            catch (_a) {
	                return null;
	            }
	        }
	        else {
	            const finalToken = await getAccessToken();
	            // Timeout is up, so throw if it's still null
	            if (finalToken === null) {
	                throw new Error("Failed to refresh access token.");
	            }
	            return finalToken;
	        }
	    }
	    let token = await tryGetAccessToken();
	    while (token === null) {
	        await delay(retryIntervalInMs);
	        token = await tryGetAccessToken();
	    }
	    return token;
	}
	/**
	 * Creates a token cycler from a credential, scopes, and optional settings.
	 *
	 * A token cycler represents a way to reliably retrieve a valid access token
	 * from a TokenCredential. It will handle initializing the token, refreshing it
	 * when it nears expiration, and synchronizes refresh attempts to avoid
	 * concurrency hazards.
	 *
	 * @param credential - the underlying TokenCredential that provides the access
	 * token
	 * @param tokenCyclerOptions - optionally override default settings for the cycler
	 *
	 * @returns - a function that reliably produces a valid access token
	 */
	function createTokenCycler(credential, tokenCyclerOptions) {
	    let refreshWorker = null;
	    let token = null;
	    let tenantId;
	    const options = Object.assign(Object.assign({}, DEFAULT_CYCLER_OPTIONS), tokenCyclerOptions);
	    /**
	     * This little holder defines several predicates that we use to construct
	     * the rules of refreshing the token.
	     */
	    const cycler = {
	        /**
	         * Produces true if a refresh job is currently in progress.
	         */
	        get isRefreshing() {
	            return refreshWorker !== null;
	        },
	        /**
	         * Produces true if the cycler SHOULD refresh (we are within the refresh
	         * window and not already refreshing)
	         */
	        get shouldRefresh() {
	            var _a;
	            if (cycler.isRefreshing) {
	                return false;
	            }
	            if ((token === null || token === void 0 ? void 0 : token.refreshAfterTimestamp) && token.refreshAfterTimestamp < Date.now()) {
	                return true;
	            }
	            return ((_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : 0) - options.refreshWindowInMs < Date.now();
	        },
	        /**
	         * Produces true if the cycler MUST refresh (null or nearly-expired
	         * token).
	         */
	        get mustRefresh() {
	            return (token === null || token.expiresOnTimestamp - options.forcedRefreshWindowInMs < Date.now());
	        },
	    };
	    /**
	     * Starts a refresh job or returns the existing job if one is already
	     * running.
	     */
	    function refresh(scopes, getTokenOptions) {
	        var _a;
	        if (!cycler.isRefreshing) {
	            // We bind `scopes` here to avoid passing it around a lot
	            const tryGetAccessToken = () => credential.getToken(scopes, getTokenOptions);
	            // Take advantage of promise chaining to insert an assignment to `token`
	            // before the refresh can be considered done.
	            refreshWorker = beginRefresh(tryGetAccessToken, options.retryIntervalInMs, 
	            // If we don't have a token, then we should timeout immediately
	            (_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : Date.now())
	                .then((_token) => {
	                refreshWorker = null;
	                token = _token;
	                tenantId = getTokenOptions.tenantId;
	                return token;
	            })
	                .catch((reason) => {
	                // We also should reset the refresher if we enter a failed state.  All
	                // existing awaiters will throw, but subsequent requests will start a
	                // new retry chain.
	                refreshWorker = null;
	                token = null;
	                tenantId = undefined;
	                throw reason;
	            });
	        }
	        return refreshWorker;
	    }
	    return async (scopes, tokenOptions) => {
	        //
	        // Simple rules:
	        // - If we MUST refresh, then return the refresh task, blocking
	        //   the pipeline until a token is available.
	        // - If we SHOULD refresh, then run refresh but don't return it
	        //   (we can still use the cached token).
	        // - Return the token, since it's fine if we didn't return in
	        //   step 1.
	        //
	        const hasClaimChallenge = Boolean(tokenOptions.claims);
	        const tenantIdChanged = tenantId !== tokenOptions.tenantId;
	        if (hasClaimChallenge) {
	            // If we've received a claim, we know the existing token isn't valid
	            // We want to clear it so that that refresh worker won't use the old expiration time as a timeout
	            token = null;
	        }
	        // If the tenantId passed in token options is different to the one we have
	        // Or if we are in claim challenge and the token was rejected and a new access token need to be issued, we need to
	        // refresh the token with the new tenantId or token.
	        const mustRefresh = tenantIdChanged || hasClaimChallenge || cycler.mustRefresh;
	        if (mustRefresh) {
	            return refresh(scopes, tokenOptions);
	        }
	        if (cycler.shouldRefresh) {
	            refresh(scopes, tokenOptions);
	        }
	        return token;
	    };
	}

	// Copyright (c) Microsoft Corporation.
	/**
	 * The programmatic identifier of the bearerTokenAuthenticationPolicy.
	 */
	const bearerTokenAuthenticationPolicyName = "bearerTokenAuthenticationPolicy";
	/**
	 * Default authorize request handler
	 */
	async function defaultAuthorizeRequest(options) {
	    const { scopes, getAccessToken, request } = options;
	    const getTokenOptions = {
	        abortSignal: request.abortSignal,
	        tracingOptions: request.tracingOptions,
	    };
	    const accessToken = await getAccessToken(scopes, getTokenOptions);
	    if (accessToken) {
	        options.request.headers.set("Authorization", `Bearer ${accessToken.token}`);
	    }
	}
	/**
	 * We will retrieve the challenge only if the response status code was 401,
	 * and if the response contained the header "WWW-Authenticate" with a non-empty value.
	 */
	function getChallenge$1(response) {
	    const challenge = response.headers.get("WWW-Authenticate");
	    if (response.status === 401 && challenge) {
	        return challenge;
	    }
	    return;
	}
	/**
	 * A policy that can request a token from a TokenCredential implementation and
	 * then apply it to the Authorization header of a request as a Bearer token.
	 */
	function bearerTokenAuthenticationPolicy(options) {
	    var _a;
	    const { credential, scopes, challengeCallbacks } = options;
	    const logger = options.logger || logger$1;
	    const callbacks = Object.assign({ authorizeRequest: (_a = challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequest) !== null && _a !== void 0 ? _a : defaultAuthorizeRequest, authorizeRequestOnChallenge: challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequestOnChallenge }, challengeCallbacks);
	    // This function encapsulates the entire process of reliably retrieving the token
	    // The options are left out of the public API until there's demand to configure this.
	    // Remember to extend `BearerTokenAuthenticationPolicyOptions` with `TokenCyclerOptions`
	    // in order to pass through the `options` object.
	    const getAccessToken = credential
	        ? createTokenCycler(credential /* , options */)
	        : () => Promise.resolve(null);
	    return {
	        name: bearerTokenAuthenticationPolicyName,
	        /**
	         * If there's no challenge parameter:
	         * - It will try to retrieve the token using the cache, or the credential's getToken.
	         * - Then it will try the next policy with or without the retrieved token.
	         *
	         * It uses the challenge parameters to:
	         * - Skip a first attempt to get the token from the credential if there's no cached token,
	         *   since it expects the token to be retrievable only after the challenge.
	         * - Prepare the outgoing request if the `prepareRequest` method has been provided.
	         * - Send an initial request to receive the challenge if it fails.
	         * - Process a challenge if the response contains it.
	         * - Retrieve a token with the challenge information, then re-send the request.
	         */
	        async sendRequest(request, next) {
	            if (!request.url.toLowerCase().startsWith("https://")) {
	                throw new Error("Bearer token authentication is not permitted for non-TLS protected (non-https) URLs.");
	            }
	            await callbacks.authorizeRequest({
	                scopes: Array.isArray(scopes) ? scopes : [scopes],
	                request,
	                getAccessToken,
	                logger,
	            });
	            let response;
	            let error;
	            try {
	                response = await next(request);
	            }
	            catch (err) {
	                error = err;
	                response = err.response;
	            }
	            if (callbacks.authorizeRequestOnChallenge &&
	                (response === null || response === void 0 ? void 0 : response.status) === 401 &&
	                getChallenge$1(response)) {
	                // processes challenge
	                const shouldSendRequest = await callbacks.authorizeRequestOnChallenge({
	                    scopes: Array.isArray(scopes) ? scopes : [scopes],
	                    request,
	                    response,
	                    getAccessToken,
	                    logger,
	                });
	                if (shouldSendRequest) {
	                    return next(request);
	                }
	            }
	            if (error) {
	                throw error;
	            }
	            else {
	                return response;
	            }
	        },
	    };
	}

	// Copyright (c) Microsoft Corporation.
	// Licensed under the MIT License.
	/**
	 * The programmatic identifier of the ndJsonPolicy.
	 */
	const ndJsonPolicyName = "ndJsonPolicy";
	/**
	 * ndJsonPolicy is a policy used to control keep alive settings for every request.
	 */
	function ndJsonPolicy() {
	    return {
	        name: ndJsonPolicyName,
	        async sendRequest(request, next) {
	            // There currently isn't a good way to bypass the serializer
	            if (typeof request.body === "string" && request.body.startsWith("[")) {
	                const body = JSON.parse(request.body);
	                if (Array.isArray(body)) {
	                    request.body = body.map((item) => JSON.stringify(item) + "\n").join("");
	                }
	            }
	            return next(request);
	        },
	    };
	}

	// Copyright (c) Microsoft Corporation.
	/**
	 * The programmatic identifier of the auxiliaryAuthenticationHeaderPolicy.
	 */
	const auxiliaryAuthenticationHeaderPolicyName = "auxiliaryAuthenticationHeaderPolicy";
	const AUTHORIZATION_AUXILIARY_HEADER = "x-ms-authorization-auxiliary";
	async function sendAuthorizeRequest(options) {
	    var _a, _b;
	    const { scopes, getAccessToken, request } = options;
	    const getTokenOptions = {
	        abortSignal: request.abortSignal,
	        tracingOptions: request.tracingOptions,
	    };
	    return (_b = (_a = (await getAccessToken(scopes, getTokenOptions))) === null || _a === void 0 ? void 0 : _a.token) !== null && _b !== void 0 ? _b : "";
	}
	/**
	 * A policy for external tokens to `x-ms-authorization-auxiliary` header.
	 * This header will be used when creating a cross-tenant application we may need to handle authentication requests
	 * for resources that are in different tenants.
	 * You could see [ARM docs](https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/authenticate-multi-tenant) for a rundown of how this feature works
	 */
	function auxiliaryAuthenticationHeaderPolicy(options) {
	    const { credentials, scopes } = options;
	    const logger = options.logger || logger$1;
	    const tokenCyclerMap = new WeakMap();
	    return {
	        name: auxiliaryAuthenticationHeaderPolicyName,
	        async sendRequest(request, next) {
	            if (!request.url.toLowerCase().startsWith("https://")) {
	                throw new Error("Bearer token authentication for auxiliary header is not permitted for non-TLS protected (non-https) URLs.");
	            }
	            if (!credentials || credentials.length === 0) {
	                logger.info(`${auxiliaryAuthenticationHeaderPolicyName} header will not be set due to empty credentials.`);
	                return next(request);
	            }
	            const tokenPromises = [];
	            for (const credential of credentials) {
	                let getAccessToken = tokenCyclerMap.get(credential);
	                if (!getAccessToken) {
	                    getAccessToken = createTokenCycler(credential);
	                    tokenCyclerMap.set(credential, getAccessToken);
	                }
	                tokenPromises.push(sendAuthorizeRequest({
	                    scopes: Array.isArray(scopes) ? scopes : [scopes],
	                    request,
	                    getAccessToken,
	                    logger,
	                }));
	            }
	            const auxiliaryTokens = (await Promise.all(tokenPromises)).filter((token) => Boolean(token));
	            if (auxiliaryTokens.length === 0) {
	                logger.warning(`None of the auxiliary tokens are valid. ${AUTHORIZATION_AUXILIARY_HEADER} header will not be set.`);
	                return next(request);
	            }
	            request.headers.set(AUTHORIZATION_AUXILIARY_HEADER, auxiliaryTokens.map((token) => `Bearer ${token}`).join(", "));
	            return next(request);
	        },
	    };
	}

	// Copyright (c) Microsoft Corporation.

	var esm = /*#__PURE__*/Object.freeze({
		__proto__: null,
		createEmptyPipeline: createEmptyPipeline,
		createPipelineFromOptions: createPipelineFromOptions,
		createDefaultHttpClient: createDefaultHttpClient,
		createHttpHeaders: createHttpHeaders,
		createPipelineRequest: createPipelineRequest,
		RestError: RestError,
		isRestError: isRestError,
		decompressResponsePolicy: decompressResponsePolicy,
		decompressResponsePolicyName: decompressResponsePolicyName,
		exponentialRetryPolicy: exponentialRetryPolicy,
		exponentialRetryPolicyName: exponentialRetryPolicyName,
		setClientRequestIdPolicy: setClientRequestIdPolicy,
		setClientRequestIdPolicyName: setClientRequestIdPolicyName,
		logPolicy: logPolicy,
		logPolicyName: logPolicyName,
		multipartPolicy: multipartPolicy,
		multipartPolicyName: multipartPolicyName,
		proxyPolicy: proxyPolicy,
		proxyPolicyName: proxyPolicyName,
		getDefaultProxySettings: getDefaultProxySettings,
		redirectPolicy: redirectPolicy,
		redirectPolicyName: redirectPolicyName,
		systemErrorRetryPolicy: systemErrorRetryPolicy,
		systemErrorRetryPolicyName: systemErrorRetryPolicyName,
		throttlingRetryPolicy: throttlingRetryPolicy,
		throttlingRetryPolicyName: throttlingRetryPolicyName,
		retryPolicy: retryPolicy,
		tracingPolicy: tracingPolicy,
		tracingPolicyName: tracingPolicyName,
		defaultRetryPolicy: defaultRetryPolicy,
		userAgentPolicy: userAgentPolicy,
		userAgentPolicyName: userAgentPolicyName,
		tlsPolicy: tlsPolicy,
		tlsPolicyName: tlsPolicyName,
		formDataPolicy: formDataPolicy,
		formDataPolicyName: formDataPolicyName,
		bearerTokenAuthenticationPolicy: bearerTokenAuthenticationPolicy,
		bearerTokenAuthenticationPolicyName: bearerTokenAuthenticationPolicyName,
		ndJsonPolicy: ndJsonPolicy,
		ndJsonPolicyName: ndJsonPolicyName,
		auxiliaryAuthenticationHeaderPolicy: auxiliaryAuthenticationHeaderPolicy,
		auxiliaryAuthenticationHeaderPolicyName: auxiliaryAuthenticationHeaderPolicyName,
		createFile: createFile,
		createFileFromStream: createFileFromStream
	});

	// Copyright (c) Microsoft Corporation.
	// Licensed under the MIT license.
	/**
	 * Browser-only implementation of the module's state. The browser esm variant will not load the commonjs state, so we do not need to share state between the two.
	 */
	const state = {
	    operationRequestMap: new WeakMap(),
	};

	// Copyright (c) Microsoft Corporation.
	/**
	 * @internal
	 * Retrieves the value to use for a given operation argument
	 * @param operationArguments - The arguments passed from the generated client
	 * @param parameter - The parameter description
	 * @param fallbackObject - If something isn't found in the arguments bag, look here.
	 *  Generally used to look at the service client properties.
	 */
	function getOperationArgumentValueFromParameter(operationArguments, parameter, fallbackObject) {
	    let parameterPath = parameter.parameterPath;
	    const parameterMapper = parameter.mapper;
	    let value;
	    if (typeof parameterPath === "string") {
	        parameterPath = [parameterPath];
	    }
	    if (Array.isArray(parameterPath)) {
	        if (parameterPath.length > 0) {
	            if (parameterMapper.isConstant) {
	                value = parameterMapper.defaultValue;
	            }
	            else {
	                let propertySearchResult = getPropertyFromParameterPath(operationArguments, parameterPath);
	                if (!propertySearchResult.propertyFound && fallbackObject) {
	                    propertySearchResult = getPropertyFromParameterPath(fallbackObject, parameterPath);
	                }
	                let useDefaultValue = false;
	                if (!propertySearchResult.propertyFound) {
	                    useDefaultValue =
	                        parameterMapper.required ||
	                            (parameterPath[0] === "options" && parameterPath.length === 2);
	                }
	                value = useDefaultValue ? parameterMapper.defaultValue : propertySearchResult.propertyValue;
	            }
	        }
	    }
	    else {
	        if (parameterMapper.required) {
	            value = {};
	        }
	        for (const propertyName in parameterPath) {
	            const propertyMapper = parameterMapper.type.modelProperties[propertyName];
	            const propertyPath = parameterPath[propertyName];
	            const propertyValue = getOperationArgumentValueFromParameter(operationArguments, {
	                parameterPath: propertyPath,
	                mapper: propertyMapper,
	            }, fallbackObject);
	            if (propertyValue !== undefined) {
	                if (!value) {
	                    value = {};
	                }
	                value[propertyName] = propertyValue;
	            }
	        }
	    }
	    return value;
	}
	function getPropertyFromParameterPath(parent, parameterPath) {
	    const result = { propertyFound: false };
	    let i = 0;
	    for (; i < parameterPath.length; ++i) {
	        const parameterPathPart = parameterPath[i];
	        // Make sure to check inherited properties too, so don't use hasOwnProperty().
	        if (parent && parameterPathPart in parent) {
	            parent = parent[parameterPathPart];
	        }
	        else {
	            break;
	        }
	    }
	    if (i === parameterPath.length) {
	        result.propertyValue = parent;
	        result.propertyFound = true;
	    }
	    return result;
	}
	const originalRequestSymbol = Symbol.for("@azure/core-client original request");
	function hasOriginalRequest(request) {
	    return originalRequestSymbol in request;
	}
	function getOperationRequestInfo(request) {
	    if (hasOriginalRequest(request)) {
	        return getOperationRequestInfo(request[originalRequestSymbol]);
	    }
	    let info = state.operationRequestMap.get(request);
	    if (!info) {
	        info = {};
	        state.operationRequestMap.set(request, info);
	    }
	    return info;
	}

	// Copyright (c) Microsoft Corporation.
	const defaultJsonContentTypes = ["application/json", "text/json"];
	const defaultXmlContentTypes = ["application/xml", "application/atom+xml"];
	/**
	 * The programmatic identifier of the deserializationPolicy.
	 */
	const deserializationPolicyName = "deserializationPolicy";
	/**
	 * This policy handles parsing out responses according to OperationSpecs on the request.
	 */
	function deserializationPolicy(options = {}) {
	    var _a, _b, _c, _d, _e, _f, _g;
	    const jsonContentTypes = (_b = (_a = options.expectedContentTypes) === null || _a === void 0 ? void 0 : _a.json) !== null && _b !== void 0 ? _b : defaultJsonContentTypes;
	    const xmlContentTypes = (_d = (_c = options.expectedContentTypes) === null || _c === void 0 ? void 0 : _c.xml) !== null && _d !== void 0 ? _d : defaultXmlContentTypes;
	    const parseXML = options.parseXML;
	    const serializerOptions = options.serializerOptions;
	    const updatedOptions = {
	        xml: {
	            rootName: (_e = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.rootName) !== null && _e !== void 0 ? _e : "",
	            includeRoot: (_f = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.includeRoot) !== null && _f !== void 0 ? _f : false,
	            xmlCharKey: (_g = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.xmlCharKey) !== null && _g !== void 0 ? _g : XML_CHARKEY,
	        },
	    };
	    return {
	        name: deserializationPolicyName,
	        async sendRequest(request, next) {
	            const response = await next(request);
	            return deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, updatedOptions, parseXML);
	        },
	    };
	}
	function getOperationResponseMap(parsedResponse) {
	    let result;
	    const request = parsedResponse.request;
	    const operationInfo = getOperationRequestInfo(request);
	    const operationSpec = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationSpec;
	    if (operationSpec) {
	        if (!(operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationResponseGetter)) {
	            result = operationSpec.responses[parsedResponse.status];
	        }
	        else {
	            result = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationResponseGetter(operationSpec, parsedResponse);
	        }
	    }
	    return result;
	}
	function shouldDeserializeResponse(parsedResponse) {
	    const request = parsedResponse.request;
	    const operationInfo = getOperationRequestInfo(request);
	    const shouldDeserialize = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.shouldDeserialize;
	    let result;
	    if (shouldDeserialize === undefined) {
	        result = true;
	    }
	    else if (typeof shouldDeserialize === "boolean") {
	        result = shouldDeserialize;
	    }
	    else {
	        result = shouldDeserialize(parsedResponse);
	    }
	    return result;
	}
	async function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, options, parseXML) {
	    const parsedResponse = await parse(jsonContentTypes, xmlContentTypes, response, options, parseXML);
	    if (!shouldDeserializeResponse(parsedResponse)) {
	        return parsedResponse;
	    }
	    const operationInfo = getOperationRequestInfo(parsedResponse.request);
	    const operationSpec = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationSpec;
	    if (!operationSpec || !operationSpec.responses) {
	        return parsedResponse;
	    }
	    const responseSpec = getOperationResponseMap(parsedResponse);
	    const { error, shouldReturnResponse } = handleErrorResponse(parsedResponse, operationSpec, responseSpec, options);
	    if (error) {
	        throw error;
	    }
	    else if (shouldReturnResponse) {
	        return parsedResponse;
	    }
	    // An operation response spec does exist for current status code, so
	    // use it to deserialize the response.
	    if (responseSpec) {
	        if (responseSpec.bodyMapper) {
	            let valueToDeserialize = parsedResponse.parsedBody;
	            if (operationSpec.isXML && responseSpec.bodyMapper.type.name === MapperTypeNames.Sequence) {
	                valueToDeserialize =
	                    typeof valueToDeserialize === "object"
	                        ? valueToDeserialize[responseSpec.bodyMapper.xmlElementName]
	                        : [];
	            }
	            try {
	                parsedResponse.parsedBody = operationSpec.serializer.deserialize(responseSpec.bodyMapper, valueToDeserialize, "operationRes.parsedBody", options);
	            }
	            catch (deserializeError) {
	                const restError = new RestError(`Error ${deserializeError} occurred in deserializing the responseBody - ${parsedResponse.bodyAsText}`, {
	                    statusCode: parsedResponse.status,
	                    request: parsedResponse.request,
	                    response: parsedResponse,
	                });
	                throw restError;
	            }
	        }
	        else if (operationSpec.httpMethod === "HEAD") {
	            // head methods never have a body, but we return a boolean to indicate presence/absence of the resource
	            parsedResponse.parsedBody = response.status >= 200 && response.status < 300;
	        }
	        if (responseSpec.headersMapper) {
	            parsedResponse.parsedHeaders = operationSpec.serializer.deserialize(responseSpec.headersMapper, parsedResponse.headers.toJSON(), "operationRes.parsedHeaders", { xml: {}, ignoreUnknownProperties: true });
	        }
	    }
	    return parsedResponse;
	}
	function isOperationSpecEmpty(operationSpec) {
	    const expectedStatusCodes = Object.keys(operationSpec.responses);
	    return (expectedStatusCodes.length === 0 ||
	        (expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default"));
	}
	function handleErrorResponse(parsedResponse, operationSpec, responseSpec, options) {
	    var _a;
	    const isSuccessByStatus = 200 <= parsedResponse.status && parsedResponse.status < 300;
	    const isExpectedStatusCode = isOperationSpecEmpty(operationSpec)
	        ? isSuccessByStatus
	        : !!responseSpec;
	    if (isExpectedStatusCode) {
	        if (responseSpec) {
	            if (!responseSpec.isError) {
	                return { error: null, shouldReturnResponse: false };
	            }
	        }
	        else {
	            return { error: null, shouldReturnResponse: false };
	        }
	    }
	    const errorResponseSpec = responseSpec !== null && responseSpec !== void 0 ? responseSpec : operationSpec.responses.default;
	    const initialErrorMessage = ((_a = parsedResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(parsedResponse.status))
	        ? `Unexpected status code: ${parsedResponse.status}`
	        : parsedResponse.bodyAsText;
	    const error = new RestError(initialErrorMessage, {
	        statusCode: parsedResponse.status,
	        request: parsedResponse.request,
	        response: parsedResponse,
	    });
	    // If the item failed but there's no error spec or default spec to deserialize the error,
	    // we should fail so we just throw the parsed response
	    if (!errorResponseSpec) {
	        throw error;
	    }
	    const defaultBodyMapper = errorResponseSpec.bodyMapper;
	    const defaultHeadersMapper = errorResponseSpec.headersMapper;
	    try {
	        // If error response has a body, try to deserialize it using default body mapper.
	        // Then try to extract error code & message from it
	        if (parsedResponse.parsedBody) {
	            const parsedBody = parsedResponse.parsedBody;
	            let deserializedError;
	            if (defaultBodyMapper) {
	                let valueToDeserialize = parsedBody;
	                if (operationSpec.isXML && defaultBodyMapper.type.name === MapperTypeNames.Sequence) {
	                    valueToDeserialize = [];
	                    const elementName = defaultBodyMapper.xmlElementName;
	                    if (typeof parsedBody === "object" && elementName) {
	                        valueToDeserialize = parsedBody[elementName];
	                    }
	                }
	                deserializedError = operationSpec.serializer.deserialize(defaultBodyMapper, valueToDeserialize, "error.response.parsedBody", options);
	            }
	            const internalError = parsedBody.error || deserializedError || parsedBody;
	            error.code = internalError.code;
	            if (internalError.message) {
	                error.message = internalError.message;
	            }
	            if (defaultBodyMapper) {
	                error.response.parsedBody = deserializedError;
	            }
	        }
	        // If error response has headers, try to deserialize it using default header mapper
	        if (parsedResponse.headers && defaultHeadersMapper) {
	            error.response.parsedHeaders =
	                operationSpec.serializer.deserialize(defaultHeadersMapper, parsedResponse.headers.toJSON(), "operationRes.parsedHeaders");
	        }
	    }
	    catch (defaultError) {
	        error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody - "${parsedResponse.bodyAsText}" for the default response.`;
	    }
	    return { error, shouldReturnResponse: false };
	}
	async function parse(jsonContentTypes, xmlContentTypes, operationResponse, opts, parseXML) {
	    var _a;
	    if (!((_a = operationResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(operationResponse.status)) &&
	        operationResponse.bodyAsText) {
	        const text = operationResponse.bodyAsText;
	        const contentType = operationResponse.headers.get("Content-Type") || "";
	        const contentComponents = !contentType
	            ? []
	            : contentType.split(";").map((component) => component.toLowerCase());
	        try {
	            if (contentComponents.length === 0 ||
	                contentComponents.some((component) => jsonContentTypes.indexOf(component) !== -1)) {
	                operationResponse.parsedBody = JSON.parse(text);
	                return operationResponse;
	            }
	            else if (contentComponents.some((component) => xmlContentTypes.indexOf(component) !== -1)) {
	                if (!parseXML) {
	                    throw new Error("Parsing XML not supported.");
	                }
	                const body = await parseXML(text, opts.xml);
	                operationResponse.parsedBody = body;
	                return operationResponse;
	            }
	        }
	        catch (err) {
	            const msg = `Error "${err}" occurred while parsing the response body - ${operationResponse.bodyAsText}.`;
	            const errCode = err.code || RestError.PARSE_ERROR;
	            const e = new RestError(msg, {
	                code: errCode,
	                statusCode: operationResponse.status,
	                request: operationResponse.request,
	                response: operationResponse,
	            });
	            throw e;
	        }
	    }
	    return operationResponse;
	}

	// Copyright (c) Microsoft Corporation.
	/**
	 * Gets the list of status codes for streaming responses.
	 * @internal
	 */
	function getStreamingResponseStatusCodes(operationSpec) {
	    const result = new Set();
	    for (const statusCode in operationSpec.responses) {
	        const operationResponse = operationSpec.responses[statusCode];
	        if (operationResponse.bodyMapper &&
	            operationResponse.bodyMapper.type.name === MapperTypeNames.Stream) {
	            result.add(Number(statusCode));
	        }
	    }
	    return result;
	}
	/**
	 * Get the path to this parameter's value as a dotted string (a.b.c).
	 * @param parameter - The parameter to get the path string for.
	 * @returns The path to this parameter's value as a dotted string.
	 * @internal
	 */
	function getPathStringFromParameter(parameter) {
	    const { parameterPath, mapper } = parameter;
	    let result;
	    if (typeof parameterPath === "string") {
	        result = parameterPath;
	    }
	    else if (Array.isArray(parameterPath)) {
	        result = parameterPath.join(".");
	    }
	    else {
	        result = mapper.serializedName;
	    }
	    return result;
	}

	// Copyright (c) Microsoft Corporation.
	/**
	 * The programmatic identifier of the serializationPolicy.
	 */
	const serializationPolicyName = "serializationPolicy";
	/**
	 * This policy handles assembling the request body and headers using
	 * an OperationSpec and OperationArguments on the request.
	 */
	function serializationPolicy(options = {}) {
	    const stringifyXML = options.stringifyXML;
	    return {
	        name: serializationPolicyName,
	        async sendRequest(request, next) {
	            const operationInfo = getOperationRequestInfo(request);
	            const operationSpec = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationSpec;
	            const operationArguments = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationArguments;
	            if (operationSpec && operationArguments) {
	                serializeHeaders(request, operationArguments, operationSpec);
	                serializeRequestBody(request, operationArguments, operationSpec, stringifyXML);
	            }
	            return next(request);
	        },
	    };
	}
	/**
	 * @internal
	 */
	function serializeHeaders(request, operationArguments, operationSpec) {
	    var _a, _b;
	    if (operationSpec.headerParameters) {
	        for (const headerParameter of operationSpec.headerParameters) {
	            let headerValue = getOperationArgumentValueFromParameter(operationArguments, headerParameter);
	            if ((headerValue !== null && headerValue !== undefined) || headerParameter.mapper.required) {
	                headerValue = operationSpec.serializer.serialize(headerParameter.mapper, headerValue, getPathStringFromParameter(headerParameter));
	                const headerCollectionPrefix = headerParameter.mapper
	                    .headerCollectionPrefix;
	                if (headerCollectionPrefix) {
	                    for (const key of Object.keys(headerValue)) {
	                        request.headers.set(headerCollectionPrefix + key, headerValue[key]);
	                    }
	                }
	                else {
	                    request.headers.set(headerParameter.mapper.serializedName || getPathStringFromParameter(headerParameter), headerValue);
	                }
	            }
	        }
	    }
	    const customHeaders = (_b = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.requestOptions) === null || _b === void 0 ? void 0 : _b.customHeaders;
	    if (customHeaders) {
	        for (const customHeaderName of Object.keys(customHeaders)) {
	            request.headers.set(customHeaderName, customHeaders[customHeaderName]);
	        }
	    }
	}
	/**
	 * @internal
	 */
	function serializeRequestBody(request, operationArguments, operationSpec, stringifyXML = function () {
	    throw new Error("XML serialization unsupported!");
	}) {
	    var _a, _b, _c, _d, _e;
	    const serializerOptions = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.serializerOptions;
	    const updatedOptions = {
	        xml: {
	            rootName: (_b = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.rootName) !== null && _b !== void 0 ? _b : "",
	            includeRoot: (_c = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.includeRoot) !== null && _c !== void 0 ? _c : false,
	            xmlCharKey: (_d = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.xmlCharKey) !== null && _d !== void 0 ? _d : XML_CHARKEY,
	        },
	    };
	    const xmlCharKey = updatedOptions.xml.xmlCharKey;
	    if (operationSpec.requestBody && operationSpec.requestBody.mapper) {
	        request.body = getOperationArgumentValueFromParameter(operationArguments, operationSpec.requestBody);
	        const bodyMapper = operationSpec.requestBody.mapper;
	        const { required, serializedName, xmlName, xmlElementName, xmlNamespace, xmlNamespacePrefix, nullable, } = bodyMapper;
	        const typeName = bodyMapper.type.name;
	        try {
	            if ((request.body !== undefined && request.body !== null) ||
	                (nullable && request.body === null) ||
	                required) {
	                const requestBodyParameterPathString = getPathStringFromParameter(operationSpec.requestBody);
	                request.body = operationSpec.serializer.serialize(bodyMapper, request.body, requestBodyParameterPathString, updatedOptions);
	                const isStream = typeName === MapperTypeNames.Stream;
	                if (operationSpec.isXML) {
	                    const xmlnsKey = xmlNamespacePrefix ? `xmlns:${xmlNamespacePrefix}` : "xmlns";
	                    const value = getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, request.body, updatedOptions);
	                    if (typeName === MapperTypeNames.Sequence) {
	                        request.body = stringifyXML(prepareXMLRootList(value, xmlElementName || xmlName || serializedName, xmlnsKey, xmlNamespace), { rootName: xmlName || serializedName, xmlCharKey });
	                    }
	                    else if (!isStream) {
	                        request.body = stringifyXML(value, {
	                            rootName: xmlName || serializedName,
	                            xmlCharKey,
	                        });
	                    }
	                }
	                else if (typeName === MapperTypeNames.String &&
	                    (((_e = operationSpec.contentType) === null || _e === void 0 ? void 0 : _e.match("text/plain")) || operationSpec.mediaType === "text")) {
	                    // the String serializer has validated that request body is a string
	                    // so just send the string.
	                    return;
	                }
	                else if (!isStream) {
	                    request.body = JSON.stringify(request.body);
	                }
	            }
	        }
	        catch (error) {
	            throw new Error(`Error "${error.message}" occurred in serializing the payload - ${JSON.stringify(serializedName, undefined, "  ")}.`);
	        }
	    }
	    else if (operationSpec.formDataParameters && operationSpec.formDataParameters.length > 0) {
	        request.formData = {};
	        for (const formDataParameter of operationSpec.formDataParameters) {
	            const formDataParameterValue = getOperationArgumentValueFromParameter(operationArguments, formDataParameter);
	            if (formDataParameterValue !== undefined && formDataParameterValue !== null) {
	                const formDataParameterPropertyName = formDataParameter.mapper.serializedName || getPathStringFromParameter(formDataParameter);
	                request.formData[formDataParameterPropertyName] = operationSpec.serializer.serialize(formDataParameter.mapper, formDataParameterValue, getPathStringFromParameter(formDataParameter), updatedOptions);
	            }
	        }
	    }
	}
	/**
	 * Adds an xml namespace to the xml serialized object if needed, otherwise it just returns the value itself
	 */
	function getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, serializedValue, options) {
	    // Composite and Sequence schemas already got their root namespace set during serialization
	    // We just need to add xmlns to the other schema types
	    if (xmlNamespace && !["Composite", "Sequence", "Dictionary"].includes(typeName)) {
	        const result = {};
	        result[options.xml.xmlCharKey] = serializedValue;
	        result[XML_ATTRKEY] = { [xmlnsKey]: xmlNamespace };
	        return result;
	    }
	    return serializedValue;
	}
	function prepareXMLRootList(obj, elementName, xmlNamespaceKey, xmlNamespace) {
	    if (!Array.isArray(obj)) {
	        obj = [obj];
	    }
	    if (!xmlNamespaceKey || !xmlNamespace) {
	        return { [elementName]: obj };
	    }
	    const result = { [elementName]: obj };
	    result[XML_ATTRKEY] = { [xmlNamespaceKey]: xmlNamespace };
	    return result;
	}

	// Copyright (c) Microsoft Corporation.
	/**
	 * Creates a new Pipeline for use with a Service Client.
	 * Adds in deserializationPolicy by default.
	 * Also adds in bearerTokenAuthenticationPolicy if passed a TokenCredential.
	 * @param options - Options to customize the created pipeline.
	 */
	function createClientPipeline(options = {}) {
	    const pipeline = createPipelineFromOptions(options !== null && options !== void 0 ? options : {});
	    if (options.credentialOptions) {
	        pipeline.addPolicy(bearerTokenAuthenticationPolicy({
	            credential: options.credentialOptions.credential,
	            scopes: options.credentialOptions.credentialScopes,
	        }));
	    }
	    pipeline.addPolicy(serializationPolicy(options.serializationOptions), { phase: "Serialize" });
	    pipeline.addPolicy(deserializationPolicy(options.deserializationOptions), {
	        phase: "Deserialize",
	    });
	    return pipeline;
	}

	// Copyright (c) Microsoft Corporation.
	let cachedHttpClient;
	function getCachedDefaultHttpClient() {
	    if (!cachedHttpClient) {
	        cachedHttpClient = createDefaultHttpClient();
	    }
	    return cachedHttpClient;
	}

	// Copyright (c) Microsoft Corporation.
	const CollectionFormatToDelimiterMap = {
	    CSV: ",",
	    SSV: " ",
	    Multi: "Multi",
	    TSV: "\t",
	    Pipes: "|",
	};
	function getRequestUrl(baseUri, operationSpec, operationArguments, fallbackObject) {
	    const urlReplacements = calculateUrlReplacements(operationSpec, operationArguments, fallbackObject);
	    let isAbsolutePath = false;
	    let requestUrl = replaceAll(baseUri, urlReplacements);
	    if (operationSpec.path) {
	        let path = replaceAll(operationSpec.path, urlReplacements);
	        // QUIRK: sometimes we get a path component like /{nextLink}
	        // which may be a fully formed URL with a leading /. In that case, we should
	        // remove the leading /
	        if (operationSpec.path === "/{nextLink}" && path.startsWith("/")) {
	            path = path.substring(1);
	        }
	        // QUIRK: sometimes we get a path component like {nextLink}
	        // which may be a fully formed URL. In that case, we should
	        // ignore the baseUri.
	        if (isAbsoluteUrl(path)) {
	            requestUrl = path;
	            isAbsolutePath = true;
	        }
	        else {
	            requestUrl = appendPath(requestUrl, path);
	        }
	    }
	    const { queryParams, sequenceParams } = calculateQueryParameters(operationSpec, operationArguments, fallbackObject);
	    /**
	     * Notice that this call sets the `noOverwrite` parameter to true if the `requestUrl`
	     * is an absolute path. This ensures that existing query parameter values in `requestUrl`
	     * do not get overwritten. On the other hand when `requestUrl` is not absolute path, it
	     * is still being built so there is nothing to overwrite.
	     */
	    requestUrl = appendQueryParams(requestUrl, queryParams, sequenceParams, isAbsolutePath);
	    return requestUrl;
	}
	function replaceAll(input, replacements) {
	    let result = input;
	    for (const [searchValue, replaceValue] of replacements) {
	        result = result.split(searchValue).join(replaceValue);
	    }
	    return result;
	}
	function calculateUrlReplacements(operationSpec, operationArguments, fallbackObject) {
	    var _a;
	    const result = new Map();
	    if ((_a = operationSpec.urlParameters) === null || _a === void 0 ? void 0 : _a.length) {
	        for (const urlParameter of operationSpec.urlParameters) {
	            let urlParameterValue = getOperationArgumentValueFromParameter(operationArguments, urlParameter, fallbackObject);
	            const parameterPathString = getPathStringFromParameter(urlParameter);
	            urlParameterValue = operationSpec.serializer.serialize(urlParameter.mapper, urlParameterValue, parameterPathString);
	            if (!urlParameter.skipEncoding) {
	                urlParameterValue = encodeURIComponent(urlParameterValue);
	            }
	            result.set(`{${urlParameter.mapper.serializedName || parameterPathString}}`, urlParameterValue);
	        }
	    }
	    return result;
	}
	function isAbsoluteUrl(url) {
	    return url.includes("://");
	}
	function appendPath(url, pathToAppend) {
	    if (!pathToAppend) {
	        return url;
	    }
	    const parsedUrl = new URL(url);
	    let newPath = parsedUrl.pathname;
	    if (!newPath.endsWith("/")) {
	        newPath = `${newPath}/`;
	    }
	    if (pathToAppend.startsWith("/")) {
	        pathToAppend = pathToAppend.substring(1);
	    }
	    const searchStart = pathToAppend.indexOf("?");
	    if (searchStart !== -1) {
	        const path = pathToAppend.substring(0, searchStart);
	        const search = pathToAppend.substring(searchStart + 1);
	        newPath = newPath + path;
	        if (search) {
	            parsedUrl.search = parsedUrl.search ? `${parsedUrl.search}&${search}` : search;
	        }
	    }
	    else {
	        newPath = newPath + pathToAppend;
	    }
	    parsedUrl.pathname = newPath;
	    return parsedUrl.toString();
	}
	function calculateQueryParameters(operationSpec, operationArguments, fallbackObject) {
	    var _a;
	    const result = new Map();
	    const sequenceParams = new Set();
	    if ((_a = operationSpec.queryParameters) === null || _a === void 0 ? void 0 : _a.length) {
	        for (const queryParameter of operationSpec.queryParameters) {
	            if (queryParameter.mapper.type.name === "Sequence" && queryParameter.mapper.serializedName) {
	                sequenceParams.add(queryParameter.mapper.serializedName);
	            }
	            let queryParameterValue = getOperationArgumentValueFromParameter(operationArguments, queryParameter, fallbackObject);
	            if ((queryParameterValue !== undefined && queryParameterValue !== null) ||
	                queryParameter.mapper.required) {
	                queryParameterValue = operationSpec.serializer.serialize(queryParameter.mapper, queryParameterValue, getPathStringFromParameter(queryParameter));
	                const delimiter = queryParameter.collectionFormat
	                    ? CollectionFormatToDelimiterMap[queryParameter.collectionFormat]
	                    : "";
	                if (Array.isArray(queryParameterValue)) {
	                    // replace null and undefined
	                    queryParameterValue = queryParameterValue.map((item) => {
	                        if (item === null || item === undefined) {
	                            return "";
	                        }
	                        return item;
	                    });
	                }
	                if (queryParameter.collectionFormat === "Multi" && queryParameterValue.length === 0) {
	                    continue;
	                }
	                else if (Array.isArray(queryParameterValue) &&
	                    (queryParameter.collectionFormat === "SSV" || queryParameter.collectionFormat === "TSV")) {
	                    queryParameterValue = queryParameterValue.join(delimiter);
	                }
	                if (!queryParameter.skipEncoding) {
	                    if (Array.isArray(queryParameterValue)) {
	                        queryParameterValue = queryParameterValue.map((item) => {
	                            return encodeURIComponent(item);
	                        });
	                    }
	                    else {
	                        queryParameterValue = encodeURIComponent(queryParameterValue);
	                    }
	                }
	                // Join pipes and CSV *after* encoding, or the server will be upset.
	                if (Array.isArray(queryParameterValue) &&
	                    (queryParameter.collectionFormat === "CSV" || queryParameter.collectionFormat === "Pipes")) {
	                    queryParameterValue = queryParameterValue.join(delimiter);
	                }
	                result.set(queryParameter.mapper.serializedName || getPathStringFromParameter(queryParameter), queryParameterValue);
	            }
	        }
	    }
	    return {
	        queryParams: result,
	        sequenceParams,
	    };
	}
	function simpleParseQueryParams(queryString) {
	    const result = new Map();
	    if (!queryString || queryString[0] !== "?") {
	        return result;
	    }
	    // remove the leading ?
	    queryString = queryString.slice(1);
	    const pairs = queryString.split("&");
	    for (const pair of pairs) {
	        const [name, value] = pair.split("=", 2);
	        const existingValue = result.get(name);
	        if (existingValue) {
	            if (Array.isArray(existingValue)) {
	                existingValue.push(value);
	            }
	            else {
	                result.set(name, [existingValue, value]);
	            }
	        }
	        else {
	            result.set(name, value);
	        }
	    }
	    return result;
	}
	/** @internal */
	function appendQueryParams(url, queryParams, sequenceParams, noOverwrite = false) {
	    if (queryParams.size === 0) {
	        return url;
	    }
	    const parsedUrl = new URL(url);
	    // QUIRK: parsedUrl.searchParams will have their name/value pairs decoded, which
	    // can change their meaning to the server, such as in the case of a SAS signature.
	    // To avoid accidentally un-encoding a query param, we parse the key/values ourselves
	    const combinedParams = simpleParseQueryParams(parsedUrl.search);
	    for (const [name, value] of queryParams) {
	        const existingValue = combinedParams.get(name);
	        if (Array.isArray(existingValue)) {
	            if (Array.isArray(value)) {
	                existingValue.push(...value);
	                const valueSet = new Set(existingValue);
	                combinedParams.set(name, Array.from(valueSet));
	            }
	            else {
	                existingValue.push(value);
	            }
	        }
	        else if (existingValue) {
	            if (Array.isArray(value)) {
	                value.unshift(existingValue);
	            }
	            else if (sequenceParams.has(name)) {
	                combinedParams.set(name, [existingValue, value]);
	            }
	            if (!noOverwrite) {
	                combinedParams.set(name, value);
	            }
	        }
	        else {
	            combinedParams.set(name, value);
	        }
	    }
	    const searchPieces = [];
	    for (const [name, value] of combinedParams) {
	        if (typeof value === "string") {
	            searchPieces.push(`${name}=${value}`);
	        }
	        else if (Array.isArray(value)) {
	            // QUIRK: If we get an array of values, include multiple key/value pairs
	            for (const subValue of value) {
	                searchPieces.push(`${name}=${subValue}`);
	            }
	        }
	        else {
	            searchPieces.push(`${name}=${value}`);
	        }
	    }
	    // QUIRK: we have to set search manually as searchParams will encode comma when it shouldn't.
	    parsedUrl.search = searchPieces.length ? `?${searchPieces.join("&")}` : "";
	    return parsedUrl.toString();
	}

	// Copyright (c) Microsoft Corporation.
	const logger = createClientLogger("core-client");

	// Copyright (c) Microsoft Corporation.
	/**
	 * Initializes a new instance of the ServiceClient.
	 */
	class ServiceClient {
	    /**
	     * The ServiceClient constructor
	     * @param credential - The credentials used for authentication with the service.
	     * @param options - The service client options that govern the behavior of the client.
	     */
	    constructor(options = {}) {
	        var _a, _b;
	        this._requestContentType = options.requestContentType;
	        this._endpoint = (_a = options.endpoint) !== null && _a !== void 0 ? _a : options.baseUri;
	        if (options.baseUri) {
	            logger.warning("The baseUri option for SDK Clients has been deprecated, please use endpoint instead.");
	        }
	        this._allowInsecureConnection = options.allowInsecureConnection;
	        this._httpClient = options.httpClient || getCachedDefaultHttpClient();
	        this.pipeline = options.pipeline || createDefaultPipeline(options);
	        if ((_b = options.additionalPolicies) === null || _b === void 0 ? void 0 : _b.length) {
	            for (const { policy, position } of options.additionalPolicies) {
	                // Sign happens after Retry and is commonly needed to occur
	                // before policies that intercept post-retry.
	                const afterPhase = position === "perRetry" ? "Sign" : undefined;
	                this.pipeline.addPolicy(policy, {
	                    afterPhase,
	                });
	            }
	        }
	    }
	    /**
	     * Send the provided httpRequest.
	     */
	    async sendRequest(request) {
	        return this.pipeline.sendRequest(this._httpClient, request);
	    }
	    /**
	     * Send an HTTP request that is populated using the provided OperationSpec.
	     * @typeParam T - The typed result of the request, based on the OperationSpec.
	     * @param operationArguments - The arguments that the HTTP request's templated values will be populated from.
	     * @param operationSpec - The OperationSpec to use to populate the httpRequest.
	     */
	    async sendOperationRequest(operationArguments, operationSpec) {
	        const endpoint = operationSpec.baseUrl || this._endpoint;
	        if (!endpoint) {
	            throw new Error("If operationSpec.baseUrl is not specified, then the ServiceClient must have a endpoint string property that contains the base URL to use.");
	        }
	        // Templatized URLs sometimes reference properties on the ServiceClient child class,
	        // so we have to pass `this` below in order to search these properties if they're
	        // not part of OperationArguments
	        const url = getRequestUrl(endpoint, operationSpec, operationArguments, this);
	        const request = createPipelineRequest({
	            url,
	        });
	        request.method = operationSpec.httpMethod;
	        const operationInfo = getOperationRequestInfo(request);
	        operationInfo.operationSpec = operationSpec;
	        operationInfo.operationArguments = operationArguments;
	        const contentType = operationSpec.contentType || this._requestContentType;
	        if (contentType && operationSpec.requestBody) {
	            request.headers.set("Content-Type", contentType);
	        }
	        const options = operationArguments.options;
	        if (options) {
	            const requestOptions = options.requestOptions;
	            if (requestOptions) {
	                if (requestOptions.timeout) {
	                    request.timeout = requestOptions.timeout;
	                }
	                if (requestOptions.onUploadProgress) {
	                    request.onUploadProgress = requestOptions.onUploadProgress;
	                }
	                if (requestOptions.onDownloadProgress) {
	                    request.onDownloadProgress = requestOptions.onDownloadProgress;
	                }
	                if (requestOptions.shouldDeserialize !== undefined) {
	                    operationInfo.shouldDeserialize = requestOptions.shouldDeserialize;
	                }
	                if (requestOptions.allowInsecureConnection) {
	                    request.allowInsecureConnection = true;
	                }
	            }
	            if (options.abortSignal) {
	                request.abortSignal = options.abortSignal;
	            }
	            if (options.tracingOptions) {
	                request.tracingOptions = options.tracingOptions;
	            }
	        }
	        if (this._allowInsecureConnection) {
	            request.allowInsecureConnection = true;
	        }
	        if (request.streamResponseStatusCodes === undefined) {
	            request.streamResponseStatusCodes = getStreamingResponseStatusCodes(operationSpec);
	        }
	        try {
	            const rawResponse = await this.sendRequest(request);
	            const flatResponse = flattenResponse(rawResponse, operationSpec.responses[rawResponse.status]);
	            if (options === null || options === void 0 ? void 0 : options.onResponse) {
	                options.onResponse(rawResponse, flatResponse);
	            }
	            return flatResponse;
	        }
	        catch (error) {
	            if (typeof error === "object" && (error === null || error === void 0 ? void 0 : error.response)) {
	                const rawResponse = error.response;
	                const flatResponse = flattenResponse(rawResponse, operationSpec.responses[error.statusCode] || operationSpec.responses["default"]);
	                error.details = flatResponse;
	                if (options === null || options === void 0 ? void 0 : options.onResponse) {
	                    options.onResponse(rawResponse, flatResponse, error);
	                }
	            }
	            throw error;
	        }
	    }
	}
	function createDefaultPipeline(options) {
	    const credentialScopes = getCredentialScopes(options);
	    const credentialOptions = options.credential && credentialScopes
	        ? { credentialScopes, credential: options.credential }
	        : undefined;
	    return createClientPipeline(Object.assign(Object.assign({}, options), { credentialOptions }));
	}
	function getCredentialScopes(options) {
	    if (options.credentialScopes) {
	        return options.credentialScopes;
	    }
	    if (options.endpoint) {
	        return `${options.endpoint}/.default`;
	    }
	    if (options.baseUri) {
	        return `${options.baseUri}/.default`;
	    }
	    if (options.credential && !options.credentialScopes) {
	        throw new Error(`When using credentials, the ServiceClientOptions must contain either a endpoint or a credentialScopes. Unable to create a bearerTokenAuthenticationPolicy`);
	    }
	    return undefined;
	}

	// Copyright (c) Microsoft Corporation.
	/**
	 * Converts: `Bearer a="b", c="d", Bearer d="e", f="g"`.
	 * Into: `[ { a: 'b', c: 'd' }, { d: 'e', f: 'g' } ]`.
	 *
	 * @internal
	 */
	function parseCAEChallenge(challenges) {
	    const bearerChallenges = `, ${challenges.trim()}`.split(", Bearer ").filter((x) => x);
	    return bearerChallenges.map((challenge) => {
	        const challengeParts = `${challenge.trim()}, `.split('", ').filter((x) => x);
	        const keyValuePairs = challengeParts.map((keyValue) => (([key, value]) => ({ [key]: value }))(keyValue.trim().split('="')));
	        // Key-value pairs to plain object:
	        return keyValuePairs.reduce((a, b) => (Object.assign(Object.assign({}, a), b)), {});
	    });
	}
	/**
	 * This function can be used as a callback for the `bearerTokenAuthenticationPolicy` of `@azure/core-rest-pipeline`, to support CAE challenges:
	 * [Continuous Access Evaluation](https://docs.microsoft.com/azure/active-directory/conditional-access/concept-continuous-access-evaluation).
	 *
	 * Call the `bearerTokenAuthenticationPolicy` with the following options:
	 *
	 * ```ts
	 * import { bearerTokenAuthenticationPolicy } from "@azure/core-rest-pipeline";
	 * import { authorizeRequestOnClaimChallenge } from "@azure/core-client";
	 *
	 * const bearerTokenAuthenticationPolicy = bearerTokenAuthenticationPolicy({
	 *   authorizeRequestOnChallenge: authorizeRequestOnClaimChallenge
	 * });
	 * ```
	 *
	 * Once provided, the `bearerTokenAuthenticationPolicy` policy will internally handle Continuous Access Evaluation (CAE) challenges.
	 * When it can't complete a challenge it will return the 401 (unauthorized) response from ARM.
	 *
	 * Example challenge with claims:
	 *
	 * ```
	 * Bearer authorization_uri="https://login.windows-ppe.net/", error="invalid_token",
	 * error_description="User session has been revoked",
	 * claims="eyJhY2Nlc3NfdG9rZW4iOnsibmJmIjp7ImVzc2VudGlhbCI6dHJ1ZSwgInZhbHVlIjoiMTYwMzc0MjgwMCJ9fX0="
	 * ```
	 */
	async function authorizeRequestOnClaimChallenge(onChallengeOptions) {
	    const { scopes, response } = onChallengeOptions;
	    const logger$1 = onChallengeOptions.logger || logger;
	    const challenge = response.headers.get("WWW-Authenticate");
	    if (!challenge) {
	        logger$1.info(`The WWW-Authenticate header was missing. Failed to perform the Continuous Access Evaluation authentication flow.`);
	        return false;
	    }
	    const challenges = parseCAEChallenge(challenge) || [];
	    const parsedChallenge = challenges.find((x) => x.claims);
	    if (!parsedChallenge) {
	        logger$1.info(`The WWW-Authenticate header was missing the necessary "claims" to perform the Continuous Access Evaluation authentication flow.`);
	        return false;
	    }
	    const accessToken = await onChallengeOptions.getAccessToken(parsedChallenge.scope ? [parsedChallenge.scope] : scopes, {
	        claims: decodeStringToString(parsedChallenge.claims),
	    });
	    if (!accessToken) {
	        return false;
	    }
	    onChallengeOptions.request.headers.set("Authorization", `Bearer ${accessToken.token}`);
	    return true;
	}

	// Copyright (c) Microsoft Corporation.
	// Licensed under the MIT license.
	/**
	 * A set of constants used internally when processing requests.
	 */
	const Constants = {
	    DefaultScope: "/.default",
	    /**
	     * Defines constants for use with HTTP headers.
	     */
	    HeaderConstants: {
	        /**
	         * The Authorization header.
	         */
	        AUTHORIZATION: "authorization",
	    },
	};
	function isUuid(text) {
	    return /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/.test(text);
	}
	/**
	 * Defines a callback to handle auth challenge for Storage APIs.
	 * This implements the bearer challenge process described here: https://docs.microsoft.com/rest/api/storageservices/authorize-with-azure-active-directory#bearer-challenge
	 * Handling has specific features for storage that departs to the general AAD challenge docs.
	 **/
	const authorizeRequestOnTenantChallenge = async (challengeOptions) => {
	    const requestOptions = requestToOptions(challengeOptions.request);
	    const challenge = getChallenge(challengeOptions.response);
	    if (challenge) {
	        const challengeInfo = parseChallenge(challenge);
	        const challengeScopes = buildScopes(challengeOptions, challengeInfo);
	        const tenantId = extractTenantId(challengeInfo);
	        if (!tenantId) {
	            return false;
	        }
	        const accessToken = await challengeOptions.getAccessToken(challengeScopes, Object.assign(Object.assign({}, requestOptions), { tenantId }));
	        if (!accessToken) {
	            return false;
	        }
	        challengeOptions.request.headers.set(Constants.HeaderConstants.AUTHORIZATION, `Bearer ${accessToken.token}`);
	        return true;
	    }
	    return false;
	};
	/**
	 * Extracts the tenant id from the challenge information
	 * The tenant id is contained in the authorization_uri as the first
	 * path part.
	 */
	function extractTenantId(challengeInfo) {
	    const parsedAuthUri = new URL(challengeInfo.authorization_uri);
	    const pathSegments = parsedAuthUri.pathname.split("/");
	    const tenantId = pathSegments[1];
	    if (tenantId && isUuid(tenantId)) {
	        return tenantId;
	    }
	    return undefined;
	}
	/**
	 * Builds the authentication scopes based on the information that comes in the
	 * challenge information. Scopes url is present in the resource_id, if it is empty
	 * we keep using the original scopes.
	 */
	function buildScopes(challengeOptions, challengeInfo) {
	    if (!challengeInfo.resource_id) {
	        return challengeOptions.scopes;
	    }
	    const challengeScopes = new URL(challengeInfo.resource_id);
	    challengeScopes.pathname = Constants.DefaultScope;
	    let scope = challengeScopes.toString();
	    if (scope === "https://disk.azure.com/.default") {
	        // the extra slash is required by the service
	        scope = "https://disk.azure.com//.default";
	    }
	    return [scope];
	}
	/**
	 * We will retrieve the challenge only if the response status code was 401,
	 * and if the response contained the header "WWW-Authenticate" with a non-empty value.
	 */
	function getChallenge(response) {
	    const challenge = response.headers.get("WWW-Authenticate");
	    if (response.status === 401 && challenge) {
	        return challenge;
	    }
	    return;
	}
	/**
	 * Converts: `Bearer a="b" c="d"`.
	 * Into: `[ { a: 'b', c: 'd' }]`.
	 *
	 * @internal
	 */
	function parseChallenge(challenge) {
	    const bearerChallenge = challenge.slice("Bearer ".length);
	    const challengeParts = `${bearerChallenge.trim()} `.split(" ").filter((x) => x);
	    const keyValuePairs = challengeParts.map((keyValue) => (([key, value]) => ({ [key]: value }))(keyValue.trim().split("=")));
	    // Key-value pairs to plain object:
	    return keyValuePairs.reduce((a, b) => (Object.assign(Object.assign({}, a), b)), {});
	}
	/**
	 * Extracts the options form a Pipeline Request for later re-use
	 */
	function requestToOptions(request) {
	    return {
	        abortSignal: request.abortSignal,
	        requestOptions: {
	            timeout: request.timeout,
	        },
	        tracingOptions: request.tracingOptions,
	    };
	}

	// Copyright (c) Microsoft Corporation.

	var browser = /*#__PURE__*/Object.freeze({
		__proto__: null,
		createSerializer: createSerializer,
		MapperTypeNames: MapperTypeNames,
		ServiceClient: ServiceClient,
		createClientPipeline: createClientPipeline,
		XML_ATTRKEY: XML_ATTRKEY,
		XML_CHARKEY: XML_CHARKEY,
		deserializationPolicy: deserializationPolicy,
		deserializationPolicyName: deserializationPolicyName,
		serializationPolicy: serializationPolicy,
		serializationPolicyName: serializationPolicyName,
		authorizeRequestOnClaimChallenge: authorizeRequestOnClaimChallenge,
		authorizeRequestOnTenantChallenge: authorizeRequestOnTenantChallenge
	});

	var TrouterConfigClient_1$1 = createCommonjsModule(function (module, exports) {
	// Copyright (c) Microsoft Corporation.
	// Licensed under the MIT license.
	var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
	    if (k2 === undefined) k2 = k;
	    var desc = Object.getOwnPropertyDescriptor(m, k);
	    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
	      desc = { enumerable: true, get: function() { return m[k]; } };
	    }
	    Object.defineProperty(o, k2, desc);
	}) : (function(o, m, k, k2) {
	    if (k2 === undefined) k2 = k;
	    o[k2] = m[k];
	}));
	var __setModuleDefault = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
	    Object.defineProperty(o, "default", { enumerable: true, value: v });
	}) : function(o, v) {
	    o["default"] = v;
	});
	var __importStar = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
	    if (mod && mod.__esModule) return mod;
	    var result = {};
	    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
	    __setModuleDefault(result, mod);
	    return result;
	};
	var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
	    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
	    return new (P || (P = Promise))(function (resolve, reject) {
	        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
	        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
	        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
	        step((generator = generator.apply(thisArg, _arguments || [])).next());
	    });
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.RealTimeNotificationConfiguration = exports.TrouterConfigClient = void 0;
	const coreClient = __importStar(browser); // External library import
	 // Grouped imports from the same module

	class TrouterConfigClient extends coreClient.ServiceClient {
	    constructor(endpoint, options) {
	        // Initializing default values for options
	        if (!options) {
	            options = {};
	        }
	        const packageDetails = `azsdk-js-communication-signaling/${constants_1.PACKAGE_VERSION}`;
	        const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix
	            ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}`
	            : `${packageDetails}`;
	        const clientOptions = Object.assign(Object.assign({}, options), { userAgentOptions: {
	                userAgentPrefix,
	            }, additionalPolicies: options.additionalPolicies });
	        super(clientOptions);
	        this.apiVersion = constants_1.CONFIG_API_VERSION;
	        this.endpoint = endpoint;
	        this.httpClient = (0, esm.createDefaultHttpClient)();
	    }
	    fetchServiceUrls(credential) {
	        return __awaiter(this, void 0, void 0, function* () {
	            try {
	                const token = (yield credential.getToken()).token;
	                const request = (0, esm.createPipelineRequest)({
	                    url: `${this.endpoint}/chat/config/realTimeNotifications?api-version=${this.apiVersion}`,
	                    method: "GET",
	                    headers: (0, esm.createHttpHeaders)({
	                        Authorization: `Bearer ${token}`,
	                    }),
	                });
	                const response = yield this.pipeline.sendRequest(this.httpClient, request);
	                if (response.status !== 200 || !response.bodyAsText) {
	                    throw new Error(`Failed to fetch service URLs. Status: ${response.status}, Body: ${response.bodyAsText || "No response body"}`);
	                }
	                const data = JSON.parse(response.bodyAsText);
	                // Ensure all necessary data fields are present
	                if (!data.trouterServiceUrl || !data.registrarServiceUrl || !data.cloudType) {
	                    throw new Error("One or more required fields are missing in the response data");
	                }
	                return new RealTimeNotificationConfiguration(data.trouterServiceUrl, data.registrarServiceUrl, data.cloudType);
	            }
	            catch (error) {
	                throw new Error(`Error fetching real-time notification configuration from Chat Gateway: ${error.message}`);
	            }
	        });
	    }
	}
	exports.TrouterConfigClient = TrouterConfigClient;
	class RealTimeNotificationConfiguration {
	    constructor(trouterServiceUrl, registrarServiceUrl, cloudType) {
	        this.trouterServiceUrl = trouterServiceUrl;
	        this.registrarServiceUrl = registrarServiceUrl;
	        this.cloudType = cloudType;
	    }
	}
	exports.RealTimeNotificationConfiguration = RealTimeNotificationConfiguration;
	});

	unwrapExports(TrouterConfigClient_1$1);
	TrouterConfigClient_1$1.RealTimeNotificationConfiguration;
	TrouterConfigClient_1$1.TrouterConfigClient;

	var TrouterUtils_1 = TrouterUtils;

	var TrouterConfigClient_1 = TrouterConfigClient_1$1;

	var TrouterSettings = createCommonjsModule(function (module, exports) {
	// Copyright (c) Microsoft Corporation.
	// Licensed under the MIT license.
	var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
	    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
	    return new (P || (P = Promise))(function (resolve, reject) {
	        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
	        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
	        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
	        step((generator = generator.apply(thisArg, _arguments || [])).next());
	    });
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.defaultTelemetrySettings = exports.createSettings = void 0;


	const defaultSettings = {
	    version: "1.0.0", // SignalingClient version, required for trouter connection
	    registrationId: "", // Required for trouter connection
	    sessionId: "", // Required for trouter connection
	    pnhAppId: "AcsWeb",
	    pnhTemplate: "AcsWeb_Chat_2.1",
	    platform: "SPOOL",
	    platformUIVersion: "0.0.0",
	    environment: "", // TBD
	    productName: "acs-chat-web",
	    trouterServiceUrl: "",
	    registrarServiceUrl: "",
	    registrarRefreshTimeoutInMs: 350000,
	    timeoutOptions: {
	        connectionTimeoutMs: 20000,
	        fetchTimeoutMs: 10000,
	        pingTimeoutMs: 40000,
	        pongTimeoutMs: 5000,
	        maxBackoffMs: 50000,
	        requestTimeoutMs: 5000,
	    },
	    maxRegistrationTimeInMs: 7200000,
	};
	// Main function to create settings based on environment
	const createSettings = (credential, options) => __awaiter(void 0, void 0, void 0, function* () {
	    var _a;
	    const endpoint = options === null || options === void 0 ? void 0 : options.resourceEndpoint;
	    // Throw an error if resourceEndpoint is null or undefined
	    if (endpoint === undefined) {
	        throw new Error("'endpoint' cannot be null");
	    }
	    // Initialize the settings by cloning the default ones
	    const settings = Object.assign({}, defaultSettings);
	    settings.registrationId = (0, TrouterUtils_1.generateUuid)(); // Generate unique IDs
	    settings.sessionId = (0, TrouterUtils_1.generateUuid)();
	    // Fetch the real time configuration from the service
	    const trouterConfigClient = new TrouterConfigClient_1.TrouterConfigClient(endpoint, options);
	    const realTimeNotificationConfiguration = yield trouterConfigClient.fetchServiceUrls(credential);
	    // Append suffix to trouterServiceUrl and registrarServiceUrl
	    settings.trouterServiceUrl = `${realTimeNotificationConfiguration.trouterServiceUrl}/v4/a`;
	    settings.registrarServiceUrl = `${realTimeNotificationConfiguration.registrarServiceUrl}/v3/registrations`;
	    // Customize settings if the environment is INT
	    if (realTimeNotificationConfiguration.cloudType === "int") {
	        settings.pnhAppId = "cns-e2e-test";
	        settings.pnhTemplate = "cns-e2e-test:1.8";
	    }
	    settings.maxRegistrationTimeInMs =
	        (_a = options === null || options === void 0 ? void 0 : options.registrationTimeInMs) !== null && _a !== void 0 ? _a : defaultSettings.maxRegistrationTimeInMs;
	    return settings;
	});
	exports.createSettings = createSettings;
	exports.defaultTelemetrySettings = {
	    // TBD Can we hook up OpenTelemetry?
	    enabled: false,
	};
	});

	unwrapExports(TrouterSettings);
	TrouterSettings.defaultTelemetrySettings;
	TrouterSettings.createSettings;

	var TrouterSettings_1 = TrouterSettings;

	var SignalingClient = createCommonjsModule(function (module, exports) {
	// Copyright (c) Microsoft Corporation.
	// Licensed under the MIT license.
	var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
	    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
	    return new (P || (P = Promise))(function (resolve, reject) {
	        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
	        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
	        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
	        step((generator = generator.apply(thisArg, _arguments || [])).next());
	    });
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.CommunicationSignalingClient = exports.ConnectionState = void 0;




	var ConnectionState;
	(function (ConnectionState) {
	    ConnectionState[ConnectionState["Unknown"] = 0] = "Unknown";
	    ConnectionState[ConnectionState["Connected"] = 2] = "Connected";
	    ConnectionState[ConnectionState["Disconnected"] = 3] = "Disconnected";
	    ConnectionState[ConnectionState["Switching"] = 9] = "Switching";
	})(ConnectionState || (exports.ConnectionState = ConnectionState = {}));
	class CommunicationSignalingClient {
	    constructor(credential, logger, options) {
	        this.credential = credential;
	        this.logger = logger;
	        this.options = options;
	        this.stateChangedListener = null;
	        this.tokenFetchRetries = 0;
	        this.trouter = (0, tstrouter.createTrouterService)((0, TrouterUtils_1.toLogProvider)(logger));
	    }
	    start() {
	        return __awaiter(this, void 0, void 0, function* () {
	            var _a, _b;
	            this.resourceEndpoint = (_a = this.options) === null || _a === void 0 ? void 0 : _a.resourceEndpoint;
	            if (this.resourceEndpoint === undefined) {
	                throw new Error("'endpoint' cannot be null");
	            }
	            this.gatewayApiVersion = ((_b = this.options) === null || _b === void 0 ? void 0 : _b.gatewayApiVersion) || "2024-03-07";
	            if (this.config === undefined) {
	                this.config = {
	                    trouterSettings: yield (0, TrouterSettings_1.createSettings)(this.credential, this.options),
	                    skypeTokenProvider: (forceRefresh) => __awaiter(this, void 0, void 0, function* () {
	                        if (forceRefresh) {
	                            this.tokenFetchRetries += 1;
	                            if (this.tokenFetchRetries > constants_1.MAX_NUMBER_OF_TOKEN_FETCH_RETRIES) {
	                                yield this.stop(true);
	                                throw new Error(`Access token is expired and failed to fetch a valid one after ${constants_1.MAX_NUMBER_OF_TOKEN_FETCH_RETRIES} retries`);
	                            }
	                        }
	                        else {
	                            this.tokenFetchRetries = 0;
	                        }
	                        return Promise.resolve((yield this.credential.getToken()).token);
	                    }),
	                    telemetryConfig: {
	                        eventLogger: (0, TrouterUtils_1.toTelemetrySender)(this.logger),
	                        settings: TrouterSettings_1.defaultTelemetrySettings,
	                    },
	                };
	            }
	            this.trouter.start(this.config);
	            this.trouter.setUserActivityState(tstrouter.UserActivityState.Active);
	        });
	    }
	    stop(isTokenExpired) {
	        return __awaiter(this, void 0, void 0, function* () {
	            this.trouter.offStateChanged(this.stateChangedListener);
	            this.trouter.clearMessageHandlers();
	            this.trouter.stop(isTokenExpired !== null && isTokenExpired !== void 0 ? isTokenExpired : this.tokenFetchRetries > constants_1.MAX_NUMBER_OF_TOKEN_FETCH_RETRIES);
	        });
	    }
	    on(event, listener) {
	        if (event === "connectionChanged") {
	            this.trouter.offStateChanged(this.stateChangedListener);
	            this.stateChangedListener = (state, _url) => listener(state);
	            this.trouter.onStateChanged(this.stateChangedListener);
	            return;
	        }
	        this.trouter.registerMessageHandler((0, TrouterUtils_1.toMessageHandler)(event, listener, this.resourceEndpoint, this.gatewayApiVersion));
	    }
	}
	exports.CommunicationSignalingClient = CommunicationSignalingClient;
	});

	unwrapExports(SignalingClient);
	SignalingClient.CommunicationSignalingClient;
	SignalingClient.ConnectionState;

	var require$$0 = SignalingClient;

	var src = createCommonjsModule(function (module, exports) {
	// Copyright (c) Microsoft Corporation.
	// Licensed under the MIT license.
	var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
	    if (k2 === undefined) k2 = k;
	    var desc = Object.getOwnPropertyDescriptor(m, k);
	    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
	      desc = { enumerable: true, get: function() { return m[k]; } };
	    }
	    Object.defineProperty(o, k2, desc);
	}) : (function(o, m, k, k2) {
	    if (k2 === undefined) k2 = k;
	    o[k2] = m[k];
	}));
	var __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m, exports) {
	    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	__exportStar(require$$0, exports);
	});

	var index = unwrapExports(src);

	return index;

}));
//# sourceMappingURL=azure-communicationservices-signaling.js.map