@interopio/browser-platform 4.4.1-beta.0 → 4.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -56,5 +56,5 @@ var jsonParse=function(){var e=new RegExp('(?:false|true|null|[\\{\\}\\[\\]]|(?:
56
56
  * Copyright (c) 2014-2017, Jon Schlinkert.
57
57
  * Released under the MIT License.
58
58
  */
59
- function e(e){return"[object Object]"===Object.prototype.toString.call(e)}return hasRequiredIsPlainObject=1,Object.defineProperty(isPlainObject$3,"__esModule",{value:!0}),isPlainObject$3.isPlainObject=function(t){let r,n;if(!1===e(t))return!1;if(r=t.constructor,void 0===r)return!0;if(n=r.prototype,!1===e(n))return!1;if(!1===n.hasOwnProperty("isPrototypeOf"))return!1;return!0},isPlainObject$3}function requireSafeStringify(){if(hasRequiredSafeStringify)return safeStringify;hasRequiredSafeStringify=1,Object.defineProperty(safeStringify,"__esModule",{value:!0}),safeStringify.safeStringify=function(t){if(!t)return JSON.stringify(t);return JSON.stringify(t,(t,r)=>r&&"object"==typeof r?(0,e.isPlainObject)(r)?r:Object.prototype.toString.call(r):r)};const e=requireIsPlainObject();return safeStringify}var _null$1$1={},hasRequired_null$1,hasRequiredNullMetricsManager,hasRequiredBuilder$3;function require_null$1(){if(hasRequired_null$1)return _null$1$1;hasRequired_null$1=1,Object.defineProperty(_null$1$1,"__esModule",{value:!0}),_null$1$1.NullMetric=void 0;return _null$1$1.NullMetric=class{constructor(e,t){this.settings=e,this.logger=t,this.started=!1}start(){var e;return null===(e=this.logger)||void 0===e||e.debug(`null metric has been started instead of ${this.settings.type} one`),this.started=!0,Promise.resolve()}stop(){var e;return null===(e=this.logger)||void 0===e||e.debug(`null metric has been stopped instead of ${this.settings.type} one`),this.started=!1,Promise.resolve()}add(){}record(){}},_null$1$1}function requireNullMetricsManager(){if(hasRequiredNullMetricsManager)return nullMetricsManager;hasRequiredNullMetricsManager=1,Object.defineProperty(nullMetricsManager,"__esModule",{value:!0}),nullMetricsManager.NullMetricsManager=void 0;const e=requireNullManager$1(),t=requireSafeStringify(),r=require_null$1();class n extends e.NullManager{constructor(e,r,n){!1!==(null==r?void 0:r.logSettingsOnStartup)&&(null==n||n.info(`Starting NullMetrcsManager with settings ${(0,t.safeStringify)(e)}`)),super()}waitForFinalExport(e){return Promise.resolve()}getFromSettings(e){return new r.NullMetric(e)}get(e){return new r.NullMetric({name:e,type:e,enabled:!1,description:e})}}return nullMetricsManager.NullMetricsManager=n,nullMetricsManager}function requireBuilder$3(){if(hasRequiredBuilder$3)return builder$2;hasRequiredBuilder$3=1,Object.defineProperty(builder$2,"__esModule",{value:!0}),builder$2.MetricsManagerBuilder=void 0;const e=requireNullMetricsManager(),t=requireDist();return builder$2.MetricsManagerBuilder=class{withLogger(e){return this.logger=e,this}withSettings(e){return this.settings=e,this}withMeterProvider(e){return this.meterProviderCreateFunc=e,this}withDependencyContainer(e){return this.dependencyContainer=e,this}build(){var e,t,r,n;if((null===(e=globalThis.ioInsightsInternals)||void 0===e?void 0:e.metrics)&&!0!==(null===(t=this.settings)||void 0===t?void 0:t.definitiveInstance))return globalThis.ioInsightsInternals.metrics;const i=this.buildCore();return globalThis.ioInsightsInternals=null!==(r=globalThis.ioInsightsInternals)&&void 0!==r?r:{},globalThis.ioInsightsInternals.metrics&&!(null===(n=this.settings)||void 0===n?void 0:n.definitiveInstance)||(globalThis.ioInsightsInternals.metrics=i),i}buildCore(){var r,n,i,o;let s;if(!0!==(null===(r=this.settings)||void 0===r?void 0:r.enabled)||!0!==(null===(i=null===(n=this.settings)||void 0===n?void 0:n.metrics)||void 0===i?void 0:i.enabled)||!(s=(0,t.loadInsightsPlugin)("metrics",this.logger)))return new e.NullMetricsManager(null===(o=this.settings)||void 0===o?void 0:o.metrics,this.settings,this.logger);return s.newMetricsManager(this.settings,this.dependencyContainer,this.meterProviderCreateFunc,this.logger)}},builder$2}var builder$1$1={},nullTracesManager={},nullTracingState={},hasRequiredNullTracingState;function requireNullTracingState(){if(hasRequiredNullTracingState)return nullTracingState;hasRequiredNullTracingState=1,Object.defineProperty(nullTracingState,"__esModule",{value:!0});return nullTracingState.default=class{constructor(e,t,r){this.source=e,this.propagationInfo=t,this.disablePropagation=r,this.currentSpanStatus={code:0},this.level="OFF"}endSpan(){return Promise.resolve()}get enabled(){return!1}get id(){}get traceId(){}set status(e){this.currentSpanStatus=Object.assign({},e)}get status(){return this.currentSpanStatus}addEvent(e,t,r){return this}recordException(e,t){}isRecording(){return!1}updateName(e){return this}spanContext(){}addData(e,t){}end(){}getPropagationInfo(){return this.propagationInfo?this.propagationInfo:null}injectPropagationInfo(e){this.propagationInfo&&!this.disablePropagation&&(e.__interopIOTracePropagationInfo=this.propagationInfo)}},nullTracingState}var traces={},otelUtils={},container={},hasRequiredContainer,hasRequiredOtelUtils,hasRequiredTraces,hasRequiredNullTracesManager,hasRequiredBuilder$2;function requireContainer(){if(hasRequiredContainer)return container;hasRequiredContainer=1;var e=container&&container.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(container,"__esModule",{value:!0}),container.Container=void 0;const t=requireSafeStringify();class r{static get instance(){var e,t;return null!==(e=r._instance)&&void 0!==e?e:null===(t=null===globalThis||void 0===globalThis?void 0:globalThis.ioInsightsInternals)||void 0===t?void 0:t.instance}static get settings(){var e;return null!==(e=r._settings)&&void 0!==e?e:r.instance.settings}static set settings(e){r._settings=e}static errorless(e,t){try{if("function"!=typeof e)return e;return e()}catch(e){return r.handleErrorlessMode(e,t)}}static errorlessDefined(e,t){try{if("function"!=typeof e)return e;return e()}catch(e){return r.handleErrorlessMode(e,t)}}static errorlessAsync(t,n){return e(this,void 0,void 0,function*(){try{if("function"!=typeof t)return t;return(yield t)()}catch(e){return r.handleErrorlessMode(e,n)}})}static handleErrorlessMode(e,n){var i,o,s,a,c;let l;try{if((null==e?void 0:e.message)&&(l=(null==e?void 0:e.message)+" "+(null!==(i=null==e?void 0:e.stack)&&void 0!==i?i:(new Error).stack)),!l)try{l=(0,t.safeStringify)(e)+" "+(new Error).stack}catch(e){}if(!l)try{l=(null==e?void 0:e.toString())+" "+(new Error).stack}catch(e){}}catch(e){}l||(l="unknown "+(new Error).stack);try{if(!(null===(s=null===(o=r.instance)||void 0===o?void 0:o.settings)||void 0===s?void 0:s.errorlessMode))throw null===(a=r.instance.logger)||void 0===a||a.error("Observed error "+l),e}catch(t){throw e}try{return null===(c=r.instance.logger)||void 0===c||c.warn("Caught error "+l),n}catch(e){return n}}constructor(e,t,n,i,o){var s;this._settings=e,this._traces=t,this.metrics=n,this.logs=i,this.logger=o,this.started=!1,r._instance=this,globalThis.ioInsightsInternals=null!==(s=globalThis.ioInsightsInternals)&&void 0!==s?s:{},globalThis.ioInsightsInternals.instance=this}get traces(){var e,t;return(null===(e=null===globalThis||void 0===globalThis?void 0:globalThis.ioInsightsInternals)||void 0===e?void 0:e.traces)?null===(t=null===globalThis||void 0===globalThis?void 0:globalThis.ioInsightsInternals)||void 0===t?void 0:t.traces:this._traces}waitForFinalExport(e){var t,r,n;return Promise.allSettled([null===(t=this.traces)||void 0===t?void 0:t.waitForFinalExport(e),null===(r=this.metrics)||void 0===r?void 0:r.waitForFinalExport(e),null===(n=this.logs)||void 0===n?void 0:n.waitForFinalExport(e)])}get settings(){return this._settings}start(){return e(this,void 0,void 0,function*(){const e=this.metrics.settings.enabled?this.metrics.start():Promise.resolve(),t=this.traces.settings.enabled?this.traces.start():Promise.resolve(),r=this.logs.settings.enabled?this.logs.start():Promise.resolve();yield Promise.all([e,t,r]),this.started=!0})}stop(){return e(this,void 0,void 0,function*(){const e=this.metrics.started?this.metrics.stop():Promise.resolve(),t=this.traces.started?this.traces.stop():Promise.resolve(),r=this.logs.started?this.logs.stop():Promise.resolve();yield Promise.all([e,t,r]),this.started=!1})}}return container.Container=r,container}function requireOtelUtils(){return hasRequiredOtelUtils||(hasRequiredOtelUtils=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.extractFilteringContextFromArgs=e.deep_value=e.getOTELData=e.flattenOtelAtributes=void 0;const t=requireContainer();e.flattenOtelAtributes=(t,r)=>{if(null==t)return{};"object"!=typeof t&&(t={unknownAttribute:t});const n={};for(const[i,o]of Object.entries(t)){const t=(0,e.getOTELData)(i,o,0,r);for(const[e,r]of t)n[e]=r}return n};e.getOTELData=(e,t,i,o)=>{if((i+=1)>o)return[[e,"<depth exceeded>"]];const s=Boolean(t&&"object"==typeof t);return"number"==typeof t||"string"==typeof t||"boolean"==typeof t?[[e,t]]:n(t)?[[e,t]].concat(r(e,t,i,o)):s?r(e,t,i,o):"function"==typeof t?[]:t?[[e,t+""]]:[]};const r=(t,r,n,i)=>{const o=[];for(const[s,a]of Object.entries(r))for(const[r,c]of(0,e.getOTELData)(s,a,n,i))o.push([t+"."+r,c]);return o},n=e=>!!Array.isArray(e)&&e.every(e=>null==e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e);e.deep_value=function(e,t){if(!t)return null;for(var r=0,n=(t=t.split(".")).length;r<n;r++){if(null==e)return;e=e[t[r]]}return e};e.extractFilteringContextFromArgs=(r,n,i)=>{let o={};return"function"==typeof r.thisMapping?o=Object.assign(Object.assign({},o),t.Container.errorless(()=>r.thisMapping.apply(i,[i]))):Object.keys(r.thisMapping||{}).forEach(t=>{if(!t||!r.thisMapping)return;const n=r.thisMapping[t];o[n]=(0,e.deep_value)(i,t)}),"function"==typeof r.argMapping?o=Object.assign(Object.assign({},o),t.Container.errorless(()=>r.argMapping.apply(i,n))):Object.keys(r.argMapping||{}).forEach(t=>{if(!t||!r.argMapping)return;const i=r.argMapping[t],s=(0,e.deep_value)(n,t);"string"!=typeof s&&"number"!=typeof s||(o[i]=s)}),o}}(otelUtils)),otelUtils}function requireTraces(){if(hasRequiredTraces)return traces;hasRequiredTraces=1;var e=traces&&traces.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})},t=traces&&traces.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(traces,"__esModule",{value:!0}),traces.withSpan=void 0;const r=requireOtelUtils(),n=requireNullTracesManager(),i=t(requireNullTracingState());class o{static get instance(){var e,t;return(null===(e=null===globalThis||void 0===globalThis?void 0:globalThis.ioInsightsInternals)||void 0===e?void 0:e.traces)?null===(t=null===globalThis||void 0===globalThis?void 0:globalThis.ioInsightsInternals)||void 0===t?void 0:t.traces:(o._instance||(o._instance=new n.NullTracesManager(void 0,void 0,void 0)),o._instance)}static set instance(e){o._instance=e}static get currentTracingState(){var e;return(null===(e=o.instance)||void 0===e?void 0:e.currentTracingState)||new i.default("unknown",null,!0)}static set currentTracingState(e){o.instance&&(o.instance.currentTracingState=e)}static removePropagationInfo(e){return o.extractPropagationInfo(e,!0),e}static extractPropagationInfo(e,t){if(null==e?void 0:e.traceparent)return e;const r=null==e?void 0:e.__interopIOTracePropagationInfo;return r?(!0===t&&delete e.__interopIOTracePropagationInfo,r):null}withSequenceSpanEx(t,r,n,i,s){return e(this,void 0,void 0,function*(){return o.instance.withSequenceSpanEx(t,r,n,i,s)})}withSequenceSpan(t,r,n,i){return e(this,void 0,void 0,function*(){return o.instance.withSequenceSpan(t,r,n,i)})}static withSpan(e,t,n,i,s){return t instanceof Function||t&&!t.argMapping&&!t.thisMapping&&!t.defaults||n||i||s?o.instance.withSpan(e,t,n,i,s):function(n,i,s){let a;a=s?s.value:n;let c=function(...n){return o.withSpan(e,t?(0,r.extractFilteringContextFromArgs)(t,n,this):{},null,t,()=>a.apply(this,n))};if(o.isAsyncFunction(a)){const e=c;c=function(...t){return e.apply(this,t)},Object.defineProperty(c,Symbol.toStringTag,{value:"AsyncFunction",configurable:!0})}if(!s)return c;s.value=c}}static isAsyncFunction(e){return e&&"[object AsyncFunction]"==={}.toString.call(e)}static withSpans(e,t){for(const r in e)if("function"==typeof t[r]){const n=t[r],i=e[r];if(!i)continue;let s;s="string"==typeof i?o.withSpan(i):o.withSpan(i.source,i.decoratorOptions),t[r]=s(n)}return t}}return traces.default=o,traces.withSpan=o.withSpan,traces}function requireNullTracesManager(){if(hasRequiredNullTracesManager)return nullTracesManager;hasRequiredNullTracesManager=1;var e=nullTracesManager&&nullTracesManager.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})},t=nullTracesManager&&nullTracesManager.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(nullTracesManager,"__esModule",{value:!0}),nullTracesManager.NullTracesManager=void 0;const r=t(requireNullTracingState()),n=t(requireTraces()),i=requireNullManager$1(),o=requireSafeStringify();class s extends i.NullManager{get settings(){return this._settings||{}}set settings(e){this._settings=e}constructor(e,t,r){!1!==(null==t?void 0:t.logSettingsOnStartup)&&(null==r||r.info(`Starting NullTracesManager with settings ${(0,o.safeStringify)(e)}`)),super(),this._settings=e,this.logger=r}withSequenceSpan(t,r,n,i){return e(this,void 0,void 0,function*(){return this.withSequenceSpanEx(t,t+".start",r,n,i)})}withSequenceSpanEx(t,r,n,i,o){return e(this,void 0,void 0,function*(){return this.withSpan(t,n,null,i,o)})}get currentTracingState(){return new r.default("nullTracingState",null,!0)}set currentTracingState(e){}waitForFinalExport(e){return Promise.resolve()}withSpan(e,t,i,o,s){const a="function"==typeof t?t:"function"==typeof i?i:"function"==typeof o?o:s;if(!a)throw new Error("callback must be provided");if("function"!=typeof a)throw new Error("Callback must be a function, received "+typeof a);const c=new r.default(e,null,!0);n.default.currentTracingState=c;try{return a(c)}finally{n.default.currentTracingState=null}}setFilterConfig(e){}get startupTraceFinished(){return()=>{}}get userJourneyMarker(){return()=>{}}setUserJourneyMarker(e){}get clickstreamMarker(){return()=>{}}}return nullTracesManager.NullTracesManager=s,nullTracesManager}function requireBuilder$2(){if(hasRequiredBuilder$2)return builder$1$1;hasRequiredBuilder$2=1,Object.defineProperty(builder$1$1,"__esModule",{value:!0}),builder$1$1.TracesManagerBuilder=void 0;const e=requireNullTracesManager(),t=requireDist();return builder$1$1.TracesManagerBuilder=class{constructor(){this.traceLogger=null}withLogger(e){return this.logger=e,this}withTraceLogger(e){return this.traceLogger=e,this}withSettings(e){return this.settings=e,this}withMetrics(e){return this.metrics=e,this}withTracerProvider(e){return this.tracerProvider=e,this}withContextManager(e){var t,r;return this.settings=null!==(t=this.settings)&&void 0!==t?t:{enabled:!1},this.settings.traces=null!==(r=this.settings.traces)&&void 0!==r?r:{enabled:!1},this.settings.traces.contextManager=()=>e,this.settings.traces.useOTELContextManager=!0,this}withPropagationInfoStorage(e,t){return this.store=e,this.read=t,this}build(){var e,t,r,n;if((null===(e=globalThis.ioInsightsInternals)||void 0===e?void 0:e.traces)&&!0!==(null===(t=this.settings)||void 0===t?void 0:t.definitiveInstance))return globalThis.ioInsightsInternals.traces;const i=this.buildCore();return globalThis.ioInsightsInternals=null!==(r=globalThis.ioInsightsInternals)&&void 0!==r?r:{},globalThis.ioInsightsInternals.traces&&!(null===(n=this.settings)||void 0===n?void 0:n.definitiveInstance)||(globalThis.ioInsightsInternals.traces=i),i}buildCore(){var r,n,i,o,s,a,c,l;let u;if(this.settings.traces=null!==(r=this.settings.traces)&&void 0!==r?r:{enabled:!1},this.settings.traces.otlpExporterConfig=null!==(n=this.settings.traces.exporterSettings)&&void 0!==n?n:this.settings.traces.otlpExporterConfig,this.settings.traces.exporterSettings=null!==(i=this.settings.traces.exporterSettings)&&void 0!==i?i:this.settings.traces.otlpExporterConfig,!0!==(null===(o=this.settings)||void 0===o?void 0:o.enabled)||!0!==(null===(a=null===(s=this.settings)||void 0===s?void 0:s.traces)||void 0===a?void 0:a.enabled)||!(u=(0,t.loadInsightsPlugin)("traces",this.logger)))return new e.NullTracesManager(null===(c=this.settings)||void 0===c?void 0:c.traces,this.settings,this.logger);return u.newTracesManager(this.logger,this.settings,null!==(l=this.traceLogger)&&void 0!==l?l:this.logger,this.metrics,this.store,this.read)}},builder$1$1}var _null$3={},hasRequired_null;function require_null(){if(hasRequired_null)return _null$3;hasRequired_null=1,Object.defineProperty(_null$3,"__esModule",{value:!0}),_null$3.NullLogger=void 0;return _null$3.NullLogger=class{get level(){return 60}error(){}warn(){}info(){}debug(){}verbose(){}},_null$3}var nullManager={},hasRequiredNullManager;function requireNullManager(){if(hasRequiredNullManager)return nullManager;hasRequiredNullManager=1,Object.defineProperty(nullManager,"__esModule",{value:!0}),nullManager.NullLogsManager=void 0;const e=requireNullManager$1(),t=requireSafeStringify();class r extends e.NullManager{constructor(e,r,n){!1!==(null==r?void 0:r.logSettingsOnStartup)&&(null==n||n.info(`Starting NullLogsManager with settings ${(0,t.safeStringify)(e)}`)),super()}emit(e){return null}}return nullManager.NullLogsManager=r,nullManager}var constants$2={},hasRequiredConstants;function requireConstants(){return hasRequiredConstants||(hasRequiredConstants=1,Object.defineProperty(constants$2,"__esModule",{value:!0}),constants$2.Defaults=void 0,constants$2.Defaults={DEFAULT_USER:"unknown-user",DEFAULT_SERVICE_NAME:"unknown-service-name",DEFAULT_SERVICE_ID:"unknown-service-id",DEFAULT_SERVICE_VERSION:"unknown-service-version",DEFAULT_PLATFORM_VERSION:"unknown-platform-version"}),constants$2}var logWrapper={},hasRequiredLogWrapper;function requireLogWrapper(){if(hasRequiredLogWrapper)return logWrapper;hasRequiredLogWrapper=1,Object.defineProperty(logWrapper,"__esModule",{value:!0}),logWrapper.LogWrapper=void 0;return logWrapper.LogWrapper=class{constructor(e,t){this.logger=e,this.dropLog=t}get level(){var e;return null!==(e=this.logger.level)&&void 0!==e?e:0}error(e,...t){var r;(null===(r=this.dropLog)||void 0===r?void 0:r.call(this,50,e))||this.logger.warn(e,...t)}warn(e,...t){var r;(null===(r=this.dropLog)||void 0===r?void 0:r.call(this,50,e))||this.logger.warn(e,...t)}info(e,...t){var r;(null===(r=this.dropLog)||void 0===r?void 0:r.call(this,60,e))||this.logger.info(e,...t)}debug(e,...t){var r;(null===(r=this.dropLog)||void 0===r?void 0:r.call(this,70,e))||this.logger.debug(e,...t)}verbose(e,...t){var r;(null===(r=this.dropLog)||void 0===r?void 0:r.call(this,80,e))||this.logger.verbose(e,...t)}},logWrapper}var builder$4={},hasRequiredBuilder$1,hasRequiredBuilder;function requireBuilder$1(){if(hasRequiredBuilder$1)return builder$4;hasRequiredBuilder$1=1,Object.defineProperty(builder$4,"__esModule",{value:!0}),builder$4.LogsManagerBuilder=void 0;const e=requireDist(),t=requireNullManager();return builder$4.LogsManagerBuilder=class{withLogger(e){return this.logger=e,this}withSettings(e){return this.settings=e,this}build(){var e,t,r,n;if((null===(e=globalThis.ioInsightsInternals)||void 0===e?void 0:e.logs)&&!0!==(null===(t=this.settings)||void 0===t?void 0:t.definitiveInstance))return globalThis.ioInsightsInternals.logs;const i=this.buildCore();return globalThis.ioInsightsInternals=null!==(r=globalThis.ioInsightsInternals)&&void 0!==r?r:{},globalThis.ioInsightsInternals.logs&&!(null===(n=this.settings)||void 0===n?void 0:n.definitiveInstance)||(globalThis.ioInsightsInternals.logs=i),i}buildCore(){var r,n,i,o;let s;if(!0!==(null===(r=this.settings)||void 0===r?void 0:r.enabled)||!0!==(null===(i=null===(n=this.settings)||void 0===n?void 0:n.logs)||void 0===i?void 0:i.enabled)||!(s=(0,e.loadInsightsPlugin)("logs",this.logger)))return new t.NullLogsManager(null===(o=this.settings)||void 0===o?void 0:o.logs,this.settings,this.logger);return s.newLogsManager(this.logger,this.settings.logs,this.settings)}},builder$4}function requireBuilder(){if(hasRequiredBuilder)return builder$3;hasRequiredBuilder=1,Object.defineProperty(builder$3,"__esModule",{value:!0}),builder$3.Builder=void 0;const e=requireBuilder$3(),t=requireBuilder$2(),r=require_null(),n=requireContainer(),i=requireNullMetricsManager(),o=requireNullTracesManager(),s=requireNullManager(),a=requireConstants(),c=requireLogWrapper(),l=requireDist(),u=requireSafeStringify(),d=requireBuilder$1();class h{constructor(){this.logger=new r.NullLogger}withLogger(e){var t;e&&(this.logger=new c.LogWrapper(e,(e,t)=>{var r,n,i;return!(!(null===(r=this.settings)||void 0===r?void 0:r.suppressDoubleInitializationWarnings)||!~(t+"").indexOf("@opentelemetry/api: Attempted duplicate registration of API"))||(!(!(null===(n=this.settings)||void 0===n?void 0:n.suppressDoubleInitializationWarnings)||!~(t+"").indexOf("Current logger will overwrite one already registered"))||!(!(null===(i=this.settings)||void 0===i?void 0:i.suppressDoubleInitializationWarnings)||!~(t+"").indexOf("Current logger will be overwritten")))}));const r=(0,l.loadInsightsPlugin)("base",this.logger);if(r)if(this.logger.level){const e=null===(t=this.logger.level)||void 0===t?void 0:t.valueOf();r.diag.setLogger(this.logger,e)}else r.diag.setLogger(this.logger,70);return this}withSettings(e){return this.settings=e,n.Container.settings=e,this}withMetrics(){return this.metricsBuilder=new e.MetricsManagerBuilder,this.metricsBuilder.withLogger(this.logger),this.metricsBuilder.withSettings(Object.assign({enabled:!1},this.settings)),this.metricsBuilder}withTraces(){return this.tracesBuilder=new t.TracesManagerBuilder,this.tracesBuilder.withLogger(this.logger),this.tracesBuilder.withSettings(Object.assign({enabled:!1},this.settings)),this.tracesBuilder}withLogs(){return this.logsBuilder=new d.LogsManagerBuilder,this.logsBuilder.withLogger(this.logger),this.logsBuilder.withSettings(Object.assign({enabled:!1},this.settings)),this.logsBuilder}build(){var e,t,r,c,d,p,g,m,f;this.settings=null!==(e=this.settings)&&void 0!==e?e:{enabled:!1};const y=Object.assign({enabled:!1},this.settings);if(!1!==(null===(t=this.settings)||void 0===t?void 0:t.logSettingsOnStartup)&&this.logger.info(`Starting interop.io OTEL with settings ${(0,u.safeStringify)(this.settings)}`),0==(null===(r=this.settings)||void 0===r?void 0:r.enabled)||!(0,l.loadInsightsPlugin)("base",this.logger))return new n.Container(y,new o.NullTracesManager(this.settings.traces,y,this.logger),new i.NullMetricsManager(this.settings.metrics,y,this.logger),new s.NullLogsManager(this.settings.logs,y,this.logger),this.logger);if((null===(d=null===(c=this.settings)||void 0===c?void 0:c.metrics)||void 0===d?void 0:d.enabled)&&(null===(p=this.settings)||void 0===p?void 0:p.metrics.platformMetricsEnabled)&&!this.metricsBuilder)throw new Error("metrics.platformMetricsEnabled is true, but .withMetrics() method not called.");const $=this.settings.additionalResourceAttributes;this.settings.additionalResourceAttributes=()=>{var e,t,r,i,o,s,c,l,u,d,h,p,g,m,f,y,b,w,v,S,E,C,_,I;const T=null!==(e=n.Container.errorlessDefined($,{}))&&void 0!==e?e:{};return Object.assign(Object.assign({},T),{user:null!==(o=null!==(i=null!==(t=T.userId)&&void 0!==t?t:null===(r=this.settings)||void 0===r?void 0:r.userId)&&void 0!==i?i:T["user.id"])&&void 0!==o?o:a.Defaults.DEFAULT_USER,"user.id":null!==(u=null!==(l=null!==(s=T.userId)&&void 0!==s?s:null===(c=this.settings)||void 0===c?void 0:c.userId)&&void 0!==l?l:T["user.id"])&&void 0!==u?u:a.Defaults.DEFAULT_USER,"service.name":null!==(g=null!==(p=null!==(d=T.serviceName)&&void 0!==d?d:null===(h=this.settings)||void 0===h?void 0:h.serviceName)&&void 0!==p?p:T["service.name"])&&void 0!==g?g:a.Defaults.DEFAULT_SERVICE_NAME,"service.instance.id":null!==(b=null!==(y=null!==(m=T.serviceId)&&void 0!==m?m:null===(f=this.settings)||void 0===f?void 0:f.serviceId)&&void 0!==y?y:T["service.instance.id"])&&void 0!==b?b:a.Defaults.DEFAULT_SERVICE_ID,"service.version":null!==(E=null!==(S=null!==(w=T.serviceVersion)&&void 0!==w?w:null===(v=this.settings)||void 0===v?void 0:v.serviceVersion)&&void 0!==S?S:T["service.version"])&&void 0!==E?E:a.Defaults.DEFAULT_SERVICE_VERSION,platformVersion:null!==(I=null!==(C=T.platformVersion)&&void 0!==C?C:null===(_=this.settings)||void 0===_?void 0:_.platformVersion)&&void 0!==I?I:a.Defaults.DEFAULT_PLATFORM_VERSION})},h.maybeAddResourceAttributesToAttributes(this.settings),h.maybeAddResourceAttributesToAttributes(this.settings.logs),h.maybeAddResourceAttributesToAttributes(this.settings.metrics),h.maybeAddResourceAttributesToAttributes(this.settings.traces),h.propagateAttributeDown("useSSOAuth",this.settings,this.settings.logs),h.propagateAttributeDown("useSSOAuth",this.settings,this.settings.metrics),h.propagateAttributeDown("useSSOAuth",this.settings,this.settings.traces),h.propagateAttributeDown("useSSOAuthRawToken",this.settings,this.settings.logs),h.propagateAttributeDown("useSSOAuthRawToken",this.settings,this.settings.metrics),h.propagateAttributeDown("useSSOAuthRawToken",this.settings,this.settings.traces),h.propagateAttributesDown("headers",this.settings,this.settings.logs),h.propagateAttributesDown("headers",this.settings,this.settings.metrics),h.propagateAttributesDown("headers",this.settings,this.settings.traces),h.propagateAttributesDown("additionalAttributes",this.settings,this.settings.logs),h.propagateAttributesDown("additionalResourceAttributes",this.settings,this.settings.logs),h.propagateAttributesDown("additionalAttributes",this.settings,this.settings.metrics),h.propagateAttributesDown("additionalResourceAttributes",this.settings,this.settings.metrics),h.propagateAttributesDown("additionalAttributes",this.settings,this.settings.traces),h.propagateAttributesDown("additionalResourceAttributes",this.settings,this.settings.traces);const b=(null!==(g=this.metricsBuilder)&&void 0!==g?g:this.withMetrics()).withLogger(this.logger).withSettings(this.settings).build(),w=(null!==(m=this.tracesBuilder)&&void 0!==m?m:this.withTraces()).withLogger(this.logger).withSettings(this.settings).withMetrics(b).build();l.Traces.instance=w;const v=(null!==(f=this.logsBuilder)&&void 0!==f?f:this.withLogs()).withLogger(this.logger).withSettings(this.settings).build();return l.Logs.instance=v,new n.Container(y,w,b,v,this.logger)}static propagateAttributeDown(e,t,r){var n;r&&(r[e]=null!==(n=r[e])&&void 0!==n?n:t[e])}static propagateAttributesDown(e,t,r){var i,o;if(!r)return;const s=null!==(i=t[e])&&void 0!==i?i:{},a=null!==(o=r[e])&&void 0!==o?o:{};r[e]=()=>Object.assign(Object.assign({},n.Container.errorless(s)),n.Container.errorless(a))}static maybeAddResourceAttributesToAttributes(e){if(null==e?void 0:e.addResourceAttributesToAttributes){const t=e.additionalResourceAttributes,r=e.additionalAttributes;e.additionalAttributes=()=>Object.assign(Object.assign({},n.Container.errorless(t)),n.Container.errorless(r))}}}return builder$3.Builder=h,builder$3}var log4jsWrapper={},hasRequiredLog4jsWrapper;function requireLog4jsWrapper(){if(hasRequiredLog4jsWrapper)return log4jsWrapper;hasRequiredLog4jsWrapper=1,Object.defineProperty(log4jsWrapper,"__esModule",{value:!0}),log4jsWrapper.Log4jsWrapper=void 0;return log4jsWrapper.Log4jsWrapper=class{constructor(e){this.logger=e}get level(){return this.convert("level"in this.logger?this.logger.level:this.logger.publishLevel())}error(e,...t){this.logger.warn(e,...t)}warn(e,...t){this.logger.warn(e,...t)}info(e,...t){this.logger.info(e,...t)}debug(e,...t){this.logger.debug(e,...t)}verbose(e,...t){this.logger.trace(e,...t)}convert(e){if(void 0===e)return 60;switch("string"!=typeof e?e.levelStr.toLowerCase():e.toLowerCase()){case"off":return 0;case"error":return 30;case"warn":return 50;case"info":default:return 60;case"debug":return 70;case"trace":return 80}}},log4jsWrapper}var metricsDependencyBuilder={},nullPerfProvider={},hasRequiredNullPerfProvider,hasRequiredMetricsDependencyBuilder;function requireNullPerfProvider(){if(hasRequiredNullPerfProvider)return nullPerfProvider;hasRequiredNullPerfProvider=1,Object.defineProperty(nullPerfProvider,"__esModule",{value:!0}),nullPerfProvider.NullPerformanceProvider=void 0;return nullPerfProvider.NullPerformanceProvider=class{getAppsCPU(){return Promise.resolve(void 0)}getAppsMemory(){return Promise.resolve(void 0)}getSystemCPU(){return Promise.resolve(void 0)}getSystemMemory(){return Promise.resolve(void 0)}},nullPerfProvider}function requireMetricsDependencyBuilder(){if(hasRequiredMetricsDependencyBuilder)return metricsDependencyBuilder;hasRequiredMetricsDependencyBuilder=1,Object.defineProperty(metricsDependencyBuilder,"__esModule",{value:!0}),metricsDependencyBuilder.MetricsDependencyBuilder=void 0;const e=requireNullPerfProvider();return metricsDependencyBuilder.MetricsDependencyBuilder=class{constructor(){this.performanceProvider=new e.NullPerformanceProvider,this.instanceFocusedHandler=()=>()=>{},this.instanceStartedHandler=()=>()=>{},this.instanceStoppedHandler=()=>()=>{},this.instanceReadyHandler=()=>()=>{},this.instanceErrorHandler=()=>()=>{},this.instanceCrashHandler=()=>()=>{},this.layoutRestoredHandler=()=>()=>{},this.platformStartedHandler=()=>()=>{},this.platformErrorHandler=()=>()=>{},this.workspaceLoadedHandler=()=>()=>{},this.workspaceRestoredHandler=()=>()=>{},this.workspaceSavedHandler=()=>()=>{},this.workspaceStoppedHandler=()=>()=>{},this.workspaceSelectedHandler=()=>()=>{},this.workspaceStartedHandler=()=>()=>{},this.workspaceFrameCreatedHandler=()=>()=>{},this.workspaceFrameInitHandler=()=>()=>{},this.workspaceFramePageLoadHandler=()=>()=>{},this.workspaceFrameWorkspaceRenderHandler=()=>()=>{},this.workspaceComponentCreatedHandler=()=>()=>{},this.workspaceAppsStartedHandler=()=>()=>{},this.workspaceStartupHandler=()=>()=>{}}build(){return{performanceProvider:this.performanceProvider,instanceStartedHandler:this.instanceStartedHandler,instanceStoppedHandler:this.instanceStoppedHandler,instanceReadyHandler:this.instanceReadyHandler,instanceFocusedHandler:this.instanceFocusedHandler,instanceErrorHandler:this.instanceErrorHandler,instanceCrashHandler:this.instanceCrashHandler,layoutRestoredHandler:this.layoutRestoredHandler,platformStartedHandler:this.platformStartedHandler,platformErrorHandler:this.platformErrorHandler,workspaceLoadedHandler:this.workspaceLoadedHandler,workspaceSavedHandler:this.workspaceSavedHandler,workspaceStoppedHandler:this.workspaceStoppedHandler,workspaceSelectedHandler:this.workspaceSelectedHandler,workspaceRestoredHandler:this.workspaceRestoredHandler,workspaceStartedHandler:this.workspaceStartedHandler,workspaceStartupHandler:this.workspaceStartupHandler,workspaceFrameCreatedHandler:this.workspaceFrameCreatedHandler,workspaceFrameInitHandler:this.workspaceFrameInitHandler,workspaceFramePageLoadHandler:this.workspaceFramePageLoadHandler,workspaceFrameWorkspaceRenderHandler:this.workspaceFrameWorkspaceRenderHandler,workspaceComponentCreatedHandler:this.workspaceComponentCreatedHandler,workspaceAppsStartedHandler:this.workspaceAppsStartedHandler}}withInstanceStartedHandler(e){return this.instanceStartedHandler=e,this}withInstanceStoppedHandler(e){return this.instanceStoppedHandler=e,this}withInstanceReadyHandler(e){return this.instanceReadyHandler=e,this}withInstanceFocusedHandler(e){return this.instanceFocusedHandler=e,this}withInstanceErrorHandler(e){return this.instanceErrorHandler=e,this}withInstanceCrashHandler(e){return this.instanceCrashHandler=e,this}withLayoutRestoredHandler(e){return this.layoutRestoredHandler=e,this}withWorkspaceLoadedHandler(e){return this.workspaceLoadedHandler=e,this}withWorkspaceSavedHandler(e){return this.workspaceSavedHandler=e,this}withWorkspaceStartedHandler(e){return this.workspaceRestoredHandler=()=>()=>{},this.workspaceStartedHandler=e,this}withWorkspaceStoppedHandler(e){return this.workspaceStoppedHandler=e,this}withWorkspaceSelectedHandler(e){return this.workspaceSelectedHandler=e,this}withPlatformStartedHandler(e){return this.platformStartedHandler=e,this}withPlatformErrorHandler(e){return this.platformErrorHandler=e,this}withPerfProvider(e){return this.performanceProvider=e,this}withWorkspaceRestoredHandler(e){return this.workspaceRestoredHandler=e,this.workspaceStartedHandler=()=>()=>{},this}withWorkspaceStartupHandler(e){return this.workspaceStartupHandler=e,this}withWorkspaceFrameCreatedHandler(e){return this.workspaceFrameCreatedHandler=e,this}withWorkspaceFrameInitHandler(e){return this.workspaceFrameInitHandler=e,this}withWorkspaceFramePageLoadHandler(e){return this.workspaceFramePageLoadHandler=e,this}withWorkspaceFrameWorkspaceRenderHandler(e){return this.workspaceFrameWorkspaceRenderHandler=e,this}withWorkspaceComponentCreatedHandler(e){return this.workspaceComponentCreatedHandler=e,this}withWorkspaceAppsStartedHandler(e){return this.workspaceAppsStartedHandler=e,this}},metricsDependencyBuilder}var logs={},hasRequiredLogs;function requireLogs(){if(hasRequiredLogs)return logs;hasRequiredLogs=1,Object.defineProperty(logs,"__esModule",{value:!0}),logs.Logs=void 0;const e=requireNullManager();class t{static get instance(){var r,n;return(null===(r=null===globalThis||void 0===globalThis?void 0:globalThis.ioInsightsInternals)||void 0===r?void 0:r.logs)?null===(n=null===globalThis||void 0===globalThis?void 0:globalThis.ioInsightsInternals)||void 0===n?void 0:n.logs:(t._instance||(t._instance=new e.NullLogsManager(void 0,void 0,void 0)),t._instance)}static set instance(e){t._instance=e}static emit(e){return t.instance.emit(e)}}return logs.Logs=t,logs}var pluginLoader={},hasRequiredPluginLoader;function requirePluginLoader(){if(hasRequiredPluginLoader)return pluginLoader;hasRequiredPluginLoader=1,Object.defineProperty(pluginLoader,"__esModule",{value:!0}),pluginLoader.loadInsightsPlugin=function(t,r){if(void 0!==e.get(t))return e.get(t);if(void 0===globalThis.ioInsightsPlugins)return null;let n=globalThis.ioInsightsPlugins[t];if(!n)return null;if("function"==typeof n)try{n=n()}catch(n){return null==r||r.error(`Error loading io.Insights plugin ${t}`,n),e.set(t,null),null}return e.set(t,n),n},pluginLoader.registerInsightsPlugin=function(e,t){void 0===globalThis.ioInsightsPlugins&&(globalThis.ioInsightsPlugins={});globalThis.ioInsightsPlugins[e]=t};const e=new Map;return pluginLoader}var isNode={},hasRequiredIsNode,hasRequiredDist;function requireIsNode(){if(hasRequiredIsNode)return isNode;let e;return hasRequiredIsNode=1,Object.defineProperty(isNode,"__esModule",{value:!0}),isNode.isNode=function(){if(void 0!==e)return e;if("undefined"!=typeof window)return e=!1,!1;try{e="[object process]"===Object.prototype.toString.call(commonjsGlobal.process)}catch(t){e=!1}return e},isNode}function requireDist(){return hasRequiredDist||(hasRequiredDist=1,function(e){var t,r=dist$3&&dist$3.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),n=dist$3&&dist$3.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=dist$3&&dist$3.__importStar||(t=function(e){return t=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},t(e)},function(e){if(e&&e.__esModule)return e;var i={};if(null!=e)for(var o=t(e),s=0;s<o.length;s++)"default"!==o[s]&&r(i,e,o[s]);return n(i,e),i}),o=dist$3&&dist$3.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.SpanStatusCode=e.deep_value=e.extractFilteringContextFromArgs=e.getOTELData=e.flattenOtelAtributes=e.safeStringify=e.isNode=e.loadInsightsPlugin=e.registerInsightsPlugin=e.Logs=e.NullTracingState=e.OTEL_PI_KEY=e.withSpan=e.Traces=e.MetricsDependencyBuilder=e.NullMetric=e.Container=e.Log4jsWrapper=e.Builder=void 0;var s=requireBuilder();Object.defineProperty(e,"Builder",{enumerable:!0,get:function(){return s.Builder}});var a=requireLog4jsWrapper();Object.defineProperty(e,"Log4jsWrapper",{enumerable:!0,get:function(){return a.Log4jsWrapper}});var c=requireContainer();Object.defineProperty(e,"Container",{enumerable:!0,get:function(){return c.Container}});var l=require_null$1();Object.defineProperty(e,"NullMetric",{enumerable:!0,get:function(){return l.NullMetric}});var u=requireMetricsDependencyBuilder();Object.defineProperty(e,"MetricsDependencyBuilder",{enumerable:!0,get:function(){return u.MetricsDependencyBuilder}});const d=i(requireTraces());e.Traces=d.default,Object.defineProperty(e,"withSpan",{enumerable:!0,get:function(){return d.withSpan}}),e.OTEL_PI_KEY="__interopIOTracePropagationInfo";const h=o(requireNullTracingState());e.NullTracingState=h.default;var p=requireLogs();Object.defineProperty(e,"Logs",{enumerable:!0,get:function(){return p.Logs}});const g=requirePluginLoader();Object.defineProperty(e,"registerInsightsPlugin",{enumerable:!0,get:function(){return g.registerInsightsPlugin}}),Object.defineProperty(e,"loadInsightsPlugin",{enumerable:!0,get:function(){return g.loadInsightsPlugin}});const m=requireIsNode();Object.defineProperty(e,"isNode",{enumerable:!0,get:function(){return m.isNode}});const f=requireSafeStringify();Object.defineProperty(e,"safeStringify",{enumerable:!0,get:function(){return f.safeStringify}});const y=requireOtelUtils();var $;Object.defineProperty(e,"getOTELData",{enumerable:!0,get:function(){return y.getOTELData}}),Object.defineProperty(e,"flattenOtelAtributes",{enumerable:!0,get:function(){return y.flattenOtelAtributes}}),Object.defineProperty(e,"extractFilteringContextFromArgs",{enumerable:!0,get:function(){return y.extractFilteringContextFromArgs}}),Object.defineProperty(e,"deep_value",{enumerable:!0,get:function(){return y.deep_value}}),"undefined"!=typeof Promise&&(Promise.allSettled=Promise.allSettled||(e=>Promise.all(e.map(e=>e.then(e=>({status:"fulfilled",value:e})).catch(e=>({status:"rejected",reason:e})))))),function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"}($||(e.SpanStatusCode=$={}))}(dist$3)),dist$3}var distExports=requireDist();function setInsightsAttributes(e,t,r,n){let i=e.applicationName??"unknown-app";r&&(i=e.applicationName??r?.appName??i),n&&(i=e.applicationName??n.applicationConfig.name??i),e.applicationName=i,e.traces?.closeTrace&&r?.addCloseHandler(()=>distExports.Traces.withSpan("interopio.api.application.close",()=>{}));const o=r?.sid,s=r?.user,a=(Utils.isNode()&&process?.env?.USERNAME)??r?.env?.windowsUserName,c=(Utils.isNode()&&process?.env?.COMPUTERNAME)??r?.env?.machineName,l=n?.env??r?.env?.env,u=n?.region??r?.env?.region,d=n?.instanceId??r?.appInstanceId??"",h=r?.windowId,p={interopioCoreVersion:version$2,interopioLibVersion:t.version||version$2,host:"io.api",tracingAppName:i,tracingAppInstanceId:d,user:s,osUser:a,machine:c,env:l,region:u,windowId:h,sid:o};let g=e.additionalResourceAttributes;if("function"!=typeof g){const t=e.additionalResourceAttributes;g=()=>t}e.additionalResourceAttributes=()=>({...p,...g()})}function setDefaultTraceFilters(e){e.traces&&(e.traces.defaultFilters??=[],e.traces.defaultFilters.push({source:"interopio.api.instrumentation.fetch",canBeRoot:!1}),e.traces.defaultFilters.push({source:"interopio.api.instrumentation.xhr",canBeRoot:!1}),e.traces.defaultFilters.push({source:"interopio.api.prefs",canBeRoot:!1}),e.traces.defaultFilters.push({source:"interopio.api.layouts",canBeRoot:!1}),e.traces.defaultFilters.push({source:"interopio.api.windows",canBeRoot:!1}),e.traces.defaultFilters.push({source:"interopio.api.interop",context:{stream:"#^t42[.].*"},canBeRoot:!1,enabled:!1}),e.traces.defaultFilters.push({source:"interopio.api.interop",context:{stream:"apps.event"},canBeRoot:!1,enabled:!1}),e.traces.defaultFilters.push({source:"interopio.api.interop",context:{name:"#^t42[.].*"},canBeRoot:!1,enabled:!1}),e.traces.defaultFilters.push({source:"interopio.api.interop",context:{name:"apps.event"},canBeRoot:!1,enabled:!1}),e.traces.defaultFilters.push({source:"interopio.api.interop",context:{method:"apps.command"},canBeRoot:!1}),e.traces.defaultFilters.push({source:"interopio.api.interop",context:{method:"#^t42[.].*"},canBeRoot:!1}),e.traces.defaultFilters.push({source:"interopio.api.contexts",context:{context:"___insights_pi_storage___"},enabled:!1}),e.traces.defaultFilters.push({source:"interopio.api.contexts",context:{context:"#^t42[.].*"},canBeRoot:!1}),e.traces.defaultFilters.push({source:"interopio.api.contexts",context:{context:"#^__.*"},canBeRoot:!1}),e.traces.defaultFilters.push({source:"interopio.api.appManager",canBeRoot:!1}),e.traces.defaultFilters.push({source:"interopio.api.notifications",canBeRoot:!1}))}function prepareConfig(e,t,r){let n;if(Utils.isNode()){const e=process.env._GD_STARTING_CONTEXT_;if(e)try{n=JSON.parse(e)}catch{}}function i(){if(e.application)return e.application;if(r)return r.applicationName;if("undefined"!=typeof window&&void 0!==window.glue42electron)return window.glue42electron.application;const t=nanoid$1(10);return Utils.isNode()?n?n.applicationConfig.name:"NodeJS"+t:"undefined"!=typeof window&&"undefined"!=typeof document?document.title+` (${t})`:t}const o=function(){const o=e.gateway,s=o?.protocolVersion??3,a=o?.reconnectInterval,c=o?.reconnectAttempts;let l=o?.ws;const u=o?.sharedWorker,d=o?.inproc,h=o?.webPlatform??void 0;let p,g,m,f,y;r&&(l=r.gwURL),Utils.isNode()&&n&&n.gwURL&&(l=n.gwURL),l||u||d||(l="ws://localhost:8385");const $=i();let b=$;void 0!==r?(g=r.windowId,m=r.pid,r.env&&(f=r.env.env,y=r.env.region),b=r.application??"glue-app",p=r.appInstanceId):Utils.isNode()?(m=process.pid,n&&(f=n.env,y=n.region,p=n.instanceId)):void 0!==window?.glue42electron&&(g=window?.glue42electron.instanceId,m=window?.glue42electron.pid,f=window?.glue42electron.env,y=window?.glue42electron.region,b=window?.glue42electron.application??"glue-app",p=window?.glue42electron.instanceId);const w=e.gateway?.replaySpecs??[];w.push(ContextMessageReplaySpec);let v={application:b,applicationName:$,windowId:g,instance:p,process:m,region:y,environment:f,api:t.version||version$2};return e.identity&&(v=Object.assign(v,e.identity)),{identity:v,reconnectInterval:a,ws:l,sharedWorker:u,webPlatform:h,inproc:d,protocolVersion:s,reconnectAttempts:c,replaySpecs:w}}();let s=i();if("undefined"!=typeof window){const e=window,t=e.htmlContainer?`${e.htmlContainer.containerName}.${e.htmlContainer.application}`:e?.glue42gd?.application;t&&(s=t)}return{bus:e.bus??!1,application:s,auth:"string"==typeof e.auth?{token:e.auth}:e.auth?e.auth:Utils.isNode()&&n&&n.gwToken?{gatewayToken:n.gwToken}:e.gateway?.webPlatform?{username:"glue42",password:""}:void 0,logger:function(){let t=e.logger;const n="warn";let i;return t||(t=n),r&&(i=r.consoleLogLevel),"string"==typeof t?{console:i??t,publish:n}:{console:i??t.console??n,publish:t.publish??n}}(),connection:o,metrics:e.metrics??!0,contexts:function(){const t={reAnnounceKnownContexts:!0,subscribeOnUpdate:!0,subscribeOnGet:!0,onlyReAnnounceSubscribedContexts:!0};return void 0===e.contexts||"boolean"==typeof e.contexts&&e.contexts?t:"object"==typeof e.contexts&&{...t,...e.contexts}}(),version:t.version||version$2,libs:t.libs??[],customLogger:e.customLogger,getInsights:async function(i,o,s){const a=e.insights;if("object"!=typeof a&&"boolean"!=typeof a&&void 0!==a)throw new Error("insights/otel property should be boolean, object or unspecified");if(!1===a)return{enabled:!1};let c,l;return i?c=i.insights:Utils.isNode()&&!1!==e?.insights&&!1!==e?.insights?.enabled&&!1!==e?.insights?.requestSettings&&(c=await(o?.invoke("T42.Otel.GetConfig",void 0,n?{environment:n.env,region:n.region}:void 0,{waitTimeoutMs:0}).then(e=>e.returned).catch(e=>s?.warn("Unable to retrieve base io.Insights settings: "+(e?.message??e))))),c&&(i||n||Utils.isNode()&&("boolean"==typeof a||!a?.platformInstance))&&(c={...c,metrics:{...c?.metrics,enabled:!!c?.metrics?.enabled,platformMetricsEnabled:!1}}),l=!0===a||void 0===a?c??{enabled:!1}:deepMerge(c||{},a,{isMergeableObject:isPlainObject$1$1}),setInsightsAttributes(l,t,r,n),l.traces?.enabled&&setDefaultTraceFilters(l),l}}}function __decorate(e,t,r,n){var i,o=arguments.length,s=o<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s}"function"==typeof SuppressedError&&SuppressedError;class GW3ContextData{name;contextId;context;isAnnounced;createdByUs;joinedActivity;updateCallbacks={};activityId;sentExplicitSubscription;get hasReceivedSnapshot(){return this.snapshotPromiseWrapper.resolved}set hasReceivedSnapshot(e){e?this.snapshotPromiseWrapper.resolve():this.snapshotPromiseWrapper=new PromiseWrapper$1}get snapshotPromise(){return this.snapshotPromiseWrapper.promise}snapshotPromiseWrapper;constructor(e,t,r,n){this.contextId=e,this.name=t,this.isAnnounced=r,this.activityId=n,this.context={},this.snapshotPromiseWrapper=new PromiseWrapper$1}hasCallbacks(){return Object.keys(this.updateCallbacks).length>0}getState(){return this.isAnnounced&&this.hasCallbacks()?3:this.isAnnounced?2:this.hasCallbacks()?1:0}}var lodash_clonedeep$1={exports:{}},hasRequiredLodash_clonedeep;function requireLodash_clonedeep(){return hasRequiredLodash_clonedeep||(hasRequiredLodash_clonedeep=1,function(e,t){var r="__lodash_hash_undefined__",n=9007199254740991,i="[object Arguments]",o="[object Boolean]",s="[object Date]",a="[object Function]",c="[object GeneratorFunction]",l="[object Map]",u="[object Number]",d="[object Object]",h="[object Promise]",p="[object RegExp]",g="[object Set]",m="[object String]",f="[object Symbol]",y="[object WeakMap]",$="[object ArrayBuffer]",b="[object DataView]",w="[object Float32Array]",v="[object Float64Array]",S="[object Int8Array]",E="[object Int16Array]",C="[object Int32Array]",_="[object Uint8Array]",I="[object Uint8ClampedArray]",T="[object Uint16Array]",A="[object Uint32Array]",D=/\w*$/,x=/^\[object .+?Constructor\]$/,R=/^(?:0|[1-9]\d*)$/,O={};O[i]=O["[object Array]"]=O[$]=O[b]=O[o]=O[s]=O[w]=O[v]=O[S]=O[E]=O[C]=O[l]=O[u]=O[d]=O[p]=O[g]=O[m]=O[f]=O[_]=O[I]=O[T]=O[A]=!0,O["[object Error]"]=O[a]=O[y]=!1;var P="object"==typeof commonjsGlobal&&commonjsGlobal&&commonjsGlobal.Object===Object&&commonjsGlobal,N="object"==typeof self&&self&&self.Object===Object&&self,k=P||N||Function("return this")(),M=t&&!t.nodeType&&t,L=M&&e&&!e.nodeType&&e,F=L&&L.exports===M;function j(e,t){return e.set(t[0],t[1]),e}function U(e,t){return e.add(t),e}function B(e,t,r,n){for(var i=-1,o=e?e.length:0;++i<o;)r=t(r,e[i],i,e);return r}function q(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(e){}return t}function H(e){var t=-1,r=Array(e.size);return e.forEach(function(e,n){r[++t]=[n,e]}),r}function W(e,t){return function(r){return e(t(r))}}function G(e){var t=-1,r=Array(e.size);return e.forEach(function(e){r[++t]=e}),r}var J,K=Array.prototype,V=Function.prototype,z=Object.prototype,X=k["__core-js_shared__"],Y=(J=/[^.]+$/.exec(X&&X.keys&&X.keys.IE_PROTO||""))?"Symbol(src)_1."+J:"",Z=V.toString,Q=z.hasOwnProperty,ee=z.toString,te=RegExp("^"+Z.call(Q).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),re=F?k.Buffer:void 0,ne=k.Symbol,ie=k.Uint8Array,oe=W(Object.getPrototypeOf,Object),se=Object.create,ae=z.propertyIsEnumerable,ce=K.splice,le=Object.getOwnPropertySymbols,ue=re?re.isBuffer:void 0,de=W(Object.keys,Object),he=Le(k,"DataView"),pe=Le(k,"Map"),ge=Le(k,"Promise"),me=Le(k,"Set"),fe=Le(k,"WeakMap"),ye=Le(Object,"create"),$e=qe(he),be=qe(pe),we=qe(ge),ve=qe(me),Se=qe(fe),Ee=ne?ne.prototype:void 0,Ce=Ee?Ee.valueOf:void 0;function _e(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function Ie(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function Te(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function Ae(e){this.__data__=new Ie(e)}function De(e,t){var r=We(e)||function(e){return function(e){return function(e){return!!e&&"object"==typeof e}(e)&&Ge(e)}(e)&&Q.call(e,"callee")&&(!ae.call(e,"callee")||ee.call(e)==i)}(e)?function(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}(e.length,String):[],n=r.length,o=!!n;for(var s in e)!Q.call(e,s)||o&&("length"==s||Ue(s,n))||r.push(s);return r}function xe(e,t,r){var n=e[t];Q.call(e,t)&&He(n,r)&&(void 0!==r||t in e)||(e[t]=r)}function Re(e,t){for(var r=e.length;r--;)if(He(e[r][0],t))return r;return-1}function Oe(e,t,r,n,h,y,x){var R;if(n&&(R=y?n(e,h,y,x):n(e)),void 0!==R)return R;if(!Ve(e))return e;var P=We(e);if(P){if(R=function(e){var t=e.length,r=e.constructor(t);t&&"string"==typeof e[0]&&Q.call(e,"index")&&(r.index=e.index,r.input=e.input);return r}(e),!t)return function(e,t){var r=-1,n=e.length;t||(t=Array(n));for(;++r<n;)t[r]=e[r];return t}(e,R)}else{var N=je(e),k=N==a||N==c;if(Je(e))return function(e,t){if(t)return e.slice();var r=new e.constructor(e.length);return e.copy(r),r}(e,t);if(N==d||N==i||k&&!y){if(q(e))return y?e:{};if(R=function(e){return"function"!=typeof e.constructor||Be(e)?{}:(t=oe(e),Ve(t)?se(t):{});var t}(k?{}:e),!t)return function(e,t){return ke(e,Fe(e),t)}(e,function(e,t){return e&&ke(t,ze(t),e)}(R,e))}else{if(!O[N])return y?e:{};R=function(e,t,r,n){var i=e.constructor;switch(t){case $:return Ne(e);case o:case s:return new i(+e);case b:return function(e,t){var r=t?Ne(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.byteLength)}(e,n);case w:case v:case S:case E:case C:case _:case I:case T:case A:return function(e,t){var r=t?Ne(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}(e,n);case l:return function(e,t,r){var n=t?r(H(e),!0):H(e);return B(n,j,new e.constructor)}(e,n,r);case u:case m:return new i(e);case p:return function(e){var t=new e.constructor(e.source,D.exec(e));return t.lastIndex=e.lastIndex,t}(e);case g:return function(e,t,r){var n=t?r(G(e),!0):G(e);return B(n,U,new e.constructor)}(e,n,r);case f:return a=e,Ce?Object(Ce.call(a)):{}}var a}(e,N,Oe,t)}}x||(x=new Ae);var M=x.get(e);if(M)return M;if(x.set(e,R),!P)var L=r?function(e){return function(e,t,r){var n=t(e);return We(e)?n:function(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e}(n,r(e))}(e,ze,Fe)}(e):ze(e);return function(e,t){for(var r=-1,n=e?e.length:0;++r<n&&!1!==t(e[r],r,e););}(L||e,function(i,o){L&&(i=e[o=i]),xe(R,o,Oe(i,t,r,n,o,e,x))}),R}function Pe(e){return!(!Ve(e)||(t=e,Y&&Y in t))&&(Ke(e)||q(e)?te:x).test(qe(e));var t}function Ne(e){var t=new e.constructor(e.byteLength);return new ie(t).set(new ie(e)),t}function ke(e,t,r,n){r||(r={});for(var i=-1,o=t.length;++i<o;){var s=t[i];xe(r,s,e[s])}return r}function Me(e,t){var r=e.__data__;return function(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}(t)?r["string"==typeof t?"string":"hash"]:r.map}function Le(e,t){var r=function(e,t){return null==e?void 0:e[t]}(e,t);return Pe(r)?r:void 0}_e.prototype.clear=function(){this.__data__=ye?ye(null):{}},_e.prototype.delete=function(e){return this.has(e)&&delete this.__data__[e]},_e.prototype.get=function(e){var t=this.__data__;if(ye){var n=t[e];return n===r?void 0:n}return Q.call(t,e)?t[e]:void 0},_e.prototype.has=function(e){var t=this.__data__;return ye?void 0!==t[e]:Q.call(t,e)},_e.prototype.set=function(e,t){return this.__data__[e]=ye&&void 0===t?r:t,this},Ie.prototype.clear=function(){this.__data__=[]},Ie.prototype.delete=function(e){var t=this.__data__,r=Re(t,e);return!(r<0)&&(r==t.length-1?t.pop():ce.call(t,r,1),!0)},Ie.prototype.get=function(e){var t=this.__data__,r=Re(t,e);return r<0?void 0:t[r][1]},Ie.prototype.has=function(e){return Re(this.__data__,e)>-1},Ie.prototype.set=function(e,t){var r=this.__data__,n=Re(r,e);return n<0?r.push([e,t]):r[n][1]=t,this},Te.prototype.clear=function(){this.__data__={hash:new _e,map:new(pe||Ie),string:new _e}},Te.prototype.delete=function(e){return Me(this,e).delete(e)},Te.prototype.get=function(e){return Me(this,e).get(e)},Te.prototype.has=function(e){return Me(this,e).has(e)},Te.prototype.set=function(e,t){return Me(this,e).set(e,t),this},Ae.prototype.clear=function(){this.__data__=new Ie},Ae.prototype.delete=function(e){return this.__data__.delete(e)},Ae.prototype.get=function(e){return this.__data__.get(e)},Ae.prototype.has=function(e){return this.__data__.has(e)},Ae.prototype.set=function(e,t){var r=this.__data__;if(r instanceof Ie){var n=r.__data__;if(!pe||n.length<199)return n.push([e,t]),this;r=this.__data__=new Te(n)}return r.set(e,t),this};var Fe=le?W(le,Object):function(){return[]},je=function(e){return ee.call(e)};function Ue(e,t){return!!(t=null==t?n:t)&&("number"==typeof e||R.test(e))&&e>-1&&e%1==0&&e<t}function Be(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||z)}function qe(e){if(null!=e){try{return Z.call(e)}catch(e){}try{return e+""}catch(e){}}return""}function He(e,t){return e===t||e!=e&&t!=t}(he&&je(new he(new ArrayBuffer(1)))!=b||pe&&je(new pe)!=l||ge&&je(ge.resolve())!=h||me&&je(new me)!=g||fe&&je(new fe)!=y)&&(je=function(e){var t=ee.call(e),r=t==d?e.constructor:void 0,n=r?qe(r):void 0;if(n)switch(n){case $e:return b;case be:return l;case we:return h;case ve:return g;case Se:return y}return t});var We=Array.isArray;function Ge(e){return null!=e&&function(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=n}(e.length)&&!Ke(e)}var Je=ue||function(){return!1};function Ke(e){var t=Ve(e)?ee.call(e):"";return t==a||t==c}function Ve(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function ze(e){return Ge(e)?De(e):function(e){if(!Be(e))return de(e);var t=[];for(var r in Object(e))Q.call(e,r)&&"constructor"!=r&&t.push(r);return t}(e)}e.exports=function(e){return Oe(e,!0,!0)}}(lodash_clonedeep$1,lodash_clonedeep$1.exports)),lodash_clonedeep$1.exports}lodash_clonedeep$1.exports;var lodash_clonedeepExports$1=requireLodash_clonedeep(),cloneDeep=getDefaultExportFromCjs(lodash_clonedeepExports$1);function applyContextDelta(e,t,r){try{if(r?.canPublish("trace")&&r?.trace(`applying context delta ${JSON.stringify(t)} on context ${JSON.stringify(e)}`),!t)return e;if(t.reset)return e={...t.reset};if(e=deepClone(e,void 0),t.commands){for(const r of t.commands)"remove"===r.type?deletePath(e,r.path):"set"===r.type&&setValueToPath(e,r.value,r.path);return e}const n=t.added,i=t.updated,o=t.removed;return n&&Object.keys(n).forEach(t=>{e[t]=n[t]}),i&&Object.keys(i).forEach(t=>{mergeObjectsProperties(t,e,i)}),o&&o.forEach(t=>{delete e[t]}),distExports.Traces.removePropagationInfo(e),e}catch(n){return r?.error(`error applying context delta ${JSON.stringify(t)} on context ${JSON.stringify(e)}`,n),e}}function deepClone(e,t){return cloneDeep(e)}const mergeObjectsProperties=(e,t,r)=>{const n=r[e];if(void 0===n)return t;const i=t[e];return i&&n?"string"==typeof i||"number"==typeof i||"boolean"==typeof i||"string"==typeof n||"number"==typeof n||"boolean"==typeof n||Array.isArray(i)||Array.isArray(n)?(t[e]=n,t):(t[e]=Object.assign({},i,n),t):(t[e]=n,t)};function deepEqual(e,t){if(e===t)return!0;if(!(e instanceof Object&&t instanceof Object))return!1;if(e.constructor!==t.constructor)return!1;for(const r in e)if(e.hasOwnProperty(r)){if(!t.hasOwnProperty(r))return!1;if(e[r]!==t[r]){if("object"!=typeof e[r])return!1;if(!deepEqual(e[r],t[r]))return!1}}for(const r in t)if(t.hasOwnProperty(r)&&!e.hasOwnProperty(r))return!1;return!0}function setValueToPath(e,t,r){const n=r.split("."),i=["__proto__","constructor","prototype"];let o;for(o=0;o<n.length-1;o++){const t=n[o];if(i.includes(t))throw new Error(`The provided path ${r} is invalid. It cannot contain segment/key that is equal to one of the following values: ${i}.`);e[t]||(e[t]={}),"object"!=typeof e[t]&&(e[t]={}),e=e[t]}e[n[o]]=t}function isSubset(e,t){return Object.keys(t).every(r=>"object"==typeof t[r]?isSubset(e?.[r]||{},t[r]||{}):t[r]===e?.[r])}function deletePath(e,t){const r=t.split(".");let n;for(n=0;n<r.length-1;n++){if(!e[r[n]])return;e=e[r[n]]}delete e[r[n]]}class GW3Bridge{ERROR_URI_FAILURE="global.errors.failure";ERROR_URI_INVALID_CONTEXT="global.errors.invalid_context";_logger;_connection;_trackAllContexts;_reAnnounceKnownContexts;_subscribeOnUpdate;_subscribeOnGet;_onlyReAnnounceSubscribedContexts;_gw3Session;_contextNameToData={};_gw3Subscriptions=[];_nextCallbackSubscriptionNumber=0;_creationPromises={};_contextNameToId={};_contextIdToName={};_protocolVersion=void 0;_contextsTempCache={};_contextsSubscriptionsCache=[];_systemContextsSubKey;get protocolVersion(){if(!this._protocolVersion){const e=this._connection.availableDomains.find(e=>"context"===e.uri);this._protocolVersion=e?.version??1}return this._protocolVersion}get setPathSupported(){return this.protocolVersion>=2}constructor(e){this._connection=e.connection,this._logger=e.logger,this._trackAllContexts=e.trackAllContexts,this._reAnnounceKnownContexts=e.reAnnounceKnownContexts,this._subscribeOnUpdate=e.subscribeOnUpdate??!0,this._subscribeOnGet=e.subscribeOnGet??!0,this._onlyReAnnounceSubscribedContexts=e.onlyReAnnounceSubscribedContexts??!0,this._gw3Session=this._connection.domain("global",[GW_MESSAGE_CONTEXT_CREATED,GW_MESSAGE_SUBSCRIBED_CONTEXT,GW_MESSAGE_CONTEXT_DESTROYED,GW_MESSAGE_CONTEXT_UPDATED]),this._gw3Session.disconnected(this.resetState.bind(this)),this._gw3Session.onJoined(e=>{if(e)return this._reAnnounceKnownContexts?void this.reInitiateState().then(()=>this._connection.setLibReAnnounced({name:"contexts"})).catch(e=>{this._logger.warn(`Error while re-announcing contexts: ${JSON.stringify(e)}`)}):(this._contextsTempCache={},this._connection.setLibReAnnounced({name:"contexts"}))}),this.subscribeToContextCreatedMessages(),this.subscribeToContextUpdatedMessages(),this.subscribeToContextDestroyedMessages(),this._connection.replayer?.drain(ContextMessageReplaySpec.name,e=>{const t=e.type;t&&(t===GW_MESSAGE_CONTEXT_CREATED||t===GW_MESSAGE_CONTEXT_ADDED||t===GW_MESSAGE_ACTIVITY_CREATED?this.handleContextCreatedMessage(e):t===GW_MESSAGE_SUBSCRIBED_CONTEXT||t===GW_MESSAGE_CONTEXT_UPDATED||t===GW_MESSAGE_JOINED_ACTIVITY?this.handleContextUpdatedMessage(e):t!==GW_MESSAGE_CONTEXT_DESTROYED&&t!==GW_MESSAGE_ACTIVITY_DESTROYED||this.handleContextDestroyedMessage(e))})}dispose(){for(const e of this._gw3Subscriptions)this._connection.off(e);this._gw3Subscriptions.length=0;for(const e in this._contextNameToData)this._contextNameToId.hasOwnProperty(e)&&delete this._contextNameToData[e]}createContext(e,t){if(e in this._creationPromises)return this._creationPromises[e];const r=distExports.Traces.currentTracingState;return r.addData("INFO",{context:e}),r.addData("DIAGNOSTIC",{data:t}),t=deepClone(t),r.injectPropagationInfo(t),this._creationPromises[e]=this._gw3Session.send({type:GW_MESSAGE_CREATE_CONTEXT,domain:"global",name:e,data:t,lifetime:"retained"}).then(r=>{this._contextNameToId[e]=r.context_id,this._contextIdToName[r.context_id]=e;const n=this._contextNameToData[e]||new GW3ContextData(r.context_id,e,!0,void 0);return n.isAnnounced=!0,n.name=e,n.contextId=r.context_id,n.context=r.data||deepClone(t),n.hasReceivedSnapshot=!0,this._contextNameToData[e]=n,delete this._creationPromises[e],n.sentExplicitSubscription=!0,n.createdByUs=!0,this.subscribe(e,()=>{}),r.context_id}),this._creationPromises[e]}all(){return Object.keys(this._contextNameToData).filter(e=>this._contextNameToData[e].isAnnounced)}async update(e,t){t&&(t=deepClone(t));const r=distExports.Traces.currentTracingState;e in this._creationPromises&&(await this._creationPromises[e],distExports.Traces.currentTracingState=r);const n=this._contextNameToData[e];if(r.addData("DIAGNOSTIC",{data:n}),r.addData("DEBUG",{delta:t}),!n||!n.isAnnounced)return void await this.createContext(e,t);const i=await this.get(n.name);distExports.Traces.currentTracingState=r,distExports.Traces.removePropagationInfo(i);const o=this.setPathSupported?this.calculateContextDeltaV2(i,t):this.calculateContextDeltaV1(i,t);if(!(Object.keys(o.added).length||Object.keys(o.updated).length||o.removed.length||o.commands?.length))return Promise.resolve();const s=deepClone(o);r.injectPropagationInfo(s);const a=await this._gw3Session.send({type:GW_MESSAGE_UPDATE_CONTEXT,domain:"global",context_id:n.contextId,delta:s},{},{skipPeerId:!1});distExports.Traces.currentTracingState=r,!this._subscribeOnUpdate||n.sentExplicitSubscription||n.activityId||this.subscribe(e,()=>{}),(this._subscribeOnUpdate||n.sentExplicitSubscription||n.activityId)&&(await n.snapshotPromise,distExports.Traces.currentTracingState=r,this.handleUpdated(n,o,{updaterId:a.peer_id}))}async set(e,t){t&&(t=deepClone(t));const r=distExports.Traces.currentTracingState;e in this._creationPromises&&(await this._creationPromises[e],distExports.Traces.currentTracingState=r);const n=this._contextNameToData[e];if(r.addData("DIAGNOSTIC",{data:n}),r.injectPropagationInfo(t),!n||!n.isAnnounced)return this.createContext(e,t);const i=await this._gw3Session.send({type:GW_MESSAGE_UPDATE_CONTEXT,domain:"global",context_id:n.contextId,delta:{reset:t}},{},{skipPeerId:!1});distExports.Traces.currentTracingState=r,!this._subscribeOnUpdate||n.sentExplicitSubscription||n.activityId||this.subscribe(e,()=>{}),(this._subscribeOnUpdate||n.sentExplicitSubscription||n.activityId)&&this.handleUpdated(n,{reset:t,added:{},removed:[],updated:{}},{updaterId:i.peer_id})}setPath(e,t,r){return this.setPathSupported?this.setPaths(e,[{path:t,value:r}]):Promise.reject(new Error("contexts.setPath operation is not supported, use version 3.10 or later"))}async setPaths(e,t){if(!this.setPathSupported)return Promise.reject(new Error("contexts.setPaths operation is not supported, use version 3.10 or later"));t&&(t=deepClone(t));const r=distExports.Traces.currentTracingState;e in this._creationPromises&&(await this._creationPromises[e],distExports.Traces.currentTracingState=r);const n=this._contextNameToData[e];r.addData("DIAGNOSTIC",{data:n}),r.addData("DEBUG",{pathValues:t});const i={[distExports.OTEL_PI_KEY]:void 0};if(r.injectPropagationInfo(i),i[distExports.OTEL_PI_KEY]&&t.push({path:distExports.OTEL_PI_KEY,value:i[distExports.OTEL_PI_KEY]}),!n||!n.isAnnounced){const r={};for(const e of t)setValueToPath(r,e.value,e.path);return this.createContext(e,r)}const o=[];for(const e of t)null===e.value?o.push({type:"remove",path:e.path}):o.push({type:"set",path:e.path,value:e.value});const s=await this._gw3Session.send({type:GW_MESSAGE_UPDATE_CONTEXT,domain:"global",context_id:n.contextId,delta:{commands:o}},{},{skipPeerId:!1});distExports.Traces.currentTracingState=r,!this._subscribeOnUpdate||n.sentExplicitSubscription||n.activityId||this.subscribe(e,()=>{}),(this._subscribeOnUpdate||n.sentExplicitSubscription||n.activityId)&&(await n.snapshotPromise,distExports.Traces.currentTracingState=r,this.handleUpdated(n,{added:{},removed:[],updated:{},commands:o},{updaterId:s.peer_id}))}async get(e){const t=distExports.Traces.currentTracingState;t.addData("INFO",{context:e}),e in this._creationPromises&&(await this._creationPromises[e],distExports.Traces.currentTracingState=t);const r=this._contextNameToData[e];if(!r||!r.isAnnounced)return!r&&this._subscribeOnGet&&this.subscribeInner(e,()=>{}),Promise.resolve({});if(r&&!r.sentExplicitSubscription)return new Promise((t,r)=>{this.subscribeInner(e,(e,r,n,i)=>{distExports.Traces.removePropagationInfo(e),this._subscribeOnGet||this.unsubscribe(i),t(e)}).catch(e=>{this.isInvalidContextError(e)?t({}):r(e)})});await r.snapshotPromise;const n=r?.context??{};return distExports.Traces.removePropagationInfo(n),Promise.resolve(deepClone(n))}isInvalidContextError(e){return e.reason_uri===this.ERROR_URI_INVALID_CONTEXT||e.reason_uri===this.ERROR_URI_FAILURE&&e.reason?.startsWith("Unable to find context with id")}async subscribeInner(e,t,r){const n=distExports.Traces.currentTracingState;e in this._creationPromises&&(await this._creationPromises[e],distExports.Traces.currentTracingState=n);const i=void 0===r?this._nextCallbackSubscriptionNumber:r;void 0===r&&(this._nextCallbackSubscriptionNumber+=1,this._contextsSubscriptionsCache.push({contextName:e,subKey:i,callback:t}));let o=this._contextNameToData[e];if(!o||!o.isAnnounced)return o=o||new GW3ContextData(void 0,e,!1,void 0),this._contextNameToData[e]=o,o.updateCallbacks[i]=t,Promise.resolve(i);const s=o.hasCallbacks();if(o.updateCallbacks[i]=t,s){if(o.hasReceivedSnapshot&&!r){const e=deepClone(o.context);t(e,e,[],i)}return Promise.resolve(i)}if(o.joinedActivity||o.createdByUs){if(o.hasReceivedSnapshot&&!r){const e=deepClone(o.context);t(e,e,[],i)}return Promise.resolve(i)}if(o.context&&o.sentExplicitSubscription){if(o.hasReceivedSnapshot&&!r){const e=deepClone(o.context);t(e,e,[],i)}return Promise.resolve(i)}return this.sendSubscribe(o).then(()=>i,()=>(this.unsubscribe(i,!0),i))}async subscribe(e,t,r){const n=this.all().includes(e);distExports.Traces.currentTracingState.addData("INFO",{context:e,contextExists:n});return this.subscribeInner(e,async(...r)=>distExports.withSpan("interopio.api.contexts.bridge.subscribe.callback",{context:e},r?.[5],n=>(distExports.Traces.removePropagationInfo(r?.[0]),distExports.Traces.removePropagationInfo(r?.[1]),n.addData("INFO",{context:e}),n.addData("DEBUG",{delta:r?.[1]}),n.addData("DEBUG",{removed:r?.[2]}),n.addData("DIAGNOSTIC",{data:r?.[0]}),t(r?.[0],r?.[1],r?.[2],r?.[3],r?.[4]))),r)}unsubscribe(e,t){t||(this._contextsSubscriptionsCache=this._contextsSubscriptionsCache.filter(t=>t.subKey!==e));for(const t of Object.keys(this._contextNameToData)){const r=this._contextNameToData[t];if(!r)continue;const n=r.hasCallbacks();delete r.updateCallbacks[e],r.isAnnounced&&n&&!r.hasCallbacks()&&r.sentExplicitSubscription&&(r.hasReceivedSnapshot=!1,r.context={},this.sendUnsubscribe(r).catch(()=>{})),r.isAnnounced||r.hasCallbacks()||(delete this._contextNameToData[t],delete this._contextNameToId[t],r.contextId&&delete this._contextIdToName[r.contextId])}}async destroy(e){const t=distExports.Traces.currentTracingState;t.addData("INFO",{context:e}),e in this._creationPromises&&(await this._creationPromises[e],distExports.Traces.currentTracingState=t);const r=this._contextNameToData[e],n=r?.contextId;return r&&n?this._gw3Session.send({type:GW_MESSAGE_DESTROY_CONTEXT,domain:"global",context_id:r.contextId}).then(()=>{}):Promise.reject(`context with ${e} does not exist`)}handleUpdated(e,t,r){const n=e.context;e.context=applyContextDelta(e.context,t,this._logger),this._contextNameToData[e.name]!==e||deepEqual(n,e.context)||this.invokeUpdateCallbacks(e,t,r)}subscribeToContextCreatedMessages(){const e=[GW_MESSAGE_CONTEXT_ADDED,GW_MESSAGE_CONTEXT_CREATED,GW_MESSAGE_ACTIVITY_CREATED];for(const t of e){const e=this._connection.on(t,this.handleContextCreatedMessage.bind(this));this._gw3Subscriptions.push(e)}}handleContextCreatedMessage(e){const t=e.type;t===GW_MESSAGE_ACTIVITY_CREATED?(this._contextNameToId[e.activity_id]=e.context_id,this._contextIdToName[e.context_id]=e.activity_id):t===GW_MESSAGE_CONTEXT_ADDED&&(this._contextNameToId[e.name]=e.context_id,this._contextIdToName[e.context_id]=e.name);const r=this._contextIdToName[e.context_id];if(!r)throw new Error("Received created event for context with unknown name: "+e.context_id);if(!this._contextNameToId[r])throw new Error("Received created event for context with unknown id: "+e.context_id);let n=this._contextNameToData[r];if(n){if(n.isAnnounced)return;if(!n.hasCallbacks())throw new Error("Assertion failure: contextData.hasCallbacks()");n.isAnnounced=!0,n.contextId=e.context_id,n.activityId=e.activity_id,n.sentExplicitSubscription||this.sendSubscribe(n).catch(()=>{})}else this._contextNameToData[r]=new GW3ContextData(e.context_id,r,!0,e.activity_id),this._trackAllContexts&&this.subscribe(r,()=>{}).then(e=>this._systemContextsSubKey=e)}subscribeToContextUpdatedMessages(){const e=[GW_MESSAGE_CONTEXT_UPDATED,GW_MESSAGE_SUBSCRIBED_CONTEXT,GW_MESSAGE_JOINED_ACTIVITY];for(const t of e){const e=this._connection.on(t,this.handleContextUpdatedMessage.bind(this));this._gw3Subscriptions.push(e)}}handleContextUpdatedMessage(e){const t=e.type,r=e.context_id;let n=this._contextNameToData[this._contextIdToName[r]];const i=!n||!n.isAnnounced;if(t===GW_MESSAGE_JOINED_ACTIVITY)n||(n=this._contextNameToData[e.activity_id]||new GW3ContextData(r,e.activity_id,!0,e.activity_id)),this._contextNameToData[e.activity_id]=n,this._contextIdToName[r]=e.activity_id,this._contextNameToId[e.activity_id]=r,n.contextId=r,n.isAnnounced=!0,n.activityId=e.activity_id,n.joinedActivity=!0;else if(!n||!n.isAnnounced)return void(t===GW_MESSAGE_SUBSCRIBED_CONTEXT?(n=n||new GW3ContextData(r,e.name,!0,void 0),n.sentExplicitSubscription=!0,this._contextNameToData[e.name]=n,this._contextIdToName[r]=e.name,this._contextNameToId[e.name]=r):this._logger.error(`Received 'update' for unknown context: ${r}`));const o=n.context;if(n.hasReceivedSnapshot=!0,t===GW_MESSAGE_SUBSCRIBED_CONTEXT)n.context=e.data??{};else if(t===GW_MESSAGE_JOINED_ACTIVITY)n.context=e.context_snapshot??{};else{if(t!==GW_MESSAGE_CONTEXT_UPDATED)throw new Error("Unrecognized context update message "+t);n.context=applyContextDelta(n.context,e.delta,this._logger)}!i&&deepEqual(n.context,o)&&t!==GW_MESSAGE_SUBSCRIBED_CONTEXT||this.invokeUpdateCallbacks(n,e.delta??e.data,{updaterId:e.updater_id})}invokeUpdateCallbacks(e,t,r){if((t=t||{added:{},updated:{},reset:{},removed:[]}).commands){t.added=t.updated=t.reset={},t.removed=[];for(const e of t.commands)"remove"===e.type?(-1===e.path.indexOf(".")&&t.removed.push(e.path),setValueToPath(t.updated,null,e.path)):"set"===e.type&&setValueToPath(t.updated,e.value,e.path)}for(const n in e.updateCallbacks)if(e.updateCallbacks.hasOwnProperty(n))try{const i=e.updateCallbacks[n],o=deepClone({...t.added,...t.updated,...t.reset});i(deepClone(e.context),o,t.removed,parseInt(n,10),r,distExports.Traces.extractPropagationInfo(t))}catch(e){this._logger.debug("callback error: "+JSON.stringify(e))}}subscribeToContextDestroyedMessages(){const e=[GW_MESSAGE_CONTEXT_DESTROYED,GW_MESSAGE_ACTIVITY_DESTROYED];for(const t of e){const e=this._connection.on(t,this.handleContextDestroyedMessage.bind(this));this._gw3Subscriptions.push(e)}}handleContextDestroyedMessage(e){let t,r;if(e.type===GW_MESSAGE_ACTIVITY_DESTROYED){if(r=e.activity_id,t=this._contextNameToId[r],!t)return void this._logger.error(`Received 'destroyed' for unknown activity: ${e.activity_id}`)}else if(t=e.context_id,r=this._contextIdToName[t],!r)return void this._logger.error(`Received 'destroyed' for unknown context: ${e.context_id}`);delete this._contextIdToName[t],delete this._contextNameToId[r];const n=this._contextNameToData[r];delete this._contextNameToData[r],n&&n.isAnnounced||this._logger.error(`Received 'destroyed' for unknown context: ${t}`)}async sendSubscribe(e){e.sentExplicitSubscription=!0;try{return void await this._gw3Session.send({type:GW_MESSAGE_SUBSCRIBE_CONTEXT,domain:"global",context_id:e.contextId})}catch(t){throw e.sentExplicitSubscription=!1,t}}async sendUnsubscribe(e){const t=e.sentExplicitSubscription;e.sentExplicitSubscription=!1;try{return void await this._gw3Session.send({type:GW_MESSAGE_UNSUBSCRIBE_CONTEXT,domain:"global",context_id:e.contextId})}catch(r){throw e.sentExplicitSubscription=t,r}}calculateContextDeltaV1(e,t){const r={added:{},updated:{},removed:[],reset:void 0};if(e)for(const n of Object.keys(e))-1===Object.keys(t).indexOf(n)||null===t[n]||deepEqual(e[n],t[n])||(r.updated[n]=t[n]);for(const n of Object.keys(t))e&&-1!==Object.keys(e).indexOf(n)?null===t[n]&&r.removed.push(n):null!==t[n]&&(r.added[n]=t[n]);return r}calculateContextDeltaV2(e,t){const r={added:{},updated:{},removed:[],reset:void 0,commands:[]};for(const n of Object.keys(t))if(null!==t[n]){deepEqual(e?e[n]:null,t[n])||r.commands?.push({type:"set",path:n,value:t[n]})}else r.commands?.push({type:"remove",path:n});return r}resetState(){for(const e of this._gw3Subscriptions)this._connection.off(e);this._systemContextsSubKey&&(this.unsubscribe(this._systemContextsSubKey,!0),delete this._systemContextsSubKey),this._gw3Subscriptions=[],this._contextNameToId={},this._contextIdToName={},delete this._protocolVersion,this._contextsTempCache=Object.keys(this._contextNameToData).reduce((e,t)=>{const r=this._contextNameToData[t];return(!this._onlyReAnnounceSubscribedContexts||r.hasReceivedSnapshot)&&(e[t]=this._contextNameToData[t].context),e},{}),this._contextNameToData={}}async reInitiateState(){this.subscribeToContextCreatedMessages(),this.subscribeToContextUpdatedMessages(),this.subscribeToContextDestroyedMessages(),this._connection.replayer?.drain(ContextMessageReplaySpec.name,e=>{const t=e.type;t&&(t===GW_MESSAGE_CONTEXT_CREATED||t===GW_MESSAGE_CONTEXT_ADDED||t===GW_MESSAGE_ACTIVITY_CREATED?this.handleContextCreatedMessage(e):t===GW_MESSAGE_SUBSCRIBED_CONTEXT||t===GW_MESSAGE_CONTEXT_UPDATED||t===GW_MESSAGE_JOINED_ACTIVITY?this.handleContextUpdatedMessage(e):t!==GW_MESSAGE_CONTEXT_DESTROYED&&t!==GW_MESSAGE_ACTIVITY_DESTROYED||this.handleContextDestroyedMessage(e))}),await Promise.all(this._contextsSubscriptionsCache.map(e=>this.subscribe(e.contextName,e.callback,e.subKey))),await this.flushQueue();for(const e in this._contextsTempCache){if("object"!=typeof this._contextsTempCache[e]||0===Object.keys(this._contextsTempCache[e]).length)continue;const t=this._contextsTempCache[e];this._logger.info(`Re-announcing known context: ${e}`),await this.flushQueue(),await this.update(e,t)}this._contextsTempCache={},this._logger.info("Contexts are re-announced")}flushQueue(){return new Promise(e=>setTimeout(()=>e(),0))}}__decorate([distExports.withSpan("interopio.api.contexts.bridge.create",{argMapping:["context"]})],GW3Bridge.prototype,"createContext",null),__decorate([distExports.withSpan("interopio.api.contexts.bridge.update",{argMapping:["context"]})],GW3Bridge.prototype,"update",null),__decorate([distExports.withSpan("interopio.api.contexts.bridge.set",{argMapping:["context"]})],GW3Bridge.prototype,"set",null),__decorate([distExports.withSpan("interopio.api.contexts.bridge.setPaths",{argMapping:["context"]})],GW3Bridge.prototype,"setPaths",null),__decorate([distExports.withSpan("interopio.api.contexts.bridge.get",{argMapping:["context"]})],GW3Bridge.prototype,"get",null),__decorate([distExports.withSpan("interopio.api.contexts.bridge.subscribe",{argMapping:["context"]})],GW3Bridge.prototype,"subscribe",null),__decorate([distExports.withSpan("interopio.api.contexts.bridge.destroy",{argMapping:["context"]})],GW3Bridge.prototype,"destroy",null);class ContextsModule{initTime;initStartTime;initEndTime;_bridge;constructor(e){this._bridge=new GW3Bridge(e)}all(){return this._bridge.all()}update(e,t){return this.checkName(e),this.checkData(t),this._bridge.update(e,t)}set(e,t){return this.checkName(e),this.checkData(t),this._bridge.set(e,t)}setPath(e,t,r){this.checkName(e),this.checkPath(t);return""===t?(this.checkData(r),this.set(e,r)):this._bridge.setPath(e,t,r)}setPaths(e,t){if(this.checkName(e),!Array.isArray(t))throw new Error("Please provide the paths as an array of PathValues!");for(const{path:e,value:r}of t){this.checkPath(e);""===e&&this.checkData(r)}return this._bridge.setPaths(e,t)}subscribe(e,t){if(this.checkName(e),"function"!=typeof t)throw new Error("Please provide the callback as a function!");return this._bridge.subscribe(e,(e,r,n,i,o)=>t(e,r,n,()=>this._bridge.unsubscribe(i),o)).then(e=>()=>{this._bridge.unsubscribe(e)})}get(e){return this.checkName(e),this._bridge.get(e)}ready(){return Promise.resolve(this)}destroy(e){return this.checkName(e),this._bridge.destroy(e)}get setPathSupported(){return this._bridge.setPathSupported}checkName(e){if("string"!=typeof e||""===e)throw new Error("Please provide the name as a non-empty string!")}checkPath(e){if("string"!=typeof e)throw new Error("Please provide the path as a dot delimited string!")}checkData(e){if("object"!=typeof e)throw new Error("Please provide the data as an object!")}}function promisify(e,t,r){return"function"!=typeof t&&"function"!=typeof r?e:("function"!=typeof t?t=()=>{}:"function"!=typeof r&&(r=()=>{}),e.then(t,r))}function rejectAfter(e=0,t,r){let n;const i=()=>{n&&clearTimeout(n)};return t.then(()=>{i()}).catch(()=>{i()}),new Promise((t,i)=>{n=setTimeout(()=>i(r),e)})}__decorate([distExports.withSpan("interopio.api.contexts.module.update",{argMapping:["context"]})],ContextsModule.prototype,"update",null),__decorate([distExports.withSpan("interopio.api.contexts.module.set",{argMapping:["context"]})],ContextsModule.prototype,"set",null),__decorate([distExports.withSpan("interopio.api.contexts.module.setPaths",{argMapping:["context"]})],ContextsModule.prototype,"setPaths",null),__decorate([distExports.withSpan("interopio.api.contexts.module.subscribe",{argMapping:["context"]})],ContextsModule.prototype,"subscribe",null),__decorate([distExports.withSpan("interopio.api.contexts.module.destroy",{argMapping:["context"]})],ContextsModule.prototype,"destroy",null);var ok=function(e){return{ok:!0,result:e}},err=function(e){return{ok:!1,error:e}},asPromise=function(e){return!0===e.ok?Promise.resolve(e.result):Promise.reject(e.error)},withDefault=function(e,t){return!0===t.ok?t.result:e},withException=function(e){if(!0===e.ok)return e.result;throw e.error},map=function(e,t){return!0===t.ok?ok(e(t.result)):t},map2=function(e,t,r){return!1===t.ok?t:!1===r.ok?r:ok(e(t.result,r.result))},mapError=function(e,t){return!0===t.ok?t:err(e(t.error))},andThen=function(e,t){return!0===t.ok?e(t.result):t},__assign=function(){return __assign=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var i in t=arguments[r])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},__assign.apply(this,arguments)};function __rest(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(n=Object.getOwnPropertySymbols(e);i<n.length;i++)t.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(r[n[i]]=e[n[i]])}return r}function isEqual(e,t){if(e===t)return!0;if(null===e&&null===t)return!0;if(typeof e!=typeof t)return!1;if("object"==typeof e){if(Array.isArray(e)){if(!Array.isArray(t))return!1;if(e.length!==t.length)return!1;for(var r=0;r<e.length;r++)if(!isEqual(e[r],t[r]))return!1;return!0}var n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(r=0;r<n.length;r++){if(!t.hasOwnProperty(n[r]))return!1;if(!isEqual(e[n[r]],t[n[r]]))return!1}return!0}}var isJsonArray=function(e){return Array.isArray(e)},isJsonObject=function(e){return"object"==typeof e&&null!==e&&!isJsonArray(e)},typeString=function(e){switch(typeof e){case"string":return"a string";case"number":return"a number";case"boolean":return"a boolean";case"undefined":return"undefined";case"object":return e instanceof Array?"an array":null===e?"null":"an object";default:return JSON.stringify(e)}},expectedGot=function(e,t){return"expected "+e+", got "+typeString(t)},printPath=function(e){return e.map(function(e){return"string"==typeof e?"."+e:"["+e+"]"}).join("")},prependAt=function(e,t){var r=t.at,n=__rest(t,["at"]);return __assign({at:e+(r||"")},n)},Decoder=function(){function e(t){var r=this;this.decode=t,this.run=function(e){return mapError(function(t){return{kind:"DecoderError",input:e,at:"input"+(t.at||""),message:t.message||""}},r.decode(e))},this.runPromise=function(e){return asPromise(r.run(e))},this.runWithException=function(e){return withException(r.run(e))},this.map=function(t){return new e(function(e){return map(t,r.decode(e))})},this.andThen=function(t){return new e(function(e){return andThen(function(r){return t(r).decode(e)},r.decode(e))})},this.where=function(t,n){return r.andThen(function(r){return t(r)?e.succeed(r):e.fail(n)})}}return e.string=function(){return new e(function(e){return"string"==typeof e?ok(e):err({message:expectedGot("a string",e)})})},e.number=function(){return new e(function(e){return"number"==typeof e?ok(e):err({message:expectedGot("a number",e)})})},e.boolean=function(){return new e(function(e){return"boolean"==typeof e?ok(e):err({message:expectedGot("a boolean",e)})})},e.constant=function(t){return new e(function(e){return isEqual(e,t)?ok(t):err({message:"expected "+JSON.stringify(t)+", got "+JSON.stringify(e)})})},e.object=function(t){return new e(function(e){if(isJsonObject(e)&&t){var r={};for(var n in t)if(t.hasOwnProperty(n)){var i=t[n].decode(e[n]);if(!0!==i.ok)return void 0===e[n]?err({message:"the key '"+n+"' is required but was not present"}):err(prependAt("."+n,i.error));void 0!==i.result&&(r[n]=i.result)}return ok(r)}return isJsonObject(e)?ok(e):err({message:expectedGot("an object",e)})})},e.array=function(t){return new e(function(e){if(isJsonArray(e)&&t){return e.reduce(function(e,r,n){return map2(function(e,t){return e.concat([t])},e,function(e,r){return mapError(function(e){return prependAt("["+r+"]",e)},t.decode(e))}(r,n))},ok([]))}return isJsonArray(e)?ok(e):err({message:expectedGot("an array",e)})})},e.tuple=function(t){return new e(function(e){if(isJsonArray(e)){if(e.length!==t.length)return err({message:"expected a tuple of length "+t.length+", got one of length "+e.length});for(var r=[],n=0;n<t.length;n++){var i=t[n].decode(e[n]);if(!i.ok)return err(prependAt("["+n+"]",i.error));r[n]=i.result}return ok(r)}return err({message:expectedGot("a tuple of length "+t.length,e)})})},e.union=function(t,r){for(var n=[],i=2;i<arguments.length;i++)n[i-2]=arguments[i];return e.oneOf.apply(e,[t,r].concat(n))},e.intersection=function(t,r){for(var n=[],i=2;i<arguments.length;i++)n[i-2]=arguments[i];return new e(function(e){return[t,r].concat(n).reduce(function(t,r){return map2(Object.assign,t,r.decode(e))},ok({}))})},e.anyJson=function(){return new e(function(e){return ok(e)})},e.unknownJson=function(){return new e(function(e){return ok(e)})},e.dict=function(t){return new e(function(e){if(isJsonObject(e)){var r={};for(var n in e)if(e.hasOwnProperty(n)){var i=t.decode(e[n]);if(!0!==i.ok)return err(prependAt("."+n,i.error));r[n]=i.result}return ok(r)}return err({message:expectedGot("an object",e)})})},e.optional=function(t){return new e(function(e){return null==e?ok(void 0):t.decode(e)})},e.oneOf=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return new e(function(e){for(var r=[],n=0;n<t.length;n++){var i=t[n].decode(e);if(!0===i.ok)return i;r[n]=i.error}var o=r.map(function(e){return"at error"+(e.at||"")+": "+e.message}).join('", "');return err({message:'expected a value matching one of the decoders, got the errors ["'+o+'"]'})})},e.withDefault=function(t,r){return new e(function(e){return ok(withDefault(t,r.decode(e)))})},e.valueAt=function(t,r){return new e(function(e){for(var n=e,i=0;i<t.length;i++){if(void 0===n)return err({at:printPath(t.slice(0,i+1)),message:"path does not exist"});if("string"==typeof t[i]&&!isJsonObject(n))return err({at:printPath(t.slice(0,i+1)),message:expectedGot("an object",n)});if("number"==typeof t[i]&&!isJsonArray(n))return err({at:printPath(t.slice(0,i+1)),message:expectedGot("an array",n)});n=n[t[i]]}return mapError(function(e){return void 0===n?{at:printPath(t),message:"path does not exist"}:prependAt(printPath(t),e)},r.decode(n))})},e.succeed=function(t){return new e(function(e){return ok(t)})},e.fail=function(t){return new e(function(e){return err({message:t})})},e.lazy=function(t){return new e(function(e){return t().decode(e)})},e}(),string$2=Decoder.string,number$2=Decoder.number,boolean$2=Decoder.boolean,anyJson=Decoder.anyJson;Decoder.unknownJson;var constant=Decoder.constant,object=Decoder.object,array$1=Decoder.array;Decoder.tuple,Decoder.dict;var optional$1=Decoder.optional;Decoder.oneOf;var union$1=Decoder.union;Decoder.intersection,Decoder.withDefault,Decoder.valueAt,Decoder.succeed;var fail$1=Decoder.fail;Decoder.lazy;const functionCheck=(e,t)=>{const r=typeof e;return"function"===r?anyJson():fail$1(`The provided argument as ${t} should be of type function, provided: ${r}`)},nonEmptyStringDecoder=string$2().where(e=>e.length>0,"Expected a non-empty string"),nonNegativeNumberDecoder=number$2().where(e=>e>=0,"Expected a non-negative number or 0"),methodDefinitionDecoder=object({name:nonEmptyStringDecoder,objectTypes:optional$1(array$1(nonEmptyStringDecoder)),displayName:optional$1(string$2()),accepts:optional$1(string$2()),returns:optional$1(string$2()),description:optional$1(string$2()),version:optional$1(nonNegativeNumberDecoder),supportsStreaming:optional$1(boolean$2()),flags:optional$1(object()),getServers:optional$1(anyJson().andThen(e=>functionCheck(e,"method definition getServers")))}),methodFilterDecoder=union$1(nonEmptyStringDecoder,methodDefinitionDecoder),instanceDecoder=object({application:optional$1(nonEmptyStringDecoder),applicationName:optional$1(nonEmptyStringDecoder),pid:optional$1(nonNegativeNumberDecoder),machine:optional$1(nonEmptyStringDecoder),user:optional$1(nonEmptyStringDecoder),environment:optional$1(nonEmptyStringDecoder),region:optional$1(nonEmptyStringDecoder),service:optional$1(nonEmptyStringDecoder),instance:optional$1(nonEmptyStringDecoder),windowId:optional$1(nonEmptyStringDecoder),peerId:optional$1(nonEmptyStringDecoder),isLocal:optional$1(boolean$2()),api:optional$1(nonEmptyStringDecoder),getMethods:optional$1(anyJson().andThen(e=>functionCheck(e,"instance getMethods"))),getStreams:optional$1(anyJson().andThen(e=>functionCheck(e,"instance getStreams")))}),targetDecoder=union$1(constant("best"),constant("all"),constant("skipMine"),instanceDecoder,array$1(instanceDecoder)),invokeOptionsDecoder=object({waitTimeoutMs:optional$1(nonNegativeNumberDecoder),methodResponseTimeoutMs:optional$1(nonNegativeNumberDecoder)});var InvokeStatus;!function(e){e[e.Success=0]="Success",e[e.Error=1]="Error"}(InvokeStatus||(InvokeStatus={}));class Client{protocol;repo;instance;configuration;constructor(e,t,r,n){this.protocol=e,this.repo=t,this.instance=r,this.configuration=n}subscribe(e,t,r,n,i){const o=distExports.Traces.currentTracingState;o.addData("INFO",{stream:Utils.getMethodName(e)}),o.addData("INFO",{options:t});const s=(e,r,n,o)=>{t.methodResponseTimeout=t.methodResponseTimeout??t.waitTimeoutMs,this.protocol.client.subscribe(r,t,e,n,o,i)},a=new Promise((r,n)=>{const i=e=>{r(e)},o=e=>{n(e)};if(!e)return void n("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");let a;if(a="string"==typeof e?{name:e}:e,!a.name)return void n("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");void 0===t&&(t={});let c=t.target;if(void 0===c&&(c="best"),"string"==typeof c&&"all"!==c&&"best"!==c)return void n(new Error(`"${c}" is not a valid target. Valid targets are "all", "best", or an instance.`));void 0===t.methodResponseTimeout&&(t.methodResponseTimeout=t.method_response_timeout,void 0===t.methodResponseTimeout&&(t.methodResponseTimeout=this.configuration.methodResponseTimeout)),void 0===t.waitTimeoutMs&&(t.waitTimeoutMs=t.wait_for_method_timeout,void 0===t.waitTimeoutMs&&(t.waitTimeoutMs=this.configuration.waitTimeoutMs));let l=0,u=this.getServerMethodsByFilterAndTarget(a,c);if(u.length>0)s(u,u[0].methods[0],i,o);else{const r=()=>{if(c&&t.waitTimeoutMs)if(l+=500,u=this.getServerMethodsByFilterAndTarget(a,c),u.length>0){const e=u[0].methods[0];s(u,e,i,o)}else if(l>=t.waitTimeoutMs){s(u,"string"==typeof e?{name:e}:e,i,o)}else setTimeout(r,500)};setTimeout(r,500)}});return promisify(a,r,n)}servers(e){const t=void 0===e?void 0:{...e};return this.getServers(t).map(e=>e.server.instance)}methods(e){return e="string"==typeof e?{name:e}:{...e},this.getMethods(e)}methodsForInstance(e){return this.getMethodsForInstance(e)}methodAdded(e){return this.repo.onMethodAdded(e)}methodRemoved(e){return this.repo.onMethodRemoved(e)}serverAdded(e){return this.repo.onServerAdded(e)}serverRemoved(e){return this.repo.onServerRemoved((t,r)=>{e(t,r)})}serverMethodAdded(e){return this.repo.onServerMethodAdded((t,r)=>{e({server:t,method:r})})}serverMethodRemoved(e){return this.repo.onServerMethodRemoved((t,r)=>{e({server:t,method:r})})}async invoke(e,t,r,n,i,o){const s=distExports.Traces.currentTracingState;s.addData("INFO",{method:Utils.getMethodName(e)}),s.addData("INFO",{target:r,additionalOptions:n}),s.addData("DIAGNOSTIC",{arguments:t});return promisify((async()=>{const s="string"==typeof e?{name:e}:{...e};t||(t={}),r||(r="best"),n||(n={});const a=methodFilterDecoder.run(s);if(!a.ok){const e=`The provided 'method' argument is invalid. Error: ${JSON.stringify(a.error)}.`;return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}if("object"!=typeof t){const e="The provided 'argumentObj' argument is invalid. Error: The argumentObj should be an instance of an object";return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}const c=targetDecoder.run(r);if(!c.ok){const e=`The provided 'target' argument is invalid. Error: ${JSON.stringify(c.error)}.`;return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}const l=invokeOptionsDecoder.run(n);if(!l.ok){const e=`The provided 'options' argument is invalid. Error: ${JSON.stringify(l.error)}.`;return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}if(i&&"function"!=typeof i){const e="The provided 'success' function is invalid. Error: The success should be a valid function";return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}if(o&&"function"!=typeof o){const e="The provided 'error' function is invalid. Error: The error should be a valid function";return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}void 0===n.methodResponseTimeoutMs&&(n.methodResponseTimeoutMs=n.method_response_timeout,void 0===n.methodResponseTimeoutMs&&(n.methodResponseTimeoutMs=this.configuration.methodResponseTimeout)),void 0===n.waitTimeoutMs&&(n.waitTimeoutMs=n.wait_for_method_timeout,void 0===n.waitTimeoutMs&&(n.waitTimeoutMs=this.configuration.waitTimeoutMs));let u=this.getServerMethodsByFilterAndTarget(s,r);if(0===u.length)try{u=await this.tryToAwaitForMethods(s,r,n)}catch(n){const i=`Can not find a method matching ${JSON.stringify(e)} with server filter ${JSON.stringify(r)}`;return Promise.reject(this.generateInvalidInputInvocationResult(i,s,t))}const d=n.methodResponseTimeoutMs??3e4,h=n,p=u.map(e=>this.getServerInvokePromise(e.methods[0],e.server,t,h,d)),g=await Promise.all(p),m=this.getInvocationResultObj(g,s,t);return g.every(e=>e.status===InvokeStatus.Error)?Promise.reject(m):m})(),i,o)}async getServerInvokePromise(e,t,r,n,i){const o=nanoid$1(10),s=distExports.Traces.currentTracingState;r&&(r=deepClone(r),s.injectPropagationInfo(r)),s.addData("INFO",{server:t?.id,instance:t?.instance}),s.addData("INFO",{invocationId:o});const a=this.protocol.client.invoke(o,e,r,t,n),c=await Promise.race([a,rejectAfter(i,a,{invocationId:o,message:`Invocation timeout (${i} ms) reached for method name: ${e?.name}, target instance: ${JSON.stringify(t.instance)}, options: ${JSON.stringify(n)}`,status:InvokeStatus.Error})]);return s.addData("DIAGNOSTIC",{returnValue:c}),c}generateInvalidInputInvocationResult(e,t,r){const n={...t,getServers:()=>[],supportsStreaming:!1,objectTypes:t.objectTypes??[],flags:t.flags?.metadata??{}},i={invocationId:nanoid$1(10),status:InvokeStatus.Error,message:e};return this.getInvocationResultObj([i],n,r)}getInvocationResultObj(e,t,r){distExports.Traces.removePropagationInfo(r);const n=e.filter(e=>e.status===InvokeStatus.Success).reduce((e,n)=>e=[...e,{executed_by:n.instance,returned:n.result,called_with:r,method:t,message:n.message,status:n.status}],[]),i=e.filter(e=>e.status===InvokeStatus.Error).reduce((e,n)=>e=[...e,{executed_by:n.instance,called_with:r,name:t.name,message:n.message}],[]),o=e[0];return{method:t,called_with:r,returned:o.result,executed_by:o.instance,all_return_values:n,all_errors:i,message:o.message,status:o.status}}tryToAwaitForMethods(e,t,r){return new Promise((n,i)=>{if(0===r.waitTimeoutMs)return void i();let o=0;const s=setInterval(()=>{o+=500;const a=this.getServerMethodsByFilterAndTarget(e,t);if(a.length>0)clearInterval(s),n(a);else if(o>=(r.waitTimeoutMs||1e4))return clearInterval(s),void i()},500)})}filterByTarget(e,t){if("string"!=typeof e){let r;r=Array.isArray(e)?e:[e];return r.reduce((e,r)=>{const n=t.filter(e=>this.instanceMatch(r,e.server.instance));return e.concat(n)},[])}if("all"===e)return[...t];if("best"===e){const e=t.find(e=>e.server.instance.isLocal);if(e)return[e];if(void 0!==t[0])return[t[0]]}else if("skipMine"===e)return t.filter(({server:e})=>e.instance.peerId!==this.instance.peerId);return[]}instanceMatch(e,t){return e?.peerId&&e?.instance&&delete(e={...e}).peerId,this.containsProps(e,t)}methodMatch(e,t){return this.containsProps(e,t)}containsProps(e,t){return Object.keys(e).filter(t=>void 0!==e[t]&&null!==e[t]&&"function"!=typeof e[t]&&"object_types"!==t&&"display_name"!==t&&"id"!==t&&"gatewayId"!==t&&"identifier"!==t&&"_"!==t[0]).every(r=>{let n;const i=e[r],o=t[r];switch(r){case"objectTypes":n=(i||[]).every(e=>(o||[]).includes(e));break;case"flags":n=isSubset(o||{},i||{});break;default:n=String(i).toLowerCase()===String(o).toLowerCase()}return n})}getMethods(e){if(void 0===e)return this.repo.getMethods();return this.repo.getMethods().filter(t=>this.methodMatch(e,t))}getMethodsForInstance(e){const t=this.repo.getServers().filter(t=>this.instanceMatch(e,t.instance));if(0===t.length)return[];let r={};return 1===t.length?r=t[0].methods:t.forEach(e=>{Object.keys(e.methods).forEach(t=>{const n=e.methods[t];r[n.identifier]=n})}),Object.keys(r).map(e=>r[e])}getServers(e){const t=this.repo.getServers();return void 0===e?t.map(e=>({server:e,methods:[]})):t.reduce((t,r)=>{const n=Object.values(r.methods).filter(t=>this.methodMatch(e,t));return n.length>0&&t.push({server:r,methods:n}),t},[])}getServerMethodsByFilterAndTarget(e,t){const r=this.getServers(e);return this.filterByTarget(t,r)}}__decorate([distExports.withSpan("interopio.api.interop.stream.subscribe",{argMapping:e=>({stream:Utils.getMethodName(e)})})],Client.prototype,"subscribe",null),__decorate([distExports.withSpan("interopio.api.interop.invoke",{argMapping:e=>({method:Utils.getMethodName(e)})})],Client.prototype,"invoke",null),__decorate([distExports.withSpan("interopio.api.interop.invoke.server",{argMapping:{"0.name":"method"}})],Client.prototype,"getServerInvokePromise",null);class ServerSubscription{protocol;repoMethod;subscription;constructor(e,t,r){this.protocol=e,this.repoMethod=t,this.subscription=r}get stream(){if(!this.repoMethod.stream)throw new Error("no stream");return this.repoMethod.stream}get arguments(){return this.subscription.arguments||{}}get branchKey(){return this.subscription.branchKey}get instance(){if(!this.subscription.instance)throw new Error("no instance");return this.subscription.instance}close(){this.protocol.server.closeSingleSubscription(this.repoMethod,this.subscription)}push(e){this.protocol.server.pushDataToSingle(this.repoMethod,this.subscription,e)}}let Request$1=class{protocol;repoMethod;requestContext;arguments;instance;constructor(e,t,r){this.protocol=e,this.repoMethod=t,this.requestContext=r,this.arguments=r.arguments,this.instance=r.instance}accept(){this.protocol.server.acceptRequestOnBranch(this.requestContext,this.repoMethod,"")}acceptOnBranch(e){this.protocol.server.acceptRequestOnBranch(this.requestContext,this.repoMethod,e)}reject(e){this.protocol.server.rejectRequest(this.requestContext,this.repoMethod,e)}},ServerStreaming$1=class{protocol;server;constructor(e,t){this.protocol=e,this.server=t,e.server.onSubRequest((e,t)=>this.handleSubRequest(e,t)),e.server.onSubAdded((e,t)=>this.handleSubAdded(e,t)),e.server.onSubRemoved((e,t)=>this.handleSubRemoved(e,t))}handleSubRequest(e,t){if(!t||!t.streamCallbacks||"function"!=typeof t.streamCallbacks.subscriptionRequestHandler)return;const r=new Request$1(this.protocol,t,e);t.streamCallbacks.subscriptionRequestHandler(r)}handleSubAdded(e,t){if(!t||!t.streamCallbacks||"function"!=typeof t.streamCallbacks.subscriptionAddedHandler)return;const r=new ServerSubscription(this.protocol,t,e);t.streamCallbacks.subscriptionAddedHandler(r)}handleSubRemoved(e,t){if(!t||!t.streamCallbacks||"function"!=typeof t.streamCallbacks.subscriptionRemovedHandler)return;const r=new ServerSubscription(this.protocol,t,e);t.streamCallbacks.subscriptionRemovedHandler(r)}};class ServerBranch{key;protocol;repoMethod;constructor(e,t,r){this.key=e,this.protocol=t,this.repoMethod=r}subscriptions(){return this.protocol.server.getSubscriptionList(this.repoMethod,this.key).map(e=>new ServerSubscription(this.protocol,this.repoMethod,e))}close(){this.protocol.server.closeAllSubscriptions(this.repoMethod,this.key)}push(e){this.protocol.server.pushData(this.repoMethod,e,[this.key])}}class ServerStream{_protocol;_repoMethod;_server;name;constructor(e,t,r){this._protocol=e,this._repoMethod=t,this._server=r,this.name=this._repoMethod.definition.name}branches(e){const t=this._protocol.server.getBranchList(this._repoMethod);return e?t.indexOf(e)>-1?new ServerBranch(e,this._protocol,this._repoMethod):void 0:t.map(e=>new ServerBranch(e,this._protocol,this._repoMethod))}branch(e){return this.branches(e)}subscriptions(){return this._protocol.server.getSubscriptionList(this._repoMethod).map(e=>new ServerSubscription(this._protocol,this._repoMethod,e))}get definition(){const e=this._repoMethod.definition;return{accepts:e.accepts,description:e.description,displayName:e.displayName,name:e.name,objectTypes:e.objectTypes,returns:e.returns,supportsStreaming:e.supportsStreaming,flags:e.flags?.metadata}}async close(){return this._protocol.server.closeAllSubscriptions(this._repoMethod),this._server.unregister(this._repoMethod.definition,!0)}push(e,t){if("string"!=typeof t&&!Array.isArray(t)&&void 0!==t)throw new Error("invalid branches should be string or string array");if("object"!=typeof e)throw new Error("Invalid arguments. Data must be an object.");const r=distExports.Traces.currentTracingState;r.addData("INFO",{stream:this?.name,branches:t}),r.addData("DIAGNOSTIC",{data:e}),e=deepClone(e),r.injectPropagationInfo(e),this._protocol.server.pushData(this._repoMethod,e,t)}updateRepoMethod(e){this._repoMethod=e}}__decorate([distExports.withSpan("interopio.api.interop.stream.close",{thisMapping:{name:"stream"}})],ServerStream.prototype,"close",null),__decorate([distExports.withSpan("interopio.api.interop.stream.push",{thisMapping:{name:"stream"}})],ServerStream.prototype,"push",null);class Server{protocol;serverRepository;streaming;invocations=0;currentlyUnregistering={};constructor(e,t){this.protocol=e,this.serverRepository=t,this.streaming=new ServerStreaming$1(e,this),this.protocol.server.onInvoked(this.onMethodInvoked.bind(this))}createStream(e,t,r,n,i){const o=new Promise((r,n)=>{if(!e)return void n("The stream name must be unique! Please, provide either a unique string for a stream name to “glue.interop.createStream()” or a “methodDefinition” object with a unique “name” property for the stream.");let o;if(o="string"==typeof e?{name:""+e}:{...e},!o.name)return n(`The “name” property is required for the “streamDefinition” object and must be unique. Stream definition: ${JSON.stringify(o)}`);if(this.serverRepository.getList().some(e=>e.definition.name===o.name))return n(`A stream with the name "${o.name}" already exists! Please, provide a unique name for the stream.`);o.supportsStreaming=!0,t||(t={}),"function"!=typeof t.subscriptionRequestHandler&&(t.subscriptionRequestHandler=e=>{e.accept()});const s=this.serverRepository.add({definition:o,streamCallbacks:t,protocolState:{}});this.protocol.server.createStream(s).then(()=>{let e;i?(e=i,i.updateRepoMethod(s)):e=new ServerStream(this.protocol,s,this),s.stream=e,r(e)}).catch(e=>{s.repoId&&this.serverRepository.remove(s.repoId),n(e)})});return promisify(o,r,n)}register(e,t){if(!e)return Promise.reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");if(distExports.Traces.currentTracingState.addData("INFO",{method:Utils.getMethodName(e)}),"function"!=typeof t)return Promise.reject(`The second parameter must be a callback function. Method: ${Utils.getMethodName(e)}`);const r=async(e,r)=>{try{const n=t(e.args,e.instance);if(n&&"function"==typeof n.then){const e=distExports.Traces.currentTracingState,t=await n;distExports.Traces.currentTracingState=e,r(void 0,t)}else r(void 0,n)}catch(e){r(e??"",e??"")}};return r.userCallback=t,this.registerCore(e,r)}registerAsync(e,t){if(!e)return Promise.reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");if(distExports.Traces.currentTracingState.addData("INFO",{method:Utils.getMethodName(e)}),"function"!=typeof t)return Promise.reject(`The second parameter must be a callback function. Method: ${Utils.getMethodName(e)}`);const r=async(e,r)=>{try{let n=!1;const i=e=>{n||r(void 0,e),n=!0},o=e=>{n||(e||(e=""),r(e,e)),n=!0},s=t(e.args,e.instance,i,o);s&&"function"==typeof s.then&&s.then(i).catch(o)}catch(e){r(e,void 0)}};return r.userCallbackAsync=t,this.registerCore(e,r)}async unregister(e,t=!1){if(void 0===e)return Promise.reject("Please, provide either a unique string for a name or an object containing a “name” property.");if(distExports.Traces.currentTracingState.addData("INFO",{method:Utils.getMethodName(e)}),"function"==typeof e)return void await this.unregisterWithPredicate(e,t);let r;if(r="string"==typeof e?{name:e}:e,void 0===r.name)return Promise.reject("Method name is required. Cannot find a method if the method name is undefined!");const n=this.serverRepository.getList().find(e=>e.definition.name===r.name&&(e.definition.supportsStreaming||!1)===t);if(!n)return Promise.reject(`Method with a name "${r.name}" does not exist or is not registered by your application!`);await this.removeMethodsOrStreams([n])}async unregisterWithPredicate(e,t){const r=this.serverRepository.getList().filter(t=>e(t.definition)).filter(e=>(e.definition.supportsStreaming||!1)===t);if(!r||0===r.length)return Promise.reject(`Could not find a ${t?"stream":"method"} matching the specified condition!`);await this.removeMethodsOrStreams(r)}removeMethodsOrStreams(e){const t=[];return e.forEach(e=>{const r=this.protocol.server.unregister(e).then(()=>{e.repoId&&this.serverRepository.remove(e.repoId)});t.push(r),this.addAsCurrentlyUnregistering(e.definition.name,r)}),Promise.all(t)}async addAsCurrentlyUnregistering(e,t){const r=new Promise(e=>setTimeout(e,5e3));this.currentlyUnregistering[e]=Promise.race([t,r]).then(()=>{delete this.currentlyUnregistering[e]})}async registerCore(e,t){let r;if(r="string"==typeof e?{name:""+e}:{...e},!r.name)return Promise.reject(`Please, provide a (unique) string value for the “name” property in the “methodDefinition” object: ${JSON.stringify(e)}`);await this.currentlyUnregistering[r.name];if(this.serverRepository.getList().some(e=>e.definition.name===r.name))return Promise.reject(`A method with the name "${r.name}" already exists! Please, provide a unique name for the method.`);if(r.supportsStreaming)return Promise.reject(`When you create methods with “glue.interop.register()” or “glue.interop.registerAsync()” the property “supportsStreaming” cannot be “true”. If you want “${r.name}” to be a stream, please use the “glue.interop.createStream()” method.`);const n=this.serverRepository.add({definition:r,theFunction:t,protocolState:{}});return this.protocol.server.register(n).catch(e=>{throw n?.repoId&&this.serverRepository.remove(n.repoId),e})}onMethodInvoked(e,t,r){const n=distExports.Traces.extractPropagationInfo(r.args,!0);distExports.withSpan("interopio.api.interop.register.callback",{method:e?.definition?.name},n,n=>{if(n.addData("INFO",{method:e?.definition?.name}),n.addData("INFO",{invocationId:t}),n.addData("INFO",{invoker:r?.instance}),n.addData("DIAGNOSTIC",{arguments:r?.args}),!e||!e.theFunction)return void(n.status={code:distExports.SpanStatusCode.ERROR,message:"Required argument 'methodToExecute' is missing."});let i;const o=new Promise(e=>{i=e});return e.theFunction(r,(r,o)=>{if(null!=r){if(r.message&&"string"==typeof r.message)r=r.message;else if("string"!=typeof r)try{r=JSON.stringify(r)}catch(e){r=`un-stringifyable error in onMethodInvoked! Top level prop names: ${Object.keys(r)}`}n.status={code:distExports.SpanStatusCode.ERROR,message:r},n.recordException(r)}o?("object"!=typeof o||Array.isArray(o))&&(o={_value:o}):o={},n.addData("DIAGNOSTIC",{returnValue:o}),this.protocol.server.methodInvocationResult(e,t,r,o),i()}),o})}}__decorate([distExports.withSpan("interopio.api.interop.stream.create",{argMapping:e=>({stream:Utils.getMethodName(e)})})],Server.prototype,"createStream",null),__decorate([distExports.withSpan("interopio.api.interop.register",{argMapping:e=>({method:Utils.getMethodName(e)})})],Server.prototype,"register",null),__decorate([distExports.withSpan("interopio.api.interop.register.async",{argMapping:e=>({method:Utils.getMethodName(e)})})],Server.prototype,"registerAsync",null),__decorate([distExports.withSpan("interopio.api.interop.unregister",{argMapping:e=>({method:Utils.getMethodName(e)})})],Server.prototype,"unregister",null);class InstanceWrapper{wrapped={};constructor(e,t,r){this.wrapped.getMethods=function(){return e.methodsForInstance(this)},this.wrapped.getStreams=function(){return e.methodsForInstance(this).filter(e=>e.supportsStreaming)},t&&this.refreshWrappedObject(t),r&&(r.loggedIn(()=>{this.refresh(r)}),this.refresh(r))}unwrap(){return this.wrapped}refresh(e){if(!e)return;const t=e?.resolvedIdentity,r=Object.assign({},t??{},{peerId:e?.peerId});this.refreshWrappedObject(r)}refreshWrappedObject(e){Object.keys(e).forEach(t=>{this.wrapped[t]=e[t]}),this.wrapped.user=e.user,this.wrapped.instance=e.instance,this.wrapped.application=e.application??nanoid$1(10),this.wrapped.applicationName=e.applicationName,this.wrapped.pid=e.pid??e.process??Math.floor(1e10*Math.random()),this.wrapped.machine=e.machine,this.wrapped.environment=e.environment,this.wrapped.region=e.region,this.wrapped.windowId=e.windowId,this.wrapped.isLocal=e.isLocal??!0,this.wrapped.api=e.api,this.wrapped.service=e.service,this.wrapped.peerId=e.peerId}}const hideMethodSystemFlags=e=>({...e,flags:e.flags.metadata||{}});class ClientRepository{logger;API;servers={};myServer;methodsCount={};callbacks=CallbackRegistryFactory();constructor(e,t){this.logger=e,this.API=t;const r=this.API.instance.peerId;this.myServer={id:r,methods:{},instance:this.API.instance,wrapper:this.API.unwrappedInstance},this.servers[r]=this.myServer}addServer(e,t){this.logger.debug(`adding server ${t}`);const r=this.servers[t];if(r)return r.id;const n=new InstanceWrapper(this.API,e),i={id:t,methods:{},instance:n.unwrap(),wrapper:n};return this.servers[t]=i,this.callbacks.execute("onServerAdded",i.instance),t}removeServerById(e,t){const r=this.servers[e];r?(this.logger.debug(`removing server ${e}`),Object.keys(r.methods).forEach(t=>{this.removeServerMethod(e,t)}),delete this.servers[e],this.callbacks.execute("onServerRemoved",r.instance,t)):this.logger.warn(`not aware of server ${e}, my state ${JSON.stringify(Object.keys(this.servers))}`)}addServerMethod(e,t){const r=this.servers[e];if(!r)throw new Error("server does not exists");if(r.methods[t.id])return;const n=this.createMethodIdentifier(t),i={identifier:n,gatewayId:t.id,name:t.name,displayName:t.display_name,description:t.description,version:t.version,objectTypes:t.object_types||[],accepts:t.input_signature,returns:t.result_signature,supportsStreaming:void 0!==t.flags&&t.flags.streaming,flags:t.flags??{},getServers:()=>this.getServersByMethod(n)};i.object_types=i.objectTypes,i.display_name=i.displayName,r.methods[t.id]=i;const o=hideMethodSystemFlags(i);return this.methodsCount[n]||(this.methodsCount[n]=0,this.callbacks.execute("onMethodAdded",o)),this.methodsCount[n]=this.methodsCount[n]+1,this.callbacks.execute("onServerMethodAdded",r.instance,o),i}removeServerMethod(e,t){const r=this.servers[e];if(!r)throw new Error("server does not exists");const n=r.methods[t];delete r.methods[t];const i=hideMethodSystemFlags(n);this.methodsCount[n.identifier]=this.methodsCount[n.identifier]-1,0===this.methodsCount[n.identifier]&&this.callbacks.execute("onMethodRemoved",i),this.callbacks.execute("onServerMethodRemoved",r.instance,i)}getMethods(){return this.extractMethodsFromServers(Object.values(this.servers)).map(hideMethodSystemFlags)}getServers(){return Object.values(this.servers).map(this.hideServerMethodSystemFlags)}onServerAdded(e){const t=this.callbacks.add("onServerAdded",e),r=this.getServers().map(e=>e.instance);return this.returnUnsubWithDelayedReplay(t,r,e)}onMethodAdded(e){const t=this.callbacks.add("onMethodAdded",e),r=this.getMethods();return this.returnUnsubWithDelayedReplay(t,r,e)}onServerMethodAdded(e){const t=this.callbacks.add("onServerMethodAdded",e);let r=!1;const n=this.getServers();return setTimeout(()=>{n.forEach(t=>{const n=t.methods;Object.keys(n).forEach(i=>{r||e(t.instance,n[i])})})},0),()=>{r=!0,t()}}onMethodRemoved(e){return this.callbacks.add("onMethodRemoved",e)}onServerRemoved(e){return this.callbacks.add("onServerRemoved",e)}onServerMethodRemoved(e){return this.callbacks.add("onServerMethodRemoved",e)}getServerById(e){if(this.servers[e])return this.hideServerMethodSystemFlags(this.servers[e])}reset(){Object.keys(this.servers).forEach(e=>{this.removeServerById(e,"reset")}),this.servers={[this.myServer.id]:this.myServer},this.methodsCount={}}createMethodIdentifier(e){const t=e.input_signature??"",r=e.result_signature??"";return(e.name+t+r).toLowerCase()}getServersByMethod(e){const t=[];return Object.values(this.servers).forEach(r=>{Object.values(r.methods).forEach(n=>{n.identifier===e&&t.push(r.instance)})}),t}returnUnsubWithDelayedReplay(e,t,r){let n=!1;return setTimeout(()=>{t.forEach(e=>{n||r(e)})},0),()=>{n=!0,e()}}hideServerMethodSystemFlags(e){const t={};return Object.entries(e.methods).forEach(([e,r])=>{t[e]=hideMethodSystemFlags(r)}),{...e,methods:t}}extractMethodsFromServers(e){return Object.values(e).reduce((e,t)=>[...e,...Object.values(t.methods)],[])}}class ServerRepository{nextId=0;methods=[];add(e){return e.repoId=String(this.nextId),this.nextId+=1,this.methods.push(e),e}remove(e){if("string"!=typeof e)return new TypeError("Expecting a string");this.methods=this.methods.filter(t=>t.repoId!==e)}getById(e){if("string"==typeof e)return this.methods.find(t=>t.repoId===e)}getList(){return this.methods.map(e=>e)}length(){return this.methods.length}reset(){this.methods=[]}}const SUBSCRIPTION_REQUEST="onSubscriptionRequest",SUBSCRIPTION_ADDED="onSubscriptionAdded",SUBSCRIPTION_REMOVED="onSubscriptionRemoved";class ServerStreaming{session;repository;serverRepository;logger;ERR_URI_SUBSCRIPTION_FAILED="com.tick42.agm.errors.subscription.failure";callbacks=CallbackRegistryFactory();nextStreamId=0;constructor(e,t,r,n){this.session=e,this.repository=t,this.serverRepository=r,this.logger=n,e.on("add-interest",e=>{this.handleAddInterest(e)}),e.on("remove-interest",e=>{this.handleRemoveInterest(e)})}acceptRequestOnBranch(e,t,r){if("string"!=typeof r&&(r=""),"object"!=typeof t.protocolState.subscriptionsMap)throw new TypeError("The streaming method is missing its subscriptions.");if(!Array.isArray(t.protocolState.branchKeyToStreamIdMap))throw new TypeError("The streaming method is missing its branches.");const n=this.getStreamId(t,r),i=e.msg.subscription_id,o={id:i,arguments:e.arguments,instance:e.instance,branchKey:r,streamId:n,subscribeMsg:e.msg};t.protocolState.subscriptionsMap[i]=o,this.session.sendFireAndForget({type:"accepted",subscription_id:i,stream_id:n}).catch(e=>{this.logger.warn(`Failed to send accepted message for subscription ${i}: ${JSON.stringify(e)}`)}),this.callbacks.execute(SUBSCRIPTION_ADDED,o,t)}rejectRequest(e,t,r){"string"!=typeof r&&(r=""),this.sendSubscriptionFailed("Subscription rejected by user. "+r,e.msg.subscription_id)}pushData(e,t,r){if("object"!=typeof e||!Array.isArray(e.protocolState.branchKeyToStreamIdMap))return;if("object"!=typeof t)throw new Error("Invalid arguments. Data must be an object.");"string"==typeof r?r=[r]:(!Array.isArray(r)||r.length<=0)&&(r=[]);const n=e.protocolState.branchKeyToStreamIdMap.filter(e=>!r||0===r.length||r.indexOf(e.key)>=0).map(e=>e.streamId);n.forEach(e=>{const r={type:"publish",stream_id:e,data:t};this.session.sendFireAndForget(r).catch(t=>{this.logger.warn(`Failed to send publish message for stream ${e}: ${JSON.stringify(t)}`)})})}pushDataToSingle(e,t,r){if("object"!=typeof r)throw new Error("Invalid arguments. Data must be an object.");const n={type:"post",subscription_id:t.id,data:r};this.session.sendFireAndForget(n).catch(e=>{this.logger.warn(`Failed to send post message for subscription ${t.id}: ${JSON.stringify(e)}`)})}closeSingleSubscription(e,t){e.protocolState.subscriptionsMap&&delete e.protocolState.subscriptionsMap[t.id];const r={type:"drop-subscription",subscription_id:t.id,reason:"Server dropping a single subscription"};this.session.sendFireAndForget(r).catch(e=>{this.logger.warn(`Failed to send drop-subscription message for subscription ${t.id}: ${JSON.stringify(e)}`)}),this.callbacks.execute(SUBSCRIPTION_REMOVED,t,e)}closeMultipleSubscriptions(e,t){if("object"!=typeof e||"object"!=typeof e.protocolState.subscriptionsMap)return;if(!e.protocolState.subscriptionsMap)return;const r=e.protocolState.subscriptionsMap;let n=Object.keys(r).map(e=>r[e]);"string"==typeof t&&(n=n.filter(e=>e.branchKey===t)),n.forEach(e=>{delete r[e.id];const t={type:"drop-subscription",subscription_id:e.id,reason:"Server dropping all subscriptions on stream_id: "+e.streamId};this.session.sendFireAndForget(t).catch(t=>{this.logger.warn(`Failed to send drop-subscription message for subscription ${e.id}: ${JSON.stringify(t)}`)})})}getSubscriptionList(e,t){if("object"!=typeof e)return[];let r=[];if(!e.protocolState.subscriptionsMap)return[];const n=e.protocolState.subscriptionsMap,i=Object.keys(n).map(e=>n[e]);return r="string"!=typeof t?i:i.filter(e=>e.branchKey===t),r}getBranchList(e){if("object"!=typeof e)return[];if(!e.protocolState.subscriptionsMap)return[];const t=e.protocolState.subscriptionsMap,r=Object.keys(t).map(e=>t[e]),n=[];return r.forEach(e=>{let t="";"object"==typeof e&&"string"==typeof e.branchKey&&(t=e.branchKey),-1===n.indexOf(t)&&n.push(t)}),n}onSubAdded(e){this.onSubscriptionLifetimeEvent(SUBSCRIPTION_ADDED,e)}onSubRequest(e){this.onSubscriptionLifetimeEvent(SUBSCRIPTION_REQUEST,e)}onSubRemoved(e){this.onSubscriptionLifetimeEvent(SUBSCRIPTION_REMOVED,e)}handleRemoveInterest(e){const t=this.serverRepository.getById(e.method_id);if("string"!=typeof e.subscription_id||"object"!=typeof t)return;if(!t.protocolState.subscriptionsMap)return;if("object"!=typeof t.protocolState.subscriptionsMap[e.subscription_id])return;const r=t.protocolState.subscriptionsMap[e.subscription_id];delete t.protocolState.subscriptionsMap[e.subscription_id],this.callbacks.execute(SUBSCRIPTION_REMOVED,r,t)}onSubscriptionLifetimeEvent(e,t){this.callbacks.add(e,t)}getNextStreamId(){return this.nextStreamId+++""}handleAddInterest(e){const t=this.repository.getServerById(e.caller_id),r=t?.instance??{},n={msg:e,arguments:e.arguments_kv||{},instance:r},i=this.serverRepository.getById(e.method_id);if(void 0===i){const t="No method with id "+e.method_id+" on this server.";return void this.sendSubscriptionFailed(t,e.subscription_id)}i.protocolState.subscriptionsMap&&i.protocolState.subscriptionsMap[e.subscription_id]?this.sendSubscriptionFailed("A subscription with id "+e.subscription_id+" already exists.",e.subscription_id):this.callbacks.execute(SUBSCRIPTION_REQUEST,n,i)}sendSubscriptionFailed(e,t){const r={type:"error",reason_uri:this.ERR_URI_SUBSCRIPTION_FAILED,reason:e,request_id:t};this.session.sendFireAndForget(r).catch(e=>{this.logger.warn(`Failed to send subscription failed message for subscription ${t}: ${JSON.stringify(e)}`)})}getStreamId(e,t){if("string"!=typeof t&&(t=""),!e.protocolState.branchKeyToStreamIdMap)throw new Error(`streaming ${e.definition.name} method without protocol state`);const r=e.protocolState.branchKeyToStreamIdMap.filter(e=>e.key===t)[0];let n=r?r.streamId:void 0;return"string"==typeof n&&""!==n||(n=this.getNextStreamId(),e.protocolState.branchKeyToStreamIdMap.push({key:t,streamId:n})),n}}class ServerProtocol{session;clientRepository;serverRepository;logger;callbacks=CallbackRegistryFactory();streaming;constructor(e,t,r,n){this.session=e,this.clientRepository=t,this.serverRepository=r,this.logger=n,this.streaming=new ServerStreaming(e,t,r,n.subLogger("streaming")),this.session.on("invoke",e=>this.handleInvokeMessage(e))}createStream(e){return e.protocolState.subscriptionsMap={},e.protocolState.branchKeyToStreamIdMap=[],this.register(e,!0)}register(e,t){const r=e.definition,n=Object.assign({},{metadata:r.flags??{}},{streaming:t||!1}),i={type:"register",methods:[{id:e.repoId,name:r.name,display_name:r.displayName,description:r.description,version:r.version,flags:n,object_types:r.objectTypes||r.object_types,input_signature:r.accepts,result_signature:r.returns,restrictions:void 0}]};return this.session.send(i,{methodId:e.repoId}).then(()=>{this.logger.debug("registered method "+e.definition.name+" with id "+e.repoId)}).catch(t=>{throw this.logger.warn(`failed to register method ${e.definition.name} with id ${e.repoId} - ${JSON.stringify(t)}`),t})}onInvoked(e){this.callbacks.add("onInvoked",e)}methodInvocationResult(e,t,r,n){let i;i=r||""===r?{type:"error",request_id:t,reason_uri:"agm.errors.client_error",reason:r,context:n,peer_id:void 0}:{type:"yield",invocation_id:t,peer_id:this.session.peerId,result:n,request_id:void 0},this.session.sendFireAndForget(i).catch(r=>{this.logger.warn(`Failed to send method invocation result for method ${e.definition.name} invocation ${t} - ${JSON.stringify(r)}`)})}async unregister(e){const t={type:"unregister",methods:[e.repoId]};await this.session.send(t)}getBranchList(e){return this.streaming.getBranchList(e)}getSubscriptionList(e,t){return this.streaming.getSubscriptionList(e,t)}closeAllSubscriptions(e,t){this.streaming.closeMultipleSubscriptions(e,t)}pushData(e,t,r){this.streaming.pushData(e,t,r)}pushDataToSingle(e,t,r){this.streaming.pushDataToSingle(e,t,r)}closeSingleSubscription(e,t){this.streaming.closeSingleSubscription(e,t)}acceptRequestOnBranch(e,t,r){this.streaming.acceptRequestOnBranch(e,t,r)}rejectRequest(e,t,r){this.streaming.rejectRequest(e,t,r)}onSubRequest(e){this.streaming.onSubRequest(e)}onSubAdded(e){this.streaming.onSubAdded(e)}onSubRemoved(e){this.streaming.onSubRemoved(e)}handleInvokeMessage(e){const t=e.invocation_id,r=e.caller_id,n=e.method_id,i=e.arguments_kv,o=this.serverRepository.getList().filter(e=>e.repoId===n)[0];if(void 0===o)return;const s=this.clientRepository.getServerById(r)?.instance,a={args:i,instance:s};this.callbacks.execute("onInvoked",o,t,a)}}class UserSubscription{repository;subscriptionData;get requestArguments(){return this.subscriptionData.params.arguments||{}}get servers(){return this.subscriptionData.trackedServers.reduce((e,t)=>{if(t.subscriptionId){const r=this.repository.getServerById(t.serverId)?.instance;r&&e.push(r)}return e},[])}get serverInstance(){return this.servers[0]}get stream(){return this.subscriptionData.method}constructor(e,t){this.repository=e,this.subscriptionData=t}onData(e){if("function"!=typeof e)throw new TypeError("The data callback must be a function.");this.subscriptionData.handlers.onData.push(e),1===this.subscriptionData.handlers.onData.length&&this.subscriptionData.queued.data.length>0&&this.subscriptionData.queued.data.forEach(t=>{e(t)})}onClosed(e){if("function"!=typeof e)throw new TypeError("The callback must be a function.");this.subscriptionData.handlers.onClosed.push(e)}onFailed(e){}onConnected(e){if("function"!=typeof e)throw new TypeError("The callback must be a function.");this.subscriptionData.handlers.onConnected.push(e)}close(){this.subscriptionData.close()}setNewSubscription(e){this.subscriptionData=e}}class TimedCache{config;cache=[];timeoutIds=[];constructor(e){this.config=e}add(e){const t=nanoid$1(10);this.cache.push({id:t,element:e});const r=setTimeout(()=>{const e=this.cache.findIndex(e=>e.id===t);e<0||this.cache.splice(e,1)},this.config.ELEMENT_TTL_MS);this.timeoutIds.push(r)}flush(){const e=this.cache.map(e=>e.element);return this.timeoutIds.forEach(e=>clearInterval(e)),this.cache=[],this.timeoutIds=[],e}}const STATUS_AWAITING_ACCEPT="awaitingAccept",STATUS_SUBSCRIBED="subscribed",ERR_MSG_SUB_FAILED="Subscription failed.",ERR_MSG_SUB_REJECTED="Subscription rejected.",ON_CLOSE_MSG_SERVER_INIT="ServerInitiated",ON_CLOSE_MSG_CLIENT_INIT="ClientInitiated";class ClientStreaming{session;repository;logger;subscriptionsList={};timedCache=new TimedCache({ELEMENT_TTL_MS:1e4});subscriptionIdToLocalKeyMap={};nextSubLocalKey=0;constructor(e,t,r){this.session=e,this.repository=t,this.logger=r,e.on("subscribed",this.handleSubscribed),e.on("event",this.handleEventData),e.on("subscription-cancelled",this.handleSubscriptionCancelled)}subscribe(e,t,r,n,i,o){if(distExports.Traces.removePropagationInfo(t.arguments),0===r.length)return void i({method:e,called_with:t.arguments,message:ERR_MSG_SUB_FAILED+" No available servers matched the target params."});const s=this.getNextSubscriptionLocalKey(),a=this.registerSubscription(s,e,t,n,i,t.methodResponseTimeout||1e4,o);"object"==typeof a?r.forEach(r=>{const n=r.server.id,i=r.methods.find(t=>t.name===e.name);if(!i)return void this.logger.error(`can not find method ${e.name} for target ${r.server.id}`);a.trackedServers.push({serverId:n,subscriptionId:void 0});const o={type:"subscribe",server_id:n,method_id:i.gatewayId,arguments_kv:t.arguments};this.session.send(o,{serverId:n,subLocalKey:s}).then(e=>this.handleSubscribed(e)).catch(e=>this.handleErrorSubscribing(e))}):i({method:e,called_with:t.arguments,message:ERR_MSG_SUB_FAILED+" Unable to register the user callbacks."})}drainSubscriptions(){const e=Object.values(this.subscriptionsList);return this.subscriptionsList={},this.subscriptionIdToLocalKeyMap={},e}drainSubscriptionsCache(){return this.timedCache.flush()}getNextSubscriptionLocalKey(){const e=this.nextSubLocalKey;return this.nextSubLocalKey+=1,e}registerSubscription(e,t,r,n,i,o,s){const a={localKey:e,status:STATUS_AWAITING_ACCEPT,method:t,params:r,success:n,error:i,trackedServers:[],handlers:{onData:s?.handlers.onData||[],onClosed:s?.handlers.onClosed||[],onConnected:s?.handlers.onConnected||[]},queued:{data:[],closers:[]},timeoutId:void 0,close:()=>this.closeSubscription(e),subscription:s?.subscription};return s||(r.onData&&a.handlers.onData.push(r.onData),r.onClosed&&a.handlers.onClosed.push(r.onClosed),r.onConnected&&a.handlers.onConnected.push(r.onConnected)),this.subscriptionsList[e]=a,a.timeoutId=setTimeout(()=>{if(void 0===this.subscriptionsList[e])return;const n=this.subscriptionsList[e];n.status===STATUS_AWAITING_ACCEPT?(i({method:t,called_with:r.arguments,message:ERR_MSG_SUB_FAILED+" Subscription attempt timed out after "+o+" ms."}),delete this.subscriptionsList[e]):n.status===STATUS_SUBSCRIBED&&n.trackedServers.length>0&&(n.trackedServers=n.trackedServers.filter(e=>void 0!==e.subscriptionId),delete n.timeoutId,n.trackedServers.length<=0&&(this.callOnClosedHandlers(n),delete this.subscriptionsList[e]))},o),a}handleErrorSubscribing=e=>{const t=e._tag,r=t.subLocalKey,n=this.subscriptionsList[r];if("object"==typeof n&&(n.trackedServers=n.trackedServers.filter(e=>e.serverId!==t.serverId),n.trackedServers.length<=0)){if(clearTimeout(n.timeoutId),n.status===STATUS_AWAITING_ACCEPT){const t="string"==typeof e.reason&&""!==e.reason?' Publisher said "'+e.reason+'".':" No reason given.",r="object"==typeof n.params.arguments?JSON.stringify(n.params.arguments):"{}";n.error({message:ERR_MSG_SUB_REJECTED+t+" Called with:"+r,called_with:distExports.Traces.removePropagationInfo(n.params.arguments),method:n.method})}else n.status===STATUS_SUBSCRIBED&&this.callOnClosedHandlers(n);delete this.subscriptionsList[r]}};handleSubscribed=e=>{const t=e._tag.subLocalKey,r=this.subscriptionsList[t];if("object"!=typeof r)return;const n=e._tag.serverId,i=r.trackedServers.filter(e=>e.serverId===n)[0];if("object"!=typeof i)return;i.subscriptionId=e.subscription_id,this.subscriptionIdToLocalKeyMap[e.subscription_id]=t;const o=r.status===STATUS_AWAITING_ACCEPT;if(r.status=STATUS_SUBSCRIBED,o){let e=!1,t=r.subscription;t?(t.setNewSubscription(r),r.success(t),e=!0):(t=new UserSubscription(this.repository,r),r.subscription=t,r.success(t));for(const n of r.handlers.onConnected)try{n(t.serverInstance,e)}catch(e){}}};handleEventData=e=>{const t=this.subscriptionIdToLocalKeyMap[e.subscription_id];if(void 0===t)return;const r=this.subscriptionsList[t];if("object"!=typeof r)return;const n=r.trackedServers.filter(t=>t.subscriptionId===e.subscription_id);if(1!==n.length)return;const i=e.oob,o=n[0].serverId,s=this.repository.getServerById(o),a=r.handlers.onData,c=r.queued.data,l={data:e.data,server:s?.instance??{},requestArguments:r.params.arguments,message:void 0,private:i},u=distExports.Traces.extractPropagationInfo(l.data,!0),d=r?.method?.name;distExports.withSpan("interopio.api.interop.stream.onData",{method:d,stream:d},u,()=>{const e=distExports.Traces.currentTracingState;e.addData("INFO",{method:d}),e.addData("INFO",{stream:d}),e.addData("INFO",{handlerCount:a?.length}),e.addData("DIAGNOSTIC",{data:l}),a.length>0?a.forEach(e=>{"function"==typeof e&&e(deepClone(l))}):c.push(deepClone(l))})};handleSubscriptionCancelled=e=>{const t=this.subscriptionIdToLocalKeyMap[e.subscription_id];if(void 0===t)return;const r=this.subscriptionsList[t];if("object"!=typeof r)return;const n=r.trackedServers.length-1;r.trackedServers=r.trackedServers.filter(t=>t.subscriptionId!==e.subscription_id||(r.queued.closers.push(t.serverId),!1)),r.trackedServers.length===n&&(r.trackedServers.length<=0&&(this.timedCache.add(r),clearTimeout(r.timeoutId),this.callOnClosedHandlers(r),delete this.subscriptionsList[t]),delete this.subscriptionIdToLocalKeyMap[e.subscription_id])};callOnClosedHandlers(e,t){const r=e.queued.closers.length,n=r>0?e.queued.closers[r-1]:null;let i;void 0!==n&&"string"==typeof n&&(i=this.repository.getServerById(n)?.instance??{}),e.handlers.onClosed.forEach(r=>{"function"==typeof r&&r({message:t||ON_CLOSE_MSG_SERVER_INIT,requestArguments:e.params.arguments||{},server:i,stream:e.method})})}closeSubscription(e){const t=this.subscriptionsList[e];"object"==typeof t&&(t.trackedServers.forEach(e=>{void 0!==e.subscriptionId&&(t.queued.closers.push(e.serverId),this.session.sendFireAndForget({type:"unsubscribe",subscription_id:e.subscriptionId,reason_uri:"",reason:ON_CLOSE_MSG_CLIENT_INIT}).catch(t=>{this.logger.warn(`Error sending unsubscribe for subscription id ${e.subscriptionId}: ${JSON.stringify(t)}`)}),delete this.subscriptionIdToLocalKeyMap[e.subscriptionId])}),t.trackedServers=[],this.callOnClosedHandlers(t,ON_CLOSE_MSG_CLIENT_INIT),delete this.subscriptionsList[e])}}class ClientProtocol{session;repository;logger;streaming;constructor(e,t,r){this.session=e,this.repository=t,this.logger=r,e.on("peer-added",e=>this.handlePeerAdded(e)),e.on("peer-removed",e=>this.handlePeerRemoved(e)),e.on("methods-added",e=>this.handleMethodsAddedMessage(e)),e.on("methods-removed",e=>this.handleMethodsRemovedMessage(e)),this.streaming=new ClientStreaming(e,t,r)}subscribe(e,t,r,n,i,o){this.streaming.subscribe(e,t,r,n,i,o)}invoke(e,t,r,n){const i=n.id,o={type:"call",server_id:i,method_id:t.gatewayId,arguments_kv:r};return this.session.send(o,{invocationId:e,serverId:i}).then(e=>this.handleResultMessage(e)).catch(e=>this.handleInvocationError(e))}drainSubscriptions(){return this.streaming.drainSubscriptions()}drainSubscriptionsCache(){return this.streaming.drainSubscriptionsCache()}handlePeerAdded(e){const t=e.new_peer_id,r=e.identity,n=!e.meta||e.meta.local,i=Number(r.process),o={...r,pid:isNaN(i)?r.process:i,peerId:t,isLocal:n};this.repository.addServer(o,t)}handlePeerRemoved(e){const t=e.removed_id,r=e.reason;this.repository.removeServerById(t,r)}handleMethodsAddedMessage(e){const t=e.server_id;e.methods.forEach(e=>{this.repository.addServerMethod(t,e)})}handleMethodsRemovedMessage(e){const t=e.server_id,r=e.methods,n=this.repository.getServerById(t);if(n){Object.keys(n.methods).forEach(e=>{const i=n.methods[e];r.indexOf(i.gatewayId)>-1&&this.repository.removeServerMethod(t,e)})}}handleResultMessage(e){const t=e._tag.invocationId,r=e.result,n=e._tag.serverId,i=this.repository.getServerById(n);return{invocationId:t,result:r,instance:i?.instance,status:InvokeStatus.Success,message:""}}handleInvocationError(e){if(this.logger.debug(`handle invocation error ${JSON.stringify(e)}`),"_tag"in e){const t=e._tag.invocationId,r=e._tag.serverId,n=this.repository.getServerById(r),i=e.reason;return{invocationId:t,result:e.context,instance:n?.instance,status:InvokeStatus.Error,message:i}}return{invocationId:"",message:e.message,status:InvokeStatus.Error,error:e}}}function gW3ProtocolFactory(e,t,r,n,i,o){const s=i.logger.subLogger("gw3-protocol");let a;const c=new Promise(e=>{a=e}),l=t.domain("agm",["subscribed"]),u=new ServerProtocol(l,r,n,s.subLogger("server")),d=new ClientProtocol(l,r,s.subLogger("client"));return l.onJoined(i=>{r.addServer(e,t.peerId),i?async function(){s.info("reconnected - will replay registered methods and subscriptions"),d.drainSubscriptionsCache().forEach(e=>{const t=e.method,r=Object.assign({},e.params);s.info(`trying to soft-re-subscribe to method ${t.name}, with params: ${JSON.stringify(r)}`),o.client.subscribe(t,r,void 0,void 0,e).then(()=>s.info(`soft-subscribing to method ${t.name} DONE`)).catch(e=>s.warn(`subscribing to method ${t.name} failed: ${JSON.stringify(e)}}`))});const e=[],t=d.drainSubscriptions();for(const r of t){const t=r.method,n=Object.assign({},r.params);s.info(`trying to re-subscribe to method ${t.name}, with params: ${JSON.stringify(n)}`),e.push(o.client.subscribe(t,n,void 0,void 0,r).then(()=>s.info(`subscribing to method ${t.name} DONE`)))}const r=n.getList();n.reset();for(const t of r){const r=t.definition;t.stream?e.push(o.server.createStream(r,t.streamCallbacks,void 0,void 0,t.stream).then(()=>s.info(`subscribing to method ${r.name} DONE`)).catch(()=>s.warn(`subscribing to method ${r.name} FAILED`))):t?.theFunction?.userCallback?e.push(o.register(r,t.theFunction.userCallback).then(()=>s.info(`registering method ${r.name} DONE`)).catch(()=>s.warn(`registering method ${r.name} FAILED`))):t?.theFunction?.userCallbackAsync&&e.push(o.registerAsync(r,t.theFunction.userCallbackAsync).then(()=>s.info(`registering method ${r.name} DONE`)).catch(()=>s.warn(`registering method ${r.name} FAILED`)))}await Promise.all(e),s.info("Interop is re-announced")}().then(()=>t.setLibReAnnounced({name:"interop"})).catch(e=>s.warn(`Error while re-announcing interop: ${JSON.stringify(e)}`)):a&&(a({client:d,server:u}),a=void 0)}),l.onLeft(()=>{r.reset()}),l.join(),c}class Interop{instance;readyPromise;client;server;unwrappedInstance;protocol;clientRepository;serverRepository;constructor(e){if(void 0===e)throw new Error("configuration is required");if(void 0===e.connection)throw new Error("configuration.connections is required");const t=e.connection;let r;if("number"!=typeof e.methodResponseTimeout&&(e.methodResponseTimeout=3e4),"number"!=typeof e.waitTimeoutMs&&(e.waitTimeoutMs=3e4),this.unwrappedInstance=new InstanceWrapper(this,void 0,t),this.instance=this.unwrappedInstance.unwrap(),this.clientRepository=new ClientRepository(e.logger.subLogger("cRep"),this),this.serverRepository=new ServerRepository,3!==t.protocolVersion)throw new Error(`protocol ${t.protocolVersion} not supported`);r=gW3ProtocolFactory(this.instance,t,this.clientRepository,this.serverRepository,e,this),this.readyPromise=r.then(t=>(this.protocol=t,this.client=new Client(this.protocol,this.clientRepository,this.instance,e),this.server=new Server(this.protocol,this.serverRepository),this))}ready(){return this.readyPromise}serverRemoved(e){return this.client.serverRemoved(e)}serverAdded(e){return this.client.serverAdded(e)}serverMethodRemoved(e){return this.client.serverMethodRemoved(e)}serverMethodAdded(e){return this.client.serverMethodAdded(e)}methodRemoved(e){return this.client.methodRemoved(e)}methodAdded(e){return this.client.methodAdded(e)}methodsForInstance(e){return this.client.methodsForInstance(e)}methods(e){return this.client.methods(e)}servers(e){return this.client.servers(e)}subscribe(e,t,r,n){return this.client.subscribe(e,t,r,n)}createStream(e,t,r,n){return this.server.createStream(e,t,r,n)}unregister(e){return this.server.unregister(e)}registerAsync(e,t){return this.server.registerAsync(e,t)}register(e,t){return this.server.register(e,t)}invoke(e,t,r,n,i,o){return this.client.invoke(e,t,r,n,i,o)}waitForMethod(e){const t=new PromiseWrapper$1,r=this.client.methodAdded(n=>{n.name===e&&(r(),t.resolve(n))});return t.promise}}const successMessages=["subscribed","success"],RECONNECT_STABILIZATION_MS=500,MAX_PENDING_PUBLISHES=1e4;class MessageBus{connection;logger;session;subscriptions;readyPromise;resubscribeInProgress;pendingPublishes=[];canDrain=!1;drainInProgress=!1;sessionGeneration=0;constructor(e,t){this.connection=e,this.logger=t,this.subscriptions=[],this.session=e.domain("bus",successMessages),this.readyPromise=this.session.join(),this.readyPromise.then(()=>{this.watchOnEvent()}),this.session.onLeft(()=>{this.canDrain=!1,this.sessionGeneration++}),this.session.onJoined(e=>{this.sessionGeneration++;const t=this.sessionGeneration,r=this.resubscribeInProgress??Promise.resolve();this.resubscribeInProgress=r.then(async()=>{try{if(e&&(await this.resubscribe(),await this.sleep(RECONNECT_STABILIZATION_MS)),this.sessionGeneration!==t)return;this.canDrain=!0,this.tryDrain()}catch(e){this.logger.error(`bus: error during onJoined chain: ${JSON.stringify(e)}`)}})})}sleep(e){return new Promise(t=>setTimeout(t,e))}ready(){return this.readyPromise}publish=(e,t,r)=>{this.publishCore(e,t,r)};publishCore(e,t,r){const{routingKey:n,target:i}=r||{},o=distExports.Traces.currentTracingState;if(o.addData("INFO",{topic:e}),o.addData("DIAGNOSTIC",{data:t}),o.addData("INFO",{routingKey:n,target:i}),t=deepClone(t),o.injectPropagationInfo(t),this.pendingPublishes.push({topic:e,data:t,options:r?deepClone(r):void 0}),this.pendingPublishes.length>MAX_PENDING_PUBLISHES){const e=this.pendingPublishes.length-MAX_PENDING_PUBLISHES;this.pendingPublishes.splice(0,e),this.logger.warn(`bus: outbox exceeded ${MAX_PENDING_PUBLISHES}, dropped ${e} oldest publish(es)`)}1!==this.pendingPublishes.length||this.canDrain?this.canDrain||this.logger.debug(`bus: queued publish to ${e} (${this.pendingPublishes.length} pending)`):this.logger.info(`bus: started buffering publishes (first topic: ${e})`),this.tryDrain()}isTransportError(e){return null!=e&&("object"!=typeof e||!e.request_id&&!e.domain)}async tryDrain(){if(!this.drainInProgress&&this.canDrain){this.drainInProgress=!0;try{let e=0;for(;this.pendingPublishes.length>0&&this.canDrain;){const t=this.pendingPublishes[0],{routingKey:r,target:n}=t.options||{},i=this.removeEmptyValues({type:"publish",topic:t.topic,data:t.data,peer_id:this.connection.peerId,routing_key:r,target_identity:n});try{await this.session.sendFireAndForget(i),this.pendingPublishes.shift(),e++}catch(e){if(this.isTransportError(e)){this.logger.info(`bus: drain paused at ${t.topic} due to transport error (${this.pendingPublishes.length} pending)`);break}this.pendingPublishes.shift(),this.logger.error(`bus: failed to publish to ${t.topic}: ${JSON.stringify(e)}`)}}e>0&&0===this.pendingPublishes.length&&this.logger.debug(`bus: drained ${e} publish(es)`)}finally{this.drainInProgress=!1}}}subscribe=(e,t,r)=>this.subscribeCore(e,t,r);subscribeCore(e,t,r){return new Promise((n,i)=>{const{routingKey:o,target:s}=r||{},a=distExports.Traces.currentTracingState;a.addData("INFO",{topic:e}),a.addData("INFO",{routingKey:o,target:s});const c=this.removeEmptyValues({type:"subscribe",topic:e,peer_id:this.connection.peerId,routing_key:o,source:s});this.session.send(c).then(r=>{const{subscription_id:i}=r;a.addData("INFO",{subscription_id:i});const c={subscription_id:i,topic:e,routingKey:o,source:s,callback:function(...r){const n=distExports.Traces.extractPropagationInfo(r?.[0],!0);distExports.withSpan("interopio.api.bus.subscribe.callback",{topic:e},n,n=>{n.addData("INFO",{topic:e,subscription_id:c.subscription_id}),n.addData("DIAGNOSTIC",{data:r?.[0]}),t.apply(this,r)})}};this.subscriptions.push(c),n({unsubscribe:()=>{const e=c.subscription_id;return this.subscriptions=this.subscriptions.filter(t=>t.subscription_id!==e),this.session.send({type:"unsubscribe",subscription_id:e,peer_id:this.connection.peerId}).catch(t=>{this.logger.warn(`Failed to send unsubscribe request for ${e}: ${JSON.stringify(t)}`)}),Promise.resolve()}})}).catch(e=>i(e))})}watchOnEvent=()=>{this.session.on("event",e=>{const{data:t,subscription_id:r}=e,n=e["publisher-identity"],i=this.subscriptions.find(e=>e.subscription_id===r);i&&(i.source?this.keysMatch(i.source,n)&&i.callback(t,i.topic,n):i.callback(t,i.topic,n))})};async resubscribe(){const e=[...this.subscriptions];this.logger.info(`bus: re-subscribing ${e.length} subscription(s) after reconnect`);for(const t of e)if(this.subscriptions.includes(t))try{const e=this.removeEmptyValues({type:"subscribe",topic:t.topic,peer_id:this.connection.peerId,routing_key:t.routingKey,source:t.source}),r=await this.session.send(e);t.subscription_id=r.subscription_id}catch(e){this.logger.error(`bus: failed to re-subscribe to topic "${t.topic}": ${JSON.stringify(e)}`)}}removeEmptyValues(e){const t={};return Object.keys(e).forEach(r=>{void 0!==e[r]&&null!==e[r]&&(t[r]=e[r])}),t}keysMatch(e,t){const r=Object.keys(e);let n=!0;return r.forEach(r=>{e[r]!==t[r]&&(n=!1)}),n}}function replaceComplexProperties(e){if(!isPrimitiveOrFunction(e))for(const t in e){if(!Object.prototype.hasOwnProperty.call(e,t))continue;const r=e[t];isPrimitiveOrFunction(r)||(isPlainObject$1$1(r)||Array.isArray(r)?replaceComplexProperties(r):e[t]=r?.constructor?.name||r.toString())}}function isPrimitiveOrFunction(e){return!e||(e!==Object(e)||"function"==typeof e)}async function loadInsightsPlugins(e,t){try{(await Promise.resolve().then(function(){return index$2})).init()}catch{e.warn("@interopio/insights-base plugin failed to load, insights will be disabled")}if(t.metrics?.enabled)try{(await Promise.resolve().then(function(){return index$1})).init()}catch{e.warn("@interopio/insights-metrics plugin failed to load, insights metrics functionality will be disabled")}if(t.traces?.enabled)try{(await Promise.resolve().then(function(){return index})).init()}catch{e.warn("@interopio/insights-traces plugin failed to load, insights traces functionality will be disabled")}}__decorate([distExports.withSpan("interopio.api.bus.publish",{argMapping:["topic"]})],MessageBus.prototype,"publishCore",null),__decorate([distExports.withSpan("interopio.api.bus.subscribe",{argMapping:["topic"]})],MessageBus.prototype,"subscribeCore",null);const IOConnectCoreFactory=(e,t)=>{const r="object"==typeof window?window.iodesktop??window.glue42gd:void 0,n="object"==typeof window?window.gdPreloadPromise??Promise.resolve():Promise.resolve(),i=new PromiseWrapper$1,o=timer("glue"),s=prepareConfig(e=e||{},t=t||{},r);let a,c,l,u,d,h,p,g;const m={};function f(e,t,r){g=l.canPublish("trace"),g&&l.trace(`registering ${e} module`);const n=n=>{if(t.initTime=r.stop(),t.initEndTime=r.endTime,t.marks=r.marks,!g)return;const i=n?`${e} failed - ${n.message}`:`${e} is ready - ${r.endTime-r.startTime}`;l.trace(i)};t.initStartTime=r.startTime,t.ready?t.ready().then(()=>{n()}).catch(e=>{const t="string"==typeof e?new Error(e):e;n(t)}):n(),Array.isArray(e)||(e=[e]),e.forEach(e=>{m[e]=t,IOConnectCoreFactory[e]=t})}function y(){const e=timer("metrics"),t=s.metrics,n=r?.getMetricsPublishingEnabled,i=s.connection.identity,o=n||(()=>!0),c=("boolean"!=typeof t&&t.disableAutoAppSystem)??!1;return u=metrics$1({connection:t?a:void 0,logger:l.subLogger("metrics"),canUpdateMetric:o,system:"Glue42",service:i?.service??r?.applicationName??s.application,instance:i?.instance??i?.windowId??nanoid$1(10),disableAutoAppSystem:c,pagePerformanceMetrics:"boolean"!=typeof t?t?.pagePerformanceMetrics:void 0}),f("metrics",u,e),Promise.resolve()}function $(){const e=timer("interop"),t={connection:a,logger:l.subLogger("interop")};return c=new Interop(t),Logger.Interop=c,f(["interop","agm"],c,e),Promise.resolve()}function b(){const e=s.activities&&3===a.protocolVersion;if(s.contexts||e){const e=timer("contexts");d=new ContextsModule({connection:a,logger:l.subLogger("contexts"),trackAllContexts:"object"==typeof s.contexts&&s.contexts.trackAllContexts,reAnnounceKnownContexts:"object"==typeof s.contexts&&s.contexts.reAnnounceKnownContexts,subscribeOnGet:"object"!=typeof s.contexts||s.contexts.subscribeOnGet,subscribeOnUpdate:"object"!=typeof s.contexts||s.contexts.subscribeOnUpdate,onlyReAnnounceSubscribedContexts:"object"!=typeof s.contexts||s.contexts.onlyReAnnounceSubscribedContexts}),f("contexts",d,e)}else{const e=a.replayer;e&&e.drain(ContextMessageReplaySpec.name)}return Promise.resolve()}async function w(){if(!s.bus)return Promise.resolve();const e=timer("bus");return h=new MessageBus(a,l.subLogger("bus")),f("bus",h,e),Promise.resolve()}function v(e){try{return e.forEach(e=>{!function(e,t){const r=timer(e),n=t(m);n&&f(e,n,r)}(e.name,e.create)}),Promise.resolve()}catch(e){return Promise.reject(e)}}return n.then(function(){const e=timer("logger");return l=new Logger(`${s.connection.identity?.application}`,void 0,s.customLogger),l.consoleLevel(s.logger.console),l.publishLevel(s.logger.publish),l.canPublish("debug")&&l.debug("initializing glue..."),f("logger",l,e),Promise.resolve(void 0)}).then(function(){const e=timer("connection");a=new Connection(s.connection,l.subLogger("connection"));let t=Promise.resolve(s.auth);return s.connection&&!s.auth&&(r?t=r.getGWToken().then(e=>({gatewayToken:e})):"undefined"!=typeof window&&window?.glue42electron?"string"==typeof window.glue42electron.gwToken&&(t=Promise.resolve({gatewayToken:window.glue42electron.gwToken})):t=Promise.reject("You need to provide auth information")),t.then(t=>{let r;if(e.mark("auth-promise-resolved"),"[object Object]"!==Object.prototype.toString.call(t))throw new Error("Invalid auth object - "+JSON.stringify(t));return r=t,a.login(r)}).then(()=>(f("connection",a,e),s)).catch(e=>{throw a&&a.logout(),e})}).then(()=>Promise.all([y(),$(),b(),w()])).then(()=>c.readyPromise).then(()=>async function(){const t="T42.ACS.RegisterInstance";if(Utils.isNode()&&"undefined"==="undefined".env._GD_STARTING_CONTEXT_&&void 0!==e?.application&&c.methods({name:t}).length>0)try{await c.invoke(t,{appName:e?.application,pid:process.pid})}catch(e){const t=e;l.error(`Cannot register as an instance: ${JSON.stringify(t.message)}`)}}()).then(()=>async function(t){const n=timer("insights"),o=await s.getInsights(r,t,l);s.insights=o;try{const e=new distExports.Builder,t=l.subLogger("insights");o.enabled&&await loadInsightsPlugins(t,o),e.withSettings(o),e.withLogger(new distExports.Log4jsWrapper(t)),e.withMetrics();const r="___insights_pi_storage___";e.withTraces().withTraceLogger(new distExports.Log4jsWrapper(t.subLogger("traces"))).withPropagationInfoStorage((e,t)=>d?.update(r,{[e.replace(/[.]/g,"_!_")]:{pi:t}}),e=>d?.get(r)?.then(t=>t[e.replace(/[.]/g,"_!_")]?.pi)??Promise.resolve(null));const s=e.build();return await s.start(),f("insights",s,n),distExports.Traces.withSpan("interopio.api.startup",()=>i.promise),p=s,Promise.resolve()}catch(e){if(n.stop(),l?.error("Error initializing insights",e),o.failOnInitError)throw e;return Promise.resolve()}finally{replaceComplexProperties(s?.insights),replaceComplexProperties(e?.insights)}}(c)).then(()=>v(s.libs||[])).then(function(){const e=Object.keys(m).map(e=>{const t=m[e];return t.ready?t.ready():Promise.resolve()});return Promise.all(e)}).then(function(){const n={coreVersion:version$2,version:s.version};o.stop();const g={feedback:e=>{c&&c.invoke("T42.ACS.Feedback",e,"best")},info:n,logger:l,interop:c,agm:c,connection:a,metrics:u,contexts:d,insights:p,bus:h,version:s.version,userConfig:e,done:()=>(l?.info("done called by user..."),a.logout())};if(g.performance={get glueVer(){return s.version},get glueConfig(){return JSON.stringify(e)},get browser(){return window.performance.timing.toJSON()},get memory(){return window.performance.memory},get initTimes(){const e=getAllTimers();return Object.keys(e).map(t=>{const r=e[t];return{name:t,duration:r.endTime-r.startTime,marks:r.marks,startTime:r.startTime,endTime:r.endTime}})}},Object.keys(m).forEach(e=>{const t=m[e];g[e]=t}),g.config={},Object.keys(s).forEach(e=>{g.config[e]=s[e]}),t&&t.extOptions&&Object.keys(t.extOptions).forEach(e=>{g.config[e]=t?.extOptions[e]}),t?.enrichGlue&&t.enrichGlue(g),r&&r.updatePerfData&&r.updatePerfData(g.performance),g.agm){const e=(e,t,r)=>function(){return g.logger.warn(`glue.js - 'glue.agm.${t}' method is deprecated, use 'glue.interop.${r}' instead.`),e.apply(g.agm,arguments)},t=g.agm;t.method_added=e(g.agm.methodAdded,"method_added","methodAdded"),t.method_removed=e(g.agm.methodRemoved,"method_removed","methodRemoved"),t.server_added=e(g.agm.serverAdded,"server_added","serverAdded"),t.server_method_aded=e(g.agm.serverMethodAdded,"server_method_aded","serverMethodAdded"),t.server_method_removed=e(g.agm.serverMethodRemoved,"server_method_removed","serverMethodRemoved")}return i.resolve(),g}).catch(e=>(i.reject({err:e}),Promise.reject({err:e,libs:m})))};"undefined"!=typeof window&&(window.IOConnectCore=IOConnectCoreFactory),IOConnectCoreFactory.version=version$2,IOConnectCoreFactory.default=IOConnectCoreFactory;const PromiseWrap=(e,t,r)=>new Promise((n,i)=>{let o=!0;const s=setTimeout(()=>{if(!o)return;o=!1;i(r||`Promise timeout hit: ${t}`)},t);e().then(e=>{o&&(o=!1,clearTimeout(s),n(e))}).catch(e=>{o&&(o=!1,clearTimeout(s),i(e))})}),PromisePlus=(e,t,r)=>new Promise((n,i)=>{const o=setTimeout(()=>{i(r||`Promise timeout hit: ${t}`)},t);new Promise(e).then(e=>{clearTimeout(o),n(e)}).catch(e=>{clearTimeout(o),i(e)})});var version$1="4.4.1-beta.0";class GlueController{portsBridge;sessionStorage;_config;_systemGlue;_contextsTrackingGlue;_clientGlue;_systemStream;_workspacesStream;_platformClientWindowId;_systemSettings;constructor(e,t){this.portsBridge=e,this.sessionStorage=t}get logger(){return logger.get("glue.controller")}get workspaces(){return this._clientGlue.workspaces?this._clientGlue.workspaces:ioError.raiseError("Cannot access the Workspaces API")}get isWorkspacesEnabled(){return!!this._clientGlue.workspaces}get me(){return this._clientGlue.interop.instance}get platformVersion(){return version$1}get clientGlue(){return this._clientGlue}get contextsTrackingGlue(){return this._contextsTrackingGlue}get systemGlue(){return this._systemGlue}get platformWindowId(){return this._platformClientWindowId.slice()}async start(e){this._config=e;const t=this.sessionStorage.getSystemSettings();if(!t)return ioError.raiseError("Cannot initiate the glue controller, because the system settings are not defined");this._systemSettings=t,this._systemGlue=await this.initSystemGlue(e.browser),logger.setLogger(this._systemGlue.logger),this.logger?.debug(`system glue initialized successfully with config ${JSON.stringify(e.browser)}`),this._contextsTrackingGlue=await this.setUpCtxTracking(e),this.logger?.debug("glueController started successfully")}async initClientGlue(e,t,r,n){this.logger?.debug(`initializing client glue with config: ${JSON.stringify(e)}, factory: ${t?"custom":"default"}, isWorkspaceFrame: ${r}, platformApi: ${n?"provided":"none"}`);const i=await this.portsBridge.createInternalClient();this.registerClientWindow(r);const o={application:"Platform",gateway:{webPlatform:{port:i,windowId:this.platformWindowId}}},s=Object.assign({},e,o);return this._clientGlue=t?await t(s):await iOConnectBrowserFactory(s),this._clientGlue.webPlatform=n,this.logger?.debug("client glue initialized successfully"),this._clientGlue}async createPlatformSystemMethod(e){await this.createMethodAsync(GlueWebPlatformControlName,e)}async createPlatformSystemStream(){this._systemStream=await this.createStream(GlueWebPlatformStreamName)}async createSystemStream(e){return this.createStream(e)}async createWorkspacesStream(){this._workspacesStream=await this.createStream(GlueWebPlatformWorkspacesStreamName)}async createWorkspacesEventsReceiver(e){await this._systemGlue.interop.register(GlueWorkspacesEventsReceiverName,t=>e(t))}pushSystemMessage(e,t,r){if(!this._systemStream)return ioError.raiseError(`Cannot push data to domain: ${e}, because the system stream is not created`);this._systemStream.push({domain:e,operation:t,data:r})}pushWorkspacesMessage(e){if(!this._workspacesStream)return ioError.raiseError("Cannot push data to domain: workspaces, because the workspaces stream is not created");this._workspacesStream.push({data:e})}async callFrame(e,t,r){const n={operation:e.name,operationArguments:t},i=`Internal Platform->Frame Communication Error. Attempted calling workspace frame: ${r} for operation ${e.name} `;if(e.dataDecoder){const t=e.dataDecoder.run(n.operationArguments);if(!t.ok)return ioError.raiseError(`${i} OutBound validation failed: ${JSON.stringify(t.error)}`)}const o=GlueWorkspaceFrameClientControlName,s=await this.transmitMessage(o,n,i,{windowId:r},{methodResponseTimeoutMs:DEFAULT_METHOD_RESPONSE_TIMEOUT_MS$1,waitTimeoutMs:DEFAULT_WAIT_TIMEOUT_MS});if(e.resultDecoder){const t=e.resultDecoder.run(s);if(!t.ok)return ioError.raiseError(`${i} Result validation failed: ${JSON.stringify(t.error)}`)}return s}async isFrameOperationSupported(e,t){try{return!0===(await this.callFrame({name:"operationCheck",execute:()=>Promise.resolve()},{operation:e},t)).isSupported}catch{return!1}}isValidWindowId(e){if(!e)return!1;return[...this.sessionStorage.getAllWindowsData(),...this.sessionStorage.getAllNonGlue()].some(t=>t.windowId===e)}async sendShutDownSignals(){const e=this.clientGlue.windows.list().filter(e=>e.id!==this.platformWindowId);await Promise.all(e.map(e=>e.close()));const t={domain:"system",operation:"platformShutdown"},r=`Internal Platform-> ${t.domain} Domain Communication Error. Attempted sending shutdown signal to all clients.`,n=this.getLocalServers().filter(t=>e.every(e=>e.id!==t.windowId)).map(e=>({instance:e.instance}));try{await this.transmitMessage(GlueClientControlName,t,r,n,{methodResponseTimeoutMs:DEFAULT_METHOD_RESPONSE_TIMEOUT_MS$1,waitTimeoutMs:DEFAULT_WAIT_TIMEOUT_MS})}catch(e){console.warn("Failed to send shutdown signal to all clients",e)}}shutdown(){this.systemGlue.connection.logout(),this.contextsTrackingGlue?.connection.logout(),this.clientGlue.connection.logout()}async checkClientOperationSupport(e,t,r){try{return await this.callInstance(e,{name:"operationCheck",execute:async()=>{}},{operation:t.name},r)}catch(e){return{isSupported:!1}}}async callInstance(e,t,r,n,i){return this.callClient(e,t,r,n,"instance",i)}async callWindow(e,t,r,n,i){return this.callClient(e,t,r,n,"window",i)}async callClient(e,t,r,n,i="window",o){const s=t.name,a={domain:e,operation:s,data:r},c={...n,isLocal:!0},l=`Internal Platform-> ${e} Domain Communication Error. Attempted calling client ${i}: ${JSON.stringify(c)} for operation ${s}.`;if(t.dataDecoder){const e=t.dataDecoder.run(a.data);if(!e.ok)return ioError.raiseError(`${l} OutBound validation failed: ${JSON.stringify(e.error)}`)}const u=await this.transmitMessage(GlueClientControlName,a,l,c,{methodResponseTimeoutMs:DEFAULT_METHOD_RESPONSE_TIMEOUT_MS$1,waitTimeoutMs:DEFAULT_WAIT_TIMEOUT_MS,...o});if(t.resultDecoder){const e=t.resultDecoder.run(u);if(!e.ok)return ioError.raiseError(`${l} Result validation failed when calling ${i}: ${JSON.stringify(c)} for operation ${s}: ${JSON.stringify(e.error)}`)}return u}setStartContext(e,t,r){return PromisePlus((n,i)=>{let o;const s=waitFor(2,()=>{n(),o()}),a=`___${r}___${e}`;(this._clientGlue.contexts.all().some(e=>e===a)?this.waitContextDestroy(a):Promise.resolve()).then(()=>this._clientGlue.contexts.subscribe(a,s)).then(e=>(o=e,this._systemGlue.contexts.set(a,t))).then(s).catch(i)},1e4,`Timed out waiting to set the ${r} context for: ${e}`)}waitContextDestroy(e){return new Promise((t,r)=>{let n=0;const i=setInterval(()=>{const o=this._clientGlue.contexts.all().some(t=>t===e);if(++n,!o)return clearInterval(i),void t();50===n&&(clearInterval(i),r(`Timed out waiting for context: ${e} to disappear`))},100)})}async clearContext(e,t){const r=`___${t}___${e}`,n=this._systemGlue.contexts.all().some(e=>e===r);n&&await this._systemGlue.contexts.destroy(r)}async preserveAllWorkspaceWindowsContext(e){const t=this.sessionStorage.pickWorkspaceClients(t=>t.workspaceId===e);for(const e of t){const t=await this._systemGlue.contexts.get(`___window___${e.windowId}`);t&&("object"!=typeof t||Object.keys(t).length)&&await this._systemGlue.contexts.set(`___window-hibernation___${e.windowId}`,t)}}async pullHibernatedContext(e){const t=`___window-hibernation___${e}`,r=this._systemGlue.contexts.all().some(e=>e===t);if(!r)return;const n=await this._systemGlue.contexts.get(t);return await this._systemGlue.contexts.destroy(t),n}getServers(){return this._clientGlue.interop.servers()}getLocalServers(){return this.getServers().filter(e=>e.isLocal)}subscribeForServerAdded(e){return this._clientGlue.interop.serverAdded(e)}subscribeForMethodAdded(e){return this._clientGlue.interop.methodAdded(e)}invokeMethod(e,t,r,n,i,o){return this._clientGlue.interop.invoke(e,t,r,n,i,o)}setContext(e,t){return this._systemGlue.contexts.set(e,t)}destroyContext(e){return this._systemGlue.contexts.destroy(e)}getAllContexts(){return this._clientGlue.contexts.all()}switchTransport(e,t){if("contextsTrack"===t)return this._contextsTrackingGlue?this._contextsTrackingGlue.connection.switchTransport(e):Promise.resolve({success:!0});return("system"===t?this._systemGlue:this._clientGlue).connection.switchTransport(e)}onDisconnected(e){return this._systemGlue.connection.disconnected(e)}getSystemGlueTransportName(){return this._systemGlue.connection.transport.name()}async importLayout(e){await this._clientGlue.layouts.import([e],"merge")}async getLayout(e){return await this._clientGlue.layouts.get(e,"Global")}async openWindow(e){this._clientGlue.windows.list().find(t=>t.name===e.name)&&(e.name=`${e.name}-${nanoid$3(7)}`);const t={context:e.context,top:e.bounds?.top,left:e.bounds?.left,width:e.bounds?.width,height:e.bounds?.height,layoutComponentId:e.layoutComponentId};return await this._clientGlue.windows.open(e.name,e.url,t)}async startApp(e){const t={waitForAGMReady:!1,top:e.bounds?.top,left:e.bounds?.left,width:e.bounds?.width,height:e.bounds?.height,layoutComponentId:e.layoutComponentId,channelId:e.channelId};return await this._clientGlue.appManager.application(e.name).start(e.context,t)}async getOrCreateWorkspaceFrame({bounds:e,layoutComponentId:t,frameId:r}){return r?await this.workspaces.getFrame(e=>e.id===r):await this.workspaces.createEmptyFrame({frameConfig:{bounds:e||void 0},layoutComponentId:t||void 0})}getAppNameByInstanceId(e){return this._clientGlue.interop.servers().find(t=>t.instance===e)?.application}getAllWindowNames(){return this._clientGlue.windows.list().map(e=>e.name)}getAllOpenedIds(){return this._clientGlue.windows.list().map(e=>e.id)}getAllOtherNonPlatformWindows(e){return this._clientGlue.windows.list().filter(t=>"Platform"!==t.name&&t.id!==e)}async getAllOpenedFrameIds(){return(await this.workspaces.getAllFrames()).map(e=>e.id)}getAllApplicationNames(){return this._clientGlue.appManager.applications().map(e=>e.name)}getAllApplications(){return this._clientGlue.appManager.applications()}getAllLayoutsSummaries(){return this._clientGlue.layouts.getAll("Global")}getAllWorkspacesSummaries(){return this._clientGlue.layouts.getAll("Workspace")}async getWorkspaceWindowById(e){return this._clientGlue.workspaces?.getWindow(t=>t.id===e)}getWindowById(e){return this._clientGlue.windows.list().find(t=>t.id===e)}async getAllWorkspacesFrames(){return await this.workspaces.getAllFrames()}async getWorkspacesByFrameId(e){return await this.workspaces.getAllWorkspaces(t=>t.frameId===e)}registerProvider(e){return this._clientGlue.search?this._clientGlue.search.registerProvider(e):ioError.raiseError("Cannot start the search provider for Glue42 Core Plus, because the Search API is missing")}async processServerApplicationsData(e){const t=e,r=await this._clientGlue.appManager.inMemory.import(t,"merge");r.errors&&r.errors.length&&r.errors.forEach(e=>{this.logger?.warn(`App: ${e.app} was not imported, because of error: ${e.error}`)})}async initSystemGlue(e){const t=await this.portsBridge.createInternalClient(),r=e?.systemLogger?.level??"warn",n=await IOConnectCoreFactory({application:"Platform-System",gateway:{webPlatform:{port:t}},logger:r,customLogger:e?.systemLogger?.customLogger,identity:{instance:this._systemSettings.systemInstanceId}});return this.logger?.debug("system glue initialized successfully"),n}async setUpCtxTracking(e){if(this._config.connection.preferred)return await this.initContextsTrackingGlue({reAnnounceKnownContexts:!0,trackAllContexts:!0},e)}async initContextsTrackingGlue(e,t){this.logger?.debug(`initializing contexts tracking glue with contexts settings - ${JSON.stringify(e)}`);const r=await this.portsBridge.createInternalClient(),n=await IOConnectCoreFactory({application:"Platform-Contexts-Track",gateway:{webPlatform:{port:r}},logger:t?.browser?.systemLogger?.level??"warn",customLogger:t?.browser?.systemLogger?.customLogger,contexts:e,identity:{instance:this._systemSettings.ctxTrackInstanceId}});return this.logger?.debug("contexts tracking glue initialized successfully"),n}registerClientWindow(e){const t=window.name?window.name:`g42-${nanoid$3(10)}`;if(e){const e=this.sessionStorage.getPlatformFrame();if(this._platformClientWindowId=e?e.windowId:t,!e){const e={windowId:this.platformWindowId,active:!0,isPlatform:!0};this.sessionStorage.saveFrameData(e)}return void(window.name=this.platformWindowId)}const r=this.sessionStorage.getWindowDataByName("Platform");this._platformClientWindowId=r?r.windowId:t,r||this.sessionStorage.saveWindowData({name:"Platform",windowId:this.platformWindowId}),window.name=this.platformWindowId}async createMethodAsync(e,t){await this._systemGlue.interop.registerAsync(e,t)}async createStream(e){return this._systemGlue.interop.createStream(e)}async transmitMessage(e,t,r,n,i){let o;try{if(o=await this._systemGlue.interop.invoke(e,t,n,i),!o)throw new Error(`${r} Received unsupported result from the client - empty result`);if(!Array.isArray(o.all_return_values)||0===o.all_return_values.length)throw new Error(`${r} Received unsupported result from the client - empty values collection`)}catch(e){if(e&&e.all_errors&&e.all_errors.length){const t=e.all_errors[0].message;return ioError.raiseError(`${r} -> Inner message: ${t}`)}return ioError.raiseError(`${r} -> Inner message: ${e.message}`)}return o.all_return_values[0].returned}}class PortsBridge{gateway;sessionStorage;windowsStateController;ioc;registry=CallbackRegistryFactory$2();transactionsController;allPorts={};allClients=[];unLoadStarted=!1;isPreferredActivated=!1;activePreferredTransportConfig;_communicationId;startUpPromise;startupResolve;_genericMessageHandler;_unloaderHandler;connectionConfig;constructor(e,t,r,n){this.gateway=e,this.sessionStorage=t,this.windowsStateController=r,this.ioc=n,this.transactionsController=this.ioc.transactionsController}get logger(){return logger.get("ports.bridge.controller")}shutdown(){window.removeEventListener("message",this._genericMessageHandler),window.removeEventListener("pagehide",this._unloaderHandler),this.registry.clear(),this.allPorts={},this.allClients=[],this.isPreferredActivated=!1,this.unLoadStarted=!1}async configure(e){this.connectionConfig=e.connection,this.startUpPromise=new Promise(e=>{this.startupResolve=e});const t=this.sessionStorage.getSystemSettings();if(!t)return ioError.raiseError("Cannot initiate the platform port bridge, because the system settings are not defined");this._communicationId=t.systemInstanceId,await this.gateway.start(e?.gateway,e?.user),this.setupListeners()}start(){this.startupResolve()}async createInternalClient(){const e=this.ioc.createMessageChannel();return await this.gateway.setupInternalClient(e.port1),e.port2}onClientUnloaded(e){return this.registry.add("client-unloaded",e)}async handleExtConnectionRequest(e,t){const r=e.glue42core;if(!!!r.parentWindowId){const e=r.clientId,t={windowId:e,name:e};await this.ioc.windowsController.processNewWindow(t)}await this.gateway.connectExtClient(t,(e,t)=>{this.removeClient({clientId:e},t)});const n=this.sessionStorage.getWindowDataByName("Platform")?.windowId,i={glue42core:{type:Glue42CoreMessageTypes.connectionAccepted.name,parentWindowId:n,appName:"ext-no-app",clientId:r.clientId,clientType:"child"}};this.allPorts[r.clientId]=t,t.postMessage(i)}setActivePreferredTransportConfig(e){"secondary"!==e.type?delete this.activePreferredTransportConfig:this.activePreferredTransportConfig=e}setPreferredActivated(){this.isPreferredActivated=!0}async switchAllClientsTransport(e){const t=Object.keys(this.allPorts).map(t=>this.sendClientPortRequest({type:Glue42CoreMessageTypes.transportSwitchRequest.name,timeout:defaultClientPortRequestTimeoutMS,clientId:t,args:{switchSettings:e}}));await Promise.all(t)}async checkClientsPreferredLogic(){const e=Object.keys(this.allPorts).map(e=>this.sendClientPortRequest({type:Glue42CoreMessageTypes.checkPreferredLogic.name,timeout:defaultClientPreferredLogicTestTimeoutMS,clientId:e}));try{return await Promise.all(e),{success:!0}}catch(e){return{success:!1}}}async checkClientsPreferredConnection(e){const t=Object.keys(this.allPorts).map(t=>this.sendClientPortRequest({type:Glue42CoreMessageTypes.checkPreferredConnection.name,args:{url:e},timeout:defaultClientPortRequestTimeoutMS,clientId:t}));try{return await Promise.all(t),{success:!0}}catch(e){return{success:!1}}}removeGwClient(e){const t=this.allClients.find(t=>t.bridgeInstanceId===e);t&&(this.allClients=this.allClients.filter(t=>t.bridgeInstanceId!==e),t.client.close(),this.allPorts[t.clientId]&&delete this.allPorts[t.clientId])}unloader(){this.unLoadStarted=!0;for(const e in this.allPorts)this.allPorts[e].postMessage({type:"platformUnload"});this.sessionStorage.handlePlatformUnloadCleanup()}genericMessageHandler(e){if(e.data?.type===FDC3HelloRequestType)return void this.processFDC3WebRequest(e);const t=e.data?.glue42core;t&&!this.unLoadStarted&&(t.type!==Glue42CoreMessageTypes.connectionRequest.name?t.type!==Glue42CoreMessageTypes.platformPing.name?t.type!==Glue42CoreMessageTypes.parentPing.name||this.startUpPromise.then(()=>this.handleParentPing(e.source,e.origin)):this.startUpPromise.then(()=>this.handlePlatformPing(e.source,e.origin)):this.startUpPromise.then(()=>this.handleRemoteConnectionRequest(e.source,e.origin,t.clientId,t.clientType,t.bridgeInstanceId,t.selfAssignedWindowId)))}async handleRemoteConnectionRequest(e,t,r,n,i,o){if(checkIsOriginBlocked(t,this.connectionConfig.blockList)){const r=`Origin '${t}' is blocked by the Platform.`;return this.rejectClientConnection(e,r,t)}const s=this.ioc.createMessageChannel(),a=await this.gateway.connectClient(s.port1);this.setupGwClientPort({client:a,clientId:r,clientPort:s.port1}),this.allClients.push({client:a,bridgeInstanceId:i,clientId:r,source:e});const c=this.sessionStorage.getBridgeInstanceData(i),l=c?.appName,u=this.sessionStorage.getWindowDataByName("Platform")?.windowId,d={glue42core:{type:Glue42CoreMessageTypes.connectionAccepted.name,port:s.port2,connectionProtocolVersion:connectionProtocolVersion,communicationId:this._communicationId,isPreferredActivated:this.isPreferredActivated,parentWindowId:u,appName:l,clientId:r,clientType:n}};o&&await this.ioc.windowsController.registerSelfAssignedWindow({windowId:o,name:o},o),e.postMessage(d,t,[s.port2])}rejectClientConnection(e,t,r){this.logger?.error(t);const n={glue42core:{type:Glue42CoreMessageTypes.connectionRejected.name,error:t}};e.postMessage(n,r)}processFDC3WebRequest(e){const t=this.windowsStateController.getAll().find(t=>t.window===e.source);if(!t)return void this.logger?.warn("[Browser Platform] FDC3 Hello request received from an unknown source, ignoring it.");const r={type:FDC3HelloResponseType,meta:{connectionAttemptUuid:e.data?.meta.connectionAttemptUuid,timestamp:(new Date).toISOString()},payload:{iframeUrl:`${window.fdc3ProxyUrl??FDC3ProxyUrl}?parentId=${t.windowId}`}};e.source.postMessage(r,e.origin)}handleParentPing(e,t){const r={glue42core:{type:Glue42CoreMessageTypes.parentReady.name}};e.postMessage(r,t)}handlePlatformPing(e,t){const r={glue42core:{type:Glue42CoreMessageTypes.platformReady.name}};e.postMessage(r,t)}removeClient(e,t,r){const{clientId:n,ownWindowId:i}=e;this.allPorts[n]&&!r&&delete this.allPorts[n];const o=this.allClients.find(e=>e.clientId===n);if(!o)return void this.logger?.warn(`Received client unload for unknown client: ${n}, ignoring it`);if(this.allClients=this.allClients.filter(e=>e.clientId!==n),o.client.close(),!t)return;const s={windowId:i,win:o.source};this.registry.execute("client-unloaded",s)}setupGwClientPort(e){this.allPorts[e.clientId]&&this.allPorts[e.clientId].onmessage&&(this.allPorts[e.clientId].onmessage=null),this.allPorts[e.clientId]=e.clientPort,e.clientPort.onmessage=t=>{const r=t.data?.glue42core,n=r?.type;if(n!==Glue42CoreMessageTypes.clientUnload.name&&n!==Glue42CoreMessageTypes.gatewayDisconnect.name){if(n===Glue42CoreMessageTypes.transportSwitchResponse.name){return void(r.args.success?this.transactionsController.completeTransaction(r.transactionId):this.transactionsController.failTransaction(r.transactionId,`The client: ${e.clientId} could not connect using the provided transport config.`))}if(n===Glue42CoreMessageTypes.getCurrentTransport.name){const t=r.transactionId;return void e.clientPort.postMessage({type:Glue42CoreMessageTypes.getCurrentTransportResponse.name,args:{transportState:this.getCurrentTransportState()},transactionId:t})}if(n===Glue42CoreMessageTypes.checkPreferredLogicResponse.name)return this.transactionsController.completeTransaction(r.transactionId);if(n===Glue42CoreMessageTypes.checkPreferredConnectionResponse.name){const t=r.args;return t.error?this.transactionsController.failTransaction(r.transactionId,t.error):t.live?this.transactionsController.completeTransaction(r.transactionId):this.transactionsController.failTransaction(r.transactionId,`Client ${e.clientId} could not connect to the preferred WS.`)}this.allClients.every(t=>t.client!==e.client)?this.logger?.trace(`Ignoring a protocol message, because the destination client has been disconnected: ${JSON.stringify(t.data)}`):e.client.send(t.data)}else this.removeClient(r.data,!0,r.type===Glue42CoreMessageTypes.gatewayDisconnect.name)}}getCurrentTransportState(){const e=this.ioc.glueController.getSystemGlueTransportName();return{transportName:e,type:e===webPlatformTransportName?"default":"secondary",transportConfig:e===webPlatformTransportName?void 0:this.activePreferredTransportConfig?.transportConfig}}sendClientPortRequest(e){const t=this.allPorts[e.clientId];if(!t)return ioError.raiseError(`Cannot sent port request: ${e.type} to ${e.clientId}, because there is no such client`);const r=this.transactionsController.createTransaction(e.type,e.timeout||defaultClientPortRequestTimeoutMS),n=e.type,i=e.args;return t.postMessage({type:n,args:i,transactionId:r.id}),r.lock}setupListeners(){this._genericMessageHandler=this.genericMessageHandler.bind(this),window.addEventListener("message",this._genericMessageHandler),this._unloaderHandler=this.unloader.bind(this),window.addEventListener("pagehide",this._unloaderHandler)}}const windowOperationDecoder=oneOf$1(constant$2("openWindow"),constant$2("windowHello"),constant$2("getUrl"),constant$2("getTitle"),constant$2("setTitle"),constant$2("moveResize"),constant$2("focus"),constant$2("close"),constant$2("getBounds"),constant$2("getFrameBounds"),constant$2("registerWorkspaceWindow"),constant$2("unregisterWorkspaceWindow"),constant$2("operationCheck"),constant$2("focusChange"),constant$2("getChannel"),constant$2("setZoomFactor"),constant$2("refresh")),openWindowConfigDecoder=object$2({name:nonEmptyStringDecoder$2,url:nonEmptyStringDecoder$2,options:optional$3(windowOpenSettingsDecoder)});object$2({windowId:nonEmptyStringDecoder$2,name:nonEmptyStringDecoder$2});const simpleWindowDecoder=object$2({windowId:nonEmptyStringDecoder$2}),windowBoundsResultDecoder=object$2({windowId:nonEmptyStringDecoder$2,bounds:windowBoundsDecoder}),frameWindowBoundsResultDecoder=object$2({bounds:windowBoundsDecoder}),windowUrlResultDecoder=object$2({windowId:nonEmptyStringDecoder$2,url:nonEmptyStringDecoder$2}),windowMoveResizeConfigDecoder=object$2({windowId:nonEmptyStringDecoder$2,top:optional$3(number$4()),left:optional$3(number$4()),width:optional$3(nonNegativeNumberDecoder$2),height:optional$3(nonNegativeNumberDecoder$2),relative:optional$3(boolean$3())}),windowTitleConfigDecoder=object$2({windowId:nonEmptyStringDecoder$2,title:string$4()}),windowChannelResultDecoder=object$2({channel:optional$3(nonEmptyStringDecoder$2)}),windowZoomFactorConfigDecoder=object$2({windowId:nonEmptyStringDecoder$2,factorIndex:nonNegativeNumberDecoder$2}),workspacesOperationDecoder=oneOf$1(constant$2("isWindowInWorkspace"),constant$2("createWorkspace"),constant$2("createFrame"),constant$2("initFrame"),constant$2("getAllFramesSummaries"),constant$2("getFrameSummary"),constant$2("getAllWorkspacesSummaries"),constant$2("getWorkspaceSnapshot"),constant$2("getAllLayoutsSummaries"),constant$2("openWorkspace"),constant$2("deleteLayout"),constant$2("saveLayout"),constant$2("importLayout"),constant$2("exportAllLayouts"),constant$2("restoreItem"),constant$2("maximizeItem"),constant$2("focusItem"),constant$2("closeItem"),constant$2("closeWorkspace"),constant$2("resizeItem"),constant$2("moveFrame"),constant$2("getFrameSnapshot"),constant$2("forceLoadWindow"),constant$2("ejectWindow"),constant$2("setItemTitle"),constant$2("moveWindowTo"),constant$2("addWindow"),constant$2("addContainer"),constant$2("bundleWorkspace"),constant$2("bundleItem"),constant$2("changeFrameState"),constant$2("getFrameState"),constant$2("getFrameBounds"),constant$2("frameHello"),constant$2("hibernateWorkspace"),constant$2("resumeWorkspace"),constant$2("getWorkspacesConfig"),constant$2("lockWorkspace"),constant$2("lockContainer"),constant$2("lockWindow"),constant$2("pinWorkspace"),constant$2("unpinWorkspace"),constant$2("getWorkspaceIcon"),constant$2("setWorkspaceIcon"),constant$2("checkStarted"),constant$2("getPlatformFrameId"),constant$2("getWorkspaceWindowsOnLayoutSaveContext"),constant$2("getWorkspacesLayouts"),constant$2("setMaximizationBoundary"),constant$2("operationCheck"),constant$2("getWorkspaceWindowFrameBounds"),constant$2("focusChange"),constant$2("bringBackToWorkspace"),constant$2("showChannelsLink")),frameHelloDecoder=object$2({windowId:optional$3(nonEmptyStringDecoder$2)}),workspaceWindowDataDecoder=object$2({name:nonEmptyStringDecoder$2,windowId:nonEmptyStringDecoder$2,frameId:nonEmptyStringDecoder$2,workspaceId:optional$3(nonEmptyStringDecoder$2),appName:optional$3(nonEmptyStringDecoder$2),context:optional$3(anyJson$2()),title:optional$3(nonEmptyStringDecoder$2),channelId:optional$3(nonEmptyStringDecoder$2)}),isWindowInSwimlaneResultDecoder=object$2({inWorkspace:boolean$3()}),allParentDecoder=oneOf$1(constant$2("workspace"),constant$2("row"),constant$2("column"),constant$2("group")),subParentDecoder=oneOf$1(constant$2("row"),constant$2("column"),constant$2("group")),frameStateDecoder=oneOf$1(constant$2("maximized"),constant$2("minimized"),constant$2("normal"));object$2({saveLayout:optional$3(boolean$3())});const deleteLayoutConfigDecoder=object$2({name:nonEmptyStringDecoder$2}),swimlaneWindowDefinitionDecoder=object$2({type:optional$3(constant$2("window")),appName:optional$3(nonEmptyStringDecoder$2),windowId:optional$3(nonEmptyStringDecoder$2),context:optional$3(anyJson$2())}),strictSwimlaneWindowDefinitionDecoder=object$2({type:constant$2("window"),appName:optional$3(nonEmptyStringDecoder$2),windowId:optional$3(nonEmptyStringDecoder$2),context:optional$3(anyJson$2())}),parentDefinitionDecoder=object$2({type:optional$3(subParentDecoder),children:optional$3(lazy(()=>array$3(oneOf$1(swimlaneWindowDefinitionDecoder,parentDefinitionDecoder)))),config:optional$3(anyJson$2())}),groupDefinitionConfigDecoder=object$2({minWidth:optional$3(number$4()),maxWidth:optional$3(number$4()),minHeight:optional$3(number$4()),maxHeight:optional$3(number$4()),allowExtract:optional$3(boolean$3()),allowReorder:optional$3(boolean$3()),allowDrop:optional$3(boolean$3()),allowDropHeader:optional$3(boolean$3()),allowDropLeft:optional$3(boolean$3()),allowDropTop:optional$3(boolean$3()),allowDropRight:optional$3(boolean$3()),allowDropBottom:optional$3(boolean$3()),showMaximizeButton:optional$3(boolean$3()),showEjectButton:optional$3(boolean$3()),showAddWindowButton:optional$3(boolean$3())}),rowDefinitionConfigDecoder=object$2({minHeight:optional$3(number$4()),maxHeight:optional$3(number$4()),allowDrop:optional$3(boolean$3()),allowSplitters:optional$3(boolean$3()),isPinned:optional$3(boolean$3()),maximizationBoundary:optional$3(boolean$3())}),columnDefinitionConfigDecoder=object$2({minWidth:optional$3(number$4()),maxWidth:optional$3(number$4()),allowDrop:optional$3(boolean$3()),allowSplitters:optional$3(boolean$3()),isPinned:optional$3(boolean$3()),maximizationBoundary:optional$3(boolean$3())}),strictColumnDefinitionDecoder=object$2({type:constant$2("column"),children:optional$3(lazy(()=>array$3(oneOf$1(strictSwimlaneWindowDefinitionDecoder,strictParentDefinitionDecoder)))),config:optional$3(columnDefinitionConfigDecoder)}),strictRowDefinitionDecoder=object$2({type:constant$2("row"),children:optional$3(lazy(()=>array$3(oneOf$1(strictSwimlaneWindowDefinitionDecoder,strictParentDefinitionDecoder)))),config:optional$3(rowDefinitionConfigDecoder)}),strictGroupDefinitionDecoder=object$2({type:constant$2("group"),children:optional$3(lazy(()=>array$3(oneOf$1(strictSwimlaneWindowDefinitionDecoder,strictParentDefinitionDecoder)))),config:optional$3(groupDefinitionConfigDecoder)}),strictParentDefinitionDecoder=oneOf$1(strictGroupDefinitionDecoder,strictColumnDefinitionDecoder,strictRowDefinitionDecoder);oneOf$1(string$4().where(e=>"maximized"===e.toLowerCase(),"Expected a case insensitive variation of 'maximized'"),string$4().where(e=>"normal"===e.toLowerCase(),"Expected a case insensitive variation of 'normal'"));const newFrameConfigDecoder=object$2({bounds:optional$3(object$2({left:optional$3(number$4()),top:optional$3(number$4()),width:optional$3(nonNegativeNumberDecoder$2),height:optional$3(nonNegativeNumberDecoder$2)})),frameId:optional$3(nonEmptyStringDecoder$2)}),loadStrategyDecoder=oneOf$1(constant$2("direct"),constant$2("delayed"),constant$2("lazy")),restoreWorkspaceConfigDecoder=object$2({app:optional$3(nonEmptyStringDecoder$2),context:optional$3(anyJson$2()),loadStrategy:optional$3(loadStrategyDecoder),title:optional$3(nonEmptyStringDecoder$2),reuseWorkspaceId:optional$3(nonEmptyStringDecoder$2),frameId:optional$3(nonEmptyStringDecoder$2),lockdown:optional$3(boolean$3()),activateFrame:optional$3(boolean$3()),newFrame:optional$3(oneOf$1(newFrameConfigDecoder,boolean$3())),noTabHeader:optional$3(boolean$3()),inMemoryLayout:optional$3(boolean$3()),isPinned:optional$3(boolean$3()),icon:optional$3(nonEmptyStringDecoder$2),isSelected:optional$3(boolean$3()),positionIndex:optional$3(nonNegativeNumberDecoder$2)}),openWorkspaceConfigDecoder=object$2({name:nonEmptyStringDecoder$2,restoreOptions:optional$3(restoreWorkspaceConfigDecoder)}),workspaceDefinitionDecoder=object$2({children:optional$3(array$3(oneOf$1(swimlaneWindowDefinitionDecoder,parentDefinitionDecoder))),context:optional$3(anyJson$2()),config:optional$3(object$2({title:optional$3(nonEmptyStringDecoder$2),position:optional$3(nonNegativeNumberDecoder$2),isFocused:optional$3(boolean$3()),loadStrategy:optional$3(loadStrategyDecoder),noTabHeader:optional$3(boolean$3()),allowDrop:optional$3(boolean$3()),allowDropLeft:optional$3(boolean$3()),allowDropTop:optional$3(boolean$3()),allowDropRight:optional$3(boolean$3()),allowDropBottom:optional$3(boolean$3()),allowExtract:optional$3(boolean$3()),allowWindowReorder:optional$3(boolean$3()),allowSystemHibernation:optional$3(boolean$3()),showSaveButton:optional$3(boolean$3()),allowWorkspaceTabReorder:optional$3(boolean$3()),allowWorkspaceTabExtract:optional$3(boolean$3()),showCloseButton:optional$3(boolean$3()),allowSplitters:optional$3(boolean$3()),positionIndex:optional$3(nonNegativeNumberDecoder$2)})),frame:optional$3(object$2({reuseFrameId:optional$3(nonEmptyStringDecoder$2),newFrame:optional$3(oneOf$1(boolean$3(),newFrameConfigDecoder))}))});object$2({type:allParentDecoder,definition:optional$3(oneOf$1(workspaceDefinitionDecoder,parentDefinitionDecoder))});const workspaceCreateConfigDecoder=intersection(workspaceDefinitionDecoder,object$2({saveConfig:optional$3(object$2({saveLayout:optional$3(boolean$3())}))})),getFrameSummaryConfigDecoder=object$2({itemId:nonEmptyStringDecoder$2}),frameSummaryDecoder=object$2({id:nonEmptyStringDecoder$2,isFocused:optional$3(boolean$3()),isInitialized:optional$3(boolean$3()),initializationContext:optional$3(object$2({context:optional$3(anyJson$2())}))});object$2({id:nonEmptyStringDecoder$2,frameId:nonEmptyStringDecoder$2,positionIndex:number$4(),title:nonEmptyStringDecoder$2,focused:boolean$3(),layoutName:optional$3(nonEmptyStringDecoder$2),isSelected:optional$3(boolean$3())}),object$2({type:subParentDecoder,id:nonEmptyStringDecoder$2,frameId:nonEmptyStringDecoder$2,workspaceId:nonEmptyStringDecoder$2,positionIndex:number$4()});const eventTypeDecoder=oneOf$1(constant$2("frame"),constant$2("workspace"),constant$2("container"),constant$2("window"));object$2({type:eventTypeDecoder,branch:nonEmptyStringDecoder$2}),oneOf$1(constant$2("opened"),constant$2("closing"),constant$2("closed"),constant$2("focus"),constant$2("added"),constant$2("loaded"),constant$2("removed"),constant$2("childrenUpdate"),constant$2("containerChange"),constant$2("maximized"),constant$2("restored"),constant$2("minimized"),constant$2("normal"),constant$2("selected"),constant$2("lock-configuration-changed"),constant$2("hibernated"),constant$2("resumed"),constant$2("tab-reordered"));const workspaceConfigResultDecoder=object$2({frameId:nonEmptyStringDecoder$2,title:nonEmptyStringDecoder$2,positionIndex:nonNegativeNumberDecoder$2,name:nonEmptyStringDecoder$2,layoutName:optional$3(nonEmptyStringDecoder$2),isHibernated:boolean$3(),isSelected:boolean$3(),lastActive:number$4(),allowDrop:optional$3(boolean$3()),allowExtract:optional$3(boolean$3()),allowWindowReorder:optional$3(boolean$3()),allowSystemHibernation:optional$3(boolean$3()),allowSplitters:optional$3(boolean$3()),showCloseButton:optional$3(boolean$3()),showSaveButton:optional$3(boolean$3()),allowWorkspaceTabReorder:optional$3(boolean$3()),allowDropLeft:optional$3(boolean$3()),allowDropTop:optional$3(boolean$3()),allowDropRight:optional$3(boolean$3()),allowDropBottom:optional$3(boolean$3()),showAddWindowButtons:optional$3(boolean$3()),showEjectButtons:optional$3(boolean$3()),showWindowCloseButtons:optional$3(boolean$3()),minWidth:optional$3(number$4()),maxWidth:optional$3(number$4()),minHeight:optional$3(number$4()),maxHeight:optional$3(number$4()),widthInPx:optional$3(number$4()),heightInPx:optional$3(number$4())}),baseChildSnapshotConfigDecoder=object$2({frameId:nonEmptyStringDecoder$2,workspaceId:nonEmptyStringDecoder$2,positionIndex:number$4()}),parentSnapshotConfigDecoder=anyJson$2(),swimlaneWindowSnapshotConfigDecoder=intersection(baseChildSnapshotConfigDecoder,object$2({windowId:optional$3(nonEmptyStringDecoder$2),isMaximized:optional$3(boolean$3()),isFocused:boolean$3(),isSelected:optional$3(boolean$3()),title:optional$3(string$4()),appName:optional$3(nonEmptyStringDecoder$2),context:optional$3(anyJson$2()),channel:optional$3(nonEmptyStringDecoder$2),instanceId:optional$3(nonEmptyStringDecoder$2)})),childSnapshotResultDecoder=object$2({id:optional$3(nonEmptyStringDecoder$2),config:oneOf$1(parentSnapshotConfigDecoder,swimlaneWindowSnapshotConfigDecoder),children:optional$3(lazy(()=>array$3(childSnapshotResultDecoder))),type:oneOf$1(constant$2("window"),constant$2("row"),constant$2("column"),constant$2("group"))}),workspaceSnapshotResultDecoder=object$2({id:nonEmptyStringDecoder$2,config:workspaceConfigResultDecoder,children:array$3(childSnapshotResultDecoder),frameSummary:frameSummaryDecoder,context:optional$3(anyJson$2())}),customWorkspaceChildSnapshotDecoder=object$2({id:nonEmptyStringDecoder$2,config:oneOf$1(parentSnapshotConfigDecoder,swimlaneWindowSnapshotConfigDecoder),children:optional$3(lazy(()=>array$3(customWorkspaceChildSnapshotDecoder))),type:oneOf$1(constant$2("window"),constant$2("row"),constant$2("column"),constant$2("group"))}),groupLayoutItemDecoder=object$2({type:constant$2("group"),config:anyJson$2(),children:array$3(oneOf$1(windowLayoutItemDecoder))}),columnLayoutItemDecoder=object$2({type:constant$2("column"),config:anyJson$2(),children:array$3(oneOf$1(groupLayoutItemDecoder,windowLayoutItemDecoder,lazy(()=>columnLayoutItemDecoder),lazy(()=>rowLayoutItemDecoder)))}),rowLayoutItemDecoder=object$2({type:constant$2("row"),config:anyJson$2(),children:array$3(oneOf$1(columnLayoutItemDecoder,groupLayoutItemDecoder,windowLayoutItemDecoder,lazy(()=>rowLayoutItemDecoder)))}),workspaceLayoutDecoder=object$2({name:nonEmptyStringDecoder$2,type:constant$2("Workspace"),metadata:optional$3(anyJson$2()),components:array$3(object$2({type:constant$2("Workspace"),application:optional$3(nonEmptyStringDecoder$2),state:object$2({config:anyJson$2(),context:anyJson$2(),children:array$3(oneOf$1(rowLayoutItemDecoder,columnLayoutItemDecoder,groupLayoutItemDecoder,windowLayoutItemDecoder))})}))}),workspacesLayoutImportConfigDecoder=object$2({layout:workspaceLayoutDecoder,mode:oneOf$1(constant$2("replace"),constant$2("merge"))}),exportedLayoutsResultDecoder=object$2({layouts:array$3(workspaceLayoutDecoder)}),frameSummaryResultDecoder=frameSummaryDecoder,frameSummariesResultDecoder=object$2({summaries:array$3(frameSummaryResultDecoder)}),workspaceSummaryResultDecoder=object$2({id:nonEmptyStringDecoder$2,config:workspaceConfigResultDecoder}),workspaceSummariesResultDecoder=object$2({summaries:array$3(workspaceSummaryResultDecoder)}),frameSnapshotResultDecoder=object$2({id:nonEmptyStringDecoder$2,config:anyJson$2(),workspaces:array$3(workspaceSnapshotResultDecoder)}),layoutSummaryDecoder=object$2({name:nonEmptyStringDecoder$2}),layoutSummariesDecoder=object$2({summaries:array$3(layoutSummaryDecoder)}),simpleWindowOperationSuccessResultDecoder=object$2({windowId:nonEmptyStringDecoder$2}),voidResultDecoder=anyJson$2(),frameStateResultDecoder=object$2({state:frameStateDecoder}),frameBoundsDecoder=object$2({top:number$4(),left:number$4(),width:nonNegativeNumberDecoder$2,height:nonNegativeNumberDecoder$2}),frameBoundsResultDecoder=object$2({bounds:frameBoundsDecoder}),resizeConfigDecoder=object$2({width:optional$3(nonNegativeNumberDecoder$2),height:optional$3(nonNegativeNumberDecoder$2),relative:optional$3(boolean$3())}),moveConfigDecoder=object$2({top:optional$3(number$4()),left:optional$3(number$4()),relative:optional$3(boolean$3())}),simpleItemConfigDecoder=object$2({itemId:nonEmptyStringDecoder$2}),ejectWindowDataDecoder=object$2({itemId:nonEmptyStringDecoder$2,windowId:optional$3(nonEmptyStringDecoder$2)}),frameSnapshotConfigDecoder=object$2({itemId:nonEmptyStringDecoder$2,excludeIds:optional$3(boolean$3())}),frameStateConfigDecoder=object$2({frameId:nonEmptyStringDecoder$2,requestedState:frameStateDecoder}),setItemTitleConfigDecoder=object$2({itemId:nonEmptyStringDecoder$2,title:nonEmptyStringDecoder$2}),moveWindowConfigDecoder=object$2({itemId:nonEmptyStringDecoder$2,containerId:nonEmptyStringDecoder$2}),resizeItemConfigDecoder=intersection(simpleItemConfigDecoder,resizeConfigDecoder),moveFrameConfigDecoder=intersection(simpleItemConfigDecoder,moveConfigDecoder);object$2({id:nonEmptyStringDecoder$2,type:subParentDecoder});const addWindowConfigDecoder=object$2({definition:swimlaneWindowDefinitionDecoder,parentId:nonEmptyStringDecoder$2,parentType:allParentDecoder}),addContainerConfigDecoder=object$2({definition:strictParentDefinitionDecoder,parentId:nonEmptyStringDecoder$2,parentType:allParentDecoder}),addItemResultDecoder=object$2({itemId:nonEmptyStringDecoder$2,windowId:optional$3(nonEmptyStringDecoder$2)});object$2({live:boolean$3()});const bundleWorkspaceConfigDecoder=object$2({type:oneOf$1(constant$2("row"),constant$2("column")),workspaceId:nonEmptyStringDecoder$2}),bundleItemConfigDecoder=object$2({type:oneOf$1(constant$2("row"),constant$2("column")),itemId:nonEmptyStringDecoder$2}),workspaceSelectorDecoder=object$2({workspaceId:nonEmptyStringDecoder$2}),containerSummaryResultDecoder=object$2({itemId:nonEmptyStringDecoder$2,config:parentSnapshotConfigDecoder});object$2({frameSummary:frameSummaryDecoder,frameBounds:optional$3(frameBoundsDecoder)}),object$2({workspaceSummary:workspaceSummaryResultDecoder,frameSummary:frameSummaryDecoder,frameBounds:optional$3(frameBoundsDecoder)}),object$2({containerSummary:containerSummaryResultDecoder}),object$2({windowSummary:object$2({itemId:nonEmptyStringDecoder$2,parentId:nonEmptyStringDecoder$2,config:swimlaneWindowSnapshotConfigDecoder})});const workspaceLayoutSaveConfigDecoder=object$2({name:nonEmptyStringDecoder$2,workspaceId:nonEmptyStringDecoder$2,saveContext:optional$3(boolean$3()),saveWindowContexts:optional$3(boolean$3())}),lockWorkspaceDecoder=object$2({workspaceId:nonEmptyStringDecoder$2,config:optional$3(object$2({allowDrop:optional$3(boolean$3()),allowDropLeft:optional$3(boolean$3()),allowDropTop:optional$3(boolean$3()),allowDropRight:optional$3(boolean$3()),allowDropBottom:optional$3(boolean$3()),allowExtract:optional$3(boolean$3()),allowWindowReorder:optional$3(boolean$3()),allowSystemHibernation:optional$3(boolean$3()),allowSplitters:optional$3(boolean$3()),showCloseButton:optional$3(boolean$3()),showSaveButton:optional$3(boolean$3()),allowWorkspaceTabReorder:optional$3(boolean$3()),showWindowCloseButtons:optional$3(boolean$3()),showEjectButtons:optional$3(boolean$3()),showAddWindowButtons:optional$3(boolean$3())}))}),lockWindowDecoder=object$2({windowPlacementId:nonEmptyStringDecoder$2,config:optional$3(object$2({allowExtract:optional$3(boolean$3()),allowReorder:optional$3(boolean$3()),showCloseButton:optional$3(boolean$3())}))}),lockRowDecoder=object$2({itemId:nonEmptyStringDecoder$2,type:constant$2("row"),config:optional$3(object$2({allowDrop:optional$3(boolean$3()),allowSplitters:optional$3(boolean$3())}))}),lockColumnDecoder=object$2({itemId:nonEmptyStringDecoder$2,type:constant$2("column"),config:optional$3(object$2({allowDrop:optional$3(boolean$3()),allowSplitters:optional$3(boolean$3())}))}),lockGroupDecoder=object$2({itemId:nonEmptyStringDecoder$2,type:constant$2("group"),config:optional$3(object$2({allowExtract:optional$3(boolean$3()),allowReorder:optional$3(boolean$3()),allowDrop:optional$3(boolean$3()),allowDropHeader:optional$3(boolean$3()),allowDropLeft:optional$3(boolean$3()),allowDropTop:optional$3(boolean$3()),allowDropRight:optional$3(boolean$3()),allowDropBottom:optional$3(boolean$3()),showMaximizeButton:optional$3(boolean$3()),showEjectButton:optional$3(boolean$3()),showAddWindowButton:optional$3(boolean$3())}))}),lockContainerDecoder=oneOf$1(lockColumnDecoder,lockGroupDecoder,lockRowDecoder),pinWorkspaceDecoder=object$2({workspaceId:nonEmptyStringDecoder$2,icon:optional$3(nonEmptyStringDecoder$2)}),setWorkspaceIconDecoder=object$2({workspaceId:nonEmptyStringDecoder$2,icon:optional$3(nonEmptyStringDecoder$2)}),workspaceIconDecoder=object$2({icon:optional$3(nonEmptyStringDecoder$2)});object$2({applicationName:optional$3(string$4()),frameConfig:optional$3(newFrameConfigDecoder),context:optional$3(object$2()),layoutComponentId:optional$3(nonEmptyStringDecoder$2)});const restoreWorkspaceDefinitionDecoder=object$2({name:nonEmptyStringDecoder$2,restoreOptions:optional$3(restoreWorkspaceConfigDecoder)});object$2({frameId:nonEmptyStringDecoder$2,workspaces:array$3(oneOf$1(workspaceDefinitionDecoder,restoreWorkspaceDefinitionDecoder))});const getWorkspaceWindowsOnLayoutSaveContextConfigDecoder=object$2({layoutType:oneOf$1(constant$2("Global"),constant$2("Workspace")),layoutName:nonEmptyStringDecoder$2,windowIds:array$3(nonEmptyStringDecoder$2),context:optional$3(anyJson$2()),instances:optional$3(array$3(nonEmptyStringDecoder$2)),ignoreInstances:optional$3(array$3(nonEmptyStringDecoder$2)),ignoreContexts:optional$3(boolean$3()),saveWindowContexts:optional$3(boolean$3())}),setMaximizationBoundaryConfigDecoder=object$2({itemId:nonEmptyStringDecoder$2,enabled:boolean$3()}),workspaceWindowOnSaveDataDecoder=object$2({windowId:nonEmptyStringDecoder$2,windowContext:optional$3(anyJson$2())}),getWorkspaceWindowsOnLayoutSaveContextResult=object$2({windowsOnSaveData:array$3(workspaceWindowOnSaveDataDecoder)}),getWorkspacesLayoutsConfigDecoder=object$2({frameId:nonEmptyStringDecoder$2,layoutName:nonEmptyStringDecoder$2,layoutType:oneOf$1(constant$2("Global"),constant$2("Workspace")),context:optional$3(anyJson$2()),ignoreContexts:optional$3(boolean$3()),saveWindowContexts:optional$3(boolean$3())}),getWorkspacesLayoutsResponseDecoder=object$2({workspaces:array$3(workspaceSnapshotResultDecoder)}),showChannelsLinkDecoder=object$2({windowId:nonEmptyStringDecoder$2,frameId:nonEmptyStringDecoder$2,channelsNames:array$3(nonEmptyStringDecoder$2)}),ZOOM_FACTORS=Object.freeze({0:24,1:33,2:50,3:67,4:75,5:80,6:90,7:100,8:110,9:125,10:150,11:175,12:200,13:250,14:300,15:400,16:500});class WindowsController{glueController;sessionController;stateController;ioc;started=!1;clientResponseTimeoutMs;defaultBounds;explicitClosingWindowIds={};connectionConfig;refreshLocks={};operations={openWindow:{name:"openWindow",execute:this.openWindow.bind(this),dataDecoder:openWindowConfigDecoder},windowHello:{name:"windowHello",execute:this.handleWindowHello.bind(this)},getBounds:{name:"getBounds",dataDecoder:simpleWindowDecoder,resultDecoder:windowBoundsResultDecoder,execute:this.handleGetBounds.bind(this)},getFrameBounds:{name:"getFrameBounds",dataDecoder:simpleWindowDecoder,resultDecoder:frameWindowBoundsResultDecoder,execute:this.handleGetBounds.bind(this)},getUrl:{name:"getUrl",dataDecoder:simpleWindowDecoder,resultDecoder:windowUrlResultDecoder,execute:this.handleGetUrl.bind(this)},moveResize:{name:"moveResize",dataDecoder:windowMoveResizeConfigDecoder,execute:this.handleMoveResize.bind(this)},focus:{name:"focus",dataDecoder:simpleWindowDecoder,execute:this.handleFocus.bind(this)},close:{name:"close",dataDecoder:simpleWindowDecoder,execute:this.handleClose.bind(this)},getTitle:{name:"getTitle",dataDecoder:simpleWindowDecoder,resultDecoder:windowTitleConfigDecoder,execute:this.handleGetTitle.bind(this)},setTitle:{name:"setTitle",dataDecoder:windowTitleConfigDecoder,execute:this.handleSetTitle.bind(this)},registerWorkspaceWindow:{name:"registerWorkspaceWindow",dataDecoder:workspaceWindowDataDecoder,execute:this.registerWorkspaceWindow.bind(this)},unregisterWorkspaceWindow:{name:"unregisterWorkspaceWindow",dataDecoder:simpleWindowDecoder,execute:this.handleWorkspaceClientRemoval.bind(this)},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)},focusChange:{name:"focusChange",dataDecoder:focusEventDataDecoder,execute:this.handleFocusEvent.bind(this)},getChannel:{name:"getChannel",dataDecoder:simpleWindowDecoder,resultDecoder:windowChannelResultDecoder,execute:this.handleGetChannel.bind(this)},setZoomFactor:{name:"setZoomFactor",dataDecoder:windowZoomFactorConfigDecoder,execute:this.handleSetZoomFactor.bind(this)},refresh:{name:"refresh",dataDecoder:simpleWindowDecoder,execute:this.handleRefresh.bind(this)}};constructor(e,t,r,n){this.glueController=e,this.sessionController=t,this.stateController=r,this.ioc=n}get logger(){return logger.get("windows.controller")}get moveResizeOperation(){return this.operations.moveResize}get getFrameBoundsOperation(){return this.operations.getFrameBounds}get setTitleOperation(){return this.operations.setTitle}get getBoundsOperation(){return this.operations.getBounds}handlePlatformShutdown(){this.started=!1}async start(e){this.clientResponseTimeoutMs=e.windows.windowResponseTimeoutMs,this.defaultBounds=e.windows.defaultWindowOpenBounds,this.started=!0,this.connectionConfig=e.connection,this.stateController.onWindowDisappeared(e=>this.cleanUpWindow(e).catch(t=>this.logger?.warn(`error while cleaning up window ${e}: ${t?.message}`)))}ready(){return Promise.resolve()}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this windows control message, because the controller has not been started");const t=e.data,r=e.commandId,n=windowOperationDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This window request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`Windows request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`Windows request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}async getWindowTitle(e,t){return(await this.handleGetTitle({windowId:e},t)).title}async getWindowBounds(e,t){return(await this.handleGetBounds({windowId:e},t)).bounds}async processNewWindow(e,t,r){this.logger?.trace(`processing a new window with id: ${e.windowId} and name: ${e.name}`),this.sessionController.saveWindowData(e),r&&this.stateController.add(r,e.windowId),t&&(this.logger?.trace(`setting the context for window ${e.windowId}`),await this.glueController.setStartContext(e.windowId,t,"window")),this.emitStreamData("windowAdded",e)}async handleWorkspaceClientRemoval(e){this.sessionController.removeEjectedWindowId(e.windowId),await this.cleanUpWindow(e.windowId),this.ioc.portsBridge.removeGwClient(e.windowId)}handleClientUnloaded(e,t){if(this.logger?.trace(`handling unloading of ${e}`),e&&!this.explicitClosingWindowIds[e]){if(!t||t.closed)return this.logger?.trace(`${e} detected as closed, processing window cleanup`),void this.cleanUpWindow(e).catch(t=>this.logger?.warn(`error while cleaning up window ${e}: ${t.message}`));this.logger?.trace(`${e} detected as not closed, adding to state controller`),this.stateController.add(t,e)}}setExplicitClosingWindowId(e){this.explicitClosingWindowIds[e]=!0}async cleanUpWindow(e){this.stateController.remove(e);if(this.sessionController.fullWindowClean(e)){try{await this.glueController.clearContext(e,"window")}catch(t){this.logger?.warn(`error while clearing the context of window ${e}: ${t?.message}`)}this.emitStreamData("windowRemoved",{windowId:e}),delete this.explicitClosingWindowIds[e],await this.waitEventFlush()}}async registerSelfAssignedWindow(e,t){this.logger?.trace(`[${t}] handling workspace window registration with id: ${e.windowId} and name: ${e.name}`),this.sessionController.saveWindowData({windowId:e.windowId,name:e.name,selfAssigned:!0}),this.sessionController.saveNonGlue({windowId:e.windowId}),this.emitStreamData("windowAdded",{windowId:e.windowId,name:e.name}),this.logger?.trace(`[${t}] workspace window registered successfully with id ${e.windowId} and name ${e.name}`)}async registerWorkspaceWindow(e,t){this.logger?.trace(`[${t}] handling workspace window registration with id: ${e.windowId} and name: ${e.name}`),this.sessionController.removeEjectedWindowId(e.windowId),e.channelId&&this.sessionController.addWindowChannel(e.windowId,e.channelId),this.sessionController.saveWindowData({windowId:e.windowId,name:e.name,initialChannelId:e.channelId}),this.sessionController.saveWorkspaceClient({windowId:e.windowId,frameId:e.frameId,initialTitle:e.title,workspaceId:e.workspaceId}),this.sessionController.saveNonGlue({windowId:e.windowId});const r=await this.glueController.pullHibernatedContext(e.windowId),n=e.context||r;n&&await this.glueController.setStartContext(e.windowId,n,"window"),this.emitStreamData("windowAdded",{windowId:e.windowId,name:e.name}),this.logger?.trace(`[${t}] workspace window registered successfully with id ${e.windowId} and name ${e.name}`)}async handleFocusEvent(e,t){this.logger?.trace(`[${t}] handling focus event from window id: ${e.windowId} and hasFocus: ${e.hasFocus}`),this.emitStreamData("focusChange",e),this.logger?.trace(`[${t}] focus event from window id: ${e.windowId} and hasFocus: ${e.hasFocus} handled`)}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}emitStreamData(e,t){this.logger?.trace(`sending notification of event: ${e} with data: ${JSON.stringify(t)}`),this.glueController.pushSystemMessage("windows",e,t)}async openWindow(e,t){if(this.sessionController.getWindowDataByName(e.name))return ioError.raiseError(`Cannot open a window with name: ${e.name}, because a window with that name already exists.`);if(checkIsOriginBlocked(e.url,this.connectionConfig.blockList))return ioError.raiseError(`Cannot open a window with url: ${e.url}, because its origin is blocked by the Platform`);this.logger?.trace(`[${t}] handling open command with a valid name: ${e.name}, url: ${e.url} and options: ${JSON.stringify(e.options)}`);const r=await this.getStartingBounds(e,t),n=e.options?.windowId??`g42-${nanoid$3(10)}`,i={name:e.name,windowId:n,initialBounds:r,initialUrl:e.url,initialContext:e.options?.context,layoutComponentId:e.options?.layoutComponentId},o=`left=${r.left},top=${r.top},width=${r.width},height=${r.height}`;this.logger?.trace(`[${t}] calling native window open with bounds: ${o}`);const s=window.open(e.url,i.windowId,o);return s?(await this.processNewWindow(i,e.options?.context,s),this.logger?.trace(`[${t}] the new window is opened, saved in session, state and announced, responding to the caller`),i):ioError.raiseError(`Cannot open window with url: ${e.url} and name: ${e.name}. The most likely reason is that the user has not approved popups or has a blocker.`)}async handleWindowHello(e,t){if(this.logger?.trace(`[${t}] handling a hello message from a real windowId: ${e.windowId}`),e.windowId){this.stateController.remove(e.windowId),this.sessionController.removeNonGlue({windowId:e.windowId});const r=this.sessionController.getWorkspaceClientById(e.windowId);if(r&&r.initialTitle){const n=e.windowId,i=r.initialTitle;PromiseWrap(()=>this.glueController.callWindow("windows",this.operations.setTitle,{windowId:n,title:i},{windowId:n}),this.clientResponseTimeoutMs).catch(e=>this.logger?.trace(`[${t}] error while setting the workspace window title: ${e.message}`))}}const r=!(!e.windowId||!this.sessionController.getFrameData(e.windowId)),n=this.sessionController.getAllWindowsData().map(e=>({windowId:e.windowId,name:e.name}));this.logger?.trace(`[${t}] a full list of all current windows has been compiled, sending it to the caller`);const i=e.windowId?this.refreshLocks[e.windowId]:void 0;return i&&e.windowId&&(i.open(),delete this.refreshLocks[e.windowId]),{windows:n,isWorkspaceFrame:r}}handleGetUrl(e,t){if(!this.sessionController.getWindowDataById(e.windowId))return ioError.raiseError(`Cannot get the url of window: ${e.windowId}, because it does not exist for the platform`);this.logger?.trace(`[${t}] handling a get url request for window ${e.windowId}`);const r=`Cannot get the url of window: ${e.windowId}, because it is either a non-glue window or it hasn't initiated it's glue yet`;return PromiseWrap(()=>this.glueController.callWindow("windows",this.operations.getUrl,e,{windowId:e.windowId}),this.clientResponseTimeoutMs,r)}handleGetTitle(e,t){if(!this.sessionController.getWindowDataById(e.windowId))return ioError.raiseError(`Cannot get the title of window: ${e.windowId}, because it does not exist for the platform`);this.logger?.trace(`[${t}] handling a get title request for window ${e.windowId}`);const r=`Cannot get the title of window: ${e.windowId}, because it is either a non-glue window or it hasn't initiated it's glue yet`;return PromiseWrap(()=>this.glueController.callWindow("windows",this.operations.getTitle,e,{windowId:e.windowId}),this.clientResponseTimeoutMs,r)}async handleSetTitle(e,t){if(!this.sessionController.getWindowDataById(e.windowId))return ioError.raiseError(`Cannot set the title of window: ${e.windowId}, because it does not exist for the platform`);this.sessionController.getWorkspaceClientById(e.windowId)&&await this.ioc.workspacesController.setItemTitle({itemId:e.windowId,title:e.title},t),this.logger?.trace(`[${t}] handling a set title request for window ${e.windowId} and title: ${e.title}`);const r=`Cannot set the title of window: ${e.windowId}, because it is either a non-glue window or it hasn't initiated it's glue yet`;await PromiseWrap(()=>this.glueController.callWindow("windows",this.operations.setTitle,e,{windowId:e.windowId}),this.clientResponseTimeoutMs,r)}async handleMoveResize(e,t){if(this.sessionController.getWorkspaceClientById(e.windowId))return ioError.raiseError(`Cannot move resize window id ${e.windowId}, because it is in a workspace. Consider using the workspaces API to get more control`);const r=this.sessionController.getWindowDataById(e.windowId);if(!r)return ioError.raiseError(`Cannot move resize window: ${e.windowId}, because it does not exist for the platform`);if("Platform"===r.name)return ioError.raiseError("Move-resizing the main application is not allowed");this.logger?.trace(`[${t}] handling a move resize request for window ${e.windowId} and data: ${JSON.stringify(e)}`);const n=`Cannot move resize window: ${e.windowId}, because it is either a non-glue window or it hasn't initiated it's glue yet`;await PromiseWrap(()=>this.glueController.callWindow("windows",this.operations.moveResize,e,{windowId:e.windowId}),this.clientResponseTimeoutMs,n),await this.pause(500)}handleGetBounds(e,t){if(this.sessionController.getWorkspaceClientById(e.windowId))return ioError.raiseError(`Cannot get bounds of window id ${e.windowId}, because it is in a workspace. Consider using the workspaces API to get more info`);if(!this.sessionController.getWindowDataById(e.windowId))return ioError.raiseError(`Cannot get the bounds of window: ${e.windowId}, because it does not exist for the platform`);this.logger?.trace(`[${t}] handling a get bounds request for window ${e.windowId}`);const r=`Cannot get the bounds of window: ${e.windowId}, because it is either a non-glue window or it hasn't initiated it's glue yet`;return PromiseWrap(()=>this.glueController.callWindow("windows",this.operations.getBounds,e,{windowId:e.windowId}),this.clientResponseTimeoutMs,r)}async handleFocus(e,t){if(this.sessionController.getWorkspaceClientById(e.windowId))return ioError.raiseError(`Cannot focus window id ${e.windowId}, because it is in a workspace. Consider using the workspaces API to get more control`);const r=this.sessionController.getWindowDataById(e.windowId);if(!r)return ioError.raiseError(`Cannot focus window: ${e.windowId}, because it is not known by the platform`);this.logger?.trace(`[${t}] handling a focus request for window ${e.windowId}`),window.open(void 0,r.windowId)}async handleClose(e,t){if(this.sessionController.getWorkspaceClientById(e.windowId))return this.logger?.trace(`[${t}] this window is detected as a workspace window, closing via the workspaces controller`),void await this.ioc.workspacesController.closeItem({itemId:e.windowId},t);if(this.sessionController.getInstanceData(e.windowId))return this.logger?.trace(`[${t}] this window is detected as an application instance, closing via the appManager controller`),void await this.ioc.applicationsController.handleInstanceStop({id:e.windowId},t);const r=this.sessionController.getWindowDataById(e.windowId);return r?"Platform"===r.name?ioError.raiseError("Closing the main application is not allowed"):r.selfAssigned?ioError.raiseError("Closing self-assigned windows (windows not opened by the Glue API) is not allowed"):(this.logger?.trace(`[${t}] handling a close request for window ${e.windowId}`),window.open(void 0,r.windowId)?.close(),await this.cleanUpWindow(r.windowId),void this.logger?.trace(`[${t}] window ${e.windowId} has been closed, removed from session, state and announced`)):ioError.raiseError(`Cannot close window: ${e.windowId}, because it is not known by the platform`)}async getStartingBounds(e,t){const r={top:e.options?.top??this.defaultBounds.top,left:e.options?.left??this.defaultBounds.left,height:e.options?.height??this.defaultBounds.height,width:e.options?.width??this.defaultBounds.width};if(!e.options?.relativeTo)return r;const n=e.options.relativeTo,i=this.sessionController.getWindowDataById(n);if(!i)return r;try{const n=(await this.handleGetBounds({windowId:i.windowId},t)).bounds,o=e.options.relativeDirection??"right";return getRelativeBounds(r,n,o)}catch(e){return r}}pause(e){return new Promise(t=>setTimeout(t,e))}handleGetChannel(e,t){this.logger?.trace(`[${t}] handling a get channel request for window ${e.windowId}`);if(!this.sessionController.getWindowDataById(e.windowId))return ioError.raiseError(`Cannot get the channel of window: ${e.windowId}, because it does not exist for the platform`);const r=`Cannot get the channel of window: ${e.windowId}, because it is either a non-glue window or it hasn't initiated it's glue yet`;return PromiseWrap(()=>this.glueController.callWindow("windows",this.operations.getChannel,e,{windowId:e.windowId}),this.clientResponseTimeoutMs,r)}async handleSetZoomFactor(e,t){this.logger?.trace(`[${t}] handling a set zoom factor request for window ${e.windowId} and factor: ${ZOOM_FACTORS[e.factorIndex]}`);if(!this.sessionController.getWindowDataById(e.windowId))return ioError.raiseError(`Cannot set the zoom factor of window: ${e.windowId}, because it does not exist for the platform`);const r=`Cannot set the zoom factor of window: ${e.windowId}, because it is either a non-glue window or it hasn't initiated it's glue yet`;await PromiseWrap(()=>this.glueController.callWindow("windows",this.operations.setZoomFactor,e,{windowId:e.windowId}),this.clientResponseTimeoutMs,r),this.emitStreamData("zoomFactorChange",e)}async handleRefresh(e,t){this.logger?.trace(`[${t}] handling a refresh request for window ${e.windowId}`);const r=this.sessionController.getWindowDataById(e.windowId);if(!r)return ioError.raiseError(`Cannot refresh window: ${e.windowId}, because it does not exist for the platform`);if("Platform"===r.name)return ioError.raiseError("Refreshing the main application is not allowed");const n=`Cannot refresh window: ${e.windowId}, because it is either a non-glue window or it hasn't initiated it's glue yet`,{isSupported:i}=await this.glueController.checkClientOperationSupport("windows",this.operations.refresh,{instance:e.windowId});if(!i)return ioError.raiseError(`[${t}] Cannot handle refresh request, because the target instance does not support the operation`);await PromiseWrap(()=>this.glueController.callWindow("windows",this.operations.refresh,e,{windowId:e.windowId}),this.clientResponseTimeoutMs,n);const o=this.createRefreshLock();this.refreshLocks[e.windowId]=o,await o.lock}createRefreshLock(){let e;const t=PromisePlus(t=>{e=t},3e3,"The refresh lock was not opened in time, this is most likely a bug in the platform");if(!e)throw new Error("The open function for the refresh lock was not initialized properly");return{open:e,lock:t}}waitEventFlush(){return new Promise(e=>setTimeout(e,10))}}class SessionStorageController{cache={};sessionStorage;windowsNamespace="g42_core_windows";instancesNamespace="g42_core_instances";bridgeInstancesNamespace="g42_core_bridge";nonGlueNamespace="g42_core_nonglue";workspaceWindowsNamespace="g42_core_workspace_clients";workspaceFramesNamespace="g42_core_workspace_frames";workspaceHibernationNamespace="g42_core_workspace_hibernation";globalLayoutsNamespace="g42_core_layouts_global";workspaceLayoutsNamespace="g42_core_layouts_workspace";appDefsNamespace="g42_core_app_definitions";appDefsInmemoryNamespace="g42_core_app_definitions_inmemory";notificationsNamespace="g42_core_notifications";prefsRestSchedulerNamespace="g42_core_prefs_rest_scheduler";layoutsSystemNamespace="g42_core_layouts_system";systemNamespace="g42_system";workspaceFrameCache="g42_workspace_frame_cache";channelsNamespace="g42_core_channels";ejectedWindowIdsNamespace="g42_core_ejected_windows";allNamespaces=[this.bridgeInstancesNamespace,this.windowsNamespace,this.instancesNamespace,this.nonGlueNamespace,this.workspaceWindowsNamespace,this.workspaceFramesNamespace,this.globalLayoutsNamespace,this.workspaceLayoutsNamespace,this.appDefsNamespace,this.workspaceHibernationNamespace,this.appDefsInmemoryNamespace,this.notificationsNamespace,this.prefsRestSchedulerNamespace,this.workspaceFrameCache,this.channelsNamespace,this.ejectedWindowIdsNamespace];get logger(){return logger.get("session.storage")}start(){this.sessionStorage=window.sessionStorage,this.allNamespaces.forEach(e=>{this.getItem(e)||this.setItem(e,JSON.stringify([]))})}shutdown(){this.allNamespaces.forEach(e=>{this.setItem(e,JSON.stringify([]))}),this.removeItem(this.systemNamespace),this.removeItem(this.layoutsSystemNamespace)}getSystemSettings(){const e=this.getItem(this.systemNamespace);if(e)return JSON.parse(e)}setSystemSettings(e){this.setItem(this.systemNamespace,JSON.stringify(e))}getLayoutsSystemData(){const e=this.getItem(this.layoutsSystemNamespace);return e?JSON.parse(e):{}}setLayoutsSystemData(e){this.setItem(this.layoutsSystemNamespace,JSON.stringify(e))}getTimeout(e){const t=this.getNamespaceData(this.workspaceHibernationNamespace);return t.find(t=>t.workspaceId===e)?.timeout}removeTimeout(e){const t=this.getNamespaceData(this.workspaceHibernationNamespace);t.find(t=>t.workspaceId===e)&&this.setItem(this.workspaceHibernationNamespace,JSON.stringify(t.filter(t=>t.workspaceId!==e)))}saveTimeout(e,t){const r=this.getNamespaceData(this.workspaceHibernationNamespace);r.some(t=>t.workspaceId===e)||(r.push({workspaceId:e,timeout:t}),this.setItem(this.workspaceHibernationNamespace,JSON.stringify(r)))}exportClearTimeouts(){const e=this.getNamespaceData(this.workspaceHibernationNamespace);return this.setItem(this.workspaceHibernationNamespace,JSON.stringify([])),e}getAllApps(e){const t="remote"===e?this.appDefsNamespace:this.appDefsInmemoryNamespace;return this.getNamespaceData(t)}overwriteApps(e,t){const r="remote"===t?this.appDefsNamespace:this.appDefsInmemoryNamespace;this.setItem(r,JSON.stringify(e))}removeApp(e,t){const r="remote"===t?this.appDefsNamespace:this.appDefsInmemoryNamespace,n=this.getAllApps(t),i=n.find(t=>t.name===e);return i&&this.setItem(r,JSON.stringify(n.filter(t=>t.name!==e))),i}getLayoutSnapshot(e){const t="Global"===e?this.globalLayoutsNamespace:this.workspaceLayoutsNamespace;return{layouts:this.getNamespaceData(t)}}saveLayoutSnapshot(e,t){const r="Global"===t?this.globalLayoutsNamespace:this.workspaceLayoutsNamespace;this.setItem(r,JSON.stringify(e.layouts))}saveFrameData(e){const t=this.getNamespaceData(this.workspaceFramesNamespace);t.some(t=>t.windowId===e.windowId)||(t.push(e),this.setItem(this.workspaceFramesNamespace,JSON.stringify(t)))}getPlatformFrame(){return this.getAllFrames().find(e=>e.isPlatform)}getAllFrames(){return this.getNamespaceData(this.workspaceFramesNamespace)}getFrameData(e){return this.getAllFrames().find(t=>t.windowId===e)}setFrameActive(e){const t=this.getAllFrames(),r=t.find(t=>t.windowId===e);r&&!r.active&&(r.active=!0,this.setItem(this.workspaceFramesNamespace,JSON.stringify(t)))}removeFrameData(e){return!!e&&this.doRemove(e,this.workspaceFramesNamespace)}saveWorkspaceClient(e){const t=this.getNamespaceData(this.workspaceWindowsNamespace);t.some(t=>t.windowId===e.windowId)||(t.push(e),this.setItem(this.workspaceWindowsNamespace,JSON.stringify(t)))}getWorkspaceClientById(e){return this.getNamespaceData(this.workspaceWindowsNamespace).find(t=>t.windowId===e)}pickWorkspaceClients(e){return this.getNamespaceData(this.workspaceWindowsNamespace).filter(e)}removeWorkspaceClient(e){return!!e&&this.doRemove(e,this.workspaceWindowsNamespace)}getAllNonGlue(){return this.getNamespaceData(this.nonGlueNamespace)}saveNonGlue(e){const t=this.getNamespaceData(this.nonGlueNamespace);return t.some(t=>t.windowId===e.windowId)?(this.logger?.trace(`did not save this data: ${JSON.stringify(e)}, because an entry with this id already exists`),!1):(this.logger?.trace(`saving non glue window with id: ${e.windowId}`),t.push(e),this.setItem(this.nonGlueNamespace,JSON.stringify(t)),!0)}removeNonGlue(e){return!(!e||!e.windowId)&&(this.logger?.trace(`removing non glue window with id: ${e.windowId}`),this.doRemove(e.windowId,this.nonGlueNamespace))}saveBridgeInstanceData(e){const t=this.getNamespaceData(this.bridgeInstancesNamespace);t.some(t=>t.windowId===e.windowId)?this.logger?.trace(`did not save this data: ${JSON.stringify(e)}, because an entry with this id already exists`):(this.logger?.trace(`saving new instance with id: ${e.windowId} and app name: ${e.appName}`),t.push(e),this.setItem(this.bridgeInstancesNamespace,JSON.stringify(t)))}getBridgeInstanceData(e){return this.getNamespaceData(this.bridgeInstancesNamespace).find(t=>t.windowId===e)}removeBridgeInstanceData(e){const t=this.getNamespaceData(this.bridgeInstancesNamespace);this.setItem(this.bridgeInstancesNamespace,JSON.stringify(t.filter(t=>t.windowId!==e)))}saveInstanceData(e){const t=this.getNamespaceData(this.instancesNamespace);t.some(t=>t.id===e.id)?this.logger?.trace(`did not save this data: ${JSON.stringify(e)}, because an entry with this id already exists`):(this.logger?.trace(`saving new instance with id: ${e.id} and app name: ${e.applicationName}`),t.push(e),this.setItem(this.instancesNamespace,JSON.stringify(t)))}removeInstance(e){this.logger?.trace(`removing instance with id: ${e}`);const t=this.getAllInstancesData();this.setItem(this.instancesNamespace,JSON.stringify(t.filter(t=>t.id!==e))),this.removeBridgeInstanceData(e)}getInstanceData(e){return this.getAllInstancesData().find(t=>t.id===e)}getAllInstancesData(){return this.getNamespaceData(this.instancesNamespace)}removeNotification(e){const t=this.getNamespaceData(this.notificationsNamespace);t.find(t=>t.id===e)&&this.setItem(this.notificationsNamespace,JSON.stringify(t.filter(t=>t.id!==e)))}saveNewNotification(e){const t=this.getAllNotifications();if(t.some(t=>t.id===e.id))return ioError.raiseError(`Notification with id ${e.id} already exists`);this.logger?.trace(`saving notification with id: ${e.id}`),t.push(e),this.setItem(this.notificationsNamespace,JSON.stringify(t))}updateNotification(e){const t=this.getAllNotifications(),r=t.findIndex(t=>t.id===e.id);if(-1===r)return ioError.raiseError(`Notification with id ${e.id} does not exist`);this.logger?.trace(`updating notification with id: ${e.id}`),t[r]=e,this.setItem(this.notificationsNamespace,JSON.stringify(t))}getNotification(e){return this.getAllNotifications().find(t=>t.id===e)}getAllNotifications(){return this.getNamespaceData(this.notificationsNamespace)}savePrefsRestSchedulerCache(e){const t=this.getAllPrefsRestSchedulerCache();t.some(t=>t.app===e.app)?this.logger?.trace(`did not save this data: ${JSON.stringify(e)}, because an entry with this app already exists`):(this.logger?.trace(`saving prefs rest scheduler cache for app: ${e.app}`),t.push(e),this.setItem(this.prefsRestSchedulerNamespace,JSON.stringify(t)))}getAllPrefsRestSchedulerCache(){return this.getNamespaceData(this.prefsRestSchedulerNamespace)}clearAllPrefsRestSchedulerCache(){this.setItem(this.prefsRestSchedulerNamespace,JSON.stringify([]))}saveWindowData(e){const t=this.getAllWindowsData();t.some(t=>t.name===e.name)?this.logger?.trace(`did not save this data: ${JSON.stringify(e)}, because an entry with this name already exists`):(this.logger?.trace(`saving window with id: ${e.windowId} and name: ${e.name}`),t.push(e),this.setItem(this.windowsNamespace,JSON.stringify(t)))}getAllWindowsData(){return this.getNamespaceData(this.windowsNamespace)}getWindowDataById(e){return this.getAllWindowsData().find(t=>t.windowId===e)}getWindowDataByName(e){return this.getAllWindowsData().find(t=>t.name===e)}removeWindowData(e){return!!e&&(this.logger?.trace(`removing window with id: ${e}`),this.doRemove(e,this.windowsNamespace))}fullWindowClean(e){const t=this.removeWindowData(e),r=this.removeNonGlue({windowId:e}),n=this.removeWorkspaceClient(e);return t||r||n}addWindowChannel(e,t){const r=this.getNamespaceData(this.channelsNamespace),n=r.findIndex(t=>t.windowId===e);if(-1===n)return this.logger?.trace(`no channel data found for window with id: ${e}, creating new entry`),r.push({windowId:e,channels:[t]}),this.setItem(this.channelsNamespace,JSON.stringify(r));this.logger?.trace(`adding channel data for window with id: ${e}`),r[n].channels=Array.from(new Set([...r[n].channels||[],t])),this.setItem(this.channelsNamespace,JSON.stringify(r))}setChannelsForWindow(e,t){const r=this.getNamespaceData(this.channelsNamespace),n=r.findIndex(t=>t.windowId===e);if(-1===n)return this.logger?.trace(`no channel data found for window with id: ${e}, creating new entry`),r.push({windowId:e,channels:t}),this.setItem(this.channelsNamespace,JSON.stringify(r));this.logger?.trace(`adding channels data for window with id: ${e}`),r[n].channels=Array.from(new Set(t)),this.setItem(this.channelsNamespace,JSON.stringify(r))}setAdditionalChannelForWindow(e,t){const r=this.getNamespaceData(this.channelsNamespace),n=r.findIndex(t=>t.windowId===e);if(-1===n)return this.logger?.trace(`no channel data found for window with id: ${e}, creating new entry`),r.push({windowId:e,channels:[t]}),this.setItem(this.channelsNamespace,JSON.stringify(r));this.logger?.trace(`add additional channel data for window with id: ${e}`),r[n].channels=Array.from(new Set([...r[n].channels??[],t])),this.setItem(this.channelsNamespace,JSON.stringify(r))}addChannelRestrictionsByWindowId(e,t){const r=this.getNamespaceData(this.channelsNamespace),n=r.findIndex(t=>t.windowId===e);if(-1===n)return this.logger?.trace(`no channel data found for window with id: ${e}, creating new entry with restrictions`),r.push({windowId:e,restrictions:[t]}),this.setItem(this.channelsNamespace,JSON.stringify(r));this.logger?.trace(`channel data found for window with id: ${e}, updating restrictions`);const i=r[n].restrictions?.some(e=>e.name===t.name);r[n].restrictions=i?[t]:[...r[n].restrictions||[],t],this.setItem(this.channelsNamespace,JSON.stringify(r))}addAllChannelsRestrictionsByWindowId(e,t){const r=this.getNamespaceData(this.channelsNamespace),n=r.findIndex(t=>t.windowId===e);if(-1===n)return this.logger?.trace(`no channel data found for window with id: ${e}, creating new entry with restrictions`),r.push({windowId:e,restrictions:t}),this.setItem(this.channelsNamespace,JSON.stringify(r));this.logger?.trace(`channel data found for window with id: ${e}, updating restrictions`),r[n].restrictions=t,this.setItem(this.channelsNamespace,JSON.stringify(r))}addEjectedWindowId(e){const t=this.getNamespaceData(this.ejectedWindowIdsNamespace),r=Array.from(new Set([...t,e]));this.setItem(this.ejectedWindowIdsNamespace,JSON.stringify(r))}removeEjectedWindowId(e){const t=this.getNamespaceData(this.ejectedWindowIdsNamespace).filter(t=>t!==e);this.setItem(this.ejectedWindowIdsNamespace,JSON.stringify(t))}getEjectedWindowIds(){return this.getNamespaceData(this.ejectedWindowIdsNamespace)}getWindowChannelData(e){return this.getNamespaceData(this.channelsNamespace).find(t=>t.windowId===e)}getAllWindowsChannelData(){return this.getNamespaceData(this.channelsNamespace)}removeWindowChannelData(e){return!!e&&this.doRemove(e,this.channelsNamespace)}handlePlatformUnloadCleanup(){const e=this.getNamespaceData(this.workspaceWindowsNamespace);if(!e.length)return;this.getAllWindowsData().forEach(t=>{const r=e.find(e=>e.windowId===t.windowId);if(!r)return;const n=this.getFrameData(r.frameId);n?.isPlatform&&(this.fullWindowClean(t.windowId),this.removeWindowChannelData(t.windowId),this.removeInstance(t.windowId))})}doRemove(e,t){const r=this.getNamespaceData(t).reduce((t,r)=>(r.windowId===e?t.removed=!0:t.newData.push(r),t),{removed:!1,newData:[]});return this.setItem(t,JSON.stringify(r.newData)),r.removed}getNamespaceData(e){const t=this.getItem(e);return t?JSON.parse(t):[]}getItem(e){const t=this.sessionStorage.getItem(e);return t?(this.cache[e]=t,t):(this.doFullRecovery(),this.cache[e])}setItem(e,t){this.cache[e]=t,this.sessionStorage.setItem(e,t)}removeItem(e){delete this.cache[e],this.sessionStorage.removeItem(e)}doFullRecovery(){this.logger?.warn("Session storage is empty or corrupted, performing full recovery from in-memory cache");this.allNamespaces.filter(e=>e!==this.systemNamespace&&e!==this.layoutsSystemNamespace).forEach(e=>{const t=this.cache[e]??JSON.stringify([]);this.setItem(e,t)}),this.setItem(this.systemNamespace,this.cache[this.systemNamespace]??JSON.stringify({})),this.setItem(this.layoutsSystemNamespace,this.cache[this.layoutsSystemNamespace]??JSON.stringify({})),this.logger?.info("Full recovery completed, session storage is now restored from in-memory cache")}}class WindowsStateController{sessionStorage;registry=CallbackRegistryFactory$2();checkIntervalMs=500;childrenToCheck=[];checkerCancelled=!1;currentTimeout;constructor(e){this.sessionStorage=e}get logger(){return logger.get("state.controller")}start(){this.checkerCancelled=!1;const e=this.sessionStorage.getAllNonGlue(),t=this.sessionStorage.pickWorkspaceClients(()=>!0);this.logger?.debug(`starting state controller with ${e.length} non-glue windows and ${t.length} workspace clients from previous session`);e.filter(e=>t.every(t=>t.windowId!==e.windowId)).forEach(e=>{this.logger?.trace(`detected non glue window with id ${e.windowId} from previous session, attempting reference refresh`);const t=window.open(void 0,e.windowId);t&&this.childrenToCheck.push({window:t,windowId:e.windowId})}),this.checkWindows(),this.logger?.debug(`state controller startup completed with ${this.childrenToCheck.length} windows to monitor`)}add(e,t){this.logger?.trace(`adding window id: ${t} to non glue state checking`);this.sessionStorage.saveNonGlue({windowId:t})&&this.childrenToCheck.push({window:e,windowId:t})}getAll(){return this.logger?.trace("getting all non glue windows"),this.childrenToCheck}remove(e){this.logger?.trace(`removing window id: ${e} from non glue state checking`),this.sessionStorage.removeNonGlue({windowId:e}),this.childrenToCheck=this.childrenToCheck.filter(t=>t.windowId!==e)}cancel(){this.logger?.debug("cancelling state controller"),this.currentTimeout&&clearTimeout(this.currentTimeout),this.checkerCancelled=!0,this.registry.clear()}onWindowDisappeared(e){return this.registry.add("window-disappear",e)}checkWindows(){this.checkerCancelled||(this.childrenToCheck.forEach(e=>{if(!e.window||e.window.closed)return this.logger?.trace(`non glue window ${e.windowId} has disappeared, removing from collections and announcing.`),this.remove(e.windowId),void this.registry.execute("window-disappear",e.windowId)}),this.currentTimeout=setTimeout(this.checkWindows.bind(this),this.checkIntervalMs))}}const intentsOperationTypesDecoder=oneOf$1(constant$2("findIntent"),constant$2("getIntents"),constant$2("raise"),constant$2("operationCheck"),constant$2("filterHandlers"),constant$2("getIntentsByHandler")),intentHandlerDecoder=object$2({applicationName:nonEmptyStringDecoder$2,applicationTitle:optional$3(string$4()),applicationDescription:optional$3(string$4()),applicationIcon:optional$3(string$4()),type:oneOf$1(constant$2("app"),constant$2("instance")),displayName:optional$3(string$4()),contextTypes:optional$3(array$3(nonEmptyStringDecoder$2)),instanceId:optional$3(string$4()),instanceTitle:optional$3(string$4()),resultType:optional$3(nonEmptyStringDecoder$2),customConfig:optional$3(object$2())}),intentDecoder=object$2({name:nonEmptyStringDecoder$2,handlers:array$3(intentHandlerDecoder)}),intentTargetDecoder=oneOf$1(constant$2("startNew"),constant$2("reuse"),object$2({app:optional$3(nonEmptyStringDecoder$2),instance:optional$3(nonEmptyStringDecoder$2)})),intentContextDecoder=object$2({type:optional$3(nonEmptyStringDecoder$2),data:optional$3(object$2())}),intentsDecoder=array$3(intentDecoder),wrappedIntentsDecoder=object$2({intents:intentsDecoder}),wrappedIntentFilterDecoder=object$2({filter:optional$3(object$2({name:optional$3(nonEmptyStringDecoder$2),contextType:optional$3(nonEmptyStringDecoder$2),resultType:optional$3(nonEmptyStringDecoder$2)}))});object$2({applicationName:nonEmptyStringDecoder$2,applicationIcon:optional$3(string$4()),instanceId:optional$3(string$4())});const applicationStartOptionsDecoder=object$2({top:optional$3(number$4()),left:optional$3(number$4()),width:optional$3(nonNegativeNumberDecoder$2),height:optional$3(nonNegativeNumberDecoder$2),relativeTo:optional$3(nonEmptyStringDecoder$2),relativeDirection:optional$3(windowRelativeDirectionDecoder),waitForAGMReady:optional$3(boolean$3()),channelId:optional$3(nonEmptyStringDecoder$2)}),intentRequestDecoder=object$2({intent:nonEmptyStringDecoder$2,target:optional$3(intentTargetDecoder),context:optional$3(intentContextDecoder),options:optional$3(applicationStartOptionsDecoder),handlers:optional$3(array$3(intentHandlerDecoder)),timeout:optional$3(nonNegativeNumberDecoder$2),waitUserResponseIndefinitely:optional$3(boolean$3()),clearSavedHandler:optional$3(boolean$3())}),resolverConfigDecoder=object$2({enabled:optional$3(boolean$3()),appName:string$4(),waitResponseTimeout:number$4()}),intentResultDecoder=object$2({request:intentRequestDecoder,handler:intentHandlerDecoder,result:anyJson$2()}),resolverResponseDecoder=object$2({intent:nonEmptyStringDecoder$2,handler:intentHandlerDecoder,correlationId:optional$3(string$4()),userSettings:object$2({preserveChoice:optional$3(boolean$3())})}),handlerExclusionCriteriaApplicationNameDecoder=object$2({applicationName:nonEmptyStringDecoder$2}),handlerExclusionCriteriaInstanceIdDecoder=object$2({instanceId:nonEmptyStringDecoder$2}),handlerExclusionCriteriaDecoder=oneOf$1(handlerExclusionCriteriaApplicationNameDecoder,handlerExclusionCriteriaInstanceIdDecoder),handlerFilterDecoder=object$2({title:optional$3(nonEmptyStringDecoder$2),openResolver:optional$3(boolean$3()),timeout:optional$3(nonNegativeNumberDecoder$2),intent:optional$3(nonEmptyStringDecoder$2),contextTypes:optional$3(array$3(nonEmptyStringDecoder$2)),resultType:optional$3(nonEmptyStringDecoder$2),applicationNames:optional$3(array$3(nonEmptyStringDecoder$2)),excludeList:optional$3(array$3(handlerExclusionCriteriaDecoder))}),filterHandlersResultDecoder=object$2({handlers:array$3(intentHandlerDecoder)}),embeddedResolverConfigDecoder=object$2({enabled:boolean$3(),initialCaller:object$2({instanceId:nonEmptyStringDecoder$2})}),filterHandlersWithResolverConfigDecoder=object$2({filterHandlersRequest:handlerFilterDecoder,resolverConfig:resolverConfigDecoder,embeddedResolverConfig:optional$3(embeddedResolverConfigDecoder)}),intentInfoDecoder=object$2({intent:nonEmptyStringDecoder$2,contextTypes:optional$3(array$3(nonEmptyStringDecoder$2)),description:optional$3(nonEmptyStringDecoder$2),displayName:optional$3(nonEmptyStringDecoder$2),icon:optional$3(nonEmptyStringDecoder$2),resultType:optional$3(nonEmptyStringDecoder$2)}),getIntentsResultDecoder=object$2({intents:array$3(intentInfoDecoder)}),raiseIntentRequestDecoder=object$2({intentRequest:intentRequestDecoder,resolverConfig:resolverConfigDecoder,embeddedResolverConfig:optional$3(embeddedResolverConfigDecoder)}),appManagerOperationTypesDecoder=oneOf$1(constant$2("appHello"),constant$2("applicationStart"),constant$2("instanceStop"),constant$2("registerWorkspaceApp"),constant$2("unregisterWorkspaceApp"),constant$2("export"),constant$2("import"),constant$2("remove"),constant$2("clear"),constant$2("registerRemoteApps"),constant$2("operationCheck")),basicInstanceDataDecoder=object$2({id:nonEmptyStringDecoder$2}),instanceDataDecoder=object$2({id:nonEmptyStringDecoder$2,applicationName:nonEmptyStringDecoder$2}),applicationDataDecoder=object$2({name:nonEmptyStringDecoder$2,type:nonEmptyStringDecoder$2.where(e=>"window"===e,"Expected a value of window"),createOptions:applicationDetailsDecoder,instances:array$3(instanceDataDecoder),userProperties:optional$3(anyJson$2()),title:optional$3(nonEmptyStringDecoder$2),version:optional$3(nonEmptyStringDecoder$2),icon:optional$3(string$4()),caption:optional$3(nonEmptyStringDecoder$2),fdc3:optional$3(anyJson$2())}),appHelloSuccessDecoder$1=object$2({apps:array$3(applicationDataDecoder),initialChannelId:optional$3(nonEmptyStringDecoder$2)}),appHelloDecoder=object$2({windowId:optional$3(nonEmptyStringDecoder$2)}),originAppDecoder=object$2({interopInstance:nonEmptyStringDecoder$2,name:optional$3(nonEmptyStringDecoder$2)}),startReasonDecoder=object$2({originApp:originAppDecoder,intentRequest:optional$3(intentRequestDecoder)}),applicationStartConfigDecoder=object$2({name:nonEmptyStringDecoder$2,id:optional$3(nonEmptyStringDecoder$2),context:optional$3(anyJson$2()),top:optional$3(number$4()),left:optional$3(number$4()),width:optional$3(nonNegativeNumberDecoder$2),height:optional$3(nonNegativeNumberDecoder$2),relativeTo:optional$3(nonEmptyStringDecoder$2),relativeDirection:optional$3(oneOf$1(constant$2("top"),constant$2("left"),constant$2("right"),constant$2("bottom"))),waitForAGMReady:optional$3(boolean$3()),forceChromeTab:optional$3(boolean$3()),layoutComponentId:optional$3(nonEmptyStringDecoder$2),channelId:optional$3(nonEmptyStringDecoder$2),startReason:optional$3(startReasonDecoder)}),appsImportOperationDecoder=object$2({definitions:array$3(allApplicationDefinitionsDecoder),mode:oneOf$1(constant$2("replace"),constant$2("merge"))}),appRemoveConfigDecoder=object$2({name:nonEmptyStringDecoder$2}),appsExportOperationDecoder=object$2({definitions:array$3(glueCoreAppDefinitionDecoder)}),appsRemoteRegistrationDecoder=object$2({definitions:array$3(allApplicationDefinitionsDecoder)});class ApplicationsController{glueController;sessionStorage;stateController;appDirectory;managerController;ioc;registry=CallbackRegistryFactory$2();config;connectionConfig;applicationStartTimeoutMs=15e3;managerAppsCheckCount=0;started=!1;defaultBounds;explicitClosingInstanceIds={};isManagerConfigured;locks={};operations={appHello:{name:"appHello",dataDecoder:appHelloDecoder,resultDecoder:appHelloSuccessDecoder$1,execute:this.handleAppHello.bind(this)},applicationStart:{name:"applicationStart",dataDecoder:applicationStartConfigDecoder,resultDecoder:instanceDataDecoder,execute:this.handleApplicationStart.bind(this)},instanceStop:{name:"instanceStop",dataDecoder:basicInstanceDataDecoder,execute:this.handleInstanceStop.bind(this)},registerWorkspaceApp:{name:"registerWorkspaceApp",dataDecoder:workspaceWindowDataDecoder,execute:this.registerWorkspaceApp.bind(this)},unregisterWorkspaceApp:{name:"unregisterWorkspaceApp",dataDecoder:simpleWindowDecoder,execute:this.unregisterWorkspaceApp.bind(this)},import:{name:"import",dataDecoder:appsImportOperationDecoder,execute:this.handleImport.bind(this)},remove:{name:"remove",dataDecoder:appRemoveConfigDecoder,execute:this.handleRemove.bind(this)},export:{name:"export",resultDecoder:appsExportOperationDecoder,execute:this.handleExport.bind(this)},clear:{name:"clear",execute:this.handleClear.bind(this)},registerRemoteApps:{name:"registerRemoteApps",dataDecoder:appsRemoteRegistrationDecoder,execute:this.handleRegisterRemoteApps.bind(this)},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)}};constructor(e,t,r,n,i,o){this.glueController=e,this.sessionStorage=t,this.stateController=r,this.appDirectory=n,this.managerController=i,this.ioc=o}get logger(){return logger.get("applications.controller")}handlePlatformShutdown(){this.managerAppsCheckCount=0,this.locks={},this.started=!1,this.appDirectory.stop()}async start(e){this.defaultBounds=e.windows.defaultWindowOpenBounds,this.logger?.trace("initializing applications"),this.config=e.applications,this.connectionConfig=e.connection,this.isManagerConfigured=!!e.manager?.url,await this.appDirectory.start({config:e.applications,appsStateChange:e=>this.emitStreamData("appDirectoryStateChange",e),sequelizer:this.ioc.createSequelizer(),isManagerConfigured:this.isManagerConfigured}),this.started=!0,this.stateController.onWindowDisappeared(e=>this.processInstanceClosed(e).catch(e=>this.logger?.warn(`error while processing instance closed: ${e?.message}`))),this.logger?.trace("initialization is completed")}async ready(){if(!this.isManagerConfigured)return;const e=this.managerController.getAllApps();await this.confirmApps(e)}async confirmApps(e){const t=this.glueController.clientGlue,r=e.every(e=>{const r=e.appId??e.name;return!!t.appManager.application(r)});return++this.managerAppsCheckCount,r?this.logger?.trace("all manager applications are loaded, proceeding"):this.managerAppsCheckCount>10?ioError.raiseError("not all manager applications are loaded after 10 checks, stopping the process"):(this.logger?.trace("not all manager applications are loaded, waiting for them to be loaded"),await wait(500),this.confirmApps(e))}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this windows control message, because the controller has not been started");const t=e.data,r=e.commandId,n=appManagerOperationTypesDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This appManager request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`AppManager request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`AppManager request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}handleClientUnloaded(e,t){if(this.logger?.trace(`handling unloading of ${e}`),e&&!this.explicitClosingInstanceIds[e])return!t||t.closed?(this.logger?.trace(`${e} detected as closed, processing instance closed`),void this.processInstanceClosed(e).catch(e=>this.logger?.warn(`error while processing instance closed: ${e.message}`))):void this.logger?.trace(`${e} detected as not closed, skipping instance closed procedure`)}async unregisterWorkspaceApp(e){this.sessionStorage.removeEjectedWindowId(e.windowId),this.ioc.windowsController.setExplicitClosingWindowId(e.windowId),this.explicitClosingInstanceIds[e.windowId]=!0,await this.processInstanceClosed(e.windowId),await this.ioc.windowsController.cleanUpWindow(e.windowId),this.ioc.portsBridge.removeGwClient(e.windowId)}async handleApplicationStart(e,t){this.logger?.trace(`[${t}] handling application start command for application: ${e.name}`);const r=new Date,n=(await this.appDirectory.getAll()).find(t=>t.name===e.name);if(!n)return ioError.raiseError(`Cannot start an instance of application: ${e.name}, because it is not found.`);if(checkIsOriginBlocked(n.createOptions.url,this.connectionConfig.blockList))return ioError.raiseError(`Cannot start an instance of application: ${e.name}, because its origin is blocked by the Platform`);const i={id:e.id??`g42-${nanoid$3(10)}`,applicationName:e.name},o=await this.getStartingBounds(n.createOptions,e,t),s=e.forceChromeTab?void 0:`left=${o.left},top=${o.top},width=${o.width},height=${o.height}`;this.logger?.trace(`[${t}] open arguments are valid, opening to bounds: ${s}`);const a=window.open(n.createOptions.url,i.id,s);if(!a)return ioError.raiseError(`Cannot start an instance with url: ${n.createOptions.url} for application: ${e.name}. The most likely reason is that the user has not approved popups or has a blocker.`);this.sessionStorage.saveBridgeInstanceData({windowId:i.id,appName:i.applicationName});const c={data:i,context:e.context};if(await this.processNewInstance(c),this.logger?.trace(`[${t}] the new window has been opened successfully with id: ${i.id}, checking for AGM ready and notifying windows`),e.waitForAGMReady&&(this.logger?.trace(`[${t}] wait for AGM is set, configuring the lock`),this.setLock(i.id)),await this.notifyWindows(n.createOptions.url,i,o,a,e.context,e.layoutComponentId,e.channelId),e.channelId&&this.sessionStorage.addWindowChannel(i.id,e.channelId),this.locks[i.id])try{await PromiseWrap(()=>this.locks[i.id]?.keyOne,this.applicationStartTimeoutMs)}catch(t){return delete this.locks[i.id],ioError.raiseError(`Application start for ${e.name} timed out waiting for client to initialize Glue`)}this.logger?.trace(`[${t}] the windows controller has been successfully notified`),this.logger?.trace(`[${t}] the new instance with id ${i.id} has been saved, announced and context set, lifting key two and responding to caller`),this.locks[i.id]?.openKeyTwo();const l=this.glueController.getLocalServers().find(({instance:e})=>i.id===e),u={start:r,end:new Date};return this.registry.execute("instance-started",{id:i.id,api:l?.api,applicationName:i.applicationName,startup:u}),i}onInstanceStarted(e){return"function"!=typeof e?ioError.raiseError("onInstanceStarted requires a single argument of type function"):this.registry.add("instance-started",e)}async processInstanceClosed(e){if(!e)return;const t=this.sessionStorage.getInstanceData(e);if(t){delete this.locks[t.id],this.sessionStorage.removeInstance(t.id);try{await this.glueController.clearContext(e,"instance")}catch(t){this.logger?.warn(`error while clearing the context of instance ${e}: ${t?.message}`)}this.emitStreamData("instanceStopped",t),await this.waitEventFlush(),delete this.explicitClosingInstanceIds[t.id]}}async notifyWindows(e,t,r,n,i,o,s){const a={windowId:t.id,name:`${t.applicationName}_${t.id}`,initialUrl:e,initialContext:i,initialBounds:r,layoutComponentId:o,initialChannelId:s};await this.ioc.windowsController.processNewWindow(a,i,n)}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}async handleAppHello(e,t){this.logger?.trace(`[${t}] handling hello message for id: ${e.windowId}`),e.windowId&&this.locks[e.windowId]&&(this.logger?.trace(`[${t}] found an app lock, unlocking key one and waiting for the second one`),this.locks[e.windowId].openKeyOne(),await this.locks[e.windowId].keyTwo,delete this.locks[e.windowId],this.logger?.trace(`[${t}] the lock is lifted, proceeding`));const r=this.sessionStorage.getAllInstancesData(),n=(await this.appDirectory.getAll()).map(e=>{const t=r.filter(t=>t.applicationName===e.name);return{...e,instances:t}});if(e.windowId){this.logger?.trace(`[${t}] there is a valid windowId, removing ${e.windowId} from the state controller`),this.stateController.remove(e.windowId);const r=n.find(t=>t.instances.some(t=>t.id===e.windowId)),i=!!this.sessionStorage.getWorkspaceClientById(e.windowId);if(r?.title&&!i){const n=e.windowId,i=r.title;PromiseWrap(()=>this.glueController.callWindow("windows",this.ioc.windowsController.setTitleOperation,{windowId:n,title:i},{windowId:n}),2e4).catch(e=>this.logger?.trace(`[${t}] error while setting the application instance title: ${e.message}`))}}if(!e.windowId){this.logger?.trace(`[${t}] no windowId was provided, returning all apps without initialChannelId`);return{apps:n}}const i=this.sessionStorage.getWindowDataById(e.windowId),o=this.sessionStorage.getWindowChannelData(e.windowId),s=o?o.channels?.[0]:i?.initialChannelId,a={apps:n,initialChannelId:s};return this.logger?.trace(`[${t}] compiled a list of all active applications and instances and returning it to the caller with initialChannelId: ${s}`),a}async handleInstanceStop(e,t){this.logger?.trace(`[${t}] handling stop command for instance: ${e.id}`);if(this.sessionStorage.getWorkspaceClientById(e.id))return this.logger?.trace(`[${t}] this instance is detected as a workspace window, closing via the workspaces controller`),void await this.ioc.workspacesController.closeItem({itemId:e.id},t);if(!this.sessionStorage.getInstanceData(e.id))return ioError.raiseError(`Cannot close instance: ${e.id}, because it is not known by the platform`);const r=this.sessionStorage.getWindowDataById(e.id);if(!r)return ioError.raiseError(`Cannot close instance: ${e.id}, because it's window is not known by the platform`);this.ioc.windowsController.setExplicitClosingWindowId(e.id),this.explicitClosingInstanceIds[e.id]=!0,window.open(void 0,r.windowId)?.close(),await this.processInstanceClosed(e.id),await this.ioc.windowsController.cleanUpWindow(e.id),this.logger?.trace(`[${t}] instance ${e.id} has been closed, removed from store, announced stopped and notified windows, responding to caller`)}async handleRegisterRemoteApps(e,t){if(this.logger?.trace(`[${t}] handling remote bypass command`),this.config.remote)return ioError.raiseError(`[${t}] cannot accept remote apps from the protocol, because there is an active remote configuration.`);await this.appDirectory.processAppDefinitions(e.definitions,{mode:"replace",type:"remote"}),this.logger?.trace(`[${t}] remote bypass command completed`)}async handleImport(e,t){this.logger?.trace(`[${t}] handling import command`),await this.appDirectory.processAppDefinitions(e.definitions,{type:"inmemory",mode:e.mode}),this.logger?.trace(`[${t}] import command completed`)}async handleRemove(e,t){this.logger?.trace(`[${t}] handling remove command for ${e.name}`);const r=await this.appDirectory.removeInMemory(e.name);r&&(this.logger?.trace(`definition ${r.name} removed successfully`),this.emitStreamData("appDirectoryStateChange",{appsRemoved:[r],appsAdded:[],appsChanged:[]}))}async handleExport(e,t){this.logger?.trace(`[${t}] handling export command`);const r=await this.appDirectory.exportInMemory();return this.logger?.trace(`[${t}] export command successful`),{definitions:r}}async handleClear(e,t){this.logger?.trace(`[${t}] handling clear command`),await this.appDirectory.processAppDefinitions([],{type:"inmemory",mode:"replace"}),this.logger?.trace(`[${t}] all in-memory apps are cleared`)}setLock(e){const t={},r=new Promise(e=>{t.openKeyOne=e}),n=new Promise(e=>{t.openKeyTwo=e});t.keyOne=r,t.keyTwo=n,this.locks[e]=t}async registerWorkspaceApp(e,t){if(!e.appName)return ioError.raiseError(`Cannot register application with config: ${JSON.stringify(e)}, because no app name was found`);const r=await this.appDirectory.getAll();if(e.appName===defaultNoAppWindowComponentAppName$1)return await this.ioc.windowsController.registerWorkspaceWindow(e,t);if(!r.some(t=>t.name===e.appName))return ioError.raiseError(`Cannot register application with config: ${JSON.stringify(e)}, because no app with this name name was found`);this.sessionStorage.removeEjectedWindowId(e.windowId),e.channelId&&this.sessionStorage.addWindowChannel(e.windowId,e.channelId),this.sessionStorage.saveBridgeInstanceData({windowId:e.windowId,appName:e.appName}),this.logger?.trace(`[${t}] processing valid workspace application registration with id ${e.windowId}, app name ${e.appName} and frame ${e.frameId}`),e.context&&await this.glueController.setStartContext(e.windowId,e.context,"instance");const n={id:e.windowId,applicationName:e.appName};this.sessionStorage.saveInstanceData(n),this.emitStreamData("instanceStarted",n),this.logger?.trace(`[${t}] instance registration is completed and announced, calling windows registration`),await this.ioc.windowsController.registerWorkspaceWindow(e,t)}async processNewInstance(e){e.context&&await this.glueController.setStartContext(e.data.id,e.context,"instance"),this.sessionStorage.saveInstanceData(e.data),this.emitStreamData("instanceStarted",e.data)}emitStreamData(e,t){this.logger?.trace(`sending notification of event: ${e} with data: ${JSON.stringify(t)}`),this.glueController.pushSystemMessage("appManager",e,t)}async getStartingBounds(e,t,r){const n={top:t.top??e.top??this.defaultBounds.top,left:t.left??e.left??this.defaultBounds.left,width:t.width??e.width??this.defaultBounds.width,height:t.height??e.height??this.defaultBounds.height};if(!t.relativeTo)return n;try{const e=await this.ioc.windowsController.getWindowBounds(t.relativeTo,r),i=t.relativeDirection??"right";return getRelativeBounds(n,e,i)}catch(e){return n}}waitEventFlush(){return new Promise(e=>setTimeout(e,10))}}const layoutsOperationTypesDecoder=oneOf$1(constant$2("get"),constant$2("getAll"),constant$2("export"),constant$2("import"),constant$2("remove"),constant$2("save"),constant$2("restore"),constant$2("rename"),constant$2("getGlobalPermissionState"),constant$2("checkGlobalActivated"),constant$2("requestGlobalPermission"),constant$2("operationCheck"),constant$2("getDefaultGlobal"),constant$2("setDefaultGlobal"),constant$2("clearDefaultGlobal"),constant$2("updateMetadata"),constant$2("getCurrent")),newLayoutOptionsDecoder=object$2({name:nonEmptyStringDecoder$2,context:optional$3(anyJson$2()),metadata:optional$3(anyJson$2()),instances:optional$3(array$3(nonEmptyStringDecoder$2)),ignoreInstances:optional$3(array$3(nonEmptyStringDecoder$2)),setAsCurrent:optional$3(boolean$3()),ignoreContexts:optional$3(boolean$3()),saveWindowContexts:optional$3(boolean$3())}),restoreOptionsDecoder=object$2({name:nonEmptyStringDecoder$2,context:optional$3(anyJson$2()),closeRunningInstance:optional$3(boolean$3()),closeMe:optional$3(boolean$3()),timeout:optional$3(nonNegativeNumberDecoder$2)}),simpleLayoutConfigDecoder=object$2({name:nonEmptyStringDecoder$2,type:layoutTypeDecoder}),getAllLayoutsConfigDecoder=object$2({type:layoutTypeDecoder}),saveLayoutConfigDecoder=object$2({layout:newLayoutOptionsDecoder}),renameLayoutConfigDecoder=object$2({layout:glueLayoutDecoder,newName:nonEmptyStringDecoder$2}),layoutResultDecoder=object$2({status:nonEmptyStringDecoder$2}),updateLayoutMetadataConfigDecoder=object$2({layout:glueLayoutDecoder}),restoreLayoutConfigDecoder=object$2({layout:restoreOptionsDecoder}),allLayoutsFullConfigDecoder=object$2({layouts:array$3(glueLayoutDecoder)}),importModeDecoder=oneOf$1(constant$2("replace"),constant$2("merge")),layoutsImportConfigDecoder=object$2({layouts:array$3(glueLayoutDecoder),mode:importModeDecoder,skipManagerRequest:optional$3(boolean$3())}),allLayoutsSummariesResultDecoder=object$2({summaries:array$3(layoutSummaryDecoder$1)});object$2({layout:glueLayoutDecoder});const optionalSimpleLayoutResult=object$2({layout:optional$3(glueLayoutDecoder)}),setDefaultGlobalConfigDecoder=object$2({name:nonEmptyStringDecoder$2});object$2({layoutType:oneOf$1(constant$2("Global"),constant$2("Workspace")),layoutName:nonEmptyStringDecoder$2,context:optional$3(anyJson$2()),instances:optional$3(array$3(nonEmptyStringDecoder$2)),ignoreInstances:optional$3(array$3(nonEmptyStringDecoder$2))}),object$2({windowContext:optional$3(anyJson$2())});const fullSaveRequestResponseDecoder=object$2({bounds:windowBoundsDecoder,windowContext:optional$3(anyJson$2()),url:nonEmptyStringDecoder$2,name:nonEmptyStringDecoder$2,application:nonEmptyStringDecoder$2,windowId:nonEmptyStringDecoder$2,initialContext:optional$3(anyJson$2())});object$2({windowContext:optional$3(anyJson$2()),windowId:nonEmptyStringDecoder$2,frameId:nonEmptyStringDecoder$2}),object$2({windows:array$3(fullSaveRequestResponseDecoder)});const permissionStateResultDecoder=object$2({state:oneOf$1(constant$2("prompt"),constant$2("denied"),constant$2("granted"))}),simpleAvailabilityResultDecoder=object$2({isAvailable:boolean$3()}),defaultNoAppWindowComponentAppName="no-app-window",defaultPermissionTimeoutMS=25e3,defaultRestHeaders$1={"Content-Type":"application/json",Accept:"application/json"},defaultRestRequestTimeoutMS$1=3e4,layoutEventOperations={added:"layoutAdded",changed:"layoutChanged",removed:"layoutRemoved",renamed:"layoutRenamed"},getWindowManagementPermissionStatus=async e=>{try{return await navigator.permissions.query({name:"window-management"})}catch(t){e?.warn(extractErrorMsg$1(t));return await navigator.permissions.query({name:"window-placement"})}};class LayoutsController{glueController;globalBuilder;globalRestorer;localStore;managerStore;restStore;sessionStore;registry=CallbackRegistryFactory$2();unsubFuncs=[];started=!1;store;operations={get:{name:"get",dataDecoder:simpleLayoutConfigDecoder,resultDecoder:optionalSimpleLayoutResult,execute:this.handleGetLayout.bind(this)},getAll:{name:"getAll",dataDecoder:getAllLayoutsConfigDecoder,resultDecoder:allLayoutsSummariesResultDecoder,execute:this.handleGetAll.bind(this)},getCurrent:{name:"getCurrent",resultDecoder:optionalSimpleLayoutResult,execute:this.handleGetCurrentLayout.bind(this)},export:{name:"export",dataDecoder:getAllLayoutsConfigDecoder,resultDecoder:allLayoutsFullConfigDecoder,execute:this.handleExport.bind(this)},import:{name:"import",dataDecoder:layoutsImportConfigDecoder,execute:this.handleImport.bind(this)},remove:{name:"remove",dataDecoder:simpleLayoutConfigDecoder,execute:this.handleRemove.bind(this)},rename:{name:"rename",dataDecoder:renameLayoutConfigDecoder,resultDecoder:layoutResultDecoder,execute:this.handleRename.bind(this)},save:{name:"save",dataDecoder:saveLayoutConfigDecoder,execute:this.handleSave.bind(this)},restore:{name:"restore",dataDecoder:restoreLayoutConfigDecoder,execute:this.handleRestore.bind(this)},getGlobalPermissionState:{name:"getGlobalPermissionState",resultDecoder:permissionStateResultDecoder,execute:this.handleGetGlobalPermissionState.bind(this)},requestGlobalPermission:{name:"requestGlobalPermission",resultDecoder:simpleAvailabilityResultDecoder,execute:this.handleRequestGlobalPermission.bind(this)},checkGlobalActivated:{name:"checkGlobalActivated",resultDecoder:simpleAvailabilityResultDecoder,execute:this.handleCheckGlobalActivated.bind(this)},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)},getDefaultGlobal:{name:"getDefaultGlobal",resultDecoder:optionalSimpleLayoutResult,execute:this.handleGetDefaultGlobal.bind(this)},setDefaultGlobal:{name:"setDefaultGlobal",dataDecoder:setDefaultGlobalConfigDecoder,execute:this.handleSetDefaultGlobal.bind(this)},clearDefaultGlobal:{name:"clearDefaultGlobal",execute:this.handleClearDefaultGlobal.bind(this)},updateMetadata:{name:"updateMetadata",dataDecoder:updateLayoutMetadataConfigDecoder,execute:this.handleUpdateMetadata.bind(this)}};constructor(e,t,r,n,i,o,s){this.glueController=e,this.globalBuilder=t,this.globalRestorer=r,this.localStore=n,this.managerStore=i,this.restStore=o,this.sessionStore=s}get logger(){return logger.get("layouts.controller")}handlePlatformShutdown(){this.started=!1,this.unsubFuncs.forEach(e=>e()),this.unsubFuncs=[],this.store.stop()}async start(e){this.store=this.getStore(e),this.setupStoreListeners(),await this.store.start(e),this.started=!0,this.logger?.trace("initialization is completed")}ready(){return Promise.resolve()}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this windows control message, because the controller has not been started");const t=e.data,r=e.commandId,n=layoutsOperationTypesDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This layouts request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`Layouts request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r,e.callerId,e.callerType),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`Layouts request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}async handleSave(e,t){this.logger?.trace(`[${t}] handling save layout with config: ${JSON.stringify(e)}`),await this.checkRequestPermission("save"),this.logger?.trace(`[${t}] the required permissions are granted, proceeding.`);const r=await this.globalBuilder.saveGlobalLayout(e,t);return(e.layout.setAsCurrent??!0)&&this.sessionStore.setLayoutsSystemData({currentLayoutName:r.name}),this.logger?.trace(`[${t}] layout ${e.layout.name} was saved successfully`),{layout:r}}async handleRestore(e,t,r,n){this.logger?.trace(`[${t}] handling restore layout with config: ${JSON.stringify(e)}`),await this.checkRequestPermission("restore",e.layout.timeout);const i=new Date,o=await this.get("Global",e.layout.name,t);if(!o)return ioError.raiseError(`Layout with name "${e.layout.name}" and type: "Global" cannot be found`);await this.globalRestorer.restoreGlobalLayout(e,t,r,n);const s=new Date;this.registry.execute("layout-restored",{layoutName:e.layout.name,startTime:i,endTime:s}),await this.emitData({operation:"layoutRestored",layout:o}),this.logger?.trace(`[${t}] layout ${e.layout.name} was restored successfully`)}onLayoutRestored(e){return"function"!=typeof e?ioError.raiseError("onLayoutRestored requires a single argument of type function"):this.registry.add("layout-restored",e)}async handleGetAll(e,t){this.logger?.trace(`[${t}] handling get all layout summaries request for type: ${e.type}`);const r=(await this.store.getAllLayouts(e.type,t)).map(e=>({name:e.name,type:e.type,context:e.context,metadata:e.metadata}));return this.logger?.trace(`[${t}] all summaries have been compiled, responding to caller`),{summaries:r}}async handleGetCurrentLayout(e,t){this.logger?.trace(`[${t}] handling get current layout request`);const{currentLayoutName:r}=this.sessionStore.getLayoutsSystemData(),n=r?await this.get("Global",r,t):void 0;return this.logger?.trace(`[${t}] request completed, responding to the caller with layout with name: ${r}`),{layout:n}}async handleExport(e,t){this.logger?.trace(`[${t}] handling get all layout full request for type: ${e.type}`);const r=await this.store.getAllLayouts(e.type,t);return this.logger?.trace(`[${t}] full layouts collection have been compiled, responding to caller`),{layouts:r}}async handleImport(e,t){this.logger?.trace(`[${t}] handling mass import request for layout names: ${e.layouts.map(e=>e.name).join(", ")}`);const r=e.layouts.filter(e=>"Workspace"===e.type),n=e.layouts.filter(e=>"Global"===e.type).map(e=>({...e,token:e.token??generateLayoutToken()}));await this.store.saveLayouts(r,n,e.mode,t),this.logger?.trace(`[${t}] mass import completed, responding to caller`)}async handleRemove(e,t){this.logger?.trace(`[${t}] handling remove request for ${JSON.stringify(e)}`);const r=await this.get(e.type,e.name,t);r?(await this.store.deleteLayout(r,t),this.logger?.trace(`[${t}] layout with name "${e.name}" and type: "${e.type}" has been removed`)):this.logger?.trace(`[${t}] layout with name "${e.name}" and type: "${e.type}" cannot be found and therefore cannot be removed`)}async handleRename(e,t){this.logger?.trace(`[${t}] handling rename request for ${JSON.stringify(e)}`);const r=e.layout.name;if(e.newName===r)return this.logger?.trace(`[${t}] The provided new layout name ${e.newName} is the same as the current one.`),{status:"Success"};const n=await this.get(e.layout.type,r,t);if(!n){const n=`layout with name "${r}" and type: "${e.layout.type}" cannot be found`;return this.logger?.trace(`[${t}] ${n}`),{status:n}}return await this.store.renameLayout(n,e.newName,t)}async handleUpdateMetadata(e,t){this.logger?.trace(`[${t}] handling update metadata request for ${JSON.stringify(e)}`);const r=await this.get(e.layout.type,e.layout.name,t);if(!r)return ioError.raiseError(`Layout with name "${e.layout.name}" and type: "${e.layout.type}" cannot be found`);const n={...r,metadata:e.layout.metadata};return"Global"===r.type?await this.store.saveLayouts([],[n],"merge",t):await this.store.saveLayouts([n],[],"merge",t)}async handleGetLayout(e,t){this.logger?.trace(`[${t}] handling get layout request for name: ${e.name} and type: ${e.type}`);const r=(await this.store.getAllLayouts(e.type,t)).find(t=>t.name===e.name);return this.logger?.trace(`[${t}] request completed, responding to the caller`),{layout:r}}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}async handleGetGlobalPermissionState(e,t){this.logger?.trace(`[${t}] handling Get Global Permission State request`);const{state:r}=await getWindowManagementPermissionStatus(this.logger);return this.logger?.trace(`[${t}] request completed with state: ${r}, responding to the caller`),{state:r}}async handleRequestGlobalPermission(e,t){this.logger?.trace(`[${t}] handling Request Global Permission command`);const{state:r}=await getWindowManagementPermissionStatus(this.logger);if("granted"===r)return{isAvailable:!0};if("denied"===r)return{isAvailable:!1};try{return await window.getScreenDetails(),this.logger?.trace(`[${t}] request completed, responding to the caller`),{isAvailable:!0}}catch(e){return this.logger?.trace(`[${t}] request completed, responding to the caller`),{isAvailable:!1}}}async handleCheckGlobalActivated(e,t){return this.logger?.trace(`[${t}] handling Check Global Activated request`),this.logger?.trace(`[${t}] request completed, responding to the caller`),{isAvailable:!0}}async handleGetDefaultGlobal(e,t){this.logger?.trace(`[${t}] handling Get Default Global request`);return{layout:await this.store.getDefaultLayout(t)}}async handleSetDefaultGlobal(e,t){this.logger?.trace(`[${t}] handling Set Default Global request for name: ${e.name}`);const r=(await this.store.getAllLayouts("Global",t)).find(t=>t.name===e.name);if(!r)return ioError.raiseError(`Layout ${e.name} does not exist`);await this.store.setDefaultLayout(e.name,t),await this.emitData({operation:"defaultLayoutChanged",layout:{name:r.name}})}async handleClearDefaultGlobal(e,t){this.logger?.trace(`[${t}] handling Clear Default Global request`),await this.store.clearDefaultLayout(t),await this.emitData({operation:"defaultLayoutChanged"}),this.logger?.trace(`[${t}] request completed, responding to the caller`)}updateCurrentLayoutIfNeeded(e){if("Global"!==e.layout.type)return;const t=this.sessionStore.getLayoutsSystemData(),r=e.operation===layoutEventOperations.renamed&&t.currentLayoutName===e.layout.prevName,n=e.operation===layoutEventOperations.removed&&t.currentLayoutName===e.layout.name;(r||n)&&(r&&(t.currentLayoutName=e.layout.name),n&&(t.currentLayoutName=void 0),this.sessionStore.setLayoutsSystemData(t))}async emitData(e){this.logger?.trace(`sending notification of event: ${e.operation} with data: ${JSON.stringify(e)}`),this.glueController.pushSystemMessage("layouts",e.operation,e.layout)}async announceEvents(e){let t=0;for(const r of e)++t,t%10==0&&await this.waitEventFlush(),await this.emitData(r)}async get(e,t,r){return(await this.store.getAllLayouts(e,r)).find(r=>r.name===t&&r.type===e)}waitEventFlush(){return new Promise(e=>setTimeout(e,10))}async checkRequestPermission(e,t=defaultPermissionTimeoutMS){if(window.gtf)return;const{state:r}=await getWindowManagementPermissionStatus(this.logger);switch(r){case"granted":return;case"prompt":try{return void await PromiseWrap(()=>window.getScreenDetails(),t,"Timeout waiting for user permission for Multi-Screen Window Placement")}catch(t){return ioError.raiseError(`Cannot complete operation ${e} for Global Layouts, because the user has not granted the Multi-Screen Window Placement permission`)}case"denied":return ioError.raiseError(`Cannot complete operation ${e} for Global Layouts, because the user has denied the Multi-Screen Window Placement permission`)}}setupStoreListeners(){const e=this.store.onLayoutsAdded(e=>{this.announceEvents(e.map(e=>({operation:layoutEventOperations.added,layout:e}))).catch(e=>this.logger?.warn(extractErrorMsg$1(e)))}),t=this.store.onLayoutsChanged(e=>{this.announceEvents(e.map(e=>({operation:layoutEventOperations.changed,layout:e}))).catch(e=>this.logger?.warn(extractErrorMsg$1(e)))}),r=this.store.onLayoutsRemoved(e=>{const t=layoutEventOperations.removed;this.announceEvents(e.map(e=>({operation:t,layout:e}))).catch(e=>this.logger?.warn(extractErrorMsg$1(e))),e.forEach(e=>this.updateCurrentLayoutIfNeeded({operation:t,layout:e}))}),n=this.store.onLayoutsRenamed(e=>{const t=layoutEventOperations.renamed;this.announceEvents(e.map(e=>({operation:t,layout:e}))).catch(e=>this.logger?.warn(extractErrorMsg$1(e))),e.forEach(e=>this.updateCurrentLayoutIfNeeded({operation:t,layout:e}))});this.unsubFuncs.push(e,t,r,n)}getStore(e){const t=e.layouts?.mode,r=!(!e?.manager?.url||!e?.manager?.features?.layoutsStore),n=!!e?.layouts?.rest?.url;return!t&&r?this.managerStore:!t&&n?this.restStore:t||r?"idb"===t||"session"===t?(this.checkForConflictingLocalSettings(n),this.localStore):"rest"===t&&n?this.restStore:"rest"!==t||n?"manager"===t&&r?this.managerStore:"manager"!==t||r?ioError.raiseError("Cannot set layouts store."):ioError.raiseError("The layouts store is configured to be managed, but the manager is not configured."):ioError.raiseError("The layouts store is configured to be rest, but the rest url is not configured."):this.localStore}checkForConflictingLocalSettings(e){if(e)return ioError.raiseError("Layouts store is configured to be local, but the rest url is also configured. Please either remove de-config rest or set the layouts store to be rest.")}}const instanceOfAny=(e,t)=>t.some(t=>e instanceof t);let idbProxyableTypes,cursorAdvanceMethods;function getIdbProxyableTypes(){return idbProxyableTypes||(idbProxyableTypes=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function getCursorAdvanceMethods(){return cursorAdvanceMethods||(cursorAdvanceMethods=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const cursorRequestMap=new WeakMap,transactionDoneMap=new WeakMap,transactionStoreNamesMap=new WeakMap,transformCache=new WeakMap,reverseTransformCache=new WeakMap;function promisifyRequest(e){const t=new Promise((t,r)=>{const n=()=>{e.removeEventListener("success",i),e.removeEventListener("error",o)},i=()=>{t(wrap(e.result)),n()},o=()=>{r(e.error),n()};e.addEventListener("success",i),e.addEventListener("error",o)});return t.then(t=>{t instanceof IDBCursor&&cursorRequestMap.set(t,e)}).catch(()=>{}),reverseTransformCache.set(t,e),t}function cacheDonePromiseForTransaction(e){if(transactionDoneMap.has(e))return;const t=new Promise((t,r)=>{const n=()=>{e.removeEventListener("complete",i),e.removeEventListener("error",o),e.removeEventListener("abort",o)},i=()=>{t(),n()},o=()=>{r(e.error||new DOMException("AbortError","AbortError")),n()};e.addEventListener("complete",i),e.addEventListener("error",o),e.addEventListener("abort",o)});transactionDoneMap.set(e,t)}let idbProxyTraps={get(e,t,r){if(e instanceof IDBTransaction){if("done"===t)return transactionDoneMap.get(e);if("objectStoreNames"===t)return e.objectStoreNames||transactionStoreNamesMap.get(e);if("store"===t)return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return wrap(e[t])},set:(e,t,r)=>(e[t]=r,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function replaceTraps(e){idbProxyTraps=e(idbProxyTraps)}function wrapFunction(e){return e!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?getCursorAdvanceMethods().includes(e)?function(...t){return e.apply(unwrap(this),t),wrap(cursorRequestMap.get(this))}:function(...t){return wrap(e.apply(unwrap(this),t))}:function(t,...r){const n=e.call(unwrap(this),t,...r);return transactionStoreNamesMap.set(n,t.sort?t.sort():[t]),wrap(n)}}function transformCachableValue(e){return"function"==typeof e?wrapFunction(e):(e instanceof IDBTransaction&&cacheDonePromiseForTransaction(e),instanceOfAny(e,getIdbProxyableTypes())?new Proxy(e,idbProxyTraps):e)}function wrap(e){if(e instanceof IDBRequest)return promisifyRequest(e);if(transformCache.has(e))return transformCache.get(e);const t=transformCachableValue(e);return t!==e&&(transformCache.set(e,t),reverseTransformCache.set(t,e)),t}const unwrap=e=>reverseTransformCache.get(e);function openDB(e,t,{blocked:r,upgrade:n,blocking:i,terminated:o}={}){const s=indexedDB.open(e,t),a=wrap(s);return n&&s.addEventListener("upgradeneeded",e=>{n(wrap(s.result),e.oldVersion,e.newVersion,wrap(s.transaction),e)}),r&&s.addEventListener("blocked",e=>r(e.oldVersion,e.newVersion,e)),a.then(e=>{o&&e.addEventListener("close",()=>o()),i&&e.addEventListener("versionchange",e=>i(e.oldVersion,e.newVersion,e))}).catch(()=>{}),a}function deleteDB(e,{blocked:t}={}){const r=indexedDB.deleteDatabase(e);return t&&r.addEventListener("blocked",e=>t(e.oldVersion,e)),wrap(r).then(()=>{})}const readMethods=["get","getKey","getAll","getAllKeys","count"],writeMethods=["put","add","delete","clear"],cachedMethods=new Map;function getMethod(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(cachedMethods.get(t))return cachedMethods.get(t);const r=t.replace(/FromIndex$/,""),n=t!==r,i=writeMethods.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!i&&!readMethods.includes(r))return;const o=async function(e,...t){const o=this.transaction(e,i?"readwrite":"readonly");let s=o.store;return n&&(s=s.index(t.shift())),(await Promise.all([s[r](...t),i&&o.done]))[0]};return cachedMethods.set(t,o),o}replaceTraps(e=>({...e,get:(t,r,n)=>getMethod(t,r)||e.get(t,r,n),has:(t,r)=>!!getMethod(t,r)||e.has(t,r)}));class IDBController{_database;defaultDBName="glue42core";dbName=this.defaultDBName;dbVersion=3;globalLayoutsObjectStoreName="globalLayouts";prefsObjectStoreName="prefs";serviceWorkerObjectStoreName="serviceWorker";workspaceLayoutsObjectStoreName="workspaceLayouts";constructor(){"indexedDB"in window||ioError.raiseError("Cannot initialize the local storage, because IndexedDB is not supported")}get database(){return this._database?this._database:ioError.raiseError("There is no open database")}async start(e){e?.id&&(this.dbName=e?.id);const t=await openDB(this.dbName,this.dbVersion,{upgrade:this.setUpDB.bind(this)});this._database=t}stop(){this.database.close(),delete this._database,this.dbName=this.defaultDBName}getAllLayouts(e){const t=this.getLayoutsObjectStoreName(e);return this.database.getAll(t)}deleteLayout(e,t){const r=this.getLayoutsObjectStoreName(t);return this.database.delete(r,e)}clearLayouts(e){const t=this.getLayoutsObjectStoreName(e);return this.database.clear(t)}getLayout(e,t){const r=this.getLayoutsObjectStoreName(t);return this.database.get(r,e)}storeLayout(e){runDecoderWithIOError(glueLayoutDecoder,e);const t=this.getLayoutsObjectStoreName(e.type);return this.database.put(t,e,e.name)}async renameLayout(e,t){runDecoderWithIOError(glueLayoutDecoder,e);const r=this.getLayoutsObjectStoreName(e.type),n=this.database.transaction(r,"readwrite");await Promise.all([n.store.delete(t),n.store.put(e,e.name),n.done])}getLayoutsObjectStoreName(e){switch(e){case"Workspace":return this.workspaceLayoutsObjectStoreName;case"Global":return this.globalLayoutsObjectStoreName;default:return ioError.raiseError(`The provided layout type is not recognized: ${e}`)}}clearServiceWorker(){return this.database.clear(this.serviceWorkerObjectStoreName)}storeServiceWorker(e){return this.database.put(this.serviceWorkerObjectStoreName,e,"workerData")}async clearAllPrefs(e){const t=(await this.getAllPrefs()).map(({app:t})=>({app:t,data:{},lastUpdate:e})),r=this.database.transaction(this.prefsObjectStoreName,"readwrite");return await Promise.all([...t.map(e=>r.store.put(e,e.app)),r.done]),t}getAllPrefs(){return this.database.getAll(this.prefsObjectStoreName)}getPrefs(e){return this.database.get(this.prefsObjectStoreName,e)}deletePrefs(e){return this.database.delete(this.prefsObjectStoreName,e)}async replaceAllPrefs(e){const t=this.database.transaction(this.prefsObjectStoreName,"readwrite");return await t.store.clear(),await Promise.all([...e.map(e=>t.store.put(e,e.app)),t.done]),e}async setPrefs(e){return await this.database.put(this.prefsObjectStoreName,e,e.app),e}async updatePrefs(e){const t=await this.database.get(this.prefsObjectStoreName,e.app),r=t?{app:e.app,data:{...t.data,...e.data},lastUpdate:e.lastUpdate}:e;return this.setPrefs(r)}setUpDB(e){e.objectStoreNames.contains(this.workspaceLayoutsObjectStoreName)||e.createObjectStore(this.workspaceLayoutsObjectStoreName),e.objectStoreNames.contains(this.globalLayoutsObjectStoreName)||e.createObjectStore(this.globalLayoutsObjectStoreName),e.objectStoreNames.contains(this.serviceWorkerObjectStoreName)||e.createObjectStore(this.serviceWorkerObjectStoreName),e.objectStoreNames.contains(this.prefsObjectStoreName)||e.createObjectStore(this.prefsObjectStoreName)}}const defaultLoadingConfig={defaultStrategy:"direct",delayed:{batch:1,initialOffsetInterval:1e3,interval:5e3},showDelayedIndicator:!1};class WorkspacesController{framesController;glueController;stateController;hibernationWatcher;sequelizer;sessionStorageController;ioc;registry=CallbackRegistryFactory$2();_started=!1;settings;defaultWindowOpenBounds;connectionConfig;operations={frameHello:{name:"frameHello",dataDecoder:frameHelloDecoder,execute:this.handleFrameHello.bind(this)},isWindowInWorkspace:{name:"isWindowInWorkspace",dataDecoder:simpleItemConfigDecoder,resultDecoder:isWindowInSwimlaneResultDecoder,execute:this.isWindowInWorkspace.bind(this)},createWorkspace:{name:"createWorkspace",dataDecoder:workspaceCreateConfigDecoder,resultDecoder:workspaceSnapshotResultDecoder,execute:this.createWorkspace.bind(this)},createFrame:{name:"createFrame",resultDecoder:frameSummaryResultDecoder,execute:this.createFrame.bind(this)},initFrame:{name:"initFrame",resultDecoder:voidResultDecoder,execute:this.initFrame.bind(this)},getAllFramesSummaries:{name:"getAllFramesSummaries",resultDecoder:frameSummariesResultDecoder,execute:this.getAllFramesSummaries.bind(this)},getFrameSummary:{name:"getFrameSummary",dataDecoder:getFrameSummaryConfigDecoder,resultDecoder:frameSummaryDecoder,execute:this.getFrameSummary.bind(this)},getAllWorkspacesSummaries:{name:"getAllWorkspacesSummaries",resultDecoder:workspaceSummariesResultDecoder,execute:this.getAllWorkspacesSummaries.bind(this)},getWorkspaceSnapshot:{name:"getWorkspaceSnapshot",dataDecoder:simpleItemConfigDecoder,resultDecoder:workspaceSnapshotResultDecoder,execute:this.getWorkspaceSnapshot.bind(this)},getAllLayoutsSummaries:{name:"getAllLayoutsSummaries",resultDecoder:layoutSummariesDecoder,execute:this.getAllLayoutsSummaries.bind(this)},openWorkspace:{name:"openWorkspace",dataDecoder:openWorkspaceConfigDecoder,resultDecoder:workspaceSnapshotResultDecoder,execute:this.openWorkspace.bind(this)},deleteLayout:{name:"deleteLayout",dataDecoder:deleteLayoutConfigDecoder,resultDecoder:voidResultDecoder,execute:this.deleteLayout.bind(this)},saveLayout:{name:"saveLayout",dataDecoder:workspaceLayoutSaveConfigDecoder,resultDecoder:workspaceLayoutDecoder,execute:this.saveLayout.bind(this)},importLayout:{name:"importLayout",dataDecoder:workspacesLayoutImportConfigDecoder,resultDecoder:voidResultDecoder,execute:this.importLayout.bind(this)},exportAllLayouts:{name:"exportAllLayouts",resultDecoder:exportedLayoutsResultDecoder,execute:this.exportAllLayouts.bind(this)},restoreItem:{name:"restoreItem",dataDecoder:simpleItemConfigDecoder,resultDecoder:voidResultDecoder,execute:this.restoreItem.bind(this)},maximizeItem:{name:"maximizeItem",dataDecoder:simpleItemConfigDecoder,resultDecoder:voidResultDecoder,execute:this.maximizeItem.bind(this)},focusItem:{name:"focusItem",dataDecoder:simpleItemConfigDecoder,resultDecoder:voidResultDecoder,execute:this.focusItem.bind(this)},closeItem:{name:"closeItem",dataDecoder:simpleItemConfigDecoder,resultDecoder:voidResultDecoder,execute:this.closeItem.bind(this)},closeWorkspace:{name:"closeWorkspace",dataDecoder:simpleItemConfigDecoder,resultDecoder:voidResultDecoder,execute:this.closeWorkspace.bind(this)},resizeItem:{name:"resizeItem",dataDecoder:resizeItemConfigDecoder,resultDecoder:voidResultDecoder,execute:this.resizeItem.bind(this)},changeFrameState:{name:"changeFrameState",dataDecoder:frameStateConfigDecoder,resultDecoder:voidResultDecoder,execute:this.changeFrameState.bind(this)},getFrameState:{name:"getFrameState",dataDecoder:simpleItemConfigDecoder,resultDecoder:frameStateResultDecoder,execute:this.getFrameState.bind(this)},getFrameBounds:{name:"getFrameBounds",dataDecoder:simpleItemConfigDecoder,resultDecoder:frameBoundsResultDecoder,execute:this.getFrameBounds.bind(this)},moveFrame:{name:"moveFrame",dataDecoder:moveFrameConfigDecoder,resultDecoder:voidResultDecoder,execute:this.moveFrame.bind(this)},getFrameSnapshot:{name:"getFrameSnapshot",dataDecoder:frameSnapshotConfigDecoder,resultDecoder:frameSnapshotResultDecoder,execute:this.getFrameSnapshot.bind(this)},forceLoadWindow:{name:"forceLoadWindow",dataDecoder:simpleItemConfigDecoder,resultDecoder:simpleWindowOperationSuccessResultDecoder,execute:this.forceLoadWindow.bind(this)},ejectWindow:{name:"ejectWindow",dataDecoder:ejectWindowDataDecoder,resultDecoder:simpleWindowOperationSuccessResultDecoder,execute:this.ejectWindow.bind(this)},setItemTitle:{name:"setItemTitle",dataDecoder:setItemTitleConfigDecoder,resultDecoder:voidResultDecoder,execute:this.setItemTitle.bind(this)},moveWindowTo:{name:"moveWindowTo",dataDecoder:moveWindowConfigDecoder,resultDecoder:voidResultDecoder,execute:this.moveWindowTo.bind(this)},addWindow:{name:"addWindow",dataDecoder:addWindowConfigDecoder,resultDecoder:addItemResultDecoder,execute:this.addWindow.bind(this)},addContainer:{name:"addContainer",dataDecoder:addContainerConfigDecoder,resultDecoder:addItemResultDecoder,execute:this.addContainer.bind(this)},bundleWorkspace:{name:"bundleWorkspace",dataDecoder:bundleWorkspaceConfigDecoder,resultDecoder:voidResultDecoder,execute:this.bundleWorkspace.bind(this)},bundleItem:{name:"bundleItem",dataDecoder:bundleItemConfigDecoder,resultDecoder:voidResultDecoder,execute:this.bundleItem.bind(this)},hibernateWorkspace:{name:"hibernateWorkspace",dataDecoder:workspaceSelectorDecoder,resultDecoder:voidResultDecoder,execute:this.hibernateWorkspace.bind(this)},resumeWorkspace:{name:"resumeWorkspace",dataDecoder:workspaceSelectorDecoder,resultDecoder:voidResultDecoder,execute:this.resumeWorkspace.bind(this)},getWorkspacesConfig:{name:"getWorkspacesConfig",resultDecoder:workspacesConfigDecoder,execute:this.getWorkspacesConfiguration.bind(this)},lockWorkspace:{name:"lockWorkspace",dataDecoder:lockWorkspaceDecoder,resultDecoder:voidResultDecoder,execute:this.lockWorkspace.bind(this)},lockWindow:{name:"lockWindow",dataDecoder:lockWindowDecoder,resultDecoder:voidResultDecoder,execute:this.lockWindow.bind(this)},lockContainer:{name:"lockContainer",dataDecoder:lockContainerDecoder,resultDecoder:voidResultDecoder,execute:this.lockContainer.bind(this)},pinWorkspace:{name:"pinWorkspace",dataDecoder:pinWorkspaceDecoder,resultDecoder:voidResultDecoder,execute:this.pinWorkspace.bind(this)},unpinWorkspace:{name:"unpinWorkspace",dataDecoder:workspaceSelectorDecoder,resultDecoder:voidResultDecoder,execute:this.unpinWorkspace.bind(this)},getWorkspaceIcon:{name:"getWorkspaceIcon",dataDecoder:workspaceSelectorDecoder,resultDecoder:workspaceIconDecoder,execute:this.getWorkspaceIcon.bind(this)},setWorkspaceIcon:{name:"setWorkspaceIcon",dataDecoder:setWorkspaceIconDecoder,resultDecoder:voidResultDecoder,execute:this.setWorkspaceIcon.bind(this)},checkStarted:{name:"checkStarted",execute:this.handleCheckStarted.bind(this)},getPlatformFrameId:{name:"getPlatformFrameId",execute:this.handleGetPlatformFrameId.bind(this)},getWorkspacesLayouts:{name:"getWorkspacesLayouts",dataDecoder:getWorkspacesLayoutsConfigDecoder,resultDecoder:getWorkspacesLayoutsResponseDecoder,execute:this.handleGetWorkspacesLayouts.bind(this)},getWorkspaceWindowsOnLayoutSaveContext:{name:"getWorkspaceWindowsOnLayoutSaveContext",dataDecoder:getWorkspaceWindowsOnLayoutSaveContextConfigDecoder,resultDecoder:getWorkspaceWindowsOnLayoutSaveContextResult,execute:this.handleGetWorkspaceWindowsOnLayoutSaveContext.bind(this)},setMaximizationBoundary:{name:"setMaximizationBoundary",dataDecoder:setMaximizationBoundaryConfigDecoder,resultDecoder:voidResultDecoder,execute:this.handleSetMaximizationBoundary.bind(this)},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)},getWorkspaceWindowFrameBounds:{name:"getWorkspaceWindowFrameBounds",resultDecoder:frameBoundsResultDecoder,dataDecoder:simpleItemConfigDecoder,execute:this.getWorkspaceWindowFrameBounds.bind(this)},focusChange:{name:"focusChange",dataDecoder:focusEventDataDecoder,execute:this.handleFocusEvent.bind(this)},bringBackToWorkspace:{name:"bringBackToWorkspace",dataDecoder:bringBackToWorkspaceDataDecoder,execute:this.handleBringBackToWorkspace.bind(this)},showChannelsLink:{name:"showChannelsLink",dataDecoder:showChannelsLinkDecoder,resultDecoder:voidResultDecoder,execute:this.showChannelsLink.bind(this)}};constructor(e,t,r,n,i,o,s){this.framesController=e,this.glueController=t,this.stateController=r,this.hibernationWatcher=n,this.sequelizer=i,this.sessionStorageController=o,this.ioc=s}get started(){return this._started}set started(e){this._started=e}handlePlatformShutdown(){this.started=!1,this.hibernationWatcher.stop(),this.framesController.stop()}async start(e){e.workspaces?(this.connectionConfig=e.connection,this.settings=this.applyDefaults(e.workspaces),this.defaultWindowOpenBounds=e.windows.defaultWindowOpenBounds,this.settings.hibernation&&this.hibernationWatcher.start(this,this.settings.hibernation),await Promise.all([this.glueController.createWorkspacesStream(),this.glueController.createWorkspacesEventsReceiver(this.bridgeWorkspaceEvent.bind(this))]),this.started=!0):this.started=!1}async configurePostStart(){await this.framesController.start(this.settings,this.defaultWindowOpenBounds,this.operations.getFrameSummary),this.stateController.onWindowDisappeared(e=>this.framesController.handleFrameDisappeared(e))}get logger(){return logger.get("workspaces.controller")}ready(){return Promise.resolve()}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this workspaces control message, because the controller has not been started");const t=e.data,r=e.commandId,n=workspacesOperationDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This workspace request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`Workspace request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`Workspace request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}handleClientUnloaded(e,t){this.logger?.trace(`handling unloading of ${e}`),t&&!t.closed||(this.logger?.trace(`${e} detected as closed, checking if frame and processing close`),this.framesController.handleFrameDisappeared(e))}bridgeWorkspaceEvent(e){if(this.glueController.pushWorkspacesMessage(e),"opened"===e.action&&"workspace"===e.type){const{workspaceSummary:t}=e.payload;this.registry.execute("workspace-started",{layoutName:t.config.layoutName})}if("closed"===e.action&&"workspace"===e.type){const{workspaceSummary:t}=e.payload;this.glueController.clearContext(t.id,"workspace"),this.registry.execute("workspace-closed",{layoutName:t.config.layoutName})}this.settings.hibernation&&this.hibernationWatcher.notifyEvent(e)}onWorkspaceClosed(e){return"function"!=typeof e?ioError.raiseError("onWorkspaceClosed requires a single argument of type function"):this.registry.add("workspace-closed",e)}onWorkspaceStarted(e){return"function"!=typeof e?ioError.raiseError("onWorkspaceStarted requires a single argument of type function"):this.registry.add("workspace-started",e)}onWorkspaceSaved(e){return"function"!=typeof e?ioError.raiseError("onWorkspaceSaved requires a single argument of type function"):this.registry.add("workspace-saved",e)}async closeWorkspace(e,t){return this.sequelizer.enqueue(async()=>{this.logger?.trace(`[${t}] handling closeWorkspace request with config ${JSON.stringify(e)}`);const r=e.itemId,n=(await this.getAllWorkspacesSummaries({},t)).summaries,i=n.find(e=>e.id===r);if(!i)return ioError.raiseError(`Cannot close workspace with id: ${r}, because it is unknown to the platform`);const o=i.config.frameId,s=1===n.filter(e=>e.config.frameId===o).length,a=this.glueController.platformWindowId;if(s&&o===a&&this.logger?.info(`[${t}] this is the last workspace in the platform frame, cannot close the platform frame.`),s&&o!==a)return this.logger?.trace(`[${t}] this is the last workspace in frame ${o}, closing the frame`),await this.framesController.closeFrame(o),void this.logger?.trace(`[${t}] the frame window is closed`);this.logger?.trace(`[${t}] targeting frame ${o} for closing workspace ${r}`),await this.glueController.callFrame(this.operations.closeItem,e,o),this.logger?.trace(`[${t}] frame ${o} gave a success signal, responding to caller`)})}async closeFrame(e,t){return this.sequelizer.enqueue(async()=>{this.logger?.trace(`[${t}] handling closeFrame request with config ${JSON.stringify(e)}`),await this.framesController.closeFrame(e.itemId),this.logger?.trace(`[${t}] the frame window is closed`)})}async closeItem(e,t){this.logger?.trace(`[${t}] handling closeItem request with config ${JSON.stringify(e)}`);const r=this.framesController.getAll().find(t=>t.windowId===e.itemId);if(r)return await this.closeFrame(e,t);const n=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeting frame ${n.windowId}`),await this.glueController.callFrame(this.operations.closeItem,e,n.windowId),this.logger?.trace(`[${t}] frame ${n.windowId} gave a success signal, responding to caller`)}async setItemTitle(e,t){this.logger?.trace(`[${t}] handling setItemTitle request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.setItemTitle,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async hibernateWorkspace(e,t){this.logger?.trace(`[${t}] handling hibernateWorkspace request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.workspaceId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.preserveAllWorkspaceWindowsContext(e.workspaceId),await this.glueController.callFrame(this.operations.hibernateWorkspace,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async getWorkspacesConfiguration(e,t){return this.logger?.trace(`[${t}] handling getWorkspacesConfiguration request`),this.settings}async getWorkspaceWindowFrameBounds(e,t){this.logger?.trace(`[${t}] handling getWorkspaceWindowFrameBounds request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.itemId}),n=await this.glueController.callWindow("windows",this.ioc.windowsController.getFrameBoundsOperation,{windowId:r.windowId},{windowId:r.windowId});return this.logger?.trace(`[${t}] getWorkspaceWindowFrameBounds completed`),{bounds:n.bounds}}async getAllFramesSummaries(e,t){if(this.logger?.trace(`[${t}] handling getAllFramesSummaries request`),!this.started)return{summaries:[]};const r=await this.framesController.getAll();this.logger?.trace(`[${t}] sending getFrameSummary to all known frames: ${r.join(", ")}`);const n=(await Promise.all(r.map(e=>this.glueController.callFrame(this.operations.getFrameSummary,{itemId:e.windowId},e.windowId)))).filter(e=>"none"!==e.id);return this.logger?.trace(`[${t}] all frames responded, returning to caller`),{summaries:n}}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}async handleFrameHello(e,t){this.logger?.trace(`[${t}] handling handleFrameHello command with config: ${JSON.stringify(e)}`),e.windowId&&this.framesController.processNewHello(e.windowId)}async isWindowInWorkspace(e,t){this.logger?.trace(`[${t}] handling isWindowInWorkspace command with config: ${JSON.stringify(e)}`);const r=this.framesController.getAll();this.logger?.trace(`[${t}] sending isWindowInWorkspace to all known frames: ${JSON.stringify(r.join(", "))}`);const n=(await Promise.all(r.map(t=>this.glueController.callFrame(this.operations.isWindowInWorkspace,e,t.windowId)))).some(e=>e.inWorkspace);return this.logger?.trace(`[${t}] all frames responded, returning ${n} to the caller`),{inWorkspace:n}}async createWorkspace(e,t){this.logger?.trace(`[${t}] handling createWorkspace command`);const r=this.getBlockedAppNames(e.children??[],t);if(r.length)return ioError.raiseError(`Cannot complete 'createWorkspace' operation because there're app origins blocked by the Platform. Blocked names: ${JSON.stringify(r)}`);const n={frameId:e.frame?.reuseFrameId,newFrame:e.frame?.newFrame,itemId:e.config?.reuseWorkspaceId},i=await this.framesController.getFrameInstance(n);this.logger?.trace(`[${t}] calling frame: ${i.windowId}, based on selection config: ${JSON.stringify(n)}`);const o=await this.glueController.callFrame(this.operations.createWorkspace,e,i.windowId);return this.logger?.trace(`[${t}] frame ${i.windowId} responded with a valid snapshot, returning to caller`),o}async createFrame(e,t){this.logger?.trace(`[${t}] handling createFrame command`);const r=await this.framesController.openFrame(e.frameConfig,e.layoutComponentId);this.logger?.trace(`[${t}] calling frame: ${r.windowId}}`);const n=await this.glueController.callFrame(this.operations.createFrame,e,r.windowId);return this.logger?.trace(`[${t}] frame ${r.windowId} responded returning to caller`),n}async initFrame(e,t){this.logger?.trace(`[${t}] handling initFrame command`);const r={frameId:e.frameId},n=await this.framesController.getFrameInstance(r);this.logger?.trace(`[${t}] calling frame: ${n.windowId}, based on selection config: ${JSON.stringify(r)}`);const i=await this.filterWorkspacesWithInstanceRestrictions(e.workspaces,t),o={...e,workspaces:i};await this.glueController.callFrame(this.operations.initFrame,o,n.windowId),this.logger?.trace(`[${t}] frame ${n.windowId} responded returning to caller`)}async getFrameSummary(e,t){this.logger?.trace(`[${t}] handling getFrameSummary request for config: ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] forwarding getFrameSummary to frame ${r.windowId}`);const n=await this.glueController.callFrame(this.operations.getFrameSummary,e,r.windowId);return this.logger?.trace(`[${t}] frame ${r.windowId} responded with a valid summary, returning to caller`),n}async getAllWorkspacesSummaries(e,t){this.logger?.trace(`[${t}] handling getAllWorkspacesSummaries request`);const r=this.framesController.getAll();this.logger?.trace(`[${t}] sending getAllWorkspacesSummaries to all known frames: ${r.join(", ")}`);const n=(await Promise.all(r.map(e=>this.glueController.callFrame(this.operations.getAllWorkspacesSummaries,{},e.windowId)))).reduce((e,t)=>(e.push(...t.summaries),e),[]);return this.logger?.trace(`[${t}] all frames responded, results were aggregated, returning to caller`),{summaries:n}}async getWorkspaceSnapshot(e,t){this.logger?.trace(`[${t}] handling getWorkspaceSnapshot for config: ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeting frame ${r.windowId}`);const n=await this.glueController.callFrame(this.operations.getWorkspaceSnapshot,e,r.windowId);return this.logger?.trace(`[${t}] frame ${r.windowId} responded with a valid snapshot, retuning to caller`),n}async handleCheckStarted(e,t){return this.logger?.trace(`[${t}] handling handleCheckStarted request`),this.logger?.trace(`[${t}] the controller has been started, responding to caller`),{started:!0}}async handleGetPlatformFrameId(e,t){this.logger?.trace(`[${t}] handling GetPlatformFrameId request`);const r=this.framesController.getPlatformFrameSessionData();return this.logger?.trace(`[${t}] GetPlatformFrameId completed, responding to caller`),{id:r?.windowId}}async getFrameSessionData(e,t){this.logger?.trace(`[${t}] handling getFrameSessionData request`);const r=this.framesController.getFrameConfig(e.frameId);return this.logger?.trace(`[${t}] getFrameSessionData completed, responding to caller`),r}async handleGetWorkspacesLayouts(e,t){this.logger?.trace(`[${t}] handling handleGetWorkspacesLayouts request for frame: ${e.frameId} for layout: ${e.layoutName} of type: ${e.layoutType} and config: ${JSON.stringify(e)}`);const r=await this.glueController.callFrame(this.operations.getWorkspacesLayouts,e,e.frameId);if(this.logger?.trace(`[${t}] handleGetWorkspacesLayouts request completed for frame: ${e.frameId} for layout: ${e.layoutName} of type: ${e.layoutType} and config: ${JSON.stringify(e)}`),!e.ignoreContexts)return this.logger?.info(`[${t}] 'ignoreContexts' flag not set on layout save request, returning workspace and window contexts as received from frame ${e.frameId}`),r;return await this.checkIsIgnoreContextsOnLayoutSaveSupported(e.frameId,t)?(this.logger?.info(`[${t}] Returning workspaces layouts response as received from frame ${e.frameId}.`),r):(this.clearWorkspaceAndWindowsContexts(r.workspaces),this.logger?.info(`[${t}] Returning workspaces layouts response after clearing workspace and window contexts in the Platform`),r)}async getFrameBounds(e,t){this.logger?.trace(`[${t}] handling getFrameBounds request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({frameId:e.itemId}),n=await this.glueController.callWindow("windows",this.ioc.windowsController.getFrameBoundsOperation,{windowId:r.windowId},{windowId:r.windowId});return this.logger?.trace(`[${t}] getFrameBounds completed`),{bounds:n.bounds}}async showChannelsLink(e,t){this.logger?.trace(`[${t}] - received 'showChannelsLink' signal for windowId ${e.windowId}`);const r=await this.framesController.getFrameInstance({frameId:e.frameId});if(!r)return ioError.raiseError(`[${t}] - frame ${e.frameId} not found, cannot show channels link`);await this.glueController.callFrame(this.operations.showChannelsLink,e,r.windowId),this.logger?.trace(`[${t}] - frame ${r.windowId} gave a success signal, responding to caller`)}async getAllLayoutsSummaries(e,t){this.logger?.trace(`[${t}] handling getAllLayoutsSummaries command`);const r=(await this.ioc.layoutsController.handleGetAll({type:"Workspace"},t)).summaries.map(e=>({name:e.name}));return this.logger?.trace(`[${t}] all layouts retrieved and mapped, returning to caller`),{summaries:r}}async openWorkspace(e,t){this.logger?.trace(`[${t}] handling openWorkspace command for name: ${e.name}`);const r={frameId:e.restoreOptions?.frameId,newFrame:e.restoreOptions?.newFrame,itemId:e.restoreOptions?.reuseWorkspaceId},n=await this.tryFocusExistingWorkspace(e.name,t),i=await this.framesController.getFrameInstance(r);return n?await this.getWorkspaceSnapshot({itemId:n},t):await this.glueController.callFrame(this.operations.openWorkspace,e,i.windowId)}async deleteLayout(e,t){this.logger?.trace(`[${t}] handling deleteLayout request for name: ${e.name}`),await this.ioc.layoutsController.handleRemove({name:e.name,type:"Workspace"},t),this.logger?.trace(`[${t}] layouts reported this layout as deleted, responding to caller`)}async saveLayout(e,t){this.logger?.trace(`[${t}] handling saveLayout request for workspace ${e.workspaceId} and name ${e.name}`);const r=await this.framesController.getFrameInstance({itemId:e.workspaceId});this.logger?.trace(`[${t}] forwarding request to frame ${r.windowId}`);const n=(await this.glueController.callFrame(this.operations.getWorkspaceSnapshot,{itemId:e.workspaceId},r.windowId)).config.layoutName,i=await this.glueController.callFrame(this.operations.saveLayout,e,r.windowId);return this.logger?.trace(`[${t}] frame ${r.windowId} responded with a valid layout, returning to caller`),this.registry.execute("workspace-saved",{layoutName:i.name,oldLayoutName:n}),i}async importLayout(e,t){this.logger?.trace(`[${t}] handling importLayout command for layout ${e.layout.name}`),await this.ioc.layoutsController.handleImport({layouts:[e.layout],mode:e.mode},t),this.logger?.trace(`[${t}] the layouts controller successfully imported the layout, responding to caller`)}async exportAllLayouts(e,t){this.logger?.trace(`[${t}] handling exportAllLayouts request`);return await this.ioc.layoutsController.handleExport({type:"Workspace"},t)}async restoreItem(e,t){this.logger?.trace(`[${t}] handling restoreItem request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.restoreItem,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async maximizeItem(e,t){this.logger?.trace(`[${t}] handling maximizeItem request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.maximizeItem,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async focusItem(e,t){this.logger?.trace(`[${t}] handling focusItem request with config ${JSON.stringify(e)}`);const r=this.framesController.getAll().find(t=>t.windowId===e.itemId);if(r)return this.logger?.trace(`[${t}] this is targeted at a frame, focusing the frame`),void window.open(void 0,r.windowId);const n=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeting frame ${n.windowId}`),await this.glueController.callFrame(this.operations.focusItem,e,n.windowId),this.logger?.trace(`[${t}] frame ${n.windowId} gave a success signal, responding to caller`)}async resizeItem(e,t){this.logger?.trace(`[${t}] handling resizeItem request with config ${JSON.stringify(e)}`);const r=this.framesController.getAll().find(t=>t.windowId===e.itemId);if(r){this.logger?.trace(`[${t}] detected targeted item is frame, building window resize config`);const n={windowId:e.itemId,width:e.width,height:e.height,relative:e.relative};return await this.glueController.callWindow("windows",this.ioc.windowsController.moveResizeOperation,n,{windowId:r.windowId}),void this.logger?.trace(`[${t}] window resize responded with success, returning to caller`)}const n=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeted item is not a frame, it is located in frame ${n.windowId}`),await this.glueController.callFrame(this.operations.resizeItem,e,n.windowId),this.logger?.trace(`[${t}] frame ${n.windowId} gave a success signal, responding to caller`)}async getFrameSnapshot(e,t){this.logger?.trace(`[${t}] handling getFrameSnapshot request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeting frame ${r.windowId}`);const n=await this.glueController.callFrame(this.operations.getFrameSnapshot,e,r.windowId);return this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`),n}async forceLoadWindow(e,t){this.logger?.trace(`[${t}] handling forceLoadWindow request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeting frame ${r.windowId}`);const n=await this.glueController.callFrame(this.operations.forceLoadWindow,e,r.windowId);return this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`),n}async ejectWindow(e,t){this.logger?.trace(`[${t}] handling ejectWindow request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance(e);e.windowId&&this.sessionStorageController.addEjectedWindowId(e.windowId),this.logger?.trace(`[${t}] targeting frame ${r.windowId}`);const n=await this.glueController.callFrame(this.operations.ejectWindow,e,r.windowId);return this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`),n}async moveWindowTo(e,t){this.logger?.trace(`[${t}] handling moveWindowTo request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.moveWindowTo,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async addWindow(e,t){if(this.logger?.trace(`[${t}] handling addWindow request with config ${JSON.stringify(e)}`),e.definition.appName&&this.checkIfOriginBlockedByAppName(e.definition.appName))return ioError.raiseError(`Cannot complete 'addWindow' operation - origin of app '${e.definition.appName}' is blocked by the Platform`);const r=await this.framesController.getFrameInstance({itemId:e.parentId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`);const n=await this.glueController.callFrame(this.operations.addWindow,e,r.windowId);return this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal: ${JSON.stringify(n)}, responding to caller`),n}checkIfOriginBlockedByAppName(e){const t=this.glueController.getAllApplications().find(t=>t.name===e);return t?checkIsOriginBlocked(t.userProperties.details.url,this.connectionConfig.blockList):ioError.raiseError(`Application with name: ${e} does not exist`)}extractAppNamesFromConfig(e,t=[]){if("window"===e.type&&e.appName)return t.push(e.appName),t;for(const r of e.children||[])this.extractAppNamesFromConfig(r,t);return t}getBlockedAppNames(e,t){const r=[];for(const t of e)this.extractAppNamesFromConfig(t,r);this.logger?.trace(`[${t}] filtering blocked apps from all gathered appNames: ${JSON.stringify(r)}`);const n=r.filter(e=>this.checkIfOriginBlockedByAppName(e));return this.logger?.trace(`[${t}] blocked app names: ${JSON.stringify(n)}`),n}async addContainer(e,t){this.logger?.trace(`[${t}] handling addContainer request with config ${JSON.stringify(e)}`);const r=this.getBlockedAppNames(e.definition.children??[],t);if(r.length)return ioError.raiseError(`Cannot complete 'addContainer' operation because there're app origins blocked by the Platform. Blocked names: ${JSON.stringify(r)}`);const n=await this.framesController.getFrameInstance({itemId:e.parentId});this.logger?.trace(`[${t}] targeting frame ${n.windowId}`);const i=await this.glueController.callFrame(this.operations.addContainer,e,n.windowId);return this.logger?.trace(`[${t}] frame ${n.windowId} gave a success signal: ${JSON.stringify(i)}, responding to caller`),i}async bundleWorkspace(e,t){this.logger?.trace(`[${t}] handling bundleWorkspace request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.workspaceId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.bundleWorkspace,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async bundleItem(e,t){this.logger?.trace(`[${t}] handling bundleItem request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.itemId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.bundleItem,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async resumeWorkspace(e,t){this.logger?.trace(`[${t}] handling resumeWorkspace request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.workspaceId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.resumeWorkspace,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async lockWorkspace(e,t){this.logger?.trace(`[${t}] handling lockWorkspace request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.workspaceId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.lockWorkspace,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async lockContainer(e,t){this.logger?.trace(`[${t}] handling lockContainer request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.itemId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.lockContainer,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async lockWindow(e,t){this.logger?.trace(`[${t}] handling lockWindow request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.windowPlacementId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.lockWindow,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async pinWorkspace(e,t){this.logger?.trace(`[${t}] handling pinWorkspace request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.workspaceId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.pinWorkspace,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async unpinWorkspace(e,t){this.logger?.trace(`[${t}] handling unpinWorkspace request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.workspaceId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.unpinWorkspace,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async getWorkspaceIcon(e,t){this.logger?.trace(`[${t}] handling getWorkspaceIcon request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.workspaceId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`);const n=await this.glueController.callFrame(this.operations.getWorkspaceIcon,e,r.windowId);return this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`),n}async setWorkspaceIcon(e,t){this.logger?.trace(`[${t}] handling setWorkspaceIcon request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.workspaceId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.setWorkspaceIcon,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async handleGetWorkspaceWindowsOnLayoutSaveContext(e,t){this.logger?.trace(`[${t}] handling GetWorkspaceWindowsOnLayoutSaveContext request with config: ${JSON.stringify(e)}`);const r=await Promise.all(e.windowIds.map(async t=>({windowId:t,windowContext:await this.getWorkspaceWindowOnLayoutSaveData(t,e)})));return this.logger?.trace(`[${t}] operation GetWorkspaceWindowsOnLayoutSaveContext completed responding`),{windowsOnSaveData:r}}async handleSetMaximizationBoundary(e,t){this.logger?.trace(`[${t}] handling setMaximizationBoundary request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.setMaximizationBoundary,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async changeFrameState(e,t){return ioError.raiseError("Frame states are not supported in Glue42 Core")}async getFrameState(e,t){return ioError.raiseError("Frame states are not supported in Glue42 Core")}async handleFocusEvent(e,t){this.logger?.trace(`[${t}] handling focus event from frame id: ${e.windowId} and hasFocus: ${e.hasFocus}`);try{await this.framesController.getFrameInstance({frameId:e.windowId})}catch(r){return void this.logger?.trace(`[${t}] ignoring focus event for unrecognized frame with id: ${e.windowId}`)}const r={type:"frame",action:"focus",payload:{frameSummary:{id:e.windowId,isFocused:e.hasFocus}}};this.bridgeWorkspaceEvent(r),this.logger?.trace(`[${t}] focus event from frame id: ${e.windowId} and hasFocus: ${e.hasFocus} handled`)}async moveFrame(e,t){this.logger?.trace(`[${t}] handling moveFrame command with config: ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({frameId:e.itemId}),n={windowId:e.itemId,top:e.top,left:e.left,relative:e.relative};await this.glueController.callWindow("windows",this.ioc.windowsController.moveResizeOperation,n,{windowId:r.windowId}),this.logger?.trace(`[${t}] frame with id ${r.windowId} was successfully moved, responding to caller`)}applyDefaults(e){const t=e?.hibernation||{},r=deepMerge$1(defaultLoadingConfig,e?.loadingStrategy||{});return{...e,loadingStrategy:r,hibernation:t}}async getWorkspaceWindowOnLayoutSaveData(e,t){if(this.ioc.sessionController.getAllNonGlue().some(t=>t.windowId===e))return this.ioc.layoutsBuilder.getNonGlueWindowContext(t,e);return this.ioc.sessionController.getWorkspaceClientById(e)?this.ioc.layoutsBuilder.getGlueClientWindowContextOnSaveRequest(t,e):ioError.raiseError(`Cannot ask window: ${e} for on layout save request, because it is not a known workspace window`)}async handleBringBackToWorkspace({windowId:e},t){this.logger?.trace(`[${t}] - received 'bringBackToWorkspace' signal for windowId ${e}`);if(!this.glueController.getWindowById(e))return ioError.raiseError(`Cannot bring back window with id ${e} to workspace because it is not known by the platform`);this.sessionStorageController.addEjectedWindowId(e);const r=await this.glueController.clientGlue.contexts.get(`___window___${e}`);if(!r||!Object.keys(r).length||!r.___io___?.ejectedWindow)return ioError.raiseError(`Cannot bring back window with id ${e} to workspace because it was never a part from one`);const{___io___:{ejectedWindow:n}}=r,i=await this.framesController.getFrameInstance({itemId:n.frameId}),o={definition:{type:"group",children:[{windowId:e,type:"window"}]},parentType:"workspace",parentId:n.workspaceId},s=await this.glueController.callFrame(this.operations.addContainer,o,i.windowId);this.logger?.trace(`[${t}] - frame ${i.windowId} gave a success signal: ${JSON.stringify(s)}`)}async tryFocusExistingWorkspace(e,t){const r=await this.ioc.layoutsController.handleGetLayout({name:e,type:"Workspace"},t);if(!this.hasInstanceRestriction(r.layout))return;const n=(await this.getAllWorkspacesSummaries({},t)).summaries.find(t=>t.config.layoutName===e);return n?(await this.focusItem({itemId:n.id},t),n.id):void 0}hasInstanceRestriction(e){if(!e)return!1;const t=e.components[0];return!1===t.state?.config?.allowMultiple}async filterWorkspacesWithInstanceRestrictions(e,t){const r=await this.getAllWorkspacesSummaries({},t),n=await Promise.all(e.map(e=>e).filter(e=>e.name).map(e=>this.ioc.layoutsController.handleGetLayout({name:e.name,type:"Workspace"},t))),i=e.filter((e,t,i)=>{if(!this.isRestoreWorkspaceDefinition(e))return!0;const o=n.find(t=>t.layout?.name===e.name)?.layout;if(!this.hasInstanceRestriction(o))return!0;const s=r.summaries.find(t=>t.config.layoutName===e.name),a=e!==i.find(t=>this.isRestoreWorkspaceDefinition(t)&&t.name===e.name);return!s&&!a},[]);return i}isRestoreWorkspaceDefinition(e){return!!e.name}async checkIsIgnoreContextsOnLayoutSaveSupported(e,t){const r=await this.glueController.isFrameOperationSupported("isIgnoreContextsOnLayoutSaveSupported",e);return this.logger?.info(`[${t}] Frame ${e} ${r?"supports":"does NOT support"} 'ignoreContexts' flag on layout save requests`),r}clearWorkspaceAndWindowsContexts(e){e.forEach(e=>{e.context={},this.clearWorkspaceChildrenContexts(e.children)})}clearWorkspaceChildrenContexts(e){e.forEach(e=>{"window"!==e.type?this.clearWorkspaceChildrenContexts(e.children):e.config.context={}})}}const INTENTS_RESOLVER_INTEROP_PREFIX="T42.Intents.Resolver.Control.",INTENTS_RESOLVER_WIDTH=400,INTENTS_RESOLVER_HEIGHT=400,DEFAULT_METHOD_RESPONSE_TIMEOUT_MS=6e4,DEFAULT_RAISE_TIMEOUT_MS=9e4,DEFAULT_PICK_HANDLER_BY_TIMEOUT_MS=9e4,ERRORS=errors.intents;class IntentsController{glueController;legacyResolverController;appDirectory;windowsController;prefsController;uiController;operations={getIntents:{name:"getIntents",resultDecoder:wrappedIntentsDecoder,execute:this.getWrappedIntents.bind(this)},findIntent:{name:"findIntent",dataDecoder:wrappedIntentFilterDecoder,resultDecoder:wrappedIntentsDecoder,execute:this.findIntent.bind(this)},raise:{name:"raise",dataDecoder:raiseIntentRequestDecoder,resultDecoder:intentResultDecoder,execute:this.raise.bind(this)},filterHandlers:{name:"filterHandlers",dataDecoder:filterHandlersWithResolverConfigDecoder,resultDecoder:filterHandlersResultDecoder,execute:this.filterHandlers.bind(this)},getIntentsByHandler:{name:"getIntentsByHandler",dataDecoder:intentHandlerDecoder,resultDecoder:getIntentsResultDecoder,execute:this.getIntentsByHandler.bind(this)},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)}};started=!1;isIntentsSharingEnabledViaBridge=!1;constructor(e,t,r,n,i,o){this.glueController=e,this.legacyResolverController=t,this.appDirectory=r,this.windowsController=n,this.prefsController=i,this.uiController=o}get logger(){return logger.get("intents.controller")}handlePlatformShutdown(){this.started=!1}async start(e){this.started=!0;const t=e.gateway?.bridge;this.isIntentsSharingEnabledViaBridge=!!t?.url&&!1!==t.intents?.enabled}ready(){return Promise.resolve()}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this intents control message, because the controller has not been started");const t=e.data,r=e.commandId,n=e.callerId,i=e.callerType,o=intentsOperationTypesDecoder.run(e.operation);if(!o.ok)return ioError.raiseError(`This intents request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(o.error)}`);const s=o.result,a=this.operations[s].dataDecoder?.run(t);if(a&&!a.ok)return ioError.raiseError(`Intents request for ${s} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(a.error)}`);this.logger?.debug(`[${r}] ${s} command is valid with data: ${JSON.stringify(t)}`);const c=await this.operations[s].execute(t,r,n,i),l=this.operations[s].resultDecoder?.run(c);return l&&!l.ok?ioError.raiseError(`Intents request for ${s} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(l.error)}`):(this.logger?.trace(`[${r}] ${s} command was executed successfully`),c)}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}extractAppIntents(e){const t={},r=e.filter(e=>e.intents.length>0);for(const e of r)for(const r of e.intents){t[r.name]||(t[r.name]=[]);const n={applicationName:e.name,applicationTitle:e.title,applicationDescription:e.caption,displayName:r.displayName,contextTypes:r.contexts,applicationIcon:e.icon,type:"app",resultType:r.resultType,customConfig:r.customConfig};t[r.name].push(n)}return t}async getInstanceIntents(e,t){const r={},n=this.isIntentsSharingEnabledViaBridge?this.glueController.getServers():this.glueController.getLocalServers();for(const i of n){const n=(i.getMethods?.()||[]).filter(e=>e.name.startsWith(GlueWebIntentsPrefix));await Promise.all(n.map(async n=>{const o=n.name.replace(GlueWebIntentsPrefix,"");r[o]=r[o]??[];const s={apps:e,server:i,method:n,commandId:t,intentName:o},a=this.glueController.isValidWindowId(s.server.windowId)?await this.getInstanceIntentHandler(s):this.getInstanceIntentHandlerWithInvalidWindowId(s);r[o].push(a)}))}return r}getInstanceIntentHandlerWithInvalidWindowId({server:e,method:t,apps:r,intentName:n}){const i=this.glueController.clientGlue.appManager.instances().find(t=>t.id===e.instance),o=t.flags.intent;if(!i)return{instanceId:e.instance,applicationName:e.application??e.applicationName??"",applicationIcon:o.icon,applicationTitle:"",applicationDescription:o.description,displayName:o.displayName,contextTypes:o.contextTypes,instanceTitle:e.instance,type:"instance",resultType:o.resultType,customConfig:o.customConfig};const{application:s}=i,a=r.find(e=>e.name===s.name)?.intents?.find(e=>e.name===n);return{instanceId:e.instance,applicationName:s.name,applicationIcon:o.icon??s.icon,applicationTitle:s.title??"",applicationDescription:o.description??s.caption,displayName:o.displayName??a?.displayName,contextTypes:o.contextTypes??a?.contexts,instanceTitle:"",type:"instance",resultType:o.resultType??a?.resultType}}async getInstanceIntentHandler({apps:e,intentName:t,server:r,method:n,commandId:i}){const o=e.find(e=>e.name===r.application),s=o?.intents?.find(e=>e.name===t)||void 0,a=n.flags.intent,c=await this.windowsController.getWindowTitle(r.windowId??"",i);return{instanceId:r.windowId||r.instance,applicationName:r.application||"",applicationIcon:a.icon||o?.icon,applicationTitle:o?.title||"",applicationDescription:a.description||o?.caption,displayName:a.displayName||s?.displayName,contextTypes:a.contextTypes||s?.contexts,instanceTitle:c,type:"instance",resultType:s?.resultType||a.resultType,customConfig:a.customConfig}}mergeIntentStores(e,t){const r={};for(const n of new Set([...Object.keys(e),...Object.keys(t)]))r[n]=[...e[n]||[],...t[n]||[]];return r}wrapIntents(e){return{intents:e}}async getIntents(e){const t=(await this.appDirectory.getAll()).map(e=>({name:e.name,title:e.title||"",icon:e.icon,caption:e.caption,intents:e.userProperties.intents??[]})),r=this.extractAppIntents(t);this.logger?.trace(`[${e}] got app intents`);const n=await this.getInstanceIntents(t,e);this.logger?.trace(`[${e}] got instance intents`);const i=this.mergeIntentStores(r,n);return Object.keys(i).map(e=>({name:e,handlers:i[e]}))}async getWrappedIntents(e){this.logger?.trace(`[${e}] handling getIntents command`);const t=await this.getIntents(e);return this.logger?.trace(`[${e}] getIntents command completed`),this.wrapIntents(t)}async findIntent(e,t){this.logger?.trace(`[${t}] handling findIntent command`);const r=e.filter;let n=await this.getIntents(t);if(!r)return this.wrapIntents(n);if("string"==typeof r)return this.wrapIntents(n.filter(e=>e.name===r));if(r.contextType){const e=r.contextType.toLowerCase();n=n.filter(t=>t.handlers.some(t=>t.contextTypes?.some(t=>t.toLowerCase()===e)))}if(r.name&&(n=n.filter(e=>e.name===r.name)),r.resultType){const e=r.resultType.toLowerCase();n=n.filter(t=>t.handlers.some(t=>t.resultType?.toLowerCase()===e))}return this.logger?.trace(`[${t}] findIntent command completed`),this.wrapIntents(n)}async getIntent(e,t){return(await this.getIntents(t)).find(t=>t.name===e)}async startApp(e,t){const r={...t.options??{},originIntentRequest:t};return(await this.glueController.clientGlue.appManager.application(e).start(t.context,r)).id}async raiseIntent(e,t,r,n){this.logger?.trace(`[${t}] handling raiseIntent command with intentRequest: ${JSON.stringify(e)}`);const i=e.intent,o=await this.getIntent(i,t);if(!o)return ioError.raiseError(`Intent ${i} not found!`);this.logger?.trace(`Raised intent definition: ${JSON.stringify(o)}`);const s=e.handlers?this.findHandlerByFilter(e.handlers,{type:"app"}):this.findHandlerByFilter(o.handlers,{type:"app"}),a=e.handlers?this.findHandlerByFilter(e.handlers,{type:"instance"}):this.findHandlerByFilter(o.handlers,{type:"instance"});let c;if(e.target&&"reuse"!==e.target||(c=a||s),"startNew"===e.target&&(c=s),"object"==typeof e.target&&e.target.app&&(c=this.findHandlerByFilter(o.handlers,{app:e.target.app})),"object"==typeof e.target&&e.target.instance&&(c=this.findHandlerByFilter(o.handlers,{instance:e.target.instance,app:e.target.app})),!c)return ioError.raiseError(`Can not raise intent for request ${JSON.stringify(e)} - can not find intent handler!`);return await this.raiseIntentToTargetHandler({request:e,handler:c,commandId:t,callerId:r,timeout:n})}findHandlerByFilter(e,t){return t.type?e.find(e=>e.type===t.type):t.instance?e.find(e=>t.app?e.applicationName===t.app&&e.instanceId===t.instance:e.instanceId===t.instance):t.app?e.find(e=>e.applicationName===t.app):void 0}async raiseIntentToTargetHandler({handler:e,request:t,callerId:r,commandId:n,timeout:i}){this.logger?.trace(`Raising intent to target handler:${JSON.stringify(e)}`);const o=e.instanceId?Promise.resolve(e.instanceId):this.startApp(e.applicationName,t).catch(e=>{const t=e instanceof Error||"string"==typeof e?e:JSON.stringify(e);return ioError.raiseError(`${ERRORS.TARGET_INSTANCE_UNAVAILABLE}. Reason: ${t}`)}),s=await o,a=`${GlueWebIntentsPrefix}${t.intent}`;this.logger?.trace(`Searching for interop server offering method ${a}`);const c={methodResponseTimeoutMs:i?i+1e3:DEFAULT_METHOD_RESPONSE_TIMEOUT_MS,waitTimeoutMs:i?i+1e3:DEFAULT_METHOD_RESPONSE_TIMEOUT_MS},l=this.glueController.invokeMethod(a,{...t.context,_initialCallerId:r},{instance:s},c).catch(e=>ioError.raiseError(`${ERRORS.INTENT_HANDLER_REJECTION}. Reason: ${e instanceof Error?e:JSON.stringify(e)}`)),u=await l;return this.logger?.trace(`[${n}] raiseIntent command completed. Returning result: ${JSON.stringify(u)}`),{request:t,handler:{...e,instanceId:s,type:"instance"},result:u.returned}}async raise(e,t,r,n){if(this.logger?.trace(`[${t}] Receive raise command with config: ${JSON.stringify(e)}`),!r)return ioError.raiseError(`${ERRORS.CALLER_NOT_DEFINED} for 'raise' command with request ${JSON.stringify(e)}`);const i=e.intentRequest.timeout||DEFAULT_RAISE_TIMEOUT_MS,o={instanceId:void 0},s=this.coreRaiseIntent.bind(this,{request:e,resolverInstance:o,timeout:i,commandId:t,callerId:this.getCallerIdByCallerType(r,n)});return e.intentRequest.waitUserResponseIndefinitely?s():PromiseWrap(s,i,`${ERRORS.TIMEOUT_HIT} - waited ${i}ms for 'raise' to resolve`)}async handleRaiseWithEmbeddedResolver({intentRequest:e,initialCaller:t,timeout:r,commandId:n}){this.logger?.trace(`[${n}] handling raise command with embedded resolver`);const i=e.waitUserResponseIndefinitely?MAX_SET_TIMEOUT_DELAY:r,o={commandId:n,config:{intentRequest:e,timeout:i},methodResponseTimeoutMs:i,initialCaller:t},s=await this.uiController.openResolver(o);s.isClosed&&ioError.raiseError(`${ERRORS.USER_CANCELLED}`),s.isExpired&&ioError.raiseError(`${ERRORS.TIMEOUT_HIT} - waited ${r}ms for user to choose an intent handler`);const a=s.userChoice?.handler;if(!a)return ioError.raiseError(`${ERRORS.HANDLER_NOT_FOUND}`);if(!!s.userChoice?.userSettings.preserveChoice)try{this.logger?.trace(`[${n}] - User wants to preserve the chosen of handler: ${JSON.stringify(a)}`),await this.preserveUserChoice({initialCaller:t,commandId:n,handler:a,intentName:e.intent})}catch(e){this.logger?.warn(`[${n}] - Prefs API threw the following error: ${e}. Handler won't be preserved`)}return this.handleRaiseToTargetHandler(e,a,n,t.instanceId,r)}async coreRaiseIntent({request:e,resolverInstance:t,timeout:r,commandId:n,callerId:i}){const{resolverConfig:o,intentRequest:s,embeddedResolverConfig:a}=e,c=(await this.findIntent({filter:{name:s.intent}},n)).intents.find(e=>e.name===s.intent);if(!c)return ioError.raiseError(`${ERRORS.INTENT_NOT_FOUND} with name ${s.intent}`);this.logger?.trace(`[${n}] Intent to be handled: ${JSON.stringify(c)}`);const{open:l,reason:u}=this.checkIfResolverShouldBeOpenedForRaise(c,s,o,a);if(!l)return this.logger?.trace(`[${n}] Intent Resolver UI won't be used. Reason: ${u}`),this.handleRaiseWithoutResolver({request:e,commandId:n,callerId:i,timeout:r});if(this.logger?.trace(`[${n}] Starting Intent Resolver app for intent request: ${JSON.stringify(e)}`),a?.enabled)return this.logger?.trace(`[${n}] Handling 'raise' with embedded intent resolver`),this.handleRaiseWithEmbeddedResolver({intentRequest:s,initialCaller:a.initialCaller,timeout:r,commandId:n});if(o){this.logger?.trace(`[${n}] Handling 'raise' with legacy intent resolver`);const o=this.handleRaiseWithLegacyResolver({request:e,commandId:n,resolverInstance:t,callerId:i,timeout:r});return o.catch(()=>t.instanceId&&this.legacyResolverController.stopResolverInstance(t.instanceId)),o}return ioError.raiseError(`Couldn't complete 'raise' operation with request: ${JSON.stringify(s)}`)}async handleRaiseToTargetHandler(e,t,r,n,i){const o=`with timeout of ${e.timeout??DEFAULT_RAISE_TIMEOUT_MS}ms`;if(this.logger?.trace(`Raising intent to target handler: ${JSON.stringify(t)} ${o}`),e.waitUserResponseIndefinitely)return PromiseWrap(()=>this.raiseIntentToTargetHandler({request:e,handler:{...t,type:t.instanceId?"instance":"app"},commandId:r,timeout:i,callerId:n}),i,`${ERRORS.INTENT_DELIVERY_FAILED} - waited ${i}ms for client to handle the raised intent`);const s=await this.raiseIntentToTargetHandler({request:e,handler:{...t,type:t.instanceId?"instance":"app"},commandId:r,callerId:n,timeout:i});return this.logger?.trace(`Result from raise() method for intent ${JSON.stringify(e.intent)}: ${JSON.stringify(s)}`),s}async handleRaiseWithoutResolver({request:e,commandId:t,callerId:r,timeout:n}){const{intentRequest:i}=e;return i.waitUserResponseIndefinitely?PromiseWrap(()=>this.raiseIntent(i,t,r,n),n,`${ERRORS.TIMEOUT_HIT} - waited ${n}ms for 'raise' to resolve`):this.raiseIntent(i,t,r,n)}async handleRaiseWithLegacyResolver(e){const{request:t,callerId:r,commandId:n,resolverInstance:i,timeout:o}=e,s=await this.legacyResolverController.startResolverApp({request:t.intentRequest,resolverConfig:t.resolverConfig,callerId:r,commandId:n,resolverInstance:i,method:"raise"});return this.handleRaiseToTargetHandler(t.intentRequest,s,n,r,o)}async preserveUserChoice({initialCaller:e,commandId:t,filter:r,intentName:n,handler:i}){const o=e.instanceId===this.glueController.me.instance?this.prefsController.platformAppName:this.glueController.getAppNameByInstanceId(e.instanceId);if(!o)return;this.logger?.info(`[${t}] - Saving user's choice of handler for '${o}' app`);const s=await this.prefsController.get({app:o},t),a=s.prefs.data?.intents??{},c={...s.prefs.data,intents:{...a,[n]:{handler:i,filter:r}}};await this.prefsController.update({app:o,data:c},t)}checkIfIntentHasMoreThanOneHandler(e,t){const r=t.handlers||e.handlers;if(!t.target)return r.length>1;if("reuse"===t.target)return r.filter(e=>"instance"===e.type&&e.instanceId).length>1||e.handlers.filter(e=>"app"===e.type).length>1;if("startNew"===t.target)return r.filter(e=>"app"===e.type).length>1;if(t.target.instance)return!1;if(t.target.app){const e=t.target.app;return r.filter(t=>t.applicationName===e&&t.instanceId).length>1}return!1}checkIfResolverShouldBeOpenedForRaise(e,t,r,n){if(!this.checkIfIntentHasMoreThanOneHandler(e,t))return{open:!1,reason:"Raised intent has only one handler"};if(n?.enabled)return{open:!0};const i=this.checkIfResolverShouldBeOpenByResolverConfig(r);return i.open?{open:!0}:i}checkIfResolverShouldBeOpenedForFilterHandlers(e,t,r,n){return 1===e.length?{open:!1,reason:`There's only one valid intent handler for filter ${JSON.stringify(t)}`}:!1===t.openResolver?{open:!1,reason:"Intents resolver is disabled by IntentHandler filter"}:n?.enabled?{open:!0}:this.checkIfResolverShouldBeOpenByResolverConfig(r)}checkIfResolverShouldBeOpenByResolverConfig(e){if(!e.enabled)return{open:!1,reason:"Intent Resolver is disabled. Raising intent to first found handler"};return this.glueController.clientGlue.appManager.application(e.appName)?{open:!0}:{open:!1,reason:`Application with name ${e.appName} not found`}}async filterHandlers(e,t,r,n){if(this.logger?.trace(`[${t}] Receive 'filterHandlers' command with request: ${JSON.stringify(e)}`),!r)return ioError.raiseError("Cannot preform 'filterHandlers' - callerId is not defined");const{filterHandlersRequest:i,resolverConfig:o,embeddedResolverConfig:s}=e,a=await this.getIntents(t),c=this.filterHandlersBy(a,i);if(!c?.length)return{handlers:[]};const{open:l,reason:u}=this.checkIfResolverShouldBeOpenedForFilterHandlers(c,i,o,s);if(!l)return this.logger?.trace(`[${t}] Intent Resolver UI won't be used. Reason: ${u}`),{handlers:c};const d=i.timeout||DEFAULT_PICK_HANDLER_BY_TIMEOUT_MS;if(s?.enabled)return this.logger?.trace(`[${t}] Handling 'filterHandlers' with embedded intent resolver`),PromiseWrap(()=>this.handleFilterHandlersWithEmbeddedResolver({commandId:t,handlerFilter:i,initialCaller:s.initialCaller,timeout:d}),d,`${ERRORS.TIMEOUT_HIT} - waited ${d}ms for 'filterHandlers' to resolve`);const h={instanceId:void 0};return{handlers:[await PromiseWrap(()=>this.legacyResolverController.startResolverApp({request:i,resolverConfig:o,commandId:t,callerId:this.getCallerIdByCallerType(r,n),resolverInstance:h,method:"filterHandlers"}),d,`Timeout of ${d}ms hit for 'filterHandlers' request with filter: ${JSON.stringify(e.filterHandlersRequest)}`)]}}async handleFilterHandlersWithEmbeddedResolver({commandId:e,handlerFilter:t,initialCaller:r,timeout:n}){const i={commandId:e,config:{handlerFilter:t,timeout:n},methodResponseTimeoutMs:n,initialCaller:r},o=await this.uiController.openResolver(i);o.isClosed&&ioError.raiseError(`${ERRORS.USER_CANCELLED}`),o.isExpired&&ioError.raiseError(`${ERRORS.TIMEOUT_HIT} - waited ${n}ms for user to choose an intent handler`);const{handler:s,intent:a}=o.userChoice??{};if(!s)return ioError.raiseError(`${ERRORS.HANDLER_NOT_FOUND}`);if(!a)return ioError.raiseError(`${ERRORS.INTENT_NOT_FOUND} for handlerFilter: ${JSON.stringify(t)}`);if(!!o.userChoice?.userSettings.preserveChoice)try{this.logger?.trace(`[${e}] - User wants to preserve the chosen of handler: ${JSON.stringify(s)}`);const n={applicationNames:t.applicationNames,contextTypes:t.contextTypes,resultType:t.resultType};await this.preserveUserChoice({initialCaller:r,commandId:e,handler:s,intentName:a,filter:n})}catch(t){this.logger?.warn(`[${e}] - Prefs API threw the following error: ${t}. Handler won't be preserved`)}return{handlers:[s]}}filterHandlersBy(e,t){const r=e.filter(e=>{if(!t.intent||t.intent===e.name){if(t.excludeList&&(e.handlers=this.excludeIntentHandlers(e,t.excludeList)),t.resultType){const r=e.handlers.filter(e=>e.resultType&&e.resultType===t.resultType);if(!r.length)return;e.handlers=r}if(t.contextTypes){const r=e.handlers.filter(e=>t.contextTypes?.every(t=>e.contextTypes?.includes(t)));if(!r.length)return;e.handlers=r}if(t.applicationNames){const r=e.handlers.filter(e=>t.applicationNames?.includes(e.applicationName));if(!r.length)return;e.handlers=r}return e}}),n=r.map(e=>e.handlers).flat(1);return n.filter((e,t)=>t===n.findIndex(t=>e.instanceId?e.instanceId===t.instanceId:!t.instanceId&&t.applicationName===e.applicationName))}excludeIntentHandlers(e,t){return e.handlers.filter(e=>!t.some(t=>"applicationName"in t?t.applicationName===e.applicationName:"instanceId"in t&&t.instanceId===e.instanceId))}async getIntentsByHandler(e,t){this.logger?.log(`[${t}] - Receive 'getIntents' command with request: ${JSON.stringify(e)}`);const r=runDecoderWithIOError(intentHandlerDecoder,e),n=await this.getIntents(t);clearNullUndefined(r),this.logger?.info(`[${t}] - extracting valid intents for the passed handler`);const i=this.extractIntentsWithInfoByHandler(n,r);return this.logger?.info(`[${t}] - returning intents for handler ${JSON.stringify(e)}`),{intents:i}}isHandlerValid(e,t){return Object.keys(e).every(r=>"contextTypes"===r?e.contextTypes?.every(e=>t.contextTypes?.includes(e)):t[r]===e[r])}extractIntentsWithInfoByHandler(e,t){return e.reduce((e,r)=>(r.handlers.forEach(n=>{if(!this.isHandlerValid(t,n))return;const i={intent:r.name,contextTypes:n.contextTypes,description:n.applicationDescription,displayName:n.displayName,icon:n.applicationIcon,resultType:n.resultType};e.push(i)}),e),[])}getCallerIdByCallerType(e,t){return"plugin"===t?this.glueController.me.instance??"":e}}const channelOperationDecoder=oneOf$1(constant$2("appHello"),constant$2("addChannel"),constant$2("removeChannel"),constant$2("operationCheck"),constant$2("getMyChannel"),constant$2("getWindowIdsOnChannel"),constant$2("getWindowIdsWithChannels"),constant$2("joinChannel"),constant$2("restrict"),constant$2("getRestrictions"),constant$2("restrictAll"),constant$2("notifyChannelsChanged"),constant$2("leaveChannel"),constant$2("requestChannelSelector"),constant$2("getMode")),leaveChannelDecoder=object$2({windowId:nonEmptyStringDecoder$2,channelName:optional$3(nonEmptyStringDecoder$2)}),channelsChangedDecoder=object$2({windowId:nonEmptyStringDecoder$2,channelNames:array$3(nonEmptyStringDecoder$2)}),modeDecoder=oneOf$1(constant$2("single"),constant$2("multi")),getChannelsModeDecoder=object$2({mode:modeDecoder}),channelFDC3DisplayMetadataDecoder=object$2({color:optional$3(nonEmptyStringDecoder$2),icon:optional$3(nonEmptyStringDecoder$2),name:optional$3(nonEmptyStringDecoder$2),glyph:optional$3(nonEmptyStringDecoder$2)}),channelFdc3MetaDecoder=object$2({id:nonEmptyStringDecoder$2,displayMetadata:optional$3(channelFDC3DisplayMetadataDecoder)}),channelMetaDecoder=object$2({color:nonEmptyStringDecoder$2,fdc3:optional$3(channelFdc3MetaDecoder)}),channelDefinitionDecoder=object$2({name:nonEmptyStringDecoder$2,meta:channelMetaDecoder,data:optional$3(anyJson$2())}),removeChannelDataDecoder=object$2({name:nonEmptyStringDecoder$2}),getMyChanelResultDecoder=object$2({channel:optional$3(nonEmptyStringDecoder$2)}),getWindowIdsOnChannelDataDecoder=object$2({channel:nonEmptyStringDecoder$2}),getWindowIdsOnChannelResultDecoder=object$2({windowIds:array$3(nonEmptyStringDecoder$2)}),getWindowIdsWithChannelsResultDecoder=object$2({windowIdsWithChannels:array$3(object$2({application:nonEmptyStringDecoder$2,channel:optional$3(nonEmptyStringDecoder$2),windowId:nonEmptyStringDecoder$2}))}),windowWithChannelFilterDecoder=object$2({application:optional$3(nonEmptyStringDecoder$2),channels:optional$3(array$3(nonEmptyStringDecoder$2)),windowIds:optional$3(array$3(nonEmptyStringDecoder$2))}),wrappedWindowWithChannelFilterDecoder=object$2({filter:optional$3(windowWithChannelFilterDecoder)}),joinChannelDataDecoder=object$2({channel:nonEmptyStringDecoder$2,windowId:nonEmptyStringDecoder$2}),channelRestrictionConfigWithWindowIdDecoder=object$2({name:nonEmptyStringDecoder$2,read:boolean$3(),write:boolean$3(),windowId:nonEmptyStringDecoder$2}),restrictionConfigDataDecoder=object$2({config:channelRestrictionConfigWithWindowIdDecoder}),getRestrictionsDataDecoder=object$2({windowId:nonEmptyStringDecoder$2}),restrictionsConfigDecoder=object$2({read:boolean$3(),write:boolean$3(),windowId:nonEmptyStringDecoder$2}),restrictAllDataDecoder=object$2({restrictions:restrictionsConfigDecoder}),channelRestrictionsDecoder=object$2({name:nonEmptyStringDecoder$2,read:boolean$3(),write:boolean$3(),windowId:optional$3(nonEmptyStringDecoder$2)}),restrictionsDecoder=object$2({channels:array$3(channelRestrictionsDecoder)}),requestChannelSelectorConfigDecoder=object$2({windowId:nonEmptyStringDecoder$2,channelsNames:array$3(nonEmptyStringDecoder$2)}),appHelloDataDecoder=object$2({windowId:nonEmptyStringDecoder$2}),appHelloSuccessDecoder=object$2({mode:modeDecoder,channels:array$3(nonEmptyStringDecoder$2),restrictions:array$3(channelRestrictionsDecoder)});class ChannelsController{glueController;sessionController;workspacesController;mode;operations={appHello:{name:"appHello",dataDecoder:appHelloDataDecoder,execute:this.handleAppHello.bind(this),resultDecoder:appHelloSuccessDecoder},addChannel:{name:"addChannel",execute:this.addChannel.bind(this),dataDecoder:channelDefinitionDecoder},removeChannel:{name:"removeChannel",execute:this.removeChannel.bind(this),dataDecoder:removeChannelDataDecoder},getMyChannel:{name:"getMyChannel",execute:async()=>{},resultDecoder:getMyChanelResultDecoder},getWindowIdsOnChannel:{name:"getWindowIdsOnChannel",execute:this.handleGetWindowIdsOnChannel.bind(this),dataDecoder:getWindowIdsOnChannelDataDecoder,resultDecoder:getWindowIdsOnChannelResultDecoder},getWindowIdsWithChannels:{name:"getWindowIdsWithChannels",execute:this.handleGetWindowIdsWithChannels.bind(this),dataDecoder:wrappedWindowWithChannelFilterDecoder,resultDecoder:getWindowIdsWithChannelsResultDecoder},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)},joinChannel:{name:"joinChannel",dataDecoder:joinChannelDataDecoder,execute:this.handleJoinChannel.bind(this)},restrict:{name:"restrict",dataDecoder:restrictionConfigDataDecoder,execute:this.restrict.bind(this)},getRestrictions:{name:"getRestrictions",dataDecoder:getRestrictionsDataDecoder,execute:this.getRestrictions.bind(this),resultDecoder:restrictionsDecoder},restrictAll:{name:"restrictAll",dataDecoder:restrictAllDataDecoder,execute:this.restrictAll.bind(this)},notifyChannelsChanged:{name:"notifyChannelsChanged",execute:this.handleChannelsChanged.bind(this),dataDecoder:channelsChangedDecoder},leaveChannel:{name:"leaveChannel",dataDecoder:leaveChannelDecoder,execute:this.handleLeaveChannel.bind(this)},requestChannelSelector:{name:"requestChannelSelector",dataDecoder:requestChannelSelectorConfigDecoder,execute:this.handleRequestChannelSelector.bind(this)},getMode:{name:"getMode",resultDecoder:getChannelsModeDecoder,execute:this.handleGetMode.bind(this)}};constructor(e,t,r){this.glueController=e,this.sessionController=t,this.workspacesController=r}get logger(){return logger.get("channels.controller")}async start(e){const t=e.channels.definitions;this.logger?.trace("initializing channels"),this.mode=e.channels.mode,this.logger?.trace(`initializing channels with mode: ${this.mode}`),await this.setupChannels(t),this.logger?.trace("initialization is completed")}ready(){return Promise.resolve()}async handleControl(e){const t=e.data,r=e.commandId,n=e.callerId,i=channelOperationDecoder.run(e.operation);if(!i.ok)return ioError.raiseError(`This channels request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(i.error)}`);const o=i.result,s=this.operations[o].dataDecoder?.run(t);if(s&&!s.ok)return ioError.raiseError(`Channels request for ${o} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(s.error)}`);this.logger?.debug(`[${r}] ${o} command is valid with data: ${JSON.stringify(t)}`);const a=await this.operations[o].execute(t,r,n),c=this.operations[o].resultDecoder?.run(a);return c&&!c.ok?ioError.raiseError(`Channels request for ${o} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(c.error)}`):(this.logger?.trace(`[${r}] ${o} command was executed successfully`),a)}handleClientUnloaded(e,t){this.logger?.trace(`[${e}] - Received client unloaded event for windowId: ${e}`);this.sessionController.getEjectedWindowIds().includes(e)?this.logger?.trace(`[${e}] - A workspace window with ID ${e} is being ejected or brought back to workspace. Keeping track of it.`):t&&!t.closed||(this.sessionController.removeEjectedWindowId(e),this.sessionController.removeWindowChannelData(e),this.logger?.trace(`[${e}] - Client unloaded event processed. Removed from Session Storage successfully`))}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}async handleAppHello({windowId:e},t){this.logger?.trace(`[${t}] - Received 'appHello' message for window with ID: ${e}`);this.checkIfValidWindowOrInteropInstanceId(e)||ioError.raiseError(`[${t}] - Cannot complete 'appHello' operation - received invalid window ID: ${e}`);const r=this.sessionController.getWindowChannelData(e);return this.logger?.trace(`[${t}] - Session data for window with ID ${e}: ${JSON.stringify(r)}`),{mode:this.mode,channels:r?.channels||[],restrictions:r?.restrictions||[]}}async handleLeaveChannel(e,t){this.trace(`[${t}] handling leaveChannel command with windowId: ${e.windowId}`,t);this.checkIfValidWindowOrInteropInstanceId(e.windowId)||ioError.raiseError(`[${t}] - Cannot complete 'leaveChannel' operation - received invalid window ID: ${e.windowId}`),this.removeChannelsFromSessionStorage(e.windowId,e.channelName),await this.glueController.callWindow("channels",this.operations.leaveChannel,e,{instance:e.windowId}),this.trace(`[${t}] successfully left the channel on window with ID "${e.windowId}"`,t)}removeChannelsFromSessionStorage(e,t){const r=this.sessionController.getWindowChannelData(e);if(!r?.channels?.length)return void this.logger?.trace(`No channels data found for window with id: ${e}, nothing to remove`);const n=t?r.channels.filter(e=>e!==t):[];this.sessionController.setChannelsForWindow(e,n)}async setupChannels(e){await Promise.all(e.map(e=>this.addChannel(e)))}async addChannel(e,t){this.trace(`[${t}] handling addChannel command with a valid name: ${e.name}, color: ${e.meta.color} and data: ${JSON.stringify(e.data)}`,t);const r={name:e.name,meta:e.meta,data:e.data||{}},n=this.createContextName(r.name);this.trace(`[${t}] setting a new channel context with name: ${n}`,t),await this.glueController.setContext(n,r),this.trace(`[${t}] channel context with name: ${n} created successfully`,t)}async removeChannel({name:e},t){this.trace(`[${t}] handling removeChannel command with a valid name: ${e}`,t);const r=this.createContextName(e);await this.glueController.destroyContext(r),this.trace(`[${t}] channel context with name: ${r} destroyed successfully`,t)}async getWindowChannel(e,t){if(!await this.checkIfAppHelloSupported(e))return this.trace(`[${t}] client is outdated and does not support platform session storage, falling back to window call`,t),this.glueController.callWindow("channels",this.operations.getMyChannel,{},{instance:e});const r=this.sessionController.getWindowChannelData(e),n=r?.channels?.[0];return{channel:n}}async handleGetWindowIdsOnChannel({channel:e},t){this.trace(`[${t}] handling getWindowIdsOnChannel command with channel: ${e}`,t);const r=this.glueController.getLocalServers().reduce((e,{windowId:t})=>t?[...e,t]:e,[]);this.trace(`[${t}] compiled a list of the IDs of all the windows that will be called: [${r.join(", ")}]`,t);const n=await Promise.all(r.map(async e=>{const{channel:r}=await this.getWindowChannel(e,t);return{channel:r,windowId:e}})),i=n.filter(t=>t.channel===e).map(({windowId:e})=>e);return this.trace(`[${t}] compiled a list of all windowIds that are on the "${e}" channel and returning it to the caller: [${i.join(", ")}]`,t),{windowIds:i}}async handleGetWindowIdsWithChannels({filter:e},t){this.trace(`[${t}] handling getWindowIdsWithChannels command with filter: ${JSON.stringify(e)}`,t);const r=this.glueController.getLocalServers(),n=this.glueController.getAllApplicationNames(),i=r.filter(({windowId:e})=>e);this.trace(`[${t}] compiled a list of the IDs of all the windows that will be called: [${i.map(({windowId:e})=>e).join(", ")}]`,t);const o=await Promise.all(i.map(async({applicationName:e,windowId:r})=>{const{channel:i}=await this.getWindowChannel(r,t);return{application:e&&n.includes(e)?e:"no-app-window",...i?{channel:i}:{},windowId:r}}));let s=o;return e?(e.application&&(this.trace(`[${t}] filtering windows by application: ${e.application}`,t),s=s.filter(({application:t})=>t===e.application)),e.channels&&(this.trace(`[${t}] filtering windows by channels: [${e.channels.join(", ")}]`,t),s=s.filter(({channel:t})=>t&&e.channels?.includes(t))),e.windowIds&&(this.trace(`[${t}] filtering windows by windowIds: [${e.windowIds.join(", ")}]`,t),s=s.filter(({windowId:t})=>e.windowIds?.includes(t))),this.trace(`[${t}] compiled a list of all windowIds with channels and returning it to the caller: ${JSON.stringify(s)}`,t),{windowIdsWithChannels:s}):(this.trace(`[${t}] compiled a list of all windowIds with channels and returning it to the caller: ${JSON.stringify(s)}`,t),{windowIdsWithChannels:s})}async handleChannelsChanged(e,t){this.trace(`[${t}] handling notifyChannelsChanged command with data: ${JSON.stringify(e)}`,t),this.glueController.pushSystemMessage("windows","notifyChannelsChanged",e),this.trace(`[${t}] successfully notified all windows about the channel change`,t)}async handleRequestChannelSelector(e,t){this.trace(`[${t}] handling requestChannelSelector command with windowId: ${e.windowId} and initial channels: ${e.channelsNames?.join(", ")}`,t);const r=this.sessionController.getWorkspaceClientById(e.windowId);if(!r)return ioError.raiseError(`Failed to display channel selector on window with ID "${e.windowId}", because the provided windowId is not a workspace window.`);await this.workspacesController.showChannelsLink({windowId:r.windowId,frameId:r.frameId,channelsNames:e.channelsNames},t),this.trace(`[${t}] successfully notified all windows about the channel change`,t)}async handleGetMode(){return{mode:this.mode}}async handleJoinChannel({channel:e,windowId:t},r){this.trace(`[${r}] handling joinChannel command with channel: ${e} and windowId: ${t}`,r);this.checkIfValidWindowOrInteropInstanceId(t)||ioError.raiseError(`[${r}] - Cannot complete 'joinChannel' operation - received invalid window ID: ${t}`),"single"===this.mode?this.sessionController.setChannelsForWindow(t,[e]):this.sessionController.setAdditionalChannelForWindow(t,e),await this.glueController.callWindow("channels",this.operations.joinChannel,{channel:e,windowId:t},{instance:t}),this.trace(`[${r}] successfully joined "${e}" channel on window with ID "${t}"`,r)}createContextName(e){return`${ChannelContextPrefix}${e}`}trace(e,t){t&&this.logger?.trace(e)}async restrict({config:e},t,r){this.trace(`[${t}] received restrict command with config ${JSON.stringify(e)} from callerId: ${r}`,t);this.checkIfValidWindowOrInteropInstanceId(e.windowId)||ioError.raiseError(`[${t}] - Cannot complete 'restrict' operation - received invalid window ID: ${e.windowId}`),this.sessionController.addChannelRestrictionsByWindowId(e.windowId,e),await this.glueController.callWindow("channels",this.operations.restrict,{config:e},{instance:e.windowId})}async getRestrictions({windowId:e},t,r){this.trace(`[${t}] received getRestrictions command for window with id ${e} from callerId: ${r}`,t);this.checkIfValidWindowOrInteropInstanceId(e)||ioError.raiseError(`[${t}] - Cannot complete 'getRestrictions' operation - received invalid window ID: ${e}`);if(!await this.checkIfAppHelloSupported(e))return this.logger?.trace(`[${t}] - Client's restrictions are saved in its own session storage. Calling it to get restrictions.`),this.glueController.callWindow("channels",this.operations.getRestrictions,{windowId:e},{instance:e});const n=this.sessionController.getWindowChannelData(e);return{channels:n?.restrictions||[]}}async restrictAll({restrictions:e},t,r){this.trace(`[${t}] received restrictAll command with config ${JSON.stringify(e)} from callerId: ${r}`,t);return this.checkIfValidWindowOrInteropInstanceId(e.windowId)||ioError.raiseError(`[${t}] - Cannot complete 'restrictAll' operation - received invalid window ID: ${e.windowId}`),this.addAllChannelRestrictionsInSessionStorage(e.windowId,e),this.glueController.callWindow("channels",this.operations.restrictAll,{restrictions:e},{instance:e.windowId})}addAllChannelRestrictionsInSessionStorage(e,t){const r=this.glueController.getAllContexts().filter(e=>e.startsWith(ChannelContextPrefix)).map(e=>e.replace(ChannelContextPrefix,"")),n=r.map(e=>({name:e,...t}));this.sessionController.addAllChannelsRestrictionsByWindowId(e,n)}checkIfValidWindowOrInteropInstanceId(e){if(this.glueController.isValidWindowId(e))return!0;if(this.glueController.platformWindowId===e)return!0;return!!this.glueController.getLocalServers().some(t=>t.instance===e)}async checkIfAppHelloSupported(e){try{return(await this.glueController.checkClientOperationSupport("channels",this.operations.appHello,{instance:e})).isSupported}catch(t){return this.logger?.trace(`Client with windowId: ${e} does NOT support 'appHello' message.`),!1}}}class FramesController{sessionController;glueController;ioc;config;defaultBounds;frameSummaryOperation;locks={};defaultFrameHelloTimeoutMs=15e3;_handleUnload;constructor(e,t,r){this.sessionController=e,this.glueController=t,this.ioc=r}get myFrameId(){return this.glueController.platformWindowId}stop(){this._handleUnload&&window.removeEventListener("pagehide",this._handleUnload)}async start(e,t,r){this.config=e,this.defaultBounds=t,this.frameSummaryOperation=r}async openFrame(e,t){const r="object"==typeof e?e.bounds??{}:{},n=r.top??this.defaultBounds.top,i=r.left??this.defaultBounds.left,o=r.width??this.defaultBounds.width,s=r.height??this.defaultBounds.height,a="object"==typeof e&&e?.frameId?e.frameId:`g42-${nanoid$3(10)}`;if(this.sessionController.getAllFrames().some(e=>e.windowId===a))return ioError.raiseError(`Cannot open a frame with id: ${a}, because a frame with this id already exists`);const c={windowId:a,active:!1,isPlatform:!1,layoutComponentId:t},l=`left=${i},top=${n},width=${o},height=${s}`,u=(await this.getWorkspacesUrls()).workspacesUrl.current,d=u.includes("?")?`${u}&emptyFrame=true`:`${u}?emptyFrame=true`;if(!window.open(d,c.windowId,l))return ioError.raiseError("Cannot open a new workspace frame, because the user has not allowed popups or uses a blocker");this.sessionController.saveFrameData(c);try{return await this.waitHello(c.windowId),{windowId:c.windowId}}catch(e){return delete this.locks[c.windowId],ioError.raiseError("Cannot open a new frame, because the workspace frame app did not send a hello in time")}}async closeFrame(e){if(this.myFrameId===e)return ioError.raiseError("Cannot close the platform frame, because it is the current frame");this.sessionController.getFrameData(e)&&(this.handleFrameDisappeared(e),window.open(void 0,e)?.close())}processNewHello(e){this.sessionController.getFrameData(e)&&(this.sessionController.setFrameActive(e),this.locks[e]?.lift())}handleFrameDisappeared(e){this.sessionController.getFrameData(e)&&(this.sessionController.removeFrameData(e),this.clearAllWorkspaceWindows(e))}getAll(){return this.sessionController.getAllFrames().filter(e=>e.active).map(e=>({windowId:e.windowId}))}async getFrameInstance(e){if(e){if(["frameId","itemId","newFrame"].reduce((t,r)=>(e[r]&&t.push(r),t),[]).length>1)return ioError.raiseError(`Cannot retrieve the frame, because of over-specification: the provided selection object must have either 1 or none of the possible properties: ${JSON.stringify(e)}`)}const t=this.getAll();if(e?.frameId){const r=t.find(t=>t.windowId===e.frameId);return r||ioError.raiseError(`Cannot retrieve a frame with Id: ${e.frameId}, because it is not known by the platform`)}return e?.itemId?this.getFrameByItemId(e.itemId,t):e?.newFrame?this.openFrame(e.newFrame):t.length?this.getLastOpenedFrame():this.openFrame()}getPlatformFrameSessionData(){return this.sessionController.getAllFrames().find(e=>e.isPlatform)}getFrameConfig(e){return this.sessionController.getAllFrames().find(t=>t.windowId===e)}clearAllWorkspaceWindows(e){this.sessionController.pickWorkspaceClients(t=>t.frameId===e).forEach(e=>{this.ioc.applicationsController.unregisterWorkspaceApp({windowId:e.windowId})})}async waitHello(e){return PromisePlus(t=>{this.locks[e]={lift:t}},this.defaultFrameHelloTimeoutMs,"Frame hello timed out")}getLastOpenedFrame(){const e=this.sessionController.getAllFrames().filter(e=>e.active);return e[e.length-1]}async getFrameByItemId(e,t){if(!t.length)return ioError.raiseError(`Cannot get frame by item id for: ${e}, because not frames were found`);for(const r of t){if("none"!==(await this.glueController.callFrame(this.frameSummaryOperation,{itemId:e},r.windowId)).id)return r}return ioError.raiseError(`Cannot find frame for item: ${e}`)}getWorkspacesUrls(){return new URL(window.location.href).protocol.includes("extension")?new Promise(e=>{chrome.storage.local.get("workspacesUrl",t=>{e(t)})}):Promise.resolve({workspacesUrl:{current:this.config.src,default:this.config.src}})}}class WorkspaceHibernationWatcher{session;sequelizer;workspacesController;settings;running;constructor(e,t){this.session=e,this.sequelizer=t}get logger(){return logger.get("workspaces.hibernation")}stop(){this.running=!1}start(e,t){this.logger?.trace(`starting the hibernation watcher with following settings: ${JSON.stringify(this.settings)}`),this.running=!0,this.workspacesController=e,this.settings=t;const r=this.session.exportClearTimeouts();this.settings?.idleWorkspaces?.idleMSThreshold&&r.forEach(e=>this.buildTimer(e.workspaceId)),this.logger?.trace("The hibernation watcher has started successfully")}notifyEvent(e){"window"===e.type&&this.handleWorkspaceWindowEvent(e),"workspace"===e.type&&this.handleWorkspaceEvent(e)}handleWorkspaceWindowEvent(e){("opened"===e.action||"added"===e.action)&&(this.sequelizer.enqueue(()=>this.checkMaximumAmountCore()),this.addTimersForWorkspacesInFrame(e.payload.windowSummary.config.frameId))}handleWorkspaceEvent(e){const t="selected"===e.action,r="lock-configuration-changed"===e.action,n=e.payload;if(!("selected"===e.action||"opened"===e.action||"lock-configuration-changed"===e.action))return;this.sequelizer.enqueue(()=>this.checkMaximumAmountCore());const i=n.workspaceSummary.config.allowSystemHibernation;if(!(t||r&&i))return;const o=this.session.getTimeout(n.workspaceSummary.id);o&&(clearTimeout(o),this.session.removeTimeout(n.workspaceSummary.id)),this.addTimersForWorkspacesInFrame(n.frameSummary.id)}compare(e,t){return e.config.lastActive>t.config.lastActive?1:e.config.lastActive<t.config.lastActive?-1:0}async checkMaximumAmountCore(){const e=this.settings?.maximumActiveWorkspaces?.threshold;if(this.logger?.trace(`Checking for maximum active workspaces rule. The threshold is ${e}`),"number"!=typeof e)return;const t=nanoid$3(10),r=(await this.workspacesController.getAllWorkspacesSummaries({},t)).summaries.map(e=>this.workspacesController.getWorkspaceSnapshot({itemId:e.id},t)),n=(await Promise.all(r)).filter(e=>!this.isWorkspaceHibernated(e.config)&&!this.isWorkspaceEmpty(e)),i=n.filter(e=>this.isSystemHibernationAllowed(e));if(n.length<=e)return;this.logger?.trace(`Found ${i.length} eligible for hibernation workspaces`);const o=i.sort(this.compare).slice(0,n.length-e).map(e=>this.tryHibernateWorkspace(e.id));await Promise.all(o)}async tryHibernateWorkspace(e){try{const t=await this.workspacesController.getWorkspaceSnapshot({itemId:e},nanoid$3(10));if(!this.canBeHibernated(t))return;this.logger?.trace(`trying to hibernate workspace ${e}`),await this.workspacesController.hibernateWorkspace({workspaceId:e},nanoid$3(10)),this.logger?.trace(`workspace ${e} was hibernated successfully`)}catch(e){this.logger?.trace(e)}}canBeHibernated(e){const t=this.isWorkspaceHibernated(e.config),r=this.isWorkspaceSelected(e.config),n=this.isWorkspaceEmpty(e),i=this.isSystemHibernationAllowed(e);return!t&&!r&&!n&&i}isWorkspaceHibernated(e){return e.isHibernated}isWorkspaceSelected(e){return e.isSelected}isWorkspaceEmpty(e){return!e.children.length}isSystemHibernationAllowed(e){const{allowSystemHibernation:t}=e.config;return"boolean"!=typeof t||t}async getWorkspacesInFrame(e){const t=(await this.workspacesController.getAllWorkspacesSummaries({},nanoid$3(10))).summaries.reduce((t,r)=>(r.config.frameId===e&&t.push(this.workspacesController.getWorkspaceSnapshot({itemId:r.id},nanoid$3(10))),t),[]);return await Promise.all(t)}async addTimersForWorkspacesInFrame(e){if(!this.settings?.idleWorkspaces?.idleMSThreshold)return;(await this.getWorkspacesInFrame(e)).forEach(e=>{this.canBeHibernated(e)&&!this.session.getTimeout(e.id)&&(this.buildTimer(e.id),this.logger?.trace(`Starting workspace idle timer ( ${this.settings?.idleWorkspaces?.idleMSThreshold}ms ) for workspace ${e.id}`))})}buildTimer(e){const t=window.setTimeout(()=>{this.running&&(this.logger?.trace(`Timer triggered will try to hibernated ${e}`),this.tryHibernateWorkspace(e),this.session.removeTimeout(e))},this.settings?.idleWorkspaces?.idleMSThreshold);this.session.saveTimeout(e,t)}}class SystemController{session;workspacesController;glueController;pluginsController;profileData;environment;base={};started=!1;errorPort=errorChannel.port2;registry=CallbackRegistryFactory$2();platformOperations=["cleanupClientsOnWorkspaceFrameUnregister"];operations={getEnvironment:{name:"getEnvironment",resultDecoder:anyDecoder,execute:this.handleGetEnvironment.bind(this)},getBase:{name:"getBase",resultDecoder:anyDecoder,execute:this.handleGetBase.bind(this)},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)},workspacesInitCheck:{name:"workspacesInitCheck",resultDecoder:workspacesInitCheckResultDecoder,execute:this.handleWorkspacesInitCheck.bind(this)},clientError:{name:"clientError",dataDecoder:clientErrorDataDecoder,execute:this.handleClientError.bind(this)},systemHello:{name:"systemHello",resultDecoder:systemHelloSuccessDecoder,execute:this.handleSystemHello.bind(this)},getProfileData:{name:"getProfileData",execute:this.handleGetProfileData.bind(this)}};constructor(e,t,r,n){this.session=e,this.workspacesController=t,this.glueController=r,this.pluginsController=n}get logger(){return logger.get("system.controller")}handlePlatformShutdown(){this.started=!1,this.registry.clear()}async start(e){this.environment=e.environment,this.base={workspaces:{frameCache:e.workspacesFrameCache},workspacesFrameCache:e.workspacesFrameCache,communicationId:this.session.getSystemSettings()?.systemInstanceId,platformVersion:version$1,connectionProtocolVersion:connectionProtocolVersion,fdc3:{webProxyUrl:FDC3ProxyUrl}},this.profileData=e.profileData,this.errorPort.onmessage=e=>{this.registry.execute("platform-error",{message:e.data})},this.started=!0}ready(){return Promise.resolve()}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this system control message, because the controller has not been started");const t=e.data,r=e.commandId,n=e.callerId,i=systemOperationTypesDecoder.run(e.operation);if(!i.ok)return ioError.raiseError(`This system request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(i.error)}`);const o=i.result,s=this.operations[o].dataDecoder?.run(t);if(s&&!s.ok)return ioError.raiseError(`System request for ${o} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(s.error)}`);this.logger?.debug(`[${r}] ${o} command is valid with data: ${JSON.stringify(t)}`);const a=await this.operations[o].execute(t,r,n),c=this.operations[o].resultDecoder?.run(a);return c&&!c.ok?ioError.raiseError(`System request for ${o} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(c.error)}`):(this.logger?.trace(`[${r}] ${o} command was executed successfully`),a)}onPlatformError(e){return this.registry.add("platform-error",e)}onClientError(e){return this.registry.add("client-error",e)}setProfileData(e){this.profileData=e}async handleOperationCheck(e){const t=Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase()),r=this.platformOperations.some(t=>t.toLowerCase()===e.operation.toLowerCase());return{isSupported:t||r}}async handleGetEnvironment(){return this.environment}async handleGetProfileData(){if(!this.profileData)return;return{...this.profileData,plugins:this.pluginsController.registeredPlugins.map(e=>({name:e.name,version:e.version}))}}async handleGetBase(){return this.base}async handleWorkspacesInitCheck(){return{initialized:this.workspacesController.started}}async handleClientError({message:e},t,r){this.logger?.trace(`[${t}] received clientError command with message ${e} from callerId: ${r}`),this.glueController.clientGlue?r&&r===this.glueController.me.instance?this.registry.execute("platform-error",{message:e}):this.registry.execute("client-error",{message:e,callerId:r}):this.registry.execute("platform-error",{message:e})}async handleSystemHello(){return{isClientErrorOperationSupported:!0}}}class AppDirectory{remoteWatcher;manager;cache;unsubFuncs=[];maxAllowedApplicationsInStore=1e4;baseEventFlushDurationMs=10;appsStateChange;sequelizer;isManagerConfigured;constructor(e,t,r){this.remoteWatcher=e,this.manager=t,this.cache=r}stop(){this.unsubFuncs.forEach(e=>e()),this.unsubFuncs=[]}async start(e){if(this.logger?.trace("Starting the application directory"),this.appsStateChange=e.appsStateChange,this.sequelizer=e.sequelizer,await this.cache.start(e.config.remote),e.config.local?.length&&(this.logger?.trace("Detected local applications, parsing..."),await this.processAppDefinitions(e.config.local,{type:"inmemory",mode:"merge"})),e.isManagerConfigured&&(this.isManagerConfigured=e.isManagerConfigured,this.setupManagerListeners(),this.logger?.trace("Detected manager configuration, starting the watcher...")),e.config.remote){this.logger?.trace("Detected remote app store configuration, starting the watcher...");try{await this.remoteWatcher.start(e.config.remote,e=>this.processAppDefinitions(e,{type:"remote",mode:"replace"}))}catch(e){return this.handleRemoteConnectionFailure(e)}}}processAppDefinitions(e,t){return this.sequelizer.enqueue(async()=>{const r=e.map(e=>this.parseDefinition(e)),n=[...await this.cache.getAllRemoteApps(),...await this.cache.getAllMemoryApps()],i=this[t.mode](n,r);if(i.readyApps.length>this.maxAllowedApplicationsInStore)return ioError.raiseError("Cannot save the app definitions, because the total number exceeds 10000, which is the limit.");const o="remote"===t.type?this.cache.saveRemoteApps.bind(this.cache):this.cache.saveMemoryApps.bind(this.cache);await o(i.readyApps),await this.announceApps(i)})}getAll(){return this.sequelizer.enqueue(async()=>{const e=new Map,t=await this.cache.getAllMemoryApps(),r=await this.cache.getAllRemoteApps(),n=this.isManagerConfigured?this.manager.getAllApps().map(this.parseDefinition):[];return r.forEach(t=>e.set(t.name,t)),n.forEach(t=>e.set(t.name,t)),t.forEach(t=>e.set(t.name,t)),Array.from(e.values())})}exportInMemory(){return this.sequelizer.enqueue(async()=>(await this.cache.getAllMemoryApps()).map(this.reverseParseDefinition))}removeInMemory(e){return this.sequelizer.enqueue(async()=>this.cache.removeMemoryApp(e))}merge(e,t){const r={readyApps:[],addedApps:[],changedApps:[],removedApps:[]},n=e.reduce((e,t)=>(e[t.name]=t,e),{});return t.forEach(e=>n[e.name]&&!objEqualFast(e,n[e.name])?(n[e.name]=e,void r.changedApps.push(e)):n[e.name]?void 0:(n[e.name]=e,void r.addedApps.push(e))),r.readyApps=Object.values(n),r}replace(e,t){const r={readyApps:[],addedApps:[],changedApps:[],removedApps:[]},n=e.reduce((e,t)=>(e[t.name]=t,e),{});return t.forEach(e=>{n[e.name]||r.addedApps.push(e),n[e.name]&&!objEqualFast(e,n[e.name])&&r.changedApps.push(e),n[e.name]&&(n[e.name].isChecked=!0)}),r.removedApps=e.filter(e=>!e.isChecked),r.readyApps=t,r}reverseParseDefinition(e){const{details:t,intents:r,hidden:n,...i}=e.userProperties;void 0!==r&&(i.intents=r),void 0!==n&&(i.hidden=n);const o={name:e.name,type:e.type,details:t,customProperties:i},s={title:e.title,version:e.version,icon:e.icon,caption:e.caption,intents:r,hidden:n,fdc3:e.fdc3};for(const[e,t]of Object.entries(s))void 0!==t&&(o[e]=t);return o}parseDefinition(e){const t=["name","title","version","customProperties","icon","caption","type"],r=Object.fromEntries(Object.entries(e).filter(([e])=>!t.includes(e))),{isFdc3:n}=fdc3.isFdc3Definition(e);let i;if(n)i=fdc3.parseToBrowserBaseAppData(e);else{const t=e.details;i={createOptions:t,type:e.type||"window",name:e.name,title:e.title,version:e.version,icon:e.icon,caption:e.caption,userProperties:{...r,...e.customProperties}},i.userProperties.details||(i.userProperties.details=t)}return Object.keys(i).forEach(e=>void 0===i[e]&&delete i[e]),i}get logger(){return logger.get("applications.remote.directory")}async announceApps(e){const t={appsAdded:e.addedApps,appsChanged:e.changedApps,appsRemoved:e.removedApps};this.logger?.trace(`announcing a change in the app directory state: ${JSON.stringify(t)}`),this.appsStateChange(t),await this.waitEventFlush()}setupManagerListeners(){const e=this.manager.onAppsAdded(e=>{this.announceApps({addedApps:e.map(this.parseDefinition),changedApps:[],removedApps:[],readyApps:[]}).catch(e=>this.logger?.warn(extractErrorMsg$1(e)))}),t=this.manager.onAppsDeleted(e=>{this.announceApps({addedApps:[],changedApps:[],removedApps:e.map(this.parseDefinition),readyApps:[]}).catch(e=>this.logger?.warn(extractErrorMsg$1(e)))}),r=this.manager.onAppsChanged(e=>{this.announceApps({addedApps:[],changedApps:e.map(this.parseDefinition),removedApps:[],readyApps:[]}).catch(e=>this.logger?.warn(extractErrorMsg$1(e)))});this.unsubFuncs.push(e,t,r)}waitEventFlush(){return new Promise(e=>setTimeout(e,this.baseEventFlushDurationMs))}async handleRemoteConnectionFailure(e){const t=await this.cache.getAllRemoteApps();if(!t?.length)return ioError.raiseError(`The connection to the remote app store failed and there are no cached entries, cannot continue. Error: ${extractErrorMsg$1(e)}`);this.logger?.warn(`The connection to the remote app store failed, but there are cached entries, continuing with the cached apps. Error: ${extractErrorMsg$1(e)}`)}}const defaultRemoteWatcherHeaders={"Content-Type":"application/json",Accept:"application/json"},defaultRemoteWatcherRequestTimeoutMS=3e3,fetchTimeout=(e,t=defaultFetchTimeoutMs,r=new AbortController)=>new Promise((n,i)=>{const o={signal:r.signal};let s=!1;const a=setTimeout(()=>{s=!0,i(new Error(`Fetch request for: ${JSON.stringify(e)} timed out at: ${t} milliseconds`)),r.abort()},t);fetch(e,o).then(e=>{s||(clearTimeout(a),n(e))}).catch(e=>{s||(clearTimeout(a),i(e))})});class RemoteWatcher{scheduler;handleApps;config;constructor(e){this.scheduler=e}async start(e,t){this.handleApps=t,this.config=this.prepareConfig(e);const r=this.doInitialRequest();if(this.configureScheduler(),this.config.waitInitialResponse)return this.logger?.info("Waiting for the initial response from the remote app store before proceeding"),void await r;r.catch(e=>this.logger?.error("The initial request to the remote app store failed",e))}getRequest(){const e=new Headers;for(const t in defaultRemoteWatcherHeaders)e.append(t,defaultRemoteWatcherHeaders[t]);for(const t in this.config.customHeaders)this.logger?.trace("Custom headers detected and set"),e.append(t,this.config.customHeaders[t]);const t={method:"GET",headers:e,mode:"cors",cache:"default"},r=this.config.getRequestInit?.({url:this.config.url,requestInit:t});return new Request(this.config.url,{...t,...r})}get logger(){return logger.get("applications.remote.directory")}prepareConfig(e){const t={...e,requestTimeout:e.requestTimeout??defaultRemoteWatcherRequestTimeoutMS,customHeaders:e.customHeaders??{},getRequestInit:e.getRequestInit??(()=>({})),waitInitialResponse:e.waitInitialResponse??!0};return t.cache?.enabled&&!t.pollingInterval?ioError.raiseError("Polling interval is required when cache is enabled"):t.pollingInterval&&t.pollingInterval<5e3?ioError.raiseError("Polling interval must be at least 5000ms"):t}configureScheduler(){if(!this.config.pollingInterval)return void this.logger?.info("Polling interval is not set, skipping scheduler setup");const e="applications:get:all";if(this.scheduler.checkEntryExists(e))return;const t={key:e,getRequest:()=>this.getRequest(),timeout:this.config.requestTimeout,refreshIntervalMS:this.config.pollingInterval,onData:this.processGetAllAppsUpdate.bind(this),onError:e=>this.logger?.error("Error during get all application definitions from scheduler",e)};this.scheduler.register(t)}async processGetAllAppsUpdate(e){if(!e||!Array.isArray(e.applications))return this.logger?.warn("The remote response was either empty or did not contain an applications collection");this.logger?.trace("There is a valid response from the app store, processing definitions...");const t=e.applications.reduce((e,t)=>{const r=allApplicationDefinitionsDecoder.run(t);return r.ok?e.push(t):this.logger?.warn(`Removing applications definition with name: ${t.name} from the remote response, because of validation error: ${JSON.stringify(r.error)}`),e},[]);await this.handleApps(t)}async doInitialRequest(){try{const e=this.getRequest(),t=await fetchTimeout(e,this.config.requestTimeout),r=await t.json();await this.processGetAllAppsUpdate(r)}catch(e){return ioError.raiseError("Error during initial request to get all applications",e)}}}class ServiceWorkerController{idbController;registry=CallbackRegistryFactory$2();_serviceWorkerRegistration;channel;_broadcastMessageHandler;constructor(e){this.idbController=e}get logger(){return logger.get("service.worker.web.platform")}get serviceWorkerRegistration(){return this._serviceWorkerRegistration?this._serviceWorkerRegistration:ioError.raiseError("Accessing missing service worker registration object. This is caused because the application is trying to raise a persistent notification, which requires a service worker. Please provide a service worker config when initializing GlueWebPlatform.")}shutdown(){this.channel?.removeEventListener("message",this._broadcastMessageHandler),this.registry.clear()}async connect(e){if(e.serviceWorker){if(this.logger?.info("Detected service worker definition, connecting..."),!e.serviceWorker.url&&void 0===e.serviceWorker.registrationPromise)return ioError.raiseError("The service worker config is defined, but it is missing a url or a registration promise, please provide one or the other");if(e.serviceWorker.url&&void 0!==e.serviceWorker.registrationPromise)return ioError.raiseError("The service worker is over-specified, there is both defined url and a registration promise, please provide one or the other");await this.prepareSwDb(),this._serviceWorkerRegistration=e.serviceWorker.url?await this.registerWorker(e.serviceWorker.url):await this.waitRegistration(e.serviceWorker.registrationPromise),this._serviceWorkerRegistration&&this.setUpBroadcastChannelConnection(),this.logger?.info("Service worker connection completed.")}}async showNotification(e,t){const r=Object.assign({},e,{title:void 0,clickInterop:void 0,actions:void 0});r.actions=e.actions?.map(e=>({action:e.action,title:e.title,icon:e.icon}));const n={focusPlatformOnDefaultClick:e.focusPlatformOnDefaultClick,clickInterop:e.clickInterop,actions:e.actions,id:t};r.data?r.data.glueData=n:r.data={glueData:n},await this.serviceWorkerRegistration.showNotification(e.title,r)}notifyReady(){this._serviceWorkerRegistration&&this.channel.postMessage({platformStarted:!0})}onNotificationClick(e){return this.registry.add("notification-click",e)}onNotificationClose(e){return this.registry.add("notification-close",e)}setUpBroadcastChannelConnection(){this.channel=new BroadcastChannel(serviceWorkerBroadcastChannelName),this._broadcastMessageHandler=this.broadcastMessageHandler.bind(this),this.channel.addEventListener("message",this._broadcastMessageHandler)}broadcastMessageHandler(e){const t=e.data,r=t?.messageType;if(r)if("ping"!==r){if("notificationClick"===r){const e=t.action,r=t.glueData;return void this.registry.execute("notification-click",{action:e,glueData:r})}if("notificationClose"===r){const e=t.action,r=t.glueData;return void this.registry.execute("notification-close",{action:e,glueData:r})}"notificationError"!==r||this.logger?.error(`Service worker error when raising notification: ${t.error}`)}else this.channel.postMessage({pong:!0})}async registerWorker(e){if("serviceWorker"in navigator)try{return await navigator.serviceWorker.register(e)}catch(e){const t="string"==typeof e?e:JSON.stringify(e.message);this.logger?.warn(t)}else this.logger?.warn(`A defined service worker has not been registered at ${e} because this browser does not support it.`)}async waitRegistration(e){if("function"!=typeof e.then||"function"!=typeof e.catch)return ioError.raiseError("The provided service worker registration promise is not a promise");const t=await e;return"function"!=typeof t.showNotification?ioError.raiseError("The provided registration promise is a promise, but it resolved with an object which does not appear to be a ServiceWorkerRegistration"):t}async prepareSwDb(){await this.idbController.clearServiceWorker(),await this.idbController.storeServiceWorker({platformUrl:window.location.href})}}const setNotificationDefaults=e=>{e.showToast="boolean"!=typeof e.showToast||e.showToast,e.showInPanel="boolean"!=typeof e.showInPanel||e.showInPanel,e.timestamp=void 0===e.timestamp?Date.now():e.timestamp,e.state=void 0===e.state?"Active":e.state},notificationsOperationDecoder=oneOf$1(constant$2("raiseNotification"),constant$2("requestPermission"),constant$2("getPermission"),constant$2("operationCheck"),constant$2("list"),constant$2("clear"),constant$2("click"),constant$2("clearAll"),constant$2("configure"),constant$2("getConfiguration"),constant$2("setState"),constant$2("clearOld"),constant$2("getActiveCount")),interopActionSettingsDecoder=object$2({method:nonEmptyStringDecoder$2,arguments:optional$3(anyJson$2()),target:optional$3(oneOf$1(constant$2("all"),constant$2("best")))}),glue42NotificationActionDecoder=object$2({action:string$4(),title:nonEmptyStringDecoder$2,icon:optional$3(string$4()),interop:optional$3(interopActionSettingsDecoder)}),notificationStateDecoder=oneOf$1(constant$2("Active"),constant$2("Acknowledged"),constant$2("Seen"),constant$2("Closed"),constant$2("Stale"),constant$2("Snoozed"),constant$2("Processing")),glue42NotificationOptionsDecoder=object$2({title:nonEmptyStringDecoder$2,clickInterop:optional$3(interopActionSettingsDecoder),actions:optional$3(array$3(glue42NotificationActionDecoder)),focusPlatformOnDefaultClick:optional$3(boolean$3()),badge:optional$3(string$4()),body:optional$3(string$4()),data:optional$3(anyJson$2()),dir:optional$3(oneOf$1(constant$2("auto"),constant$2("ltr"),constant$2("rtl"))),icon:optional$3(string$4()),image:optional$3(string$4()),lang:optional$3(string$4()),renotify:optional$3(boolean$3()),requireInteraction:optional$3(boolean$3()),silent:optional$3(boolean$3()),tag:optional$3(string$4()),timestamp:optional$3(nonNegativeNumberDecoder$2),vibrate:optional$3(array$3(number$4())),severity:optional$3(oneOf$1(constant$2("Low"),constant$2("None"),constant$2("Medium"),constant$2("High"),constant$2("Critical"))),showToast:optional$3(boolean$3()),showInPanel:optional$3(boolean$3()),state:optional$3(notificationStateDecoder)}),glue42NotificationOptionsWithDefaultsDecoder=object$2({title:nonEmptyStringDecoder$2,clickInterop:optional$3(interopActionSettingsDecoder),actions:optional$3(array$3(glue42NotificationActionDecoder)),focusPlatformOnDefaultClick:optional$3(boolean$3()),badge:optional$3(string$4()),body:optional$3(string$4()),data:optional$3(anyJson$2()),dir:optional$3(oneOf$1(constant$2("auto"),constant$2("ltr"),constant$2("rtl"))),icon:optional$3(string$4()),image:optional$3(string$4()),lang:optional$3(string$4()),renotify:optional$3(boolean$3()),requireInteraction:optional$3(boolean$3()),silent:optional$3(boolean$3()),tag:optional$3(string$4()),timestamp:nonNegativeNumberDecoder$2,vibrate:optional$3(array$3(number$4())),severity:optional$3(oneOf$1(constant$2("Low"),constant$2("None"),constant$2("Medium"),constant$2("High"),constant$2("Critical"))),showToast:boolean$3(),showInPanel:boolean$3(),state:optional$3(notificationStateDecoder)}),raiseNotificationDecoder=object$2({settings:glue42NotificationOptionsDecoder,id:nonEmptyStringDecoder$2}),raiseNotificationResultDecoder=object$2({settings:glue42NotificationOptionsWithDefaultsDecoder}),permissionRequestResultDecoder=object$2({permissionGranted:boolean$3()}),permissionQueryResultDecoder=object$2({permission:oneOf$1(constant$2("default"),constant$2("granted"),constant$2("denied"))}),simpleNotificationSelectDecoder=object$2({id:nonEmptyStringDecoder$2}),notificationClickConfigDecoder=object$2({id:nonEmptyStringDecoder$2,action:optional$3(nonEmptyStringDecoder$2)}),notificationsDataDecoder=object$2({id:nonEmptyStringDecoder$2,title:nonEmptyStringDecoder$2,clickInterop:optional$3(interopActionSettingsDecoder),actions:optional$3(array$3(glue42NotificationActionDecoder)),focusPlatformOnDefaultClick:optional$3(boolean$3()),badge:optional$3(string$4()),body:optional$3(string$4()),data:optional$3(anyJson$2()),dir:optional$3(oneOf$1(constant$2("auto"),constant$2("ltr"),constant$2("rtl"))),icon:optional$3(string$4()),image:optional$3(string$4()),lang:optional$3(string$4()),renotify:optional$3(boolean$3()),requireInteraction:optional$3(boolean$3()),silent:optional$3(boolean$3()),tag:optional$3(string$4()),timestamp:optional$3(nonNegativeNumberDecoder$2),vibrate:optional$3(array$3(number$4())),severity:optional$3(oneOf$1(constant$2("Low"),constant$2("None"),constant$2("Medium"),constant$2("High"),constant$2("Critical"))),showToast:optional$3(boolean$3()),showInPanel:optional$3(boolean$3()),state:optional$3(notificationStateDecoder)}),allNotificationsDataDecoder=object$2({notifications:array$3(notificationsDataDecoder)}),notificationsConfigurationDecoder=object$2({enable:optional$3(boolean$3()),enableToasts:optional$3(boolean$3()),sourceFilter:optional$3(notificationFilterDecoder),showNotificationBadge:optional$3(boolean$3())}),notificationsConfigurationProtocolDecoder=object$2({configuration:notificationsConfigurationDecoder}),notificationsActiveCountDecoder=object$2({count:number$4()}),notificationSetStateRequestDecoder=object$2({id:nonEmptyStringDecoder$2,state:notificationStateDecoder}),prefsNotificationsDecoder=object$2({config:notificationsConfigurationDecoder});class NotificationsController{glueController;serviceWorkerController;session;localStorage;prefsController;started=!1;isInExtension=!1;clearNotificationOnClick;extNotificationConfig;systemUnsubFuncs=[];_chromeClickedHandler;_chromeButtonClickedHandler;_chromeClosedHandler;operations={raiseNotification:{name:"raiseNotification",execute:this.handleRaiseNotification.bind(this),dataDecoder:raiseNotificationDecoder,resultDecoder:raiseNotificationResultDecoder},requestPermission:{name:"requestPermission",resultDecoder:permissionRequestResultDecoder,execute:this.handleRequestPermission.bind(this)},getPermission:{name:"getPermission",resultDecoder:permissionQueryResultDecoder,execute:this.handleGetPermission.bind(this)},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)},list:{name:"list",resultDecoder:allNotificationsDataDecoder,execute:this.handleList.bind(this)},click:{name:"click",dataDecoder:notificationClickConfigDecoder,execute:this.handleClick.bind(this)},clear:{name:"clear",dataDecoder:simpleNotificationSelectDecoder,execute:this.handleClear.bind(this)},clearAll:{name:"clearAll",execute:this.handleClearAll.bind(this)},configure:{name:"configure",dataDecoder:notificationsConfigurationProtocolDecoder,execute:this.handleConfigure.bind(this)},getActiveCount:{name:"getActiveCount",resultDecoder:notificationsActiveCountDecoder,execute:this.handleGetActiveCount.bind(this)},getConfiguration:{name:"getConfiguration",resultDecoder:notificationsConfigurationProtocolDecoder,execute:this.handleGetConfiguration.bind(this)},setState:{name:"setState",dataDecoder:notificationSetStateRequestDecoder,execute:this.handleSetState.bind(this)},clearOld:{name:"clearOld",execute:this.handleClearOld.bind(this)}};constructor(e,t,r,n,i){this.glueController=e,this.serviceWorkerController=t,this.session=r,this.localStorage=n,this.prefsController=i}get logger(){return logger.get("notifications.controller")}get config(){const e=this.localStorage.getNotificationsConfig();return e||ioError.raiseError("The notifications configuration has not been set.")}get currentActiveCount(){return this.session.getAllNotifications().reduce((e,t)=>"Active"===t.state?e+1:e,0)}handlePlatformShutdown(){this.started=!1;new URL(window.location.href).protocol.includes("extension")&&this.removeExtensionNotificationsListeners(),this.systemUnsubFuncs.forEach(e=>e()),this.systemUnsubFuncs=[]}async start(){this.clearNotificationOnClick=this.config.clearNotificationOnClick;new URL(window.location.href).protocol.includes("extension")&&await this.setupExtensionNotifications(),this.listenForServiceWorkerNotificationEvents(),this.started=!0}async setupInitialConfig(){const e=this.prefsController.storeType;if(!e||"local"===e)return void this.logger?.info("The notifications service will use the local storage for the notifications configuration");let t;try{t=await this.glueController.clientGlue.prefs.get(systemPrefsAppName)}catch(e){return void this.logger?.warn(`Failed to get the system preferences for the notifications service: ${e}, falling back to local storage`)}const r=t?.data[notificationsPrefsKey];if(!r)return void this.logger?.info("The system preferences for the notifications service are not set in prefs, falling back to local storage");const n=prefsNotificationsDecoder.run(r);if(!n.ok)return void this.logger?.error(`The system preferences from Prefs for the notifications service did not pass validation: ${JSON.stringify(n.error)}, falling back to local storage`);const i=n.result.config;this.localStorage.updateNotificationsConfig(i)}ready(){return Promise.resolve()}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this notifications control message, because the controller has not been started");const t=e.data,r=e.commandId,n=e.callerId,i=notificationsOperationDecoder.run(e.operation);if(!i.ok)return ioError.raiseError(`This notifications request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(i.error)}`);const o=i.result,s=this.operations[o].dataDecoder?.run(t);if(s&&!s.ok)return ioError.raiseError(`Notifications request for ${o} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(s.error)}`);this.logger?.debug(`[${r}] ${o} command is valid with data: ${JSON.stringify(t)}`);const a=await this.operations[o].execute(t,r,n),c=this.operations[o].resultDecoder?.run(a);return c&&!c.ok?ioError.raiseError(`Notifications request for ${o} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(c.error)}`):(this.logger?.trace(`[${r}] ${o} command was executed successfully`),a)}async handleConfigure({configuration:e},t,r=""){if(this.logger?.trace(`[${t}] handling a notification configure message with data: ${JSON.stringify(e)}`),this.validateServiceAccess(r,!0),this.localStorage.updateNotificationsConfig(e),this.glueController.pushSystemMessage("notifications","configurationChanged",{configuration:this.config}),"local"!==this.prefsController.storeType){const e={config:this.config};this.glueController.clientGlue.prefs.update({[notificationsPrefsKey]:e},{app:systemPrefsAppName}).catch(e=>{this.logger?.warn(`Failed to update the notifications configuration in prefs: ${e} - the settings are only updated in the local storage`)})}this.logger?.trace(`[${t}] handling a notification configure message completed`)}async handleGetActiveCount(e,t){return this.logger?.trace(`[${t}] handling a get active count message`),{count:this.currentActiveCount}}async handleGetConfiguration(e,t){this.logger?.trace(`[${t}] handling a get notification configure message`);const r={...this.config};return this.logger?.trace(`[${t}] handling a get notification configure message completed`),{configuration:r}}async handleList(e,t){this.logger?.trace(`[${t}] handling a list notification message`);const r=this.session.getAllNotifications();return this.logger?.trace(`[${t}] list notification message completed`),{notifications:r}}async handleSetState({id:e,state:t},r){this.logger?.trace(`[${r}] handling a set state notification message with data: ${JSON.stringify({id:e,state:t})}`);const n=this.session.getNotification(e);if(!n)return ioError.raiseError(`Cannot set state of a notification: ${e}, because it doesn't exist`);const i=this.currentActiveCount;n.state=t,this.session.updateNotification(n),this.glueController.pushSystemMessage("notifications","stateChange",{id:e,state:t}),this.syncActiveCount(i)}async handleClick(e,t){this.logger?.trace(`[${t}] handling a click notification message with data: ${JSON.stringify(e)}`);const r=this.session.getNotification(e.id);return r?e.action&&r.actions?.every(t=>t.action!==e.action)?ioError.raiseError(`Cannot click action ${e.action} of ${e.id}, because that notification does not have that action`):(this.handleNotificationClick({notification:r,action:e.action}),void this.logger?.trace(`[${t}] handling a click notification message completed`)):ioError.raiseError(`Cannot click a notification: ${e.id}, because it doesn't exist`)}async handleClear(e,t){this.logger?.trace(`[${t}] handling a clear notification message with data: ${JSON.stringify(e)}`);const r=this.currentActiveCount;this.removeNotification(e.id),this.syncActiveCount(r),this.logger?.trace(`[${t}] handling a clear notification message completed`)}async handleClearAll(e,t){this.logger?.trace(`[${t}] handling a clearAll notifications message`);const r=this.session.getAllNotifications(),n=r.reduce((e,t)=>"Active"===t.state?e+1:e,0);r.forEach(e=>this.removeNotification(e.id)),this.syncActiveCount(n),this.logger?.trace(`[${t}] handling a clearAll notification message completed`)}async handleClearOld(e,t){this.logger?.trace(`[${t}] handling a clearOld notifications message`);const r=this.session.getAllNotifications(),n=r.reduce((e,t)=>"Active"===t.state?e+1:e,0);r.filter(e=>"Active"!==e.state).forEach(e=>this.removeNotification(e.id)),this.syncActiveCount(n),this.logger?.trace(`[${t}] handling a clearOld notification message completed`)}async handleRaiseNotification({settings:e,id:t},r,n=""){if(this.logger?.trace(`[${r}] handling a raise notification message with a title: ${e.title}`),!this.config.enable)return ioError.raiseError("Cannot raise a notification, because the notifications service is disabled");this.validateServiceAccess(n);const i=this.currentActiveCount;setNotificationDefaults(e),this.processNewNotification(e,t);const o=this.config.enableToasts?!!e.showToast:this.config.enableToasts;await this.showToast({settings:e,id:t},o,r);const s={definition:Object.assign({},e,{title:void 0,clickInterop:void 0,actions:void 0}),id:t};return setTimeout(()=>this.glueController.pushSystemMessage("notifications","notificationShow",s),0),this.logger?.trace(`[${r}] notification with a title: ${e.title} was successfully raised`),this.syncActiveCount(i),{settings:e}}async showToast({settings:e,id:t},r,n){if(!r)return;if(this.isInExtension)return void await this.raiseExtensionToast(e,t,n);e.actions&&e.actions.length?await this.raiseActionsToast(e,t,n):this.raiseSimpleToast(e,t,n)}async handleGetPermission(e,t){this.logger?.trace(`[${t}] handling a get permission message`);const r=Notification.permission;return this.logger?.trace(`[${t}] permission for raising notifications is: ${r}`),{permission:r}}async handleRequestPermission(e,t){this.logger?.trace(`[${t}] handling a request permission message`);let r=Notification.permission;"granted"!==r&&(r=await Notification.requestPermission());const n="granted"===r;return this.logger?.trace(`[${t}] permission for raising notifications is: ${r}`),{permissionGranted:n}}validateServiceAccess(e,t){const r=this.glueController.getAppNameByInstanceId(e)||"";if(t&&e===this.glueController.me.instance)return;if(this.config.sourceFilter.blocked.includes(r))return ioError.raiseError(`Cannot complete the notifications operation, because the caller app: ${r} is blocked from the notifications service`);const n=this.config.sourceFilter.allowed.includes("*"),i=this.config.sourceFilter.allowed.includes(r);return n||i?void 0:ioError.raiseError(`Cannot complete the notifications operation, because the caller app: ${r} is not present in the allowed list of the notifications service`)}async raiseSimpleToast(e,t,r){this.logger?.trace(`[${r}] notification with a title: ${e.title} was found to be non-persistent and therefore will be raised with the native notifications API`);const n=Object.assign({},e,{title:void 0,clickInterop:void 0}),i=new Notification(e.title,n);i.onclick=()=>{e.focusPlatformOnDefaultClick&&window.focus();const r=this.session.getNotification(t);r&&this.handleNotificationClick({action:"",notification:r})},i.onclose=()=>{const e=this.currentActiveCount;this.removeNotification(t),this.syncActiveCount(e)}}async raiseActionsToast(e,t,r){this.logger?.trace(`[${r}] notification with a title: ${e.title} was found to be persistent and therefore the service worker will be instructed to raise it.`),await this.serviceWorkerController.showNotification(e,t)}raiseExtensionToast(e,t,r){return new Promise((n,i)=>{if(this.logger?.trace(`[${r}] notification with a title: ${e.title} will be raised with the native extension notifications API, because the platform is running in extension mode`),!this.extNotificationConfig)return i("Cannot raise a notification, because the environment settings for the extension mode are missing.");const o=e.actions?e.actions.map(e=>({title:e.title,iconUrl:e.icon})):void 0,s={type:"basic",iconUrl:e.icon||this.extNotificationConfig.defaultIcon,title:e.title,message:e.body||this.extNotificationConfig.defaultMessage,silent:e.silent,requireInteraction:e.requireInteraction,imageUrl:e.image,buttons:o};chrome.notifications.create(t,s,()=>n())})}async setupExtensionNotifications(){this.isInExtension=!0,this.extNotificationConfig=(await this.getExtNotificationsConfig()).notifications,this.listenForExtensionNotificationsEvents()}listenForExtensionNotificationsEvents(){this._chromeClickedHandler=this.chromeClickedHandler.bind(this),chrome.notifications.onClicked.addListener(this._chromeClickedHandler),this._chromeButtonClickedHandler=this.chromeButtonClickedHandler.bind(this),chrome.notifications.onButtonClicked.addListener(this._chromeButtonClickedHandler),this._chromeClosedHandler=this.chromeClosedHandler.bind(this),chrome.notifications.onClosed.addListener(this._chromeClosedHandler)}removeExtensionNotificationsListeners(){chrome.notifications.onClicked.removeListener(this._chromeClickedHandler),chrome.notifications.onButtonClicked.removeListener(this._chromeButtonClickedHandler),chrome.notifications.onClosed.removeListener(this._chromeClosedHandler)}chromeClickedHandler(e){const t=this.session.getNotification(e);t&&this.handleNotificationClick({notification:t})}chromeButtonClickedHandler(e,t){const r=this.session.getNotification(e);if(!r)return;if(!r.actions)return;const n=r.actions[t].action;this.handleNotificationClick({action:n,notification:r})}chromeClosedHandler(e){const t=this.currentActiveCount;this.removeNotification(e),this.syncActiveCount(t)}listenForServiceWorkerNotificationEvents(){const e=this.serviceWorkerController.onNotificationClick(e=>{const t=this.session.getNotification(e.glueData.id);t&&this.handleNotificationClick({action:e.action,notification:t})}),t=this.serviceWorkerController.onNotificationClose(e=>{const t=this.currentActiveCount;this.removeNotification(e.glueData.id),this.syncActiveCount(t)});this.systemUnsubFuncs.push(e),this.systemUnsubFuncs.push(t)}getExtNotificationsConfig(){return new Promise(e=>{chrome.storage.local.get("notifications",t=>{e(t)})})}handleNotificationClick(e){!e.action&&e.notification.clickInterop&&this.callDefinedInterop(e.notification.clickInterop);const t=e.action?e.notification.actions?.find(t=>t.action===e.action):null;t&&t.interop&&this.callDefinedInterop(t.interop),e.notification.data?.glueData&&delete e.notification.data.glueData;const r={definition:e.notification,action:e.action,id:e.notification.id};if(this.clearNotificationOnClick){const t=this.currentActiveCount;this.removeNotification(e.notification.id),this.syncActiveCount(t)}this.glueController.pushSystemMessage("notifications","notificationClick",r)}callDefinedInterop(e){const t=e.method,r=e.arguments,n=e.target;this.glueController.invokeMethod(t,r,n).catch(e=>{const t="string"==typeof e?e:JSON.stringify(e.message);this.logger?.warn(`The interop invocation defined in the clickInterop was rejected, reason: ${t}`)})}processNewNotification(e,t){const r={id:t,...e};this.session.saveNewNotification(r),this.glueController.pushSystemMessage("notifications","notificationRaised",{notification:r})}removeNotification(e){this.session.removeNotification(e),this.glueController.pushSystemMessage("notifications","notificationClosed",{id:e})}syncActiveCount(e){const t=this.currentActiveCount;e!==t&&this.glueController.pushSystemMessage("notifications","activeCountChange",{count:t})}}const extensionOperationTypesDecoder=oneOf$1(constant$2("clientHello"),constant$2("operationCheck")),clientHelloResponseDecoder=object$2({widget:object$2({inject:boolean$3()})}),clientHelloDecoder=object$2({windowId:optional$3(nonEmptyStringDecoder$2)});class ExtensionController{session;started=!1;operations={clientHello:{name:"appHello",resultDecoder:clientHelloResponseDecoder,dataDecoder:clientHelloDecoder,execute:this.handleClientHello.bind(this)},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)}};constructor(e){this.session=e}get logger(){return logger.get("extension.controller")}handlePlatformShutdown(){this.started=!1}async start(){this.started=!0,this.logger?.trace("initialization is completed")}ready(){return Promise.resolve()}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this extension control message, because the controller has not been started");const t=e.data,r=e.commandId,n=extensionOperationTypesDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This extension request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`Extension request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`Extension request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}async handleClientHello(e,t){this.logger?.trace(`[${t}] handling client hello command`);const r=(await this.getWidgetConfig()).widget,n={widget:{inject:!(!!e.windowId&&!!this.session.getFrameData(e.windowId))&&(!!r&&r.enable)}};return this.logger?.trace(`[${t}] responding to client hello command with: ${JSON.stringify(n)}`),n}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}getWidgetConfig(){return new URL(window.location.href).protocol.includes("extension")?new Promise(e=>{chrome.storage.local.get("widget",t=>{e(t)})}):Promise.resolve({widget:{enable:!1}})}}class AsyncSequelizer{minSequenceInterval;queue=[];isExecutingQueue=!1;constructor(e=0){this.minSequenceInterval=e}enqueue(e){return new Promise((t,r)=>{this.queue.push({action:e,resolve:t,reject:r}),this.executeQueue()})}async executeQueue(){if(!this.isExecutingQueue){for(this.isExecutingQueue=!0;this.queue.length;){const e=this.queue.shift();if(!e)return void(this.isExecutingQueue=!1);try{const t=await e.action();e.resolve(t)}catch(t){e.reject(t)}await this.intervalBreak()}this.isExecutingQueue=!1}}intervalBreak(){return new Promise(e=>setTimeout(e,this.minSequenceInterval))}}class PreferredConnectionController{glueController;portsBridge;sequelizer;registry=CallbackRegistryFactory$2();unsub;discoveryInterval;shouldForceTransfer;preferredUrl;preferredAuth;stopped=!1;constructor(e,t,r){this.glueController=e,this.portsBridge=t,this.sequelizer=r}get logger(){return logger.get("preferred.connection.controller")}shutdown(){this.stopped=!0,this.registry.clear()}async start(e){this.logger?.trace(`Starting the preferred connection with config: ${JSON.stringify(e)}`),this.stopped=!1,this.portsBridge.setPreferredActivated(),e.preferred&&(this.preferredUrl=e.preferred.url,this.preferredAuth=Object.assign({},{provider:"core"},e.preferred.auth),this.shouldForceTransfer="boolean"==typeof e.preferred.forceIncompleteSwitch&&e.preferred.forceIncompleteSwitch,this.discoveryInterval="number"==typeof e.preferred.discoveryIntervalMS?e.preferred.discoveryIntervalMS:defaultPreferredDiscoveryIntervalMS,this.logger?.trace("Starting the initial preferred connection check"),await this.connectPreferred(),this.logger?.trace("The preferred connection controller initiated."))}onReconnect(e){return this.registry.add("system-reconnect",e)}async connectPreferred(e,t,r){if(this.stopped&&!e)return;const n=await this.checkPreFlight(t);if(!n.ready&&e)return ioError.raiseError("The provided preferred connection is not ready.");if(!n.ready)return this.logger?.trace("The preflight is not ready, restarting the preferred tracking."),void wait(this.discoveryInterval).then(()=>this.connectPreferred(e,t,r));const i={type:"secondary",transportConfig:Object.assign({url:t||this.preferredUrl},{auth:r||this.preferredAuth})};if(this.logger?.trace("Switching the system glue."),this.stopped)return;if(!(await this.glueController.switchTransport(i,"system")).success)return this.logger?.trace("The switch attempt was not successful, revered to default."),void wait(this.discoveryInterval).then(()=>this.connectPreferred(e,t,r));this.portsBridge.setActivePreferredTransportConfig(i),this.logger?.trace("The switch to the preferred connection was successful, transferring all children.");try{await this.changeClientsConnection(i)}catch(n){return this.logger?.warn(`Some platform clients could not connect to the preferred connection, reverting all to the default connection. Reason: ${JSON.stringify(n)}`),void this.fullDefaultRevert().then(()=>wait(this.discoveryInterval).then(()=>this.connectPreferred(e,t,r))).catch(()=>wait(this.discoveryInterval).then(()=>this.connectPreferred(e,t,r)))}this.logger?.trace("The platform is now fully connected to the preferred connection, hooking up disconnection logic."),this.registry.execute("system-reconnect");const o=this.glueController.onDisconnected(()=>this.handleDisconnected(o,e));this.unsub=o}async revertToDefault(){this.unsub&&(this.unsub(),delete this.unsub),await this.fullDefaultRevert()}async fullDefaultRevert(){await this.glueController.switchTransport({type:"default"},"system"),this.portsBridge.setActivePreferredTransportConfig({type:"default"}),await this.changeClientsConnection({type:"default"})}handleDisconnected(e,t){this.logger?.trace("The platform has been disconnected from the preferred transport, reverting all to the default one."),e(),this.fullDefaultRevert().then(()=>{this.registry.execute("system-reconnect"),this.logger?.trace("The platform reversion to default completed, restarting the preferred tracking."),t||wait(this.discoveryInterval).then(()=>this.connectPreferred())}).catch(()=>wait(this.discoveryInterval).then(()=>this.connectPreferred()))}changeClientsConnection(e){return this.sequelizer.enqueue(async()=>{try{await Promise.all([this.glueController.switchTransport(e,"client"),this.portsBridge.switchAllClientsTransport(e)])}catch(e){if(this.logger?.trace(`Some clients could not connect to the preferred transport with error: ${JSON.stringify(e)}`),!this.shouldForceTransfer)return this.logger?.trace("The platform is not forcing a transfer in cases of errors, re-throwing."),ioError.raiseError(e);this.logger?.trace("The platform is forcing a transfer regardless of the errors.")}await this.glueController.switchTransport(e,"contextsTrack")})}checkPreferredConnection(e){return new Promise(t=>{const r=new WebSocket(e);r.onerror=()=>t({live:!1}),r.onopen=()=>{r.close(),t({live:!0})}})}async checkPreFlight(e){this.logger?.trace("Starting the preflight check");if(!(await this.checkPreferredConnection(e||this.preferredUrl)).live)return this.logger?.trace("The preferred connection is not live."),{ready:!1};this.logger?.trace(`Found a live preferred connection at: ${e||this.preferredUrl}, testing the availability of transport switching logic in all current clients`);const t=await this.portsBridge.checkClientsPreferredLogic();if(this.logger?.trace(`The logic check returned: ${JSON.stringify(t)}`),!t.success&&!this.shouldForceTransfer)return this.logger?.trace("The preflight check is marked as not ready"),{ready:!1};this.logger?.trace("Checking the possibility of all clients to connect to the preferred connection");const r=await this.portsBridge.checkClientsPreferredConnection(e||this.preferredUrl);return this.logger?.trace(`The connection check returned: ${JSON.stringify(r)}`),r.success||this.shouldForceTransfer?(this.logger?.trace("The preflight check is marked as ready"),{ready:!0}):(this.logger?.trace("The preflight check is marked as not ready"),{ready:!1})}}class TransactionsController{transactionLocks={};get logger(){return logger.get("transactions.controller")}completeTransaction(e,t){if("string"!=typeof e)return ioError.raiseError(`Cannot complete the transaction, because the provided id is not a string: ${JSON.stringify(e)}`);const r=this.transactionLocks[e];r?r.lift(t):this.logger?.warn(`Cannot mark a transaction as complete, because there is not lock with id ${e}`)}failTransaction(e,t){const r=this.transactionLocks[e];r?r.fail(t):this.logger?.warn(`Cannot mark a transaction as failed, because there is not lock with id ${e}`)}createTransaction(e,t){const r={},n=nanoid$3(10),i=new Promise((i,o)=>{let s=!0;r.lift=e=>{s=!1,delete this.transactionLocks[n],i(e)},r.fail=e=>{s=!1,delete this.transactionLocks[n],o(e)},setTimeout(()=>{s&&(s=!1,this.logger?.warn(`Transaction for operation: ${e} timed out.`),delete this.transactionLocks[n],o(`Transaction for operation: ${e} timed out.`))},t)});return r.lock=i,r.id=n,this.transactionLocks[n]=r,r}}class InterceptionController{interceptions=[];shutdown(){this.interceptions=[]}async registerInterceptor(e,t){runDecoderWithIOError(interceptorRegistrationRequestDecoder,e),runDecoderWithIOError(nonEmptyStringDecoder$2,t);const r=e.interceptions.reduce((e,t)=>(this.interceptions.some(e=>e.domain===t.domain&&e.operation===t.operation)&&e.push({domain:t.domain,operation:t.operation}),e),[]);if(r.length){const e=r.map(e=>`${e.domain} - ${e.operation}`).join(", ");return ioError.raiseError(`Interception registration is rejected, because the following collisions where found: ${e}`)}e.interceptions.forEach(r=>{this.interceptions.push({domain:r.domain,operation:r.operation,callInterceptor:e.callInterceptor,registrantName:t})})}getOperationInterceptor(e){const t=this.interceptions.find(t=>t.domain===e.domain&&t.operation===e.operation);if(t)return{name:t.registrantName,intercept:t.callInterceptor}}}class PluginsController{interceptionController;glueController;handlePluginMessage;platformApi;allPlugins;registeredPlugins=[];constructor(e,t){this.interceptionController=e,this.glueController=t}get logger(){return logger.get("plugins.controller")}async shutdown(){this.logger?.debug(`starting plugins shutdown for all plugins: [${this.allPlugins.map(e=>e.name).join(", ")}]`),this.allPlugins.forEach(e=>{if(e.stop)try{e.stop()}catch(t){this.logger?.warn(`Plugin: ${e.name} threw while onPlatformShutdown -> ${extractErrorMsg$1(t)}`)}}),this.allPlugins=[],this.registeredPlugins=[],this.logger?.debug("plugins shutdown completed")}async start(e){if(this.logger?.debug(`initializing plugins with ${JSON.stringify((e.plugins??[]).map(e=>e.name))} plugins`),!e.plugins)return;if(this.allPlugins=e.plugins,this.handlePluginMessage=e.handlePluginMessage,this.platformApi=e.api,!e.plugins||!e.plugins.length)return;const t=[],r=[];for(const n of e.plugins){const e=this.startPlugin(n);n.critical&&(t.push(e),r.push(n.name))}this.logger?.debug(`waiting for ${t.length} critical plugins to start: [${r.join(", ")}]`),await Promise.all(t),this.logger?.debug(`all critical plugins started successfully [${r.join(", ")}]`)}async startPlugin(e){this.logger?.debug(`starting plugin with definition: ${JSON.stringify(e)}`);try{const t=this.buildPlatformControls(e.name,this.platformApi);this.validatePlugin(e.name),await e.start(this.glueController.clientGlue,e.config,t),this.registerPlugin(e.name,e.version??"N/A"),this.logger?.debug(`plugin '${e.name}' started successfully`)}catch(t){this.logger?.error(`plugin '${e.name}' failed to start with error: ${extractErrorMsg$1(t)}`);const r="string"==typeof t?t:JSON.stringify(t.message),n=`Plugin: ${e.name} threw while initiating: ${r}`;if(e.critical)return ioError.raiseError(n);this.logger?.warn(n)}}buildPlatformControls(e,t){return{control:t=>this.handlePluginMessage(t,e),logger:logger.get(e),platformApi:t,interception:{register:t=>this.interceptionController.registerInterceptor(t,e)},system:{sendControl:t=>this.handlePluginMessage(t,e)}}}validatePlugin(e){if(this.registeredPlugins.some(t=>t.name===e))throw new Error(`Plugin: ${e} is already registered`)}registerPlugin(e,t){this.registeredPlugins.push({name:e,version:t})}}class DomainsController{systemController;windowsController;applicationsController;layoutsController;workspacesController;intentsController;channelsController;notificationsController;extensionController;searchController;themesController;managerController;prefsController;otelController;uiController;defaultDomainNames=["system","windows","appManager","layouts","workspaces","intents","channels","notifications","extension","search","themes","prefs","otel","ui"];domains;constructor(e,t,r,n,i,o,s,a,c,l,u,d,h,p,g){this.systemController=e,this.windowsController=t,this.applicationsController=r,this.layoutsController=n,this.workspacesController=i,this.intentsController=o,this.channelsController=s,this.notificationsController=a,this.extensionController=c,this.searchController=l,this.themesController=u,this.managerController=d,this.prefsController=h,this.otelController=p,this.uiController=g,this.setDomains()}setDomains(){this.domains={system:{name:"system",libController:this.systemController},windows:{name:"windows",libController:this.windowsController},appManager:{name:"appManager",libController:this.applicationsController},layouts:{name:"layouts",libController:this.layoutsController},workspaces:{name:"workspaces",libController:this.workspacesController},intents:{name:"intents",libController:this.intentsController},channels:{name:"channels",libController:this.channelsController},notifications:{name:"notifications",libController:this.notificationsController},extension:{name:"extension",libController:this.extensionController},search:{name:"search",libController:this.searchController},themes:{name:"themes",libController:this.themesController},manager:{name:"manager",libController:this.managerController},prefs:{name:"prefs",libController:this.prefsController},otel:{name:"otel",libController:this.otelController},ui:{name:"ui",libController:this.uiController}}}get logger(){return logger.get("domains.controller")}shutdown(){Object.values(this.domains).forEach(e=>e.libController.handlePlatformShutdown?e.libController.handlePlatformShutdown():null),this.domains={system:{name:"system",libController:this.systemController},windows:{name:"windows",libController:this.windowsController},appManager:{name:"appManager",libController:this.applicationsController},layouts:{name:"layouts",libController:this.layoutsController},workspaces:{name:"workspaces",libController:this.workspacesController},intents:{name:"intents",libController:this.intentsController},channels:{name:"channels",libController:this.channelsController},notifications:{name:"notifications",libController:this.notificationsController},extension:{name:"extension",libController:this.extensionController},search:{name:"search",libController:this.searchController},themes:{name:"themes",libController:this.themesController},prefs:{name:"prefs",libController:this.prefsController},otel:{name:"otel",libController:this.otelController},ui:{name:"ui",libController:this.uiController}}}setProfileData(e){this.systemController.setProfileData(e)}async setNotificationsData(){await this.notificationsController.setupInitialConfig()}async setThemesData(){await this.themesController.setupInitialThemes()}validateDomain(e){const t=this.domains[e];if(!t)return ioError.raiseError(`Accessing a missing domain: ${e}.`);const r=t.domainNameDecoder?t.domainNameDecoder:libDomainDecoder;runDecoderWithIOError(r,e)}async startAllDomains(e){this.logger?.trace("Starting all domains lib controllers"),await Promise.all(Object.values(this.domains).map(t=>t.libController.start(e))),this.logger?.trace("All domains have been initialized")}async configurePostStartAllDomains(){this.logger?.trace("Starting all domains lib controllers"),await Promise.all(Object.values(this.domains).filter(e=>!!e.libController.configurePostStart).map(e=>e.libController.configurePostStart&&e.libController.configurePostStart())),this.logger?.trace("All domains have been initialized")}notifyDomainsClientUnloaded(e){this.logger?.trace(`detected unloading of client: ${e.windowId}, notifying all controllers`),Object.values(this.domains).forEach(t=>{try{t.libController.handleClientUnloaded?.(e.windowId,e.win)}catch(r){const n="string"==typeof r?r:JSON.stringify(r.message),i=t.name;this.logger?.error(`${i} controller threw when handling unloaded client ${e.windowId} with error message: ${n}`)}})}executeControlMessage(e){const t=this.domains[e.domain];return t?t.libController.handleControl(e):ioError.raiseError(`Cannot process message for domain: ${e.domain} and operation ${e.operation}, because no domain can service it.`)}registerDynamicDomain(e){return Object.values(this.domains).map(e=>e.name).some(t=>t===e.name)?ioError.raiseError(`Cannot register a domain with name: ${e.name}, because it is already registered`):e.libController&&e.libController.start&&e.libController.handleControl&&e.libController.handleClientUnloaded?e.domainNameDecoder?void(this.domains[e.name]=e):ioError.raiseError(`Cannot register a domain with name: ${e.name}, because it does not have a domain decoder`):ioError.raiseError(`Cannot register a domain with name: ${e.name}, because it does not have a valid libController`)}unregisterDynamicDomain(e){if(this.defaultDomainNames.some(t=>t===e))return ioError.raiseError(`Cannot unregister a domain: ${e}, because it is a reserved default domain`);delete this.domains[e]}async domainsReady(){this.logger?.trace("Verifying all domains lib controllers ready"),await Promise.all(Object.values(this.domains).map(e=>e.libController.ready())),this.logger?.trace("All domains have signaled ready")}}class LegacyResolverController{glueController;workspacesController;windowsController;prefsController;intentsResolverResponsePromises={};constructor(e,t,r,n){this.glueController=e,this.workspacesController=t,this.windowsController=r,this.prefsController=n}get logger(){return logger.get("intents.resolver.controller")}async startResolverApp({request:e,resolverConfig:t,commandId:r,callerId:n,resolverInstance:i,method:o}){this.logger?.trace(`[${r}] Intents Resolver UI with app name ${t.appName} will be used for request: ${JSON.stringify(e)}`);const s=await this.registerResponseMethod();this.logger?.trace(`[${r}] Registered interop method ${s}`);const a=this.buildStartContext(o,e,s,n),c=await this.buildStartOptions(n,r);this.logger?.trace(`[${r}] Starting Intents Resolver UI with context: ${JSON.stringify(a)} and options: ${c}`);const l=this.glueController.clientGlue.appManager.application(t.appName).start(a,c).catch(e=>ioError.raiseError(`${ERRORS.RESOLVER_UNAVAILABLE}. Reason: ${e instanceof Error||"string"==typeof e?e:JSON.stringify(e)}`)),u=await l;i.instanceId=u.id,this.logger?.trace(`[${r}] Intents Resolver instance with id ${u.id} opened`),this.subscribeOnInstanceStopped(u,o);const d="raise"===o?`for intent request ${JSON.stringify(e)}`:`for '${o}' method with filter ${JSON.stringify(e)}`,h=`${ERRORS.RESOLVER_TIMEOUT} - waited ${t.waitResponseTimeout}ms for the user the choose a handler ${d}`;this.createResponsePromise({intent:"raise"===o?e.intent:void 0,instanceId:u.id,responseMethodName:s,timeout:t.waitResponseTimeout,errorMsg:h});try{return await this.handleInstanceResponse({request:e,instanceId:u.id,method:o,commandId:r,caller:a.initialCaller})}catch(e){return this.stopResolverInstance(i.instanceId),ioError.raiseError(e)}}stopResolverInstance(e){const t=this.glueController.clientGlue.appManager.instances().find(t=>t.id===e);t&&t.stop().catch(e=>this.logger?.warn(e))}async handleInstanceResponse({method:e,caller:t,commandId:r,instanceId:n,request:i}){const o=await this.intentsResolverResponsePromises[n].promise,s="raise"===e?`for intent ${o.intent} `:"";if(this.logger?.trace(`[${r}] Intent handler chosen ${s}: ${JSON.stringify(o.handler)}. Stopping resolver instance with id ${n}`),this.stopResolverInstance(n),this.logger?.trace(`[${r}] Instance with id ${n} successfully stopped`),!o?.userSettings?.preserveChoice)return o.handler;try{await this.saveUserChoice({intent:o.intent,handler:o.handler,filter:"filterHandlers"===e?{applicationNames:i.applicationNames,contextTypes:i.contextTypes,resultType:i.resultType}:void 0,caller:t},r)}catch(e){this.logger?.warn(`[${r}] - Prefs API threw the following error: ${e}`)}return o.handler}async registerResponseMethod(){const e=INTENTS_RESOLVER_INTEROP_PREFIX+nanoid$3(10);return await this.glueController.clientGlue.interop.register(e,(e,t)=>this.responseHandler(e,t)),e}createResponsePromise({instanceId:e,intent:t,responseMethodName:r,timeout:n,errorMsg:i}){let o=()=>{},s=()=>{};const a=PromisePlus((e,t)=>{o=e,s=t},n,i);this.intentsResolverResponsePromises[e]={intent:t,resolve:o,reject:s,promise:a,methodName:r}}buildStartContext(e,t,r,n){const i={callerId:this.glueController.clientGlue.interop.instance.instance,methodName:r,resolverApi:"1.0"},o=this.glueController.getLocalServers().find(e=>e.instance===n);if(!o)throw new Error(`Cannot find window with id: ${n} - the client which sent the "raise" command is no longer opened`);const s=o.application??o.applicationName,a={applicationName:s,applicationTitle:s?this.glueController.clientGlue.appManager.application(s)?.title:"",id:n};return"raise"===e?{...i,initialCaller:a,intent:t}:{...i,initialCaller:a,handlerFilter:t}}async buildStartOptions(e,t){const r=await this.getTargetBounds(e,t);return r?{top:(r.height-INTENTS_RESOLVER_HEIGHT)/2+r.top,left:(r.width-INTENTS_RESOLVER_WIDTH)/2+r.left,width:INTENTS_RESOLVER_WIDTH,height:INTENTS_RESOLVER_HEIGHT}:ioError.raiseError(`[${t}] Cannot find window with id: ${e} - the client which sent the "raise" command is no longer opened`)}async getTargetBounds(e,t){const r=await this.tryGetWindowBasedBounds(e,t)??await this.tryGetWorkspaceBasedBounds(e,t);if(r)return this.logger?.trace(`[${t}] Opening Intents Resolver UI with bounds: ${JSON.stringify(r)}`),r;const n={top:window.screen.availTop??0,left:window.screen.availLeft??0,width:window.screen.width,height:window.screen.height};return this.logger?.trace(`[${t}] Opening Intents Resolver UI relative to my screen bounds: ${JSON.stringify(n)}`),n}async tryGetWindowBasedBounds(e,t){const r=this.glueController.clientGlue.windows.findById(e),n=this.getServerInstanceByWindowId(e);if(!r&&!n)return ioError.raiseError(`Client with id "${e}" does not exist`);if(!r&&n)return this.getWindowBoundsByServerInstance(n,e,t);if(!r)return ioError.raiseError(`Client with id "${e}" does not exist`);try{const n=await r.getBounds();return this.logger?.trace(`[${t}] Opening the resolver UI with bounds: ${JSON.stringify(n)}, relative to a window with id: ${e}`),n}catch(r){return void this.logger?.trace(`[${t}] Failure to get bounds of a window with id ${e}. Error: ${JSON.stringify(r)}`)}}getServerInstanceByWindowId(e){return this.glueController.getLocalServers().find(t=>t.instance===e)}async getWindowBoundsByServerInstance(e,t,r){try{const{bounds:r}=await this.glueController.callWindow("windows",this.windowsController.getBoundsOperation,{windowId:t},{instance:e.instance});return r}catch(t){this.logger?.trace(`[${r}] Failure to get bounds of a window with instance ${e.instance}. Error: ${JSON.stringify(t)}`)}}async tryGetWorkspaceBasedBounds(e,t){try{const{bounds:r}=await this.workspacesController.getWorkspaceWindowFrameBounds({itemId:e},t);return this.logger?.trace(`[${t}] Opening the resolver UI relative to my workspace frame window bounds: ${JSON.stringify(r)}`),r}catch(e){this.logger?.trace(`[${t}] Failure to get my workspace frame window bounds. Error: ${JSON.stringify(e)}`)}}responseHandler(e,t){const r=resolverResponseDecoder.run(e),n=t.instance;return n?r.ok?(this.logger?.trace(`Intent Resolver instance with id ${n} send a valid response: ${JSON.stringify(r.result)}`),this.intentsResolverResponsePromises[n].resolve(e)):(this.logger?.trace(`Intent Resolver instance with id ${n} sent an invalid response. Error: ${JSON.stringify(r.error)}`),this.intentsResolverResponsePromises[n].reject(r.error.message),void this.stopResolverInstance(n)):ioError.raiseError("Cannot find instance id for the response of the intent resolver")}subscribeOnInstanceStopped(e,t){const{application:r}=e,n=r.onInstanceStopped(r=>{if(r.id!==e.id)return;const i=this.intentsResolverResponsePromises[r.id];if(!i)return n();const o="raise"===t?`raised intent ${i.intent}`:`'${t}' method`,s=`${ERRORS.USER_CANCELLED} for ${o}`;i.reject(s),this.cleanUpIntentResolverPromise(r.id),n()})}async cleanUpIntentResolverPromise(e){const t=this.intentsResolverResponsePromises[e];if(!t)return;this.glueController.clientGlue.interop.unregister(t.methodName).catch(e=>this.logger?.warn(e)),delete this.intentsResolverResponsePromises[e]}async saveUserChoice({intent:e,handler:t,filter:r,caller:n},i){const o="Platform"===n.applicationName?this.prefsController.platformAppName:n.applicationName;this.logger?.info(`[${i}] - Saving user's choice of handler for '${o}' app`);const s=await this.prefsController.get({app:o},i),a=s.prefs.data?.intents??{},c={...s.prefs.data,intents:{...a,[e]:{handler:t,filter:r}}};await this.prefsController.update({app:o,data:c},i)}}class LicenseController{verifyLicense(e){if(!e||"string"!=typeof e)return{valid:!1};const t=KEYUTIL_1.getKey(publicLicKey);return{valid:KJUR_1.jws.JWS.verifyJWT(e,t,{alg:["RS256"]})}}getLicensePayload(e){if(!e)return ioError.raiseError("No license key was provided");const t=KJUR_1.jws.JWS.readSafeJSONString(b64utoutf8_1(e.split(".")[1]));return t&&"string"==typeof t.type&&"number"==typeof t.expiration?(t.type=t.type.toLowerCase(),t):ioError.raiseError("The license key payload is invalid")}isPlatformOriginAllowed(e,t=[]){if(!t.length||t.includes("*"))return!0;if("localhost"===e.hostname)return!0;return t.some(t=>pm(t)(e.origin))}checkExpired(e){return!(!e||"number"!=typeof e)&&e<=Date.now()}}class Builder{glueController;sessionStore;windowsController;workspacesController;constructor(e,t,r,n){this.glueController=e,this.sessionStore=t,this.windowsController=r,this.workspacesController=n}get logger(){return logger.get("layouts.builder")}async saveGlobalLayout(e,t){const r=await this.getRawWindowsLayoutData({layoutType:"Global",layoutName:e.layout.name,context:e.layout.context,instances:e.layout.instances,ignoreInstances:e.layout.ignoreInstances,ignoreContexts:e.layout.ignoreContexts,saveWindowContexts:e.layout.saveWindowContexts},t);this.logger?.trace(`[${t}] received valid data for the eligible windows`);const n=await this.glueController.getLayout(e.layout.name),i=n?await this.updateLayout(n,e.layout,r.windows,t):await this.buildNewLayout(e.layout,r.windows,t);return this.logger?.trace(`[${t}] the layout object was constructed, importing.`),await this.glueController.importLayout(i),this.logger?.trace(`[${t}] the import for layout: ${i.name} was completed, responding.`),i}async getGlueClientWindowContextOnSaveRequest(e,t){if(e.ignoreContexts)return{};const r=`Cannot fetch the layout save data from window with id: ${t}`,n=await PromiseWrap(async()=>{try{return await this.glueController.callWindow("layouts",{name:"clientSaveRequest",execute:async()=>{}},e,{windowId:t})}catch{return{}}},15e3,r);return n.windowContext?n.windowContext:e.saveWindowContexts?this.getWebWindowContext(t):{}}async getNonGlueWindowContext(e,t){return e.ignoreContexts?{}:e.saveWindowContexts?this.getWebWindowContext(t):{}}async getWebWindowContext(e){const t=this.glueController.getWindowById(e);return await(t?.getContext())??{}}async updateLayout(e,t,r,n){this.logger?.trace(`[${n}] updating an existing layout with name ${t.name}`),e.context=t.context??{},e.metadata=t.metadata??{},e.token=e.token??generateLayoutToken();const i=r.filter(e=>!!e.layoutComponentId).map(e=>e.layoutComponentId),o=this.getLayoutIdOccurrenceMap(i),s=r.map(t=>this.generateWindowComponent(e,t,o,n));this.logger?.trace(`[${n}] the window components are completed, we have ${s.length} windows for the layout`);const a=this.getBaseSaveRequestFromSaveConfig(t),c=e.components.filter(e=>"workspaceFrame"===e.type),l=await this.compileWorkspacesFrameComponents(c,a,n);return this.logger?.trace(`[${n}] the workspaces frame components are completed, we have ${l.length} frames for the layout`),e.components=[],e.components.push(...s),e.components.push(...l),e}async buildNewLayout(e,t,r){this.logger?.trace(`[${r}] build a brand new layout with name ${e.name}`);const n={name:e.name,type:"Global",context:e.context??{},metadata:e.metadata??{},components:[],token:generateLayoutToken(),version:2},i=t.map(e=>this.buildNewWindowComponent(e,r));this.logger?.trace(`[${r}] the window components are completed, we have ${i.length} windows for the layout`);const o=this.getBaseSaveRequestFromSaveConfig(e),s=await this.compileWorkspacesFrameComponents([],o,r);return this.logger?.trace(`[${r}] the workspaces frame components are completed, we have ${s.length} frames for the layout`),n.components.push(...i),n.components.push(...s),n}getBaseSaveRequestFromSaveConfig(e){return{layoutName:e.name,layoutType:"Global",context:e.context,ignoreContexts:e.ignoreContexts,saveWindowContexts:e.saveWindowContexts}}async getRawWindowsLayoutData(e,t){this.logger?.trace(`[${t}] handling send save requests for layout: ${e.layoutName} to instances: ${e.instances?.join(", ")}`);const r={windows:[...await Promise.all(this.getEligibleGlueWindows(e.instances,e.ignoreInstances).map(r=>this.buildRawGlueWindowData(r,e,t))),...await Promise.all(this.getEligibleNonGlueWindows(e.instances,e.ignoreInstances).map(t=>this.buildRawNonGlueWindowData(t,e)))]};return this.logger?.trace(`[${t}] request completed, responding to the caller`),r}async buildRawGlueWindowData(e,t,r){if(!e.initialUrl)return ioError.raiseError(`Missing URL for client: ${e.name}`);const n=await this.getGlueClientWindowContextOnSaveRequest(t,e.windowId),i=this.sessionStore.getAllInstancesData().find(t=>t.id===e.windowId),o=await this.windowsController.getWindowBounds(e.windowId,r),s=await this.glueController.callWindow("channels",{name:"getMyChannel",execute:async()=>{}},{},{windowId:e.windowId});return{bounds:o,windowContext:n,url:e.initialUrl,name:e.name,application:i?i.applicationName:defaultNoAppWindowComponentAppName,initialContext:t.ignoreContexts?{}:e.initialContext,windowId:e.windowId,layoutComponentId:e.layoutComponentId,channelId:s.channel}}async buildRawNonGlueWindowData(e,t){if(!e.initialUrl)return ioError.raiseError(`Missing URL for client: ${e.name}`);const r=this.sessionStore.getAllInstancesData().find(t=>t.id===e.windowId),n=await this.getNonGlueWindowContext(t,e.windowId);return{bounds:e.initialBounds??defaultPlatformConfig.windows.defaultWindowOpenBounds,windowContext:n,url:e.initialUrl,name:e.name,application:r?r.applicationName:defaultNoAppWindowComponentAppName,initialContext:t.ignoreContexts?{}:e.initialContext,windowId:e.windowId,layoutComponentId:e.layoutComponentId}}getEligibleNonGlueWindows(e,t){const r=this.getAllEligibleWindows(e,t),n=this.sessionStore.getAllNonGlue(),i=this.sessionStore.pickWorkspaceClients(()=>!0);return r.filter(e=>n.some(t=>t.windowId===e.windowId)&&i.every(t=>t.windowId!==e.windowId))}getEligibleGlueWindows(e,t){const r=this.getAllEligibleWindows(e,t),n=this.sessionStore.getAllNonGlue(),i=this.sessionStore.pickWorkspaceClients(()=>!0);return r.filter(e=>i.every(t=>t.windowId!==e.windowId)&&n.every(t=>t.windowId!==e.windowId))}getAllEligibleWindows(e,t){let r=this.sessionStore.getAllWindowsData().filter(e=>"Platform"!==e.name);if(e&&e.length){const t=this.glueController.getLocalServers().filter(t=>e.some(e=>t.instance===e));r=r.filter(e=>t.some(t=>t.windowId===e.windowId))}if(t&&t.length){const e=this.glueController.getLocalServers().filter(e=>t.some(t=>e.instance===t));r=r.filter(t=>e.every(e=>e.windowId!==t.windowId))}return r}updateExistingWindowComponent(e,t,r){return this.logger?.trace(`[${r}] performing a soft update on am existing component ${e.application} with id ${e.state.instanceId}`),e.state.context=t.windowContext?t.windowContext:e.state.context,e.state.bounds=t.bounds,e.state.createArgs.context=t.initialContext?t.initialContext:e.state.createArgs?.context,e.state.instanceId=e.state.instanceId?e.state.instanceId:t.windowId,e.state.channelId=t.channelId,e}buildNewWindowComponent(e,t){return this.logger?.trace(`[${t}] building a brand new component ${e.application} with id ${e.windowId}`),{type:"window",componentType:"application",application:e.application,state:{context:e.windowContext??{},bounds:e.bounds,createArgs:{name:e.name,url:e.url,context:e.initialContext??{}},windowState:"Normal",restoreState:"Normal",restoreSettings:{groupId:"glue_42_core",groupZOrder:0},instanceId:e.windowId,isSticky:!0,isCollapsed:!1,channelId:e.channelId}}}async compileWorkspacesFrameComponents(e,t,r){this.logger?.trace(`[${r}] requesting information about all running workspaces frames`);const n=await this.getAllFramesSnapshotsWithBounds(t,r);this.logger?.trace(`[${r}] got information on ${n.length} frames, composing the frame components`);const i=n.filter(e=>!!e.config?.layoutComponentId).map(e=>e.config.layoutComponentId),o=this.getLayoutIdOccurrenceMap(i);return n.map(t=>this.generateFrameComponent(t,e,o,r))}getLayoutIdOccurrenceMap(e){const t={};return e.forEach(e=>{t[e]?t[e]=1+t[e]:t[e]=1}),t}softUpdateFrameComponent(e,t,r,n){return this.logger?.trace(`[${n}] performing a soft update on am existing frame component ${e.state.instanceId}`),e.state.bounds=t.bounds,e.state.selectedWorkspace=-1===r?0:r,e.state.workspaces=t.snapshot.workspaces,e.state.context=Object.assign({},e.state.context,{isPlatform:t.config.isPlatform}),e}createNewFrameComponent(e,t,r){return this.logger?.trace(`[${r}] building a new frame component ${e.snapshot.id}`),{type:"workspaceFrame",application:"workspaces-demo",componentType:"application",state:{context:{isPlatform:e.config.isPlatform},bounds:e.bounds,instanceId:e.snapshot.id,selectedWorkspace:-1===t?0:t,workspaces:e.snapshot.workspaces,restoreState:"Normal",windowState:"Normal"}}}generateWindowComponent(e,t,r,n){const i=e.components.find(e=>"window"===e.type&&e.state.instanceId===t.layoutComponentId),o=t.layoutComponentId?r[t.layoutComponentId]:0;return i&&o<2?this.updateExistingWindowComponent(i,t,n):this.buildNewWindowComponent(t,n)}generateFrameComponent(e,t,r,n){const i=e.snapshot.workspaces.findIndex(e=>e?.config?.isSelected),o=t.find(t=>t.state.instanceId===e.config.layoutComponentId),s=e.config.layoutComponentId?r[e.config.layoutComponentId]:0;return o&&s<2?this.softUpdateFrameComponent(o,e,i,n):this.createNewFrameComponent(e,i,n)}async getAllFramesSnapshotsWithBounds(e,t){const r=(await this.workspacesController.getAllFramesSummaries(void 0,t)).summaries||[];return await Promise.all(r.map(async r=>{const n=await this.workspacesController.handleGetWorkspacesLayouts({frameId:r.id,...e},t),i=await this.workspacesController.getFrameSessionData({frameId:r.id},t);return{bounds:(await this.workspacesController.getFrameBounds({itemId:r.id},t)).bounds,snapshot:{id:r.id,workspaces:n.workspaces,config:{}},config:{isPlatform:i?.isPlatform,layoutComponentId:i?.layoutComponentId}}}))}}class Restorer{glueController;validator;resetter;workspacesController;sessionStore;constructor(e,t,r,n,i){this.glueController=e,this.validator=t,this.resetter=r,this.workspacesController=n,this.sessionStore=i}get logger(){return logger.get("layouts.restorer")}async restoreGlobalLayout(e,t,r,n){const i=await this.glueController.getLayout(e.layout.name);if(!i)return ioError.raiseError(`Cannot restore layout: ${e.layout.name}, because it was not found in this platform`);if("Global"!==i.type)return ioError.raiseError(`Cannot restore layout: ${e.layout.name}, because it is not a Global Layout`);if(!r||!n)return ioError.raiseError(`Cannot restore layout: ${e.layout.name}, because the callerId or callerType are missing`);await this.validator.doInitialValidation(i,t),this.logger?.trace(`[${t}] the initial validation of the compliancy of the layout was completed`),await this.closeInstances(n,r,t,e.layout.closeMe,e.layout.closeRunningInstances),this.logger?.trace(`[${t}] closed all necessary running instances`),await this.restore(i,e,t);const o=this.sessionStore.getLayoutsSystemData();o.currentLayoutName=i.name,this.sessionStore.setLayoutsSystemData(o),this.logger?.trace(`[${t}] the layout ${i.name} was restored`)}async closeInstances(e,t,r,n,i){(void 0===i||i)&&await this.resetter.closeAllExceptCaller(t,r);(n||void 0===n&&void 0===i||void 0===n&&i)&&await this.resetter.closeCaller(e,t,r)}async restore(e,t,r){this.logger?.trace(`[${r}] starting the restore process of ${e.name}`);const n=await this.canPlatformFrameAcceptComponent(r)?this.pickComponentForPlatformFrame(e.components.filter(e=>"workspaceFrame"===e.type)):null,i=Promise.all(e.components.map(i=>{if("window"===i.type)return this.restoreWindowComponent(i,r,e.context,t.layout.context);if("workspaceFrame"===i.type){const o=n===i;return this.restoreWorkspaceFrameComponent(i,r,e.context,t.layout.context,o)}}));await i}async restoreWindowComponent(e,t,r,n){this.logger?.trace(`[${t}] restoring window component ${e.application} with id ${e.state.instanceId} and bounds: ${JSON.stringify(e.state.bounds)}`);const i=Object.assign({},r,e.state.context,e.state.createArgs.context,n),o=e.state.channelId,s=e.state.bounds,a=await this.checkTargetBoundsPossible(s);a.isPossible||this.logger?.warn(`Restoring ${e.application} not possible with the saved bounds, falling back to default bounds`);const c=a.isPossible?s:void 0;this.logger?.trace(`[${t}] calling the respective glue open/start method`);const l=e.application===defaultNoAppWindowComponentAppName?this.glueController.openWindow({name:e.state.createArgs.name,url:e.state.createArgs.url,layoutComponentId:e.state.instanceId,context:i,bounds:c}):this.glueController.startApp({name:e.application,layoutComponentId:e.state.instanceId,context:i,bounds:c});this.logger?.trace(`[${t}] the component was started`);const u=await l;o&&await this.glueController.callWindow("channels",{name:"joinChannel",execute:async()=>{}},{windowId:u.id,channel:o},{instance:u.id}).catch(console.error)}async restoreWorkspaceFrameComponent(e,t,r,n,i){this.logger?.trace(`[${t}] restoring workspace frame component $with id ${e.state.instanceId} and bounds: ${JSON.stringify(e.state.bounds)}`);const o=i?(await this.getPlatformFrame(t))?.id:void 0,s=await this.createFrameWithWorkspaceComponents(e,o);this.logger?.trace(`[${t}] the frame was restored, selecting the correct workspace`);const a=await s.workspaces();await(a[e.state.selectedWorkspace]?.focus()),this.logger?.trace(`[${t}] the correct workspace was selected, restoring the workspaces context`);const c=Object.assign({},r,n);await Promise.all(a.map(e=>e.updateContext(c))),this.logger?.trace(`[${t}] the frame component ${e.state.instanceId} is restored`)}async canPlatformFrameAcceptComponent(e){const t=await this.getPlatformFrame(e);if(!t)return!1;const r=await t.workspaces();return 1===r.length&&0===r[0].getAllWindows().length}pickComponentForPlatformFrame(e){if(0===e.length)return;return e.find(e=>e.state.context?.isPlatform)||e[0]}async checkTargetBoundsPossible(e){if(window.gtf)return{isPossible:!0};return(await window.getScreenDetails()).screens.find(t=>{const r=e.left>=t.left&&e.left<=t.left+t.width,n=e.top>=t.top&&e.top<=t.top+t.height;return r&&n})?{isPossible:!0}:{isPossible:!1}}async getPlatformFrame(e){if(!this.glueController.isWorkspacesEnabled)return;if(!await this.workspacesController.handleCheckStarted(void 0,e))return;const t=(await this.workspacesController.handleGetPlatformFrameId({},e)).id;return t?this.glueController.getOrCreateWorkspaceFrame({frameId:t}):void 0}async createFrameWithWorkspaceComponents(e,t){const r=await this.glueController.getOrCreateWorkspaceFrame({frameId:t,bounds:e.state.bounds,layoutComponentId:e.state.instanceId});return await this.glueController.invokeMethod(GlueWorkspaceFrameClientControlName,{operation:"initFrameFromSnapshot",operationArguments:{workspaces:e.state.workspaces,keepWorkspaces:[]}},{windowId:r.id}),r}}class LayoutValidator{glueController;workspacesController;constructor(e,t){this.glueController=e,this.workspacesController=t}async doInitialValidation(e,t){this.validateRequiredApplicationsExistence(e),await this.validateWorkspaceConfigurationInPlatform(e,t),this.validateNoAppNameAndUrl(e)}async doFinalValidation(e){this.validateWindowNamesCollision(e),this.validateInstanceIdCollision(e),await this.validateWorkspaceFramesIdCollisions(e)}validateWindowNamesCollision(e){const t=e.components.filter(e=>"window"===e.type&&e.application===defaultNoAppWindowComponentAppName&&!!e.state.createArgs.name).map(e=>e.state.createArgs.name),r=this.glueController.getAllWindowNames(),n=t.filter(e=>r.some(t=>e===t));if(n.length)return ioError.raiseError(`Cannot restore layout: ${e.name}, because there are window names collisions: ${n.join(", ")}`)}validateInstanceIdCollision(e){const t=e.components.filter(e=>"window"===e.type&&!!e.state.instanceId).map(e=>e.state.instanceId),r=this.glueController.getAllOpenedIds(),n=t.filter(e=>r.some(t=>e===t));if(n.length)return ioError.raiseError(`Cannot restore layout: ${e.name}, because there are instances ids collisions: ${n.join(", ")}`)}async validateWorkspaceFramesIdCollisions(e){if(e.components.every(e=>"workspaceFrame"!==e.type))return;const t=await this.glueController.getAllOpenedFrameIds(),r=e.components.filter(e=>"workspaceFrame"===e.type).map(e=>e.state.instanceId).filter(e=>t.some(t=>e===t));return r.length?ioError.raiseError(`Cannot restore layout: ${e.name}, because there are frame ids collisions: ${r.join(", ")}`):void 0}validateNoAppNameAndUrl(e){const t=e.components.filter(e=>"window"===e.type&&e.application===defaultNoAppWindowComponentAppName).filter(e=>!("window"!==e.type||e.state.createArgs.name&&e.state.createArgs.url));if(!t.length)return;const r=t.map(e=>JSON.stringify(e.state.createArgs)).join(", ");return ioError.raiseError(`Cannot restore layout: ${e.name}, because it has window components, which are not defined applications and are missing name or url, provided insufficient createArgs are: ${r}`)}validateRequiredApplicationsExistence(e){const t=this.glueController.getAllApplicationNames(),r=e.components.filter(e=>"window"===e.type&&e.application!==defaultNoAppWindowComponentAppName).map(e=>e.application);if(r.push(...this.getRequiredAppNamesFromWorkspaceFrameComponents(e)),!r.length)return;const n=r.filter(e=>t.every(t=>t!==e));return n.length?ioError.raiseError(`Cannot restore layout: ${e.name}, because some required applications are not registered with this platform: ${n.join(", ")}`):void 0}async validateWorkspaceConfigurationInPlatform(e,t){if(e.components.every(e=>"Workspace"!==e.type||"workspaceFrame"!==e.type))return;const r=(await this.workspacesController.handleCheckStarted({},t))?.started;return r?void 0:ioError.raiseError(`Cannot restore layout: ${e.name}, because this platform does not have a valid Workspaces configuration`)}getRequiredAppNamesFromWorkspaceFrameComponents(e){const t=[];for(const r of e.components)if("workspaceFrame"===r.type){const e=r.state.workspaces.reduce((e,t)=>(e.push(...this.getAllAppNamesFromChildren(t.children)),e),[]);t.push(...e)}return t}getAllAppNamesFromChildren(e){const t=e.filter(e=>"window"===e.type&&!!e.config.appName&&e.config.appName!==defaultNoAppWindowComponentAppName).map(e=>e.config.appName);for(const r of e)"window"!==r.type&&t.push(...this.getAllAppNamesFromChildren(r.children));return t}}class Resetter{glueController;workspacesController;constructor(e,t){this.glueController=e,this.workspacesController=t}get logger(){return logger.get("layouts.resetter")}async closeAllExceptCaller(e,t){const r=this.glueController.getAllOtherNonPlatformWindows(e);await Promise.all(r.map(async e=>{if(this.glueController.isWorkspacesEnabled){if(await this.glueController.getWorkspaceWindowById(e.id))return}return e.close()})),this.glueController.isWorkspacesEnabled&&await this.closeNecessaryWorkspacesFrames(e,t)}async closeCaller(e,t,r){if("plugin"===e)return;if(await this.glueController.getWorkspaceWindowById(t))return void await this.cleanupWorkspaceCaller(t,r);const n=this.glueController.getWindowById(t);n&&"Platform"!==n.name?await n.close():this.logger?.warn("The close caller was missing, is an iframe or is a platform")}async closeNecessaryWorkspacesFrames(e,t){const r=(await this.workspacesController.handleGetPlatformFrameId({},t)).id;let n=await this.glueController.getAllWorkspacesFrames();r&&(n=n.filter(e=>e.id!==r),await this.cleanUpFrameExceptCaller(r,e));const i=await this.glueController.getWorkspaceWindowById(e);i&&(n=n.filter(e=>e.id!==i.frameId),await this.cleanUpFrameExceptCaller(i.frameId,e)),await Promise.all(n.map(e=>e.close()))}async cleanUpFrameExceptCaller(e,t){const r=await this.glueController.getWorkspacesByFrameId(e),n=r.filter(e=>!e.getWindow(e=>e.id===t)),i=r.find(e=>e.getWindow(e=>e.id===t));await Promise.all(n.map(e=>e.close()));const o=i?i.getAllWindows(e=>e.id!==t):[];await Promise.all(o.map(e=>e.close()))}async cleanupWorkspaceCaller(e,t){const r=(await this.workspacesController.handleGetPlatformFrameId({},t)).id,n=await this.glueController.getWorkspaceWindowById(e);n&&(n.frameId!==r?await n.frame.close():await n.workspace.close())}}const searchOperationDecoder=oneOf$1(constant$2("operationCheck"));class SearchController{glueController;appsRepo;layoutsRepo;workspacesRepo;started=!1;repos=[];provider;activeQueries={};unsubFuncs=[];operations={operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)}};constructor(e,t,r,n){this.glueController=e,this.appsRepo=t,this.layoutsRepo=r,this.workspacesRepo=n}get logger(){return logger.get("notifications.controller")}get providerName(){return`io.Connect Browser Platform ${this.glueController.me.instance}`}handlePlatformShutdown(){this.started=!1,this.unsubFuncs.forEach(e=>e()),this.unsubFuncs=[],this.repos=[],this.activeQueries={},this.provider?.unregister()}async configurePostStart(){if(this.repos.push(this.appsRepo),this.repos.push(this.layoutsRepo),!this.glueController.isWorkspacesEnabled)return;this.repos.push(this.workspacesRepo);const e=this.repos.map(e=>({name:e.type,displayName:e.displayType})),t={name:this.providerName,types:e};if(this.logger?.trace(`Registering the platform as a provider with name: ${t.name} and types: ${JSON.stringify(t.types?.join(", "))}.`),this.provider=await this.glueController.registerProvider(t),!this.provider)return ioError.raiseError("The platform was not registered successfully as a provider.");this.logger?.trace("The platform was registered successfully as a provider.");const r=this.provider.onQuery(e=>{this.processQuery(e).then(()=>this.markQueryDone(e)).catch(t=>this.markQueryError(e,t))}),n=this.provider.onQueryCancel(this.processQueryCancel.bind(this));this.unsubFuncs.push(r),this.unsubFuncs.push(n),this.started=!0,this.logger?.info("The module started successfully.")}async start(){this.logger?.info("Starting the Global Search provider.")}ready(){return Promise.resolve()}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this search control message, because the controller has not been started");const t=e.data,r=e.commandId,n=searchOperationDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This search request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`Search request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`Search request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}async processQuery(e){this.logger?.info(`Processing a new query for: ${e.search}`),this.activeQueries[e.id]={allowedResultsCount:e.providerLimits?.maxResults||Number.MAX_SAFE_INTEGER};const t=e.types?this.repos.filter(t=>e.types?.some(e=>e.name===t.type)):this.repos;await Promise.all(t.map(t=>this.callRepo(t,e)))}async callRepo(e,t){const r=await this.getRepoResults(e,t);this.activeQueries[t.id]&&r&&this.sendResults(r,t)}async getRepoResults(e,t){try{return await e.getResults(t)}catch(e){return void this.markQueryError(t,e)}}sendResults(e,t){try{e.forEach(e=>{this.activeQueries[t.id]&&(this.activeQueries[t.id].allowedResultsCount?(--this.activeQueries[t.id].allowedResultsCount,t.sendResult(e)):this.markQueryDone(t))})}catch(e){this.logger?.warn(`Failed sending results for query: ${t.search} with an error: ${extractErrorMsg$1(e)}`)}}markQueryDone(e){this.activeQueries[e.id]&&(this.logger?.info(`The query for: ${e.search} is completed`),delete this.activeQueries[e.id],e.done())}markQueryError(e,t){this.activeQueries[e.id]&&(this.logger?.warn(`The query for: ${e.search} ended with an error: ${extractErrorMsg$1(t)}`),delete this.activeQueries[e.id],e.error(extractErrorMsg$1(t)))}processQueryCancel(e){delete this.activeQueries[e.id]}}class ApplicationsRepository{glueController;type="application";displayType="Applications";constructor(e){this.glueController=e}getResults(e){const t=new Set,r={count:Math.min(e.providerLimits?.maxResultsPerType||Number.MAX_SAFE_INTEGER,e.providerLimits?.maxResults||Number.MAX_SAFE_INTEGER)},n=this.glueController.getAllApplications();if(n.filter(t=>checkMatch(r,()=>!!t.title?.toLowerCase().includes(e.search.toLowerCase()))).forEach(e=>t.add(e)),!r.count)return Promise.resolve(this.transformApps(t));if(n.filter(t=>checkMatch(r,()=>!!t.caption?.toLowerCase().includes(e.search.toLowerCase()))).forEach(e=>t.add(e)),!r.count)return Promise.resolve(this.transformApps(t));return n.filter(t=>checkMatch(r,()=>t.name.toLowerCase().includes(e.search.toLowerCase()))).forEach(e=>t.add(e)),Promise.resolve(this.transformApps(t))}transformApps(e){const t=[];for(const r of e.values())t.push({type:{name:this.type,displayName:this.displayType},id:r.name,displayName:r.title,description:r.caption,iconURL:r.icon});return t}}class LayoutsRepository{glueController;type="layout";displayType="Layouts";constructor(e){this.glueController=e}async getResults(e){const t=new Set,r={count:Math.min(e.providerLimits?.maxResultsPerType||Number.MAX_SAFE_INTEGER,e.providerLimits?.maxResults||Number.MAX_SAFE_INTEGER)};return(await this.glueController.getAllLayoutsSummaries()).filter(t=>checkMatch(r,()=>t.name.toLowerCase().includes(e.search.toLowerCase()))).forEach(e=>t.add(e)),this.transformLayouts(t)}transformLayouts(e){const t=[];for(const r of e.values())t.push({type:{name:this.type,displayName:this.displayType},id:r.name,displayName:r.name});return t}}class WorkspacesRepository{glueController;type="workspace";displayType="Workspaces";constructor(e){this.glueController=e}async getResults(e){const t=new Set,r={count:Math.min(e.providerLimits?.maxResultsPerType||Number.MAX_SAFE_INTEGER,e.providerLimits?.maxResults||Number.MAX_SAFE_INTEGER)};return(await this.glueController.getAllWorkspacesSummaries()).filter(t=>checkMatch(r,()=>t.name.toLowerCase().includes(e.search.toLowerCase()))).forEach(e=>t.add(e)),this.transformWorkspaces(t)}transformWorkspaces(e){const t=[];for(const r of e.values())t.push({type:{name:this.type,displayName:this.displayType},id:r.name,displayName:r.name});return t}}class LocalStoreController{localStorage;defaultGlobalLayoutNamespace="g42_core_plus_default_global_layout";themesNamespace="g42_core_plus_themes";notificationsNamespace="g42_core_notifications_config";restSchedulerNamespace="g42_core_rest_scheduler";username="g42_public";constructor(){this.localStorage=window.localStorage}start(e){e?.id&&(this.username=e.id);if(!this.localStorage.getItem(this.username)){const e={[this.defaultGlobalLayoutNamespace]:{},[this.themesNamespace]:[],[this.restSchedulerNamespace]:{}};this.localStorage.setItem(this.username,JSON.stringify(e))}}stop(){this.username="g42_public"}saveThemeIfMissing(e){const t=this.getData(this.themesNamespace)||[];t.some(t=>t.theme.name===e.theme.name)||(t.push(e),this.saveData(this.themesNamespace,t))}getAllThemes(){return this.getData(this.themesNamespace)||[]}markThemeSelected(e,t){const r=this.getData(this.themesNamespace)||[],n=r.find(t=>t.theme.name===e);return n?(r.forEach(e=>{e.selected=!1,e.isUserSelected=!1}),n.selected=!0,n.isUserSelected=!!t,this.saveData(this.themesNamespace,r),n.theme):ioError.raiseError(`Cannot mark theme: ${e} as selected, because it doesn't exist`)}getRestSchedulerEntry(e){return this.getAllRestSchedulerEntries()[e]}getAllRestSchedulerEntries(){return this.getData(this.restSchedulerNamespace)||{}}saveRestSchedulerEntry(e){const t=this.getAllRestSchedulerEntries();t[e.key]=e,this.saveData(this.restSchedulerNamespace,t)}clearRestSchedulerEntries(){this.saveData(this.restSchedulerNamespace,{})}deleteRestSchedulerEntry(e){const t=this.getAllRestSchedulerEntries();delete t[e],this.saveData(this.restSchedulerNamespace,t)}getDefaultGlobalLayoutName(){const e=this.getData(this.defaultGlobalLayoutNamespace);return e?.name}saveDefaultGlobalLayout(e){this.saveData(this.defaultGlobalLayoutNamespace,{name:e})}clearDefaultGlobalLayout(){this.saveData(this.defaultGlobalLayoutNamespace,{})}getNotificationsConfig(){return this.getData(this.notificationsNamespace)}setNotificationsConfig(e){this.saveData(this.notificationsNamespace,e)}updateNotificationsConfig(e){const t=this.getNotificationsConfig();if(!t)return ioError.raiseError("Cannot update notifications config, because it doesn't exist");this.setNotificationsConfig(deepMerge$1(t,e,{arrayMerge:(e,t)=>t}))}getData(e){const t=this.localStorage.getItem(this.username);return t?JSON.parse(t)[e]:ioError.raiseError(`Cannot get data for namespace: ${e}, because the user data is missing`)}saveData(e,t){const r=this.localStorage.getItem(this.username);if(!r)return ioError.raiseError(`Cannot set data for namespace: ${e}, because the user data is missing`);const n=JSON.parse(r);n[e]=t,this.localStorage.setItem(this.username,JSON.stringify(n))}}const themesOperationDecoder=oneOf$1(constant$2("getCurrent"),constant$2("list"),constant$2("select"),constant$2("operationCheck")),themeDecoder=object$2({displayName:nonEmptyStringDecoder$2,name:nonEmptyStringDecoder$2}),simpleThemeResponseDecoder=object$2({theme:themeDecoder}),allThemesResponseDecoder=object$2({themes:array$3(themeDecoder)}),selectThemeConfigDecoder=object$2({name:nonEmptyStringDecoder$2}),themesStoreDataDecoder=object$2({theme:themeDecoder,selected:boolean$3(),isUserSelected:boolean$3()}),prefsThemesDecoder=object$2({themes:array$3(themesStoreDataDecoder)}),GlueCorePlusThemesStream="T42.Core.Plus.Themes.Stream",lightTheme={name:"light",displayName:"Light"},darkTheme={name:"dark",displayName:"Dark"};class ThemesController{glueController;localStore;prefsStore;started=!1;themesStream;config;initResolve;initPromise=PromisePlus(e=>{this.initResolve=e},3e4,"Themes controller initialization timed out");operations={getCurrent:{name:"getCurrent",resultDecoder:simpleThemeResponseDecoder,execute:this.handleGetCurrent.bind(this)},list:{name:"list",resultDecoder:allThemesResponseDecoder,execute:this.handleList.bind(this)},select:{name:"select",dataDecoder:selectThemeConfigDecoder,execute:this.handleSelect.bind(this)},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)}};constructor(e,t,r){this.glueController=e,this.localStore=t,this.prefsStore=r}get logger(){return logger.get("themes.controller")}async start(e){this.started=!0,this.config=e.themes,this.themesStream=await this.glueController.createSystemStream(GlueCorePlusThemesStream)}async setupInitialThemes(){this.localStore.saveThemeIfMissing({theme:lightTheme,selected:!1,isUserSelected:!1}),this.localStore.saveThemeIfMissing({theme:darkTheme,selected:!1,isUserSelected:!1}),await this.applyInitialTheme(),this.initResolve()}handlePlatformShutdown(){this.started=!1,this.themesStream.close()}ready(){return Promise.resolve()}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this themes control message, because the controller has not been started");await this.initPromise;const t=e.data,r=e.commandId,n=themesOperationDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This themes request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`Themes request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`Themes request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}handleClientUnloaded(){}async applyInitialTheme(){const e=this.prefsStore.storeType;if(!e||"local"===e)return this.logger?.info("The themes service will use the local storage for the themes data"),void this.applyDefaultThemeIfNoUserSelection();let t;try{t=await this.glueController.clientGlue.prefs.get(systemPrefsAppName)}catch(e){return this.logger?.warn(`Failed to get system preferences for themes service: ${e}, falling back to local storage`),void this.applyDefaultThemeIfNoUserSelection()}const r=t?.data[themesPrefsKey];if(!r?.themes?.length)return this.logger?.info("The system preferences for the themes service are not set in prefs, falling back to local storage"),void this.applyDefaultThemeIfNoUserSelection();const n=prefsThemesDecoder.run(r);if(!n.ok)return this.logger?.error(`The system preferences from Prefs for the themes service did not pass validation: ${JSON.stringify(n.error)}, falling back to local storage`),void this.applyDefaultThemeIfNoUserSelection();const i=n.result.themes.find(e=>e.isUserSelected),o=i?.theme.name??this.getDefaultTheme(),s=this.localStore.markThemeSelected(o,!!i);this.themesStream.push({theme:s})}applyDefaultThemeIfNoUserSelection(){if(this.localStore.getAllThemes().some(e=>e.isUserSelected))return;const e=this.localStore.markThemeSelected(this.getDefaultTheme(),!1);this.themesStream.push({theme:e})}getDefaultTheme(){return"os"===this.config.defaultTheme?this.getOsTheme():this.config.defaultTheme===lightTheme.name?lightTheme.name:darkTheme.name}async saveThemesToPrefs(){const e={[themesPrefsKey]:{themes:this.localStore.getAllThemes()}};await this.glueController.clientGlue.prefs.update(e,{app:systemPrefsAppName})}async handleGetCurrent(e,t){this.logger?.trace(`[${t}] handling a getCurrent message`);const r=this.getSelectedTheme();return r?{theme:r}:ioError.raiseError("No selected theme found!")}async handleList(e,t){this.logger?.trace(`[${t}] handling a list message`);return{themes:this.localStore.getAllThemes().map(e=>e.theme)}}async handleSelect(e,t){this.logger?.trace(`[${t}] handling a select message`);const r=this.getSelectedTheme();if(r?.name===e.name)return void this.logger?.debug(`[${t}] The selected theme is already applied, no need to proceed further`);const n=this.localStore.markThemeSelected(e.name,!0);this.themesStream.push({theme:n}),"local"!==this.prefsStore.storeType&&this.saveThemesToPrefs().catch(e=>{this.logger?.warn(`Failed to sync themes to prefs: ${e} - the themes data is only updated in the local storage`)})}getSelectedTheme(){return this.localStore.getAllThemes().find(e=>e.selected)?.theme}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}getOsTheme(){return window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}}function bind(e,t){return function(){return e.apply(t,arguments)}}const{toString:toString}=Object.prototype,{getPrototypeOf:getPrototypeOf$2}=Object,{iterator:iterator,toStringTag:toStringTag}=Symbol,kindOf=(e=>t=>{const r=toString.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),kindOfTest=e=>(e=e.toLowerCase(),t=>kindOf(t)===e),typeOfTest=e=>t=>typeof t===e,{isArray:isArray$2}=Array,isUndefined=typeOfTest("undefined");function isBuffer(e){return null!==e&&!isUndefined(e)&&null!==e.constructor&&!isUndefined(e.constructor)&&isFunction$3(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const isArrayBuffer=kindOfTest("ArrayBuffer");function isArrayBufferView(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&isArrayBuffer(e.buffer),t}const isString=typeOfTest("string"),isFunction$3=typeOfTest("function"),isNumber=typeOfTest("number"),isObject$3=e=>null!==e&&"object"==typeof e,isBoolean=e=>!0===e||!1===e,isPlainObject$2=e=>{if("object"!==kindOf(e))return!1;const t=getPrototypeOf$2(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||toStringTag in e||iterator in e)},isEmptyObject=e=>{if(!isObject$3(e)||isBuffer(e))return!1;try{return 0===Object.keys(e).length&&Object.getPrototypeOf(e)===Object.prototype}catch(e){return!1}},isDate=kindOfTest("Date"),isFile=kindOfTest("File"),isReactNativeBlob=e=>!(!e||void 0===e.uri),isReactNative=e=>e&&void 0!==e.getParts,isBlob=kindOfTest("Blob"),isFileList=kindOfTest("FileList"),isStream=e=>isObject$3(e)&&isFunction$3(e.pipe);function getGlobal$1(){return"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0!==global?global:{}}const G=getGlobal$1(),FormDataCtor=void 0!==G.FormData?G.FormData:void 0,isFormData=e=>{if(!e)return!1;if(FormDataCtor&&e instanceof FormDataCtor)return!0;const t=getPrototypeOf$2(e);if(!t||t===Object.prototype)return!1;if(!isFunction$3(e.append))return!1;const r=kindOf(e);return"formdata"===r||"object"===r&&isFunction$3(e.toString)&&"[object FormData]"===e.toString()},isURLSearchParams=kindOfTest("URLSearchParams"),[isReadableStream,isRequest,isResponse,isHeaders]=["ReadableStream","Request","Response","Headers"].map(kindOfTest),trim=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function forEach(e,t,{allOwnKeys:r=!1}={}){if(null==e)return;let n,i;if("object"!=typeof e&&(e=[e]),isArray$2(e))for(n=0,i=e.length;n<i;n++)t.call(null,e[n],n,e);else{if(isBuffer(e))return;const i=r?Object.getOwnPropertyNames(e):Object.keys(e),o=i.length;let s;for(n=0;n<o;n++)s=i[n],t.call(null,e[s],s,e)}}function findKey(e,t){if(isBuffer(e))return null;t=t.toLowerCase();const r=Object.keys(e);let n,i=r.length;for(;i-- >0;)if(n=r[i],t===n.toLowerCase())return n;return null}const _global$1="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,isContextDefined=e=>!isUndefined(e)&&e!==_global$1;function merge$2(){const{caseless:e,skipUndefined:t}=isContextDefined(this)&&this||{},r={},n=(n,i)=>{if("__proto__"===i||"constructor"===i||"prototype"===i)return;const o=e&&findKey(r,i)||i;isPlainObject$2(r[o])&&isPlainObject$2(n)?r[o]=merge$2(r[o],n):isPlainObject$2(n)?r[o]=merge$2({},n):isArray$2(n)?r[o]=n.slice():t&&isUndefined(n)||(r[o]=n)};for(let e=0,t=arguments.length;e<t;e++)arguments[e]&&forEach(arguments[e],n);return r}const extend=(e,t,r,{allOwnKeys:n}={})=>(forEach(t,(t,n)=>{r&&isFunction$3(t)?Object.defineProperty(e,n,{value:bind(t,r),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(e,n,{value:t,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:n}),e),stripBOM=e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits=(e,t,r,n)=>{e.prototype=Object.create(t.prototype,n),Object.defineProperty(e.prototype,"constructor",{value:e,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject=(e,t,r,n)=>{let i,o,s;const a={};if(t=t||{},null==e)return t;do{for(i=Object.getOwnPropertyNames(e),o=i.length;o-- >0;)s=i[o],n&&!n(s,e,t)||a[s]||(t[s]=e[s],a[s]=!0);e=!1!==r&&getPrototypeOf$2(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},endsWith=(e,t,r)=>{e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;const n=e.indexOf(t,r);return-1!==n&&n===r},toArray=e=>{if(!e)return null;if(isArray$2(e))return e;let t=e.length;if(!isNumber(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},isTypedArray=(e=>t=>e&&t instanceof e)("undefined"!=typeof Uint8Array&&getPrototypeOf$2(Uint8Array)),forEachEntry=(e,t)=>{const r=(e&&e[iterator]).call(e);let n;for(;(n=r.next())&&!n.done;){const r=n.value;t.call(e,r[0],r[1])}},matchAll=(e,t)=>{let r;const n=[];for(;null!==(r=e.exec(t));)n.push(r);return n},isHTMLForm=kindOfTest("HTMLFormElement"),toCamelCase=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(e,t,r){return t.toUpperCase()+r}),hasOwnProperty$2=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),isRegExp=kindOfTest("RegExp"),reduceDescriptors=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),n={};forEach(r,(r,i)=>{let o;!1!==(o=t(r,i,e))&&(n[i]=o||r)}),Object.defineProperties(e,n)},freezeMethods=e=>{reduceDescriptors(e,(t,r)=>{if(isFunction$3(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;const n=e[r];isFunction$3(n)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")}))})},toObjectSet=(e,t)=>{const r={},n=e=>{e.forEach(e=>{r[e]=!0})};return isArray$2(e)?n(e):n(String(e).split(t)),r},noop=()=>{},toFiniteNumber=(e,t)=>null!=e&&Number.isFinite(e=+e)?e:t;function isSpecCompliantForm(e){return!!(e&&isFunction$3(e.append)&&"FormData"===e[toStringTag]&&e[iterator])}const toJSONObject=e=>{const t=new Array(10),r=(e,n)=>{if(isObject$3(e)){if(t.indexOf(e)>=0)return;if(isBuffer(e))return e;if(!("toJSON"in e)){t[n]=e;const i=isArray$2(e)?[]:{};return forEach(e,(e,t)=>{const o=r(e,n+1);!isUndefined(o)&&(i[t]=o)}),t[n]=void 0,i}}return e};return r(e,0)},isAsyncFn=kindOfTest("AsyncFunction"),isThenable=e=>e&&(isObject$3(e)||isFunction$3(e))&&isFunction$3(e.then)&&isFunction$3(e.catch),_setImmediate=(setImmediateSupported="function"==typeof setImmediate,postMessageSupported=isFunction$3(_global$1.postMessage),setImmediateSupported?setImmediate:postMessageSupported?(token=`axios@${Math.random()}`,callbacks=[],_global$1.addEventListener("message",({source:e,data:t})=>{e===_global$1&&t===token&&callbacks.length&&callbacks.shift()()},!1),e=>{callbacks.push(e),_global$1.postMessage(token,"*")}):e=>setTimeout(e));var setImmediateSupported,postMessageSupported,token,callbacks;const asap="undefined"!=typeof queueMicrotask?queueMicrotask.bind(_global$1):_setImmediate,isIterable=e=>null!=e&&isFunction$3(e[iterator]);var utils$3={isArray:isArray$2,isArrayBuffer:isArrayBuffer,isBuffer:isBuffer,isFormData:isFormData,isArrayBufferView:isArrayBufferView,isString:isString,isNumber:isNumber,isBoolean:isBoolean,isObject:isObject$3,isPlainObject:isPlainObject$2,isEmptyObject:isEmptyObject,isReadableStream:isReadableStream,isRequest:isRequest,isResponse:isResponse,isHeaders:isHeaders,isUndefined:isUndefined,isDate:isDate,isFile:isFile,isReactNativeBlob:isReactNativeBlob,isReactNative:isReactNative,isBlob:isBlob,isRegExp:isRegExp,isFunction:isFunction$3,isStream:isStream,isURLSearchParams:isURLSearchParams,isTypedArray:isTypedArray,isFileList:isFileList,forEach:forEach,merge:merge$2,extend:extend,trim:trim,stripBOM:stripBOM,inherits:inherits,toFlatObject:toFlatObject,kindOf:kindOf,kindOfTest:kindOfTest,endsWith:endsWith,toArray:toArray,forEachEntry:forEachEntry,matchAll:matchAll,isHTMLForm:isHTMLForm,hasOwnProperty:hasOwnProperty$2,hasOwnProp:hasOwnProperty$2,reduceDescriptors:reduceDescriptors,freezeMethods:freezeMethods,toObjectSet:toObjectSet,toCamelCase:toCamelCase,noop:noop,toFiniteNumber:toFiniteNumber,findKey:findKey,global:_global$1,isContextDefined:isContextDefined,isSpecCompliantForm:isSpecCompliantForm,toJSONObject:toJSONObject,isAsyncFn:isAsyncFn,isThenable:isThenable,setImmediate:_setImmediate,asap:asap,isIterable:isIterable};let AxiosError$1=class e extends Error{static from(t,r,n,i,o,s){const a=new e(t.message,r||t.code,n,i,o);return a.cause=t,a.name=t.name,null!=t.status&&null==a.status&&(a.status=t.status),s&&Object.assign(a,s),a}constructor(e,t,r,n,i){super(e),Object.defineProperty(this,"message",{value:e,enumerable:!0,writable:!0,configurable:!0}),this.name="AxiosError",this.isAxiosError=!0,t&&(this.code=t),r&&(this.config=r),n&&(this.request=n),i&&(this.response=i,this.status=i.status)}toJSON(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:utils$3.toJSONObject(this.config),code:this.code,status:this.status}}};AxiosError$1.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE",AxiosError$1.ERR_BAD_OPTION="ERR_BAD_OPTION",AxiosError$1.ECONNABORTED="ECONNABORTED",AxiosError$1.ETIMEDOUT="ETIMEDOUT",AxiosError$1.ERR_NETWORK="ERR_NETWORK",AxiosError$1.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS",AxiosError$1.ERR_DEPRECATED="ERR_DEPRECATED",AxiosError$1.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE",AxiosError$1.ERR_BAD_REQUEST="ERR_BAD_REQUEST",AxiosError$1.ERR_CANCELED="ERR_CANCELED",AxiosError$1.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT",AxiosError$1.ERR_INVALID_URL="ERR_INVALID_URL",AxiosError$1.ERR_FORM_DATA_DEPTH_EXCEEDED="ERR_FORM_DATA_DEPTH_EXCEEDED";var httpAdapter=null;function isVisitable(e){return utils$3.isPlainObject(e)||utils$3.isArray(e)}function removeBrackets(e){return utils$3.endsWith(e,"[]")?e.slice(0,-2):e}function renderKey(e,t,r){return e?e.concat(t).map(function(e,t){return e=removeBrackets(e),!r&&t?"["+e+"]":e}).join(r?".":""):t}function isFlatArray(e){return utils$3.isArray(e)&&!e.some(isVisitable)}const predicates=utils$3.toFlatObject(utils$3,{},null,function(e){return/^is[A-Z]/.test(e)});function toFormData$1(e,t,r){if(!utils$3.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const n=(r=utils$3.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(e,t){return!utils$3.isUndefined(t[e])})).metaTokens,i=r.visitor||d,o=r.dots,s=r.indexes,a=r.Blob||"undefined"!=typeof Blob&&Blob,c=void 0===r.maxDepth?100:r.maxDepth,l=a&&utils$3.isSpecCompliantForm(t);if(!utils$3.isFunction(i))throw new TypeError("visitor must be a function");function u(e){if(null===e)return"";if(utils$3.isDate(e))return e.toISOString();if(utils$3.isBoolean(e))return e.toString();if(!l&&utils$3.isBlob(e))throw new AxiosError$1("Blob is not supported. Use a Buffer instead.");return utils$3.isArrayBuffer(e)||utils$3.isTypedArray(e)?l&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function d(e,r,i){let a=e;if(utils$3.isReactNative(t)&&utils$3.isReactNativeBlob(e))return t.append(renderKey(i,r,o),u(e)),!1;if(e&&!i&&"object"==typeof e)if(utils$3.endsWith(r,"{}"))r=n?r:r.slice(0,-2),e=JSON.stringify(e);else if(utils$3.isArray(e)&&isFlatArray(e)||(utils$3.isFileList(e)||utils$3.endsWith(r,"[]"))&&(a=utils$3.toArray(e)))return r=removeBrackets(r),a.forEach(function(e,n){!utils$3.isUndefined(e)&&null!==e&&t.append(!0===s?renderKey([r],n,o):null===s?r:r+"[]",u(e))}),!1;return!!isVisitable(e)||(t.append(renderKey(i,r,o),u(e)),!1)}const h=[],p=Object.assign(predicates,{defaultVisitor:d,convertValue:u,isVisitable:isVisitable});if(!utils$3.isObject(e))throw new TypeError("data must be an object");return function e(r,n,o=0){if(!utils$3.isUndefined(r)){if(o>c)throw new AxiosError$1("Object is too deeply nested ("+o+" levels). Max depth: "+c,AxiosError$1.ERR_FORM_DATA_DEPTH_EXCEEDED);if(-1!==h.indexOf(r))throw Error("Circular reference detected in "+n.join("."));h.push(r),utils$3.forEach(r,function(r,s){!0===(!(utils$3.isUndefined(r)||null===r)&&i.call(t,r,utils$3.isString(s)?s.trim():s,n,p))&&e(r,n?n.concat(s):[s],o+1)}),h.pop()}}(e),t}function encode$1(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"};return encodeURIComponent(e).replace(/[!'()~]|%20/g,function(e){return t[e]})}function AxiosURLSearchParams(e,t){this._pairs=[],e&&toFormData$1(e,this,t)}const prototype=AxiosURLSearchParams.prototype;function encode(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function buildURL(e,t,r){if(!t)return e;const n=r&&r.encode||encode,i=utils$3.isFunction(r)?{serialize:r}:r,o=i&&i.serialize;let s;if(s=o?o(t,i):utils$3.isURLSearchParams(t)?t.toString():new AxiosURLSearchParams(t,i).toString(n),s){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+s}return e}prototype.append=function(e,t){this._pairs.push([e,t])},prototype.toString=function(e){const t=e?function(t){return e.call(this,t,encode$1)}:encode$1;return this._pairs.map(function(e){return t(e[0])+"="+t(e[1])},"").join("&")};class InterceptorManager{constructor(){this.handlers=[]}use(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){utils$3.forEach(this.handlers,function(t){null!==t&&e(t)})}}var transitionalDefaults={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0},URLSearchParams$1="undefined"!=typeof URLSearchParams?URLSearchParams:AxiosURLSearchParams,FormData$2="undefined"!=typeof FormData?FormData:null,Blob$1="undefined"!=typeof Blob?Blob:null,platform$1={isBrowser:!0,classes:{URLSearchParams:URLSearchParams$1,FormData:FormData$2,Blob:Blob$1},protocols:["http","https","file","blob","url","data"]};const hasBrowserEnv="undefined"!=typeof window&&"undefined"!=typeof document,_navigator="object"==typeof navigator&&navigator||void 0,hasStandardBrowserEnv=hasBrowserEnv&&(!_navigator||["ReactNative","NativeScript","NS"].indexOf(_navigator.product)<0),hasStandardBrowserWebWorkerEnv="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,origin=hasBrowserEnv&&window.location.href||"http://localhost";var utils$2=Object.freeze({__proto__:null,hasBrowserEnv:hasBrowserEnv,hasStandardBrowserEnv:hasStandardBrowserEnv,hasStandardBrowserWebWorkerEnv:hasStandardBrowserWebWorkerEnv,navigator:_navigator,origin:origin}),platform={...utils$2,...platform$1};function toURLEncodedForm(e,t){return toFormData$1(e,new platform.classes.URLSearchParams,{visitor:function(e,t,r,n){return platform.isNode&&utils$3.isBuffer(e)?(this.append(t,e.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)},...t})}function parsePropPath(e){return utils$3.matchAll(/\w+|\[(\w*)]/g,e).map(e=>"[]"===e[0]?"":e[1]||e[0])}function arrayToObject(e){const t={},r=Object.keys(e);let n;const i=r.length;let o;for(n=0;n<i;n++)o=r[n],t[o]=e[o];return t}function formDataToJSON(e){function t(e,r,n,i){let o=e[i++];if("__proto__"===o)return!0;const s=Number.isFinite(+o),a=i>=e.length;if(o=!o&&utils$3.isArray(n)?n.length:o,a)return utils$3.hasOwnProp(n,o)?n[o]=utils$3.isArray(n[o])?n[o].concat(r):[n[o],r]:n[o]=r,!s;n[o]&&utils$3.isObject(n[o])||(n[o]=[]);return t(e,r,n[o],i)&&utils$3.isArray(n[o])&&(n[o]=arrayToObject(n[o])),!s}if(utils$3.isFormData(e)&&utils$3.isFunction(e.entries)){const r={};return utils$3.forEachEntry(e,(e,n)=>{t(parsePropPath(e),n,r,0)}),r}return null}const own=(e,t)=>null!=e&&utils$3.hasOwnProp(e,t)?e[t]:void 0;function stringifySafely(e,t,r){if(utils$3.isString(e))try{return(t||JSON.parse)(e),utils$3.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(r||JSON.stringify)(e)}const defaults={transitional:transitionalDefaults,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const r=t.getContentType()||"",n=r.indexOf("application/json")>-1,i=utils$3.isObject(e);i&&utils$3.isHTMLForm(e)&&(e=new FormData(e));if(utils$3.isFormData(e))return n?JSON.stringify(formDataToJSON(e)):e;if(utils$3.isArrayBuffer(e)||utils$3.isBuffer(e)||utils$3.isStream(e)||utils$3.isFile(e)||utils$3.isBlob(e)||utils$3.isReadableStream(e))return e;if(utils$3.isArrayBufferView(e))return e.buffer;if(utils$3.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let o;if(i){const t=own(this,"formSerializer");if(r.indexOf("application/x-www-form-urlencoded")>-1)return toURLEncodedForm(e,t).toString();if((o=utils$3.isFileList(e))||r.indexOf("multipart/form-data")>-1){const r=own(this,"env"),n=r&&r.FormData;return toFormData$1(o?{"files[]":e}:e,n&&new n,t)}}return i||n?(t.setContentType("application/json",!1),stringifySafely(e)):e}],transformResponse:[function(e){const t=own(this,"transitional")||defaults.transitional,r=t&&t.forcedJSONParsing,n=own(this,"responseType"),i="json"===n;if(utils$3.isResponse(e)||utils$3.isReadableStream(e))return e;if(e&&utils$3.isString(e)&&(r&&!n||i)){const r=!(t&&t.silentJSONParsing)&&i;try{return JSON.parse(e,own(this,"parseReviver"))}catch(e){if(r){if("SyntaxError"===e.name)throw AxiosError$1.from(e,AxiosError$1.ERR_BAD_RESPONSE,this,null,own(this,"response"));throw e}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:platform.classes.FormData,Blob:platform.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};utils$3.forEach(["delete","get","head","post","put","patch"],e=>{defaults.headers[e]={}});const ignoreDuplicateOf=utils$3.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]);var parseHeaders=e=>{const t={};let r,n,i;return e&&e.split("\n").forEach(function(e){i=e.indexOf(":"),r=e.substring(0,i).trim().toLowerCase(),n=e.substring(i+1).trim(),!r||t[r]&&ignoreDuplicateOf[r]||("set-cookie"===r?t[r]?t[r].push(n):t[r]=[n]:t[r]=t[r]?t[r]+", "+n:n)}),t};const $internals=Symbol("internals"),INVALID_HEADER_VALUE_CHARS_RE=/[^\x09\x20-\x7E\x80-\xFF]/g;function trimSPorHTAB(e){let t=0,r=e.length;for(;t<r;){const r=e.charCodeAt(t);if(9!==r&&32!==r)break;t+=1}for(;r>t;){const t=e.charCodeAt(r-1);if(9!==t&&32!==t)break;r-=1}return 0===t&&r===e.length?e:e.slice(t,r)}function normalizeHeader(e){return e&&String(e).trim().toLowerCase()}function sanitizeHeaderValue(e){return trimSPorHTAB(e.replace(INVALID_HEADER_VALUE_CHARS_RE,""))}function normalizeValue(e){return!1===e||null==e?e:utils$3.isArray(e)?e.map(normalizeValue):sanitizeHeaderValue(String(e))}function parseTokens(e){const t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=r.exec(e);)t[n[1]]=n[2];return t}const isValidHeaderName=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function matchHeaderValue(e,t,r,n,i){return utils$3.isFunction(n)?n.call(this,t,r):(i&&(t=r),utils$3.isString(t)?utils$3.isString(n)?-1!==t.indexOf(n):utils$3.isRegExp(n)?n.test(t):void 0:void 0)}function formatHeader(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,r)=>t.toUpperCase()+r)}function buildAccessors(e,t){const r=utils$3.toCamelCase(" "+t);["get","set","has"].forEach(n=>{Object.defineProperty(e,n+r,{value:function(e,r,i){return this[n].call(this,t,e,r,i)},configurable:!0})})}let AxiosHeaders$1=class{constructor(e){e&&this.set(e)}set(e,t,r){const n=this;function i(e,t,r){const i=normalizeHeader(t);if(!i)throw new Error("header name must be a non-empty string");const o=utils$3.findKey(n,i);(!o||void 0===n[o]||!0===r||void 0===r&&!1!==n[o])&&(n[o||t]=normalizeValue(e))}const o=(e,t)=>utils$3.forEach(e,(e,r)=>i(e,r,t));if(utils$3.isPlainObject(e)||e instanceof this.constructor)o(e,t);else if(utils$3.isString(e)&&(e=e.trim())&&!isValidHeaderName(e))o(parseHeaders(e),t);else if(utils$3.isObject(e)&&utils$3.isIterable(e)){let r,n,i={};for(const t of e){if(!utils$3.isArray(t))throw TypeError("Object iterator must return a key-value pair");i[n=t[0]]=(r=i[n])?utils$3.isArray(r)?[...r,t[1]]:[r,t[1]]:t[1]}o(i,t)}else null!=e&&i(t,e,r);return this}get(e,t){if(e=normalizeHeader(e)){const r=utils$3.findKey(this,e);if(r){const e=this[r];if(!t)return e;if(!0===t)return parseTokens(e);if(utils$3.isFunction(t))return t.call(this,e,r);if(utils$3.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=normalizeHeader(e)){const r=utils$3.findKey(this,e);return!(!r||void 0===this[r]||t&&!matchHeaderValue(this,this[r],r,t))}return!1}delete(e,t){const r=this;let n=!1;function i(e){if(e=normalizeHeader(e)){const i=utils$3.findKey(r,e);!i||t&&!matchHeaderValue(r,r[i],i,t)||(delete r[i],n=!0)}}return utils$3.isArray(e)?e.forEach(i):i(e),n}clear(e){const t=Object.keys(this);let r=t.length,n=!1;for(;r--;){const i=t[r];e&&!matchHeaderValue(this,this[i],i,e,!0)||(delete this[i],n=!0)}return n}normalize(e){const t=this,r={};return utils$3.forEach(this,(n,i)=>{const o=utils$3.findKey(r,i);if(o)return t[o]=normalizeValue(n),void delete t[i];const s=e?formatHeader(i):String(i).trim();s!==i&&delete t[i],t[s]=normalizeValue(n),r[s]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return utils$3.forEach(this,(r,n)=>{null!=r&&!1!==r&&(t[n]=e&&utils$3.isArray(r)?r.join(", "):r)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+": "+t).join("\n")}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const r=new this(e);return t.forEach(e=>r.set(e)),r}static accessor(e){const t=(this[$internals]=this[$internals]={accessors:{}}).accessors,r=this.prototype;function n(e){const n=normalizeHeader(e);t[n]||(buildAccessors(r,e),t[n]=!0)}return utils$3.isArray(e)?e.forEach(n):n(e),this}};function transformData(e,t){const r=this||defaults,n=t||r,i=AxiosHeaders$1.from(n.headers);let o=n.data;return utils$3.forEach(e,function(e){o=e.call(r,o,i.normalize(),t?t.status:void 0)}),i.normalize(),o}function isCancel$1(e){return!(!e||!e.__CANCEL__)}AxiosHeaders$1.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),utils$3.reduceDescriptors(AxiosHeaders$1.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[r]=e}}}),utils$3.freezeMethods(AxiosHeaders$1);let CanceledError$1=class extends AxiosError$1{constructor(e,t,r){super(null==e?"canceled":e,AxiosError$1.ERR_CANCELED,t,r),this.name="CanceledError",this.__CANCEL__=!0}};function settle(e,t,r){const n=r.config.validateStatus;r.status&&n&&!n(r.status)?t(new AxiosError$1("Request failed with status code "+r.status,[AxiosError$1.ERR_BAD_REQUEST,AxiosError$1.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):e(r)}function parseProtocol(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function speedometer(e,t){e=e||10;const r=new Array(e),n=new Array(e);let i,o=0,s=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),l=n[s];i||(i=c),r[o]=a,n[o]=c;let u=s,d=0;for(;u!==o;)d+=r[u++],u%=e;if(o=(o+1)%e,o===s&&(s=(s+1)%e),c-i<t)return;const h=l&&c-l;return h?Math.round(1e3*d/h):void 0}}function throttle(e,t){let r,n,i=0,o=1e3/t;const s=(t,o=Date.now())=>{i=o,r=null,n&&(clearTimeout(n),n=null),e(...t)};return[(...e)=>{const t=Date.now(),a=t-i;a>=o?s(e,t):(r=e,n||(n=setTimeout(()=>{n=null,s(r)},o-a)))},()=>r&&s(r)]}const progressEventReducer=(e,t,r=3)=>{let n=0;const i=speedometer(50,250);return throttle(r=>{const o=r.loaded,s=r.lengthComputable?r.total:void 0,a=null!=s?Math.min(o,s):o,c=Math.max(0,a-n),l=i(c);n=Math.max(n,a);e({loaded:a,total:s,progress:s?a/s:void 0,bytes:c,rate:l||void 0,estimated:l&&s?(s-a)/l:void 0,event:r,lengthComputable:null!=s,[t?"download":"upload"]:!0})},r)},progressEventDecorator=(e,t)=>{const r=null!=e;return[n=>t[0]({lengthComputable:r,total:e,loaded:n}),t[1]]},asyncDecorator=e=>(...t)=>utils$3.asap(()=>e(...t));var isURLSameOrigin=platform.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,platform.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(platform.origin),platform.navigator&&/(msie|trident)/i.test(platform.navigator.userAgent)):()=>!0,cookies=platform.hasStandardBrowserEnv?{write(e,t,r,n,i,o,s){if("undefined"==typeof document)return;const a=[`${e}=${encodeURIComponent(t)}`];utils$3.isNumber(r)&&a.push(`expires=${new Date(r).toUTCString()}`),utils$3.isString(n)&&a.push(`path=${n}`),utils$3.isString(i)&&a.push(`domain=${i}`),!0===o&&a.push("secure"),utils$3.isString(s)&&a.push(`SameSite=${s}`),document.cookie=a.join("; ")},read(e){if("undefined"==typeof document)return null;const t=document.cookie.match(new RegExp("(?:^|; )"+e+"=([^;]*)"));return t?decodeURIComponent(t[1]):null},remove(e){this.write(e,"",Date.now()-864e5,"/")}}:{write(){},read:()=>null,remove(){}};function isAbsoluteURL(e){return"string"==typeof e&&/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function combineURLs(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function buildFullPath(e,t,r){let n=!isAbsoluteURL(t);return e&&(n||!1===r)?combineURLs(e,t):t}const headersToObject=e=>e instanceof AxiosHeaders$1?{...e}:e;function mergeConfig$2(e,t){t=t||{};const r=Object.create(null);function n(e,t,r,n){return utils$3.isPlainObject(e)&&utils$3.isPlainObject(t)?utils$3.merge.call({caseless:n},e,t):utils$3.isPlainObject(t)?utils$3.merge({},t):utils$3.isArray(t)?t.slice():t}function i(e,t,r,i){return utils$3.isUndefined(t)?utils$3.isUndefined(e)?void 0:n(void 0,e,0,i):n(e,t,0,i)}function o(e,t){if(!utils$3.isUndefined(t))return n(void 0,t)}function s(e,t){return utils$3.isUndefined(t)?utils$3.isUndefined(e)?void 0:n(void 0,e):n(void 0,t)}function a(r,i,o){return utils$3.hasOwnProp(t,o)?n(r,i):utils$3.hasOwnProp(e,o)?n(void 0,r):void 0}Object.defineProperty(r,"hasOwnProperty",{value:Object.prototype.hasOwnProperty,enumerable:!1,writable:!0,configurable:!0});const c={url:o,method:o,data:o,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,allowedSocketPaths:s,responseEncoding:s,validateStatus:a,headers:(e,t,r)=>i(headersToObject(e),headersToObject(t),0,!0)};return utils$3.forEach(Object.keys({...e,...t}),function(n){if("__proto__"===n||"constructor"===n||"prototype"===n)return;const o=utils$3.hasOwnProp(c,n)?c[n]:i,s=o(utils$3.hasOwnProp(e,n)?e[n]:void 0,utils$3.hasOwnProp(t,n)?t[n]:void 0,n);utils$3.isUndefined(s)&&o!==a||(r[n]=s)}),r}var resolveConfig=e=>{const t=mergeConfig$2({},e),r=e=>utils$3.hasOwnProp(t,e)?t[e]:void 0,n=r("data");let i=r("withXSRFToken");const o=r("xsrfHeaderName"),s=r("xsrfCookieName");let a=r("headers");const c=r("auth"),l=r("baseURL"),u=r("allowAbsoluteUrls"),d=r("url");if(t.headers=a=AxiosHeaders$1.from(a),t.url=buildURL(buildFullPath(l,d,u),e.params,e.paramsSerializer),c&&a.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),utils$3.isFormData(n))if(platform.hasStandardBrowserEnv||platform.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(utils$3.isFunction(n.getHeaders)){const e=n.getHeaders(),t=["content-type","content-length"];Object.entries(e).forEach(([e,r])=>{t.includes(e.toLowerCase())&&a.set(e,r)})}if(platform.hasStandardBrowserEnv){utils$3.isFunction(i)&&(i=i(t));if(!0===i||null==i&&isURLSameOrigin(t.url)){const e=o&&s&&cookies.read(s);e&&a.set(o,e)}}return t};const isXHRAdapterSupported="undefined"!=typeof XMLHttpRequest;var xhrAdapter=isXHRAdapterSupported&&function(e){return new Promise(function(t,r){const n=resolveConfig(e);let i=n.data;const o=AxiosHeaders$1.from(n.headers).normalize();let s,a,c,l,u,{responseType:d,onUploadProgress:h,onDownloadProgress:p}=n;function g(){l&&l(),u&&u(),n.cancelToken&&n.cancelToken.unsubscribe(s),n.signal&&n.signal.removeEventListener("abort",s)}let m=new XMLHttpRequest;function f(){if(!m)return;const n=AxiosHeaders$1.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders());settle(function(e){t(e),g()},function(e){r(e),g()},{data:d&&"text"!==d&&"json"!==d?m.response:m.responseText,status:m.status,statusText:m.statusText,headers:n,config:e,request:m}),m=null}m.open(n.method.toUpperCase(),n.url,!0),m.timeout=n.timeout,"onloadend"in m?m.onloadend=f:m.onreadystatechange=function(){m&&4===m.readyState&&(0!==m.status||m.responseURL&&0===m.responseURL.indexOf("file:"))&&setTimeout(f)},m.onabort=function(){m&&(r(new AxiosError$1("Request aborted",AxiosError$1.ECONNABORTED,e,m)),m=null)},m.onerror=function(t){const n=t&&t.message?t.message:"Network Error",i=new AxiosError$1(n,AxiosError$1.ERR_NETWORK,e,m);i.event=t||null,r(i),m=null},m.ontimeout=function(){let t=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded";const i=n.transitional||transitionalDefaults;n.timeoutErrorMessage&&(t=n.timeoutErrorMessage),r(new AxiosError$1(t,i.clarifyTimeoutError?AxiosError$1.ETIMEDOUT:AxiosError$1.ECONNABORTED,e,m)),m=null},void 0===i&&o.setContentType(null),"setRequestHeader"in m&&utils$3.forEach(o.toJSON(),function(e,t){m.setRequestHeader(t,e)}),utils$3.isUndefined(n.withCredentials)||(m.withCredentials=!!n.withCredentials),d&&"json"!==d&&(m.responseType=n.responseType),p&&([c,u]=progressEventReducer(p,!0),m.addEventListener("progress",c)),h&&m.upload&&([a,l]=progressEventReducer(h),m.upload.addEventListener("progress",a),m.upload.addEventListener("loadend",l)),(n.cancelToken||n.signal)&&(s=t=>{m&&(r(!t||t.type?new CanceledError$1(null,e,m):t),m.abort(),m=null)},n.cancelToken&&n.cancelToken.subscribe(s),n.signal&&(n.signal.aborted?s():n.signal.addEventListener("abort",s)));const y=parseProtocol(n.url);y&&-1===platform.protocols.indexOf(y)?r(new AxiosError$1("Unsupported protocol "+y+":",AxiosError$1.ERR_BAD_REQUEST,e)):m.send(i||null)})};const composeSignals=(e,t)=>{const{length:r}=e=e?e.filter(Boolean):[];if(t||r){let r,n=new AbortController;const i=function(e){if(!r){r=!0,s();const t=e instanceof Error?e:this.reason;n.abort(t instanceof AxiosError$1?t:new CanceledError$1(t instanceof Error?t.message:t))}};let o=t&&setTimeout(()=>{o=null,i(new AxiosError$1(`timeout of ${t}ms exceeded`,AxiosError$1.ETIMEDOUT))},t);const s=()=>{e&&(o&&clearTimeout(o),o=null,e.forEach(e=>{e.unsubscribe?e.unsubscribe(i):e.removeEventListener("abort",i)}),e=null)};e.forEach(e=>e.addEventListener("abort",i));const{signal:a}=n;return a.unsubscribe=()=>utils$3.asap(s),a}},streamChunk=function*(e,t){let r=e.byteLength;if(r<t)return void(yield e);let n,i=0;for(;i<r;)n=i+t,yield e.slice(i,n),i=n},readBytes=async function*(e,t){for await(const r of readStream(e))yield*streamChunk(r,t)},readStream=async function*(e){if(e[Symbol.asyncIterator])return void(yield*e);const t=e.getReader();try{for(;;){const{done:e,value:r}=await t.read();if(e)break;yield r}}finally{await t.cancel()}},trackStream=(e,t,r,n)=>{const i=readBytes(e,t);let o,s=0,a=e=>{o||(o=!0,n&&n(e))};return new ReadableStream({async pull(e){try{const{done:t,value:n}=await i.next();if(t)return a(),void e.close();let o=n.byteLength;if(r){let e=s+=o;r(e)}e.enqueue(new Uint8Array(n))}catch(e){throw a(e),e}},cancel:e=>(a(e),i.return())},{highWaterMark:2})},DEFAULT_CHUNK_SIZE=65536,{isFunction:isFunction$2}=utils$3,globalFetchAPI=(({Request:e,Response:t})=>({Request:e,Response:t}))(utils$3.global),{ReadableStream:ReadableStream$1,TextEncoder:TextEncoder$1}=utils$3.global,test=(e,...t)=>{try{return!!e(...t)}catch(e){return!1}},factory$2=e=>{e=utils$3.merge.call({skipUndefined:!0},globalFetchAPI,e);const{fetch:t,Request:r,Response:n}=e,i=t?isFunction$2(t):"function"==typeof fetch,o=isFunction$2(r),s=isFunction$2(n);if(!i)return!1;const a=i&&isFunction$2(ReadableStream$1),c=i&&("function"==typeof TextEncoder$1?(l=new TextEncoder$1,e=>l.encode(e)):async e=>new Uint8Array(await new r(e).arrayBuffer()));var l;const u=o&&a&&test(()=>{let e=!1;const t=new r(platform.origin,{body:new ReadableStream$1,method:"POST",get duplex(){return e=!0,"half"}}),n=t.headers.has("Content-Type");return null!=t.body&&t.body.cancel(),e&&!n}),d=s&&a&&test(()=>utils$3.isReadableStream(new n("").body)),h={stream:d&&(e=>e.body)};i&&["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!h[e]&&(h[e]=(t,r)=>{let n=t&&t[e];if(n)return n.call(t);throw new AxiosError$1(`Response type '${e}' is not supported`,AxiosError$1.ERR_NOT_SUPPORT,r)})});const p=async(e,t)=>{const n=utils$3.toFiniteNumber(e.getContentLength());return null==n?(async e=>{if(null==e)return 0;if(utils$3.isBlob(e))return e.size;if(utils$3.isSpecCompliantForm(e)){const t=new r(platform.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return utils$3.isArrayBufferView(e)||utils$3.isArrayBuffer(e)?e.byteLength:(utils$3.isURLSearchParams(e)&&(e+=""),utils$3.isString(e)?(await c(e)).byteLength:void 0)})(t):n};return async e=>{let{url:i,method:s,data:a,signal:c,cancelToken:l,timeout:g,onDownloadProgress:m,onUploadProgress:f,responseType:y,headers:$,withCredentials:b="same-origin",fetchOptions:w}=resolveConfig(e),v=t||fetch;y=y?(y+"").toLowerCase():"text";let S=composeSignals([c,l&&l.toAbortSignal()],g),E=null;const C=S&&S.unsubscribe&&(()=>{S.unsubscribe()});let _;try{if(f&&u&&"get"!==s&&"head"!==s&&0!==(_=await p($,a))){let e,t=new r(i,{method:"POST",body:a,duplex:"half"});if(utils$3.isFormData(a)&&(e=t.headers.get("content-type"))&&$.setContentType(e),t.body){const[e,r]=progressEventDecorator(_,progressEventReducer(asyncDecorator(f)));a=trackStream(t.body,DEFAULT_CHUNK_SIZE,e,r)}}utils$3.isString(b)||(b=b?"include":"omit");const t=o&&"credentials"in r.prototype;if(utils$3.isFormData(a)){const e=$.getContentType();e&&/^multipart\/form-data/i.test(e)&&!/boundary=/i.test(e)&&$.delete("content-type")}const c={...w,signal:S,method:s.toUpperCase(),headers:$.normalize().toJSON(),body:a,duplex:"half",credentials:t?b:void 0};E=o&&new r(i,c);let l=await(o?v(E,w):v(i,c));const g=d&&("stream"===y||"response"===y);if(d&&(m||g&&C)){const e={};["status","statusText","headers"].forEach(t=>{e[t]=l[t]});const t=utils$3.toFiniteNumber(l.headers.get("content-length")),[r,i]=m&&progressEventDecorator(t,progressEventReducer(asyncDecorator(m),!0))||[];l=new n(trackStream(l.body,DEFAULT_CHUNK_SIZE,r,()=>{i&&i(),C&&C()}),e)}y=y||"text";let I=await h[utils$3.findKey(h,y)||"text"](l,e);return!g&&C&&C(),await new Promise((t,r)=>{settle(t,r,{data:I,headers:AxiosHeaders$1.from(l.headers),status:l.status,statusText:l.statusText,config:e,request:E})})}catch(t){if(C&&C(),t&&"TypeError"===t.name&&/Load failed|fetch/i.test(t.message))throw Object.assign(new AxiosError$1("Network Error",AxiosError$1.ERR_NETWORK,e,E,t&&t.response),{cause:t.cause||t});throw AxiosError$1.from(t,t&&t.code,e,E,t&&t.response)}}},seedCache=new Map,getFetch=e=>{let t=e&&e.env||{};const{fetch:r,Request:n,Response:i}=t,o=[n,i,r];let s,a,c=o.length,l=seedCache;for(;c--;)s=o[c],a=l.get(s),void 0===a&&l.set(s,a=c?new Map:factory$2(t)),l=a;return a};getFetch();const knownAdapters={http:httpAdapter,xhr:xhrAdapter,fetch:{get:getFetch}};utils$3.forEach(knownAdapters,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(e){}Object.defineProperty(e,"adapterName",{value:t})}});const renderReason=e=>`- ${e}`,isResolvedHandle=e=>utils$3.isFunction(e)||null===e||!1===e;function getAdapter$1(e,t){e=utils$3.isArray(e)?e:[e];const{length:r}=e;let n,i;const o={};for(let s=0;s<r;s++){let r;if(n=e[s],i=n,!isResolvedHandle(n)&&(i=knownAdapters[(r=String(n)).toLowerCase()],void 0===i))throw new AxiosError$1(`Unknown adapter '${r}'`);if(i&&(utils$3.isFunction(i)||(i=i.get(t))))break;o[r||"#"+s]=i}if(!i){const e=Object.entries(o).map(([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build"));let t=r?e.length>1?"since :\n"+e.map(renderReason).join("\n"):" "+renderReason(e[0]):"as no adapter specified";throw new AxiosError$1("There is no suitable adapter to dispatch the request "+t,"ERR_NOT_SUPPORT")}return i}var adapters={getAdapter:getAdapter$1,adapters:knownAdapters};function throwIfCancellationRequested(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new CanceledError$1(null,e)}function dispatchRequest(e){throwIfCancellationRequested(e),e.headers=AxiosHeaders$1.from(e.headers),e.data=transformData.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return adapters.getAdapter(e.adapter||defaults.adapter,e)(e).then(function(t){return throwIfCancellationRequested(e),t.data=transformData.call(e,e.transformResponse,t),t.headers=AxiosHeaders$1.from(t.headers),t},function(t){return isCancel$1(t)||(throwIfCancellationRequested(e),t&&t.response&&(t.response.data=transformData.call(e,e.transformResponse,t.response),t.response.headers=AxiosHeaders$1.from(t.response.headers))),Promise.reject(t)})}const VERSION$6="1.15.2",validators$1={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{validators$1[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const deprecatedWarnings={};function assertOptions(e,t,r){if("object"!=typeof e)throw new AxiosError$1("options must be an object",AxiosError$1.ERR_BAD_OPTION_VALUE);const n=Object.keys(e);let i=n.length;for(;i-- >0;){const o=n[i],s=Object.prototype.hasOwnProperty.call(t,o)?t[o]:void 0;if(s){const t=e[o],r=void 0===t||s(t,o,e);if(!0!==r)throw new AxiosError$1("option "+o+" must be "+r,AxiosError$1.ERR_BAD_OPTION_VALUE);continue}if(!0!==r)throw new AxiosError$1("Unknown option "+o,AxiosError$1.ERR_BAD_OPTION)}}validators$1.transitional=function(e,t,r){function n(e,t){return"[Axios v"+VERSION$6+"] Transitional option '"+e+"'"+t+(r?". "+r:"")}return(r,i,o)=>{if(!1===e)throw new AxiosError$1(n(i," has been removed"+(t?" in "+t:"")),AxiosError$1.ERR_DEPRECATED);return t&&!deprecatedWarnings[i]&&(deprecatedWarnings[i]=!0,console.warn(n(i," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,i,o)}},validators$1.spelling=function(e){return(t,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};var validator$1={assertOptions:assertOptions,validators:validators$1};const validators=validator$1.validators;let Axios$1=class{constructor(e){this.defaults=e||{},this.interceptors={request:new InterceptorManager,response:new InterceptorManager}}async request(e,t){try{return await this._request(e,t)}catch(e){if(e instanceof Error){let t={};Error.captureStackTrace?Error.captureStackTrace(t):t=new Error;const r=(()=>{if(!t.stack)return"";const e=t.stack.indexOf("\n");return-1===e?"":t.stack.slice(e+1)})();try{if(e.stack){if(r){const t=r.indexOf("\n"),n=-1===t?-1:r.indexOf("\n",t+1),i=-1===n?"":r.slice(n+1);String(e.stack).endsWith(i)||(e.stack+="\n"+r)}}else e.stack=r}catch(e){}}throw e}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=mergeConfig$2(this.defaults,t);const{transitional:r,paramsSerializer:n,headers:i}=t;void 0!==r&&validator$1.assertOptions(r,{silentJSONParsing:validators.transitional(validators.boolean),forcedJSONParsing:validators.transitional(validators.boolean),clarifyTimeoutError:validators.transitional(validators.boolean),legacyInterceptorReqResOrdering:validators.transitional(validators.boolean)},!1),null!=n&&(utils$3.isFunction(n)?t.paramsSerializer={serialize:n}:validator$1.assertOptions(n,{encode:validators.function,serialize:validators.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),validator$1.assertOptions(t,{baseUrl:validators.spelling("baseURL"),withXsrfToken:validators.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let o=i&&utils$3.merge(i.common,i[t.method]);i&&utils$3.forEach(["delete","get","head","post","put","patch","common"],e=>{delete i[e]}),t.headers=AxiosHeaders$1.concat(o,i);const s=[];let a=!0;this.interceptors.request.forEach(function(e){if("function"==typeof e.runWhen&&!1===e.runWhen(t))return;a=a&&e.synchronous;const r=t.transitional||transitionalDefaults;r&&r.legacyInterceptorReqResOrdering?s.unshift(e.fulfilled,e.rejected):s.push(e.fulfilled,e.rejected)});const c=[];let l;this.interceptors.response.forEach(function(e){c.push(e.fulfilled,e.rejected)});let u,d=0;if(!a){const e=[dispatchRequest.bind(this),void 0];for(e.unshift(...s),e.push(...c),u=e.length,l=Promise.resolve(t);d<u;)l=l.then(e[d++],e[d++]);return l}u=s.length;let h=t;for(;d<u;){const e=s[d++],t=s[d++];try{h=e(h)}catch(e){t.call(this,e);break}}try{l=dispatchRequest.call(this,h)}catch(e){return Promise.reject(e)}for(d=0,u=c.length;d<u;)l=l.then(c[d++],c[d++]);return l}getUri(e){return buildURL(buildFullPath((e=mergeConfig$2(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}};utils$3.forEach(["delete","get","head","options"],function(e){Axios$1.prototype[e]=function(t,r){return this.request(mergeConfig$2(r||{},{method:e,url:t,data:(r||{}).data}))}}),utils$3.forEach(["post","put","patch"],function(e){function t(t){return function(r,n,i){return this.request(mergeConfig$2(i||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:r,data:n}))}}Axios$1.prototype[e]=t(),Axios$1.prototype[e+"Form"]=t(!0)});let CancelToken$1=class e{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise(function(e){t=e});const r=this;this.promise.then(e=>{if(!r._listeners)return;let t=r._listeners.length;for(;t-- >0;)r._listeners[t](e);r._listeners=null}),this.promise.then=e=>{let t;const n=new Promise(e=>{r.subscribe(e),t=e}).then(e);return n.cancel=function(){r.unsubscribe(t)},n},e(function(e,n,i){r.reason||(r.reason=new CanceledError$1(e,n,i),t(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let t;const r=new e(function(e){t=e});return{token:r,cancel:t}}};function spread$1(e){return function(t){return e.apply(null,t)}}function isAxiosError$1(e){return utils$3.isObject(e)&&!0===e.isAxiosError}const HttpStatusCode$1={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};function createInstance(e){const t=new Axios$1(e),r=bind(Axios$1.prototype.request,t);return utils$3.extend(r,Axios$1.prototype,t,{allOwnKeys:!0}),utils$3.extend(r,t,null,{allOwnKeys:!0}),r.create=function(t){return createInstance(mergeConfig$2(e,t))},r}Object.entries(HttpStatusCode$1).forEach(([e,t])=>{HttpStatusCode$1[t]=e});const axios=createInstance(defaults);axios.Axios=Axios$1,axios.CanceledError=CanceledError$1,axios.CancelToken=CancelToken$1,axios.isCancel=isCancel$1,axios.VERSION=VERSION$6,axios.toFormData=toFormData$1,axios.AxiosError=AxiosError$1,axios.Cancel=axios.CanceledError,axios.all=function(e){return Promise.all(e)},axios.spread=spread$1,axios.isAxiosError=isAxiosError$1,axios.mergeConfig=mergeConfig$2,axios.AxiosHeaders=AxiosHeaders$1,axios.formToJSON=e=>formDataToJSON(utils$3.isHTMLForm(e)?new FormData(e):e),axios.getAdapter=adapters.getAdapter,axios.HttpStatusCode=HttpStatusCode$1,axios.default=axios;const{Axios:Axios,AxiosError:AxiosError,CanceledError:CanceledError,isCancel:isCancel,CancelToken:CancelToken,VERSION:VERSION$5,all:all,Cancel:Cancel,isAxiosError:isAxiosError,spread:spread,toFormData:toFormData,AxiosHeaders:AxiosHeaders,HttpStatusCode:HttpStatusCode,formToJSON:formToJSON,getAdapter:getAdapter,mergeConfig:mergeConfig$1}=axios;class InvalidTokenError extends Error{}function b64DecodeUnicode(e){return decodeURIComponent(atob(e).replace(/(.)/g,(e,t)=>{let r=t.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r}))}function base64UrlDecode(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return b64DecodeUnicode(t)}catch(e){return atob(t)}}function jwtDecode(e,t){if("string"!=typeof e)throw new InvalidTokenError("Invalid token specified: must be a string");t||(t={});const r=!0===t.header?0:1,n=e.split(".")[r];if("string"!=typeof n)throw new InvalidTokenError(`Invalid token specified: missing part #${r+1}`);let i;try{i=base64UrlDecode(n)}catch(e){throw new InvalidTokenError(`Invalid token specified: invalid base64 for part #${r+1} (${e.message})`)}try{return JSON.parse(i)}catch(e){throw new InvalidTokenError(`Invalid token specified: invalid json for part #${r+1} (${e.message})`)}}InvalidTokenError.prototype.name="InvalidTokenError";var browser="object"==typeof self?self.FormData:window.FormData,FormData$1=getDefaultExportFromCjs$2(browser);function $constructor(e,t,r){function n(r,n){if(r._zod||Object.defineProperty(r,"_zod",{value:{def:n,constr:s,traits:new Set},enumerable:!1}),r._zod.traits.has(e))return;r._zod.traits.add(e),t(r,n);const i=s.prototype,o=Object.keys(i);for(let e=0;e<o.length;e++){const t=o[e];t in r||(r[t]=i[t].bind(r))}}const i=r?.Parent??Object;class o extends i{}function s(e){var t;const i=r?.Parent?new o:this;n(i,e),(t=i._zod).deferred??(t.deferred=[]);for(const e of i._zod.deferred)e();return i}return Object.defineProperty(o,"name",{value:e}),Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:t=>!!(r?.Parent&&t instanceof r.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}class $ZodAsyncError extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const globalConfig={};function config(e){return globalConfig}function jsonStringifyReplacer(e,t){return"bigint"==typeof t?t.toString():t}function cached(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function nullish(e){return null==e}function cleanRegex(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}const EVALUATING=Symbol("evaluating");function defineLazy(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==EVALUATING)return void 0===n&&(n=EVALUATING,n=r()),n},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}const captureStackTrace="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function isObject$2(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function clone(e,t,r){const n=new e._zod.constr(t??e._zod.def);return t&&!r?.parent||(n._zod.parent=e),n}function normalizeParams(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(void 0!==t?.error)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}function optionalKeys(e){return Object.keys(e).filter(t=>"optional"===e[t]._zod.optin&&"optional"===e[t]._zod.optout)}function aborted(e,t=0){if(!0===e.aborted)return!0;for(let r=t;r<e.issues.length;r++)if(!0!==e.issues[r]?.continue)return!0;return!1}function prefixIssues(e,t){return t.map(t=>{var r;return(r=t).path??(r.path=[]),t.path.unshift(e),t})}function unwrapMessage(e){return"string"==typeof e?e:e?.message}function finalizeIssue(e,t,r){const n={...e,path:e.path??[]};if(!e.message){const i=unwrapMessage(e.inst?._zod.def?.error?.(e))??unwrapMessage(t?.error?.(e))??unwrapMessage(r.customError?.(e))??unwrapMessage(r.localeError?.(e))??"Invalid input";n.message=i}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function getLengthableOrigin(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}const initializer=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,jsonStringifyReplacer,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},$ZodError=$constructor("$ZodError",initializer),$ZodRealError=$constructor("$ZodError",initializer,{Parent:Error}),_parse=e=>(t,r,n,i)=>{const o=n?Object.assign(n,{async:!1}):{async:!1},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new $ZodAsyncError;if(s.issues.length){const t=new(i?.Err??e)(s.issues.map(e=>finalizeIssue(e,o,config())));throw captureStackTrace(t,i?.callee),t}return s.value},parse=_parse($ZodRealError),_parseAsync=e=>async(t,r,n,i)=>{const o=n?Object.assign(n,{async:!0}):{async:!0};let s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){const t=new(i?.Err??e)(s.issues.map(e=>finalizeIssue(e,o,config())));throw captureStackTrace(t,i?.callee),t}return s.value},parseAsync=_parseAsync($ZodRealError),_safeParse=e=>(t,r,n)=>{const i=n?{...n,async:!1}:{async:!1},o=t._zod.run({value:r,issues:[]},i);if(o instanceof Promise)throw new $ZodAsyncError;return o.issues.length?{success:!1,error:new(e??$ZodError)(o.issues.map(e=>finalizeIssue(e,i,config())))}:{success:!0,data:o.value}},safeParse=_safeParse($ZodRealError),_safeParseAsync=e=>async(t,r,n)=>{const i=n?Object.assign(n,{async:!0}):{async:!0};let o=t._zod.run({value:r,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(e=>finalizeIssue(e,i,config())))}:{success:!0,data:o.value}},safeParseAsync=_safeParseAsync($ZodRealError),dateSource="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",date$1=new RegExp(`^${dateSource}$`);function timeSource(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function datetime$1(e){const t=timeSource({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const n=`${t}(?:${r.join("|")})`;return new RegExp(`^${dateSource}T(?:${n})$`)}const string$1=e=>new RegExp(`^${e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*"}$`),number$1=/^-?\d+(?:\.\d+)?/,boolean$1=/^(?:true|false)$/i,_null$2=/^null$/i,_undefined$2=/^undefined$/i,$ZodCheck=$constructor("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),$ZodCheckMinLength=$constructor("$ZodCheckMinLength",(e,t)=>{var r;$ZodCheck.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!nullish(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const r=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const n=r.value;if(n.length>=t.minimum)return;const i=getLengthableOrigin(n);r.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),$ZodCheckStringFormat=$constructor("$ZodCheckStringFormat",(e,t)=>{var r,n;$ZodCheck.init(e,t),e._zod.onattach.push(e=>{const r=e._zod.bag;r.format=t.format,t.pattern&&(r.patterns??(r.patterns=new Set),r.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),version={major:4,minor:1,patch:13},$ZodType=$constructor("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=version;const n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(const t of n)for(const r of t._zod.onattach)r(e);if(0===n.length)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const t=(e,t,r)=>{let n,i=aborted(e);for(const o of t){if(o._zod.def.when){if(!o._zod.def.when(e))continue}else if(i)continue;const t=e.issues.length,s=o._zod.check(e);if(s instanceof Promise&&!1===r?.async)throw new $ZodAsyncError;if(n||s instanceof Promise)n=(n??Promise.resolve()).then(async()=>{await s;e.issues.length!==t&&(i||(i=aborted(e,t)))});else{if(e.issues.length===t)continue;i||(i=aborted(e,t))}}return n?n.then(()=>e):e},r=(r,i,o)=>{if(aborted(r))return r.aborted=!0,r;const s=t(i,n,o);if(s instanceof Promise){if(!1===o.async)throw new $ZodAsyncError;return s.then(t=>e._zod.parse(t,o))}return e._zod.parse(s,o)};e._zod.run=(i,o)=>{if(o.skipChecks)return e._zod.parse(i,o);if("backward"===o.direction){const t=e._zod.parse({value:i.value,issues:[]},{...o,skipChecks:!0});return t instanceof Promise?t.then(e=>r(e,i,o)):r(t,i,o)}const s=e._zod.parse(i,o);if(s instanceof Promise){if(!1===o.async)throw new $ZodAsyncError;return s.then(e=>t(e,n,o))}return t(s,n,o)}}e["~standard"]={validate:t=>{try{const r=safeParse(e,t);return r.success?{value:r.data}:{issues:r.error?.issues}}catch(r){return safeParseAsync(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}}),$ZodString=$constructor("$ZodString",(e,t)=>{$ZodType.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??string$1(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch(n){}return"string"==typeof r.value||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),$ZodStringFormat=$constructor("$ZodStringFormat",(e,t)=>{$ZodCheckStringFormat.init(e,t),$ZodString.init(e,t)}),$ZodISODateTime=$constructor("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=datetime$1(t)),$ZodStringFormat.init(e,t)}),$ZodISODate=$constructor("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=date$1),$ZodStringFormat.init(e,t)}),$ZodNumber=$constructor("$ZodNumber",(e,t)=>{$ZodType.init(e,t),e._zod.pattern=e._zod.bag.pattern??number$1,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch(e){}const i=r.value;if("number"==typeof i&&!Number.isNaN(i)&&Number.isFinite(i))return r;const o="number"==typeof i?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...o?{received:o}:{}}),r}}),$ZodBoolean=$constructor("$ZodBoolean",(e,t)=>{$ZodType.init(e,t),e._zod.pattern=boolean$1,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Boolean(r.value)}catch(e){}const i=r.value;return"boolean"==typeof i||r.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),r}}),$ZodUndefined=$constructor("$ZodUndefined",(e,t)=>{$ZodType.init(e,t),e._zod.pattern=_undefined$2,e._zod.values=new Set([void 0]),e._zod.optin="optional",e._zod.optout="optional",e._zod.parse=(t,r)=>{const n=t.value;return void 0===n||t.issues.push({expected:"undefined",code:"invalid_type",input:n,inst:e}),t}}),$ZodNull=$constructor("$ZodNull",(e,t)=>{$ZodType.init(e,t),e._zod.pattern=_null$2,e._zod.values=new Set([null]),e._zod.parse=(t,r)=>{const n=t.value;return null===n||t.issues.push({expected:"null",code:"invalid_type",input:n,inst:e}),t}}),$ZodUnknown=$constructor("$ZodUnknown",(e,t)=>{$ZodType.init(e,t),e._zod.parse=e=>e});function handleArrayResult(e,t,r){e.issues.length&&t.issues.push(...prefixIssues(r,e.issues)),t.value[r]=e.value}const $ZodArray=$constructor("$ZodArray",(e,t)=>{$ZodType.init(e,t),e._zod.parse=(r,n)=>{const i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),r;r.value=Array(i.length);const o=[];for(let e=0;e<i.length;e++){const s=i[e],a=t.element._zod.run({value:s,issues:[]},n);a instanceof Promise?o.push(a.then(t=>handleArrayResult(t,r,e))):handleArrayResult(a,r,e)}return o.length?Promise.all(o).then(()=>r):r}});function handlePropertyResult(e,t,r,n){e.issues.length&&t.issues.push(...prefixIssues(r,e.issues)),void 0===e.value?r in n&&(t.value[r]=void 0):t.value[r]=e.value}function normalizeDef(e){const t=Object.keys(e.shape);for(const r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const r=optionalKeys(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function handleCatchall(e,t,r,n,i,o){const s=[],a=i.keySet,c=i.catchall._zod,l=c.def.type;for(const i in t){if(a.has(i))continue;if("never"===l){s.push(i);continue}const o=c.run({value:t[i],issues:[]},n);o instanceof Promise?e.push(o.then(e=>handlePropertyResult(e,r,i,t))):handlePropertyResult(o,r,i,t)}return s.length&&r.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:o}),e.length?Promise.all(e).then(()=>r):r}const $ZodObject=$constructor("$ZodObject",(e,t)=>{$ZodType.init(e,t);const r=Object.getOwnPropertyDescriptor(t,"shape");if(!r?.get){const e=t.shape;Object.defineProperty(t,"shape",{get:()=>{const r={...e};return Object.defineProperty(t,"shape",{value:r}),r}})}const n=cached(()=>normalizeDef(t));defineLazy(e._zod,"propValues",()=>{const e=t.shape,r={};for(const t in e){const n=e[t]._zod;if(n.values){r[t]??(r[t]=new Set);for(const e of n.values)r[t].add(e)}}return r});const i=isObject$2,o=t.catchall;let s;e._zod.parse=(t,r)=>{s??(s=n.value);const a=t.value;if(!i(a))return t.issues.push({expected:"object",code:"invalid_type",input:a,inst:e}),t;t.value={};const c=[],l=s.shape;for(const e of s.keys){const n=l[e]._zod.run({value:a[e],issues:[]},r);n instanceof Promise?c.push(n.then(r=>handlePropertyResult(r,t,e,a))):handlePropertyResult(n,t,e,a)}return o?handleCatchall(c,a,t,r,n.value,e):c.length?Promise.all(c).then(()=>t):t}});function handleUnionResults(e,t,r,n){for(const r of e)if(0===r.issues.length)return t.value=r.value,t;const i=e.filter(e=>!aborted(e));return 1===i.length?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(e=>e.issues.map(e=>finalizeIssue(e,n,config())))}),t)}const $ZodUnion=$constructor("$ZodUnion",(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),defineLazy(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),defineLazy(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),defineLazy(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){const e=t.options.map(e=>e._zod.pattern);return new RegExp(`^(${e.map(e=>cleanRegex(e.source)).join("|")})$`)}});const r=1===t.options.length,n=t.options[0]._zod.run;e._zod.parse=(i,o)=>{if(r)return n(i,o);let s=!1;const a=[];for(const e of t.options){const t=e._zod.run({value:i.value,issues:[]},o);if(t instanceof Promise)a.push(t),s=!0;else{if(0===t.issues.length)return t;a.push(t)}}return s?Promise.all(a).then(t=>handleUnionResults(t,i,e,o)):handleUnionResults(a,i,e,o)}});function handleOptionalResult(e,t){return e.issues.length&&void 0===t?{issues:[],value:void 0}:e}const $ZodOptional=$constructor("$ZodOptional",(e,t)=>{$ZodType.init(e,t),e._zod.optin="optional",e._zod.optout="optional",defineLazy(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),defineLazy(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${cleanRegex(e.source)})?$`):void 0}),e._zod.parse=(e,r)=>{if("optional"===t.innerType._zod.optin){const n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(t=>handleOptionalResult(t,e.value)):handleOptionalResult(n,e.value)}return void 0===e.value?e:t.innerType._zod.run(e,r)}});var _a;class $ZodRegistry{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){const r=t[0];if(this._map.set(e,r),r&&"object"==typeof r&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const r={...this.get(t)??{}};delete r.id;const n={...r,...this._map.get(e)};return Object.keys(n).length?n:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function registry(){return new $ZodRegistry}function _string(e,t){return new e({type:"string",...normalizeParams(t)})}function _isoDateTime(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...normalizeParams(t)})}function _isoDate(e,t){return new e({type:"string",format:"date",check:"string_format",...normalizeParams(t)})}function _number(e,t){return new e({type:"number",checks:[],...normalizeParams(t)})}function _boolean(e,t){return new e({type:"boolean",...normalizeParams(t)})}function _undefined$1(e,t){return new e({type:"undefined",...normalizeParams(t)})}function _null$1(e,t){return new e({type:"null",...normalizeParams(t)})}function _unknown(e){return new e({type:"unknown"})}function _minLength(e,t){return new $ZodCheckMinLength({check:"min_length",...normalizeParams(t),minimum:e})}(_a=globalThis).__zod_globalRegistry??(_a.__zod_globalRegistry=registry());const ZodMiniType=$constructor("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");$ZodType.init(e,t),e.def=t,e.type=t.type,e.parse=(t,r)=>parse(e,t,r,{callee:e.parse}),e.safeParse=(t,r)=>safeParse(e,t,r),e.parseAsync=async(t,r)=>parseAsync(e,t,r,{callee:e.parseAsync}),e.safeParseAsync=async(t,r)=>safeParseAsync(e,t,r),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),e.clone=(t,r)=>clone(e,t,r),e.brand=()=>e,e.register=(t,r)=>(t.add(e,r),e)}),ZodMiniString=$constructor("ZodMiniString",(e,t)=>{$ZodString.init(e,t),ZodMiniType.init(e,t)});function string(e){return _string(ZodMiniString,e)}const ZodMiniStringFormat=$constructor("ZodMiniStringFormat",(e,t)=>{$ZodStringFormat.init(e,t),ZodMiniString.init(e,t)}),ZodMiniNumber=$constructor("ZodMiniNumber",(e,t)=>{$ZodNumber.init(e,t),ZodMiniType.init(e,t)});function number(e){return _number(ZodMiniNumber,e)}const ZodMiniBoolean=$constructor("ZodMiniBoolean",(e,t)=>{$ZodBoolean.init(e,t),ZodMiniType.init(e,t)});function boolean(e){return _boolean(ZodMiniBoolean,e)}const ZodMiniUndefined=$constructor("ZodMiniUndefined",(e,t)=>{$ZodUndefined.init(e,t),ZodMiniType.init(e,t)});function _undefined(e){return _undefined$1(ZodMiniUndefined,e)}const ZodMiniNull=$constructor("ZodMiniNull",(e,t)=>{$ZodNull.init(e,t),ZodMiniType.init(e,t)});function _null(e){return _null$1(ZodMiniNull,e)}const ZodMiniUnknown=$constructor("ZodMiniUnknown",(e,t)=>{$ZodUnknown.init(e,t),ZodMiniType.init(e,t)});function unknown(){return _unknown(ZodMiniUnknown)}const ZodMiniArray=$constructor("ZodMiniArray",(e,t)=>{$ZodArray.init(e,t),ZodMiniType.init(e,t)});function array(e,t){return new ZodMiniArray({type:"array",element:e,...normalizeParams(t)})}const ZodMiniObject=$constructor("ZodMiniObject",(e,t)=>{$ZodObject.init(e,t),ZodMiniType.init(e,t),defineLazy(e,"shape",()=>t.shape)});function looseObject(e,t){return new ZodMiniObject({type:"object",shape:e,catchall:unknown(),...normalizeParams(t)})}const ZodMiniUnion=$constructor("ZodMiniUnion",(e,t)=>{$ZodUnion.init(e,t),ZodMiniType.init(e,t)});function union(e,t){return new ZodMiniUnion({type:"union",options:e,...normalizeParams(t)})}const ZodMiniOptional=$constructor("ZodMiniOptional",(e,t)=>{$ZodOptional.init(e,t),ZodMiniType.init(e,t)});function optional(e){return new ZodMiniOptional({type:"optional",innerType:e})}const ZodMiniISODateTime=$constructor("ZodMiniISODateTime",(e,t)=>{$ZodISODateTime.init(e,t),ZodMiniStringFormat.init(e,t)});function datetime(e){return _isoDateTime(ZodMiniISODateTime,e)}const ZodMiniISODate=$constructor("ZodMiniISODate",(e,t)=>{$ZodISODate.init(e,t),ZodMiniStringFormat.init(e,t)});function date(e){return _isoDate(ZodMiniISODate,e)}var clientCapabilities=[{capability:"ADMIN_API_V2_APP_ADD",introducedInVersion:"1.5.0"},{capability:"ADMIN_API_V2_APP_ADD_OR_UPDATE",introducedInVersion:"1.5.0"},{capability:"ADMIN_API_V2_APP_UPDATE",introducedInVersion:"1.5.0"},{capability:"ADMIN_API_V2_LAYOUT_ADD",introducedInVersion:"1.5.0"},{capability:"ADMIN_API_V2_LAYOUT_ADD_OR_UPDATE",introducedInVersion:"1.5.0"},{capability:"ADMIN_API_V2_LAYOUT_UPDATE",introducedInVersion:"1.5.0"},{capability:"METRICS_ENDPOINTS_DB_CONNECTIVITY",introducedInVersion:"1.7.0"},{capability:"API_V2_SERVER_INFO_ENHANCED",introducedInVersion:"2.0.0"},{capability:"HTTP_TEST",introducedInVersion:"2.0.0"}],clientCapabilitiesByName=new Map;for(const e of clientCapabilities)clientCapabilitiesByName.set(e.capability,e);var BaseAPI=class{constructor(e){this.options=e,this.setOptions(e)}_responseSuccessCallback;_responseErrorCallback;_errorsInterceptorsId;_headersInterceptorId;_serverInfoWrapper={initialized:!1};axiosInstance;setOptions(e){if(!e.auth)throw new Error("please provide auth info");this.options=e,this._errorsInterceptorsId&&this.axiosInstance?.interceptors?.response?.eject(this._errorsInterceptorsId),this._headersInterceptorId&&this.axiosInstance?.interceptors?.request?.eject(this._headersInterceptorId);const t=this.getBaseHeaders(e);this.axiosInstance=axios.create({transformResponse:e.transformResponse,baseURL:e.baseUrl,headers:t,timeout:this.options.requestTimeout,withCredentials:e?.auth?.includeCredentials,validateStatus:this.defaultIsStatusCodeValid,maxContentLength:1/0,maxBodyLength:1/0}),this._errorsInterceptorsId=this.axiosInstance?.interceptors?.response?.use(e=>{try{this._responseSuccessCallback?.(e)}catch{}return e},e=>{try{this._responseErrorCallback?.(e)}catch{}return Promise.reject(e)}),this._headersInterceptorId=this.axiosInstance?.interceptors?.request?.use(async e=>{const t=this.getBaseHeaders(this.options);for(const[r,n]of Object.entries(t))e.headers.set(r,n);if(this.options.getHeaders){const t=await this.options.getHeaders({...e,method:e.method,url:e.url,body:e.data})??{};for(const[r,n]of Object.entries(t))e.headers.set(r,n)}return e},e=>Promise.reject(e))}async whoAmI(){return(await this.axiosInstance.get("/whoami")).data}onResponseSuccessCallback(e){this._responseSuccessCallback=e}onResponseErrorCallback(e){this._responseErrorCallback=e}async initialize(){try{const e=await this.axiosInstance.get("/v2/server/info");this.initializeServerInfo(e.data)}catch(e){if(404===(e?.response?.status??e?.status))return console.warn('Warning: The "GET /v2/server/info" endpoint returned a status code of 404. This means that the io.Manager server is version is < 1.5.0. Proceeding with an empty set of capabilities.'),void this.initializeServerInfo({version:"< 1.5.0",capabilities:[],licenseInfo:{licenseSupported:!1},base:void 0,machine:void 0,start:void 0});throw e}}get serverInfo(){return this._serverInfoWrapper.initialized||this.throwNotInitialized(),this._serverInfoWrapper}hasCapability(e){return this._serverInfoWrapper.initialized||this.throwNotInitialized(),this._serverInfoWrapper.capabilitiesByName.has(e)}async unloadClient(e,t){if(!e||!t)return;const r=new Headers({...this.getBaseHeaders(this.options),...await(this.options.getHeaders?.({method:"POST",url:`${this.options.baseUrl}/user/goodbye`}))}),n=new Request(`${this.options.baseUrl}/user/goodbye`,{method:"POST",headers:r,mode:"cors",cache:"default",keepalive:!0,body:JSON.stringify({session:e})});window.fetch(n)}getHeaders(e){return this.getBaseHeaders(e)}getBaseHeaders(e){const t={};if(e.auth?.username&&(t.user=e.auth.username),(e.auth?.basic?.username||e.auth?.basic?.password)&&(t.Authorization=`Basic ${this.toBase64(`${e.auth.basic.username}:${e.auth.basic.password}`)}`),e.auth?.token?.bearer&&(t.Authorization=`Bearer ${e.auth.token.bearer}`),e.headers)for(const r of Object.keys(e.headers))t[r]=e.headers[r];return t}initializeServerInfo(e){const t=new Map;for(const r of e.capabilities)t.set(r.capability,r);if("2.0.0"===e.version){const e={capability:"HTTP_TEST",introducedInVersion:"2.0.0"};t.set(e.capability,e)}Object.assign(this._serverInfoWrapper,{initialized:!0,capabilitiesByName:t,...e})}ensureCapability(e){if(this.options.disableCapabilityCheck)return;this._serverInfoWrapper.initialized||this.throwNotInitialized();if(!this._serverInfoWrapper.capabilitiesByName.get(e)){const t=clientCapabilitiesByName.get(e);if(!t)throw new Error(`Client capability "${e}" not found.`);throw new Error(`io.Manager server version "${this.serverInfo.version}" doesn't support capability "${e}" which was introduced in version "${t.introducedInVersion}".`)}}throwNotInitialized(){throw new Error("You need to call initialize() first, before calling this API.")}toBase64(e){return"undefined"!=typeof window?window.btoa(e):Buffer.from(e,"utf-8").toString("base64")}defaultIsStatusCodeValid(e){return e<400}};function customEncodeURIComponent(e){return decodeURIComponent(e)!==e?e:encodeURIComponent(e)}var PromiseWrapper=class{static delay(e){return new Promise(t=>setTimeout(t,e))}resolve=()=>{};reject=()=>{};promise;rejected=!1;resolved=!1;get ended(){return this.rejected||this.resolved}constructor(){this.promise=new Promise((e,t)=>{this.resolve=t=>{this.resolved=!0,e(t)},this.reject=e=>{this.rejected=!0,t(e)}})}};function debugSanitizeValue(e){switch(typeof e){case"number":case"bigint":case"boolean":return e;case"string":return`Sanitized(type=string, length=${e.length})`;case"function":return`Sanitized(type=function, name=${e.name||"anonymous"})`;case"object":return null===e?"Sanitized(type=object, value=null)":e instanceof Date||e instanceof RegExp?e:`Sanitized(type=object, propertyCount=${Object.keys(e).length})`;default:return`Sanitized(type=${typeof e})`}}var RequestLogger=class{constructor(e,t,r,n){this.logger=e,this.logLevel=t,this.disableLogSanitization=r,this.logHTTPHeaders=n}shouldLogRequest(){return this.logger.isLevelEnabled(this.logLevel)}logRequest(e){if(!this.shouldLogRequest())return;const t=e();let r=`Calling endpoint "${t.endpointName}" (${t.operationName})`,n=!1;if(t.pathParameters&&Object.keys(t.pathParameters).length>0){const e=structuredClone(t.pathParameters);n&&(r+=" and"),r+=` with path parameters: ${JSON.stringify(e)}`,n=!0}if(t.queryParameters&&Object.keys(t.queryParameters).length>0){const e=structuredClone(t.queryParameters);n&&(r+=" and"),r+=` with query parameters: ${JSON.stringify(e)}`,n=!0}if(t.requestBody){const e=structuredClone(t.requestBody);if(!this.disableLogSanitization)for(const r of t.sanitizeRequestBodyProperties??[]){const t=e[r];t&&(e[r]=debugSanitizeValue(t))}n&&(r+=" and"),r+=` with request body: ${JSON.stringify(e)}`,n=!0}this.logger.log(this.logLevel,r)}logResponse(e){if(!this.shouldLogRequest())return;const t=e();let r=`Endpoint "${t.endpointName}" (${t.operationName}) returned status code of ${t.response.statusCode} and response body`;if("string"==typeof t.response.body)r+=" (string): ",r+=t.response.body;else if("boolean"==typeof t.response.body)r+=" (boolean): ",r+=t.response.body.toString();else if("number"==typeof t.response.body)r+=" (number): ",r+=t.response.body.toString();else if(void 0===t.response.body)r+=" is undefined";else if(null===t.response.body)r+=" is null";else if("object"==typeof t.response.body){const e=structuredClone(t.response.body);if(!this.disableLogSanitization)for(const r of t.sanitizeResponseBodyProperties??[]){const t=e[r];t&&(e[r]=debugSanitizeValue(t))}r+=" (object): ",r+=JSON.stringify(e)}else r+=" is something strange";this.logger.log(this.logLevel,r)}logRequestHeaders(e){if(!this.shouldLogRequest())return;if(!this.logHTTPHeaders)return;if(!this.disableLogSanitization)return;const t=e();this.logger.log(this.logLevel,`Using request headers: ${JSON.stringify(t)}`)}logResponseHeaders(e){if(!this.shouldLogRequest())return;if(!this.logHTTPHeaders)return;if(!this.disableLogSanitization)return;const t=e();this.logger.log(this.logLevel,`Received response headers: ${JSON.stringify(t)}`)}};function extendedOptional(e){return optional(union([e,_null(),_undefined()]))}function anyIsoDate(){return union([datetime({offset:!0,local:!0}),date()])}var zodHelpers={extendedOptional:extendedOptional,anyIsoDate:anyIsoDate};looseObject({name:string(),base:string(),version:string(),start:zodHelpers.anyIsoDate(),status:string()}),looseObject({id:string(),email:zodHelpers.extendedOptional(string()),groups:array(string()),apps:array(string())});var App2=looseObject({definition:looseObject({}),name:string(),disabled:boolean(),public:boolean(),accessList:zodHelpers.extendedOptional(array(string())),createdBy:string(),createdOn:zodHelpers.anyIsoDate(),lastModifiedBy:zodHelpers.extendedOptional(string()),lastModifiedOn:zodHelpers.extendedOptional(zodHelpers.anyIsoDate())});looseObject({items:array(App2),total:number()}),looseObject({items:array(App2),total:number()});var AddOrUpdateAppRequest2=looseObject({definition:looseObject({}),name:string(),disabled:boolean(),public:boolean(),accessList:zodHelpers.extendedOptional(array(string()))});looseObject({apps:array(AddOrUpdateAppRequest2)}),looseObject({application:App2}),looseObject({definition:looseObject({}),name:string(),disabled:boolean(),public:boolean(),accessList:zodHelpers.extendedOptional(array(string()))}),looseObject({definition:looseObject({}),name:string(),disabled:boolean(),public:boolean(),accessList:zodHelpers.extendedOptional(array(string()))});var Layout2=looseObject({definition:string(),id:string(),type:string(),name:string(),owner:zodHelpers.extendedOptional(string()),public:boolean(),disabled:boolean(),accessList:zodHelpers.extendedOptional(array(string())),createdBy:string(),createdOn:zodHelpers.anyIsoDate(),lastModifiedBy:zodHelpers.extendedOptional(string()),lastModifiedOn:zodHelpers.extendedOptional(zodHelpers.anyIsoDate()),default:zodHelpers.extendedOptional(boolean())});looseObject({items:array(Layout2),total:number()}),looseObject({definition:string(),id:zodHelpers.extendedOptional(string()),type:string(),name:string(),owner:zodHelpers.extendedOptional(string()),public:boolean(),disabled:boolean(),accessList:zodHelpers.extendedOptional(array(string())),default:zodHelpers.extendedOptional(boolean())}),looseObject({layout:Layout2}),looseObject({definition:string(),type:string(),name:string(),owner:zodHelpers.extendedOptional(string()),public:boolean(),disabled:boolean(),accessList:zodHelpers.extendedOptional(array(string())),default:zodHelpers.extendedOptional(boolean())}),looseObject({definition:string(),id:zodHelpers.extendedOptional(string()),type:string(),name:string(),owner:zodHelpers.extendedOptional(string()),public:boolean(),disabled:boolean(),accessList:zodHelpers.extendedOptional(array(string())),default:zodHelpers.extendedOptional(boolean())});var Group=looseObject({name:string()});looseObject({items:array(Group),total:number()}),looseObject({canGetUserGroups:boolean(),canGetAllGroups:boolean(),canAddGroup:boolean(),canRemoveGroup:boolean(),canAddUserToGroup:boolean(),canRemoveUserFromGroup:boolean()}),looseObject({name:string()});var RefreshRequestLastDataInfoOthers=looseObject({groups:zodHelpers.extendedOptional(array(string()))}),RefreshRequestLastDataInfo=looseObject({checksum:zodHelpers.extendedOptional(string()),last:number(),other:zodHelpers.extendedOptional(RefreshRequestLastDataInfoOthers)}),RefreshRequestCategory=looseObject({include:boolean(),latestDataInfo:zodHelpers.extendedOptional(RefreshRequestLastDataInfo)}),RefreshDataRequest=looseObject({applications:zodHelpers.extendedOptional(RefreshRequestCategory),layouts:zodHelpers.extendedOptional(RefreshRequestCategory),commands:zodHelpers.extendedOptional(RefreshRequestCategory),configs:zodHelpers.extendedOptional(RefreshRequestCategory)}),ApplicationRefreshResponseData=looseObject({data:zodHelpers.extendedOptional(array(looseObject({}))),hasChanges:boolean(),info:zodHelpers.extendedOptional(RefreshRequestLastDataInfo)}),UserLayoutDefinition=looseObject({definition:string(),id:string(),type:string(),name:string(),owner:zodHelpers.extendedOptional(string()),default:zodHelpers.extendedOptional(boolean())}),LayoutRefreshResponseData=looseObject({hasChanges:boolean(),data:zodHelpers.extendedOptional(array(UserLayoutDefinition)),info:zodHelpers.extendedOptional(RefreshRequestLastDataInfo)}),CommandStatus2=string().check(_minLength(1)),ResultType2=string().check(_minLength(1)),Command2=looseObject({status:CommandStatus2,resultType:zodHelpers.extendedOptional(ResultType2),traceContext:zodHelpers.extendedOptional(looseObject({})),id:string(),user:string(),session:string(),machine:string(),createdBy:string(),createdAt:number(),command:string(),commandParams:zodHelpers.extendedOptional(string()),resultData:zodHelpers.extendedOptional(looseObject({})),resultAt:zodHelpers.extendedOptional(number())}),CommandRefreshResponseData=looseObject({hasChanges:boolean(),data:zodHelpers.extendedOptional(array(Command2)),info:zodHelpers.extendedOptional(RefreshRequestLastDataInfo)}),ConfigRefreshResponseData=looseObject({hasChanges:boolean(),data:zodHelpers.extendedOptional(array(looseObject({}))),info:zodHelpers.extendedOptional(RefreshRequestLastDataInfo)}),RefreshDataResponse=looseObject({applications:zodHelpers.extendedOptional(ApplicationRefreshResponseData),layouts:zodHelpers.extendedOptional(LayoutRefreshResponseData),commands:zodHelpers.extendedOptional(CommandRefreshResponseData),config:zodHelpers.extendedOptional(ConfigRefreshResponseData)});looseObject({session:string(),user:string(),email:zodHelpers.extendedOptional(string()),exp:number(),iat:number()}),looseObject({version:string()});var ConnectBrowserPlatformInfo=looseObject({version:string()});looseObject({platform:ConnectBrowserPlatformInfo});var ConnectBrowserInfo=looseObject({platform:ConnectBrowserPlatformInfo}),ConnectInfo=looseObject({version:string(),core:zodHelpers.extendedOptional(ConnectBrowserInfo),build:string(),region:string(),env:string()}),OSInfo=looseObject({name:zodHelpers.extendedOptional(string()),version:zodHelpers.extendedOptional(string()),arch:zodHelpers.extendedOptional(string())}),Bounds=looseObject({x:zodHelpers.extendedOptional(number()),y:zodHelpers.extendedOptional(number()),width:zodHelpers.extendedOptional(number()),height:zodHelpers.extendedOptional(number())}),Display=looseObject({bounds:zodHelpers.extendedOptional(Bounds),workingArea:zodHelpers.extendedOptional(Bounds),dpi:zodHelpers.extendedOptional(number()),isPrimary:zodHelpers.extendedOptional(boolean()),aspectRatio:zodHelpers.extendedOptional(string()),scaleFactor:zodHelpers.extendedOptional(number())}),BrowserInfo=looseObject({name:string(),version:string(),engine:string()}),MachineInfo=looseObject({user:string(),name:zodHelpers.extendedOptional(string()),os:zodHelpers.extendedOptional(OSInfo),displays:zodHelpers.extendedOptional(array(Display)),browser:zodHelpers.extendedOptional(BrowserInfo)}),HelloRequest=looseObject({glue:ConnectInfo,machine:zodHelpers.extendedOptional(MachineInfo),initialDataRequest:zodHelpers.extendedOptional(RefreshDataRequest),includeServerInfo:zodHelpers.extendedOptional(boolean())}),ServerCapability2=string().check(_minLength(1)),ServerCapabilityWithMetadata2=looseObject({capability:ServerCapability2,introducedInVersion:string()}),LicenseType2=string().check(_minLength(1)),LicenseOrganization=looseObject({displayName:string(),identifier:string()}),LicensePayload=looseObject({type:LicenseType2,licensee:string(),expiration:number(),organization:LicenseOrganization,email:string(),issuedBy:string()}),LicenseInfo2=looseObject({licensePayload:LicensePayload,isExpired:boolean(),licenseSupported:boolean()}),ServerInfoResponse2=looseObject({capabilities:array(ServerCapabilityWithMetadata2),version:string(),licenseInfo:zodHelpers.extendedOptional(LicenseInfo2),base:zodHelpers.extendedOptional(string()),start:zodHelpers.extendedOptional(zodHelpers.anyIsoDate()),machine:zodHelpers.extendedOptional(string()),inactiveSessionTimeoutInSeconds:zodHelpers.extendedOptional(number())}),HelloResponse=looseObject({token:string(),data:RefreshDataResponse,serverInfo:zodHelpers.extendedOptional(ServerInfoResponse2),sessionNotPersisted:zodHelpers.extendedOptional(boolean())}),GoodbyeRequest=looseObject({session:string()}),RefreshTokenRequest=looseObject({token:string()}),RefreshTokenResponse=looseObject({token:string()}),SaveUserLayoutRequest=looseObject({definition:string(),id:zodHelpers.extendedOptional(string()),type:string(),name:string(),default:zodHelpers.extendedOptional(boolean())}),RenameLayoutRequest=looseObject({newName:string()}),SetDefaultLayoutRequest=looseObject({id:zodHelpers.extendedOptional(string())}),AddCommandResultRequest=looseObject({result:looseObject({})}),AddCommandFileResultRequest=looseObject({fileName:string(),contents:string()});looseObject({result:zodHelpers.extendedOptional(looseObject({}))});var AppPreferences=looseObject({data:looseObject({}),id:string(),app:string(),user:string(),lastUpdate:zodHelpers.anyIsoDate()}),AddOrUpdatePrefsRequest=looseObject({data:looseObject({}),merge:boolean(),id:zodHelpers.extendedOptional(string()),app:zodHelpers.extendedOptional(string()),user:zodHelpers.extendedOptional(string())});looseObject({attachment:string(),description:string()});var Feedback=looseObject({id:string(),date:zodHelpers.anyIsoDate(),user:string(),session:string(),description:string(),attachment:string(),reviewed:boolean(),comment:zodHelpers.extendedOptional(string())}),HttpTestRequest=looseObject({}),HttpTestResponse=looseObject({requestBody:looseObject({}),statusCode:number(),customHeader:zodHelpers.extendedOptional(string())}),LayoutIdentifier=looseObject({id:zodHelpers.extendedOptional(string()),name:zodHelpers.extendedOptional(string()),type:zodHelpers.extendedOptional(string())}),User2=looseObject({layouts:zodHelpers.extendedOptional(array(LayoutIdentifier)),id:string(),email:zodHelpers.extendedOptional(string()),password:zodHelpers.extendedOptional(string()),apps:array(string()),groups:array(string()),lastUpdated:zodHelpers.extendedOptional(number()),firstName:zodHelpers.extendedOptional(string()),lastName:zodHelpers.extendedOptional(string())});looseObject({items:array(User2),total:number()}),looseObject({items:array(User2),total:number()});var AddUserRequest=looseObject({layouts:zodHelpers.extendedOptional(array(LayoutIdentifier)),id:string(),email:zodHelpers.extendedOptional(string()),password:zodHelpers.extendedOptional(string()),apps:array(string()),groups:array(string()),lastUpdated:zodHelpers.extendedOptional(number()),firstName:zodHelpers.extendedOptional(string()),lastName:zodHelpers.extendedOptional(string())});looseObject({users:array(AddUserRequest)}),looseObject({user:User2}),looseObject({layouts:zodHelpers.extendedOptional(array(LayoutIdentifier)),apps:zodHelpers.extendedOptional(array(string()))});var UserAppStatusExplain2=string().check(_minLength(1)),UserAppStatus=looseObject({explain:UserAppStatusExplain2,app:App2,available:boolean(),explainMore:zodHelpers.extendedOptional(string())});looseObject({apps:array(UserAppStatus)}),looseObject({app:string()}),looseObject({layouts:array(Layout2)}),looseObject({id:LayoutIdentifier}),looseObject({user:string(),groups:array(string())}),looseObject({groups:array(string())});var Machine=looseObject({id:string(),user:string(),name:zodHelpers.extendedOptional(string()),os:zodHelpers.extendedOptional(OSInfo),displays:zodHelpers.extendedOptional(array(Display)),browser:zodHelpers.extendedOptional(BrowserInfo)});looseObject({items:array(Command2),total:number()}),looseObject({command:Command2}),looseObject({resultType:zodHelpers.extendedOptional(ResultType2),traceContext:zodHelpers.extendedOptional(looseObject({})),session:string(),command:string(),commandParams:zodHelpers.extendedOptional(string())}),looseObject({id:string()});var CommandType2=string().check(_minLength(1));looseObject({type:CommandType2,paramsExamples:looseObject({}),description:string(),supportedVersions:array(string())}),looseObject({type:CommandType2,paramsExample:zodHelpers.extendedOptional(string()),description:string()}),looseObject({version:string(),core:zodHelpers.extendedOptional(ConnectBrowserInfo),build:string(),region:string(),env:string()});var UserSession2=looseObject({id:string(),user:string(),start:zodHelpers.anyIsoDate(),end:zodHelpers.extendedOptional(zodHelpers.anyIsoDate()),glue:ConnectInfo,machine:string(),lastDataFetch:zodHelpers.extendedOptional(zodHelpers.anyIsoDate()),closed:zodHelpers.extendedOptional(boolean()),closeReason:zodHelpers.extendedOptional(string())});looseObject({items:array(UserSession2),total:number()});var CleanSessionsAction2=string().check(_minLength(1));looseObject({action:CleanSessionsAction2,all:zodHelpers.extendedOptional(boolean()),lastFetchThresholdInMinutes:zodHelpers.extendedOptional(number()),createdBefore:zodHelpers.extendedOptional(zodHelpers.anyIsoDate())}),looseObject({itemsCount:number()}),looseObject({items:array(Machine),total:number()});var ClientCrashInfo=looseObject({_companyName:string(),_productName:string(),_version:string(),build:string(),env:string(),guid:string(),machine:string(),osArch:string(),osPlatform:string(),osUser:string(),osVersion:string(),osarch:string(),pid:string(),plat:string(),platform:string(),process_type:string(),prod:string(),ptype:string(),region:string(),session:string(),user:string(),ver:string(),version:string(),filename:string(),isStoredCompressed:boolean()}),ClientCrash=looseObject({id:string(),date:zodHelpers.anyIsoDate(),user:zodHelpers.extendedOptional(string()),info:ClientCrashInfo,reviewed:boolean(),comment:zodHelpers.extendedOptional(string())});looseObject({items:array(ClientCrash),total:number()}),looseObject({upload_file_minidump:string(),_companyName:string(),_productName:string(),_version:string(),build:string(),env:string(),guid:string(),machine:string(),osArch:string(),osPlatform:string(),osUser:string(),osVersion:string(),osarch:string(),pid:string(),plat:string(),platform:string(),process_type:string(),prod:string(),ptype:string(),region:string(),session:string(),user:string(),ver:string(),version:string(),filename:string()}),looseObject({comment:zodHelpers.extendedOptional(string()),reviewed:boolean()}),looseObject({version:string(),started:string(),name:string(),machine:string()});var AppsDataSummary=looseObject({total:number()}),LayoutsDataSummary=looseObject({total:number(),common:number(),private:number()}),CrashesDataSummary=looseObject({total:number(),notReviewed:number()}),FeedbacksDataSummary=looseObject({total:number(),notReviewed:number()}),CommandsDataSummary=looseObject({total:number()}),UsersDataSummary=looseObject({total:number()}),SessionsDataSummary=looseObject({active:number()}),PrefsDataSummary=looseObject({total:number()});looseObject({apps:AppsDataSummary,layouts:LayoutsDataSummary,crashes:CrashesDataSummary,feedbacks:FeedbacksDataSummary,commands:CommandsDataSummary,users:UsersDataSummary,sessions:SessionsDataSummary,prefs:PrefsDataSummary}),looseObject({items:array(Feedback),total:number()}),looseObject({comment:zodHelpers.extendedOptional(string()),reviewed:boolean()}),looseObject({items:array(AppPreferences),total:number()});var AuditLogEntityType2=string().check(_minLength(1)),AuditLogOperation2=string().check(_minLength(1)),AuditLogRequest=looseObject({body:looseObject({}),action:string(),path:string(),params:string(),query:string()}),AuditLogResponse=looseObject({status:string(),body:looseObject({})}),AuditLog=looseObject({entityType:AuditLogEntityType2,operation:AuditLogOperation2,newValue:zodHelpers.extendedOptional(looseObject({})),oldValue:zodHelpers.extendedOptional(looseObject({})),id:string(),user:zodHelpers.extendedOptional(string()),parent:zodHelpers.extendedOptional(string()),date:zodHelpers.anyIsoDate(),session:zodHelpers.extendedOptional(string()),server:string(),entityId:zodHelpers.extendedOptional(string()),entityDisplayName:zodHelpers.extendedOptional(string()),operationComment:zodHelpers.extendedOptional(string()),request:zodHelpers.extendedOptional(AuditLogRequest),response:zodHelpers.extendedOptional(AuditLogResponse)});looseObject({items:array(AuditLog),total:number()}),looseObject({all:zodHelpers.extendedOptional(boolean()),createdBefore:zodHelpers.extendedOptional(zodHelpers.anyIsoDate())}),looseObject({version:string(),group:string(),user:string()});var ConfigEntry=looseObject({contents:looseObject({}),meta:zodHelpers.extendedOptional(looseObject({})),merge:zodHelpers.extendedOptional(boolean())});looseObject({"system.json":zodHelpers.extendedOptional(ConfigEntry),"themes.json":zodHelpers.extendedOptional(ConfigEntry),"stickywindows.json":zodHelpers.extendedOptional(ConfigEntry),"channels.json":zodHelpers.extendedOptional(ConfigEntry),"logger.json":zodHelpers.extendedOptional(ConfigEntry)});var ConnectSystemConfigIdentifier=looseObject({version:string(),group:string(),user:string()}),ConnectConfigs=looseObject({"system.json":zodHelpers.extendedOptional(ConfigEntry),"themes.json":zodHelpers.extendedOptional(ConfigEntry),"stickywindows.json":zodHelpers.extendedOptional(ConfigEntry),"channels.json":zodHelpers.extendedOptional(ConfigEntry),"logger.json":zodHelpers.extendedOptional(ConfigEntry)}),ConnectSystemConfigEntry=looseObject({identifier:ConnectSystemConfigIdentifier,configs:ConnectConfigs,weight:zodHelpers.extendedOptional(number())});looseObject({items:array(ConnectSystemConfigEntry),total:number()}),looseObject({identifiers:array(ConnectSystemConfigIdentifier),configs:ConnectConfigs}),looseObject({identifier:ConnectSystemConfigIdentifier,exact:boolean()}),looseObject({identifier:ConnectSystemConfigIdentifier,configs:ConnectConfigs,weight:zodHelpers.extendedOptional(number())});var ConnectConfigKey2=string().check(_minLength(1));looseObject({config:ConnectConfigKey2,identifier:ConnectSystemConfigIdentifier}),looseObject({type:string().check(_minLength(1)),data:array(looseObject({}))}),looseObject({isValid:boolean(),errors:array(looseObject({}))});var TextFilterType2=string().check(_minLength(1)),TextFilterCondition=looseObject({filterType:string().check(_minLength(1)),type:TextFilterType2,filter:string(),in:zodHelpers.extendedOptional(array(string()))}),NumberFilterType2=string().check(_minLength(1)),NumberFilterCondition=looseObject({filterType:string().check(_minLength(1)),type:NumberFilterType2,filter:zodHelpers.extendedOptional(number()),filterTo:zodHelpers.extendedOptional(number())}),DateFilterType2=string().check(_minLength(1)),DateFilterCondition=looseObject({filterType:string().check(_minLength(1)),type:DateFilterType2,dateFrom:zodHelpers.extendedOptional(string()),dateTo:zodHelpers.extendedOptional(string())}),BooleanFilterType2=string().check(_minLength(1)),BooleanFilterCondition=looseObject({filterType:string().check(_minLength(1)),type:BooleanFilterType2,filter:boolean()}),LogicalConditionOperator2=string().check(_minLength(1));looseObject({condition1:zodHelpers.extendedOptional(union([TextFilterCondition,NumberFilterCondition,DateFilterCondition,BooleanFilterCondition,looseObject({})])),condition2:zodHelpers.extendedOptional(union([TextFilterCondition,NumberFilterCondition,DateFilterCondition,BooleanFilterCondition,looseObject({})])),operator:zodHelpers.extendedOptional(LogicalConditionOperator2)});var SortOrderEnum2=string().check(_minLength(1)),SortOrder=looseObject({sort:SortOrderEnum2,colId:string()}),DataRequestOffset=looseObject({start:number(),count:number()});looseObject({filter:zodHelpers.extendedOptional(looseObject({})),ORFilters:zodHelpers.extendedOptional(array(looseObject({}))),groupKeys:zodHelpers.extendedOptional(array(string())),rowGroupCols:zodHelpers.extendedOptional(array(string())),sort:zodHelpers.extendedOptional(array(SortOrder)),offset:zodHelpers.extendedOptional(DataRequestOffset),excludeFields:zodHelpers.extendedOptional(array(string()))});var ZodSchemas={RefreshDataRequest:RefreshDataRequest,UserLayoutDefinition:UserLayoutDefinition,Command:Command2,RefreshDataResponse:RefreshDataResponse,HelloRequest:HelloRequest,HelloResponse:HelloResponse,GoodbyeRequest:GoodbyeRequest,RefreshTokenRequest:RefreshTokenRequest,RefreshTokenResponse:RefreshTokenResponse,SaveUserLayoutRequest:SaveUserLayoutRequest,RenameLayoutRequest:RenameLayoutRequest,SetDefaultLayoutRequest:SetDefaultLayoutRequest,AddCommandResultRequest:AddCommandResultRequest,AddCommandFileResultRequest:AddCommandFileResultRequest,AppPreferences:AppPreferences,AddOrUpdatePrefsRequest:AddOrUpdatePrefsRequest,Feedback:Feedback,HttpTestRequest:HttpTestRequest,HttpTestResponse:HttpTestResponse},RequestValidator=class{constructor(e){this.options=e}async validateRequestBody(e){if(this.options.disableRequestBodyValidation)return;const{requestBody:t,schema:r,operationName:n,endpointName:i}=e(),o=await r.safeParseAsync(t,{reportInput:!0});if(!o.success)throw new IOManagerRequestValidationError(`Request body schema validation failed for endpoint "${i}" (${n})`,{cause:o.error,schema:r})}async validateResponseBody(e){if(this.options.disableResponseBodyValidation)return;const{responseBody:t,schema:r,operationName:n,endpointName:i}=e(),o=await r.safeParseAsync(t,{reportInput:!0});if(!o.success)throw new IOManagerRequestValidationError(`Response body schema validation failed for endpoint "${i}" (${n})`,{cause:o.error,schema:r})}},IOManagerRequestValidationError=class extends Error{#l;validationErrors;constructor(e,t){super(e,t),this.name="IOManagerRequestValidationError",this.#l=t,this.validationErrors=JSON.stringify(this.#l.cause.issues)}getZodError(){return this.#l.cause}getSchema(){return this.#l.schema}},ClientAPI=class extends BaseAPI{sessionTokenString;sessionToken;requestLogger;requestValidator;constructor(e){super(e),this.setOptions(e)}setOptions(e){super.setOptions(e),this.sessionTokenString&&this.updateToken(this.sessionTokenString),e.logger&&(this.requestLogger=new RequestLogger(e.logger,e.requestLoggerLevel??"trace",e.disableLogSanitization??!1,e.logHTTPHeaders??!1)),this.requestValidator=new RequestValidator({disableLogSanitization:e.disableLogSanitization??!1,disableRequestBodyValidation:e.disableRequestBodyValidation??!1,disableResponseBodyValidation:e.disableResponseBodyValidation??!1})}unload(){this.sessionToken&&this.sessionTokenString&&this.unloadClient(this.sessionToken.session,this.sessionTokenString)}async refreshData(e,t){const r="POST",n="/user",i=`${r} ${n}`,o="refreshData";this.requestLogger?.logRequest(()=>({endpointName:i,operationName:o,requestBody:e})),await this.requestValidator.validateRequestBody(()=>({requestBody:e,schema:ZodSchemas.RefreshDataRequest,operationName:o,endpointName:i}));const s=await this.sendRequest({method:r,url:n,body:e,...t});return this.requestLogger?.logResponse(()=>({endpointName:i,operationName:o,response:s})),this.fixRefreshDataResponse(s?.body),await this.requestValidator.validateResponseBody(()=>({responseBody:s.body,schema:ZodSchemas.RefreshDataResponse,operationName:o,endpointName:i})),s.body}async getApps(e){const t="/user/apps",r=`GET ${t}`,n="getApps";this.requestLogger?.logRequest(()=>({endpointName:r,operationName:n}));const i=await this.sendRequest({method:"GET",url:t,...e});return this.requestLogger?.logResponse(()=>({endpointName:r,operationName:n,response:i})),await this.requestValidator.validateResponseBody(()=>({responseBody:i.body,schema:array(looseObject({})),operationName:n,endpointName:r})),i.body}async getLayouts(e){const t="/user/layouts",r=`GET ${t}`,n="getLayouts";this.requestLogger?.logRequest(()=>({endpointName:r,operationName:n}));const i=await this.sendRequest({method:"GET",url:t,...e});return this.requestLogger?.logResponse(()=>({endpointName:r,operationName:n,response:i})),this.fixLayouts(i.body),await this.requestValidator.validateResponseBody(()=>({responseBody:i.body,schema:array(ZodSchemas.UserLayoutDefinition),operationName:n,endpointName:r})),i.body}async saveLayout(e,t){const r="POST",n="/user/layouts",i=`${r} ${n}`,o="saveLayout";this.requestLogger?.logRequest(()=>({endpointName:i,operationName:o,requestBody:e})),await this.requestValidator.validateRequestBody(()=>({requestBody:e,schema:ZodSchemas.SaveUserLayoutRequest,operationName:o,endpointName:i}));const s=await this.sendRequest({method:r,url:n,body:e,...t});return this.requestLogger?.logResponse(()=>({endpointName:i,operationName:o,response:s})),this.fixLayout(s.body),await this.requestValidator.validateResponseBody(()=>({responseBody:s.body,schema:ZodSchemas.UserLayoutDefinition,operationName:o,endpointName:i})),s.body}async deleteUserLayout(e,t){const r="DELETE",n=`${r} /user/layouts/:id`,i="deleteUserLayout";this.requestLogger?.logRequest(()=>({endpointName:n,operationName:i,pathParameters:{id:e}}));const o=await this.sendRequest({method:r,url:`/user/layouts/${customEncodeURIComponent(e)}`,...t});this.requestLogger?.logResponse(()=>({endpointName:n,operationName:i,response:o}))}async deleteAllUserLayouts(e){const t="DELETE",r="/user/layouts/",n=`${t} ${r}`,i="deleteAllUserLayouts";this.requestLogger?.logRequest(()=>({endpointName:n,operationName:i}));const o=await this.sendRequest({method:t,url:r,...e});return this.requestLogger?.logResponse(()=>({endpointName:n,operationName:i,response:o})),this.fixLayouts(o.body),await this.requestValidator.validateResponseBody(()=>({responseBody:o.body,schema:array(ZodSchemas.UserLayoutDefinition),operationName:i,endpointName:n})),o.body}async renameLayout(e,t,r){const n="POST",i=`${n} /user/layouts/:id/rename`,o="renameLayout",s={newName:t};this.requestLogger?.logRequest(()=>({endpointName:i,operationName:o,pathParameters:{id:e},requestBody:s})),await this.requestValidator.validateRequestBody(()=>({requestBody:s,schema:ZodSchemas.RenameLayoutRequest,operationName:o,endpointName:i}));const a=await this.sendRequest({method:n,url:`/user/layouts/${customEncodeURIComponent(e)}/rename`,body:s,...r});return this.requestLogger?.logResponse(()=>({endpointName:i,operationName:o,response:a})),this.fixLayout(a.body),await this.requestValidator.validateResponseBody(()=>({responseBody:a.body,schema:ZodSchemas.UserLayoutDefinition,operationName:o,endpointName:i})),a.body}async getDefaultLayout(e){const t="/user/layouts/default",r=`GET ${t}`,n="getDefaultLayout";this.requestLogger?.logRequest(()=>({endpointName:r,operationName:n}));const i=await this.sendRequest({method:"GET",url:t,...e});if(this.requestLogger?.logResponse(()=>({endpointName:r,operationName:n,response:i})),204!==i.statusCode)return await this.requestValidator.validateResponseBody(()=>({responseBody:i.body,schema:ZodSchemas.UserLayoutDefinition,operationName:n,endpointName:r})),this.fixLayout(i.body),i.body}async setDefaultLayout(e,t){const r="POST",n="/user/layouts/default",i=`${r} ${n}`,o="setDefaultLayout",s={id:e};this.requestLogger?.logRequest(()=>({endpointName:i,operationName:o,requestBody:s})),await this.requestValidator.validateRequestBody(()=>({requestBody:s,schema:ZodSchemas.SetDefaultLayoutRequest,operationName:o,endpointName:i}));const a=await this.sendRequest({method:r,url:n,body:s,...t});if(this.requestLogger?.logResponse(()=>({endpointName:i,operationName:o,response:a})),204!==a.statusCode)return this.fixLayout(a.body),await this.requestValidator.validateResponseBody(()=>({responseBody:a.body,schema:zodHelpers.extendedOptional(ZodSchemas.UserLayoutDefinition),operationName:o,endpointName:i})),a.body}async openSession(e,t,r,n){const i="POST",o="/user/hello",s=`${i} ${o}`,a="openSession",c={machine:e,glue:t,...r??{}},l={"serverx-token":""};this.requestLogger?.logRequest(()=>({endpointName:s,operationName:a,requestBody:c,headers:l})),await this.requestValidator.validateRequestBody(()=>({requestBody:c,schema:ZodSchemas.HelloRequest,operationName:a,endpointName:s}));const u=await this.sendRequest({method:i,url:o,body:c,headers:l,...n});this.requestLogger?.logResponse(()=>({endpointName:s,operationName:a,response:u,sanitizeResponseBodyProperties:["token"]})),this.fixRefreshDataResponse(u?.body?.data),await this.requestValidator.validateResponseBody(()=>({responseBody:u.body,schema:ZodSchemas.HelloResponse,operationName:a,endpointName:s}));const d=this.updateToken(u.body.token);return u.body.serverInfo&&this.initializeServerInfo(u.body.serverInfo),{...u.body,token:d}}async closeSession(e,t){if(!(e=e??this.sessionToken.session))throw new Error("no active session");const r="POST",n="/user/goodbye",i=`${r} ${n}`,o="closeSession",s={session:e},a={"serverx-token":""};this.requestLogger?.logRequest(()=>({endpointName:i,operationName:o,requestBody:s,headers:a})),await this.requestValidator.validateRequestBody(()=>({requestBody:s,schema:ZodSchemas.GoodbyeRequest,operationName:o,endpointName:i}));const c=await this.sendRequest({method:r,url:n,body:s,headers:a,...t});this.requestLogger?.logResponse(()=>({endpointName:i,operationName:o,response:c}))}async refreshToken(e){const t="POST",r="/user/refresh",n=`${t} ${r}`,i="refreshToken",o={token:this.sessionTokenString};this.requestLogger?.logRequest(()=>({endpointName:n,operationName:i,requestBody:o,sanitizeRequestBodyProperties:["token"]})),await this.requestValidator.validateRequestBody(()=>({requestBody:o,schema:ZodSchemas.RefreshTokenRequest,operationName:i,endpointName:n}));const s=await this.sendRequest({method:t,url:r,body:o,...e});return this.requestLogger?.logResponse(()=>({endpointName:n,operationName:i,response:s,sanitizeResponseBodyProperties:["token"]})),await this.requestValidator.validateResponseBody(()=>({responseBody:s.body,schema:ZodSchemas.RefreshTokenResponse,operationName:i,endpointName:n})),this.updateToken(s.body.token)}async getCommands(e){const t="GET /user/commands/:session",r="getCommands";this.requestLogger?.logRequest(()=>({endpointName:t,operationName:r,pathParameters:{session:this.sessionToken.session}}));const n=await this.sendRequest({method:"GET",url:`/user/commands/${customEncodeURIComponent(this.sessionToken.session)}`,...e});return this.requestLogger?.logResponse(()=>({endpointName:t,operationName:r,response:n})),await this.requestValidator.validateResponseBody(()=>({responseBody:n.body,schema:array(ZodSchemas.Command),operationName:r,endpointName:t})),n.body}async setCommandResult(e,t,r){const n="POST",i=`${n} /user/commands/:commandId`,o="setCommandResult";this.requestLogger?.logRequest(()=>({endpointName:i,operationName:o,pathParameters:{commandId:e},requestBody:t})),await this.requestValidator.validateRequestBody(()=>({requestBody:t,schema:ZodSchemas.AddCommandResultRequest,operationName:o,endpointName:i}));const s=await this.sendRequest({method:n,url:`/user/commands/${customEncodeURIComponent(e)}`,body:t,...r});this.requestLogger?.logResponse(()=>({endpointName:i,operationName:o,response:s}))}async setCommandFileResult(e,t,r,n){const i="POST",o=`${i} /user/commands/:commandId/file`,s="setCommandFileResult",a={fileName:t,contents:r};this.requestLogger?.logRequest(()=>({endpointName:o,operationName:s,pathParameters:{commandId:e},requestBody:a,sanitizeRequestBodyProperties:["contents"]})),await this.requestValidator.validateRequestBody(()=>({requestBody:a,schema:ZodSchemas.AddCommandFileResultRequest,operationName:s,endpointName:o}));const c=await this.sendRequest({method:i,url:`/user/commands/${customEncodeURIComponent(e)}/file`,body:a,...n});this.requestLogger?.logResponse(()=>({endpointName:o,operationName:s,response:c}))}async getPrefs(e,t,r){const n="GET /user/prefs/:app",i="getPrefs";let o=`/user/prefs/${customEncodeURIComponent(e)}`;const s=new URLSearchParams;t&&s.set("last",t.getTime().toString()),o+=`?${s.toString()}`,this.requestLogger?.logRequest(()=>({endpointName:n,operationName:i,pathParameters:{app:e},queryParameters:Object.fromEntries(s.entries())}));const a=await this.sendRequest({method:"GET",url:o,validateStatusCode:e=>e<400||404===e,...r});return this.requestLogger?.logResponse(()=>({endpointName:n,operationName:i,response:a})),404===a.statusCode&&(a.body=void 0),await this.requestValidator.validateResponseBody(()=>({responseBody:a.body,schema:zodHelpers.extendedOptional(ZodSchemas.AppPreferences),operationName:i,endpointName:n})),a.body}async getAllPrefs(e){const t="/user/prefs/",r=`GET ${t}`,n="getAllPrefs";this.requestLogger?.logRequest(()=>({endpointName:r,operationName:n}));const i=await this.sendRequest({method:"GET",url:t,...e});return this.requestLogger?.logResponse(()=>({endpointName:r,operationName:n,response:i})),await this.requestValidator.validateResponseBody(()=>({responseBody:i.body,schema:array(ZodSchemas.AppPreferences),operationName:n,endpointName:r})),i.body}async setPrefs(e,t){const r="POST",n="/user/prefs/",i=`${r} ${n}`,o="setPrefs";this.requestLogger?.logRequest(()=>({endpointName:i,operationName:o,requestBody:e})),await this.requestValidator.validateRequestBody(()=>({requestBody:e,schema:ZodSchemas.AddOrUpdatePrefsRequest,operationName:o,endpointName:i}));const s=await this.sendRequest({method:r,url:n,body:e,...t});return this.requestLogger?.logResponse(()=>({endpointName:i,operationName:o,response:s})),this.fixSetPrefsResponse(s?.body),await this.requestValidator.validateResponseBody(()=>({responseBody:s.body,schema:ZodSchemas.AppPreferences,operationName:o,endpointName:i})),s.body}async deletePrefs(e,t){const r="DELETE",n=`${r} /user/prefs/:app`,i="deletePrefs";this.requestLogger?.logRequest(()=>({endpointName:n,operationName:i,pathParameters:{app:e}}));const o=await this.sendRequest({method:r,url:`/user/prefs/${customEncodeURIComponent(e)}`,...t});this.requestLogger?.logResponse(()=>({endpointName:n,operationName:i,response:o}))}async deleteAllPrefs(e){const t="DELETE",r="/user/prefs/",n=`${t} ${r}`,i="deleteAllPrefs";this.requestLogger?.logRequest(()=>({endpointName:n,operationName:i}));const o=await this.sendRequest({method:t,url:r,...e});this.requestLogger?.logResponse(()=>({endpointName:n,operationName:i,response:o}))}async addFeedback(e,t,r){const n="POST",i="/user/feedbacks",o=`${n} ${i}`,s="addFeedback",a=new FormData$1;a.append("description",e),a.append("attachment",t),this.requestLogger?.logRequest(()=>({endpointName:o,operationName:s}));const c=await this.sendRequest({method:n,url:i,body:a,json:!1,...r});return this.requestLogger?.logResponse(()=>({endpointName:o,operationName:s,response:c})),await this.requestValidator.validateResponseBody(()=>({responseBody:c.body,schema:ZodSchemas.Feedback,operationName:s,endpointName:o})),c.body}async httpTest(e,t,r,n){this.ensureCapability("HTTP_TEST");const i="POST",o="/user/http-test",s=`${i} ${o}`,a="httpTest",c=new URLSearchParams;c.append("statusCode",e?.toString());const l=`${o}?${c.toString()}`,u={};r&&(u["X-Custom-IOManager-Header"]=r),this.requestLogger?.logRequest(()=>({endpointName:s,operationName:a,requestBody:t,queryParams:Object.fromEntries(c.entries()),headers:u})),await this.requestValidator.validateRequestBody(()=>({requestBody:t,schema:zodHelpers.extendedOptional(ZodSchemas.HttpTestRequest),operationName:a,endpointName:s}));const d=await this.sendRequest({method:i,url:l,body:t,headers:u,validateStatusCode:()=>!0,...n});return this.requestLogger?.logResponse(()=>({endpointName:s,operationName:a,response:d})),await this.requestValidator.validateResponseBody(()=>({responseBody:d.body,schema:ZodSchemas.HttpTestResponse,operationName:a,endpointName:s})),d}fixRefreshDataResponse(e){"string"==typeof e?.config?.info?.last&&(e.config.info.last=Number(e.config.info.last)),"string"==typeof e?.commands?.info?.last&&(e.commands.info.last=Number(e.commands.info.last)),"string"==typeof e?.applications?.info?.last&&(e.applications.info.last=Number(e.applications.info.last)),"string"==typeof e?.layouts?.info?.last&&(e.layouts.info.last=Number(e.layouts.info.last)),this.fixLayouts(e?.layouts?.data)}fixSetPrefsResponse(e){"string"==typeof e?.data&&(e.data=JSON.parse(e.data))}fixLayouts(e){if(Array.isArray(e))for(const t of e)this.fixLayout(t)}fixLayout(e){if(!e)return;let t;function r(){if(!t)try{t=JSON.parse(e.definition)}catch{}}"string"!=typeof e.name&&(r(),e.name="string"==typeof t?.name?t.name:""),"string"!=typeof e.type&&(r(),e.type="string"==typeof t?.type?t.type:"")}updateToken(e){return this.sessionToken=jwtDecode(e),this.sessionTokenString=e,this.options.headers=this.options.headers??{},this.options.headers["serverx-token"]=e,this.sessionToken}async sendRequest(e){return this.options.req?this.callCustomRequestImplementation(e):this.callAxiosRequestImplementation(e)}async callAxiosRequestImplementation(e){const t=await this.axiosInstance.request({method:e.method,url:e.url,headers:e.headers,timeout:e.timeout,data:e.body,validateStatus:e.validateStatusCode??this.defaultIsStatusCodeValid});return{body:t.data,statusCode:t.status,headers:t.headers}}async callCustomRequestImplementation(e){if(!this.options.req)throw new Error("this.options.req is falsy.");const t={...e,method:e.method?.toLowerCase(),baseUrl:e.baseUrl??this.options.baseUrl,url:this.resolveFullUrl(e.url,e.baseUrl??this.options.baseUrl),json:e.json??!0,timeout:e.timeout??this.options.requestTimeout},r={...this.getBaseHeaders(this.options)??{},...await(this.options.getHeaders?.(t)),...e.headers??{}};t.headers=r,this.interceptCustomRequest?.(t),this.requestLogger?.logRequestHeaders(()=>t.headers);const n=new PromiseWrapper;return this.options.req(t,(r,i)=>{if(r)if(this.interceptCustomResponseError){const e=this.interceptCustomResponseError?.(t,r,void 0);n.reject(e)}else n.reject(r);else{if(i?.body){const e=this.options?.transformResponse;i.body=e?.(i.body,i.headers)??i.body}this.requestLogger?.logResponseHeaders(()=>i?.headers);const r=e.validateStatusCode??this.defaultIsStatusCodeValid;if(i?.statusCode&&!r(i.statusCode)){const e=new CustomRequestError(`Request failed with status code ${i.statusCode}`),r=Math.floor(i.statusCode/100);if(4===r?e.code="ERR_BAD_REQUEST":5===r&&(e.code="ERR_BAD_RESPONSE"),this.interceptCustomResponseError){const r=this.interceptCustomResponseError?.(t,e,i);n.reject(r)}else n.reject(e)}else this.interceptCustomResponse?.(t,i),n.resolve(i)}}),n.promise}resolveFullUrl(e,t){let r=e;r.startsWith("/")&&(r=r.substring(1));let n=t;return n.endsWith("/")||(n+="/"),new URL(r,n).href}interceptCustomRequest;interceptCustomResponse;interceptCustomResponseError},CustomRequestError=class extends Error{code;status},SanitizedIOManagerApiError=class e extends Error{code;status;isSessionExpired;isCustomTimeoutError;validationErrors;request;responseBodyError;static fromAxiosError(t){const r=Number(t?.response?.status),n=t?.response?.data;let i;if(t?.message)i=t?.message;else if("errors"in t&&t?.errors&&Array.isArray(t?.errors)){const e=t?.errors?.map(e=>e?.message).filter(e=>e);e.length&&(i=e.join(", "))}const o=new e(i);if(o.name="SanitizedIOManagerApiError",o.stack=t?.stack,t instanceof IOManagerRequestValidationError){const e=t;o.validationErrors=e.validationErrors}Number.isFinite(r)&&(o.status=r),t?.code&&(o.code=t?.code),o.request={baseUrl:t?.config?.baseURL,url:t?.config?.url,method:t?.config?.method};const s=400===r&&"invalid-glue42-server-token"===n?.error?.message;return s&&(o.isSessionExpired=s),o.responseBodyError=n?.error,o}static fromCustomRequestError(t,r,n){const i=Number(r?.statusCode),o=r?.body,s=new e(n?.message);if(s.name="SanitizedIOManagerApiError",s.stack=n?.stack,n instanceof IOManagerRequestValidationError){const e=n;s.validationErrors=e.validationErrors}let a;Number.isFinite(i)&&(s.status=i),n?.code?s.code=n?.code:n?.message?.includes("net::ERR_CONNECTION_REFUSED")&&(s.code="ECONNREFUSED"),t.baseUrl&&t.url.startsWith(t.baseUrl)?(a=t.url.slice(t.baseUrl.length),a.startsWith("/")||(a=`/${a}`)):a=t.url,s.request={baseUrl:t.baseUrl,url:a,method:t.method};const c=400===i&&"invalid-glue42-server-token"===o?.error?.message;return c&&(s.isSessionExpired=c),s.responseBodyError=o?.error,n.isCustomTimeoutError&&(s.isCustomTimeoutError=n.isCustomTimeoutError),s}},CachedClientAPI=class extends ClientAPI{get connectionState(){return{isConnected:this._isConnected,baseUrl:this.options.baseUrl,serverEnabled:!0,cacheEnabled:this.options.enableCaching,disconnectionError:this._disconnectionError}}get token(){return this.sessionToken?this.sessionToken:this.options.enableCaching?this._cachedToken:void 0}_callbacks=CallbackRegistryFactory$2();_isConnected=!1;_refreshTokenIntervalId;_refreshDataIntervalId;_slowestRequests=[];_statParams;_lastApplicationsInfo;_lastLayoutsInfo;_lastCommandsInfo;_lastConfigsInfo;_lastApplicationsData;_lastLayoutsData;_lastConfigsData;_cachedToken;_disconnectionError;_sessionNotPersisted;_cachedClientRequestInterceptor;_cachedClientResponseInterceptor;get logger(){return this.options.logger}get cache(){if(!this.options.enableCaching)throw new Error("Accessing the cache is not allowed when caching is disabled.");return this.options.managerCache}constructor(e){super(e),this.setOptions(e)}setOptions(e){e.refresh??={},e.refresh.applications??=!0,e.refresh.layouts??=!0,e.refresh.commands??=!0,e.refresh.configs??=!1,super.setOptions(e);const t=e=>{const t={startTime:this.getNowMs(),startTimeDate:new Date,operation:`${e.method} ${e.url}`};e.__perf=t},r=e=>{const t=e.__perf;t.endTime=this.getNowMs(),t.duration=t.endTime-t.startTime,this._slowestRequests.push(t),this._slowestRequests.sort((e,t)=>t.duration-e.duration),this._slowestRequests.length>5&&this._slowestRequests.pop()};this._cachedClientRequestInterceptor&&this.axiosInstance.interceptors?.request?.eject(this._cachedClientRequestInterceptor),this._cachedClientRequestInterceptor=this.axiosInstance.interceptors.request.use(e=>(t(e),e),e=>e?.config?.method?Promise.reject(SanitizedIOManagerApiError.fromAxiosError(e)):Promise.reject(e)),this.interceptCustomRequest=e=>{t(e)},this._cachedClientResponseInterceptor&&this.axiosInstance.interceptors?.response?.eject(this._cachedClientResponseInterceptor),this._cachedClientResponseInterceptor=this.axiosInstance.interceptors.response.use(e=>(r(e.config),e),e=>(r(e.config),e?.config?.method?Promise.reject(SanitizedIOManagerApiError.fromAxiosError(e)):Promise.reject(e))),this.interceptCustomResponse=e=>{r(e)},this.interceptCustomResponseError=(e,t,n)=>(r(e),SanitizedIOManagerApiError.fromCustomRequestError(e,n,t))}async start(...e){this._statParams=e;const t=this._statParams[2]??={};let r;t.initialDataRequest??=this.createRefreshDataRequest(!0),t.includeServerInfo=!0,this.logger.info(`Initiating connection to ${this.options.baseUrl}`);let n=!1;try{let e;if(this.logger.info("Opening a session..."),this.options.enableCaching){const i=await this.cache.get("session");if(i&&(this._cachedToken=i.value),r=await this.readDataCache(t.initialDataRequest),n=Boolean(i&&r),n){const t=[...this._statParams];t[3]??={},t[3].timeout=this.options.openSessionRequestTimeout,e=await super.openSession(...t)}else e=await this.retryStart(...this._statParams)}else e=await this.retryStart(...this._statParams);return this.logger.info(`Session opened. Initial data received: ${this.getSnapshotSummary(e.data).join(", ")}`),this._sessionNotPersisted=e.sessionNotPersisted,e.sessionNotPersisted&&this.logger.warn("Session was opened in read-only mode and was not persisted on the server."),this.writeToFields(e.data),this.options.enableCaching&&(this.logger.info("Writing session info to cache."),await this.cache.set("session",e.token),await this.cache.set("sessionNotPersisted",e.sessionNotPersisted),await this.writeDataCache(e.data)),this.notifyConnected(),this.startTokenTimer(),this.startDataTimer(),e}catch(e){if(this.notifyDisconnected(e),!this.options.enableCaching)throw this.logger.error("Failed to open a session.",e),e;if(!n)throw this.logger.error("Failed to open a session. Cache miss.",e),e;this.logger.warn("Failed to open a session. Proceeding from cache.",e);const t=await this.cache.get("sessionNotPersisted");return t?.value&&this.logger.warn("Cached session was opened in read-only mode and was not persisted on the server."),this.writeToFields(r),this.startTokenTimer(),this.startDataTimer(),{token:this._cachedToken,data:r}}}async stop(){this.stopTokenTimer(),this.stopDataTimer(),this.logger.info("Slowest requests:");for(const e of this._slowestRequests)this.logger.info(`${e.startTimeDate.toISOString()} - operation: ${e.operation}, duration (ms): ${e.duration}`);this.logger.info("Closing session."),await super.closeSession(void 0,{timeout:this.options.closeSessionRequestTimeout})}onConnectedStateChanged(e){return this._callbacks.add("onConnectedStateChanged",e)}async onAppsChanged(e){const t=this._callbacks.add("onAppsChanged",e);try{this._lastApplicationsData&&(this.logger.debug("Calling onAppsChanged",this._lastApplicationsData),this._callbacks.execute("onAppsChanged",this._lastApplicationsData))}catch(e){throw t(),e}return t}async onLayoutsChanged(e){const t=this._callbacks.add("onLayoutsChanged",e);try{this._lastLayoutsData&&(this.logger.debug("Calling onLayoutsChanged",this._lastLayoutsData),this._callbacks.execute("onLayoutsChanged",this._lastLayoutsData))}catch(e){throw t(),e}return t}async onCommandsReceived(e){return this._callbacks.add("onCommandsReceived",e)}async onConfigsChanged(e){const t=this._callbacks.add("onConfigsChanged",e);try{this._lastConfigsData&&(this.logger.debug("Calling onConfigsChanged",this._lastConfigsData),this._callbacks.execute("onConfigsChanged",this._lastConfigsData))}catch(e){throw t(),e}return t}openSession(...e){throw new Error("Calling `openSession` directly is not supported. Call `start` instead.")}closeSession(...e){throw new Error("Calling `closeSession` directly is not supported. Call `stop` instead.")}async refreshData(...e){this.logger.isTraceEnabled()?this.logger.trace(`Requesting data changes: ${JSON.stringify(e[0])}`):this.logger.info(`Requesting data changes: ${JSON.stringify(this.sanitizeGroups(e[0]))}`);let t=!1;try{const r=await this.handleAuth(async r=>(t=Boolean(r),r?r.data:await super.refreshData(...e)));if(this.notifyConnected(),r&&!t){const e=this.getSnapshotSummary(r);e.length?this.logger.info(`Data received: ${e.join(", ")}`):this.logger.info("No new data was received."),this.writeToFields(r),this.options.enableCaching&&await this.writeDataCache(r)}return r}catch(t){if(this.notifyDisconnected(t),!this.options.enableCaching)throw this.logger.debug("Refresh data request failed.",t),t;const r=await this.readDataCache(e[0]);if(!r)throw this.logger.debug("Refresh data request failed. Cache miss.",t),t;return this.logger.warn("Refresh data request failed. Returning data from cache.",t),r}}async refreshToken(...e){this.logger.info("Refreshing session token.");try{const t=await this.handleAuth(()=>super.refreshToken(...e));return this.notifyConnected(),this.options.enableCaching&&(this.logger.info("Writing session info to cache."),await this.cache.set("session",t)),t}catch(e){throw this.notifyDisconnected(e),this.logger.debug("Refresh token request failed.",e),e}}async getPrefs(...e){const t=e[0];try{const r=await this.handleAuth(()=>super.getPrefs(...e));return this.notifyConnected(),this.options.enableCaching&&await this.updateAllPreferencesCache(t,r),r}catch(e){if(this.notifyDisconnected(e),!this.options.enableCaching)throw this.logger.debug("getPrefs request failed.",e),e;const r=await this.cache.get("prefs_data");if(!r)throw this.logger.debug("getPrefs request failed. Cache miss.",e),e;this.logger.debug("getPrefs request failed. Returning data from cache.",e);const n=r.value.find(e=>e.app===t);return n&&"string"==typeof n?.data&&(n.data=JSON.parse(n.data)),n}}getAllPrefs(...e){return this.handleRead("getAllPrefs","prefs_data",()=>super.getAllPrefs(...e))}getDefaultLayout(...e){return this.handleRead("getDefaultLayout","read_getDefaultLayout",()=>super.getDefaultLayout(...e))}whoAmI(...e){return this.handleRead("whoAmI","read_whoAmI",()=>super.whoAmI(...e))}async getLayouts(...e){const t=await this.handleRead("getLayouts","layouts_data",()=>super.getLayouts(...e));return this._lastLayoutsData=t,this._callbacks.execute("onLayoutsChanged",t),t}getLastLayouts(){return this._lastLayoutsData}getLastApps(){return this._lastApplicationsData}async getApps(...e){const t=await this.handleRead("getApps","applications_data",()=>super.getApps(...e));return this._lastApplicationsData=t,this._callbacks.execute("onAppsChanged",t),t}async getCommands(...e){const t=await this.handleAuth(()=>super.getCommands(...e));return this._callbacks.execute("onCommandsReceived",t),t}setPrefs(...e){return this.handleWrite("setPrefs","write_setPrefs",()=>super.setPrefs(...e))}setCommandResult(...e){return this.handleWrite("setCommandResult","write_setCommandResult",()=>super.setCommandResult(...e))}addFeedback(...e){return this.handleWrite("addFeedback","write_addFeedback",()=>super.addFeedback(...e))}setDefaultLayout(...e){return this.handleWrite("setDefaultLayout","write_setDefaultLayout",()=>super.setDefaultLayout(...e))}deleteAllPrefs(...e){return this.handleWrite("deleteAllPrefs","write_deleteAllPrefs",()=>super.deleteAllPrefs(...e))}deleteAllUserLayouts(...e){return this.handleWrite("deleteAllUserLayouts","write_deleteAllUserLayouts",()=>super.deleteAllUserLayouts(...e))}setCommandFileResult(...e){return this.handleWrite("setCommandFileResult","write_setCommandFileResult",()=>super.setCommandFileResult(...e))}saveLayout(...e){return this.handleWrite("saveLayout","write_saveLayout",()=>super.saveLayout(...e))}renameLayout(...e){return this.handleWrite("renameLayout","write_renameLayout",()=>super.renameLayout(...e))}deletePrefs(...e){return this.handleWrite("deletePrefs","write_deletePrefs",()=>super.deletePrefs(...e))}deleteUserLayout(...e){return this.handleWrite("deleteUserLayout","write_deleteUserLayout",()=>super.deleteUserLayout(...e))}notifyDisconnected(e){if(this._isConnected){this._isConnected=!1,this._disconnectionError=e,this.logger.warn("io.Manager connection state changed: disconnected.",e);const t={isConnected:this._isConnected,baseUrl:this.options.baseUrl,serverEnabled:!0,cacheEnabled:this.options.enableCaching,disconnectionError:e};this._callbacks.execute("onConnectedStateChanged",t)}}notifyConnected(){if(!this._isConnected){this._isConnected=!0,this._disconnectionError=void 0,this.logger.info("io.Manager connection state changed: connected.");const e={isConnected:this._isConnected,baseUrl:this.options.baseUrl,serverEnabled:!0,cacheEnabled:this.options.enableCaching};this._callbacks.execute("onConnectedStateChanged",e)}}async refreshTokenTimeout(){try{this.options.asyncSequelizer?await this.options.asyncSequelizer.enqueue(async()=>{await this.refreshToken()}):await this.refreshToken()}catch(e){this.logger.warn("Refresh token request failed.",e)}finally{this.startTokenTimer()}}async refreshDataTimeout(){const e=this.createRefreshDataRequest();try{this.options.asyncSequelizer?await this.options.asyncSequelizer.enqueue(async()=>{await this.refreshData(e)}):await this.refreshData(e)}catch(e){this.logger.warn("Refresh data request failed.",e)}finally{this.startDataTimer()}}createRefreshDataRequest(e){return{applications:{include:Boolean(this.options.refresh?.applications),latestDataInfo:e?void 0:this._lastApplicationsInfo},layouts:{include:Boolean(this.options.refresh?.layouts),latestDataInfo:e?void 0:this._lastLayoutsInfo},commands:{include:Boolean(this.options.refresh?.commands),latestDataInfo:e?void 0:this._lastCommandsInfo},configs:{include:Boolean(this.options.refresh?.configs),latestDataInfo:e?void 0:this._lastConfigsInfo}}}startTokenTimer(){this.logger.info(`Starting the session token refresh timer for ${this.options.tokenRefreshInterval}s`),this._refreshTokenIntervalId=setTimeout(this.refreshTokenTimeout.bind(this),1e3*this.options.tokenRefreshInterval)}startDataTimer(){this.logger.info(`Starting data refresh timer for ${this.options.fetchInterval}s`),this._refreshDataIntervalId=setTimeout(this.refreshDataTimeout.bind(this),1e3*this.options.fetchInterval)}async recreateSession(e){if(this.logger.debug("Opening a session..."),e&&!this._sessionNotPersisted)try{this.logger.debug("Closing old session."),await super.closeSession(e,{timeout:this.options.closeSessionRequestTimeout}),this.logger.debug("Old session closed.")}catch(e){this.logger.debug("Failed to close old session.",e)}const t=await super.openSession(...this._statParams);return this.logger.info(`Session opened. Initial data received: ${this.getSnapshotSummary(t.data).join(", ")}`),this._sessionNotPersisted=t.sessionNotPersisted,t.sessionNotPersisted&&this.logger.warn("Session was opened in read-only mode and was not persisted on the server."),this.writeToFields(t.data),this.options.enableCaching&&(this.logger.info("Writing session info to cache."),await this.cache.set("session",t.token),await this.cache.set("sessionNotPersisted",t.sessionNotPersisted),await this.writeDataCache(t.data)),t}stopTokenTimer(){this.logger.info("Stopping the session token refresh timer."),this._refreshTokenIntervalId&&clearTimeout(this._refreshTokenIntervalId)}stopDataTimer(){this.logger.info("Stopping the data refresh timer."),this._refreshDataIntervalId&&clearTimeout(this._refreshDataIntervalId)}writeToFields(e){e.applications?.hasChanges&&(this._lastApplicationsData=e.applications.data,this._lastApplicationsInfo=e.applications.info,this._callbacks.execute("onAppsChanged",e.applications.data)),e.layouts?.hasChanges&&(this._lastLayoutsData=e.layouts.data,this._lastLayoutsInfo=e.layouts.info,this._callbacks.execute("onLayoutsChanged",e.layouts.data)),e.config?.hasChanges&&(this._lastConfigsData=e.config.data,this._lastConfigsInfo=e.config.info,this._callbacks.execute("onConfigsChanged",e.config.data)),e.commands?.hasChanges&&(this._lastCommandsInfo=e.commands.info,this._callbacks.execute("onCommandsReceived",e.commands.data))}async writeDataCache(e){e.applications?.hasChanges&&(await this.cache.set("applications_data",e.applications.data),await this.cache.set("applications_info",e.applications.info)),e.layouts?.hasChanges&&(await this.cache.set("layouts_data",e.layouts.data),await this.cache.set("layouts_info",e.layouts.info)),e.config?.hasChanges&&(await this.cache.set("config_data",e.config.data),await this.cache.set("config_info",e.config.info)),e.commands?.hasChanges&&await this.cache.set("commands_info",e.commands.info)}async readDataCache(e){const t={};if(!0===e.applications?.include){const r=await this.cache.get("applications_info");if(!r)return void this.logger.debug('readDataCache: Could not find "applications_info" in cache.');if(this.lastDataInfoEquals(e.applications?.latestDataInfo,r.value))t.applications={hasChanges:!1};else{const e=await this.cache.get("applications_data");t.applications={hasChanges:!0,data:e?.value,info:r.value}}}if(!0===e.layouts?.include){const r=await this.cache.get("layouts_info");if(!r)return void this.logger.debug('readDataCache: Could not find "layouts_info" in cache.');if(this.lastDataInfoEquals(e.layouts?.latestDataInfo,r.value))t.layouts={hasChanges:!1};else{const e=await this.cache.get("layouts_data");t.layouts={hasChanges:!0,data:e?.value,info:r.value}}}if(!0===e.configs?.include){const r=await this.cache.get("config_info");if(!r)return void this.logger.debug('readDataCache: Could not find "config_info" in cache.');if(this.lastDataInfoEquals(e.configs?.latestDataInfo,r.value))t.config={hasChanges:!1};else{const e=await this.cache.get("config_data");t.config={hasChanges:!0,data:e?.value,info:r.value}}}return t}async updateAllPreferencesCache(e,t){const r=await this.cache.get("prefs_data");let n=r?.value||[];if(t){const r=n.findIndex(t=>t.app===e);-1!==r?n[r]=t:n.push(t)}else n=n.filter(t=>t.app!==e);await this.cache.set("prefs_data",n)}lastDataInfoEquals(e,t){return!(!e||!t)&&(e.checksum===t.checksum||Number(e.last)===Number(t.last))}async handleRead(e,t,r){this.logger.debug(`calling handleRead operationName=${e} cacheKey=${t}`);try{const e=await this.handleAuth(r);return this.notifyConnected(),this.options.enableCaching&&await this.cache.set(t,e),e}catch(r){if(this.notifyDisconnected(r),!this.options.enableCaching)throw this.logger.debug(`${e} request failed.`,r),r;const n=await this.cache.get(t);if(!n)throw this.logger.debug(`${e} request failed. Cache miss.`,r),r;if(this.logger.debug(`${e} request failed. Returning data from cache.`,r),"prefs_data"===t){const e=n.value;if(e)for(const t of e)"string"==typeof t.data&&(t.data=JSON.parse(t.data))}return n.value}}async handleWrite(e,t,r){this.logger.debug(`calling handleWrite operationName=${e} cacheKey=${t}`);try{const e=await this.handleAuth(r);return this.notifyConnected(),e}catch(t){const r=t;throw this.logger.debug(`${e} request failed.`,t),"ReadOnlyRequestViolationError"!==r.responseBodyError?.type&&this.notifyDisconnected(t),t}}async retryStart(...e){let t=0;for(;;)try{return t>0&&this.logger.info(`Opening a session [retry ${t} of ${this.options.startRetries}]`),await super.openSession(...e)}catch(e){if(t>=this.options.startRetries)throw e;this.logger.warn(`Failed to open a session. Retrying after ${this.options.startRetryInterval}s.`,e),t+=1,await new Promise(e=>setTimeout(e,1e3*this.options.startRetryInterval))}}getSnapshotSummary(e){const t=[];return e.applications?.hasChanges&&t.push(`applications (${e.applications.data?.length})`),e.layouts?.hasChanges&&t.push(`layouts (${e.layouts.data?.length})`),e.commands?.hasChanges&&t.push(`commands (${e.commands.data?.length})`),e.config?.hasChanges&&t.push(`remote configs (${e.config.data?.length})`),t}async handleAuth(e){let t;if(!this.sessionToken||!this.sessionTokenString||this._sessionNotPersisted){let e;if(this.sessionToken||this.logger.info("Session is not open (started from cache). Opening a session..."),this._sessionNotPersisted&&this.logger.info("Session is not persisted on the server (server was in read-only mode when it created it). Opening a new session..."),this.options.enableCaching){const t=await this.cache.get("session");e=t?.value?.session}try{t=await this.recreateSession(e)}catch(e){throw this.logger.warn("Failed to open a session.",e),e}}try{return await e(t)}catch(r){if(r?.isSessionExpired){try{this.logger.warn("Session expired. Opening a new session...",r),t=await this.recreateSession(this.sessionToken?.session)}catch(e){throw this.logger.warn("Failed to re-open the session.",e),r}return await e(t)}throw r}}getNowMs(){return this.options.getNowMs?this.options.getNowMs():Number(new Date)}sanitizeGroups(e){if(null==e)return e;if("object"!=typeof e)return e;const t=structuredClone(e);function r(e){return e?Array.isArray(e)?`__REMOVED(length=${e.length})`:"__REMOVED(NON_ARRAY_TRUTHY_VALUE)":"__REMOVED(falsy)"}return function e(t){if(null!=t&&"object"==typeof t)if(Array.isArray(t))for(const r of t)e(r);else for(const n in t)t.hasOwnProperty(n)&&("groups"===n?t[n]=r(t[n]):e(t[n]))}(t),t}};const managerOperationDecoder=oneOf$1(constant$2("operationCheck")),DEFAULT_RESPONSE_TIMEOUT_MS=1e4,PREFS_CACHE_KEY="prefs_data",LAYOUTS_CACHE_KEY="layouts_data",DEFAULT_LAYOUT_CACHE_KEY="read_getDefaultLayout",PREFS_CHANGED_EVENT_KEY="onPrefsChanged",APPS_ADDED_EVENT_KEY="onAppsAdded",APPS_DELETED_EVENT_KEY="onAppsDeleted",APPS_CHANGED_EVENT_KEY="onAppsChanged",LAYOUTS_CHANGED_EVENT_KEY="onLayoutsChanged",LAYOUTS_ADDED_EVENT_KEY="onLayoutsAdded",LAYOUTS_REMOVED_EVENT_KEY="onLayoutsRemoved",LAYOUTS_RENAMED_EVENT_KEY="onLayoutsRenamed",CONNECTED_STATE_CHANGED_EVENT_KEY="onConnectedStateChanged",GET_CONNECTION_STATE_METHOD_NAME="T42.IOManager.GetConnectionState",FETCH_DATA_METHOD_NAME="T42.IOManager.FetchData",CONNECTION_STATE_STREAM_NAME="T42.IOManager.ConnectionState",defaultDataRefreshIntervalMS=6e4,defaultTokenRefreshIntervalMS=36e5;class ManagerController{identity;glueController;sequelizer;buildClient;buildCache;started=!1;name="io.Manager Client";globalConfig;config;unloadCallback;callbacks=CallbackRegistryFactory$2();lastApps=[];lastLayouts=[];lastLayoutIdsByKey=new Map;client;managerCache;connectionStateStream;get managerConnectionState(){const e={serverEnabled:!1,isConnected:!1};return this.config?this.client.connectionState:e}operations={operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)}};constructor(e,t,r,n,i){this.identity=e,this.glueController=t,this.sequelizer=r,this.buildClient=n,this.buildCache=i,this.unloadCallback=this.handleUnload.bind(this),window.addEventListener("pagehide",this.unloadCallback)}get logger(){return logger.get("manager.controller")}get isStarted(){return this.started}get isCritical(){return this.config?.critical??!0}ready(){return Promise.resolve()}handlePlatformShutdown(){this.started=!1,window.removeEventListener("pagehide",this.unloadCallback),this.handleUnload(),this.managerCache?.dispose()}async configurePostStart(){if(await this.registerInteropMethods(),!this.config)return;const e=this.globalConfig?.user?.id||"__no_user__";this.managerCache=this.buildCache(this.config,e),await this.managerCache.initialize();const t={baseUrl:this.config.url,auth:this.config.auth,headers:this.config.headers,getHeaders:this.config.getHeaders,fetchInterval:(this.config.fetchIntervalMS||defaultDataRefreshIntervalMS)/1e3,tokenRefreshInterval:(this.config.tokenRefreshIntervalMS||defaultTokenRefreshIntervalMS)/1e3,startRetries:0,startRetryInterval:1e4,refresh:{applications:Boolean(this.config.features?.applicationsStore??!0),layouts:Boolean(this.config.features?.layoutsStore??!0),commands:!1,configs:!1},requestTimeout:this.config.requests?.timeout??this.config.responseTimeoutMS??DEFAULT_RESPONSE_TIMEOUT_MS,openSessionRequestTimeout:this.config.requests?.openSessionTimeout??DEFAULT_RESPONSE_TIMEOUT_MS,closeSessionRequestTimeout:this.config.requests?.closeSessionTimeout??DEFAULT_RESPONSE_TIMEOUT_MS,enableCaching:!0,managerCache:this.managerCache,asyncSequelizer:this.sequelizer,logger:this.createManagerLogger()};this.client=this.buildClient(t),this.logger?.trace("The client API is ready.");const r=await this.identity.getMachineInfo(e),n=this.identity.getGlueInfo();this.logger?.trace(`Opening a session for machine: ${JSON.stringify(r)} and glue: ${JSON.stringify(n)}`),this.client.onConnectedStateChanged(this.handleOnConnectedStateChanged.bind(this)),await this.client.onAppsChanged(this.handleOnAppsChanged.bind(this)),await this.client.onLayoutsChanged(this.handleOnLayoutsChanged.bind(this)),await this.client.start(r,n),this.config.features?.preferencesStore&&await this.client.getAllPrefs(),this.started=!0,this.logger?.info(`Module ${this.name} started`)}async start(e){e.manager&&(this.globalConfig=e,this.config=e.manager,this.logger?.info("Starting the Manager controller."))}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this manager control message, because the controller has not been started");const t=e.data,r=e.commandId,n=managerOperationDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This manager request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`Manager request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`Manager request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}onConnectedStateChanged(e){return this.callbacks.add(CONNECTED_STATE_CHANGED_EVENT_KEY,e)}async saveLayouts(e,t,r){return this.sequelizer.enqueue(async()=>{let n;if(r&&this.logger?.trace(`[${r}] handling "saveLayouts" request | mode=${t}`),n="replace"===t?await this.client.deleteAllUserLayouts():await this.getAllCachedLayouts(),e.length){const t=new Map;for(const e of n)t.set(this.getLayoutKey(e),e);for(const r of e){const e={type:r.type,name:r.name,definition:JSON.stringify(r)},n=await this.client.saveLayout(e);t.set(this.getLayoutKey(r),n)}n=Array.from(t.values()),await this.managerCache.set(LAYOUTS_CACHE_KEY,n)}this.handleOnLayoutsChanged(n),r&&this.logger?.trace(`[${r}] request completed, layouts saved`)})}async renameLayout(e,t,r,n){return this.sequelizer.enqueue(async()=>{n&&this.logger?.trace(`[${n}] handling "renameLayout" request | oldName=${e}, newName=${t}, type=${r}`);const i=this.lastLayoutIdsByKey.get(this.getLayoutKey({name:e,type:r}));if(!i)throw new Error(`Layout with name="${e}" and type="${r}" not found.`);const o=await this.client.renameLayout(i,t),s={id:o.id,name:o.name,type:o.type,definition:o.definition};let a=await this.getAllCachedLayouts();a=a.filter(e=>e.id!==i),a.push(s),await this.managerCache.set(LAYOUTS_CACHE_KEY,a),this.setLastLayouts(a,this.parseLayouts(a));const c=this.parseLayouts([s]).map(t=>({...t,prevName:e}));this.callbacks.execute(LAYOUTS_RENAMED_EVENT_KEY,c),n&&this.logger?.trace(`[${n}] request completed, layout renamed`)})}async deleteLayout(e,t,r){return this.sequelizer.enqueue(async()=>{r&&this.logger?.trace(`[${r}] handling "deleteLayout" request | layoutName=${e}, type=${t}`);const n=this.lastLayoutIdsByKey.get(this.getLayoutKey({name:e,type:t}));if(!n)throw new Error(`Layout with name="${e}" and type="${t}" not found.`);await this.client.deleteUserLayout(n);let i=await this.getAllCachedLayouts();i=i.filter(e=>e.id!==n),await this.managerCache.set(LAYOUTS_CACHE_KEY,i),this.handleOnLayoutsChanged(i),r&&this.logger?.trace(`[${r}] request completed, layout deleted`)})}async getAllLayouts(e,t){t&&this.logger?.trace(`[${t}] handling "getAllLayouts" request | type=${e}`);const r=this.lastLayouts.filter(t=>t.type===e);return t&&this.logger?.trace(`[${t}] request completed, layouts retrieved`),r}async getLayout(e,t,r){r&&this.logger?.trace(`[${r}] handling "getLayout" request | layoutName=${e}, type=${t}`);const n=this.lastLayouts.find(r=>r.name===e&&r.type===t);return r&&this.logger?.trace(`[${r}] request completed, layout retrieved`),n}onLayoutsChanged(e){return this.callbacks.add(LAYOUTS_CHANGED_EVENT_KEY,e)}onLayoutsAdded(e){return this.callbacks.add(LAYOUTS_ADDED_EVENT_KEY,e)}onLayoutsRemoved(e){return this.callbacks.add(LAYOUTS_REMOVED_EVENT_KEY,e)}onLayoutsRenamed(e){return this.callbacks.add(LAYOUTS_RENAMED_EVENT_KEY,e)}async clearDefaultLayout(e){return this.sequelizer.enqueue(async()=>{e&&this.logger?.trace(`[${e}] handling "clearDefaultLayout" request`);const t=await this.client.setDefaultLayout();await this.managerCache.set(DEFAULT_LAYOUT_CACHE_KEY,t),e&&this.logger?.trace(`[${e}] request completed, default layout cleared`)})}async getDefaultLayout(e){return this.sequelizer.enqueue(async()=>{e&&this.logger?.trace(`[${e}] handling "getDefaultLayout" request`);const t=await this.client.getDefaultLayout();if(!t)return;const r="string"==typeof t.definition?JSON.parse(t.definition):t.definition,n=glueLayoutDecoder.run(r);if(!n.ok)throw n.error;return e&&this.logger?.trace(`[${e}] request completed, default layout retrieved`),r})}async setDefaultLayout(e,t){return this.sequelizer.enqueue(async()=>{t&&this.logger?.trace(`[${t}] handling "setDefaultLayout" request`);const r=this.lastLayoutIdsByKey.get(this.getLayoutKey({name:e,type:"Global"}));if(!r)throw new Error(`Layout with name="${e}" and type="Global" not found.`);const n=await this.client.setDefaultLayout(r);await this.managerCache.set(DEFAULT_LAYOUT_CACHE_KEY,n),t&&this.logger?.trace(`[${t}] request completed, default layout set`)})}getAllApps(){return this.lastApps}onAppsAdded(e){return this.callbacks.add(APPS_ADDED_EVENT_KEY,e)}onAppsDeleted(e){return this.callbacks.add(APPS_DELETED_EVENT_KEY,e)}onAppsChanged(e){return this.callbacks.add(APPS_CHANGED_EVENT_KEY,e)}async getPrefs(e,t){return this.config?.features?.preferencesStore?this.sequelizer.enqueue(async()=>{t&&this.logger?.trace(`[${t}] handling "getPrefs" request for app=${e}`);const r=await this.getAllCachedPrefs();let n;try{n=await this.client.getPrefs(e)}catch(e){if(!(e instanceof SanitizedIOManagerApiError&&404===e.status))throw e;n=void 0}if(n){const e=r.find(e=>e.app===n?.app);if(e&&!objEqualFast(e.data,n.data)){const e={app:n.app,prefs:this.transformPrefs(n)};this.callbacks.execute(PREFS_CHANGED_EVENT_KEY,e)}}const i=n?this.transformPrefs(n):void 0;return t&&this.logger?.trace(`[${t}] request completed, prefs retrieved`),i}):ioError.raiseError("Cannot get preferences, because the feature is not enabled")}async getAllPrefs(e){return this.config?.features?.preferencesStore?this.sequelizer.enqueue(async()=>{e&&this.logger?.trace(`[${e}] handling "getAllPrefs" request`);const t=await this.getAllCachedPrefs(),r=await this.client.getAllPrefs();this.notifyPrefs(t,r);const n=r.map(this.transformPrefs);return e&&this.logger?.trace(`[${e}] request completed, all prefs retrieved`),n}):ioError.raiseError("Cannot get all preferences, because the feature is not enabled")}async savePrefs(e,t){return this.config?.features?.preferencesStore?this.sequelizer.enqueue(async()=>{t&&this.logger?.trace(`[${t}] handling "savePrefs" request`);const r=await this.client.setPrefs({app:e.app,data:e.data,merge:!e.overwrite});await this.mergeInPreferenceCache([r]);const n={app:r.app,prefs:this.transformPrefs(r)};this.callbacks.execute(PREFS_CHANGED_EVENT_KEY,n),t&&this.logger?.trace(`[${t}] request completed, preferences saved`)}):ioError.raiseError("Cannot save preferences, because the feature is not enabled")}async clearPrefs(e,t){return this.config?.features?.preferencesStore?this.sequelizer.enqueue(async()=>{t&&this.logger?.trace(`[${t}] handling "clearPrefs" request`);const r=await Promise.all(e.map(e=>this.client.setPrefs({app:e,data:{},merge:!1})));await this.mergeInPreferenceCache(r);for(const e of r){const t={app:e.app,prefs:this.transformPrefs(e)};this.callbacks.execute(PREFS_CHANGED_EVENT_KEY,t)}t&&this.logger?.trace(`[${t}] request completed, preferences cleared`)}):ioError.raiseError("Cannot clear preferences, because the feature is not enabled")}async clearAllPrefs(e){return this.config?.features?.preferencesStore?this.sequelizer.enqueue(async()=>{e&&this.logger?.trace(`[${e}] handling "clearAllPrefs" request`);let t=await this.client.getAllPrefs();t=await Promise.all(t.map(e=>this.client.setPrefs({app:e.app,data:{},merge:!1}))),await this.managerCache.set(PREFS_CACHE_KEY,t);for(const e of t){const t={app:e.app,prefs:this.transformPrefs(e)};this.callbacks.execute(PREFS_CHANGED_EVENT_KEY,t)}e&&this.logger?.trace(`[${e}] request completed, all preferences cleared`)}):ioError.raiseError("Cannot clear all preferences, because the feature is not enabled")}clearCache(){return this.managerCache?.clear()}onPrefsChanged(e){return this.config?.features?.preferencesStore?this.callbacks.add(PREFS_CHANGED_EVENT_KEY,e):ioError.raiseError("Cannot subscribe to prefs changes, because the feature is not enabled")}handleOnLayoutsChanged(e){const t=this.parseLayouts(e);this.notifyLayouts(this.lastLayouts,t),this.setLastLayouts(e,t)}setLastLayouts(e,t){this.lastLayouts=t,this.lastLayoutIdsByKey.clear();for(const t of e)this.lastLayoutIdsByKey.set(this.getLayoutKey(t),t.id)}getLayoutKey(e){return e.name+" | "+e.type}notifyLayouts(e,t){const r=[],n=[],i=[],o=new Set(t.map(e=>e.name)),s=new Map;for(const t of e)o.has(t.name)||n.push(t),s.set(this.getLayoutKey(t),t);for(const e of t){const t=s.get(this.getLayoutKey(e));t?objEqualFast(e,t)||i.push(e):r.push(e)}r.length&&this.callbacks.execute(LAYOUTS_ADDED_EVENT_KEY,r),n.length&&this.callbacks.execute(LAYOUTS_REMOVED_EVENT_KEY,n),i.length&&this.callbacks.execute(LAYOUTS_CHANGED_EVENT_KEY,i)}parseLayouts(e){const t=e.map(e=>"string"==typeof e.definition?JSON.parse(e.definition):e.definition);return this.sanitizeLayouts(t).valid}sanitizeLayouts(e){return e.reduce((e,t)=>{const r=glueLayoutDecoder.run(t);return r.ok?e.valid.push(t):this.logger?.warn(`A layout with name: ${t.name} was not imported, because of error: ${JSON.stringify(r.error)}`),e},{valid:[]})}sanitizeApps(e){return e.reduce((e,t)=>{const r=allApplicationDefinitionsDecoder.run(t);return r.ok?e.valid.push(t):this.logger?.warn(`An app with name: ${t.name} was not imported, because of error: ${JSON.stringify(r.error)}`),e},{valid:[]})}notifyPrefs(e,t){const r=[],n=new Map;for(const t of e)n.set(t.app,t);for(const e of t){const t=n.get(e.app);t&&!objEqualFast(e.data,t.data)&&r.push(e)}for(const e of r){const t={app:e.app,prefs:this.transformPrefs(e)};this.callbacks.execute(PREFS_CHANGED_EVENT_KEY,t)}}async mergeInPreferenceCache(e){const t=await this.getAllCachedPrefs();for(const r of e){const e=t.findIndex(e=>e.app===r.app);-1!==e?t[e]=r:t.push(r)}await this.managerCache.set(PREFS_CACHE_KEY,t)}async getAllCachedPrefs(){const e=(await this.managerCache.get(PREFS_CACHE_KEY))?.value??[];for(const t of e)"string"==typeof t?.data&&(t.data=JSON.parse(t.data));return e}async getAllCachedLayouts(){return(await this.managerCache.get(LAYOUTS_CACHE_KEY))?.value??[]}handleOnConnectedStateChanged(e){const t=this.convertStateToConnectionState(e);this.connectionStateStream.push(t),this.callbacks.execute(CONNECTED_STATE_CHANGED_EVENT_KEY,t)}handleOnAppsChanged(e){let t=e;t=this.sanitizeApps(t)?.valid,this.notifyApps(this.lastApps,t),this.lastApps=t}notifyApps(e,t){const r=[],n=[],i=[],o=new Set(t.map(e=>e.name)),s=new Map;for(const t of e)o.has(t.name)||n.push(t),s.set(t.name,t);for(const e of t){const t=s.get(e.name);t?objEqualFast(e,t)||i.push(e):r.push(e)}r.length&&this.callbacks.execute(APPS_ADDED_EVENT_KEY,r),n.length&&this.callbacks.execute(APPS_DELETED_EVENT_KEY,n),i.length&&this.callbacks.execute(APPS_CHANGED_EVENT_KEY,i)}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}handleUnload(){this.unregisterInteropMethods(),this.client&&(this.callbacks.clear(),this.client.unload())}transformPrefs({app:e,data:t,lastUpdate:r}){return{app:e,data:t,lastUpdate:r}}convertErrorToDisconnectionError(e){return e?{message:e.message,name:e.name,code:e.code,status:e.status,request:e.request,isSessionExpired:e.isSessionExpired}:e}convertStateToConnectionState(e){const{disconnectionError:t,...r}=e;return{...r,disconnectionError:this.convertErrorToDisconnectionError(t)}}async registerInteropMethods(){this.logger?.info("Registering io.Manager interop methods"),await this.glueController.clientGlue.interop.register(GET_CONNECTION_STATE_METHOD_NAME,this.getConnectionState.bind(this)),await this.glueController.clientGlue.interop.register(FETCH_DATA_METHOD_NAME,this.handleFetchDataRequest.bind(this)),this.connectionStateStream=await this.glueController.clientGlue.interop.createStream(CONNECTION_STATE_STREAM_NAME,this.getConnectionStateStreamOptions())}unregisterInteropMethods(){this.logger?.info("Unregistering io.Manager interop methods"),this.glueController.clientGlue.interop.unregister(GET_CONNECTION_STATE_METHOD_NAME),this.glueController.clientGlue.interop.unregister(FETCH_DATA_METHOD_NAME),this.connectionStateStream.close()}getConnectionState(){return this.convertStateToConnectionState(this.managerConnectionState)}async handleFetchDataRequest(e){this.client&&await this.client.refreshData({applications:{include:e.applications??!1},commands:{include:e.commands??!1},layouts:{include:e.layouts??!1},configs:{include:e.configs??!1}})}getConnectionStateStreamOptions(){return{subscriptionAddedHandler:e=>{const t=this.getConnectionState();e.push(t)}}}createManagerLogger(){const e=logger.get("io-manager-connection"),t=e=>{if(e instanceof SanitizedIOManagerApiError)return JSON.stringify(e,null,2);if(e instanceof IOManagerRequestValidationError)return`${e.toString()} ${e.getZodError().toString()}`;if(e instanceof Error)return extractErrorMsg$1(e);try{return JSON.stringify(e)}catch{return"[Unable to serialize]"}},r=(e,r)=>r.length?`${e} ${r.map(t).join(" ").trim()}`:e;return{trace(t,...n){e?.canPublish("trace")&&e?.trace(r(t,n))},debug(t,...n){e?.canPublish("debug")&&e?.debug(r(t,n))},info(t,...n){e?.canPublish("info")&&e?.info(r(t,n))},warn(t,...n){e?.canPublish("warn")&&e?.warn(r(t,n))},error(t,...n){e?.canPublish("error")&&e?.error(r(t,n))},isTraceEnabled:()=>Boolean(e?.canPublish("trace")),isDebugEnabled:()=>Boolean(e?.canPublish("debug")),isInfoEnabled:()=>Boolean(e?.canPublish("info")),isWarnEnabled:()=>Boolean(e?.canPublish("warn")),isErrorEnabled:()=>Boolean(e?.canPublish("error")),isLevelEnabled:t=>Boolean(e?.canPublish(t)),log:(t,n,...i)=>{e?.canPublish(t)&&e?.log(r(n,i),t)}}}}class Identity{uaParser;glueController;pluginsController;workspacesFrameUrl;constructor(e,t,r,n){this.uaParser=e,this.glueController=t,this.pluginsController=r,this.workspacesFrameUrl=n}get logger(){return logger.get("manager.identity")}async getMachineInfo(e){const t=this.uaParser.getResult();return{user:e,name:"",os:{name:t.os.name||"",version:t.os.version||"",arch:t.cpu.architecture||""},browser:{name:t.browser.name||"",version:t.browser.version||"",engine:t.engine.name||""},mobileDevice:"mobile"===t.device?.type?{vendor:t.device.vendor,model:t.device.model}:void 0,displays:await this.getDisplays()}}getGlueInfo(){return{version:"",build:"",region:"",env:"",core:{web:{version:this.glueController.clientGlue.version},platform:{version:this.glueController.platformVersion,plugins:this.pluginsController.registeredPlugins},plus:{version:version$1}},workspaces:this.glueController.isWorkspacesEnabled?{version:this.glueController.clientGlue.workspaces?.version,frameUrl:this.workspacesFrameUrl}:void 0}}async getDisplays(){try{const{state:e}=await getWindowManagementPermissionStatus(this.logger);if("granted"!==e)return[]}catch(e){return this.logger?.warn(extractErrorMsg$1(e)),[]}return(await window.getScreenDetails()).screens.map(e=>({bounds:{x:e.left,y:e.top,width:e.width,height:e.height},workingArea:{x:e.availLeft,y:e.availTop,width:e.availWidth,height:e.availHeight},dpi:e.devicePixelRatio,isPrimary:e.isPrimary}))}}const prefsOperationTypesDecoder=oneOf$1(constant$2("operationCheck"),constant$2("clear"),constant$2("clearAll"),constant$2("get"),constant$2("getAll"),constant$2("set"),constant$2("update"),constant$2("prefsHello"),constant$2("registerSubscriber")),appPreferencesDecoder=object$2({app:nonEmptyStringDecoder$2,data:object$2(),lastUpdate:optional$3(nonEmptyStringDecoder$2)}),basePrefsConfigDecoder=object$2({app:nonEmptyStringDecoder$2}),subscriberRegisterConfigDecoder=object$2({interopId:nonEmptyStringDecoder$2,appName:optional$3(nonEmptyStringDecoder$2)}),getPrefsResultDecoder=object$2({prefs:appPreferencesDecoder}),getAllPrefsResultDecoder=object$2({all:array$3(appPreferencesDecoder)}),changePrefsDataDecoder=object$2({app:nonEmptyStringDecoder$2,data:object$2()}),prefsHelloSuccessDecoder=object$2({platform:object$2({app:nonEmptyStringDecoder$2}),validNonExistentApps:optional$3(array$3(nonEmptyStringDecoder$2)),isAppValidationEnabled:optional$3(boolean$3())});class PrefsController{glueController;localStore;managerStore;restStore;operations={operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)},clear:{name:"clear",execute:this.clear.bind(this),dataDecoder:basePrefsConfigDecoder},clearAll:{name:"clearAll",execute:this.clearAll.bind(this)},get:{name:"get",execute:this.get.bind(this),dataDecoder:basePrefsConfigDecoder,resultDecoder:getPrefsResultDecoder},getAll:{name:"getAll",execute:this.getAll.bind(this),resultDecoder:getAllPrefsResultDecoder},set:{name:"set",execute:this.set.bind(this),dataDecoder:changePrefsDataDecoder},update:{name:"update",execute:this.update.bind(this),dataDecoder:changePrefsDataDecoder},prefsHello:{name:"prefsHello",execute:this.prefsHello.bind(this),resultDecoder:prefsHelloSuccessDecoder},registerSubscriber:{name:"registerSubscriber",dataDecoder:subscriberRegisterConfigDecoder,execute:this.registerSubscriber.bind(this)}};started=!1;unsubFuncs=[];_platformAppName=`Platform-${window.location.origin}`;config;store;isAppValidationEnabled;constructor(e,t,r,n){this.glueController=e,this.localStore=t,this.managerStore=r,this.restStore=n}get logger(){return logger.get("prefs.controller")}get systemValidNonExistentApps(){return[systemPrefsAppName]}get validNonExistentApps(){const e=Array.isArray(this.config?.validNonExistentApps)?this.config.validNonExistentApps:[];return this.systemValidNonExistentApps.concat(e)}handlePlatformShutdown(){this.started=!1,this.unsubFuncs.forEach(e=>e()),this.unsubFuncs=[],this.store.stop()}get platformAppName(){return this._platformAppName}get storeType(){return this.store.type}async start(e){this.logger?.trace("initializing prefs"),this.started=!0,this.config=e.applicationPreferences,this.isAppValidationEnabled="all"!==(this.config?.validNonExistentApps??"all"),this.store=this.getStore(e),this.setupStoreListeners(),await this.store.start(e),this.logger?.trace("initialization is completed")}ready(){return Promise.resolve()}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this prefs control message, because the controller has not been started");const t=e.data,r=e.commandId,n=prefsOperationTypesDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This prefs request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`Prefs request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`Prefs request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}async registerSubscriber({interopId:e,appName:t},r){if(this.trace(`[${r}] handling registerSubscriber command with interopId: ${e}`,r),!t)return void this.trace(`[${r}] no appName provided, skipping subscriber registration.`,r);const n=this.validateApp(t);this.store.processNewSubscriber(n),this.trace(`[${r}] registerSubscriber command was executed successfully`,r)}async get({app:e},t){this.trace(`[${t}] handling get command with app: ${e}`,t);const r={app:e,data:{}};return{prefs:await this.store.getPrefs(e,t)||r}}async update({app:e,data:t},r){this.trace(`[${r}] handling update command with app: ${e} and data: ${JSON.stringify(t)}`,r);const n=this.validateApp(e);await this.store.savePrefs({app:n,data:t,overwrite:!1},r),this.trace(`[${r}] update command was executed successfully`,r)}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}async clear({app:e},t){this.trace(`[${t}] handling clear command with app: ${e}`,t);const r=this.validateApp(e);await this.store.clearPrefs([r],t),this.trace(`[${t}] clear command was executed successfully`,t)}async clearAll(e,t){this.trace(`[${t}] handling clearAll command`,t),await this.store.clearAllPrefs(t),this.trace(`[${t}] clearAll command was executed successfully`,t)}async getAll(e,t){this.trace(`[${t}] handling getAll command`,t);const r=await this.store.getAllPrefs(t);return this.trace(`[${t}] getAll command was executed successfully`,t),{all:r}}async set({app:e,data:t},r){this.trace(`[${r}] handling set command with app: ${e} and data: ${JSON.stringify(t)}`,r);const n=this.validateApp(e);await this.store.savePrefs({app:n,data:t,overwrite:!0},r),this.trace(`[${r}] set command was executed successfully`,r)}async prefsHello(){return{platform:{app:this._platformAppName},validNonExistentApps:this.validNonExistentApps,isAppValidationEnabled:this.isAppValidationEnabled}}validateApp(e){if(!this.isAppValidationEnabled)return e;const t=this.glueController.getAllApplicationNames();return e===this._platformAppName||t.includes(e)||this.validNonExistentApps.includes(e)?e:ioError.raiseError(`The provided app name "${e}" is not valid.`)}trace(e,t){t&&this.logger?.trace(e)}setupStoreListeners(){const e=this.store.onPrefsChanged(e=>{this.emitStreamData("prefsChanged",{prefs:e.prefs})});this.unsubFuncs.push(e)}emitStreamData(e,t){this.logger?.trace(`sending notification of event: ${e} with data: ${JSON.stringify(t)}`),this.glueController.pushSystemMessage("prefs",e,t)}getStore(e){const t=e.applicationPreferences?.store?.type,r=!(!e?.manager?.url||!e?.manager?.features?.preferencesStore),n=!!e?.applicationPreferences?.store?.rest?.url;return!t&&r?this.managerStore:t||r?"local"===t?this.localStore:"rest"===t&&n?this.restStore:"rest"!==t||n?"manager"===t&&r?this.managerStore:"manager"!==t||r?ioError.raiseError("Cannot set prefs store."):ioError.raiseError("The prefs store is configured to be managed, but the manager is not configured."):ioError.raiseError("The prefs store is configured to be rest, but the rest url is not configured."):this.localStore}}class IdbBasedIOManagerCache{kvStoreName="data";dbVersion=1;dbNamePrefix="IOManagerCache";logger=logger.get("io-manager-cache");config;dbName;database;data={};constructor(e,t){if(!("indexedDB"in window))throw new Error("Cannot initialize the local storage, because IndexedDB is not supported");this.config=e,this.dbName=`${this.dbNamePrefix}-${t}-${e.url}`}async get(e){const t=this.data[e];return t?(this.logger?.trace(`Read cache data for key: ${e}`),t):void this.logger?.trace(`Read cache data for key: ${e} - key not found.`)}async set(e,t){if(!this.database)throw new Error("Database not initialized.");this.logger?.trace(`Write cache data for key: ${e}`);const r=this.data[e];r?r.value=t:this.data[e]={value:t},await this.database.put(this.kvStoreName,{value:t,key:e})}async remove(e){if(!this.database)throw new Error("Database not initialized.");this.logger?.trace(`Remove cache data for key: ${e}`),delete this.data[e],await this.database.delete(this.kvStoreName,e)}async initialize(){if(this.database=await openDB(this.dbName,this.dbVersion,{upgrade:this.setUpDB.bind(this)}),this.config.cache?.clearOld)if("databases"in indexedDB){const e=(await indexedDB.databases()).filter(e=>e.name?.startsWith(this.dbNamePrefix)&&e.name!==this.dbName);for(const t of e)if(t.name)try{this.logger?.info(`Deleting cache db "${t.name}"`),await deleteDB(t.name)}catch(e){this.logger?.warn(`Failed to delete db "${t.name}". Error: ${extractErrorMsg$1(e)}`)}}else this.logger?.warn("Could not delete extraneous cache databases. This engine does not support indexedDB.databases.");await this.readFromDB()}async dispose(){this.logger?.trace(`Closing idb connection: "${this.dbName}"`),this.database?.close(),delete this.database}async clear(){await this.dispose(),this.logger?.trace(`Deleting idb database: "${this.dbName}"`),await deleteDB(this.dbName),await this.initialize()}setUpDB(e){e.objectStoreNames.contains(this.kvStoreName)||e.createObjectStore(this.kvStoreName,{keyPath:"key"})}async readFromDB(){if(!this.database)throw new Error("Database not initialized.");this.logger?.trace(`Reading from db: "${this.dbName}"`);const e=await this.database.getAll(this.kvStoreName),t={};for(const r of e)t[r.key]=r;this.data=t}}class SessionStorageBasedIOManagerCache{storageKeyPrefix="IOManagerCache";storageKey;logger=logger.get("io-manager-cache");config;data={};constructor(e,t){if(!("sessionStorage"in window))throw new Error("Cannot initialize the local storage, because sessionStorage is not supported");this.config=e,this.storageKey=`${this.storageKeyPrefix}-${t}-${e.url}`}async get(e){const t=this.data[e];return t?(this.logger?.trace(`Read cache data for key: ${e}`),t):void this.logger?.trace(`Read cache data for key: ${e} - key not found.`)}async set(e,t){this.logger?.trace(`Write cache data for key: ${e}`);const r=this.data[e];r?r.value=t:this.data[e]={value:t},this.writeToSessionStorage()}async remove(e){this.logger?.trace(`Remove cache data for key: ${e}`),delete this.data[e],this.writeToSessionStorage()}async initialize(){if(this.config.cache?.clearOld){const e=Object.keys(sessionStorage).filter(e=>e.startsWith(this.storageKeyPrefix)&&e!==this.storageKey);for(const t of e)try{this.logger?.info(`Deleting cache item "${t}"`),sessionStorage.removeItem(t)}catch(e){this.logger?.warn(`Failed to delete cache with key "${t}". Error: ${extractErrorMsg$1(e)}`)}}await this.readFromSessionStorage()}async dispose(){}async clear(){this.logger?.trace(`Deleting sessionStorage item with key "${this.storageKey}"`),sessionStorage.removeItem(this.storageKey),await this.initialize(),this.writeToSessionStorage()}async readFromSessionStorage(){let e;this.logger?.trace(`Reading sessionStorage item with key "${this.storageKey}"`);try{e=sessionStorage.getItem(this.storageKey)}catch(e){return this.logger?.warn(`Failed to read sessionStorage item with key "${this.storageKey}". ${extractErrorMsg$1(e)}`),void(this.data={})}if(!e)return this.logger?.warn(`sessionStorage item with key "${this.storageKey}" does not exist.`),void(this.data={});try{this.data=JSON.parse(e)}catch(e){this.logger?.warn(`Failed to parse json from sessionStorage item with key "${this.storageKey}". ${extractErrorMsg$1(e)}`),this.data={}}}writeToSessionStorage(){let e;this.logger?.trace(`Writing cache to sessionStorage item with key "${this.storageKey}"`);try{e=JSON.stringify(this.data)}catch(e){return void this.logger?.warn(`Failed to serialize io-manager cache. ${extractErrorMsg$1(e)}`)}try{sessionStorage.setItem(this.storageKey,e)}catch(e){this.logger?.warn(`Failed to write to sessionStorage item with key "${this.storageKey}". ${extractErrorMsg$1(e)}`)}}}let urlAlphabet="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",nanoid=(e=21)=>{let t="",r=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+=urlAlphabet[63&r[e]];return t};const otelOperationTypesDecoder=oneOf$1(constant$2("operationCheck"));class OtelController{telemetry;getNewMetricsDependencyBuilder;glueController;getPlatformController;systemController;applicationsController;layoutsController;workspacesController;serviceId=nanoid();serviceName="io.Connect Browser";fallbackLayoutName="unknown";config;platformController;started=!1;operations={operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)}};constructor(e,t,r,n,i,o,s,a){this.telemetry=e,this.getNewMetricsDependencyBuilder=t,this.glueController=r,this.getPlatformController=n,this.systemController=i,this.applicationsController=o,this.layoutsController=s,this.workspacesController=a}get logger(){return logger.get("otel.controller")}get glue(){return this.glueController.clientGlue}get metricsDependencyContainer(){const e=this.getNewMetricsDependencyBuilder();e.withInstanceStartedHandler(this.instanceStartedHandler.bind(this)).withInstanceStoppedHandler(this.instanceStoppedHandler.bind(this)).withInstanceReadyHandler(this.instanceReadyHandler.bind(this)).withInstanceFocusedHandler(this.instanceFocusedHandler.bind(this)).withInstanceErrorHandler(this.instanceErrorHandler.bind(this)).withLayoutRestoredHandler(this.layoutRestoredHandler.bind(this)).withWorkspaceStoppedHandler(this.workspaceStoppedHandler.bind(this)).withWorkspaceStartedHandler(this.workspaceStartedHandler.bind(this)).withWorkspaceSavedHandler(this.workspaceSavedHandler.bind(this)).withPlatformStartedHandler(this.platformStartedHandler.bind(this)).withPlatformErrorHandler(this.platformErrorHandler.bind(this));return e.build()}get metricsSettings(){if(!this.config.otel?.metrics)return{enabled:!1};const{additionalResourceAttributes:e,getAdditionalAttributes:t,headers:r,metrics:n,publishInterval:i=3e4,url:o}=this.config.otel.metrics,s=t?.();this.warnIfPlatformVersionAttributeIsProvided(s),this.warnIfPlatformVersionAttributeIsProvided(e);const a=n?.map(e=>({...e,enabled:e.enabled??!0,name:e.name??e.type,description:e.description??"no description"}));return{additionalResourceAttributes:e,additionalAttributes:s,enabled:!0,headers:r,metrics:a,platformMetricsEnabled:!0,publishInterval:i,url:o}}get settings(){const e=this.config.otel?.getAdditionalAttributes?.(),t=this.config.otel?.additionalResourceAttributes;return this.warnIfPlatformVersionAttributeIsProvided(e),this.warnIfPlatformVersionAttributeIsProvided(t),{additionalAttributes:e,additionalResourceAttributes:t,enabled:!!this.config.otel?.metrics,headers:this.config.otel?.headers,metrics:this.metricsSettings,platformVersion:this.glueController.platformVersion,serviceId:this.serviceId,serviceName:this.serviceName,serviceVersion:this.glueController.platformVersion,userId:this.config.user?.id}}warnIfPlatformVersionAttributeIsProvided(e){e&&"platformVersion"in e&&this.logger?.warn("The provided additional attributes override the default platform version settings.")}async start(e){this.config=e,this.shouldStartController()&&(this.platformController=this.getPlatformController(),this.logger?.trace("Starting the Otel controller."))}async configurePostStart(){if(this.shouldStartController())try{await this.telemetry.start(this.settings,this.metricsDependencyContainer),this.started=!0}catch(e){const t=extractErrorMsg$1(e);this.logger?.error(`Failed to start Otel Controller. Reason: ${t}`)}}ready(){return Promise.resolve()}async handlePlatformShutdown(){if(this.started)try{await this.telemetry.stop(),this.started=!1,this.resetMetricHandlerSubscriptionCounters()}catch(e){const t=extractErrorMsg$1(e);this.logger?.error(`Failed to stop Otel Controller. Reason: ${t}`)}}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this otel control message, because the controller has not been started");const t=e.data,r=e.commandId,n=otelOperationTypesDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This otel request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`Otel request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`Otel request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}shouldStartController(){return!!this.config.otel?.metrics?.url}incrementMetricHandlerSubscriptionCounter(e){window.testingOtel&&++window.testingOtel.metricHandlers[e].numberOfSubscriptions}resetMetricHandlerSubscriptionCounters(){window.testingOtel&&Object.values(window.testingOtel.metricHandlers).forEach(e=>{e.numberOfSubscriptions=0})}instanceStartedHandler(e){this.incrementMetricHandlerSubscriptionCounter("instanceStarted");const t=t=>{const r={application:t.application.name};if(window.testingOtel)return window.testingOtel.metricHandlers.instanceStarted.callback(r);e(r)},r=this.glue.appManager.onInstanceStarted(t);return this.glue.appManager.instances().forEach(t),r}instanceStoppedHandler(e){return this.incrementMetricHandlerSubscriptionCounter("instanceStopped"),this.glue.appManager.onInstanceStopped(t=>{const r={application:t.application.name};if(window.testingOtel)return window.testingOtel.metricHandlers.instanceStopped.callback(r);e(r)})}instanceReadyHandler(e){return this.incrementMetricHandlerSubscriptionCounter("instanceReady"),this.applicationsController.onInstanceStarted(({api:t="unknown",applicationName:r,startup:n})=>{const i={api:t,application:r,startTime:n.start,endTime:n.end};if(window.testingOtel)return window.testingOtel.metricHandlers.instanceReady.callback(i);e(i)})}instanceFocusedHandler(e){this.incrementMetricHandlerSubscriptionCounter("instanceFocused");const t=this.glue.windows.onWindowGotFocus(t=>{const r=this.glue.appManager.instances().find(e=>e.id===t.id),n={application:r?.application?.name??t.name,focused:!0};if(window.testingOtel)return window.testingOtel.metricHandlers.instanceFocused.callback(n);e(n)}),r=this.glue.windows.onWindowLostFocus(t=>{const r=this.glue.appManager.instances().find(e=>e.id===t.id),n={application:r?.application?.name??t.name,focused:!1};if(window.testingOtel)return window.testingOtel.metricHandlers.instanceFocused.callback(n);e(n)});return()=>{t(),r()}}instanceErrorHandler(e){return this.incrementMetricHandlerSubscriptionCounter("instanceError"),this.systemController.onClientError(({callerId:t})=>{const r={application:this.glueController.getAppNameByInstanceId(t??"")??"unknown"};if(window.testingOtel)return window.testingOtel.metricHandlers.instanceError.callback(r);e(r)})}layoutRestoredHandler(e){return this.incrementMetricHandlerSubscriptionCounter("layoutRestored"),this.layoutsController.onLayoutRestored(({layoutName:t,startTime:r,endTime:n})=>{const i={layout:t,startTime:r,endTime:n};if(window.testingOtel)return window.testingOtel.metricHandlers.layoutRestored.callback(i);e(i)})}workspaceStoppedHandler(e){return this.incrementMetricHandlerSubscriptionCounter("workspaceStopped"),this.workspacesController.onWorkspaceClosed(({layoutName:t})=>{const r={layout:t??this.fallbackLayoutName};if(window.testingOtel)return window.testingOtel.metricHandlers.workspaceStopped.callback(r);e(r)})}workspaceStartedHandler(e){return this.incrementMetricHandlerSubscriptionCounter("workspaceStarted"),this.workspacesController.onWorkspaceStarted(({layoutName:t})=>{const r={layout:t??this.fallbackLayoutName};if(window.testingOtel)return window.testingOtel.metricHandlers.workspaceStarted.callback(r);e(r)})}workspaceSavedHandler(e){return this.incrementMetricHandlerSubscriptionCounter("workspaceSaved"),this.workspacesController.onWorkspaceSaved(({layoutName:t,oldLayoutName:r})=>{const n={layout:t,oldLayout:r??this.fallbackLayoutName};if(window.testingOtel)return window.testingOtel.metricHandlers.workspaceSaved.callback(n);e(n)})}platformStartedHandler(e){return this.incrementMetricHandlerSubscriptionCounter("platformStarted"),this.platformController.onPlatformStarted(({platformVersion:t,startup:r})=>{const n={startTime:r.start,endTime:r.end,api:t};if(window.testingOtel)return window.testingOtel.metricHandlers.platformStarted.callback(n);e(n)})}platformErrorHandler(e){return this.incrementMetricHandlerSubscriptionCounter("platformError"),this.systemController.onPlatformError(()=>{const t={};if(window.testingOtel)return window.testingOtel.metricHandlers.platformError.callback(t);e(t)})}}class Telemetry{getNewContainerBuilder;buildLogger;container=null;constructor(e,t){this.getNewContainerBuilder=e,this.buildLogger=t}get logger(){return logger.get("otel.telemetry")}async start(e,t){if(this.container)return ioError.raiseError("An Otel container has already been started");this.logger?.trace(`Starting an Otel container with settings: ${JSON.stringify(e)}`);const r=await this.buildContainer(e,t);await r.start(),this.container=r,this.logger?.trace("The Otel container has been started successfully")}async stop(){this.container&&(await this.container.stop(),this.container=null,this.logger?.trace("The Otel container has been stopped successfully"))}async buildContainer(e,t){const r=this.getNewContainerBuilder();if(this.logger&&r.withLogger(this.buildLogger(this.logger)),r.withSettings(e),e?.metrics?.enabled){let e;try{(await Promise.resolve().then(function(){return index$2})).init(),e=!0}catch{this.logger?.warn("@interopio/insights-base plugin failed to load, insights functionality will be disabled"),e=!1}try{e&&(await Promise.resolve().then(function(){return index$1})).init()}catch{this.logger?.warn("@interopio/insights-metrics plugin failed to load, insights metrics functionality will be disabled")}r.withMetrics().withDependencyContainer(t)}return r.build()}}class LoggerAdapter{logger;logLevelMap={error:30,warn:50,info:60,debug:70,trace:80};constructor(e){this.logger=e}get level(){const e=this.logger.consoleLevel();return this.logLevelMap[e]??60}error(e,...t){const r=this.tryStringify(e,t);this.logger.error(r)}warn(e,...t){const r=this.tryStringify(e,t);this.logger.warn(r)}info(e,...t){const r=this.tryStringify(e,t);this.logger.info(r)}debug(e,...t){const r=this.tryStringify(e,t);this.logger.debug(r)}verbose(e,...t){const r=this.tryStringify(e,t);this.logger.trace(r)}tryStringify(e,t){try{return JSON.stringify(t.length?{message:e,args:t}:{message:e})}catch(t){return e}}}const defaultWidgetConfig={channels:{selector:{enable:!0,type:"default"},displayMode:"all"},position:"bottom-center",displayInWorkspace:!1,restoreLastKnownPosition:!0};class UIController{sessionStorage;glueController;started=!1;config;operations={getResources:{name:"getResources",dataDecoder:getResourcesDataDecoder,resultDecoder:getResourcesResultDecoder,execute:this.handleGetResources.bind(this)},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)},requestAlert:{name:"requestAlert",dataDecoder:uiAlertRequestMessageDecoder,execute:this.handleAlertRequest.bind(this)},requestDialog:{name:"requestDialog",dataDecoder:uiDialogRequestMessageDecoder,resultDecoder:uiDialogClientResponseDecoder,execute:this.handleDialogRequest.bind(this)},alertInteropAction:{name:"alertInteropAction",dataDecoder:alertInteropActionDataDecoder,execute:this.handleAlertInteropAction.bind(this)},getModalsStatus:{name:"getModalsStatus",resultDecoder:modalsStatusResponseDecoder,execute:this.handleGetModalsStatus.bind(this)}};clientOperations={showAlert:{name:"showAlert",execute:noop$1},showDialog:{name:"showDialog",execute:noop$1},operationCheck:{name:"operationCheck",execute:noop$1},showResolver:{name:"showResolver",execute:noop$1}};constructor(e,t){this.sessionStorage=e,this.glueController=t}async start(e){this.started=!0,this.config=e}ready(){return Promise.resolve()}async openResolver({config:e,initialCaller:t,methodResponseTimeoutMs:r,commandId:n}){this.logger?.trace(`[${n}] Handling open resolver request with config: ${JSON.stringify(e)}`);const i=this.getIntentResolverTargetInstance(t.instanceId,n);return(await this.glueController.callInstance("ui",this.clientOperations.showResolver,{config:e},{instance:i},{methodResponseTimeoutMs:r})).result}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this UI control message, because the controller has not been started");const t=e.data,r=e.commandId,n=uiOperationTypesDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This UI request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`UI request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`UI request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}get logger(){return logger.get("ui.controller")}async handleGetResources({origin:e}){return{resources:{widget:this.getWidgetResources(e),modals:this.getModalsResources(e),intentResolver:this.getIntentResolverResources(e)}}}async handleGetModalsStatus(e,t){this.logger?.trace(`[${t}] Handling get status request`);const r={status:{platformConfigured:!!this.config.modals}};return this.logger?.trace(`[${t}] Get status request was handled successfully with response: ${JSON.stringify(r)}`),r}async handleAlertRequest(e,t){if(this.logger?.trace(`[${t}] Handling alert request with config: ${JSON.stringify(e)}`),!this.config.modals)return ioError.raiseError(`[${t}] Cannot handle alert request, because modals are not configured in the platform`);const r=this.getModalsTargetInstance(e.target.instance,t,e.target.container);this.logger?.trace(`[${t}] Target instance for the alert request is: ${r}`);const{isSupported:n}=await this.glueController.checkClientOperationSupport("ui",this.clientOperations.showAlert,{instance:r});if(!n)return ioError.raiseError(`[${t}] Cannot handle alert request, because the target instance does not support the operation`);this.logger?.trace(`[${t}] Calling the showAlert operation with the provided config`),await this.glueController.callInstance("ui",this.clientOperations.showAlert,e,{instance:r}),this.logger?.trace(`[${t}] Alert request was handled successfully`)}async handleDialogRequest(e,t){if(this.logger?.trace(`[${t}] Handling dialog request with config: ${JSON.stringify(e)}`),!this.config.modals)return ioError.raiseError(`[${t}] Cannot handle dialog request, because modals are not configured in the platform`);const r=this.getModalsTargetInstance(e.target.instance,t,e.target.container);this.logger?.trace(`[${t}] Target instance for the dialog request is: ${r}`);const{isSupported:n}=await this.glueController.checkClientOperationSupport("ui",this.clientOperations.showDialog,{instance:r});if(!n)return ioError.raiseError(`[${t}] Cannot handle dialog request, because the target instance does not support the operation`);this.logger?.trace(`[${t}] Calling the showDialog operation with the provided config`);const{timer:i}=e.config,o={methodResponseTimeoutMs:i?.duration?getSafeTimeoutDelay(i.duration+DEFAULT_METHOD_RESPONSE_TIMEOUT_MS$1):MAX_SET_TIMEOUT_DELAY},s=await this.glueController.callInstance("ui",this.clientOperations.showDialog,e,{instance:r},o);return this.logger?.trace(`[${t}] Dialog request was handled successfully.`),s}getWidgetResources(e){if(!this.config?.widget)return;return checkIsOriginBlocked(e,this.config.widget.blockList)?{blockedOrigin:!0}:{blockedOrigin:!1,config:this.config?.widget?.defaultConfig||defaultWidgetConfig,sources:this.config.widget.sources}}getModalsResources(e){if(!this.config?.modals)return;return checkIsOriginBlocked(e,this.config.modals.blockList)?{blockedOrigin:!0}:{blockedOrigin:!1,sources:this.config.modals.sources}}getIntentResolverResources(e){if(!this.config?.intentResolver)return;return checkIsOriginBlocked(e,this.config.intentResolver.blockList)?{blockedOrigin:!0}:{blockedOrigin:!1,sources:this.config.intentResolver.sources}}getModalsTargetInstance(e,t,r){const n=r?this.retrieveWindowContainerInstanceId(e,r):e;return this.glueController.getLocalServers().some(e=>e.instance===n)?n:ioError.raiseError(`[${t}] Cannot handle modals request, because the target instance does not exist - ${n}`)}retrieveWindowContainerInstanceId(e,t){if("Global"===t)return ioError.raiseError(`Cannot retrieve the instance id for the client with id: ${e}, because the container type - "Global" is not supported`);const r=this.sessionStorage.getWorkspaceClientById(e);return r?r.frameId:e}async handleAlertInteropAction(e,t){this.logger?.trace(`[${t}] Handling alert interop action with config: ${JSON.stringify(e)}`);const{method:r,arguments:n,target:i}=e.interopAction.settings,o=i?this.getInteropInstanceTarget(i,t):void 0;this.logger?.trace(`[${t}] Instance target for the alert interop action is: ${JSON.stringify(o)}`),await this.glueController.invokeMethod(r,n,o)}getInteropInstanceTarget(e,t){if("best"===e||"all"===e)return e;const r=this.glueController.getLocalServers().find(t=>t.instance===e);return r||ioError.raiseError(`[${t}] No interop instance was found for the provided target ${e}.`)}getIntentResolverTargetInstance(e,t){const r=this.sessionStorage.getWorkspaceClientById(e);this.logger?.trace(`[${t}] Initial caller id '${e}' ${r?"is":"isn't"} a workspace client.`);const n=r?r.frameId:e;return this.logger?.trace(`[${t}] Target instance id for the intent resolver is: ${n}`),n}}class LocalPrefsStore{idbController;registry=CallbackRegistryFactory$2();type="local";constructor(e){this.idbController=e}async start(){}stop(){}async getPrefs(e){return await this.idbController.getPrefs(e)}async savePrefs(e){const t=e.overwrite?"setPrefs":"updatePrefs",r=await this.idbController[t]({app:e.app,data:e.data,lastUpdate:getLastUpdateTimestamp()});this.registry.execute("prefsChanged",{app:e.app,prefs:r})}async clearPrefs(e){await Promise.all(e.map(async e=>{const t=await this.idbController.setPrefs({app:e,data:{},lastUpdate:getLastUpdateTimestamp()});this.registry.execute("prefsChanged",{app:e,prefs:t})}))}async clearAllPrefs(){(await this.idbController.clearAllPrefs(getLastUpdateTimestamp())).forEach(e=>{this.registry.execute("prefsChanged",{app:e.app,prefs:e})})}async getAllPrefs(){return await this.idbController.getAllPrefs()}onPrefsChanged(e){return this.registry.add("prefsChanged",e)}processNewSubscriber(){}}class ManagerPrefsStore{managerController;type="manager";constructor(e){this.managerController=e}async start(){}stop(){}async getPrefs(e,t){return await this.managerController.getPrefs(e,t)}async savePrefs(e,t){await this.managerController.savePrefs(e,t)}async clearPrefs(e,t){await this.managerController.clearPrefs(e,t)}async clearAllPrefs(e){await this.managerController.clearAllPrefs(e)}async getAllPrefs(e){return await this.managerController.getAllPrefs(e)}onPrefsChanged(e){return this.managerController.onPrefsChanged(e)}processNewSubscriber(){}}const defaultRestHeaders={"Content-Type":"application/json",Accept:"application/json"},defaultRestRequestTimeoutMS=3e4;class RestPrefsStore{sequelizer;scheduler;cache;sessionController;type="rest";registry=CallbackRegistryFactory$2();cacheConfig;url;requestTimeout;pollingInterval;userCustomHeaders={};getUserRequestInit=()=>({});fetched={};get logger(){return logger.get("applications.prefs.rest.store")}constructor(e,t,r,n){this.sequelizer=e,this.scheduler=t,this.cache=r,this.sessionController=n}async start(e){const t=e.applicationPreferences?.store?.rest;if(!t)return ioError.raiseError("Cannot setup prefs rest store, because of missing config");if(!t.pollingInterval&&t.cache?.enabled)return ioError.raiseError("Cannot setup prefs rest store, because polling interval is not set while cache is enabled");if(t.pollingInterval&&t.pollingInterval<5e3)return ioError.raiseError("Cannot setup prefs rest store, because polling interval is set to less than 5000ms");this.url=this.getBaseUrl(t.url),this.requestTimeout=t.requestTimeout??defaultRestRequestTimeoutMS,this.userCustomHeaders=t.customHeaders??{},this.getUserRequestInit=t.getRequestInit??(()=>({})),this.pollingInterval=t.pollingInterval??0,this.cacheConfig=t.cache??{},await this.cache.start(t);const r=this.sessionController.getAllPrefsRestSchedulerCache().map(e=>e.app);this.sessionController.clearAllPrefsRestSchedulerCache(),r.forEach(e=>this.addSchedulerEntry(e))}stop(){this.cache.stop()}async getPrefs(e,t){return this.sequelizer.enqueue(async()=>{const r=this.cacheConfig.enabled,n=r&&this.fetched[e]?await this.cache.getPrefs(e):void 0;let i;try{i=n??await this.getPrefsFromServer(e,t)}catch(t){const n=r&&await this.cache.getPrefs(e);return n?(this.logger?.warn(`Failed to fetch prefs for app ${e} from server, using cached prefs: ${t}`),n):ioError.raiseError(`Failed to fetch prefs for app ${e} from server and no cached prefs available: ${t}`)}return await this.comparePrefs(i),this.addSchedulerEntry(e),await this.cache.setPrefs(i),i})}async savePrefs(e,t){return this.sequelizer.enqueue(async()=>{const r=await this.getPrefsFromServer(e.app),n=e.overwrite?{}:r.data,i=e.overwrite?{app:e.app,data:e.data}:{app:e.app,data:{...n,...e.data}},o=this.getRequest("/","POST",i),s=await fetchTimeout(o,this.requestTimeout);if(!s.ok)return ioError.raiseError(`[${t}] The POST rest for prefs for app ${e.app} returned invalid status: ${s.status}`);const a=await this.getPrefsFromServer(e.app);await this.comparePrefs(a,r),this.addSchedulerEntry(e.app),await this.cache.setPrefs(a)})}async clearPrefs(e,t){return this.sequelizer.enqueue(async()=>{await Promise.all(e.map(async e=>{await this.clearPrefsFromServer(e,t),await this.comparePrefs({app:e,data:{}}),await this.cache.clearPrefs(e)}))})}async clearAllPrefs(e){return this.sequelizer.enqueue(async()=>{const t=(await this.getAllPrefsFromServer(e)).filter(e=>Object.keys(e.data).length);for(const r of t)try{await this.clearPrefsFromServer(r.app,e),await this.comparePrefs({app:r.app,data:{}})}catch(e){this.logger?.warn(`Failed to clear prefs for app ${r.app}: ${e}`)}await this.cache.clearAllPrefs()})}async getAllPrefs(e){return this.sequelizer.enqueue(async()=>{const t=await this.getAllPrefsFromServer(e),r=await this.cache.getAllPrefs();for(const e of r){const r=t.find(t=>t.app===e.app);r&&(await this.comparePrefs(r,e),await this.cache.setPrefs(r))}return t})}onPrefsChanged(e){return this.registry.add("prefsChanged",e)}processNewSubscriber(e){this.logger?.info(`Processing new subscriber for appName: ${e}`),this.addSchedulerEntry(e)}async getAllPrefsFromServer(e){const t=this.getRequest("/all","GET"),r=await fetchTimeout(t,this.requestTimeout);if(!r.ok)return ioError.raiseError(`[${e}] The GET all rest for all prefs returned invalid status: ${r.status}`);const n=await r.json(),i=array$3(appPreferencesDecoder).run(n);return i.ok?i.result:ioError.raiseError(`[${e}] The GET all rest for all prefs returned invalid data: ${i.error}`)}async getPrefsFromServer(e,t){const r=new URLSearchParams({app:e}).toString(),n=this.getRequest(`/?${r}`,"GET"),i=await fetchTimeout(n,this.requestTimeout);if(!i.ok)return ioError.raiseError(`[${t}] The GET rest for prefs for app ${e} returned invalid status: ${i.status}`);const o=await i.json(),s=appPreferencesDecoder.run(o);return s.ok?(this.fetched[o.app]=!0,s.result):ioError.raiseError(`[${t}] The GET rest for prefs for app ${e} returned invalid data: ${s.error}`)}async clearPrefsFromServer(e,t){const r={app:e,data:{}},n=this.getRequest("/","POST",r),i=await fetchTimeout(n,this.requestTimeout);if(!i.ok)return ioError.raiseError(`[${t}] The POST rest for prefs for app ${e} returned invalid status: ${i.status}`)}async comparePrefs(e,t){const r=t??await this.cache.getPrefs(e.app);r&&JSON.stringify(r.data)===JSON.stringify(e.data)||this.registry.execute("prefsChanged",{app:e.app,prefs:e})}getRequest(e,t,r){const n=new Headers;for(const e in defaultRestHeaders)n.append(e,defaultRestHeaders[e]);for(const e in this.userCustomHeaders)n.append(e,this.userCustomHeaders[e]);const i={method:t,headers:n,mode:"cors",cache:"default",body:r?JSON.stringify(r):void 0},o=`${this.url}${e}`,s=this.getUserRequestInit({url:o,requestInit:i});return new Request(o,{...i,...s})}getBaseUrl(e){return e.endsWith("/")?e.slice(0,-1):e}addSchedulerEntry(e){if(!this.pollingInterval)return void this.logger?.info(`Polling interval is not set, skipping scheduler entry addition for app: ${e}`);const t=new URLSearchParams({app:e}).toString(),r=`prefs:get:${e}`,n={key:r,getRequest:()=>this.getRequest(`/?${t}`,"GET"),timeout:this.requestTimeout,refreshIntervalMS:this.pollingInterval,onData:this.processSchedulerGetPrefsUpdate.bind(this),onError:t=>this.logger?.error(`Error during get prefs for ${e} request:`,t)};this.scheduler.checkEntryExists(r)||(this.sessionController.savePrefsRestSchedulerCache({app:e}),this.scheduler.register(n))}processSchedulerGetPrefsUpdate(e){return this.sequelizer.enqueue(async()=>{this.fetched[e.app]=!0;const t=appPreferencesDecoder.run(e);if(!t.ok)return this.logger?.warn(`The GET rest for prefs as part of polling for app ${e.app} returned invalid data: ${t.error}`);await this.comparePrefs(t.result),await this.cache.setPrefs(t.result)})}}class LocalLayoutsStore{idbController;sessionStore;localStore;registry=CallbackRegistryFactory$2();mode="idb";get logger(){return logger.get("layouts.local.store")}constructor(e,t,r){this.idbController=e,this.sessionStore=t,this.localStore=r}async start(e){if(this.mode=e.layouts.mode,!e.layouts.local.length)return;const t=e.layouts.local.filter(e=>"Global"===e.type),r=e.layouts.local.filter(e=>"Workspace"===e.type);await Promise.all([this.localMergeImport(t,"Global"),this.localMergeImport(r,"Workspace")])}stop(){"idb"===this.mode&&(this.idbController.clearLayouts("Global").catch(e=>this.logger?.warn(extractErrorMsg$1(e))),this.idbController.clearLayouts("Workspace").catch(e=>this.logger?.warn(extractErrorMsg$1(e))))}async saveLayouts(e,t,r,n){const i="merge"===r?this.localMergeImport.bind(this):this.localReplaceImport.bind(this);this.logger?.trace(`[${n}] importing the layouts in local ${r} mode`),await Promise.all([i(t,"Global"),i(e,"Workspace")]),this.logger?.trace(`[${n}] mass import completed, responding to caller`)}async deleteLayout(e,t){await this.localDelete(e.name,e.type),await this.announceEvents({removed:[e]}),this.logger?.trace(`[${t}] layout with name "${e.name}" and type: "${e.type}" has been removed`)}async renameLayout(e,t,r){let n;try{n=await this.localRename(e,t)}catch(t){const n=extractErrorMsg$1(t);return this.logger?.trace(`[${r}] Layout named ${e.name} has not been renamed. Reason: ${n}.`),{status:n}}return await this.announceEvents({renamed:[{...n,prevName:e.name}]}),this.logger?.trace(`[${r}] Layout named ${e.name} has been renamed to ${t}.`),{status:"Success"}}async getDefaultLayout(e){const t=this.localStore.getDefaultGlobalLayoutName(),r=await this.getAll("Global");return this.logger?.trace(this.createGetDefaultGlobalLogMessage(e,t)),r.find(e=>e.name===t)}async setDefaultLayout(e,t){this.localStore.saveDefaultGlobalLayout(e),this.logger?.trace(`[${t}] request completed for global layout with name ${e}, responding to the caller`)}async clearDefaultLayout(e){this.localStore.clearDefaultGlobalLayout(),this.logger?.trace(`[${e}] request completed, responding to the caller`)}async getAllLayouts(e){return"idb"===this.mode?await this.idbController.getAllLayouts(e):this.sessionStore.getLayoutSnapshot(e).layouts}onLayoutsAdded(e){return this.registry.add("layouts-added",e)}onLayoutsChanged(e){return this.registry.add("layouts-changed",e)}onLayoutsRemoved(e){return this.registry.add("layouts-removed",e)}onLayoutsRenamed(e){return this.registry.add("layouts-renamed",e)}async localMergeImport(e,t){const r=await this.getAll(t),n=[],i=[];for(const t of e){const e=r.findIndex(e=>e.name===t.name);e>-1&&!objEqual(t,r[e])?(this.logger?.trace(`change detected at layout ${t.name}`),i.push(t),r[e]=t):e<0&&(this.logger?.trace(`new layout: ${t.name} detected, adding and announcing`),n.push(t),r.push(t))}await this.localCleanSave(r,t),await this.announceEvents({added:n,changed:i})}async localReplaceImport(e,t){const r=await this.getAll(t),n=[],i=[],o=[];for(const t of e){const e=r.findIndex(e=>e.name===t.name);e<0?(this.logger?.trace(`new layout: ${t.name} detected, adding and announcing`),n.push(t)):(objEqual(t,r[e])||(this.logger?.trace(`change detected at layout ${t.name}`),i.push(t)),r.splice(e,1))}r.forEach(e=>{this.logger?.trace(`layout ${e.name} missing, removing and announcing`),o.push(e)}),await this.localCleanSave(e,t),await this.announceEvents({added:n,changed:i,removed:o})}async localCleanSave(e,t){if("session"!==this.mode){await this.idbController.clearLayouts(t);for(const t of e)await this.idbController.storeLayout(t)}else this.sessionStore.saveLayoutSnapshot({layouts:e},t)}async localDelete(e,t){if("idb"===this.mode)return void await this.idbController.deleteLayout(e,t);const r=this.sessionStore.getLayoutSnapshot(t).layouts,n=r.findIndex(t=>t.name===e);n>-1&&r.splice(n,1),this.sessionStore.saveLayoutSnapshot({layouts:r},t)}async localRename(e,t){const r={...e,name:t};if("idb"===this.mode)return await this.idbController.renameLayout(r,e.name),r;const n=this.sessionStore.getLayoutSnapshot(e.type).layouts,i=n.findIndex(({name:t})=>t===e.name),o=-1===i?n.length:i;return n.splice(o,1,r),this.sessionStore.saveLayoutSnapshot({layouts:n},e.type),r}async getAll(e){const t="Workspace"===e?"Workspace":"Global";return"idb"===this.mode?await this.idbController.getAllLayouts(t):this.sessionStore.getLayoutSnapshot(t).layouts}updateDefaultGlobalLayoutIfNeeded(e){const t=this.localStore.getDefaultGlobalLayoutName();if(!t)return;if("removed"===e.operation&&e.layouts.some(e=>"Global"===e.type&&e.name===t))return this.localStore.clearDefaultGlobalLayout();const r="renamed"===e.operation?e.layouts.find(e=>"Global"===e.type&&e.prevName===t):void 0;return r?this.localStore.saveDefaultGlobalLayout(r.name):void 0}async announceEvents(e){const t=[];e.added?.length&&t.push(this.throttleEvents(e.added,"layouts-added")),e.changed?.length&&t.push(this.throttleEvents(e.changed,"layouts-changed")),e.removed?.length&&(this.updateDefaultGlobalLayoutIfNeeded({operation:"removed",layouts:e.removed}),t.push(this.throttleEvents(e.removed,"layouts-removed"))),e.renamed?.length&&(this.updateDefaultGlobalLayoutIfNeeded({operation:"renamed",layouts:e.renamed}),t.push(this.throttleEvents(e.renamed,"layouts-renamed"))),await Promise.all(t),await this.waitEventFlush()}async throttleEvents(e,t){let r=0;for(const n of e)++r,r%10==0&&await this.waitEventFlush(),this.registry.execute(t,[n])}createGetDefaultGlobalLogMessage(e,t){return t?`[${e}] request completed, responding to the caller with layout with name ${t}`:`[${e}] request completed, no default global layout found, responding to the caller`}waitEventFlush(){return new Promise(e=>setTimeout(e,10))}}class ManagerLayoutsStore{manager;get logger(){return logger.get("layouts.manager.store")}constructor(e){this.manager=e}async start(){}stop(){}async saveLayouts(e,t,r,n){this.logger?.trace(`[${n}] importing the layouts to manager`),await this.manager.saveLayouts([...e,...t],r,n),this.logger?.trace(`[${n}] mass import to manager completed, responding to caller`)}async deleteLayout(e,t){await this.manager.deleteLayout(e.name,e.type,t),this.logger?.trace(`[${t}] layout with name "${e.name}" and type: "${e.type}" has been removed from manager`)}async renameLayout(e,t,r){return await this.manager.renameLayout(e.name,t,e.type,r),this.logger?.trace(`[${r}] Layout named ${e.name} has been renamed to ${t} in manager.`),{status:"Success"}}async getDefaultLayout(e){this.logger?.trace(`[${e}] getting default global layout from manager`);const t=await this.manager.getDefaultLayout(e);return this.logger?.trace(this.createGetDefaultGlobalLogMessage(e,t?.name)),t}async setDefaultLayout(e,t){this.logger?.trace(`[${t}] setting default global layout in manager`),await this.manager.setDefaultLayout(e,t),this.logger?.trace(`[${t}] request completed for global layout with name ${e}, responding to the caller`)}async clearDefaultLayout(e){this.logger?.trace(`[${e}] clearing default global layout in manager`),await this.manager.clearDefaultLayout(e),this.logger?.trace(`[${e}] request completed, responding to the caller`)}async getAllLayouts(e,t){return await this.manager.getAllLayouts(e,t)}onLayoutsAdded(e){return this.manager.onLayoutsAdded(e)}onLayoutsChanged(e){return this.manager.onLayoutsChanged(e)}onLayoutsRemoved(e){return this.manager.onLayoutsRemoved(e)}onLayoutsRenamed(e){return this.manager.onLayoutsRenamed(e)}createGetDefaultGlobalLogMessage(e,t){return t?`[${e}] request completed, responding to the caller with layout with name ${t}`:`[${e}] request completed, no default global layout found, responding to the caller`}}class RestLayoutsStore{sequelizer;scheduler;cache;registry=CallbackRegistryFactory$2();cacheConfig;config;get logger(){return logger.get("layouts.rest.store")}constructor(e,t,r){this.sequelizer=e,this.scheduler=t,this.cache=r}async start(e){const t=e.layouts?.rest;if(!t)return ioError.raiseError("Cannot setup layouts rest store, because of missing config");this.config=this.prepareConfig(t),this.logger?.info(`Starting layouts rest store with config: ${JSON.stringify({...this.config,customHeaders:"omitted"})}`),this.cacheConfig=t.cache??{},await this.cache.start(t),this.logger?.trace("Finished starting layouts rest store"),await this.dataWarmUp(),this.logger?.trace("Finished data warm up"),this.configureScheduler(),this.logger?.info("Layouts rest store started")}stop(){this.cache.stop()}async getAllLayouts(e,t){return this.sequelizer.enqueue(()=>this.getAllLayoutsNoSeq(e,t))}async saveLayouts(e,t,r,n){return this.sequelizer.enqueue(async()=>{const i=[...e,...t];"replace"===r&&await this.deleteAllLayoutsFromServer(n);const o=1===i.length;for(const e of i)try{await this.saveLayoutToServer(e,n)}catch(t){if(!o){this.logger?.warn(`Failed to save layout ${e.name} type:${e.type} with error: ${t}, continuing with the rest`);continue}return ioError.raiseError(`Failed to save layout ${e.name} type:${e.type} with error: ${t}`)}const s=await this.getAllLayoutsFromServer(n);await this.processNewLayoutsSnapshot(s)})}async deleteLayout(e,t){return this.sequelizer.enqueue(async()=>{this.logger?.trace(`[${t}] Deleting layout ${e.name} type:${e.type}`);const r=this.getRequest("/layouts","DELETE",{name:e.name,type:e.type}),n=await fetchTimeout(r,this.config.requestTimeout);if(!n.ok)return ioError.raiseError(`Failed to remove layout ${e.name} and type: ${e.type}: ${n.statusText}`);this.logger?.trace(`[${t}] Removed layout ${e.name} type:${e.type}`),await this.cache.deleteLayout(e),await this.announceEvents({removed:[e]})})}async renameLayout(e,t,r){return this.sequelizer.enqueue(async()=>{this.logger?.trace(`[${r}] Renaming layout ${e.name} type:${e.type} to ${t}`);const n=this.getRequest("/layouts","PUT",{layout:e,newName:t}),i=await fetchTimeout(n,this.config.requestTimeout);return i.ok?(await this.cache.updateLayout(e,t),this.registry.execute("layouts-renamed",[{...e,name:t,prevName:e.name}]),{status:"Success"}):{status:`Failed to rename layout ${e.name} type:${e.type}: ${i.statusText}`}})}async getDefaultLayout(e){return this.sequelizer.enqueue(async()=>{this.logger?.trace(`[${e}] Getting default layout`);const t=this.getRequest("/layouts/default","GET"),r=await fetchTimeout(t,this.config.requestTimeout);if(!r.ok)return ioError.raiseError(`[${e}] The rest for get default layout returned invalid status: ${r.status}`);let n;try{n=await r.json()}catch{return void this.logger?.trace(`[${e}] No default layout found`)}if(!n?.name)return void this.logger?.trace(`[${e}] No default layout found`);const i=n.name;return(await this.getAllLayoutsNoSeq("Global",e)).find(e=>e.name===i)})}async setDefaultLayout(e,t){this.sequelizer.enqueue(async()=>{this.logger?.trace(`[${t}] Setting default layout to ${e}`);const r=this.getRequest("/layouts/default","POST",{name:e}),n=await fetchTimeout(r,this.config.requestTimeout);if(!n.ok)return ioError.raiseError(`[${t}] The rest for set default layout returned invalid status: ${n.status}`);this.logger?.trace(`[${t}] Set default layout to ${e}`)})}async clearDefaultLayout(e){this.sequelizer.enqueue(async()=>{this.logger?.trace(`[${e}] Clearing default layout`);const t=this.getRequest("/layouts/default","POST",{}),r=await fetchTimeout(t,this.config.requestTimeout);if(!r.ok)return ioError.raiseError(`[${e}] The rest for clear default layout returned invalid status: ${r.status}`);this.logger?.trace(`[${e}] Default layout cleared`)})}onLayoutsAdded(e){return this.registry.add("layouts-added",e)}onLayoutsChanged(e){return this.registry.add("layouts-changed",e)}onLayoutsRemoved(e){return this.registry.add("layouts-removed",e)}onLayoutsRenamed(e){return this.registry.add("layouts-renamed",e)}async getAllLayoutsNoSeq(e,t){const r=this.cacheConfig.enabled?await this.cache.getAllLayouts("all"):void 0;if(r?.length)return r.filter(t=>t.type===e);const n=await this.getAllLayoutsFromServer(t);return(await this.processNewLayoutsSnapshot(n)).filter(t=>t.type===e)}async getAllLayoutsFromServer(e){this.logger?.trace(`[${e}] Fetching all layouts from server`);const t=this.getRequest("/layouts","GET"),r=await fetchTimeout(t,this.config.requestTimeout);if(!r.ok)return ioError.raiseError(`[${e}] The rest for get all layouts returned invalid status: ${r.status}`);const n=await r.json();if(!n?.layouts)return ioError.raiseError(`[${e}] The rest for get all layouts returned invalid response`);return this.sanitizeLayouts(n.layouts)}async deleteAllLayoutsFromServer(e){const t=(await this.getAllLayoutsFromServer(e)).map(e=>this.getLayoutId(e.name,e.type)),r=this.getRequest("/layouts","DELETE",{ids:t}),n=await fetchTimeout(r,this.config.requestTimeout);if(!n.ok)return ioError.raiseError(`[${e}] Failed to remove all layouts: ${n.statusText}`);this.logger?.trace(`[${e}] Removed all layouts`)}async saveLayoutToServer(e,t){const r=this.getRequest("/layouts","POST",{layout:e}),n=await fetchTimeout(r,this.config.requestTimeout),i=`[${t}] Failed to save layout ${e.name} type:${e.type}: ${n.statusText}`;if(!n.ok)throw new Error(i);this.logger?.trace(`[${t}] Saved layout ${e.name} type:${e.type}`)}getBaseUrl(e){return e.endsWith("/")?e.slice(0,-1):e}getRequest(e,t,r){const n=new Headers;for(const e in defaultRestHeaders$1)n.append(e,defaultRestHeaders$1[e]);for(const e in this.config.customHeaders)n.append(e,this.config.customHeaders[e]);const i={method:t,headers:n,mode:"cors",cache:"default",body:r?JSON.stringify(r):void 0},o=`${this.config.url}${e}`,s=this.config.getRequestInit?.({url:o,requestInit:i});return new Request(o,{...i,...s})}getLayoutId(e,t){return`${e.toLowerCase()} (${t})`}sanitizeLayouts(e){return e.reduce((e,t)=>{const r=glueLayoutDecoder.run(t);return r.ok&&e.push(t),r.ok||this.logger?.warn(`A layout with name: ${t.name} was not imported, because of error: ${JSON.stringify(r.error)}`),e},[])}async executeLayoutsChangeDetection(e,t){if(!e.length)return;const r=[],n=[],i=[],o=await this.cache.getAllLayouts(t);for(const t of e){const e=o.findIndex(e=>e.name===t.name);e<0?(this.logger?.trace(`new layout: ${t.name} detected, adding and announcing`),r.push(t)):(objEqual(t,o[e])||(this.logger?.trace(`change detected at layout ${t.name}`),n.push(t)),o.splice(e,1))}o.forEach(e=>{this.logger?.trace(`layout ${e.name} missing, removing and announcing`),i.push(e)}),await this.announceEvents({added:r,changed:n,removed:i})}async announceEvents(e){const t=[];e.added?.length&&t.push(this.throttleEvents(e.added,"layouts-added")),e.changed?.length&&t.push(this.throttleEvents(e.changed,"layouts-changed")),e.removed?.length&&t.push(this.throttleEvents(e.removed,"layouts-removed")),e.renamed?.length&&t.push(this.throttleEvents(e.renamed,"layouts-renamed")),await Promise.all(t),await this.waitEventFlush()}async throttleEvents(e,t){let r=0;for(const n of e)++r,r%10==0&&await this.waitEventFlush(),this.registry.execute(t,[n])}waitEventFlush(){return new Promise(e=>setTimeout(e,10))}processSchedulerGetAllLayoutsUpdate(e){return this.sequelizer.enqueue(async()=>{this.logger?.trace("Processing scheduler get all layouts update"),await this.processNewLayoutsSnapshot(e.layouts),this.logger?.trace("Finished processing scheduler get all layouts update")})}async processNewLayoutsSnapshot(e){const t=this.sanitizeLayouts(e),r=t.filter(e=>"Workspace"===e.type),n=t.filter(e=>"Global"===e.type);return await this.executeLayoutsChangeDetection(r,"Workspace"),await this.executeLayoutsChangeDetection(n,"Global"),await this.cache.saveLayouts(t,"replace"),t}configureScheduler(){if(!this.config.pollingInterval)return void this.logger?.info("Polling interval is not set, skipping scheduler setup");const e="layouts:get:all";if(this.scheduler.checkEntryExists(e))return;const t={key:e,getRequest:()=>this.getRequest("/layouts","GET"),timeout:this.config.requestTimeout,refreshIntervalMS:this.config.pollingInterval,onData:this.processSchedulerGetAllLayoutsUpdate.bind(this),onError:e=>this.logger?.error("Error during get all layouts from scheduler",e)};this.scheduler.register(t)}async dataWarmUp(){const e=this.getAllLayoutsFromServer("start-up");if(this.config.waitInitialResponse)try{const t=await e;await this.cache.saveLayouts(t,"replace")}catch(e){return this.handleDataWarmUpFail(e)}else e.then(e=>this.cache.saveLayouts(e,"replace")).catch(e=>{const t=extractErrorMsg$1(e);this.logger?.warn(`Layouts store initial data warm up failed: ${t}`)})}prepareConfig(e){const t={...e,url:this.getBaseUrl(e.url),requestTimeout:e.requestTimeout??defaultRestRequestTimeoutMS$1,customHeaders:e.customHeaders??{},getRequestInit:e.getRequestInit??(()=>({})),waitInitialResponse:e.waitInitialResponse??!0};return t.pollingInterval&&t.pollingInterval<5e3?ioError.raiseError("Polling interval must be at least 5000ms"):t.cache?.enabled&&!t.pollingInterval?ioError.raiseError("Polling interval is required when cache is enabled"):t}async handleDataWarmUpFail(e){const t=await this.cache.getAllLayouts("all"),r=extractErrorMsg$1(e);if(!this.cacheConfig.enabled||!t.length)return ioError.raiseError(`Layouts store initial data warm up failed: ${r}`);this.logger?.warn(`Layouts store initial data warm up failed, but cache is not empty, continuing with cached data. Response error: ${r}`)}}class RestScheduler{localStorageController;entries=new Map;currentAbortControllers=new Map;_handleConnectionChange;isAppOnline=navigator.onLine;isActive=!1;schedulerLockName;constructor(e){this.localStorageController=e}start(e){if(this.isActive)return;this.entries.size?(this.schedulerLockName=`io-connect-rest-scheduler-lock-${e?.id||"public"}`,this.isActive=!0,this.setupOnlineTracker(),this.tick()):this.logger?.info("No entries registered in the RestScheduler, skipping start.")}stop(){this.isActive=!1,this.currentAbortControllers.forEach(e=>e.abort()),this.currentAbortControllers.clear(),this.entries.clear(),this.localStorageController.clearRestSchedulerEntries(),window.removeEventListener("offline",this._handleConnectionChange),window.removeEventListener("online",this._handleConnectionChange)}checkEntryExists(e){return this.entries.has(e)}register(e){if(this.checkEntryExists(e.key))return ioError.raiseError(`Request with key "${e.key}" is already registered.`);this.entries.set(e.key,e);this.localStorageController.getRestSchedulerEntry(e.key)||this.setInitialLocalStorageEntry(e)}async tick(){if(this.isActive){if(await this.waitInterval(),!this.isAppOnline)return this.isActive=!1,void this.logger?.warn("App is offline, ticking stopped.");await navigator.locks.request(this.schedulerLockName,{ifAvailable:!0},async e=>{if(e)try{await this.executeTick()}catch(e){this.logger?.error("Error during rest scheduler tick:",e)}else this.logger?.trace("The scheduler lock is already held by another process, skipping this tick.")}),this.tick()}}async executeTick(){const e=Date.now(),t=this.localStorageController.getAllRestSchedulerEntries(),r=Array.from(this.entries).reduce((r,[n,i])=>{const o=t[n];return o||(this.setInitialLocalStorageEntry(i),r.push(n)),o&&e>=o.nextRefreshAt&&r.push(n),r},[]);if(!r.length)return;const n=this.splitKeysBasedOnConcurrency(r);for(const e of n)try{const t=Promise.all(e.map(async e=>{await this.refreshKey(e)}));await t}catch(e){const t="string"==typeof e?e:JSON.stringify(e.message);this.logger?.warn(t)}}async refreshKey(e){const t=this.entries.get(e);if(!t)return ioError.raiseError(`No request registered with key "${e}".`);if(t.continuationCheck&&!t.continuationCheck())return this.logger?.trace(`Cancelling request for key "${e}" as continuation check failed.`),this.entries.delete(e),void this.localStorageController.deleteRestSchedulerEntry(e);const r=t.getRequest(),n=new AbortController;let i,o;this.currentAbortControllers.set(e,n);try{i=await fetchTimeout(r,t.timeout,n),o=Date.now()}catch(t){return this.setEntryFailure(e,Date.now())}if(!i.ok)return this.setEntryFailure(e,o,i.status);let s=null;try{s=await i.json()}catch(e){}finally{this.setEntrySuccess(e,s,o)}}setupOnlineTracker(){this._handleConnectionChange=this.handleConnectionChange.bind(this),window.addEventListener("offline",this._handleConnectionChange),window.addEventListener("online",this._handleConnectionChange)}setEntryFailure(e,t,r){this.currentAbortControllers.delete(e);const n=this.localStorageController.getRestSchedulerEntry(e),i=this.entries.get(e);if(!i)return ioError.raiseError(`No entry found for key "${e}" in local storage.`);const o=Math.ceil(250*Math.random())+t+Math.min(i.refreshIntervalMS*Math.pow(2,n?.errorCount??0),36e5),s=n?{...n,nextRefreshAt:o,errorCount:n.errorCount+1}:{key:i.key,nextRefreshAt:o,lastRefreshedAt:0,errorCount:1};this.localStorageController.saveRestSchedulerEntry(s);const a=`Request failed with status ${r||"timeout"} for key "${e}" and url "${i.getRequest().url}".`;return i.onError?.(a),ioError.raiseError(a)}setEntrySuccess(e,t,r){this.currentAbortControllers.delete(e);const n=this.localStorageController.getRestSchedulerEntry(e),i=this.entries.get(e);if(!i)return ioError.raiseError(`No entry found for key "${e}" in local storage.`);const o=r+i.refreshIntervalMS+Math.ceil(250*Math.random()),s=n?{...n,errorCount:0,lastRefreshedAt:r,nextRefreshAt:o}:{key:i.key,nextRefreshAt:o,lastRefreshedAt:r,errorCount:0};this.localStorageController.saveRestSchedulerEntry(s);try{i.onData(t)}catch(e){this.logger?.warn(`[${i.key}] Error occurred while processing data: ${e}`)}}setInitialLocalStorageEntry(e){const t={key:e.key,nextRefreshAt:Date.now()+e.refreshIntervalMS+Math.ceil(250*Math.random()),lastRefreshedAt:0,errorCount:0};this.localStorageController.saveRestSchedulerEntry(t)}splitKeysBasedOnConcurrency(e){const t=[],r=e.length;for(let n=0;n<r;n+=maxConcurrentRequestsForScheduler)t.push(e.slice(n,n+maxConcurrentRequestsForScheduler));return t}handleConnectionChange(){const e=navigator.onLine;e&&!this.isActive&&(this.isActive=!0,this.tick()),this.isAppOnline=e}waitInterval(e){return new Promise(t=>setTimeout(t,e??globalTickIntervalMSForScheduler))}get logger(){return logger.get("system.rest.scheduler")}}class PrefsRestCache{idbCacheController;allKnownPrefs=[];cacheConfig={};constructor(e){this.idbCacheController=e}async start(e){this.allKnownPrefs=[],this.cacheConfig=e.cache??{}}async stop(){this.allKnownPrefs=[]}async getPrefs(e){return this.cacheConfig.enabled?(await this.idbCacheController.getPrefs(e))?.prefs:this.allKnownPrefs.find(t=>t.app===e)}async getAllPrefs(){if(!this.cacheConfig.enabled)return this.allKnownPrefs;return(await this.idbCacheController.getAllPrefs()).map(e=>e.prefs)}async setPrefs(e){this.allKnownPrefs=this.allKnownPrefs.filter(t=>t.app!==e.app),this.allKnownPrefs.push(e),this.cacheConfig.enabled&&await this.idbCacheController.setPrefs(e,Date.now())}async clearPrefs(e){this.allKnownPrefs=this.allKnownPrefs.filter(t=>t.app!==e),this.cacheConfig.enabled&&await this.idbCacheController.deleteManyPrefs([e])}async clearAllPrefs(){this.allKnownPrefs=[],this.cacheConfig.enabled&&await this.idbCacheController.clearPrefs()}}class IdbCacheController{_database;dbName;dbVersion=1;globalLayoutsObjectStoreName="globalLayouts";prefsObjectStoreName="prefs";workspaceLayoutsObjectStoreName="workspaceLayouts";appsDefObjectStoreName="applicationDefinitions";constructor(){this.dbName=defaultCacheDBName,"indexedDB"in window||ioError.raiseError("Cannot initialize the local storage, because IndexedDB is not supported")}get database(){return this._database?this._database:ioError.raiseError("There is no open database")}async start(e){this.dbName=`${defaultCacheDBName}-${e?.id??"public"}`;const t=await openDB(this.dbName,this.dbVersion,{upgrade:this.setUpDB.bind(this)});this._database=t}stop(){this._database&&(this.database.close(),delete this._database,this.dbName=defaultCacheDBName)}async clear(){this._database&&(await this.database.clear(this.globalLayoutsObjectStoreName),await this.database.clear(this.workspaceLayoutsObjectStoreName),await this.database.clear(this.prefsObjectStoreName),await this.database.clear(this.appsDefObjectStoreName))}async deleteOtherDBs(){const e=(await indexedDB.databases()).filter(e=>e.name&&e.name!==this.dbName&&e.name.startsWith(defaultCacheDBName)).map(e=>new Promise((t,r)=>{if(!e.name)return t();const n=indexedDB.deleteDatabase(e.name);n.onerror=t=>{console.error("Error deleting database:",t),r(new Error(`Error deleting database: ${e.name}`))},n.onsuccess=()=>{t()}}));await Promise.all(e)}async getAllLayouts(e){if("all"===e){return[...(await this.database.getAll(this.globalLayoutsObjectStoreName)).map(e=>e.layout),...(await this.database.getAll(this.workspaceLayoutsObjectStoreName)).map(e=>e.layout)]}return(await this.database.getAll(this.getLayoutsObjectStoreName(e))).map(e=>e.layout)}deleteLayout(e,t){const r=this.getLayoutsObjectStoreName(t);return this.database.delete(r,e)}storeLayout(e,t,r){const n=this.getLayoutsObjectStoreName(e.type);return this.database.put(n,{layout:{...e,name:r??e.name},lastUpdated:t},e.name)}clearLayouts(e){const t=this.getLayoutsObjectStoreName(e);return this.database.clear(t)}async getPrefs(e){return this.database.get(this.prefsObjectStoreName,e)}getAllPrefs(){return this.database.getAll(this.prefsObjectStoreName)}async setPrefs(e,t){await this.database.put(this.prefsObjectStoreName,{prefs:e,lastUpdated:t},e.app)}async deleteManyPrefs(e){for(const t of e)await this.database.delete(this.prefsObjectStoreName,t)}async clearPrefs(){await this.database.clear(this.prefsObjectStoreName)}async getAllApps(){return(await this.database.getAll(this.appsDefObjectStoreName)).map(e=>e.definition)}async setApps(e,t){const r=this.database.transaction(this.appsDefObjectStoreName,"readwrite");await Promise.all([r.store.clear(),...e.map(e=>r.store.put({definition:e,lastUpdated:t},e.name)),r.done])}setUpDB(e){e.objectStoreNames.contains(this.workspaceLayoutsObjectStoreName)||e.createObjectStore(this.workspaceLayoutsObjectStoreName),e.objectStoreNames.contains(this.globalLayoutsObjectStoreName)||e.createObjectStore(this.globalLayoutsObjectStoreName),e.objectStoreNames.contains(this.prefsObjectStoreName)||e.createObjectStore(this.prefsObjectStoreName),e.objectStoreNames.contains(this.appsDefObjectStoreName)||e.createObjectStore(this.appsDefObjectStoreName)}getLayoutsObjectStoreName(e){return"Global"!==e&&"Workspace"!==e?ioError.raiseError(`Invalid layout type: ${e}`):"Global"===e?this.globalLayoutsObjectStoreName:this.workspaceLayoutsObjectStoreName}}class LayoutsRestCache{idbCacheController;allKnownLayouts=[];cacheConfig={};constructor(e){this.idbCacheController=e}async start(e){this.allKnownLayouts=[],this.cacheConfig=e.cache??{}}async stop(){this.allKnownLayouts=[]}async getAllLayouts(e){return this.cacheConfig.enabled?await this.idbCacheController.getAllLayouts(e):this.allKnownLayouts.filter(t=>"all"===e||t.type===e)}saveLayouts(e,t){return"replace"===t?this.replaceLayouts(e):this.mergeLayouts(e)}async deleteLayout(e){this.allKnownLayouts=this.allKnownLayouts.filter(t=>t.name!==e.name&&t.type!==e.type),this.cacheConfig.enabled&&await this.idbCacheController.deleteLayout(e.name,e.type)}async updateLayout(e,t){this.allKnownLayouts=this.allKnownLayouts.filter(t=>t.name!==e.name&&t.type!==e.type),this.allKnownLayouts.push({...e,name:t??e.name}),this.cacheConfig.enabled&&await this.idbCacheController.storeLayout(e,Date.now(),t)}async replaceLayouts(e){if(this.allKnownLayouts=e,this.cacheConfig.enabled){await this.idbCacheController.clearLayouts("Global"),await this.idbCacheController.clearLayouts("Workspace");for(const t of e)await this.idbCacheController.storeLayout(t,Date.now())}}async mergeLayouts(e){for(const t of e)await this.updateLayout(t)}}class AppsRestCache{idbCacheController;sessionController;cacheConfig={};constructor(e,t){this.idbCacheController=e,this.sessionController=t}async start(e){this.cacheConfig=e?.cache??{}}async getAllRemoteApps(){return this.cacheConfig.enabled?this.idbCacheController.getAllApps():this.sessionController.getAllApps("remote")}async getAllMemoryApps(){return this.sessionController.getAllApps("inmemory")}async saveMemoryApps(e){this.sessionController.overwriteApps(e,"inmemory")}async saveRemoteApps(e){return this.cacheConfig.enabled?this.idbCacheController.setApps(e,Date.now()):this.sessionController.overwriteApps(e,"remote")}async removeMemoryApp(e){return this.sessionController.removeApp(e,"inmemory")}}class RemotePlatformConfigController{remoteManagerConfig;remoteConfigsCacheController;endpointPath="/systemConfig/get";browserPlatformConfigKey="browser-platform.json";constructor(e,t){this.remoteManagerConfig=e,this.remoteConfigsCacheController=t}async getPlatformConfig(){let e;this.isCacheEnabled&&await this.remoteConfigsCacheController.start();try{e=await this.fetchRemoteConfig()}catch(e){const t=`Received error while fetching platform configuration from io.Manager: ${extractErrorMsg$1(e)}`;return this.handleConfigError(t)}if(!e.ok){const t=`Failed to fetch the platform configuration version ${this.platformConfigVersion} from io.Manager to url ${this.endpointUrl}. Status: ${e.status} ${e.statusText}`;return this.handleConfigError(t)}const t=await e.json(),r=t?.[this.browserPlatformConfigKey]?.contents;if(!r){const e=`The fetched platform configuration from io.Manager did not provide valid io.Connect Browser Platform configuration for version ${this.platformConfigVersion}`;return this.handleConfigError(e)}this.isCacheEnabled&&await this.saveConfigToCache(r);return await this.applyConfigModifications(r)}get isCacheEnabled(){return this.remoteManagerConfig.enableCache??!0}get platformConfigVersion(){return this.remoteManagerConfig.platformVersion||version$1}get fetchTimeoutMs(){return this.remoteManagerConfig.fetchTimeoutMs||3e4}get endpointUrl(){let e=this.remoteManagerConfig.managerURL;for(;e.endsWith("/");)e=e.slice(0,-1);return`${e}${this.endpointPath}`}async fetchRemoteConfig(){const e=this.getRequest();return await fetchTimeout(e,this.fetchTimeoutMs)}async fallbackToCachedConfig(){const e=await this.remoteConfigsCacheController.getPlatformConfig(this.platformConfigVersion);if(!e)return ioError.raiseError(`No cached configuration found for Platform version ${this.platformConfigVersion}. Cannot proceed without a valid io.Connect Browser configuration.`);return await this.applyConfigModifications(e)}handleConfigError(e){return this.isCacheEnabled?(console.warn(`${e}. Attempting to retrieve cached configuration.`),this.fallbackToCachedConfig()):ioError.raiseError(`${e} and caching is disabled. Cannot proceed without valid configuration.`)}async applyConfigModifications(e){return this.remoteManagerConfig.modifyConfig?this.remoteManagerConfig.modifyConfig(e):e}saveConfigToCache(e){return this.remoteConfigsCacheController.savePlatformConfig(this.platformConfigVersion,e)}getRequest(){const e={identifier:{version:this.platformConfigVersion,group:"*",user:"*"}};return new Request(this.endpointUrl,{method:"POST",headers:{"Content-Type":"application/json",Accept:"*/*"},mode:"cors",cache:"default",body:JSON.stringify(e)})}}class RemoteConfigsCacheController{dbName="remote-configs-cache";dbVersion=1;_database;platformConfigObjectStoreName="platformConfig";constructor(){"indexedDB"in window||ioError.raiseError("Cannot initialize the remote configurations cache storage, because IndexedDB is not supported")}get database(){return this._database?this._database:ioError.raiseError("There is no open remote configurations cache database")}async start(){if(this._database)return;const e=await openDB(this.dbName,this.dbVersion,{upgrade:this.setUpDB.bind(this)});this._database=e}stop(){this.database.close(),delete this._database}async clear(){this._database&&await this.database.clear(this.platformConfigObjectStoreName)}async savePlatformConfig(e,t){await this.database.put(this.platformConfigObjectStoreName,t,e)}async getPlatformConfig(e){return this.database.get(this.platformConfigObjectStoreName,e)}async setUpDB(e){e.objectStoreNames.contains(this.platformConfigObjectStoreName)||e.createObjectStore(this.platformConfigObjectStoreName)}}class IoC{_config;_remoteConfigFromManager;_gatewayInstance;_platformInstance;_mainController;_glueController;_portsBridge;_windowsController;_applicationsController;_appDirectory;_remoteWatcher;_layoutsController;_workspacesController;_hibernationWatcher;_intentsController;_legacyResolverController;_channelsController;_notificationsController;_extensionController;_sessionController;_localStorageController;_stateChecker;_framesController;_systemController;_idbController;_serviceWorkerController;_preferredConnectionController;_transactionsController;_interceptionController;_pluginsController;_domainsController;_licenseController;_layoutsBuilder;_layoutsRestorer;_layoutsValidator;_layoutsResetter;_searchController;_appsSearchRepo;_layoutsSearchRepo;_workspacesSearchRepo;_themesController;_managerController;_managerIdentity;_prefsController;_otelController;_otelTelemetry;_uiController;_localPrefsStore;_managerPrefsStore;_restPrefsStore;_localLayoutsStore;_managerLayoutsStore;_restLayoutsStore;_restScheduler;_prefsRestCache;_layoutsRestCache;_appsRestCache;_idbCacheController;_remotePlatformConfigController;_remoteConfigsCacheController;get config(){return this._config}set config(e){this._config=e}get remoteConfigFromManager(){return this._remoteConfigFromManager}set remoteConfigFromManager(e){this._remoteConfigFromManager=e}get gateway(){return this._gatewayInstance||(this._gatewayInstance=new Gateway),this._gatewayInstance}get platform(){return this._platformInstance||(this._platformInstance=new Platform(this.controller,this.sessionController,this.localStorageController,this.config)),this._platformInstance}get domainsController(){return this._domainsController||(this._domainsController=new DomainsController(this.systemController,this.windowsController,this.applicationsController,this.layoutsController,this.workspacesController,this.intentsController,this.channelsController,this.notificationsController,this.extensionController,this.searchController,this.themesController,this.managerController,this.prefsController,this.otelController,this.uiController)),this._domainsController}get controller(){return this._mainController||(this._mainController=new PlatformController(this.domainsController,this.glueController,this.portsBridge,this.stateController,this.serviceWorkerController,this.preferredConnectionController,this.interceptionController,this.pluginsController,this.sessionController,this.licenseController,this.localStorageController,this.idbController,this.idbCacheController,this.restScheduler)),this._mainController}get glueController(){return this._glueController||(this._glueController=new GlueController(this.portsBridge,this.sessionController)),this._glueController}get restScheduler(){return this._restScheduler||(this._restScheduler=new RestScheduler(this.localStorageController)),this._restScheduler}get idbCacheController(){return this._idbCacheController||(this._idbCacheController=new IdbCacheController),this._idbCacheController}get prefsRestCache(){return this._prefsRestCache||(this._prefsRestCache=new PrefsRestCache(this.idbCacheController)),this._prefsRestCache}get layoutsRestCache(){return this._layoutsRestCache||(this._layoutsRestCache=new LayoutsRestCache(this.idbCacheController)),this._layoutsRestCache}get appsRestCache(){return this._appsRestCache||(this._appsRestCache=new AppsRestCache(this.idbCacheController,this.sessionController)),this._appsRestCache}get systemController(){return this._systemController||(this._systemController=new SystemController(this.sessionController,this.workspacesController,this.glueController,this.pluginsController)),this._systemController}get searchController(){return this._searchController||(this._searchController=new SearchController(this.glueController,this.appsSearchRepo,this.layoutsSearchRepo,this.workspacesSearchRepo)),this._searchController}get uiController(){return this._uiController||(this._uiController=new UIController(this.sessionController,this.glueController)),this._uiController}get themesController(){return this._themesController||(this._themesController=new ThemesController(this.glueController,this.localStorageController,this.prefsController)),this._themesController}get sessionController(){return this._sessionController||(this._sessionController=new SessionStorageController),this._sessionController}get localStorageController(){return this._localStorageController||(this._localStorageController=new LocalStoreController),this._localStorageController}get stateController(){return this._stateChecker||(this._stateChecker=new WindowsStateController(this.sessionController)),this._stateChecker}get windowsController(){return this._windowsController||(this._windowsController=new WindowsController(this.glueController,this.sessionController,this.stateController,this)),this._windowsController}get applicationsController(){return this._applicationsController||(this._applicationsController=new ApplicationsController(this.glueController,this.sessionController,this.stateController,this.appDirectory,this.managerController,this)),this._applicationsController}get appDirectory(){return this._appDirectory||(this._appDirectory=new AppDirectory(this.remoteWatcher,this.managerController,this.appsRestCache)),this._appDirectory}get remoteWatcher(){return this._remoteWatcher||(this._remoteWatcher=new RemoteWatcher(this.restScheduler)),this._remoteWatcher}get licenseController(){return this._licenseController||(this._licenseController=new LicenseController),this._licenseController}get localLayoutsStore(){return this._localLayoutsStore||(this._localLayoutsStore=new LocalLayoutsStore(this.idbController,this.sessionController,this.localStorageController)),this._localLayoutsStore}get managerLayoutsStore(){return this._managerLayoutsStore||(this._managerLayoutsStore=new ManagerLayoutsStore(this.managerController)),this._managerLayoutsStore}get restLayoutsStore(){return this._restLayoutsStore||(this._restLayoutsStore=new RestLayoutsStore(this.createSequelizer(),this.restScheduler,this.layoutsRestCache)),this._restLayoutsStore}get layoutsController(){return this._layoutsController||(this._layoutsController=new LayoutsController(this.glueController,this.layoutsBuilder,this.layoutsRestorer,this.localLayoutsStore,this.managerLayoutsStore,this.restLayoutsStore,this.sessionController)),this._layoutsController}get workspacesController(){return this._workspacesController||(this._workspacesController=new WorkspacesController(this.framesController,this.glueController,this.stateController,this.hibernationWatcher,this.createSequelizer(),this.sessionController,this)),this._workspacesController}get hibernationWatcher(){return this._hibernationWatcher||(this._hibernationWatcher=new WorkspaceHibernationWatcher(this.sessionController,this.createSequelizer())),this._hibernationWatcher}get intentsController(){return this._intentsController||(this._intentsController=new IntentsController(this.glueController,this.legacyResolverController,this.appDirectory,this.windowsController,this.prefsController,this.uiController)),this._intentsController}get legacyResolverController(){return this._legacyResolverController||(this._legacyResolverController=new LegacyResolverController(this.glueController,this.workspacesController,this.windowsController,this.prefsController)),this._legacyResolverController}get channelsController(){return this._channelsController||(this._channelsController=new ChannelsController(this.glueController,this.sessionController,this.workspacesController)),this._channelsController}get extensionController(){return this._extensionController||(this._extensionController=new ExtensionController(this.sessionController)),this._extensionController}get layoutsBuilder(){return this._layoutsBuilder||(this._layoutsBuilder=new Builder(this.glueController,this.sessionController,this.windowsController,this.workspacesController)),this._layoutsBuilder}get layoutsRestorer(){return this._layoutsRestorer||(this._layoutsRestorer=new Restorer(this.glueController,this.layoutsValidator,this.layoutsResetter,this.workspacesController,this.sessionController)),this._layoutsRestorer}get layoutsValidator(){return this._layoutsValidator||(this._layoutsValidator=new LayoutValidator(this.glueController,this.workspacesController)),this._layoutsValidator}get layoutsResetter(){return this._layoutsResetter||(this._layoutsResetter=new Resetter(this.glueController,this.workspacesController)),this._layoutsResetter}get notificationsController(){return this._notificationsController||(this._notificationsController=new NotificationsController(this.glueController,this.serviceWorkerController,this.sessionController,this.localStorageController,this.prefsController)),this._notificationsController}get framesController(){return this._framesController||(this._framesController=new FramesController(this.sessionController,this.glueController,this)),this._framesController}get idbController(){return this._idbController||(this._idbController=new IDBController),this._idbController}get portsBridge(){return this._portsBridge||(this._portsBridge=new PortsBridge(this.gateway,this.sessionController,this.stateController,this)),this._portsBridge}get serviceWorkerController(){return this._serviceWorkerController||(this._serviceWorkerController=new ServiceWorkerController(this.idbController)),this._serviceWorkerController}get transactionsController(){return this._transactionsController||(this._transactionsController=new TransactionsController),this._transactionsController}get interceptionController(){return this._interceptionController||(this._interceptionController=new InterceptionController),this._interceptionController}get pluginsController(){return this._pluginsController||(this._pluginsController=new PluginsController(this.interceptionController,this.glueController)),this._pluginsController}get appsSearchRepo(){return this._appsSearchRepo||(this._appsSearchRepo=new ApplicationsRepository(this.glueController)),this._appsSearchRepo}get managerController(){return this._managerController||(this._managerController=new ManagerController(this.managerIdentity,this.glueController,this.createSequelizer(),this.buildClient.bind(this),this.buildCache.bind(this))),this._managerController}get managerIdentity(){return this._managerIdentity||(this._managerIdentity=new Identity(new uaParserExports.UAParser,this.glueController,this.pluginsController,this.config?.workspaces?.src)),this._managerIdentity}get layoutsSearchRepo(){return this._layoutsSearchRepo||(this._layoutsSearchRepo=new LayoutsRepository(this.glueController)),this._layoutsSearchRepo}get workspacesSearchRepo(){return this._workspacesSearchRepo||(this._workspacesSearchRepo=new WorkspacesRepository(this.glueController)),this._workspacesSearchRepo}get preferredConnectionController(){return this._preferredConnectionController||(this._preferredConnectionController=new PreferredConnectionController(this.glueController,this.portsBridge,this.createSequelizer())),this._preferredConnectionController}get localPrefsStore(){return this._localPrefsStore||(this._localPrefsStore=new LocalPrefsStore(this.idbController)),this._localPrefsStore}get managerPrefsStore(){return this._managerPrefsStore||(this._managerPrefsStore=new ManagerPrefsStore(this.managerController)),this._managerPrefsStore}get restPrefsStore(){return this._restPrefsStore||(this._restPrefsStore=new RestPrefsStore(this.createSequelizer(),this.restScheduler,this.prefsRestCache,this.sessionController)),this._restPrefsStore}get prefsController(){return this._prefsController||(this._prefsController=new PrefsController(this.glueController,this.localPrefsStore,this.managerPrefsStore,this.restPrefsStore)),this._prefsController}get otelController(){return this._otelController||(this._otelController=new OtelController(this.otelTelemetry,this.getNewMetricsDependencyBuilder.bind(this),this.glueController,this.getPlatformController.bind(this),this.systemController,this.applicationsController,this.layoutsController,this.workspacesController)),this._otelController}get remotePlatformConfigController(){if(!this.remoteConfigFromManager)throw new Error("Cannot initialize RemotePlatformConfigController because RemoteConfigFromManager is not set");return this._remotePlatformConfigController||(this._remotePlatformConfigController=new RemotePlatformConfigController(this.remoteConfigFromManager,this.remoteConfigsCacheController)),this._remotePlatformConfigController}get remoteConfigsCacheController(){return this._remoteConfigsCacheController||(this._remoteConfigsCacheController=new RemoteConfigsCacheController),this._remoteConfigsCacheController}createMessageChannel(){return new MessageChannel}createSequelizer(e){return new AsyncSequelizer(e)}buildClient(e){return new CachedClientAPI(e)}buildCache(e,t){return e.cache?.enabled??1?new IdbBasedIOManagerCache(e,t):new SessionStorageBasedIOManagerCache(e,t)}getPlatformController(){return this.controller}getNewMetricsDependencyBuilder(){return new distExports$1.MetricsDependencyBuilder}getNewOtelContainerBuilder(){return new distExports$1.Builder}buildOtelLogger(e){return new LoggerAdapter(e)}get otelTelemetry(){return this._otelTelemetry||(this._otelTelemetry=new Telemetry(this.getNewOtelContainerBuilder.bind(this),this.buildOtelLogger.bind(this))),this._otelTelemetry}}let platformCache;const checkSingleton=()=>{const e=window.glue42core||window.iobrowser;if(e?.platformStarted)throw new Error("The Glue42 Core Platform has already been started for this application.")},initPlatformApi=async e=>{await e.platform.ready();return{io:e.platform.getClientGlue(),platform:e?.platform.getPlatformApi()}},setupPlatformConfig=async(e,t)=>{"manager"===t?.type?(e.remoteConfigFromManager=remoteConfigFromManagerDecoder.runWithException(t),e.config=await e.remotePlatformConfigController.getPlatformConfig()):e.config=t},ioConnectBrowserPlatformFactory=async e=>{const t=new IoC;await setupPlatformConfig(t,e);if(window.glue42gd||window.iodesktop)return fallbackToEnterprise(t.config);const r=!t.config?.connection?.alwaysPlatform&&await checkIsOpenerIOConnect(t.config?.connection),n=checkIfPlacedInWorkspace();if(t.config?.clientOnly||r||n){return{io:t.config?.browserFactory?await(t.config?.browserFactory(t.config?.browser)):await iOConnectBrowserFactory(t.config?.browser)}}try{checkSingleton()}catch(e){return void 0===platformCache?Promise.reject(new Error(e)):platformCache}const i=initPlatformApi(t);return t.config?.browser?.memoizeAPI&&(platformCache=i),i};"undefined"!=typeof window&&(window.IOBrowserPlatform=ioConnectBrowserPlatformFactory);const legacyGlobal=window.glue42gd||window.glue42core,ioGlobal=window.iodesktop||window.iobrowser;legacyGlobal||ioGlobal||(window.iobrowser={webStarted:!1});var dist$2={};const VERSION$4="1.9.1",re=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function _makeCompatibilityCheck(e){const t=new Set([e]),r=new Set,n=e.match(re);if(!n)return()=>!1;const i=+n[1],o=+n[2],s=+n[3];if(null!=n[4])return function(t){return t===e};function a(e){return r.add(e),!1}function c(e){return t.add(e),!0}return function(e){if(t.has(e))return!0;if(r.has(e))return!1;const n=e.match(re);if(!n)return a(e);const l=+n[1],u=+n[2],d=+n[3];return null!=n[4]||i!==l?a(e):0===i?o===u&&s<=d?c(e):a(e):o<=u?c(e):a(e)}}const isCompatible=_makeCompatibilityCheck(VERSION$4),major=VERSION$4.split(".")[0],GLOBAL_OPENTELEMETRY_API_KEY=Symbol.for(`opentelemetry.js.api.${major}`),_global="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof global?global:{};function registerGlobal(e,t,r,n=!1){var i;const o=_global[GLOBAL_OPENTELEMETRY_API_KEY]=null!==(i=_global[GLOBAL_OPENTELEMETRY_API_KEY])&&void 0!==i?i:{version:VERSION$4};if(!n&&o[e]){const t=new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${e}`);return r.error(t.stack||t.message),!1}if(o.version!==VERSION$4){const t=new Error(`@opentelemetry/api: Registration of version v${o.version} for ${e} does not match previously registered API v${VERSION$4}`);return r.error(t.stack||t.message),!1}return o[e]=t,r.debug(`@opentelemetry/api: Registered a global for ${e} v${VERSION$4}.`),!0}function getGlobal(e){var t,r;const n=null===(t=_global[GLOBAL_OPENTELEMETRY_API_KEY])||void 0===t?void 0:t.version;if(n&&isCompatible(n))return null===(r=_global[GLOBAL_OPENTELEMETRY_API_KEY])||void 0===r?void 0:r[e]}function unregisterGlobal(e,t){t.debug(`@opentelemetry/api: Unregistering a global for ${e} v${VERSION$4}.`);const r=_global[GLOBAL_OPENTELEMETRY_API_KEY];r&&delete r[e]}class DiagComponentLogger{constructor(e){this._namespace=e.namespace||"DiagComponentLogger"}debug(...e){return logProxy("debug",this._namespace,e)}error(...e){return logProxy("error",this._namespace,e)}info(...e){return logProxy("info",this._namespace,e)}warn(...e){return logProxy("warn",this._namespace,e)}verbose(...e){return logProxy("verbose",this._namespace,e)}}function logProxy(e,t,r){const n=getGlobal("diag");if(n)return n[e](t,...r)}var DiagLogLevel;function createLogLevelDiagLogger(e,t){function r(r,n){const i=t[r];return"function"==typeof i&&e>=n?i.bind(t):function(){}}return e<DiagLogLevel.NONE?e=DiagLogLevel.NONE:e>DiagLogLevel.ALL&&(e=DiagLogLevel.ALL),t=t||{},{error:r("error",DiagLogLevel.ERROR),warn:r("warn",DiagLogLevel.WARN),info:r("info",DiagLogLevel.INFO),debug:r("debug",DiagLogLevel.DEBUG),verbose:r("verbose",DiagLogLevel.VERBOSE)}}!function(e){e[e.NONE=0]="NONE",e[e.ERROR=30]="ERROR",e[e.WARN=50]="WARN",e[e.INFO=60]="INFO",e[e.DEBUG=70]="DEBUG",e[e.VERBOSE=80]="VERBOSE",e[e.ALL=9999]="ALL"}(DiagLogLevel||(DiagLogLevel={}));const API_NAME$4="diag";class DiagAPI{static instance(){return this._instance||(this._instance=new DiagAPI),this._instance}constructor(){function e(e){return function(...t){const r=getGlobal("diag");if(r)return r[e](...t)}}const t=this;t.setLogger=(e,r={logLevel:DiagLogLevel.INFO})=>{var n,i,o;if(e===t){const e=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return t.error(null!==(n=e.stack)&&void 0!==n?n:e.message),!1}"number"==typeof r&&(r={logLevel:r});const s=getGlobal("diag"),a=createLogLevelDiagLogger(null!==(i=r.logLevel)&&void 0!==i?i:DiagLogLevel.INFO,e);if(s&&!r.suppressOverrideMessage){const e=null!==(o=(new Error).stack)&&void 0!==o?o:"<failed to generate stacktrace>";s.warn(`Current logger will be overwritten from ${e}`),a.warn(`Current logger will overwrite one already registered from ${e}`)}return registerGlobal("diag",a,t,!0)},t.disable=()=>{unregisterGlobal(API_NAME$4,t)},t.createComponentLogger=e=>new DiagComponentLogger(e),t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}}class BaggageImpl{constructor(e){this._entries=e?new Map(e):new Map}getEntry(e){const t=this._entries.get(e);if(t)return Object.assign({},t)}getAllEntries(){return Array.from(this._entries.entries())}setEntry(e,t){const r=new BaggageImpl(this._entries);return r._entries.set(e,t),r}removeEntry(e){const t=new BaggageImpl(this._entries);return t._entries.delete(e),t}removeEntries(...e){const t=new BaggageImpl(this._entries);for(const r of e)t._entries.delete(r);return t}clear(){return new BaggageImpl}}const baggageEntryMetadataSymbol=Symbol("BaggageEntryMetadata"),diag$1=DiagAPI.instance();function createBaggage(e={}){return new BaggageImpl(new Map(Object.entries(e)))}function baggageEntryMetadataFromString(e){return"string"!=typeof e&&(diag$1.error("Cannot create baggage metadata from unknown type: "+typeof e),e=""),{__TYPE__:baggageEntryMetadataSymbol,toString:()=>e}}function createContextKey(e){return Symbol.for(e)}class BaseContext{constructor(e){const t=this;t._currentContext=e?new Map(e):new Map,t.getValue=e=>t._currentContext.get(e),t.setValue=(e,r)=>{const n=new BaseContext(t._currentContext);return n._currentContext.set(e,r),n},t.deleteValue=e=>{const r=new BaseContext(t._currentContext);return r._currentContext.delete(e),r}}}const ROOT_CONTEXT=new BaseContext,consoleMap=[{n:"error",c:"error"},{n:"warn",c:"warn"},{n:"info",c:"info"},{n:"debug",c:"debug"},{n:"verbose",c:"trace"}],_originalConsoleMethods={};if("undefined"!=typeof console){const e=["error","warn","info","debug","trace","log"];for(const t of e)"function"==typeof console[t]&&(_originalConsoleMethods[t]=console[t])}class DiagConsoleLogger{constructor(){function e(e){return function(...t){let r=_originalConsoleMethods[e];if("function"!=typeof r&&(r=_originalConsoleMethods.log),"function"!=typeof r&&console&&(r=console[e],"function"!=typeof r&&(r=console.log)),"function"==typeof r)return r.apply(console,t)}}for(let t=0;t<consoleMap.length;t++)this[consoleMap[t].n]=e(consoleMap[t].c)}}class NoopMeter{constructor(){}createGauge(e,t){return NOOP_GAUGE_METRIC}createHistogram(e,t){return NOOP_HISTOGRAM_METRIC}createCounter(e,t){return NOOP_COUNTER_METRIC}createUpDownCounter(e,t){return NOOP_UP_DOWN_COUNTER_METRIC}createObservableGauge(e,t){return NOOP_OBSERVABLE_GAUGE_METRIC}createObservableCounter(e,t){return NOOP_OBSERVABLE_COUNTER_METRIC}createObservableUpDownCounter(e,t){return NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC}addBatchObservableCallback(e,t){}removeBatchObservableCallback(e){}}class NoopMetric{}class NoopCounterMetric extends NoopMetric{add(e,t){}}class NoopUpDownCounterMetric extends NoopMetric{add(e,t){}}class NoopGaugeMetric extends NoopMetric{record(e,t){}}class NoopHistogramMetric extends NoopMetric{record(e,t){}}class NoopObservableMetric{addCallback(e){}removeCallback(e){}}class NoopObservableCounterMetric extends NoopObservableMetric{}class NoopObservableGaugeMetric extends NoopObservableMetric{}class NoopObservableUpDownCounterMetric extends NoopObservableMetric{}const NOOP_METER=new NoopMeter,NOOP_COUNTER_METRIC=new NoopCounterMetric,NOOP_GAUGE_METRIC=new NoopGaugeMetric,NOOP_HISTOGRAM_METRIC=new NoopHistogramMetric,NOOP_UP_DOWN_COUNTER_METRIC=new NoopUpDownCounterMetric,NOOP_OBSERVABLE_COUNTER_METRIC=new NoopObservableCounterMetric,NOOP_OBSERVABLE_GAUGE_METRIC=new NoopObservableGaugeMetric,NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC=new NoopObservableUpDownCounterMetric;function createNoopMeter(){return NOOP_METER}var ValueType;!function(e){e[e.INT=0]="INT",e[e.DOUBLE=1]="DOUBLE"}(ValueType||(ValueType={}));const defaultTextMapGetter={get(e,t){if(null!=e)return e[t]},keys:e=>null==e?[]:Object.keys(e)},defaultTextMapSetter={set(e,t,r){null!=e&&(e[t]=r)}};class NoopContextManager{active(){return ROOT_CONTEXT}with(e,t,r,...n){return t.call(r,...n)}bind(e,t){return t}enable(){return this}disable(){return this}}const API_NAME$3="context",NOOP_CONTEXT_MANAGER=new NoopContextManager;class ContextAPI{constructor(){}static getInstance(){return this._instance||(this._instance=new ContextAPI),this._instance}setGlobalContextManager(e){return registerGlobal(API_NAME$3,e,DiagAPI.instance())}active(){return this._getContextManager().active()}with(e,t,r,...n){return this._getContextManager().with(e,t,r,...n)}bind(e,t){return this._getContextManager().bind(e,t)}_getContextManager(){return getGlobal(API_NAME$3)||NOOP_CONTEXT_MANAGER}disable(){this._getContextManager().disable(),unregisterGlobal(API_NAME$3,DiagAPI.instance())}}var TraceFlags;!function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"}(TraceFlags||(TraceFlags={}));const INVALID_SPANID="0000000000000000",INVALID_TRACEID="00000000000000000000000000000000",INVALID_SPAN_CONTEXT={traceId:INVALID_TRACEID,spanId:INVALID_SPANID,traceFlags:TraceFlags.NONE};class NonRecordingSpan{constructor(e=INVALID_SPAN_CONTEXT){this._spanContext=e}spanContext(){return this._spanContext}setAttribute(e,t){return this}setAttributes(e){return this}addEvent(e,t){return this}addLink(e){return this}addLinks(e){return this}setStatus(e){return this}updateName(e){return this}end(e){}isRecording(){return!1}recordException(e,t){}}const SPAN_KEY=createContextKey("OpenTelemetry Context Key SPAN");function getSpan(e){return e.getValue(SPAN_KEY)||void 0}function getActiveSpan(){return getSpan(ContextAPI.getInstance().active())}function setSpan(e,t){return e.setValue(SPAN_KEY,t)}function deleteSpan(e){return e.deleteValue(SPAN_KEY)}function setSpanContext(e,t){return setSpan(e,new NonRecordingSpan(t))}function getSpanContext(e){var t;return null===(t=getSpan(e))||void 0===t?void 0:t.spanContext()}const isHex=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1]);function isValidHex(e,t){if("string"!=typeof e||e.length!==t)return!1;let r=0;for(let t=0;t<e.length;t+=4)r+=(0|isHex[e.charCodeAt(t)])+(0|isHex[e.charCodeAt(t+1)])+(0|isHex[e.charCodeAt(t+2)])+(0|isHex[e.charCodeAt(t+3)]);return r===t}function isValidTraceId(e){return isValidHex(e,32)&&e!==INVALID_TRACEID}function isValidSpanId(e){return isValidHex(e,16)&&e!==INVALID_SPANID}function isSpanContextValid(e){return isValidTraceId(e.traceId)&&isValidSpanId(e.spanId)}function wrapSpanContext(e){return new NonRecordingSpan(e)}const contextApi=ContextAPI.getInstance();class NoopTracer{startSpan(e,t,r=contextApi.active()){if(Boolean(null==t?void 0:t.root))return new NonRecordingSpan;const n=r&&getSpanContext(r);return isSpanContext(n)&&isSpanContextValid(n)?new NonRecordingSpan(n):new NonRecordingSpan}startActiveSpan(e,t,r,n){let i,o,s;if(arguments.length<2)return;2===arguments.length?s=t:3===arguments.length?(i=t,s=r):(i=t,o=r,s=n);const a=null!=o?o:contextApi.active(),c=this.startSpan(e,i,a),l=setSpan(a,c);return contextApi.with(l,s,void 0,c)}}function isSpanContext(e){return null!==e&&"object"==typeof e&&"spanId"in e&&"string"==typeof e.spanId&&"traceId"in e&&"string"==typeof e.traceId&&"traceFlags"in e&&"number"==typeof e.traceFlags}const NOOP_TRACER=new NoopTracer;class ProxyTracer{constructor(e,t,r,n){this._provider=e,this.name=t,this.version=r,this.options=n}startSpan(e,t,r){return this._getTracer().startSpan(e,t,r)}startActiveSpan(e,t,r,n){const i=this._getTracer();return Reflect.apply(i.startActiveSpan,i,arguments)}_getTracer(){if(this._delegate)return this._delegate;const e=this._provider.getDelegateTracer(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):NOOP_TRACER}}class NoopTracerProvider{getTracer(e,t,r){return new NoopTracer}}const NOOP_TRACER_PROVIDER=new NoopTracerProvider;class ProxyTracerProvider{getTracer(e,t,r){var n;return null!==(n=this.getDelegateTracer(e,t,r))&&void 0!==n?n:new ProxyTracer(this,e,t,r)}getDelegate(){var e;return null!==(e=this._delegate)&&void 0!==e?e:NOOP_TRACER_PROVIDER}setDelegate(e){this._delegate=e}getDelegateTracer(e,t,r){var n;return null===(n=this._delegate)||void 0===n?void 0:n.getTracer(e,t,r)}}var SamplingDecision$1,SpanKind,SpanStatusCode;!function(e){e[e.NOT_RECORD=0]="NOT_RECORD",e[e.RECORD=1]="RECORD",e[e.RECORD_AND_SAMPLED=2]="RECORD_AND_SAMPLED"}(SamplingDecision$1||(SamplingDecision$1={})),function(e){e[e.INTERNAL=0]="INTERNAL",e[e.SERVER=1]="SERVER",e[e.CLIENT=2]="CLIENT",e[e.PRODUCER=3]="PRODUCER",e[e.CONSUMER=4]="CONSUMER"}(SpanKind||(SpanKind={})),function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"}(SpanStatusCode||(SpanStatusCode={}));const VALID_KEY_CHAR_RANGE$1="[_0-9a-z-*/]",VALID_KEY$1=`[a-z]${VALID_KEY_CHAR_RANGE$1}{0,255}`,VALID_VENDOR_KEY$1=`[a-z0-9]${VALID_KEY_CHAR_RANGE$1}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE$1}{0,13}`,VALID_KEY_REGEX$1=new RegExp(`^(?:${VALID_KEY$1}|${VALID_VENDOR_KEY$1})$`),VALID_VALUE_BASE_REGEX$1=/^[ -~]{0,255}[!-~]$/,INVALID_VALUE_COMMA_EQUAL_REGEX$1=/,|=/;function validateKey$1(e){return VALID_KEY_REGEX$1.test(e)}function validateValue$1(e){return VALID_VALUE_BASE_REGEX$1.test(e)&&!INVALID_VALUE_COMMA_EQUAL_REGEX$1.test(e)}const MAX_TRACE_STATE_ITEMS$1=32,MAX_TRACE_STATE_LEN$1=512,LIST_MEMBERS_SEPARATOR$1=",",LIST_MEMBER_KEY_VALUE_SPLITTER$1="=";class TraceStateImpl{constructor(e){this._internalState=new Map,e&&this._parse(e)}set(e,t){const r=this._clone();return r._internalState.has(e)&&r._internalState.delete(e),r._internalState.set(e,t),r}unset(e){const t=this._clone();return t._internalState.delete(e),t}get(e){return this._internalState.get(e)}serialize(){return Array.from(this._internalState.keys()).reduceRight((e,t)=>(e.push(t+LIST_MEMBER_KEY_VALUE_SPLITTER$1+this.get(t)),e),[]).join(LIST_MEMBERS_SEPARATOR$1)}_parse(e){e.length>MAX_TRACE_STATE_LEN$1||(this._internalState=e.split(LIST_MEMBERS_SEPARATOR$1).reduceRight((e,t)=>{const r=t.trim(),n=r.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER$1);if(-1!==n){const i=r.slice(0,n),o=r.slice(n+1,t.length);validateKey$1(i)&&validateValue$1(o)&&e.set(i,o)}return e},new Map),this._internalState.size>MAX_TRACE_STATE_ITEMS$1&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,MAX_TRACE_STATE_ITEMS$1))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){const e=new TraceStateImpl;return e._internalState=new Map(this._internalState),e}}function createTraceState(e){return new TraceStateImpl(e)}const context=ContextAPI.getInstance(),diag=DiagAPI.instance();class NoopMeterProvider{getMeter(e,t,r){return NOOP_METER}}const NOOP_METER_PROVIDER=new NoopMeterProvider,API_NAME$2="metrics";class MetricsAPI{constructor(){}static getInstance(){return this._instance||(this._instance=new MetricsAPI),this._instance}setGlobalMeterProvider(e){return registerGlobal(API_NAME$2,e,DiagAPI.instance())}getMeterProvider(){return getGlobal(API_NAME$2)||NOOP_METER_PROVIDER}getMeter(e,t,r){return this.getMeterProvider().getMeter(e,t,r)}disable(){unregisterGlobal(API_NAME$2,DiagAPI.instance())}}const metrics=MetricsAPI.getInstance();class NoopTextMapPropagator{inject(e,t){}extract(e,t){return e}fields(){return[]}}const BAGGAGE_KEY=createContextKey("OpenTelemetry Baggage Key");function getBaggage(e){return e.getValue(BAGGAGE_KEY)||void 0}function getActiveBaggage(){return getBaggage(ContextAPI.getInstance().active())}function setBaggage(e,t){return e.setValue(BAGGAGE_KEY,t)}function deleteBaggage(e){return e.deleteValue(BAGGAGE_KEY)}const API_NAME$1="propagation",NOOP_TEXT_MAP_PROPAGATOR=new NoopTextMapPropagator;class PropagationAPI{constructor(){this.createBaggage=createBaggage,this.getBaggage=getBaggage,this.getActiveBaggage=getActiveBaggage,this.setBaggage=setBaggage,this.deleteBaggage=deleteBaggage}static getInstance(){return this._instance||(this._instance=new PropagationAPI),this._instance}setGlobalPropagator(e){return registerGlobal(API_NAME$1,e,DiagAPI.instance())}inject(e,t,r=defaultTextMapSetter){return this._getGlobalPropagator().inject(e,t,r)}extract(e,t,r=defaultTextMapGetter){return this._getGlobalPropagator().extract(e,t,r)}fields(){return this._getGlobalPropagator().fields()}disable(){unregisterGlobal(API_NAME$1,DiagAPI.instance())}_getGlobalPropagator(){return getGlobal(API_NAME$1)||NOOP_TEXT_MAP_PROPAGATOR}}const propagation=PropagationAPI.getInstance(),API_NAME="trace";class TraceAPI{constructor(){this._proxyTracerProvider=new ProxyTracerProvider,this.wrapSpanContext=wrapSpanContext,this.isSpanContextValid=isSpanContextValid,this.deleteSpan=deleteSpan,this.getSpan=getSpan,this.getActiveSpan=getActiveSpan,this.getSpanContext=getSpanContext,this.setSpan=setSpan,this.setSpanContext=setSpanContext}static getInstance(){return this._instance||(this._instance=new TraceAPI),this._instance}setGlobalTracerProvider(e){const t=registerGlobal(API_NAME,this._proxyTracerProvider,DiagAPI.instance());return t&&this._proxyTracerProvider.setDelegate(e),t}getTracerProvider(){return getGlobal(API_NAME)||this._proxyTracerProvider}getTracer(e,t){return this.getTracerProvider().getTracer(e,t)}disable(){unregisterGlobal(API_NAME,DiagAPI.instance()),this._proxyTracerProvider=new ProxyTracerProvider}}const trace=TraceAPI.getInstance();var index$3={context:context,diag:diag,metrics:metrics,propagation:propagation,trace:trace},esm$6=Object.freeze({__proto__:null,DiagConsoleLogger:DiagConsoleLogger,get DiagLogLevel(){return DiagLogLevel},INVALID_SPANID:INVALID_SPANID,INVALID_SPAN_CONTEXT:INVALID_SPAN_CONTEXT,INVALID_TRACEID:INVALID_TRACEID,ProxyTracer:ProxyTracer,ProxyTracerProvider:ProxyTracerProvider,ROOT_CONTEXT:ROOT_CONTEXT,get SamplingDecision(){return SamplingDecision$1},get SpanKind(){return SpanKind},get SpanStatusCode(){return SpanStatusCode},get TraceFlags(){return TraceFlags},get ValueType(){return ValueType},baggageEntryMetadataFromString:baggageEntryMetadataFromString,context:context,createContextKey:createContextKey,createNoopMeter:createNoopMeter,createTraceState:createTraceState,default:index$3,defaultTextMapGetter:defaultTextMapGetter,defaultTextMapSetter:defaultTextMapSetter,diag:diag,isSpanContextValid:isSpanContextValid,isValidSpanId:isValidSpanId,isValidTraceId:isValidTraceId,metrics:metrics,propagation:propagation,trace:trace}),require$$0$2=getAugmentedNamespace(esm$6);const VERSION$3="2.2.0",TMP_PROCESS_RUNTIME_NAME="process.runtime.name",TMP_TELEMETRY_SDK_NAME="telemetry.sdk.name",TMP_TELEMETRY_SDK_LANGUAGE="telemetry.sdk.language",TMP_TELEMETRY_SDK_VERSION="telemetry.sdk.version",SEMRESATTRS_PROCESS_RUNTIME_NAME=TMP_PROCESS_RUNTIME_NAME,SEMRESATTRS_TELEMETRY_SDK_NAME=TMP_TELEMETRY_SDK_NAME,SEMRESATTRS_TELEMETRY_SDK_LANGUAGE=TMP_TELEMETRY_SDK_LANGUAGE,SEMRESATTRS_TELEMETRY_SDK_VERSION=TMP_TELEMETRY_SDK_VERSION,TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS="webjs",TELEMETRYSDKLANGUAGEVALUES_WEBJS=TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS,ATTR_EXCEPTION_MESSAGE="exception.message",ATTR_EXCEPTION_STACKTRACE="exception.stacktrace",ATTR_EXCEPTION_TYPE="exception.type",ATTR_SERVICE_NAME="service.name",ATTR_TELEMETRY_SDK_LANGUAGE="telemetry.sdk.language",TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS="webjs",ATTR_TELEMETRY_SDK_NAME="telemetry.sdk.name",ATTR_TELEMETRY_SDK_VERSION="telemetry.sdk.version",ATTR_PROCESS_RUNTIME_NAME$1="process.runtime.name",SDK_INFO$2={[ATTR_TELEMETRY_SDK_NAME]:"opentelemetry",[ATTR_PROCESS_RUNTIME_NAME$1]:"browser",[ATTR_TELEMETRY_SDK_LANGUAGE]:TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS,[ATTR_TELEMETRY_SDK_VERSION]:VERSION$3};function defaultServiceName$1(){return"unknown_service"}const isPromiseLike$1=e=>null!==e&&"object"==typeof e&&"function"==typeof e.then;let ResourceImpl$1=class e{_rawAttributes;_asyncAttributesPending=!1;_schemaUrl;_memoizedAttributes;static FromAttributeList(t,r){const n=new e({},r);return n._rawAttributes=guardedRawAttributes$1(t),n._asyncAttributesPending=t.filter(([e,t])=>isPromiseLike$1(t)).length>0,n}constructor(e,t){const r=e.attributes??{};this._rawAttributes=Object.entries(r).map(([e,t])=>(isPromiseLike$1(t)&&(this._asyncAttributesPending=!0),[e,t])),this._rawAttributes=guardedRawAttributes$1(this._rawAttributes),this._schemaUrl=validateSchemaUrl$1(t?.schemaUrl)}get asyncAttributesPending(){return this._asyncAttributesPending}async waitForAsyncAttributes(){if(this.asyncAttributesPending){for(let e=0;e<this._rawAttributes.length;e++){const[t,r]=this._rawAttributes[e];this._rawAttributes[e]=[t,isPromiseLike$1(r)?await r:r]}this._asyncAttributesPending=!1}}get attributes(){if(this.asyncAttributesPending&&diag.error("Accessing resource attributes before async attributes settled"),this._memoizedAttributes)return this._memoizedAttributes;const e={};for(const[t,r]of this._rawAttributes)isPromiseLike$1(r)?diag.debug(`Unsettled resource attribute ${t} skipped`):null!=r&&(e[t]??=r);return this._asyncAttributesPending||(this._memoizedAttributes=e),e}getRawAttributes(){return this._rawAttributes}get schemaUrl(){return this._schemaUrl}merge(t){if(null==t)return this;const r=mergeSchemaUrl$1(this,t),n=r?{schemaUrl:r}:void 0;return e.FromAttributeList([...t.getRawAttributes(),...this.getRawAttributes()],n)}};function resourceFromAttributes$1(e,t){return ResourceImpl$1.FromAttributeList(Object.entries(e),t)}function resourceFromDetectedResource(e,t){return new ResourceImpl$1(e,t)}function emptyResource(){return resourceFromAttributes$1({})}function defaultResource$1(){return resourceFromAttributes$1({[ATTR_SERVICE_NAME]:defaultServiceName$1(),[ATTR_TELEMETRY_SDK_LANGUAGE]:SDK_INFO$2[ATTR_TELEMETRY_SDK_LANGUAGE],[ATTR_TELEMETRY_SDK_NAME]:SDK_INFO$2[ATTR_TELEMETRY_SDK_NAME],[ATTR_TELEMETRY_SDK_VERSION]:SDK_INFO$2[ATTR_TELEMETRY_SDK_VERSION]})}function guardedRawAttributes$1(e){return e.map(([e,t])=>isPromiseLike$1(t)?[e,t.catch(t=>{diag.debug("promise rejection for resource attribute: %s - %s",e,t)})]:[e,t])}function validateSchemaUrl$1(e){if("string"==typeof e||void 0===e)return e;diag.warn("Schema URL must be string or undefined, got %s. Schema URL will be ignored.",e)}function mergeSchemaUrl$1(e,t){const r=e?.schemaUrl,n=t?.schemaUrl;return void 0===r||""===r?n:void 0===n||""===n||r===n?r:void diag.warn('Schema URL merge conflict: old resource has "%s", updating resource has "%s". Resulting resource will have undefined Schema URL.',r,n)}const detectResources=(e={})=>{const t=(e.detectors||[]).map(t=>{try{const r=resourceFromDetectedResource(t.detect(e));return diag.debug(`${t.constructor.name} found resource.`,r),r}catch(e){return diag.debug(`${t.constructor.name} failed: ${e.message}`),emptyResource()}});return t.reduce((e,t)=>e.merge(t),emptyResource())};class EnvDetector{_MAX_LENGTH=255;_COMMA_SEPARATOR=",";_LABEL_KEY_VALUE_SPLITTER="=";_ERROR_MESSAGE_INVALID_CHARS="should be a ASCII string with a length greater than 0 and not exceed "+this._MAX_LENGTH+" characters.";_ERROR_MESSAGE_INVALID_VALUE="should be a ASCII string with a length not exceed "+this._MAX_LENGTH+" characters.";detect(e){return{attributes:{}}}_parseResourceAttributes(e){if(!e)return{};const t={},r=e.split(this._COMMA_SEPARATOR,-1);for(const e of r){const r=e.split(this._LABEL_KEY_VALUE_SPLITTER,-1);if(2!==r.length)continue;let[n,i]=r;if(n=n.trim(),i=i.trim().split(/^"|"$/).join(""),!this._isValidAndNotEmpty(n))throw new Error(`Attribute key ${this._ERROR_MESSAGE_INVALID_CHARS}`);if(!this._isValid(i))throw new Error(`Attribute value ${this._ERROR_MESSAGE_INVALID_VALUE}`);t[n]=decodeURIComponent(i)}return t}_isValid(e){return e.length<=this._MAX_LENGTH&&this._isBaggageOctetString(e)}_isBaggageOctetString(e){for(let t=0;t<e.length;t++){const r=e.charCodeAt(t);if(r<33||44===r||59===r||92===r||r>126)return!1}return!0}_isValidAndNotEmpty(e){return e.length>0&&this._isValid(e)}}const envDetector=new EnvDetector;class NoopDetector{detect(){return{attributes:{}}}}const noopDetector=new NoopDetector,hostDetector=noopDetector,osDetector=noopDetector,processDetector=noopDetector,serviceInstanceIdDetector=noopDetector;var esm$5=Object.freeze({__proto__:null,defaultResource:defaultResource$1,defaultServiceName:defaultServiceName$1,detectResources:detectResources,emptyResource:emptyResource,envDetector:envDetector,hostDetector:hostDetector,osDetector:osDetector,processDetector:processDetector,resourceFromAttributes:resourceFromAttributes$1,serviceInstanceIdDetector:serviceInstanceIdDetector}),require$$2$1=getAugmentedNamespace(esm$5);Object.defineProperty(dist$2,"__esModule",{value:!0});var init_1$1=dist$2.init=void 0;const otel_1$v=requireDist$1(),api_1$2=require$$0$2,resources_1=require$$2$1;function init$1(){(0,otel_1$v.registerInsightsPlugin)("base",()=>({resourceFromAttributes:e=>(0,resources_1.resourceFromAttributes)(e),diag:api_1$2.diag}))}init_1$1=dist$2.init=init$1;var index$2=Object.freeze({__proto__:null,default:dist$2,get init(){return init_1$1}}),dist$1={},customHistogram={},base$1={},base={},validator={};Object.defineProperty(validator,"__esModule",{value:!0}),validator.Validator=void 0;class Validator{static isNullOrUndefined(e){return null==e}static throwIfNullOrUndefined(e,t,r){if(this.isNullOrUndefined(e))throw new Error(r||`${t} must be defined`)}}validator.Validator=Validator,Object.defineProperty(base,"__esModule",{value:!0}),base.MetricBaseValidator=void 0;const validator_1$l=validator;class MetricBaseValidator{validate(e){validator_1$l.Validator.throwIfNullOrUndefined(e,"base"),validator_1$l.Validator.throwIfNullOrUndefined(e.logger,"logger"),this.validateSettings(e.settings)}validateSettings(e){validator_1$l.Validator.throwIfNullOrUndefined(e,"settings"),validator_1$l.Validator.throwIfNullOrUndefined(e.enabled,"enabled"),validator_1$l.Validator.throwIfNullOrUndefined(e.name,"name"),validator_1$l.Validator.throwIfNullOrUndefined(e.type,"type"),validator_1$l.Validator.throwIfNullOrUndefined(e.description,"description"),validator_1$l.Validator.throwIfNullOrUndefined(e.platformVersion,"platformVersion")}}base.MetricBaseValidator=MetricBaseValidator;var utils$1={},lodash_clonedeep={exports:{}};lodash_clonedeep.exports,function(e,t){var r="__lodash_hash_undefined__",n=9007199254740991,i="[object Arguments]",o="[object Boolean]",s="[object Date]",a="[object Function]",c="[object GeneratorFunction]",l="[object Map]",u="[object Number]",d="[object Object]",h="[object Promise]",p="[object RegExp]",g="[object Set]",m="[object String]",f="[object Symbol]",y="[object WeakMap]",$="[object ArrayBuffer]",b="[object DataView]",w="[object Float32Array]",v="[object Float64Array]",S="[object Int8Array]",E="[object Int16Array]",C="[object Int32Array]",_="[object Uint8Array]",I="[object Uint8ClampedArray]",T="[object Uint16Array]",A="[object Uint32Array]",D=/\w*$/,x=/^\[object .+?Constructor\]$/,R=/^(?:0|[1-9]\d*)$/,O={};O[i]=O["[object Array]"]=O[$]=O[b]=O[o]=O[s]=O[w]=O[v]=O[S]=O[E]=O[C]=O[l]=O[u]=O[d]=O[p]=O[g]=O[m]=O[f]=O[_]=O[I]=O[T]=O[A]=!0,O["[object Error]"]=O[a]=O[y]=!1;var P="object"==typeof commonjsGlobal$1&&commonjsGlobal$1&&commonjsGlobal$1.Object===Object&&commonjsGlobal$1,N="object"==typeof self&&self&&self.Object===Object&&self,k=P||N||Function("return this")(),M=t&&!t.nodeType&&t,L=M&&e&&!e.nodeType&&e,F=L&&L.exports===M;function j(e,t){return e.set(t[0],t[1]),e}function U(e,t){return e.add(t),e}function B(e,t,r,n){for(var i=-1,o=e?e.length:0;++i<o;)r=t(r,e[i],i,e);return r}function q(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(e){}return t}function H(e){var t=-1,r=Array(e.size);return e.forEach(function(e,n){r[++t]=[n,e]}),r}function W(e,t){return function(r){return e(t(r))}}function G(e){var t=-1,r=Array(e.size);return e.forEach(function(e){r[++t]=e}),r}var J,K=Array.prototype,V=Function.prototype,z=Object.prototype,X=k["__core-js_shared__"],Y=(J=/[^.]+$/.exec(X&&X.keys&&X.keys.IE_PROTO||""))?"Symbol(src)_1."+J:"",Z=V.toString,Q=z.hasOwnProperty,ee=z.toString,te=RegExp("^"+Z.call(Q).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),re=F?k.Buffer:void 0,ne=k.Symbol,ie=k.Uint8Array,oe=W(Object.getPrototypeOf,Object),se=Object.create,ae=z.propertyIsEnumerable,ce=K.splice,le=Object.getOwnPropertySymbols,ue=re?re.isBuffer:void 0,de=W(Object.keys,Object),he=Le(k,"DataView"),pe=Le(k,"Map"),ge=Le(k,"Promise"),me=Le(k,"Set"),fe=Le(k,"WeakMap"),ye=Le(Object,"create"),$e=qe(he),be=qe(pe),we=qe(ge),ve=qe(me),Se=qe(fe),Ee=ne?ne.prototype:void 0,Ce=Ee?Ee.valueOf:void 0;function _e(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function Ie(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function Te(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function Ae(e){this.__data__=new Ie(e)}function De(e,t){var r=We(e)||function(e){return function(e){return function(e){return!!e&&"object"==typeof e}(e)&&Ge(e)}(e)&&Q.call(e,"callee")&&(!ae.call(e,"callee")||ee.call(e)==i)}(e)?function(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}(e.length,String):[],n=r.length,o=!!n;for(var s in e)!Q.call(e,s)||o&&("length"==s||Ue(s,n))||r.push(s);return r}function xe(e,t,r){var n=e[t];Q.call(e,t)&&He(n,r)&&(void 0!==r||t in e)||(e[t]=r)}function Re(e,t){for(var r=e.length;r--;)if(He(e[r][0],t))return r;return-1}function Oe(e,t,r,n,h,y,x){var R;if(n&&(R=y?n(e,h,y,x):n(e)),void 0!==R)return R;if(!Ve(e))return e;var P=We(e);if(P){if(R=function(e){var t=e.length,r=e.constructor(t);t&&"string"==typeof e[0]&&Q.call(e,"index")&&(r.index=e.index,r.input=e.input);return r}(e),!t)return function(e,t){var r=-1,n=e.length;t||(t=Array(n));for(;++r<n;)t[r]=e[r];return t}(e,R)}else{var N=je(e),k=N==a||N==c;if(Je(e))return function(e,t){if(t)return e.slice();var r=new e.constructor(e.length);return e.copy(r),r}(e,t);if(N==d||N==i||k&&!y){if(q(e))return y?e:{};if(R=function(e){return"function"!=typeof e.constructor||Be(e)?{}:(t=oe(e),Ve(t)?se(t):{});var t}(k?{}:e),!t)return function(e,t){return ke(e,Fe(e),t)}(e,function(e,t){return e&&ke(t,ze(t),e)}(R,e))}else{if(!O[N])return y?e:{};R=function(e,t,r,n){var i=e.constructor;switch(t){case $:return Ne(e);case o:case s:return new i(+e);case b:return function(e,t){var r=t?Ne(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.byteLength)}(e,n);case w:case v:case S:case E:case C:case _:case I:case T:case A:return function(e,t){var r=t?Ne(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}(e,n);case l:return function(e,t,r){var n=t?r(H(e),!0):H(e);return B(n,j,new e.constructor)}(e,n,r);case u:case m:return new i(e);case p:return function(e){var t=new e.constructor(e.source,D.exec(e));return t.lastIndex=e.lastIndex,t}(e);case g:return function(e,t,r){var n=t?r(G(e),!0):G(e);return B(n,U,new e.constructor)}(e,n,r);case f:return a=e,Ce?Object(Ce.call(a)):{}}var a}(e,N,Oe,t)}}x||(x=new Ae);var M=x.get(e);if(M)return M;if(x.set(e,R),!P)var L=r?function(e){return function(e,t,r){var n=t(e);return We(e)?n:function(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e}(n,r(e))}(e,ze,Fe)}(e):ze(e);return function(e,t){for(var r=-1,n=e?e.length:0;++r<n&&!1!==t(e[r],r,e););}(L||e,function(i,o){L&&(i=e[o=i]),xe(R,o,Oe(i,t,r,n,o,e,x))}),R}function Pe(e){return!(!Ve(e)||(t=e,Y&&Y in t))&&(Ke(e)||q(e)?te:x).test(qe(e));var t}function Ne(e){var t=new e.constructor(e.byteLength);return new ie(t).set(new ie(e)),t}function ke(e,t,r,n){r||(r={});for(var i=-1,o=t.length;++i<o;){var s=t[i];xe(r,s,e[s])}return r}function Me(e,t){var r=e.__data__;return function(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}(t)?r["string"==typeof t?"string":"hash"]:r.map}function Le(e,t){var r=function(e,t){return null==e?void 0:e[t]}(e,t);return Pe(r)?r:void 0}_e.prototype.clear=function(){this.__data__=ye?ye(null):{}},_e.prototype.delete=function(e){return this.has(e)&&delete this.__data__[e]},_e.prototype.get=function(e){var t=this.__data__;if(ye){var n=t[e];return n===r?void 0:n}return Q.call(t,e)?t[e]:void 0},_e.prototype.has=function(e){var t=this.__data__;return ye?void 0!==t[e]:Q.call(t,e)},_e.prototype.set=function(e,t){return this.__data__[e]=ye&&void 0===t?r:t,this},Ie.prototype.clear=function(){this.__data__=[]},Ie.prototype.delete=function(e){var t=this.__data__,r=Re(t,e);return!(r<0)&&(r==t.length-1?t.pop():ce.call(t,r,1),!0)},Ie.prototype.get=function(e){var t=this.__data__,r=Re(t,e);return r<0?void 0:t[r][1]},Ie.prototype.has=function(e){return Re(this.__data__,e)>-1},Ie.prototype.set=function(e,t){var r=this.__data__,n=Re(r,e);return n<0?r.push([e,t]):r[n][1]=t,this},Te.prototype.clear=function(){this.__data__={hash:new _e,map:new(pe||Ie),string:new _e}},Te.prototype.delete=function(e){return Me(this,e).delete(e)},Te.prototype.get=function(e){return Me(this,e).get(e)},Te.prototype.has=function(e){return Me(this,e).has(e)},Te.prototype.set=function(e,t){return Me(this,e).set(e,t),this},Ae.prototype.clear=function(){this.__data__=new Ie},Ae.prototype.delete=function(e){return this.__data__.delete(e)},Ae.prototype.get=function(e){return this.__data__.get(e)},Ae.prototype.has=function(e){return this.__data__.has(e)},Ae.prototype.set=function(e,t){var r=this.__data__;if(r instanceof Ie){var n=r.__data__;if(!pe||n.length<199)return n.push([e,t]),this;r=this.__data__=new Te(n)}return r.set(e,t),this};var Fe=le?W(le,Object):function(){return[]},je=function(e){return ee.call(e)};function Ue(e,t){return!!(t=null==t?n:t)&&("number"==typeof e||R.test(e))&&e>-1&&e%1==0&&e<t}function Be(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||z)}function qe(e){if(null!=e){try{return Z.call(e)}catch(e){}try{return e+""}catch(e){}}return""}function He(e,t){return e===t||e!=e&&t!=t}(he&&je(new he(new ArrayBuffer(1)))!=b||pe&&je(new pe)!=l||ge&&je(ge.resolve())!=h||me&&je(new me)!=g||fe&&je(new fe)!=y)&&(je=function(e){var t=ee.call(e),r=t==d?e.constructor:void 0,n=r?qe(r):void 0;if(n)switch(n){case $e:return b;case be:return l;case we:return h;case ve:return g;case Se:return y}return t});var We=Array.isArray;function Ge(e){return null!=e&&function(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=n}(e.length)&&!Ke(e)}var Je=ue||function(){return!1};function Ke(e){var t=Ve(e)?ee.call(e):"";return t==a||t==c}function Ve(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function ze(e){return Ge(e)?De(e):function(e){if(!Be(e))return de(e);var t=[];for(var r in Object(e))Q.call(e,r)&&"constructor"!=r&&t.push(r);return t}(e)}e.exports=function(e){return Oe(e,!0,!0)}}(lodash_clonedeep,lodash_clonedeep.exports);var lodash_clonedeepExports=lodash_clonedeep.exports,__importDefault$2=commonjsGlobal$1&&commonjsGlobal$1.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(utils$1,"__esModule",{value:!0}),utils$1.reduceModality=void 0;const lodash_clonedeep_1$2=__importDefault$2(lodash_clonedeepExports);function reduceModality(e,t){var r;if(!e||!t)return e;if(!Object.keys(t))return e;e=(0,lodash_clonedeep_1$2.default)(e);for(const n in t)if(n in e){const i=null===(r=t[n])||void 0===r?void 0:r.reduceModality;if(void 0===i||i<0)continue;0===i?delete e[n]:i>0&&(e[n]=simpleHash(e[n]+"",i))}return e}function simpleHash(e,t){let r=2166136261;for(let t=0;t<e.length;t++)r^=e.charCodeAt(t),r=Math.imul(r,16777619);let n=(r>>>0).toString(16);return n.length<t?n.padEnd(t,n).slice(0,t):n.slice(0,t)}utils$1.reduceModality=reduceModality;var __awaiter$9=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(base$1,"__esModule",{value:!0}),base$1.MetricBase=void 0;const base_1$j=base,otel_1$u=requireDist$1(),utils_1$3=utils$1;class MetricBase{constructor(e,t,r,n,i){var o,s;this.settings=e,this.meter=t,this.logger=r,this.generalSettings=n,this.started=!1;(new base_1$j.MetricBaseValidator).validate(this),this.filters=null!==(o=null==n?void 0:n.filters)&&void 0!==o?o:[],this.defaultFilters=(null===(s=null==n?void 0:n.useDefaultFilters)||void 0===s||s)&&null!=i?i:[]}getFilter(e){var t,r,n,i,o,s,a,c,l,u,d,h,p;const g=(null!==(r=null===(t=this.filters)||void 0===t?void 0:t.filter(e=>e.overrideDefaultFilters))&&void 0!==r?r:[]).concat((null!==(n=this.defaultFilters)&&void 0!==n?n:[]).map(e=>{var t;return Object.assign(Object.assign({},e),{type:this.settings.type,name:null!==(t=this.settings.name)&&void 0!==t?t:this.settings.type})})).concat(null!==(o=null===(i=this.filters)||void 0===i?void 0:i.filter(e=>!e.overrideDefaultFilters))&&void 0!==o?o:[]).find(t=>{var r,n,i;if(!this.matchStringOrRegex(this.settings.type,t.type))return!1;if(!this.matchStringOrRegex(null!==(r=this.settings.name)&&void 0!==r?r:this.settings.type,t.name))return!1;for(const r of Object.keys(null!==(n=null==t?void 0:t.attributes)&&void 0!==n?n:{}))if(e[r]!==(null!==(i=null==t?void 0:t.attributes)&&void 0!==i?i:{})[r])return!1;return!0});null==g||g.enabled,null==g||g.enabled;let m=null===(s=null==g?void 0:g.enabled)||void 0===s||s;if(!1!==(null==g?void 0:g.enabled)){const e=null!==(u=null!==(a=null==g?void 0:g.sample)&&void 0!==a?a:null===(l=null===(c=this.settings)||void 0===c?void 0:c.publishingSettings)||void 0===l?void 0:l.sample)&&void 0!==u?u:null===(h=null===(d=this.generalSettings)||void 0===d?void 0:d.defaultPublishingSettings)||void 0===h?void 0:h.sample;void 0!==e&&(m=!0===e||!1!==e&&Math.random()<e)}return Object.assign(Object.assign({},g),{enabled:m,type:this.settings.type,name:null!==(p=this.settings.name)&&void 0!==p?p:this.settings.type})}start(){return __awaiter$9(this,void 0,void 0,function*(){try{yield this.createMetric(),yield this.subscribe(),this.started=!0}catch(e){this.settings.type}return Promise.resolve()})}stop(){return __awaiter$9(this,void 0,void 0,function*(){try{yield this.unsubscribe(),yield this.destroyMetric(),this.started=!1}catch(e){this.settings.type}return Promise.resolve()})}createMetric(){const e=this.settings.name||this.settings.type+"-"+this.createUniqueName(10),t=this.settings.description,r=this.settings.unit,n={explicitBucketBoundaries:this.settings.buckets};return this.metricAny=this.createMetricCore(e,{description:t,unit:r,advice:n}),Promise.resolve()}createRecordingMetric(e,t,r){var n;return"histogram"===(null!==(n=this.settings.baseMetricType)&&void 0!==n?n:r)?this.meter.createHistogram(e,t):this.meter.createGauge(e,t)}subscribe(){return Promise.resolve()}unsubscribe(){return Promise.resolve()}destroyMetric(){return Promise.resolve()}getData(){return Object.assign({platformVersion:this.settings.platformVersion,user:this.settings.user},otel_1$u.Container.errorless(this.settings.additionalAttributes))}prePublish(e){var t,r;if(!e)return e;const n=Object.assign(Object.assign({},null===(t=this.generalSettings.defaultPublishingSettings)||void 0===t?void 0:t.attributeSettings),null===(r=this.settings.publishingSettings)||void 0===r?void 0:r.attributeSettings);return(0,utils_1$3.reduceModality)(e,n)}getApplicationData(e){return Object.assign(Object.assign({},this.getData()),{application:e})}getLayoutData(e){return Object.assign(Object.assign({},this.getData()),{layout:e})}createUniqueName(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";let r="";const n=new Uint8Array(e);return crypto.getRandomValues(n),n.forEach(e=>{r+=t[e%52]}),r}matchStringOrRegex(e,t){if(!t)return!0;if("string"==typeof t&&"#"===t[0]){if(null==e||!new RegExp(t.substring(1),"i").test(e+""))return!1}else if(e!==t)return!1;return!0}}base$1.MetricBase=MetricBase,Object.defineProperty(customHistogram,"__esModule",{value:!0}),customHistogram.CustomHistogramMetric=void 0;const base_1$i=base$1;class CustomHistogramMetric extends base_1$i.MetricBase{constructor(e,t,r,n,i){super(e,t,r,n,i),this.meter=t}createMetricCore(e,t){return this.metric=this.meter.createHistogram(e,t)}record(e,t){var r,n;const i=Object.assign(Object.assign({},this.getData()),t);!1!==(null===(r=this.getFilter(i))||void 0===r?void 0:r.enabled)&&(null===(n=this.metric)||void 0===n||n.record(e,this.prePublish(i)))}}customHistogram.CustomHistogramMetric=CustomHistogramMetric;var customUpDownCounter={};Object.defineProperty(customUpDownCounter,"__esModule",{value:!0}),customUpDownCounter.CustomUpDownCounterMetric=void 0;const base_1$h=base$1;class CustomUpDownCounterMetric extends base_1$h.MetricBase{constructor(e,t,r,n,i){super(e,t,r,n,i),this.meter=t}createMetricCore(e,t){return this.metric=this.meter.createUpDownCounter(e,t)}add(e,t){var r,n;const i=Object.assign(Object.assign({},this.getData()),t);!1!==(null===(r=this.getFilter(i))||void 0===r?void 0:r.enabled)&&(null===(n=this.metric)||void 0===n||n.add(e,this.prePublish(i)))}}customUpDownCounter.CustomUpDownCounterMetric=CustomUpDownCounterMetric;var builder$1={},_default={};Object.defineProperty(_default,"__esModule",{value:!0}),_default.DefaultMetricsSettings=void 0;class DefaultMetricsSettings{constructor(){this.unknown="unknown"}get enabled(){return!0}get platformMetricsEnabled(){return!0}get userId(){return this.unknown}get platformVersion(){return this.unknown}get additionalAttributes(){return{}}get metrics(){return[this.getAppCount(),this.getAppCPU(),this.getAppCrash(),this.getAppDuration(),this.getAppDurationSoft(),this.getAppError(),this.getAppMemory(),this.getAppStarted(),this.getAppStartup(),this.getAppStopped(),this.getLayoutStartup(),this.getPlatformError(),this.getPlatformStartup(),this.getSystemCPU(),this.getSystemMemory(),this.getWorkspaceCount(),this.getWorkspaceSelected(),this.getWorkspaceStarted(),this.getWorkspaceStopped(),this.getWorkspaceStartupLegacy(),this.getWorkspaceStartup(),this.getWorkspaceStartupFrame(),this.getWorkspaceStartupFrameInit(),this.getWorkspaceStartupFramePageLoad(),this.getWorkspaceStartupFrameWorkspaceRender(),this.getWorkspaceStartupComponent(),this.getWorkspaceStartupApps()]}getWorkspaceStartupLegacy(){return Object.assign(Object.assign({},this.getSettings("workspace_startup","Time to load the workspace layout","workspace_startup_legacy","ms",[100,1e3,1e4,3e4,6e4])),{enabled:!1})}getWorkspaceStartup(){return this.getSettings("workspace_startup","Time to load the workspace layout","workspace_startup","ms")}getWorkspaceStartupFrame(){return this.getSettings("workspace_startup_frame","Time to load the workspace frame","workspace_startup_frame","ms")}getWorkspaceStartupFrameInit(){return this.getSettings("workspace_startup_frame_init","Time to initialize the workspace frame","workspace_startup_frame_init","ms")}getWorkspaceStartupFramePageLoad(){return this.getSettings("workspace_startup_frame_page_load","Time to load the page for the workspace frame","workspace_startup_frame_page_load","ms")}getWorkspaceStartupFrameWorkspaceRender(){return this.getSettings("workspace_startup_frame_workspace_render","Time to render the workspace frame","workspace_startup_frame_workspace_render","ms")}getWorkspaceStartupComponent(){return this.getSettings("workspace_startup_component","Time to load the workspace layout component","workspace_startup_component","ms")}getWorkspaceStartupApps(){return this.getSettings("workspace_startup_apps","Time to load the workspace applications","workspace_startup_apps","ms")}getAppStarted(){return this.getSettings("app_started","Number of times an application has been started during each platform session","app_started")}getAppStopped(){return this.getSettings("app_stopped","Number of times an application has been stopped during each platform session","app_stopped")}getAppCount(){return this.getSettings("app_count","Number of application instances running in the platform during each platform session","app_count")}getAppStartup(){return this.getSettings("app_startup","Time to load an application","app_startup","ms",[100,1e3,1e4,3e4,6e4])}getAppDuration(){return this.getSettings("app_duration","How long an application has been focused during each platform session","app_duration","ms",[1e3,1e4,3e4,6e4,6e5])}getAppDurationSoft(){return Object.assign(Object.assign({},this.getSettings("app_duration_soft","How long an application has been focused during each platform session (without the currently focused application)","app_duration_soft","ms",[1e3,1e4,3e4,6e4,6e5])),{enabled:!1})}getAppMemory(){return this.getSettings("app_memory","Current app memory usage","app_memory","kb")}getAppCPU(){return this.getSettings("app_cpu","Percentage of CPU used for the last interval.","app_cpu","%")}getAppError(){return this.getSettings("app_error","Number of times app error was received during each platform session","app_error")}getAppCrash(){return this.getSettings("app_crash","Number of times an application crashed during each platform session","app_crash")}getLayoutStartup(){return this.getSettings("layout_startup","Time to load a layout","layout_startup","ms",[100,1e3,1e4,3e4,6e4])}getWorkspaceStarted(){return this.getSettings("workspace_started","Number of times a workspace has been stopped during each platform session","workspace_started")}getWorkspaceStopped(){return this.getSettings("workspace_stopped","Number of times a workspace has been stopped during each platform session","workspace_stopped")}getWorkspaceSelected(){return this.getSettings("workspace_selected","TBD","workspace_selected")}getWorkspaceCount(){return this.getSettings("workspace_count","Number of workspace running in the platform during each platform session","workspace_count")}getPlatformStartup(){return this.getSettings("platform_startup","Time to load the platform","platform_startup","ms")}getPlatformError(){return this.getSettings("platform_error","Number of times platform error was received during each platform session","platform_error")}getSystemMemory(){return this.getSettings("system_memory","Free system memory, used system memory and used platform memory","system_memory","gb")}getSystemCPU(){return this.getSettings("system_cpu","Current and average system CPU and average platform CPU","system_cpu","%")}getSettings(e,t,r,n,i){return{enabled:!0,name:e,description:t,user:this.unknown,platformVersion:this.unknown,type:r,unit:n,buckets:i}}}_default.DefaultMetricsSettings=DefaultMetricsSettings,DefaultMetricsSettings.instance=new DefaultMetricsSettings;var constants$1={};Object.defineProperty(constants$1,"__esModule",{value:!0}),constants$1.Defaults=void 0,constants$1.Defaults={TRACE_VERSION:"00",DEFAULT_USER:"unknown-user",DEFAULT_SERVICE_NAME:"unknown-service-name",DEFAULT_SERVICE_ID:"unknown-service-id",DEFAULT_SERVICE_VERSION:"unknown-service-version",DEFAULT_PLATFORM_VERSION:"unknown-platform-version",DEFAULT_METRIC_DESCRIPTION:"unknown-metric",stopPropagationIfSpanIsDisabled:!1,countMetric:!1,durationMetric:!1,resultMetric:!1,countMetricOnDisabledSpans:!1,durationMetricOnDisabledSpans:!1,resultMetricOnDisabledSpans:!1,maxAttributeDepth:5,otelSpanOptions:{},disablePropagation:!1,addContextToTrace:!0,level:"INFO",forceChildTracing:!1,canBeRoot:!0,currentTracingStateGetterContextName:"interopio.insights.currentTracingStateGetter",minDurationMs:0,log:!1,logOnDisabledSpans:!1},Object.defineProperty(builder$1,"__esModule",{value:!0}),builder$1.MetricsSettingsBuilder=void 0;const default_1$1=_default,constants_1$2=constants$1,otel_1$t=requireDist$1();class MetricsSettingsBuilder{constructor(){this.metrics=new Map,this.defaultSettings=new default_1$1.DefaultMetricsSettings,this.withSettings({enabled:!1,platformVersion:constants_1$2.Defaults.DEFAULT_PLATFORM_VERSION,serviceId:constants_1$2.Defaults.DEFAULT_SERVICE_ID,serviceName:constants_1$2.Defaults.DEFAULT_SERVICE_NAME,userId:constants_1$2.Defaults.DEFAULT_USER,serviceVersion:constants_1$2.Defaults.DEFAULT_SERVICE_VERSION,metrics:this.defaultSettings})}build(){var e,t,r,n,i,o,s,a,c,l,u,d,h,p,g,m,f,y,$,b,w,v,S,E;if(this.platformMetricsEnabled){if(null===(t=this.settings)||void 0===t?void 0:t.useLegacyWorkspaceStartupMetric){this.metrics.set("workspace_startup",this.defaultSettings.getWorkspaceStartupLegacy());const e=null===(n=null===(r=this.settings)||void 0===r?void 0:r.metrics)||void 0===n?void 0:n.find(e=>{var t;return"workspace_startup"===(null!==(t=e.name)&&void 0!==t?t:e.type)});e&&this.withCustomMetric(e)}}else for(const t of this.defaultSettings.metrics)this.metrics.delete(null!==(e=t.name)&&void 0!==e?e:t.type);this.metrics.forEach(e=>{var t;this.metrics.set(null!==(t=e.name)&&void 0!==t?t:e.type,this.convert(e))});const C=null!==(o=null===(i=this.meter)||void 0===i?void 0:i.headers)&&void 0!==o?o:Object.assign(Object.assign({},otel_1$t.Container.errorless(null===(s=this.otelSettings)||void 0===s?void 0:s.headers)),otel_1$t.Container.errorless(null===(a=this.settings)||void 0===a?void 0:a.headers)),_=Object.assign(Object.assign({},this.settings),{enabled:this.enabled,platformMetricsEnabled:this.platformMetricsEnabled,url:null!==(u=null!==(c=this.meter.url)&&void 0!==c?c:null===(l=this.settings)||void 0===l?void 0:l.url)&&void 0!==u?u:"http://localhost:4318/v1/metrics",publishInterval:null!==(p=null!==(d=this.meter.publishInterval)&&void 0!==d?d:null===(h=this.settings)||void 0===h?void 0:h.publishInterval)&&void 0!==p?p:3e4,compression:null!==(g=this.meter.compression)&&void 0!==g?g:null===(m=this.settings)||void 0===m?void 0:m.compression,headers:C,hostname:null!==(f=this.meter.hostname)&&void 0!==f?f:null===(y=this.settings)||void 0===y?void 0:y.hostname,keepAlive:null!==($=this.meter.keepAlive)&&void 0!==$?$:null===(b=this.settings)||void 0===b?void 0:b.keepAlive,concurrencyLimit:null!==(w=this.meter.concurrencyLimit)&&void 0!==w?w:null===(v=this.settings)||void 0===v?void 0:v.concurrencyLimit,timeoutMillis:null!==(S=this.meter.timeoutMillis)&&void 0!==S?S:null===(E=this.settings)||void 0===E?void 0:E.timeoutMillis,metrics:[...this.metrics.values()],additionalAttributes:()=>{var e,t;return Object.assign(Object.assign({},otel_1$t.Container.errorless(null===(e=this.otelSettings)||void 0===e?void 0:e.additionalAttributes)),otel_1$t.Container.errorless(null===(t=this.settings)||void 0===t?void 0:t.additionalAttributes))}});return _}withSettings(e){var t,r,n,i,o,s,a,c,l,u,d,h;const p=this.otelSettings;this.otelSettings=e;const g=this.settings;return this.settings=null==e?void 0:e.metrics,this.withEnabled(null!==(r=null===(t=this.settings)||void 0===t?void 0:t.enabled)&&void 0!==r?r:null==g?void 0:g.enabled).withPlatformMetricsEnabled(null!==(i=null===(n=this.settings)||void 0===n?void 0:n.platformMetricsEnabled)&&void 0!==i?i:null==g?void 0:g.platformMetricsEnabled).withUser(null!==(s=null===(o=this.otelSettings)||void 0===o?void 0:o.userId)&&void 0!==s?s:null==p?void 0:p.userId).withPlatformVersion(null!==(c=null===(a=this.otelSettings)||void 0===a?void 0:a.platformVersion)&&void 0!==c?c:null==p?void 0:p.platformVersion).withAdditionalAttributes(null===(l=this.settings)||void 0===l?void 0:l.additionalAttributes).withCustomMetrics(null===(u=this.settings)||void 0===u?void 0:u.metrics).withMeter(null!==(h=null===(d=this.settings)||void 0===d?void 0:d.meter)&&void 0!==h?h:this.meter)}withEnabled(e){return this.enabled=null!=e?e:this.enabled,this}withUser(e){return this.userId=null!=e?e:this.userId,this.metrics.forEach(e=>{var t;e.user=this.userId,this.metrics.set(null!==(t=e.name)&&void 0!==t?t:e.type,e)}),this}withAdditionalAttributes(e){return this.additionalAttributes=null!=e?e:this.additionalAttributes,this.metrics.forEach(e=>{var t;e.additionalAttributes=this.additionalAttributes,this.metrics.set(null!==(t=e.name)&&void 0!==t?t:e.type,e)}),this}withPlatformVersion(e){return this.platformVersion=null!=e?e:this.platformVersion,this.metrics.forEach(e=>{var t;e.platformVersion=this.platformVersion,this.metrics.set(null!==(t=e.name)&&void 0!==t?t:e.type,e)}),this}withPlatformMetricsEnabled(e){return this.platformMetricsEnabled=null!=e?e:this.platformMetricsEnabled,this}withMeter(e){var t,r,n,i,o,s,a,c,l,u;const d=this.meter;return this.meter=Object.assign(Object.assign(Object.assign({},d),null!=e?e:{}),{url:null!==(t=null==e?void 0:e.url)&&void 0!==t?t:null==d?void 0:d.url,publishInterval:null!==(r=null==e?void 0:e.publishInterval)&&void 0!==r?r:null==d?void 0:d.publishInterval,compression:null!==(o=null!==(n=null==e?void 0:e.compression)&&void 0!==n?n:null===(i=this.settings)||void 0===i?void 0:i.compression)&&void 0!==o?o:null==d?void 0:d.compression,headers:null!==(s=null==e?void 0:e.headers)&&void 0!==s?s:null==d?void 0:d.headers,hostname:null!==(a=null==e?void 0:e.hostname)&&void 0!==a?a:null==d?void 0:d.hostname,keepAlive:null!==(c=null==e?void 0:e.keepAlive)&&void 0!==c?c:null==d?void 0:d.keepAlive,concurrencyLimit:null!==(l=null==e?void 0:e.concurrencyLimit)&&void 0!==l?l:null==d?void 0:d.concurrencyLimit,timeoutMillis:null!==(u=null==e?void 0:e.timeoutMillis)&&void 0!==u?u:null==d?void 0:d.timeoutMillis}),this}withCustomMetrics(e){return(null!=e?e:[]).forEach(e=>this.withCustomMetric(e)),this}withCustomMetric(e){var t,r,n,i;if(!e.name)throw new Error("settings.name is not defined");if(this.metrics.has(null!==(t=e.name)&&void 0!==t?t:e.type)){const t=this.metrics.get(null!==(n=e.name)&&void 0!==n?n:e.type),r=this.mergeSettings(e,t);this.metrics.set(null!==(i=r.name)&&void 0!==i?i:r.type,r)}else{const t=this.convert(e);this.metrics.set(null!==(r=e.name)&&void 0!==r?r:e.type,t)}return this}convert(e){var t,r,n,i;return Object.assign(Object.assign(Object.assign({},this.settings),e),{type:e.type,user:this.userId,enabled:null===(t=e.enabled)||void 0===t||t,name:null!==(r=e.name)&&void 0!==r?r:e.type,description:null!==(n=e.description)&&void 0!==n?n:null!==(i=e.name)&&void 0!==i?i:e.type,platformVersion:this.platformVersion,unit:e.unit,buckets:e.buckets,additionalAttributes:e.additionalAttributes})}mergeSettings(e,t){var r,n,i,o,s;return Object.assign(Object.assign(Object.assign({},t),this.settings),{type:e.type,user:this.userId,enabled:null!==(r=e.enabled)&&void 0!==r?r:t.enabled,name:null!==(n=e.name)&&void 0!==n?n:t.name,description:null!==(i=e.description)&&void 0!==i?i:t.description,platformVersion:this.platformVersion,unit:t.unit,buckets:null!==(o=e.buckets)&&void 0!==o?o:t.buckets,additionalAttributes:null!==(s=e.additionalAttributes)&&void 0!==s?s:t.additionalAttributes})}}builder$1.MetricsSettingsBuilder=MetricsSettingsBuilder;var lazyProvider={};Object.defineProperty(lazyProvider,"__esModule",{value:!0}),lazyProvider.LazyMetricsMeterProvider=void 0;class LazyMetricsMeterProvider{get metricReaders(){return this._metricReaders||this.buildMeterProvider(),this._metricReaders}constructor(e,t){this.meterProviderCreateFunc=e,this.serviceName=t}getMeter(){return this.getMeterProvider().getMeter(this.serviceName)}forceFlush(){return this.getMeterProvider().forceFlush()}getMeterProvider(){return this.meterProvider||this.buildMeterProvider(),this.meterProvider}buildMeterProvider(){const e=this.meterProviderCreateFunc();this.meterProvider=e.meterProvider,this._metricReaders=e.metricReaders}}lazyProvider.LazyMetricsMeterProvider=LazyMetricsMeterProvider;var builder={},factoryBuilder={};Object.defineProperty(factoryBuilder,"__esModule",{value:!0}),factoryBuilder.MetricsFactoryBuilderValidator=void 0;const validator_1$k=validator;class MetricsFactoryBuilderValidator{validate(e){validator_1$k.Validator.throwIfNullOrUndefined(e,"builder"),validator_1$k.Validator.throwIfNullOrUndefined(e.logger,"logger")}validateDependencies(e){validator_1$k.Validator.throwIfNullOrUndefined(e,"dependencyContainer"),validator_1$k.Validator.throwIfNullOrUndefined(e.instanceFocusedHandler,"instanceFocusedHandler"),validator_1$k.Validator.throwIfNullOrUndefined(e.instanceReadyHandler,"instanceReadyHandler"),validator_1$k.Validator.throwIfNullOrUndefined(e.instanceStartedHandler,"instanceStartedHandler"),validator_1$k.Validator.throwIfNullOrUndefined(e.instanceStoppedHandler,"instanceStoppedHandler"),validator_1$k.Validator.throwIfNullOrUndefined(e.layoutRestoredHandler,"layoutRestoredHandler"),validator_1$k.Validator.throwIfNullOrUndefined(e.performanceProvider,"performanceProvider"),validator_1$k.Validator.throwIfNullOrUndefined(e.platformStartedHandler,"platformStartedHandler")}}factoryBuilder.MetricsFactoryBuilderValidator=MetricsFactoryBuilderValidator;var factory$1={},factory={};Object.defineProperty(factory,"__esModule",{value:!0}),factory.MetricsFactoryValidator=void 0;const validator_1$j=validator;class MetricsFactoryValidator{validate(e){validator_1$j.Validator.throwIfNullOrUndefined(e,"factory"),validator_1$j.Validator.throwIfNullOrUndefined(e.metricsFactories,"metricsFactories"),validator_1$j.Validator.throwIfNullOrUndefined(e.logger,"logger")}}factory.MetricsFactoryValidator=MetricsFactoryValidator;var customCounter={};Object.defineProperty(customCounter,"__esModule",{value:!0}),customCounter.CustomCounterMetric=void 0;const base_1$g=base$1;class CustomCounterMetric extends base_1$g.MetricBase{constructor(e,t,r,n,i){super(e,t,r,n,i),this.meter=t}createMetricCore(e,t){return this.metric=this.meter.createCounter(e,t)}add(e,t){var r,n;const i=Object.assign(Object.assign({},this.getData()),t);!1!==(null===(r=this.getFilter(i))||void 0===r?void 0:r.enabled)&&(null===(n=this.metric)||void 0===n||n.add(e,this.prePublish(i)))}}customCounter.CustomCounterMetric=CustomCounterMetric;var customObservableGauge={},observable={},__awaiter$8=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(observable,"__esModule",{value:!0}),observable.ObservableMetricBase=void 0;const base_1$f=base$1,otel_1$s=requireDist$1();class ObservableResultWrapper{constructor(e,t,r,n){this.metric=e,this.innerResult=t,this.data=r,this.getFilter=n}observe(e,t){var r,n;const i=this.metric.prePublish(Object.assign(Object.assign({},this.data),t));!1!==(null===(n=null===(r=this.getFilter)||void 0===r?void 0:r.call(this,i))||void 0===n?void 0:n.enabled)&&this.innerResult.observe(e,i)}}class ObservableMetricBase extends base_1$f.MetricBase{constructor(e,t,r,n,i,o,s,a){super(e,t,r,n,i),this.observeCallback=o,this.subscribeCallback=s,this.unsubcribeCallback=a}createMetric(){const e=Object.create(null,{createMetric:{get:()=>super.createMetric}});return __awaiter$8(this,void 0,void 0,function*(){yield e.createMetric.call(this),this.metric=this.metricAny})}subscribeCore(){return otel_1$s.Container.errorlessAsync(()=>{var e,t;return null!==(t=null===(e=this.subscribeCallback)||void 0===e?void 0:e.call(this))&&void 0!==t?t:Promise.resolve()})}unsubscribeCore(){return otel_1$s.Container.errorlessAsync(()=>{var e,t;return null!==(t=null===(e=this.unsubcribeCallback)||void 0===e?void 0:e.call(this))&&void 0!==t?t:Promise.resolve()})}observeCore(e){const t=new ObservableResultWrapper(this,e,this.getData(),this.getFilter.bind(this));return otel_1$s.Container.errorlessAsync(()=>{var e,r;return null!==(r=null===(e=this.observeCallback)||void 0===e?void 0:e.call(this,t))&&void 0!==r?r:Promise.resolve()})}subscribe(){return __awaiter$8(this,void 0,void 0,function*(){this.observableCallback=this.observe.bind(this),this.metric.addCallback(this.observableCallback),yield this.subscribeCore()})}destroyMetric(){return this.metric.removeCallback(this.observableCallback),Promise.resolve()}unsubscribe(){return this.unsubscribeCore()}observe(e){return __awaiter$8(this,void 0,void 0,function*(){try{yield this.observeCore(e)}catch(e){this.settings.name,this.settings.type}})}}observable.ObservableMetricBase=ObservableMetricBase,Object.defineProperty(customObservableGauge,"__esModule",{value:!0}),customObservableGauge.CustomObservableGaugeMetric=void 0;const observable_1$5=observable;class CustomObservableGaugeMetric extends observable_1$5.ObservableMetricBase{createMetricCore(e,t){var r;return null===(r=this.meter)||void 0===r?void 0:r.createObservableGauge(e,t)}}customObservableGauge.CustomObservableGaugeMetric=CustomObservableGaugeMetric;var customObservableCounter={};Object.defineProperty(customObservableCounter,"__esModule",{value:!0}),customObservableCounter.CustomObservableCounterMetric=void 0;const observable_1$4=observable;class CustomObservableCounterMetric extends observable_1$4.ObservableMetricBase{createMetricCore(e,t){var r;return null===(r=this.meter)||void 0===r?void 0:r.createObservableCounter(e,t)}}customObservableCounter.CustomObservableCounterMetric=CustomObservableCounterMetric;var customObservableUpDownCounter={};Object.defineProperty(customObservableUpDownCounter,"__esModule",{value:!0}),customObservableUpDownCounter.CustomObservableUpDownCounterMetric=void 0;const observable_1$3=observable;class CustomObservableUpDownCounterMetric extends observable_1$3.ObservableMetricBase{createMetricCore(e,t){var r;return null===(r=this.meter)||void 0===r?void 0:r.createObservableUpDownCounter(e,t)}}customObservableUpDownCounter.CustomObservableUpDownCounterMetric=CustomObservableUpDownCounterMetric;var customGauge={};Object.defineProperty(customGauge,"__esModule",{value:!0}),customGauge.CustomGaugeMetric=void 0;const base_1$e=base$1;class CustomGaugeMetric extends base_1$e.MetricBase{constructor(e,t,r,n,i){super(e,t,r,n,i),this.meter=t}createMetricCore(e,t){return this.metric=this.meter.createGauge(e,t)}record(e,t){var r,n;const i=Object.assign(Object.assign({},this.getData()),t);!1!==(null===(r=this.getFilter(i))||void 0===r?void 0:r.enabled)&&(null===(n=this.metric)||void 0===n||n.record(e,this.prePublish(i)))}}customGauge.CustomGaugeMetric=CustomGaugeMetric;var __importDefault$1=commonjsGlobal$1&&commonjsGlobal$1.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(factory$1,"__esModule",{value:!0}),factory$1.MetricsFactory=void 0;const factory_1$1=factory,otel_1$r=requireDist$1(),customCounter_1=customCounter,customHistogram_1=customHistogram,customUpDownCounter_1=customUpDownCounter,customObservableGauge_1=customObservableGauge,customObservableCounter_1=customObservableCounter,customObservableUpDownCounter_1=customObservableUpDownCounter,customGauge_1=customGauge,otel_2=requireDist$1(),default_1=_default,lodash_clonedeep_1$1=__importDefault$1(lodash_clonedeepExports);class MetricsFactory{constructor(e,t,r){this.logger=e,this.metricsFactories=t,this.meter=r;(new factory_1$1.MetricsFactoryValidator).validate(this)}create(e,t,r,n,i){var o;const s=e.type;e.name=null!==(o=e.name)&&void 0!==o?o:s,~s.indexOf("observable")&&!r&&otel_2.Container.errorless(()=>{throw new Error(`Metric type ${s} requires observeCallback argument to be provided.`)});if(this.metricsFactories.has(s)){const r=(new default_1.DefaultMetricsSettings).metrics.find(e=>e.name===s),n=this.metricsFactories.get(s),i=(0,lodash_clonedeep_1$1.default)(e);for(const e of Object.keys(i))void 0===i[e]&&delete i[e];return n(Object.assign(Object.assign({},r),i),t)}if("custom_observable_gauge"===s)return new customObservableGauge_1.CustomObservableGaugeMetric(e,this.meter,this.logger,t,[],r,n,i);if("custom_observable_counter"===s)return new customObservableCounter_1.CustomObservableCounterMetric(e,this.meter,this.logger,t,[],r,n,i);if("custom_observable_up_down_counter"===s)return new customObservableUpDownCounter_1.CustomObservableUpDownCounterMetric(e,this.meter,this.logger,t,[],r,n,i);if("custom_counter"===s)return new customCounter_1.CustomCounterMetric(e,this.meter,this.logger,t);if("custom_gauge"===s)return new customGauge_1.CustomGaugeMetric(e,this.meter,this.logger,t);if("custom_up_down_counter"===s)return new customUpDownCounter_1.CustomUpDownCounterMetric(e,this.meter,this.logger,t);if("custom_histogram"===s)return new customHistogram_1.CustomHistogramMetric(e,this.meter,this.logger,t);return this.createNullMetric(e,"not supported")}createNullMetric(e,t){this.logger.debug(`cannot create ${e.name} metric, reason: ${t}`);return new otel_1$r.NullMetric(e,this.logger)}}factory$1.MetricsFactory=MetricsFactory;var count$3={},count$2={};Object.defineProperty(count$2,"__esModule",{value:!0}),count$2.ApplicationCountMetricValidator=void 0;const validator_1$i=validator;class ApplicationCountMetricValidator{validate(e){validator_1$i.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$i.Validator.throwIfNullOrUndefined(e.instanceStartedHandler,"instanceStartedHandler"),validator_1$i.Validator.throwIfNullOrUndefined(e.instanceStoppedHandler,"instanceStoppedHandler")}validateInstanceStarted(e){validator_1$i.Validator.throwIfNullOrUndefined(e,"args"),validator_1$i.Validator.throwIfNullOrUndefined(e.application,"application")}validateInstanceStopped(e){validator_1$i.Validator.throwIfNullOrUndefined(e,"args"),validator_1$i.Validator.throwIfNullOrUndefined(e.application,"application")}}count$2.ApplicationCountMetricValidator=ApplicationCountMetricValidator,Object.defineProperty(count$3,"__esModule",{value:!0}),count$3.ApplicationCountMetric=void 0;const base_1$d=base$1,count_1$2=count$2,otel_1$q=requireDist$1();class ApplicationCountMetric extends base_1$d.MetricBase{constructor(e,t,r,n,i,o,s){super(e,t,r,n,s),this.meter=t,this.instanceStartedHandler=i,this.instanceStoppedHandler=o,this.validator=new count_1$2.ApplicationCountMetricValidator,this.validator.validate(this)}createMetricCore(e,t){return this.appCountMetric=this.meter.createUpDownCounter(e,t)}subscribe(){return this.instanceStartedUn=otel_1$q.Container.errorless(()=>this.instanceStartedHandler(this.handleInstanceStarted.bind(this))),this.instanceStoppedUn=otel_1$q.Container.errorless(()=>this.instanceStoppedHandler(this.handleInstanceStopped.bind(this))),Promise.resolve()}unsubscribe(){return otel_1$q.Container.errorless(()=>this.instanceStartedUn),otel_1$q.Container.errorless(()=>this.instanceStoppedUn),Promise.resolve()}destroyMetric(){return Promise.resolve()}handleInstanceStarted(e){var t;try{this.validator.validateInstanceStarted(e);const r=this.getApplicationData(e.application);if(!1===(null===(t=this.getFilter(r))||void 0===t?void 0:t.enabled))return;this.appCountMetric.add(1,this.prePublish(r))}catch(e){this.settings.type}}handleInstanceStopped(e){var t;try{this.validator.validateInstanceStopped(e);const r=this.getApplicationData(e.application);if(!1===(null===(t=this.getFilter(r))||void 0===t?void 0:t.enabled))return;this.appCountMetric.add(-1,this.prePublish(r))}catch(e){this.settings.type}}}count$3.ApplicationCountMetric=ApplicationCountMetric;var cpu$1={},zeroOutClosedAppObservableGaugeMetricBase={},__awaiter$7=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(zeroOutClosedAppObservableGaugeMetricBase,"__esModule",{value:!0}),zeroOutClosedAppObservableGaugeMetricBase.ZeroOutClosedAppObservableGaugeMetricBase=void 0;const observable_1$2=observable;class ZeroOutClosedAppObservableGaugeMetricBase extends observable_1$2.ObservableMetricBase{observeCore(e){var t;return __awaiter$7(this,void 0,void 0,function*(){const r=yield this.observeCoreCore(e);if(this.reported)for(const n of this.reported.filter(e=>!r.some(t=>e.instance===t.instance))){const r=Object.assign({applicationInstance:n.instance},this.getApplicationData(n.app));!1!==(null===(t=this.getFilter(r))||void 0===t?void 0:t.enabled)&&e.observe(0,this.prePublish(r))}this.reported=r})}createMetricCore(e,t){return this.meter.createObservableGauge(e,t)}}zeroOutClosedAppObservableGaugeMetricBase.ZeroOutClosedAppObservableGaugeMetricBase=ZeroOutClosedAppObservableGaugeMetricBase;var perf={};Object.defineProperty(perf,"__esModule",{value:!0}),perf.PerformanceProviderValidator=void 0;const validator_1$h=validator;class PerformanceProviderValidator{validate(e){validator_1$h.Validator.throwIfNullOrUndefined(e,"performanceProvider")}validateAppsCPU(e){validator_1$h.Validator.throwIfNullOrUndefined(e,"data"),e.forEach(e=>{validator_1$h.Validator.throwIfNullOrUndefined(e,"item"),validator_1$h.Validator.throwIfNullOrUndefined(e.app,"app"),validator_1$h.Validator.throwIfNullOrUndefined(e.instance,"instance"),validator_1$h.Validator.throwIfNullOrUndefined(e.cpu,"cpu")})}validateAppsMemory(e){validator_1$h.Validator.throwIfNullOrUndefined(e,"data"),e.forEach(e=>{validator_1$h.Validator.throwIfNullOrUndefined(e,"item"),validator_1$h.Validator.throwIfNullOrUndefined(e.app,"app"),validator_1$h.Validator.throwIfNullOrUndefined(e.instance,"instance"),validator_1$h.Validator.throwIfNullOrUndefined(e.memory,"memory")})}validateSystemCPU(e){validator_1$h.Validator.throwIfNullOrUndefined(e,"data"),validator_1$h.Validator.throwIfNullOrUndefined(e.current,"current"),validator_1$h.Validator.throwIfNullOrUndefined(e.average,"average"),validator_1$h.Validator.throwIfNullOrUndefined(e.platform,"platform")}validateSystemMemory(e){validator_1$h.Validator.throwIfNullOrUndefined(e,"data"),validator_1$h.Validator.throwIfNullOrUndefined(e.platformTotal,"platformTotal"),validator_1$h.Validator.throwIfNullOrUndefined(e.systemFree,"systemFree"),validator_1$h.Validator.throwIfNullOrUndefined(e.systemTotal,"systemTotal")}}perf.PerformanceProviderValidator=PerformanceProviderValidator;var __awaiter$6=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(cpu$1,"__esModule",{value:!0}),cpu$1.ApplicationCPUMetric=void 0;const zeroOutClosedAppObservableGaugeMetricBase_1$1=zeroOutClosedAppObservableGaugeMetricBase,otel_1$p=requireDist$1(),perf_1$3=perf,validator_1$g=validator;class ApplicationCPUMetric extends zeroOutClosedAppObservableGaugeMetricBase_1$1.ZeroOutClosedAppObservableGaugeMetricBase{constructor(e,t,r,n,i,o){super(e,t,r,n,o),this.perfProvider=i}subscribeCore(){return Promise.resolve()}observeCoreCore(e){return __awaiter$6(this,void 0,void 0,function*(){const t=new perf_1$3.PerformanceProviderValidator;t.validate(this.perfProvider);const r=yield otel_1$p.Container.errorlessAsync(()=>this.perfProvider.getAppsCPU());return validator_1$g.Validator.isNullOrUndefined(r)?[]:(t.validateAppsCPU(r),r.forEach(t=>{var r;const n=Object.assign({applicationInstance:t.instance},this.getApplicationData(t.app));!1!==(null===(r=this.getFilter(n))||void 0===r?void 0:r.enabled)&&e.observe(t.cpu,this.prePublish(n))}),r)})}unsubscribeCore(){return Promise.resolve()}}cpu$1.ApplicationCPUMetric=ApplicationCPUMetric;var crash$1={},crash={};Object.defineProperty(crash,"__esModule",{value:!0}),crash.PlatformCrashMetricValidator=void 0;const validator_1$f=validator;class PlatformCrashMetricValidator{validate(e){validator_1$f.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$f.Validator.throwIfNullOrUndefined(e.instanceCrashHandler,"applicationCrashHandler")}validateApplicationCrash(e){validator_1$f.Validator.throwIfNullOrUndefined(e,"args"),validator_1$f.Validator.throwIfNullOrUndefined(e.application,"application")}}crash.PlatformCrashMetricValidator=PlatformCrashMetricValidator,Object.defineProperty(crash$1,"__esModule",{value:!0}),crash$1.ApplicationCrashMetric=void 0;const base_1$c=base$1,crash_1$1=crash,otel_1$o=requireDist$1();class ApplicationCrashMetric extends base_1$c.MetricBase{constructor(e,t,r,n,i,o){super(e,t,r,n,o),this.meter=t,this.instanceCrashHandler=i,this.validator=new crash_1$1.PlatformCrashMetricValidator,this.validator.validate(this)}createMetricCore(e,t){return this.applicationCrashMetric=this.meter.createCounter(e,t)}subscribe(){return this.applicationCrashUn=otel_1$o.Container.errorless(()=>this.instanceCrashHandler(this.handleInstanceCrash.bind(this))),Promise.resolve()}destroyMetric(){return Promise.resolve()}unsubscribe(){return otel_1$o.Container.errorless(()=>{var e;return null===(e=this.applicationCrashUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}handleInstanceCrash(e){var t;try{this.validator.validateApplicationCrash(e);const r=Object.assign({reason:e.reason},this.getApplicationData(e.application));if(!1===(null===(t=this.getFilter(r))||void 0===t?void 0:t.enabled))return;this.applicationCrashMetric.add(1,this.prePublish(r))}catch(e){this.settings.type}}}crash$1.ApplicationCrashMetric=ApplicationCrashMetric;var duration$1={},duration={};Object.defineProperty(duration,"__esModule",{value:!0}),duration.ApplicationDurationMetricValidator=void 0;const validator_1$e=validator;class ApplicationDurationMetricValidator{validate(e){validator_1$e.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$e.Validator.throwIfNullOrUndefined(e.instanceFocusHandler,"instanceFocusHandler")}validateFocusChanged(e){validator_1$e.Validator.throwIfNullOrUndefined(e,"args"),validator_1$e.Validator.throwIfNullOrUndefined(e.application,"application"),validator_1$e.Validator.throwIfNullOrUndefined(e.focused,"focused")}}duration.ApplicationDurationMetricValidator=ApplicationDurationMetricValidator,Object.defineProperty(duration$1,"__esModule",{value:!0}),duration$1.ApplicationDurationMetric=void 0;const validator_1$d=validator,duration_1$2=duration,observable_1$1=observable,otel_1$n=requireDist$1();class ApplicationDurationMetric extends observable_1$1.ObservableMetricBase{constructor(e,t,r,n,i,o){super(e,t,r,n,o),this.instanceFocusHandler=i,this.focusedTimes=new Map,this.validator=new duration_1$2.ApplicationDurationMetricValidator,this.validator.validate(this)}createMetricCore(e,t){return this.appDurationMetric=this.createRecordingMetric(e,t,"gauge"),this.meter.createObservableGauge(this.createUniqueName(10))}sendMetric(e,t){e.forEach(e=>{this.appDurationMetric.record(e,this.prePublish(t))})}observeCore(){return this.focusedTimes.forEach((e,t)=>{var r;const n=this.getApplicationData(t);!1!==(null===(r=this.getFilter(n))||void 0===r?void 0:r.enabled)&&(this.sendMetric(e,this.prePublish(n)),e.splice(0))}),Promise.resolve()}subscribeCore(){return this.unInstanceFocusHandler=otel_1$n.Container.errorless(()=>this.instanceFocusHandler(this.handleFocusChanged.bind(this))),Promise.resolve()}unsubscribeCore(){return otel_1$n.Container.errorless(()=>{var e;return null===(e=this.unInstanceFocusHandler)||void 0===e?void 0:e.call(this)}),Promise.resolve()}handleFocusChanged(e){try{return this.validator.validateFocusChanged(e),this.handleFocusChangedCore(e)}catch(e){this.settings.type}}handleFocusChangedCore(e){const t=e.focused,r=e.application;if(t)this.handleGotFocus(r);else try{this.handleLostFocus(r)}finally{this.currentFocusedApp=void 0}}handleGotFocus(e){const t=(new Date).getTime();this.currentFocusedApp={name:e,gotFocusTime:t},this.focusedTimes.has(this.currentFocusedApp.name)||this.focusedTimes.set(this.currentFocusedApp.name,[])}handleLostFocus(e){if(validator_1$d.Validator.isNullOrUndefined(this.currentFocusedApp))throw new Error(`cannot handle focus lost for application ${e} since there is no previous got focus event`);const t=this.currentFocusedApp.name,r=this.currentFocusedApp.gotFocusTime;if(e!==t)throw new Error(`cannot handle focus lost for application ${e} since the previous got focus event had come from application ${t}`);if(!this.focusedTimes.has(e))throw new Error(`there is no got focus event for ${e}`);this.addFocusLostEventCore(t,r)}addFocusLostEventCore(e,t){const r=(new Date).getTime()-t;this.focusedTimes.get(e).push(r)}}duration$1.ApplicationDurationMetric=ApplicationDurationMetric;var durationSoft={},__awaiter$5=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(durationSoft,"__esModule",{value:!0}),durationSoft.ApplicationDurationSoftMetric=void 0;const duration_1$1=duration$1;class ApplicationDurationSoftMetric extends duration_1$1.ApplicationDurationMetric{observeCore(){const e=Object.create(null,{observeCore:{get:()=>super.observeCore}});return __awaiter$5(this,void 0,void 0,function*(){const t=void 0!==this.currentFocusedApp,r=t?this.currentFocusedApp.name:void 0;return t&&this.handleFocusChanged({application:r,focused:!1}),yield e.observeCore.call(this),t&&this.handleFocusChanged({application:r,focused:!0}),Promise.resolve()})}}durationSoft.ApplicationDurationSoftMetric=ApplicationDurationSoftMetric;var error$3={},error$2={};Object.defineProperty(error$2,"__esModule",{value:!0}),error$2.ApplicationErrorMetricValidator=void 0;const validator_1$c=validator;class ApplicationErrorMetricValidator{validate(e){validator_1$c.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$c.Validator.throwIfNullOrUndefined(e.instanceErrorHandler,"appErrorHandler")}validateApplicationError(e){validator_1$c.Validator.throwIfNullOrUndefined(e,"args"),validator_1$c.Validator.throwIfNullOrUndefined(e.application,"application")}}error$2.ApplicationErrorMetricValidator=ApplicationErrorMetricValidator,Object.defineProperty(error$3,"__esModule",{value:!0}),error$3.ApplicationErrorMetric=void 0;const base_1$b=base$1,error_1$2=error$2,otel_1$m=requireDist$1();class ApplicationErrorMetric extends base_1$b.MetricBase{constructor(e,t,r,n,i,o){super(e,t,r,n,o),this.meter=t,this.instanceErrorHandler=i,this.validator=new error_1$2.ApplicationErrorMetricValidator,this.validator.validate(this)}createMetricCore(e,t){return this.appErrorMetric=this.meter.createCounter(e,t)}subscribe(){return this.appErrorUn=otel_1$m.Container.errorless(()=>this.instanceErrorHandler(this.instanceApplicationError.bind(this))),Promise.resolve()}destroyMetric(){return Promise.resolve()}unsubscribe(){return otel_1$m.Container.errorless(()=>{var e;return null===(e=this.appErrorUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}instanceApplicationError(e){var t;try{this.validator.validateApplicationError(e);const r=this.getApplicationData(e.application);if(!1===(null===(t=this.getFilter(r))||void 0===t?void 0:t.enabled))return;this.appErrorMetric.add(1,this.prePublish(r))}catch(e){this.settings.type}}}error$3.ApplicationErrorMetric=ApplicationErrorMetric;var memory$1={},__awaiter$4=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(memory$1,"__esModule",{value:!0}),memory$1.ApplicationMemoryMetric=void 0;const perf_1$2=perf,validator_1$b=validator,zeroOutClosedAppObservableGaugeMetricBase_1=zeroOutClosedAppObservableGaugeMetricBase,otel_1$l=requireDist$1();class ApplicationMemoryMetric extends zeroOutClosedAppObservableGaugeMetricBase_1.ZeroOutClosedAppObservableGaugeMetricBase{constructor(e,t,r,n,i,o){super(e,t,r,n,o),this.perfProvider=i,this.validator=new perf_1$2.PerformanceProviderValidator,this.validator.validate(this.perfProvider)}subscribeCore(){return Promise.resolve()}observeCoreCore(e){return __awaiter$4(this,void 0,void 0,function*(){const t=yield otel_1$l.Container.errorlessAsync(()=>this.perfProvider.getAppsMemory());return validator_1$b.Validator.isNullOrUndefined(t)?[]:(this.validator.validateAppsMemory(t),t.forEach(t=>{var r,n;const i=Object.assign({applicationInstance:t.instance},this.getApplicationData(t.app));!1!==(null===(r=this.getFilter(i))||void 0===r?void 0:r.enabled)&&e.observe(null!==(n=t.memory)&&void 0!==n?n:0,this.prePublish(i))}),t)})}unsubscribeCore(){return Promise.resolve()}}memory$1.ApplicationMemoryMetric=ApplicationMemoryMetric;var started$2={},started$1={};Object.defineProperty(started$1,"__esModule",{value:!0}),started$1.ApplicationStartedMetricValidator=void 0;const validator_1$a=validator;class ApplicationStartedMetricValidator{validate(e){validator_1$a.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$a.Validator.throwIfNullOrUndefined(e.instanceStartedHandler,"instanceStartedHandler")}validateInstanceStarted(e){validator_1$a.Validator.throwIfNullOrUndefined(e,"args"),validator_1$a.Validator.throwIfNullOrUndefined(e.application,"application")}}started$1.ApplicationStartedMetricValidator=ApplicationStartedMetricValidator,Object.defineProperty(started$2,"__esModule",{value:!0}),started$2.ApplicationStartedMetric=void 0;const base_1$a=base$1,started_1$1=started$1,otel_1$k=requireDist$1();class ApplicationStartedMetric extends base_1$a.MetricBase{constructor(e,t,r,n,i,o){super(e,t,r,n,o),this.meter=t,this.instanceStartedHandler=i,this.validator=new started_1$1.ApplicationStartedMetricValidator,this.validator.validate(this)}createMetricCore(e,t){return this.appStartedMetric=this.meter.createCounter(e,t)}subscribe(){return this.instanceStartedUn=otel_1$k.Container.errorless(()=>this.instanceStartedHandler(this.handleInstanceStarted.bind(this))),Promise.resolve()}destroyMetric(){return Promise.resolve()}unsubscribe(){return otel_1$k.Container.errorless(()=>{var e;return null===(e=this.instanceStartedUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}handleInstanceStarted(e){var t;try{this.validator.validateInstanceStarted(e);const r=this.getApplicationData(e.application);if(!1===(null===(t=this.getFilter(r))||void 0===t?void 0:t.enabled))return;this.appStartedMetric.add(1,this.prePublish(r))}catch(e){this.settings.type}}}started$2.ApplicationStartedMetric=ApplicationStartedMetric;var startup$3={},startupHistogram$1={};Object.defineProperty(startupHistogram$1,"__esModule",{value:!0}),startupHistogram$1.ApplicationStartupHistogramMetricValidator=void 0;const validator_1$9=validator;class ApplicationStartupHistogramMetricValidator{validate(e){validator_1$9.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$9.Validator.throwIfNullOrUndefined(e.instanceReadyHandler,"instanceReadyHandler")}validateInstanceReady(e){validator_1$9.Validator.throwIfNullOrUndefined(e,"args"),validator_1$9.Validator.throwIfNullOrUndefined(e.application,"application"),validator_1$9.Validator.throwIfNullOrUndefined(e.startTime,"startTime"),validator_1$9.Validator.throwIfNullOrUndefined(e.endTime,"endTime")}}startupHistogram$1.ApplicationStartupHistogramMetricValidator=ApplicationStartupHistogramMetricValidator,Object.defineProperty(startup$3,"__esModule",{value:!0}),startup$3.ApplicationStartupMetric=void 0;const startupHistogram_1$1=startupHistogram$1,base_1$9=base$1,otel_1$j=requireDist$1();class ApplicationStartupMetric extends base_1$9.MetricBase{constructor(e,t,r,n,i,o){super(e,t,r,n,o),this.meter=t,this.instanceReadyHandler=i,this.validator=new startupHistogram_1$1.ApplicationStartupHistogramMetricValidator,this.validator.validate(this)}createMetricCore(e,t){return this.appStartupMetric=this.createRecordingMetric(e,t,"gauge")}subscribe(){return this.instanceReadyUn=otel_1$j.Container.errorless(()=>this.instanceReadyHandler(this.handleInstanceReady.bind(this))),Promise.resolve()}unsubscribe(){return otel_1$j.Container.errorless(()=>{var e;return null===(e=this.instanceReadyUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}destroyMetric(){return Promise.resolve()}handleInstanceReady(e){var t;try{this.validator.validateInstanceReady(e);const r=e.endTime.getTime()-e.startTime.getTime(),n=Object.assign({api:e.api},this.getApplicationData(e.application));if(!1===(null===(t=this.getFilter(n))||void 0===t?void 0:t.enabled))return;this.appStartupMetric.record(r,this.prePublish(n))}catch(e){this.settings.type}}}startup$3.ApplicationStartupMetric=ApplicationStartupMetric;var stopped$2={},stopped$1={};Object.defineProperty(stopped$1,"__esModule",{value:!0}),stopped$1.ApplicationStoppedMetricValidator=void 0;const validator_1$8=validator;class ApplicationStoppedMetricValidator{validate(e){validator_1$8.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$8.Validator.throwIfNullOrUndefined(e.instanceStoppedHandler,"instanceStoppedHandler")}validateInstanceStopped(e){validator_1$8.Validator.throwIfNullOrUndefined(e,"args"),validator_1$8.Validator.throwIfNullOrUndefined(e.application,"application")}}stopped$1.ApplicationStoppedMetricValidator=ApplicationStoppedMetricValidator,Object.defineProperty(stopped$2,"__esModule",{value:!0}),stopped$2.ApplicationStoppedMetric=void 0;const base_1$8=base$1,stopped_1$1=stopped$1,otel_1$i=requireDist$1();class ApplicationStoppedMetric extends base_1$8.MetricBase{constructor(e,t,r,n,i,o){super(e,t,r,n,o),this.meter=t,this.instanceStoppedHandler=i,this.validator=new stopped_1$1.ApplicationStoppedMetricValidator,this.validator.validate(this)}createMetricCore(e,t){return this.appStoppedMetric=this.meter.createCounter(e,t)}subscribe(){return this.instanceStoppedUn=otel_1$i.Container.errorless(()=>this.instanceStoppedHandler(this.handleInstanceStopped.bind(this))),Promise.resolve()}unsubscribe(){return otel_1$i.Container.errorless(()=>{var e;return null===(e=this.instanceStoppedUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}destroyMetric(){return Promise.resolve()}handleInstanceStopped(e){var t;try{this.validator.validateInstanceStopped(e);const r=this.getApplicationData(e.application);if(!1===(null===(t=this.getFilter(r))||void 0===t?void 0:t.enabled))return;this.appStoppedMetric.add(1,this.prePublish(r))}catch(e){this.settings.type}}}stopped$2.ApplicationStoppedMetric=ApplicationStoppedMetric;var startup$2={},startupHistogram={};Object.defineProperty(startupHistogram,"__esModule",{value:!0}),startupHistogram.LayoutStartupMetricHistogramValidator=void 0;const validator_1$7=validator;class LayoutStartupMetricHistogramValidator{validate(e){validator_1$7.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$7.Validator.throwIfNullOrUndefined(e.layoutRestoredHandler,"layoutRestoredHandler")}validateLayoutRestored(e){validator_1$7.Validator.throwIfNullOrUndefined(e,"args"),validator_1$7.Validator.throwIfNullOrUndefined(e.layout,"layout"),validator_1$7.Validator.throwIfNullOrUndefined(e.startTime,"startTime"),validator_1$7.Validator.throwIfNullOrUndefined(e.endTime,"endTime")}}startupHistogram.LayoutStartupMetricHistogramValidator=LayoutStartupMetricHistogramValidator,Object.defineProperty(startup$2,"__esModule",{value:!0}),startup$2.LayoutStartupMetric=void 0;const startupHistogram_1=startupHistogram,base_1$7=base$1,otel_1$h=requireDist$1();class LayoutStartupMetric extends base_1$7.MetricBase{constructor(e,t,r,n,i,o){super(e,t,r,n,o),this.meter=t,this.layoutRestoredHandler=i,this.validator=new startupHistogram_1.LayoutStartupMetricHistogramValidator,this.validator.validate(this)}createMetricCore(e,t){return this.layoutStartupMetric=this.createRecordingMetric(e,t,"gauge")}subscribe(){return this.layoutRestoredUn=otel_1$h.Container.errorless(()=>this.layoutRestoredHandler(this.handleLayoutRestored.bind(this))),Promise.resolve()}unsubscribe(){return otel_1$h.Container.errorless(()=>{var e;return null===(e=this.layoutRestoredUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}handleLayoutRestored(e){var t;try{this.validator.validateLayoutRestored(e);const r=e.endTime.getTime()-e.startTime.getTime(),n=this.getLayoutData(e.layout);if(!1===(null===(t=this.getFilter(n))||void 0===t?void 0:t.enabled))return;this.layoutStartupMetric.record(r,this.prePublish(n))}catch(e){this.settings.type}}}startup$2.LayoutStartupMetric=LayoutStartupMetric;var error$1={},error={};Object.defineProperty(error,"__esModule",{value:!0}),error.PlatformErrorMetricValidator=void 0;const validator_1$6=validator;class PlatformErrorMetricValidator{validate(e){validator_1$6.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$6.Validator.throwIfNullOrUndefined(e.platformErrorHandler,"platformErrorHandler")}validatePlatformError(e){validator_1$6.Validator.throwIfNullOrUndefined(e,"args")}}error.PlatformErrorMetricValidator=PlatformErrorMetricValidator,Object.defineProperty(error$1,"__esModule",{value:!0}),error$1.PlatformErrorMetric=void 0;const base_1$6=base$1,error_1$1=error,otel_1$g=requireDist$1();class PlatformErrorMetric extends base_1$6.MetricBase{constructor(e,t,r,n,i,o){super(e,t,r,n,o),this.meter=t,this.platformErrorHandler=i,this.validator=new error_1$1.PlatformErrorMetricValidator,this.validator.validate(this)}createMetricCore(e,t){return this.platformErrorMetric=this.meter.createCounter(e,t)}subscribe(){return this.platformErrorUn=otel_1$g.Container.errorless(()=>this.platformErrorHandler(this.handlePlatformError.bind(this))),Promise.resolve()}unsubscribe(){var e;return null===(e=this.platformErrorUn)||void 0===e||e.call(this),Promise.resolve()}handlePlatformError(e){var t;try{this.validator.validatePlatformError(e);const r=this.getData();if(!1===(null===(t=this.getFilter(r))||void 0===t?void 0:t.enabled))return;this.platformErrorMetric.add(1,this.prePublish(r))}catch(e){this.settings.type}}}error$1.PlatformErrorMetric=PlatformErrorMetric;var startup$1={},startup={};Object.defineProperty(startup,"__esModule",{value:!0}),startup.PlatformStartupMetricValidator=void 0;const validator_1$5=validator;class PlatformStartupMetricValidator{validate(e){validator_1$5.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$5.Validator.throwIfNullOrUndefined(e.platformStartedHandler,"platformStartedHandler")}validatePlatformStarted(e){validator_1$5.Validator.throwIfNullOrUndefined(e,"args"),validator_1$5.Validator.throwIfNullOrUndefined(e.startTime,"startTime"),validator_1$5.Validator.throwIfNullOrUndefined(e.endTime,"endTime"),validator_1$5.Validator.throwIfNullOrUndefined(e.api,"api")}}startup.PlatformStartupMetricValidator=PlatformStartupMetricValidator,Object.defineProperty(startup$1,"__esModule",{value:!0}),startup$1.PlatformStartupMetric=void 0;const startup_1$2=startup,otel_1$f=requireDist$1(),base_1$5=base$1;class PlatformStartupMetric extends base_1$5.MetricBase{constructor(e,t,r,n,i,o){super(e,t,r,n,o),this.platformStartedHandler=i,this.validator=new startup_1$2.PlatformStartupMetricValidator,this.validator.validate(this)}createMetricCore(e,t){return this.platformStartupMetric=this.createRecordingMetric(e,t,"gauge")}subscribe(){return this.platformStartedUn=otel_1$f.Container.errorless(()=>this.platformStartedHandler(this.handlePlatformStarted.bind(this))),Promise.resolve()}unsubscribe(){return otel_1$f.Container.errorless(()=>{var e;return null===(e=this.platformStartedUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}handlePlatformStarted(e){var t,r;try{this.validator.validatePlatformStarted(e),this.startupTime=e.endTime.getTime()-e.startTime.getTime()-(null!==(t=e.idleTimeMs)&&void 0!==t?t:0),this.apiVersion=e.api;const n=Object.assign({api:this.apiVersion},this.getData());if(!1===(null===(r=this.getFilter(n))||void 0===r?void 0:r.enabled))return;this.platformStartupMetric.record(this.startupTime,this.prePublish(n))}catch(e){this.settings.type}}}startup$1.PlatformStartupMetric=PlatformStartupMetric;var cpu={},observableGauge={};Object.defineProperty(observableGauge,"__esModule",{value:!0}),observableGauge.ObservableGaugeMetricBase=void 0;const observable_1=observable;class ObservableGaugeMetricBase extends observable_1.ObservableMetricBase{createMetricCore(e,t){return this.meter.createObservableGauge(e,t)}}observableGauge.ObservableGaugeMetricBase=ObservableGaugeMetricBase;var __awaiter$3=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(cpu,"__esModule",{value:!0}),cpu.SystemCPUMetric=void 0;const observableGauge_1$1=observableGauge,perf_1$1=perf,validator_1$4=validator,otel_1$e=requireDist$1();class SystemCPUMetric extends observableGauge_1$1.ObservableGaugeMetricBase{constructor(e,t,r,n,i,o){super(e,t,r,n,o),this.perfProvider=i,this.validator=new perf_1$1.PerformanceProviderValidator,this.validator.validate(this.perfProvider)}observeCore(e){return __awaiter$3(this,void 0,void 0,function*(){const t=yield otel_1$e.Container.errorlessAsync(()=>this.perfProvider.getSystemCPU());validator_1$4.Validator.isNullOrUndefined(t)||(this.validator.validateSystemCPU(t),this.sendMetrics(t,e))})}sendMetrics(e,t){var r;let n=this.getData();!1!==(null===(r=this.getFilter(n))||void 0===r?void 0:r.enabled)&&(n=this.prePublish(n),this.settings.name,t.observe(e.current,Object.assign({type:"current_system_cpu"},n)),t.observe(e.average,Object.assign({type:"average_system_cpu"},n)),t.observe(e.platform,Object.assign({type:"average_platform_cpu"},n)))}}cpu.SystemCPUMetric=SystemCPUMetric;var memory={},__awaiter$2=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(memory,"__esModule",{value:!0}),memory.SystemMemoryMetric=void 0;const observableGauge_1=observableGauge,perf_1=perf,validator_1$3=validator,otel_1$d=requireDist$1();class SystemMemoryMetric extends observableGauge_1.ObservableGaugeMetricBase{constructor(e,t,r,n,i,o){super(e,t,r,n,o),this.perfProvider=i,this.validator=new perf_1.PerformanceProviderValidator,this.validator.validate(this.perfProvider)}observeCore(e){return __awaiter$2(this,void 0,void 0,function*(){const t=yield otel_1$d.Container.errorlessAsync(()=>this.perfProvider.getSystemMemory());validator_1$3.Validator.isNullOrUndefined(t)||(this.validator.validateSystemMemory(t),this.sendMetrics(t,e))})}sendMetrics(e,t){var r;let n=this.getData();if(!1===(null===(r=this.getFilter(n))||void 0===r?void 0:r.enabled))return;n=this.prePublish(n),this.settings.name,t.observe(e.platformTotal,Object.assign({type:"used_platform_memory"},n));const i=e.systemTotal-e.systemFree;t.observe(i,Object.assign({type:"used_system_memory"},n)),t.observe(e.systemFree,Object.assign({type:"free_system_memory"},n))}}memory.SystemMemoryMetric=SystemMemoryMetric;var count$1={},count={};Object.defineProperty(count,"__esModule",{value:!0}),count.WorkspaceCountMetricValidator=void 0;const validator_1$2=validator;class WorkspaceCountMetricValidator{validate(e){validator_1$2.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$2.Validator.throwIfNullOrUndefined(e.workspaceStartedHandler,"workspaceStartedHandler"),validator_1$2.Validator.throwIfNullOrUndefined(e.workspaceStoppedHandler,"workspaceStoppedHandler")}validateWorkspaceSaved(e){validator_1$2.Validator.throwIfNullOrUndefined(e,"args"),validator_1$2.Validator.throwIfNullOrUndefined(e.layout,"layout")}validateWorkspaceStarted(e){validator_1$2.Validator.throwIfNullOrUndefined(e,"args"),validator_1$2.Validator.throwIfNullOrUndefined(e.layout,"layout")}validateWorkspaceStopped(e){validator_1$2.Validator.throwIfNullOrUndefined(e,"args"),validator_1$2.Validator.throwIfNullOrUndefined(e.layout,"layout")}}count.WorkspaceCountMetricValidator=WorkspaceCountMetricValidator,Object.defineProperty(count$1,"__esModule",{value:!0}),count$1.WorkspaceCountMetric=void 0;const base_1$4=base$1,count_1$1=count,otel_1$c=requireDist$1();class WorkspaceCountMetric extends base_1$4.MetricBase{constructor(e,t,r,n,i,o,s,a,c){super(e,t,r,n,c),this.meter=t,this.workspaceSavedHandler=i,this.workspaceStartedHandler=o,this.workspaceRestoredHandler=s,this.workspaceStoppedHandler=a,this.validator=new count_1$1.WorkspaceCountMetricValidator,this.validator.validate(this)}createMetricCore(e,t){return this.workspaceCountMetric=this.meter.createUpDownCounter(e,t)}subscribe(){return this.workspaceStartedUn=otel_1$c.Container.errorless(()=>this.workspaceStartedHandler(this.handleWorkspaceStarted.bind(this))),this.workspaceRestoredUn=otel_1$c.Container.errorless(()=>this.workspaceRestoredHandler(this.handleWorkspaceStarted.bind(this))),this.workspaceStoppedUn=otel_1$c.Container.errorless(()=>this.workspaceStoppedHandler(this.handleWorkspaceStopped.bind(this))),this.workspaceSavedUn=otel_1$c.Container.errorless(()=>this.workspaceSavedHandler(this.handleWorkspaceSaved.bind(this))),Promise.resolve()}unsubscribe(){return otel_1$c.Container.errorless(()=>{var e;return null===(e=this.workspaceStartedUn)||void 0===e?void 0:e.call(this)}),otel_1$c.Container.errorless(()=>{var e;return null===(e=this.workspaceRestoredUn)||void 0===e?void 0:e.call(this)}),otel_1$c.Container.errorless(()=>{var e;return null===(e=this.workspaceStoppedUn)||void 0===e?void 0:e.call(this)}),otel_1$c.Container.errorless(()=>{var e;return null===(e=this.workspaceSavedUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}handleWorkspaceSaved(e){var t;try{this.validator.validateWorkspaceSaved(e);const r=this.getLayoutData(e.layout);if(!1===(null===(t=this.getFilter(r))||void 0===t?void 0:t.enabled))return;if(e.oldLayout){const t=this.getLayoutData(e.oldLayout);this.workspaceCountMetric.add(-1,t)}this.workspaceCountMetric.add(1,this.prePublish(r))}catch(e){this.settings.type}}handleWorkspaceStarted(e){var t;try{this.validator.validateWorkspaceStarted(e);const r=this.getLayoutData(e.layout);if(!1===(null===(t=this.getFilter(r))||void 0===t?void 0:t.enabled))return;this.workspaceCountMetric.add(1,this.prePublish(r))}catch(e){this.settings.type}}handleWorkspaceStopped(e){var t;try{this.validator.validateWorkspaceStopped(e);const r=this.getLayoutData(e.layout);if(!1===(null===(t=this.getFilter(r))||void 0===t?void 0:t.enabled))return;this.workspaceCountMetric.add(-1,this.prePublish(r))}catch(e){this.settings.type}}}count$1.WorkspaceCountMetric=WorkspaceCountMetric;var started={},startedOrStoppedMetric={};Object.defineProperty(startedOrStoppedMetric,"__esModule",{value:!0}),startedOrStoppedMetric.WorkspaceStartedOrStoppedMetricValidator=void 0;const validator_1$1=validator;class WorkspaceStartedOrStoppedMetricValidator{validate(e){validator_1$1.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$1.Validator.throwIfNullOrUndefined(e.workspaceActionHandler,"workspaceActionHandler")}validateWorkspaceStarted(e){validator_1$1.Validator.throwIfNullOrUndefined(e,"args")}validateWorkspaceStopped(e){validator_1$1.Validator.throwIfNullOrUndefined(e,"args"),validator_1$1.Validator.throwIfNullOrUndefined(e.layout,"layout")}}startedOrStoppedMetric.WorkspaceStartedOrStoppedMetricValidator=WorkspaceStartedOrStoppedMetricValidator,Object.defineProperty(started,"__esModule",{value:!0}),started.WorkspaceStartedMetric=void 0;const base_1$3=base$1,startedOrStoppedMetric_1$1=startedOrStoppedMetric,otel_1$b=requireDist$1();class WorkspaceStartedMetric extends base_1$3.MetricBase{constructor(e,t,r,n,i,o,s){super(e,t,r,n,s),this.meter=t,this.workspaceActionHandler=i,this.workspaceRestoredHandler=o,this.validator=new startedOrStoppedMetric_1$1.WorkspaceStartedOrStoppedMetricValidator,this.validator.validate(this)}createMetricCore(e,t){return this.workspaceStartedMetric=this.meter.createCounter(e,t)}subscribe(){return this.workspaceStartedUn=otel_1$b.Container.errorless(()=>this.workspaceActionHandler(this.handleWorkspaceStarted.bind(this))),this.workspaceRestoredUn=otel_1$b.Container.errorless(()=>this.workspaceRestoredHandler(this.handleWorkspaceStarted.bind(this))),Promise.resolve()}unsubscribe(){return otel_1$b.Container.errorless(()=>{var e;return null===(e=this.workspaceStartedUn)||void 0===e?void 0:e.call(this)}),otel_1$b.Container.errorless(()=>{var e;return null===(e=this.workspaceRestoredUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}handleWorkspaceStarted(e){var t;try{this.validator.validateWorkspaceStarted(e);const r=this.getLayoutData(e.layout);if(!1===(null===(t=this.getFilter(r))||void 0===t?void 0:t.enabled))return;this.workspaceStartedMetric.add(1,this.prePublish(r))}catch(e){this.settings.type}}}started.WorkspaceStartedMetric=WorkspaceStartedMetric;var startupLegacy={};Object.defineProperty(startupLegacy,"__esModule",{value:!0}),startupLegacy.WorkspaceStartupHistogramMetric=void 0;const startup_1$1=startup$2;class WorkspaceStartupHistogramMetric extends startup_1$1.LayoutStartupMetric{constructor(e,t,r,n,i,o,s){super(e,t,r,n,e=>{const t=this.workspaceLoadedHandler(e),r=this.workspaceRestoredHandler(e);return()=>{t(),r()}},s),this.workspaceLoadedHandler=i,this.workspaceRestoredHandler=o}}startupLegacy.WorkspaceStartupHistogramMetric=WorkspaceStartupHistogramMetric;var stopped={};Object.defineProperty(stopped,"__esModule",{value:!0}),stopped.WorkspaceStoppedMetric=void 0;const base_1$2=base$1,startedOrStoppedMetric_1=startedOrStoppedMetric,otel_1$a=requireDist$1();class WorkspaceStoppedMetric extends base_1$2.MetricBase{constructor(e,t,r,n,i,o){super(e,t,r,n,o),this.meter=t,this.workspaceActionHandler=i,this.validator=new startedOrStoppedMetric_1.WorkspaceStartedOrStoppedMetricValidator,this.validator.validate(this)}createMetricCore(e,t){return this.workspaceStoppedMetric=this.meter.createCounter(e,t)}subscribe(){return this.workspaceStoppedUn=otel_1$a.Container.errorless(()=>this.workspaceActionHandler(this.handleWorkspaceStopped.bind(this))),Promise.resolve()}unsubscribe(){return otel_1$a.Container.errorless(()=>{var e;return null===(e=this.workspaceStoppedUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}handleWorkspaceStopped(e){var t;try{this.validator.validateWorkspaceStopped(e);const r=this.getLayoutData(e.layout);if(!1===(null===(t=this.getFilter(r))||void 0===t?void 0:t.enabled))return;this.workspaceStoppedMetric.add(1,this.prePublish(r))}catch(e){this.settings.type}}}stopped.WorkspaceStoppedMetric=WorkspaceStoppedMetric;var selected={};Object.defineProperty(selected,"__esModule",{value:!0}),selected.WorkspaceSelectedMetric=void 0;const base_1$1=base$1,otel_1$9=requireDist$1();class WorkspaceSelectedMetric extends base_1$1.MetricBase{constructor(e,t,r,n,i,o){super(e,t,r,n,o),this.meter=t,this.workspaceActionHandler=i}createMetricCore(e,t){return this.workspaceSelectedMetric=this.meter.createCounter(e,t)}subscribe(){return this.workspaceSelectedUn=otel_1$9.Container.errorless(()=>this.workspaceActionHandler(this.handleSelectedStopped.bind(this))),Promise.resolve()}unsubscribe(){return otel_1$9.Container.errorless(()=>{var e;return null===(e=this.workspaceSelectedUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}handleSelectedStopped(e){var t;try{const r=this.getLayoutData(e.layout);if(!1===(null===(t=this.getFilter(r))||void 0===t?void 0:t.enabled))return;this.workspaceSelectedMetric.add(1,this.prePublish(r))}catch(e){this.settings.type}}}selected.WorkspaceSelectedMetric=WorkspaceSelectedMetric;var timedGauge={};Object.defineProperty(timedGauge,"__esModule",{value:!0}),timedGauge.WorkspaceTimedGaugeMetric=void 0;const base_1=base$1,otel_1$8=requireDist$1();class WorkspaceTimedGaugeMetric extends base_1.MetricBase{constructor(e,t,r,n,i,o,s){super(e,r,n,t,o),this.subscriber=i,this.getAttributes=s,s||(this.getAttributes=e=>{const t=Object.assign({},e);return delete t.startTime,delete t.endTime,t})}createMetricCore(e,t){return this.metric=this.createRecordingMetric(e,t,"gauge")}subscribe(){return this.unsubscribeCallback=otel_1$8.Container.errorless(()=>this.subscriber(this.handler.bind(this))),Promise.resolve()}unsubscribe(){return otel_1$8.Container.errorless(()=>{var e;return null===(e=this.unsubscribeCallback)||void 0===e?void 0:e.call(this)}),Promise.resolve()}handler(e){var t,r;try{const n=this.getLayoutData(e.layout),i=Object.assign(Object.assign({},n),null===(t=this.getAttributes)||void 0===t?void 0:t.call(this,e));if(!1===(null===(r=this.getFilter(i))||void 0===r?void 0:r.enabled))return;const o=e.endTime.getTime()-e.startTime.getTime();this.metric.record(o,this.prePublish(i))}catch(e){this.settings.type}}}timedGauge.WorkspaceTimedGaugeMetric=WorkspaceTimedGaugeMetric,Object.defineProperty(builder,"__esModule",{value:!0}),builder.MetricsFactoryBuilder=void 0;const factoryBuilder_1=factoryBuilder,factory_1=factory$1,count_1=count$3,cpu_1=cpu$1,crash_1=crash$1,duration_1=duration$1,durationSoft_1=durationSoft,error_1=error$3,memory_1=memory$1,started_1=started$2,startup_1=startup$3,stopped_1=stopped$2,startup_2=startup$2,error_2=error$1,startup_3=startup$1,cpu_2=cpu,memory_2=memory,count_2=count$1,started_2=started,startupLegacy_1=startupLegacy,stopped_2=stopped,selected_1=selected,timedGauge_1=timedGauge;class MetricsFactoryBuilder{constructor(e,t,r){this.lazyMeterProvider=e,this.dependencyContainer=t,this.logger=r,this.metricsFactories=new Map,this.metricsFactories=new Map}get meter(){return this.lazyMeterProvider.getMeter()}build(){(new factoryBuilder_1.MetricsFactoryBuilderValidator).validate(this);return new factory_1.MetricsFactory(this.logger,this.metricsFactories,this.meter)}withDefaults(){return this.withAppStarted().withAppStopped().withAppStartup().withAppCount().withAppDuration().withAppDurationSoft().withAppMemory().withAppCPU().withSystemMemory().withSystemCPU().withAppError().withAppCrash().withLayoutStartup().withWorkspaceStartupLegacy().withWorkspaceStarted().withWorkspaceStopped().withWorkspaceSelected().withWorkspaceCount().withWorkspaceMetric("workspace_startup",e=>e.workspaceStartupHandler,[{attributes:{complexLoad:!0},enabled:!1}]).withWorkspaceMetric("workspace_startup_frame",e=>e.workspaceFrameCreatedHandler,[{attributes:{complexLoad:!0},enabled:!1}]).withWorkspaceMetric("workspace_startup_frame_init",e=>e.workspaceFrameInitHandler,[{attributes:{complexLoad:!0},enabled:!1}]).withWorkspaceMetric("workspace_startup_frame_page_load",e=>e.workspaceFramePageLoadHandler,[{attributes:{complexLoad:!0},enabled:!1}]).withWorkspaceMetric("workspace_startup_frame_workspace_render",e=>e.workspaceFrameWorkspaceRenderHandler,[{attributes:{complexLoad:!0},enabled:!1}]).withWorkspaceMetric("workspace_startup_component",e=>e.workspaceComponentCreatedHandler,[{attributes:{complexLoad:!0},enabled:!1}]).withWorkspaceMetric("workspace_startup_apps",e=>e.workspaceAppsStartedHandler,[{attributes:{complexLoad:!0},enabled:!1}]).withPlatformStartup().withPlatformError()}withWorkspaceMetric(e,t,r,n){return this.metricsFactories.set(e,((e,i)=>new timedGauge_1.WorkspaceTimedGaugeMetric(e,i,this.meter,this.logger,t(this.dependencyContainer),r,n)).bind(this)),this}withAppStarted(){return this.metricsFactories.set("app_started",((e,t)=>new started_1.ApplicationStartedMetric(e,this.meter,this.logger,t,this.dependencyContainer.instanceStartedHandler)).bind(this)),this}withAppStopped(){return this.metricsFactories.set("app_stopped",((e,t)=>new stopped_1.ApplicationStoppedMetric(e,this.meter,this.logger,t,this.dependencyContainer.instanceStoppedHandler)).bind(this)),this}withAppStartup(){return this.metricsFactories.set("app_startup",((e,t)=>new startup_1.ApplicationStartupMetric(e,this.meter,this.logger,t,this.dependencyContainer.instanceReadyHandler)).bind(this)),this}withAppCount(){return this.metricsFactories.set("app_count",((e,t)=>new count_1.ApplicationCountMetric(e,this.meter,this.logger,t,this.dependencyContainer.instanceStartedHandler,this.dependencyContainer.instanceStoppedHandler)).bind(this)),this}withAppDuration(){return this.metricsFactories.set("app_duration",((e,t)=>new duration_1.ApplicationDurationMetric(e,this.meter,this.logger,t,this.dependencyContainer.instanceFocusedHandler)).bind(this)),this}withAppDurationSoft(){return this.metricsFactories.set("app_duration_soft",((e,t)=>new durationSoft_1.ApplicationDurationSoftMetric(e,this.meter,this.logger,t,this.dependencyContainer.instanceFocusedHandler)).bind(this)),this}withAppMemory(){return this.metricsFactories.set("app_memory",((e,t)=>new memory_1.ApplicationMemoryMetric(e,this.meter,this.logger,t,this.dependencyContainer.performanceProvider)).bind(this)),this}withAppCPU(){return this.metricsFactories.set("app_cpu",((e,t)=>new cpu_1.ApplicationCPUMetric(e,this.meter,this.logger,t,this.dependencyContainer.performanceProvider)).bind(this)),this}withAppError(){return this.metricsFactories.set("app_error",((e,t)=>new error_1.ApplicationErrorMetric(e,this.meter,this.logger,t,this.dependencyContainer.instanceErrorHandler)).bind(this)),this}withAppCrash(){return this.metricsFactories.set("app_crash",((e,t)=>new crash_1.ApplicationCrashMetric(e,this.meter,this.logger,t,this.dependencyContainer.instanceCrashHandler)).bind(this)),this}withSystemMemory(){return this.metricsFactories.set("system_memory",((e,t)=>new memory_2.SystemMemoryMetric(e,this.meter,this.logger,t,this.dependencyContainer.performanceProvider)).bind(this)),this}withSystemCPU(){return this.metricsFactories.set("system_cpu",((e,t)=>new cpu_2.SystemCPUMetric(e,this.meter,this.logger,t,this.dependencyContainer.performanceProvider)).bind(this)),this}withLayoutStartup(){return this.metricsFactories.set("layout_startup",((e,t)=>new startup_2.LayoutStartupMetric(e,this.meter,this.logger,t,this.dependencyContainer.layoutRestoredHandler)).bind(this)),this}withWorkspaceStartupLegacy(){return this.metricsFactories.set("workspace_startup_legacy",((e,t)=>new startupLegacy_1.WorkspaceStartupHistogramMetric(e,this.meter,this.logger,t,this.dependencyContainer.workspaceLoadedHandler,this.dependencyContainer.workspaceRestoredHandler)).bind(this)),this}withWorkspaceStarted(){return this.metricsFactories.set("workspace_started",((e,t)=>new started_2.WorkspaceStartedMetric(e,this.meter,this.logger,t,this.dependencyContainer.workspaceStartedHandler,this.dependencyContainer.workspaceRestoredHandler)).bind(this)),this}withWorkspaceStopped(){return this.metricsFactories.set("workspace_stopped",((e,t)=>new stopped_2.WorkspaceStoppedMetric(e,this.meter,this.logger,t,this.dependencyContainer.workspaceStoppedHandler)).bind(this)),this}withWorkspaceSelected(){return this.metricsFactories.set("workspace_selected",((e,t)=>new selected_1.WorkspaceSelectedMetric(e,this.meter,this.logger,t,this.dependencyContainer.workspaceSelectedHandler)).bind(this)),this}withWorkspaceCount(){return this.metricsFactories.set("workspace_count",((e,t)=>new count_2.WorkspaceCountMetric(e,this.meter,this.logger,t,this.dependencyContainer.workspaceSavedHandler,this.dependencyContainer.workspaceStartedHandler,this.dependencyContainer.workspaceRestoredHandler,this.dependencyContainer.workspaceStoppedHandler)).bind(this)),this}withPlatformStartup(){return this.metricsFactories.set("platform_startup",((e,t)=>new startup_3.PlatformStartupMetric(e,this.meter,this.logger,t,this.dependencyContainer.platformStartedHandler)).bind(this)),this}withPlatformError(){return this.metricsFactories.set("platform_error",((e,t)=>new error_2.PlatformErrorMetric(e,this.meter,this.logger,t,this.dependencyContainer.platformErrorHandler)).bind(this)),this}}builder.MetricsFactoryBuilder=MetricsFactoryBuilder;var providerFactory={},AggregationTemporality$2,InstrumentType$2,DataPointType$2;function hashAttributes(e){let t=Object.keys(e);return 0===t.length?"":(t=t.sort(),JSON.stringify(t.map(t=>[t,e[t]])))}function instrumentationScopeId(e){return`${e.name}:${e.version??""}:${e.schemaUrl??""}`}!function(e){e[e.DELTA=0]="DELTA",e[e.CUMULATIVE=1]="CUMULATIVE"}(AggregationTemporality$2||(AggregationTemporality$2={})),function(e){e.COUNTER="COUNTER",e.GAUGE="GAUGE",e.HISTOGRAM="HISTOGRAM",e.UP_DOWN_COUNTER="UP_DOWN_COUNTER",e.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",e.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",e.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"}(InstrumentType$2||(InstrumentType$2={})),function(e){e[e.HISTOGRAM=0]="HISTOGRAM",e[e.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",e[e.GAUGE=2]="GAUGE",e[e.SUM=3]="SUM"}(DataPointType$2||(DataPointType$2={}));let TimeoutError$1=class e extends Error{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype)}};function callWithTimeout$1(e,t){let r;const n=new Promise(function(e,n){r=setTimeout(function(){n(new TimeoutError$1("Operation timed out."))},t)});return Promise.race([e,n]).then(e=>(clearTimeout(r),e),e=>{throw clearTimeout(r),e})}function setEquals(e,t){if(e.size!==t.size)return!1;for(const r of e)if(!t.has(r))return!1;return!0}function binarySearchUB(e,t){let r=0,n=e.length-1,i=e.length;for(;n>=r;){const o=r+Math.trunc((n-r)/2);e[o]<t?r=o+1:(i=o,n=o-1)}return i}function equalsCaseInsensitive(e,t){return e.toLowerCase()===t.toLowerCase()}var AggregatorKind;!function(e){e[e.DROP=0]="DROP",e[e.SUM=1]="SUM",e[e.LAST_VALUE=2]="LAST_VALUE",e[e.HISTOGRAM=3]="HISTOGRAM",e[e.EXPONENTIAL_HISTOGRAM=4]="EXPONENTIAL_HISTOGRAM"}(AggregatorKind||(AggregatorKind={}));class DropAggregator{kind=AggregatorKind.DROP;createAccumulation(){}merge(e,t){}diff(e,t){}toMetricData(e,t,r,n){}}function createNewEmptyCheckpoint(e){const t=e.map(()=>0);return t.push(0),{buckets:{boundaries:e,counts:t},sum:0,count:0,hasMinMax:!1,min:1/0,max:-1/0}}class HistogramAccumulation{startTime;_boundaries;_recordMinMax;_current;constructor(e,t,r=!0,n=createNewEmptyCheckpoint(t)){this.startTime=e,this._boundaries=t,this._recordMinMax=r,this._current=n}record(e){if(Number.isNaN(e))return;this._current.count+=1,this._current.sum+=e,this._recordMinMax&&(this._current.min=Math.min(e,this._current.min),this._current.max=Math.max(e,this._current.max),this._current.hasMinMax=!0);const t=binarySearchUB(this._boundaries,e);this._current.buckets.counts[t]+=1}setStartTime(e){this.startTime=e}toPointValue(){return this._current}}class HistogramAggregator{kind=AggregatorKind.HISTOGRAM;_boundaries;_recordMinMax;constructor(e,t){this._boundaries=e,this._recordMinMax=t}createAccumulation(e){return new HistogramAccumulation(e,this._boundaries,this._recordMinMax)}merge(e,t){const r=e.toPointValue(),n=t.toPointValue(),i=r.buckets.counts,o=n.buckets.counts,s=new Array(i.length);for(let e=0;e<i.length;e++)s[e]=i[e]+o[e];let a=1/0,c=-1/0;return this._recordMinMax&&(r.hasMinMax&&n.hasMinMax?(a=Math.min(r.min,n.min),c=Math.max(r.max,n.max)):r.hasMinMax?(a=r.min,c=r.max):n.hasMinMax&&(a=n.min,c=n.max)),new HistogramAccumulation(e.startTime,r.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:r.buckets.boundaries,counts:s},count:r.count+n.count,sum:r.sum+n.sum,hasMinMax:this._recordMinMax&&(r.hasMinMax||n.hasMinMax),min:a,max:c})}diff(e,t){const r=e.toPointValue(),n=t.toPointValue(),i=r.buckets.counts,o=n.buckets.counts,s=new Array(i.length);for(let e=0;e<i.length;e++)s[e]=o[e]-i[e];return new HistogramAccumulation(t.startTime,r.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:r.buckets.boundaries,counts:s},count:n.count-r.count,sum:n.sum-r.sum,hasMinMax:!1,min:1/0,max:-1/0})}toMetricData(e,t,r,n){return{descriptor:e,aggregationTemporality:t,dataPointType:DataPointType$2.HISTOGRAM,dataPoints:r.map(([t,r])=>{const i=r.toPointValue(),o=e.type===InstrumentType$2.GAUGE||e.type===InstrumentType$2.UP_DOWN_COUNTER||e.type===InstrumentType$2.OBSERVABLE_GAUGE||e.type===InstrumentType$2.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:t,startTime:r.startTime,endTime:n,value:{min:i.hasMinMax?i.min:void 0,max:i.hasMinMax?i.max:void 0,sum:o?void 0:i.sum,buckets:i.buckets,count:i.count}}})}}}class Buckets{backing;indexBase;indexStart;indexEnd;constructor(e=new BucketsBacking,t=0,r=0,n=0){this.backing=e,this.indexBase=t,this.indexStart=r,this.indexEnd=n}get offset(){return this.indexStart}get length(){return 0===this.backing.length||this.indexEnd===this.indexStart&&0===this.at(0)?0:this.indexEnd-this.indexStart+1}counts(){return Array.from({length:this.length},(e,t)=>this.at(t))}at(e){const t=this.indexBase-this.indexStart;return e<t&&(e+=this.backing.length),e-=t,this.backing.countAt(e)}incrementBucket(e,t){this.backing.increment(e,t)}decrementBucket(e,t){this.backing.decrement(e,t)}trim(){for(let e=0;e<this.length;e++){if(0!==this.at(e)){this.indexStart+=e;break}if(e===this.length-1)return void(this.indexStart=this.indexEnd=this.indexBase=0)}for(let e=this.length-1;e>=0;e--)if(0!==this.at(e)){this.indexEnd-=this.length-e-1;break}this._rotate()}downscale(e){this._rotate();const t=1+this.indexEnd-this.indexStart,r=1<<e;let n=0,i=0;for(let e=this.indexStart;e<=this.indexEnd;){let o=e%r;o<0&&(o+=r);for(let s=o;s<r&&n<t;s++)this._relocateBucket(i,n),n++,e++;i++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart}clone(){return new Buckets(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)}_rotate(){const e=this.indexBase-this.indexStart;0!==e&&(e>0?(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,e),this.backing.reverse(e,this.backing.length)):(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,this.backing.length+e)),this.indexBase=this.indexStart)}_relocateBucket(e,t){e!==t&&this.incrementBucket(e,this.backing.emptyBucket(t))}}class BucketsBacking{_counts;constructor(e=[0]){this._counts=e}get length(){return this._counts.length}countAt(e){return this._counts[e]}growTo(e,t,r){const n=new Array(e).fill(0);n.splice(r,this._counts.length-t,...this._counts.slice(t)),n.splice(0,t,...this._counts.slice(0,t)),this._counts=n}reverse(e,t){const r=Math.floor((e+t)/2)-e;for(let n=0;n<r;n++){const r=this._counts[e+n];this._counts[e+n]=this._counts[t-n-1],this._counts[t-n-1]=r}}emptyBucket(e){const t=this._counts[e];return this._counts[e]=0,t}increment(e,t){this._counts[e]+=t}decrement(e,t){this._counts[e]>=t?this._counts[e]-=t:this._counts[e]=0}clone(){return new BucketsBacking([...this._counts])}}const SIGNIFICAND_WIDTH=52,EXPONENT_MASK=2146435072,SIGNIFICAND_MASK=1048575,EXPONENT_BIAS=1023,MIN_NORMAL_EXPONENT=1-EXPONENT_BIAS,MAX_NORMAL_EXPONENT=EXPONENT_BIAS,MIN_VALUE=Math.pow(2,-1022);function getNormalBase2(e){const t=new DataView(new ArrayBuffer(8));t.setFloat64(0,e);return((t.getUint32(0)&EXPONENT_MASK)>>20)-EXPONENT_BIAS}function getSignificand(e){const t=new DataView(new ArrayBuffer(8));t.setFloat64(0,e);const r=t.getUint32(0),n=t.getUint32(4);return(r&SIGNIFICAND_MASK)*Math.pow(2,32)+n}function ldexp(e,t){return 0===e||e===Number.POSITIVE_INFINITY||e===Number.NEGATIVE_INFINITY||Number.isNaN(e)?e:e*Math.pow(2,t)}function nextGreaterSquare(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,++e}class MappingError extends Error{}class ExponentMapping{_shift;constructor(e){this._shift=-e}mapToIndex(e){if(e<MIN_VALUE)return this._minNormalLowerBoundaryIndex();return getNormalBase2(e)+this._rightShift(getSignificand(e)-1,SIGNIFICAND_WIDTH)>>this._shift}lowerBoundary(e){const t=this._minNormalLowerBoundaryIndex();if(e<t)throw new MappingError(`underflow: ${e} is < minimum lower boundary: ${t}`);const r=this._maxNormalLowerBoundaryIndex();if(e>r)throw new MappingError(`overflow: ${e} is > maximum lower boundary: ${r}`);return ldexp(1,e<<this._shift)}get scale(){return 0===this._shift?0:-this._shift}_minNormalLowerBoundaryIndex(){let e=MIN_NORMAL_EXPONENT>>this._shift;return this._shift<2&&e--,e}_maxNormalLowerBoundaryIndex(){return MAX_NORMAL_EXPONENT>>this._shift}_rightShift(e,t){return Math.floor(e*Math.pow(2,-t))}}class LogarithmMapping{_scale;_scaleFactor;_inverseFactor;constructor(e){this._scale=e,this._scaleFactor=ldexp(Math.LOG2E,e),this._inverseFactor=ldexp(Math.LN2,-e)}mapToIndex(e){if(e<=MIN_VALUE)return this._minNormalLowerBoundaryIndex()-1;if(0===getSignificand(e)){return(getNormalBase2(e)<<this._scale)-1}const t=Math.floor(Math.log(e)*this._scaleFactor),r=this._maxNormalLowerBoundaryIndex();return t>=r?r:t}lowerBoundary(e){const t=this._maxNormalLowerBoundaryIndex();if(e>=t){if(e===t)return 2*Math.exp((e-(1<<this._scale))/this._scaleFactor);throw new MappingError(`overflow: ${e} is > maximum lower boundary: ${t}`)}const r=this._minNormalLowerBoundaryIndex();if(e<=r){if(e===r)return MIN_VALUE;if(e===r-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new MappingError(`overflow: ${e} is < minimum lower boundary: ${r}`)}return Math.exp(e*this._inverseFactor)}get scale(){return this._scale}_minNormalLowerBoundaryIndex(){return MIN_NORMAL_EXPONENT<<this._scale}_maxNormalLowerBoundaryIndex(){return(MAX_NORMAL_EXPONENT+1<<this._scale)-1}}const MIN_SCALE=-10,MAX_SCALE$1=20,PREBUILT_MAPPINGS=Array.from({length:31},(e,t)=>t>10?new LogarithmMapping(t-10):new ExponentMapping(t-10));function getMapping(e){if(e>MAX_SCALE$1||e<MIN_SCALE)throw new MappingError(`expected scale >= ${MIN_SCALE} && <= ${MAX_SCALE$1}, got: ${e}`);return PREBUILT_MAPPINGS[e+10]}class HighLow{static combine(e,t){return new HighLow(Math.min(e.low,t.low),Math.max(e.high,t.high))}low;high;constructor(e,t){this.low=e,this.high=t}}const MAX_SCALE=20,DEFAULT_MAX_SIZE=160,MIN_MAX_SIZE=2;class ExponentialHistogramAccumulation{startTime;_maxSize;_recordMinMax;_sum;_count;_zeroCount;_min;_max;_positive;_negative;_mapping;constructor(e,t=DEFAULT_MAX_SIZE,r=!0,n=0,i=0,o=0,s=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY,c=new Buckets,l=new Buckets,u=getMapping(MAX_SCALE)){this.startTime=e,this._maxSize=t,this._recordMinMax=r,this._sum=n,this._count=i,this._zeroCount=o,this._min=s,this._max=a,this._positive=c,this._negative=l,this._mapping=u,this._maxSize<MIN_MAX_SIZE&&(diag.warn(`Exponential Histogram Max Size set to ${this._maxSize}, changing to the minimum size of: ${MIN_MAX_SIZE}`),this._maxSize=MIN_MAX_SIZE)}record(e){this.updateByIncrement(e,1)}setStartTime(e){this.startTime=e}toPointValue(){return{hasMinMax:this._recordMinMax,min:this.min,max:this.max,sum:this.sum,positive:{offset:this.positive.offset,bucketCounts:this.positive.counts()},negative:{offset:this.negative.offset,bucketCounts:this.negative.counts()},count:this.count,scale:this.scale,zeroCount:this.zeroCount}}get sum(){return this._sum}get min(){return this._min}get max(){return this._max}get count(){return this._count}get zeroCount(){return this._zeroCount}get scale(){return this._count===this._zeroCount?0:this._mapping.scale}get positive(){return this._positive}get negative(){return this._negative}updateByIncrement(e,t){Number.isNaN(e)||(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=t,0!==e?(this._sum+=e*t,e>0?this._updateBuckets(this._positive,e,t):this._updateBuckets(this._negative,-e,t)):this._zeroCount+=t)}merge(e){0===this._count?(this._min=e.min,this._max=e.max):0!==e.count&&(e.min<this.min&&(this._min=e.min),e.max>this.max&&(this._max=e.max)),this.startTime=e.startTime,this._sum+=e.sum,this._count+=e.count,this._zeroCount+=e.zeroCount;const t=this._minScale(e);this._downscale(this.scale-t),this._mergeBuckets(this.positive,e,e.positive,t),this._mergeBuckets(this.negative,e,e.negative,t)}diff(e){this._min=1/0,this._max=-1/0,this._sum-=e.sum,this._count-=e.count,this._zeroCount-=e.zeroCount;const t=this._minScale(e);this._downscale(this.scale-t),this._diffBuckets(this.positive,e,e.positive,t),this._diffBuckets(this.negative,e,e.negative,t)}clone(){return new ExponentialHistogramAccumulation(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)}_updateBuckets(e,t,r){let n=this._mapping.mapToIndex(t),i=!1,o=0,s=0;if(0===e.length?(e.indexStart=n,e.indexEnd=e.indexStart,e.indexBase=e.indexStart):n<e.indexStart&&e.indexEnd-n>=this._maxSize?(i=!0,s=n,o=e.indexEnd):n>e.indexEnd&&n-e.indexStart>=this._maxSize&&(i=!0,s=e.indexStart,o=n),i){const e=this._changeScale(o,s);this._downscale(e),n=this._mapping.mapToIndex(t)}this._incrementIndexBy(e,n,r)}_incrementIndexBy(e,t,r){if(0===r)return;if(0===e.length&&(e.indexStart=e.indexEnd=e.indexBase=t),t<e.indexStart){const r=e.indexEnd-t;r>=e.backing.length&&this._grow(e,r+1),e.indexStart=t}else if(t>e.indexEnd){const r=t-e.indexStart;r>=e.backing.length&&this._grow(e,r+1),e.indexEnd=t}let n=t-e.indexBase;n<0&&(n+=e.backing.length),e.incrementBucket(n,r)}_grow(e,t){const r=e.backing.length,n=e.indexBase-e.indexStart,i=r-n;let o=nextGreaterSquare(t);o>this._maxSize&&(o=this._maxSize);const s=o-n;e.backing.growTo(o,i,s)}_changeScale(e,t){let r=0;for(;e-t>=this._maxSize;)e>>=1,t>>=1,r++;return r}_downscale(e){if(0===e)return;if(e<0)throw new Error(`impossible change of scale: ${this.scale}`);const t=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=getMapping(t)}_minScale(e){const t=Math.min(this.scale,e.scale),r=HighLow.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),n=HighLow.combine(this._highLowAtScale(this.negative,this.scale,t),this._highLowAtScale(e.negative,e.scale,t));return Math.min(t-this._changeScale(r.high,r.low),t-this._changeScale(n.high,n.low))}_highLowAtScale(e,t,r){if(0===e.length)return new HighLow(0,-1);const n=t-r;return new HighLow(e.indexStart>>n,e.indexEnd>>n)}_mergeBuckets(e,t,r,n){const i=r.offset,o=t.scale-n;for(let t=0;t<r.length;t++)this._incrementIndexBy(e,i+t>>o,r.at(t))}_diffBuckets(e,t,r,n){const i=r.offset,o=t.scale-n;for(let t=0;t<r.length;t++){let n=(i+t>>o)-e.indexBase;n<0&&(n+=e.backing.length),e.decrementBucket(n,r.at(t))}e.trim()}}class ExponentialHistogramAggregator{kind=AggregatorKind.EXPONENTIAL_HISTOGRAM;_maxSize;_recordMinMax;constructor(e,t){this._maxSize=e,this._recordMinMax=t}createAccumulation(e){return new ExponentialHistogramAccumulation(e,this._maxSize,this._recordMinMax)}merge(e,t){const r=t.clone();return r.merge(e),r}diff(e,t){const r=t.clone();return r.diff(e),r}toMetricData(e,t,r,n){return{descriptor:e,aggregationTemporality:t,dataPointType:DataPointType$2.EXPONENTIAL_HISTOGRAM,dataPoints:r.map(([t,r])=>{const i=r.toPointValue(),o=e.type===InstrumentType$2.GAUGE||e.type===InstrumentType$2.UP_DOWN_COUNTER||e.type===InstrumentType$2.OBSERVABLE_GAUGE||e.type===InstrumentType$2.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:t,startTime:r.startTime,endTime:n,value:{min:i.hasMinMax?i.min:void 0,max:i.hasMinMax?i.max:void 0,sum:o?void 0:i.sum,positive:{offset:i.positive.offset,bucketCounts:i.positive.bucketCounts},negative:{offset:i.negative.offset,bucketCounts:i.negative.bucketCounts},count:i.count,scale:i.scale,zeroCount:i.zeroCount}}})}}}const SUPPRESS_TRACING_KEY$2=createContextKey("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function suppressTracing$2(e){return e.setValue(SUPPRESS_TRACING_KEY$2,!0)}function loggingErrorHandler$2(){return e=>{diag.error(stringifyException$2(e))}}function stringifyException$2(e){return"string"==typeof e?e:JSON.stringify(flattenException$2(e))}function flattenException$2(e){const t={};let r=e;for(;null!==r;)Object.getOwnPropertyNames(r).forEach(e=>{if(t[e])return;const n=r[e];n&&(t[e]=String(n))}),r=Object.getPrototypeOf(r);return t}let delegateHandler$2=loggingErrorHandler$2();function globalErrorHandler$2(e){try{delegateHandler$2(e)}catch{}}const VERSION$2="2.7.0",ATTR_PROCESS_RUNTIME_NAME="process.runtime.name",SDK_INFO$1={[ATTR_TELEMETRY_SDK_NAME]:"opentelemetry",[ATTR_PROCESS_RUNTIME_NAME]:"browser",[ATTR_TELEMETRY_SDK_LANGUAGE]:TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS,[ATTR_TELEMETRY_SDK_VERSION]:VERSION$2},NANOSECOND_DIGITS_IN_MILLIS$2=6,MILLISECONDS_TO_NANOSECONDS$2=Math.pow(10,NANOSECOND_DIGITS_IN_MILLIS$2);function millisToHrTime$2(e){const t=e/1e3;return[Math.trunc(t),Math.round(e%1e3*MILLISECONDS_TO_NANOSECONDS$2)]}function hrTimeToMicroseconds$2(e){return 1e6*e[0]+e[1]/1e3}var ExportResultCode$2;function _export$2(e,t){return new Promise(r=>{context.with(suppressTracing$2(context.active()),()=>{e.export(t,r)})})}!function(e){e[e.SUCCESS=0]="SUCCESS",e[e.FAILED=1]="FAILED"}(ExportResultCode$2||(ExportResultCode$2={}));const internal$2={_export:_export$2};class LastValueAccumulation{startTime;_current;sampleTime;constructor(e,t=0,r=[0,0]){this.startTime=e,this._current=t,this.sampleTime=r}record(e){this._current=e,this.sampleTime=millisToHrTime$2(Date.now())}setStartTime(e){this.startTime=e}toPointValue(){return this._current}}class LastValueAggregator{kind=AggregatorKind.LAST_VALUE;createAccumulation(e){return new LastValueAccumulation(e)}merge(e,t){const r=hrTimeToMicroseconds$2(t.sampleTime)>=hrTimeToMicroseconds$2(e.sampleTime)?t:e;return new LastValueAccumulation(e.startTime,r.toPointValue(),r.sampleTime)}diff(e,t){const r=hrTimeToMicroseconds$2(t.sampleTime)>=hrTimeToMicroseconds$2(e.sampleTime)?t:e;return new LastValueAccumulation(t.startTime,r.toPointValue(),r.sampleTime)}toMetricData(e,t,r,n){return{descriptor:e,aggregationTemporality:t,dataPointType:DataPointType$2.GAUGE,dataPoints:r.map(([e,t])=>({attributes:e,startTime:t.startTime,endTime:n,value:t.toPointValue()}))}}}class SumAccumulation{startTime;monotonic;_current;reset;constructor(e,t,r=0,n=!1){this.startTime=e,this.monotonic=t,this._current=r,this.reset=n}record(e){this.monotonic&&e<0||(this._current+=e)}setStartTime(e){this.startTime=e}toPointValue(){return this._current}}class SumAggregator{kind=AggregatorKind.SUM;monotonic;constructor(e){this.monotonic=e}createAccumulation(e){return new SumAccumulation(e,this.monotonic)}merge(e,t){const r=e.toPointValue(),n=t.toPointValue();return t.reset?new SumAccumulation(t.startTime,this.monotonic,n,t.reset):new SumAccumulation(e.startTime,this.monotonic,r+n)}diff(e,t){const r=e.toPointValue(),n=t.toPointValue();return this.monotonic&&r>n?new SumAccumulation(t.startTime,this.monotonic,n,!0):new SumAccumulation(t.startTime,this.monotonic,n-r)}toMetricData(e,t,r,n){return{descriptor:e,aggregationTemporality:t,dataPointType:DataPointType$2.SUM,dataPoints:r.map(([e,t])=>({attributes:e,startTime:t.startTime,endTime:n,value:t.toPointValue()})),isMonotonic:this.monotonic}}}class DropAggregation{static DEFAULT_INSTANCE=new DropAggregator;createAggregator(e){return DropAggregation.DEFAULT_INSTANCE}}class SumAggregation{static MONOTONIC_INSTANCE=new SumAggregator(!0);static NON_MONOTONIC_INSTANCE=new SumAggregator(!1);createAggregator(e){switch(e.type){case InstrumentType$2.COUNTER:case InstrumentType$2.OBSERVABLE_COUNTER:case InstrumentType$2.HISTOGRAM:return SumAggregation.MONOTONIC_INSTANCE;default:return SumAggregation.NON_MONOTONIC_INSTANCE}}}class LastValueAggregation{static DEFAULT_INSTANCE=new LastValueAggregator;createAggregator(e){return LastValueAggregation.DEFAULT_INSTANCE}}class HistogramAggregation{static DEFAULT_INSTANCE=new HistogramAggregator([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0);createAggregator(e){return HistogramAggregation.DEFAULT_INSTANCE}}class ExplicitBucketHistogramAggregation{_boundaries;_recordMinMax;constructor(e,t=!0){if(null==e)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");e=(e=e.concat()).sort((e,t)=>e-t);const r=e.lastIndexOf(-1/0);let n=e.indexOf(1/0);-1===n&&(n=void 0),this._boundaries=e.slice(r+1,n),this._recordMinMax=t}createAggregator(e){return new HistogramAggregator(this._boundaries,this._recordMinMax)}}class ExponentialHistogramAggregation{_maxSize;_recordMinMax;constructor(e=160,t=!0){this._maxSize=e,this._recordMinMax=t}createAggregator(e){return new ExponentialHistogramAggregator(this._maxSize,this._recordMinMax)}}class DefaultAggregation{_resolve(e){switch(e.type){case InstrumentType$2.COUNTER:case InstrumentType$2.UP_DOWN_COUNTER:case InstrumentType$2.OBSERVABLE_COUNTER:case InstrumentType$2.OBSERVABLE_UP_DOWN_COUNTER:return SUM_AGGREGATION;case InstrumentType$2.GAUGE:case InstrumentType$2.OBSERVABLE_GAUGE:return LAST_VALUE_AGGREGATION;case InstrumentType$2.HISTOGRAM:return e.advice.explicitBucketBoundaries?new ExplicitBucketHistogramAggregation(e.advice.explicitBucketBoundaries):HISTOGRAM_AGGREGATION}return diag.warn(`Unable to recognize instrument type: ${e.type}`),DROP_AGGREGATION}createAggregator(e){return this._resolve(e).createAggregator(e)}}const DROP_AGGREGATION=new DropAggregation,SUM_AGGREGATION=new SumAggregation,LAST_VALUE_AGGREGATION=new LastValueAggregation,HISTOGRAM_AGGREGATION=new HistogramAggregation,DEFAULT_AGGREGATION$1=new DefaultAggregation;var AggregationType$1;function toAggregation(e){switch(e.type){case AggregationType$1.DEFAULT:return DEFAULT_AGGREGATION$1;case AggregationType$1.DROP:return DROP_AGGREGATION;case AggregationType$1.SUM:return SUM_AGGREGATION;case AggregationType$1.LAST_VALUE:return LAST_VALUE_AGGREGATION;case AggregationType$1.EXPONENTIAL_HISTOGRAM:{const t=e;return new ExponentialHistogramAggregation(t.options?.maxSize,t.options?.recordMinMax)}case AggregationType$1.EXPLICIT_BUCKET_HISTOGRAM:{const t=e;return null==t.options?HISTOGRAM_AGGREGATION:new ExplicitBucketHistogramAggregation(t.options?.boundaries,t.options?.recordMinMax)}default:throw new Error("Unsupported Aggregation")}}!function(e){e[e.DEFAULT=0]="DEFAULT",e[e.DROP=1]="DROP",e[e.SUM=2]="SUM",e[e.LAST_VALUE=3]="LAST_VALUE",e[e.EXPLICIT_BUCKET_HISTOGRAM=4]="EXPLICIT_BUCKET_HISTOGRAM",e[e.EXPONENTIAL_HISTOGRAM=5]="EXPONENTIAL_HISTOGRAM"}(AggregationType$1||(AggregationType$1={}));const DEFAULT_AGGREGATION_SELECTOR=e=>({type:AggregationType$1.DEFAULT}),DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR=e=>AggregationTemporality$2.CUMULATIVE;class MetricReader{_shutdown=!1;_metricProducers;_sdkMetricProducer;_aggregationTemporalitySelector;_aggregationSelector;_cardinalitySelector;constructor(e){this._aggregationSelector=e?.aggregationSelector??DEFAULT_AGGREGATION_SELECTOR,this._aggregationTemporalitySelector=e?.aggregationTemporalitySelector??DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR,this._metricProducers=e?.metricProducers??[],this._cardinalitySelector=e?.cardinalitySelector}setMetricProducer(e){if(this._sdkMetricProducer)throw new Error("MetricReader can not be bound to a MeterProvider again.");this._sdkMetricProducer=e,this.onInitialized()}selectAggregation(e){return this._aggregationSelector(e)}selectAggregationTemporality(e){return this._aggregationTemporalitySelector(e)}selectCardinalityLimit(e){return this._cardinalitySelector?this._cardinalitySelector(e):2e3}onInitialized(){}async collect(e){if(void 0===this._sdkMetricProducer)throw new Error("MetricReader is not bound to a MetricProducer");if(this._shutdown)throw new Error("MetricReader is shutdown");const[t,...r]=await Promise.all([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis}),...this._metricProducers.map(t=>t.collect({timeoutMillis:e?.timeoutMillis}))]),n=t.errors.concat(r.flatMap(e=>e.errors));return{resourceMetrics:{resource:t.resourceMetrics.resource,scopeMetrics:t.resourceMetrics.scopeMetrics.concat(r.flatMap(e=>e.resourceMetrics.scopeMetrics))},errors:n}}async shutdown(e){this._shutdown?diag.error("Cannot call shutdown twice."):(null==e?.timeoutMillis?await this.onShutdown():await callWithTimeout$1(this.onShutdown(),e.timeoutMillis),this._shutdown=!0)}async forceFlush(e){this._shutdown?diag.warn("Cannot forceFlush on already shutdown MetricReader."):null!=e?.timeoutMillis?await callWithTimeout$1(this.onForceFlush(),e.timeoutMillis):await this.onForceFlush()}}class PeriodicExportingMetricReader extends MetricReader{_interval;_exporter;_exportInterval;_exportTimeout;constructor(e){const{exporter:t,exportIntervalMillis:r=6e4,metricProducers:n,cardinalityLimits:i}=e;let{exportTimeoutMillis:o=3e4}=e;if(super({aggregationSelector:t.selectAggregation?.bind(t),aggregationTemporalitySelector:t.selectAggregationTemporality?.bind(t),metricProducers:n,cardinalitySelector:e=>{const t={default:2e3,...i};switch(e){case InstrumentType$2.COUNTER:return t.counter??t.default;case InstrumentType$2.GAUGE:return t.gauge??t.default;case InstrumentType$2.HISTOGRAM:return t.histogram??t.default;case InstrumentType$2.OBSERVABLE_COUNTER:return t.observableCounter??t.default;case InstrumentType$2.OBSERVABLE_UP_DOWN_COUNTER:return t.observableUpDownCounter??t.default;case InstrumentType$2.OBSERVABLE_GAUGE:return t.observableGauge??t.default;case InstrumentType$2.UP_DOWN_COUNTER:return t.upDownCounter??t.default;default:return t.default}}}),r<=0)throw Error("exportIntervalMillis must be greater than 0");if(o<=0)throw Error("exportTimeoutMillis must be greater than 0");if(r<o){if("exportIntervalMillis"in e&&"exportTimeoutMillis"in e)throw Error("exportIntervalMillis must be greater than or equal to exportTimeoutMillis");diag.info(`Timeout of ${o} exceeds the interval of ${r}. Clamping timeout to interval duration.`),o=r}this._exportInterval=r,this._exportTimeout=o,this._exporter=t}async _runOnce(){try{await callWithTimeout$1(this._doRun(),this._exportTimeout)}catch(e){if(e instanceof TimeoutError$1)return void diag.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout);globalErrorHandler$2(e)}}async _doRun(){const{resourceMetrics:e,errors:t}=await this.collect({timeoutMillis:this._exportTimeout});if(t.length>0&&diag.error("PeriodicExportingMetricReader: metrics collection errors",...t),e.resource.asyncAttributesPending)try{await(e.resource.waitForAsyncAttributes?.())}catch(e){diag.debug("Error while resolving async portion of resource: ",e),globalErrorHandler$2(e)}if(0===e.scopeMetrics.length)return;const r=await internal$2._export(this._exporter,e);if(r.code!==ExportResultCode$2.SUCCESS)throw new Error(`PeriodicExportingMetricReader: metrics export failed (error ${r.error})`)}onInitialized(){this._interval=setInterval(()=>{this._runOnce()},this._exportInterval),"number"!=typeof this._interval&&this._interval.unref()}async onForceFlush(){await this._runOnce(),await this._exporter.forceFlush()}async onShutdown(){this._interval&&clearInterval(this._interval),await this.onForceFlush(),await this._exporter.shutdown()}}class InMemoryMetricExporter{_shutdown=!1;_aggregationTemporality;_metrics=[];constructor(e){this._aggregationTemporality=e}export(e,t){this._shutdown?setTimeout(()=>t({code:ExportResultCode$2.FAILED}),0):(this._metrics.push(e),setTimeout(()=>t({code:ExportResultCode$2.SUCCESS}),0))}getMetrics(){return this._metrics}forceFlush(){return Promise.resolve()}reset(){this._metrics=[]}selectAggregationTemporality(e){return this._aggregationTemporality}shutdown(){return this._shutdown=!0,Promise.resolve()}}class ConsoleMetricExporter{_shutdown=!1;_temporalitySelector;constructor(e){this._temporalitySelector=e?.temporalitySelector??DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR}export(e,t){if(!this._shutdown)return ConsoleMetricExporter._sendMetrics(e,t);t({code:ExportResultCode$2.FAILED})}forceFlush(){return Promise.resolve()}selectAggregationTemporality(e){return this._temporalitySelector(e)}shutdown(){return this._shutdown=!0,Promise.resolve()}static _sendMetrics(e,t){for(const t of e.scopeMetrics)for(const e of t.metrics)console.dir({descriptor:e.descriptor,dataPointType:e.dataPointType,dataPoints:e.dataPoints},{depth:null});t({code:ExportResultCode$2.SUCCESS})}}let serviceName;function defaultServiceName(){if(void 0===serviceName)try{const e=globalThis.process.argv0;serviceName=e?`unknown_service:${e}`:"unknown_service"}catch{serviceName="unknown_service"}return serviceName}const isPromiseLike=e=>null!==e&&"object"==typeof e&&"function"==typeof e.then;class ResourceImpl{_rawAttributes;_asyncAttributesPending=!1;_schemaUrl;_memoizedAttributes;static FromAttributeList(e,t){const r=new ResourceImpl({},t);return r._rawAttributes=guardedRawAttributes(e),r._asyncAttributesPending=e.filter(([e,t])=>isPromiseLike(t)).length>0,r}constructor(e,t){const r=e.attributes??{};this._rawAttributes=Object.entries(r).map(([e,t])=>(isPromiseLike(t)&&(this._asyncAttributesPending=!0),[e,t])),this._rawAttributes=guardedRawAttributes(this._rawAttributes),this._schemaUrl=validateSchemaUrl(t?.schemaUrl)}get asyncAttributesPending(){return this._asyncAttributesPending}async waitForAsyncAttributes(){if(this.asyncAttributesPending){for(let e=0;e<this._rawAttributes.length;e++){const[t,r]=this._rawAttributes[e];this._rawAttributes[e]=[t,isPromiseLike(r)?await r:r]}this._asyncAttributesPending=!1}}get attributes(){if(this.asyncAttributesPending&&diag.error("Accessing resource attributes before async attributes settled"),this._memoizedAttributes)return this._memoizedAttributes;const e={};for(const[t,r]of this._rawAttributes)isPromiseLike(r)?diag.debug(`Unsettled resource attribute ${t} skipped`):null!=r&&(e[t]??=r);return this._asyncAttributesPending||(this._memoizedAttributes=e),e}getRawAttributes(){return this._rawAttributes}get schemaUrl(){return this._schemaUrl}merge(e){if(null==e)return this;const t=mergeSchemaUrl(this,e),r=t?{schemaUrl:t}:void 0;return ResourceImpl.FromAttributeList([...e.getRawAttributes(),...this.getRawAttributes()],r)}}function resourceFromAttributes(e,t){return ResourceImpl.FromAttributeList(Object.entries(e),t)}function defaultResource(){return resourceFromAttributes({[ATTR_SERVICE_NAME]:defaultServiceName(),[ATTR_TELEMETRY_SDK_LANGUAGE]:SDK_INFO$1[ATTR_TELEMETRY_SDK_LANGUAGE],[ATTR_TELEMETRY_SDK_NAME]:SDK_INFO$1[ATTR_TELEMETRY_SDK_NAME],[ATTR_TELEMETRY_SDK_VERSION]:SDK_INFO$1[ATTR_TELEMETRY_SDK_VERSION]})}function guardedRawAttributes(e){return e.map(([e,t])=>isPromiseLike(t)?[e,t.catch(t=>{diag.debug("promise rejection for resource attribute: %s - %s",e,t)})]:[e,t])}function validateSchemaUrl(e){if("string"==typeof e||void 0===e)return e;diag.warn("Schema URL must be string or undefined, got %s. Schema URL will be ignored.",e)}function mergeSchemaUrl(e,t){const r=e?.schemaUrl,n=t?.schemaUrl;return void 0===r||""===r?n:void 0===n||""===n||r===n?r:void diag.warn('Schema URL merge conflict: old resource has "%s", updating resource has "%s". Resulting resource will have undefined Schema URL.',r,n)}class ViewRegistry{_registeredViews=[];addView(e){this._registeredViews.push(e)}findViews(e,t){return this._registeredViews.filter(r=>this._matchInstrument(r.instrumentSelector,e)&&this._matchMeter(r.meterSelector,t))}_matchInstrument(e,t){return(void 0===e.getType()||t.type===e.getType())&&e.getNameFilter().match(t.name)&&e.getUnitFilter().match(t.unit)}_matchMeter(e,t){return e.getNameFilter().match(t.name)&&(void 0===t.version||e.getVersionFilter().match(t.version))&&(void 0===t.schemaUrl||e.getSchemaUrlFilter().match(t.schemaUrl))}}function createInstrumentDescriptor(e,t,r){return isValidName(e)||diag.warn(`Invalid metric name: "${e}". The metric name should be a ASCII string with a length no greater than 255 characters.`),{name:e,type:t,description:r?.description??"",unit:r?.unit??"",valueType:r?.valueType??ValueType.DOUBLE,advice:r?.advice??{}}}function createInstrumentDescriptorWithView(e,t){return{name:e.name??t.name,description:e.description??t.description,type:t.type,unit:t.unit,valueType:t.valueType,advice:t.advice}}function isDescriptorCompatibleWith(e,t){return equalsCaseInsensitive(e.name,t.name)&&e.unit===t.unit&&e.type===t.type&&e.valueType===t.valueType}const NAME_REGEXP=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function isValidName(e){return NAME_REGEXP.test(e)}class SyncInstrument{_writableMetricStorage;_descriptor;constructor(e,t){this._writableMetricStorage=e,this._descriptor=t}_record(e,t={},r=context.active()){"number"==typeof e?(this._descriptor.valueType!==ValueType.INT||Number.isInteger(e)||(diag.warn(`INT value type cannot accept a floating-point value for ${this._descriptor.name}, ignoring the fractional digits.`),e=Math.trunc(e),Number.isInteger(e)))&&this._writableMetricStorage.record(e,t,r,millisToHrTime$2(Date.now())):diag.warn(`non-number value provided to metric ${this._descriptor.name}: ${e}`)}}class UpDownCounterInstrument extends SyncInstrument{add(e,t,r){this._record(e,t,r)}}class CounterInstrument extends SyncInstrument{add(e,t,r){e<0?diag.warn(`negative value provided to counter ${this._descriptor.name}: ${e}`):this._record(e,t,r)}}class GaugeInstrument extends SyncInstrument{record(e,t,r){this._record(e,t,r)}}class HistogramInstrument extends SyncInstrument{record(e,t,r){e<0?diag.warn(`negative value provided to histogram ${this._descriptor.name}: ${e}`):this._record(e,t,r)}}class ObservableInstrument{_metricStorages;_descriptor;_observableRegistry;constructor(e,t,r){this._descriptor=e,this._metricStorages=t,this._observableRegistry=r}addCallback(e){this._observableRegistry.addCallback(e,this)}removeCallback(e){this._observableRegistry.removeCallback(e,this)}}class ObservableCounterInstrument extends ObservableInstrument{}class ObservableGaugeInstrument extends ObservableInstrument{}class ObservableUpDownCounterInstrument extends ObservableInstrument{}function isObservableInstrument(e){return e instanceof ObservableInstrument}class Meter{_meterSharedState;constructor(e){this._meterSharedState=e}createGauge(e,t){const r=createInstrumentDescriptor(e,InstrumentType$2.GAUGE,t),n=this._meterSharedState.registerMetricStorage(r);return new GaugeInstrument(n,r)}createHistogram(e,t){const r=createInstrumentDescriptor(e,InstrumentType$2.HISTOGRAM,t),n=this._meterSharedState.registerMetricStorage(r);return new HistogramInstrument(n,r)}createCounter(e,t){const r=createInstrumentDescriptor(e,InstrumentType$2.COUNTER,t),n=this._meterSharedState.registerMetricStorage(r);return new CounterInstrument(n,r)}createUpDownCounter(e,t){const r=createInstrumentDescriptor(e,InstrumentType$2.UP_DOWN_COUNTER,t),n=this._meterSharedState.registerMetricStorage(r);return new UpDownCounterInstrument(n,r)}createObservableGauge(e,t){const r=createInstrumentDescriptor(e,InstrumentType$2.OBSERVABLE_GAUGE,t),n=this._meterSharedState.registerAsyncMetricStorage(r);return new ObservableGaugeInstrument(r,n,this._meterSharedState.observableRegistry)}createObservableCounter(e,t){const r=createInstrumentDescriptor(e,InstrumentType$2.OBSERVABLE_COUNTER,t),n=this._meterSharedState.registerAsyncMetricStorage(r);return new ObservableCounterInstrument(r,n,this._meterSharedState.observableRegistry)}createObservableUpDownCounter(e,t){const r=createInstrumentDescriptor(e,InstrumentType$2.OBSERVABLE_UP_DOWN_COUNTER,t),n=this._meterSharedState.registerAsyncMetricStorage(r);return new ObservableUpDownCounterInstrument(r,n,this._meterSharedState.observableRegistry)}addBatchObservableCallback(e,t){this._meterSharedState.observableRegistry.addBatchCallback(e,t)}removeBatchObservableCallback(e,t){this._meterSharedState.observableRegistry.removeBatchCallback(e,t)}}class MetricStorage{_instrumentDescriptor;constructor(e){this._instrumentDescriptor=e}getInstrumentDescriptor(){return this._instrumentDescriptor}updateDescription(e){this._instrumentDescriptor=createInstrumentDescriptor(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})}}class HashMap{_valueMap=new Map;_keyMap=new Map;_hash;constructor(e){this._hash=e}get(e,t){return t??=this._hash(e),this._valueMap.get(t)}getOrDefault(e,t){const r=this._hash(e);if(this._valueMap.has(r))return this._valueMap.get(r);const n=t();return this._keyMap.has(r)||this._keyMap.set(r,e),this._valueMap.set(r,n),n}set(e,t,r){r??=this._hash(e),this._keyMap.has(r)||this._keyMap.set(r,e),this._valueMap.set(r,t)}has(e,t){return t??=this._hash(e),this._valueMap.has(t)}*keys(){const e=this._keyMap.entries();let t=e.next();for(;!0!==t.done;)yield[t.value[1],t.value[0]],t=e.next()}*entries(){const e=this._valueMap.entries();let t=e.next();for(;!0!==t.done;)yield[this._keyMap.get(t.value[0]),t.value[1],t.value[0]],t=e.next()}get size(){return this._valueMap.size}}class AttributeHashMap extends HashMap{constructor(){super(hashAttributes)}}class DeltaMetricProcessor{_activeCollectionStorage=new AttributeHashMap;_cumulativeMemoStorage=new AttributeHashMap;_cardinalityLimit;_overflowAttributes={"otel.metric.overflow":!0};_overflowHashCode;_aggregator;constructor(e,t){this._aggregator=e,this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=hashAttributes(this._overflowAttributes)}record(e,t,r,n){let i=this._activeCollectionStorage.get(t);if(!i){if(this._activeCollectionStorage.size>=this._cardinalityLimit){const t=this._activeCollectionStorage.getOrDefault(this._overflowAttributes,()=>this._aggregator.createAccumulation(n));return void t?.record(e)}i=this._aggregator.createAccumulation(n),this._activeCollectionStorage.set(t,i)}i?.record(e)}batchCumulate(e,t){Array.from(e.entries()).forEach(([e,r,n])=>{const i=this._aggregator.createAccumulation(t);i?.record(r);let o=i;if(this._cumulativeMemoStorage.has(e,n)){const t=this._cumulativeMemoStorage.get(e,n);o=this._aggregator.diff(t,i)}else if(this._cumulativeMemoStorage.size>=this._cardinalityLimit&&(e=this._overflowAttributes,n=this._overflowHashCode,this._cumulativeMemoStorage.has(e,n))){const t=this._cumulativeMemoStorage.get(e,n);o=this._aggregator.diff(t,i)}if(this._activeCollectionStorage.has(e,n)){const t=this._activeCollectionStorage.get(e,n);o=this._aggregator.merge(t,o)}this._cumulativeMemoStorage.set(e,i,n),this._activeCollectionStorage.set(e,o,n)})}collect(){const e=this._activeCollectionStorage;return this._activeCollectionStorage=new AttributeHashMap,e}}class TemporalMetricProcessor{_aggregator;_unreportedAccumulations=new Map;_reportHistory=new Map;constructor(e,t){this._aggregator=e,t.forEach(e=>{this._unreportedAccumulations.set(e,[])})}buildMetrics(e,t,r,n){this._stashAccumulations(r);const i=this._getMergedUnreportedAccumulations(e);let o,s=i;if(this._reportHistory.has(e)){const t=this._reportHistory.get(e),r=t.collectionTime;o=t.aggregationTemporality,s=o===AggregationTemporality$2.CUMULATIVE?TemporalMetricProcessor.merge(t.accumulations,i,this._aggregator):TemporalMetricProcessor.calibrateStartTime(t.accumulations,i,r)}else o=e.selectAggregationTemporality(t.type);this._reportHistory.set(e,{accumulations:s,collectionTime:n,aggregationTemporality:o});const a=AttributesMapToAccumulationRecords(s);if(0!==a.length)return this._aggregator.toMetricData(t,o,a,n)}_stashAccumulations(e){const t=this._unreportedAccumulations.keys();for(const r of t){let t=this._unreportedAccumulations.get(r);void 0===t&&(t=[],this._unreportedAccumulations.set(r,t)),t.push(e)}}_getMergedUnreportedAccumulations(e){let t=new AttributeHashMap;const r=this._unreportedAccumulations.get(e);if(this._unreportedAccumulations.set(e,[]),void 0===r)return t;for(const e of r)t=TemporalMetricProcessor.merge(t,e,this._aggregator);return t}static merge(e,t,r){const n=e,i=t.entries();let o=i.next();for(;!0!==o.done;){const[t,s,a]=o.value;if(e.has(t,a)){const i=e.get(t,a),o=r.merge(i,s);n.set(t,o,a)}else n.set(t,s,a);o=i.next()}return n}static calibrateStartTime(e,t,r){for(const[n,i]of e.keys()){const e=t.get(n,i);e?.setStartTime(r)}return t}}function AttributesMapToAccumulationRecords(e){return Array.from(e.entries())}class AsyncMetricStorage extends MetricStorage{_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;_attributesProcessor;constructor(e,t,r,n,i){super(e),this._aggregationCardinalityLimit=i,this._deltaMetricStorage=new DeltaMetricProcessor(t,this._aggregationCardinalityLimit),this._temporalMetricStorage=new TemporalMetricProcessor(t,n),this._attributesProcessor=r}record(e,t){const r=new AttributeHashMap;Array.from(e.entries()).forEach(([e,t])=>{r.set(this._attributesProcessor.process(e),t)}),this._deltaMetricStorage.batchCumulate(r,t)}collect(e,t){const r=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(e,this._instrumentDescriptor,r,t)}}function getIncompatibilityDetails(e,t){let r="";return e.unit!==t.unit&&(r+=`\t- Unit '${e.unit}' does not match '${t.unit}'\n`),e.type!==t.type&&(r+=`\t- Type '${e.type}' does not match '${t.type}'\n`),e.valueType!==t.valueType&&(r+=`\t- Value Type '${e.valueType}' does not match '${t.valueType}'\n`),e.description!==t.description&&(r+=`\t- Description '${e.description}' does not match '${t.description}'\n`),r}function getValueTypeConflictResolutionRecipe(e,t){return`\t- use valueType '${e.valueType}' on instrument creation or use an instrument name other than '${t.name}'`}function getUnitConflictResolutionRecipe(e,t){return`\t- use unit '${e.unit}' on instrument creation or use an instrument name other than '${t.name}'`}function getTypeConflictResolutionRecipe(e,t){const r={name:t.name,type:t.type,unit:t.unit},n=JSON.stringify(r);return`\t- create a new view with a name other than '${e.name}' and InstrumentSelector '${n}'`}function getDescriptionResolutionRecipe(e,t){const r={name:t.name,type:t.type,unit:t.unit},n=JSON.stringify(r);return`\t- create a new view with a name other than '${e.name}' and InstrumentSelector '${n}'\n \t- OR - create a new view with the name ${e.name} and description '${e.description}' and InstrumentSelector ${n}\n \t- OR - create a new view with the name ${t.name} and description '${e.description}' and InstrumentSelector ${n}`}function getConflictResolutionRecipe(e,t){return e.valueType!==t.valueType?getValueTypeConflictResolutionRecipe(e,t):e.unit!==t.unit?getUnitConflictResolutionRecipe(e,t):e.type!==t.type?getTypeConflictResolutionRecipe(e,t):e.description!==t.description?getDescriptionResolutionRecipe(e,t):""}class MetricStorageRegistry{_sharedRegistry=new Map;_perCollectorRegistry=new Map;static create(){return new MetricStorageRegistry}getStorages(e){let t=[];for(const e of this._sharedRegistry.values())t=t.concat(e);const r=this._perCollectorRegistry.get(e);if(null!=r)for(const e of r.values())t=t.concat(e);return t}register(e){this._registerStorage(e,this._sharedRegistry)}registerForCollector(e,t){let r=this._perCollectorRegistry.get(e);null==r&&(r=new Map,this._perCollectorRegistry.set(e,r)),this._registerStorage(t,r)}findOrUpdateCompatibleStorage(e){const t=this._sharedRegistry.get(e.name);return void 0===t?null:this._findOrUpdateCompatibleStorage(e,t)}findOrUpdateCompatibleCollectorStorage(e,t){const r=this._perCollectorRegistry.get(e);if(void 0===r)return null;const n=r.get(t.name);return void 0===n?null:this._findOrUpdateCompatibleStorage(t,n)}_registerStorage(e,t){const r=e.getInstrumentDescriptor(),n=t.get(r.name);void 0!==n?n.push(e):t.set(r.name,[e])}_findOrUpdateCompatibleStorage(e,t){let r=null;for(const n of t){const t=n.getInstrumentDescriptor();isDescriptorCompatibleWith(t,e)?(t.description!==e.description&&(e.description.length>t.description.length&&n.updateDescription(e.description),diag.warn("A view or instrument with the name ",e.name," has already been registered, but has a different description and is incompatible with another registered view.\n","Details:\n",getIncompatibilityDetails(t,e),"The longer description will be used.\nTo resolve the conflict:",getConflictResolutionRecipe(t,e))),r=n):diag.warn("A view or instrument with the name ",e.name," has already been registered and is incompatible with another registered view.\n","Details:\n",getIncompatibilityDetails(t,e),"To resolve the conflict:\n",getConflictResolutionRecipe(t,e))}return r}}class MultiMetricStorage{_backingStorages;constructor(e){this._backingStorages=e}record(e,t,r,n){this._backingStorages.forEach(i=>{i.record(e,t,r,n)})}}class ObservableResultImpl{_buffer=new AttributeHashMap;_instrumentName;_valueType;constructor(e,t){this._instrumentName=e,this._valueType=t}observe(e,t={}){"number"==typeof e?(this._valueType!==ValueType.INT||Number.isInteger(e)||(diag.warn(`INT value type cannot accept a floating-point value for ${this._instrumentName}, ignoring the fractional digits.`),e=Math.trunc(e),Number.isInteger(e)))&&this._buffer.set(t,e):diag.warn(`non-number value provided to metric ${this._instrumentName}: ${e}`)}}class BatchObservableResultImpl{_buffer=new Map;observe(e,t,r={}){if(!isObservableInstrument(e))return;let n=this._buffer.get(e);null==n&&(n=new AttributeHashMap,this._buffer.set(e,n)),"number"==typeof t?(e._descriptor.valueType!==ValueType.INT||Number.isInteger(t)||(diag.warn(`INT value type cannot accept a floating-point value for ${e._descriptor.name}, ignoring the fractional digits.`),t=Math.trunc(t),Number.isInteger(t)))&&n.set(r,t):diag.warn(`non-number value provided to metric ${e._descriptor.name}: ${t}`)}}class ObservableRegistry{_callbacks=[];_batchCallbacks=[];addCallback(e,t){this._findCallback(e,t)>=0||this._callbacks.push({callback:e,instrument:t})}removeCallback(e,t){const r=this._findCallback(e,t);r<0||this._callbacks.splice(r,1)}addBatchCallback(e,t){const r=new Set(t.filter(isObservableInstrument));if(0===r.size)return void diag.error("BatchObservableCallback is not associated with valid instruments",t);this._findBatchCallback(e,r)>=0||this._batchCallbacks.push({callback:e,instruments:r})}removeBatchCallback(e,t){const r=new Set(t.filter(isObservableInstrument)),n=this._findBatchCallback(e,r);n<0||this._batchCallbacks.splice(n,1)}async observe(e,t){const r=this._observeCallbacks(e,t),n=this._observeBatchCallbacks(e,t);return(await Promise.allSettled([...r,...n])).filter(e=>"rejected"===e.status).map(e=>e.reason)}_observeCallbacks(e,t){return this._callbacks.map(async({callback:r,instrument:n})=>{const i=new ObservableResultImpl(n._descriptor.name,n._descriptor.valueType);let o=Promise.resolve(r(i));null!=t&&(o=callWithTimeout$1(o,t)),await o,n._metricStorages.forEach(t=>{t.record(i._buffer,e)})})}_observeBatchCallbacks(e,t){return this._batchCallbacks.map(async({callback:r,instruments:n})=>{const i=new BatchObservableResultImpl;let o=Promise.resolve(r(i));null!=t&&(o=callWithTimeout$1(o,t)),await o,n.forEach(t=>{const r=i._buffer.get(t);null!=r&&t._metricStorages.forEach(t=>{t.record(r,e)})})})}_findCallback(e,t){return this._callbacks.findIndex(r=>r.callback===e&&r.instrument===t)}_findBatchCallback(e,t){return this._batchCallbacks.findIndex(r=>r.callback===e&&setEquals(r.instruments,t))}}class SyncMetricStorage extends MetricStorage{_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;_attributesProcessor;constructor(e,t,r,n,i){super(e),this._aggregationCardinalityLimit=i,this._deltaMetricStorage=new DeltaMetricProcessor(t,this._aggregationCardinalityLimit),this._temporalMetricStorage=new TemporalMetricProcessor(t,n),this._attributesProcessor=r}record(e,t,r,n){t=this._attributesProcessor.process(t,r),this._deltaMetricStorage.record(e,t,r,n)}collect(e,t){const r=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(e,this._instrumentDescriptor,r,t)}}class NoopAttributesProcessor{process(e,t){return e}}class MultiAttributesProcessor{_processors;constructor(e){this._processors=e}process(e,t){let r=e;for(const e of this._processors)r=e.process(r,t);return r}}class AllowListProcessor{_allowedAttributeNames;constructor(e){this._allowedAttributeNames=e}process(e,t){const r={};return Object.keys(e).forEach(t=>{this._allowedAttributeNames.includes(t)&&(r[t]=e[t])}),r}}class DenyListProcessor{_deniedAttributeNames;constructor(e){this._deniedAttributeNames=e}process(e,t){const r={};return Object.keys(e).forEach(t=>{this._deniedAttributeNames.includes(t)||(r[t]=e[t])}),r}}function createNoopAttributesProcessor(){return NOOP}function createMultiAttributesProcessor(e){return new MultiAttributesProcessor(e)}function createAllowListAttributesProcessor(e){return new AllowListProcessor(e)}function createDenyListAttributesProcessor(e){return new DenyListProcessor(e)}const NOOP=new NoopAttributesProcessor;class MeterSharedState{metricStorageRegistry=new MetricStorageRegistry;observableRegistry=new ObservableRegistry;meter;_meterProviderSharedState;_instrumentationScope;constructor(e,t){this.meter=new Meter(this),this._meterProviderSharedState=e,this._instrumentationScope=t}registerMetricStorage(e){const t=this._registerMetricStorage(e,SyncMetricStorage);return 1===t.length?t[0]:new MultiMetricStorage(t)}registerAsyncMetricStorage(e){return this._registerMetricStorage(e,AsyncMetricStorage)}async collect(e,t,r){const n=await this.observableRegistry.observe(t,r?.timeoutMillis),i=this.metricStorageRegistry.getStorages(e);if(0===i.length)return null;const o=[];return i.forEach(r=>{const n=r.collect(e,t);null!=n&&o.push(n)}),0===o.length?{errors:n}:{scopeMetrics:{scope:this._instrumentationScope,metrics:o},errors:n}}_registerMetricStorage(e,t){let r=this._meterProviderSharedState.viewRegistry.findViews(e,this._instrumentationScope).map(r=>{const n=createInstrumentDescriptorWithView(r,e),i=this.metricStorageRegistry.findOrUpdateCompatibleStorage(n);if(null!=i)return i;const o=r.aggregation.createAggregator(n),s=new t(n,o,r.attributesProcessor,this._meterProviderSharedState.metricCollectors,r.aggregationCardinalityLimit);return this.metricStorageRegistry.register(s),s});if(0===r.length){const n=this._meterProviderSharedState.selectAggregations(e.type).map(([r,n])=>{const i=this.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(r,e);if(null!=i)return i;const o=n.createAggregator(e),s=r.selectCardinalityLimit(e.type),a=new t(e,o,createNoopAttributesProcessor(),[r],s);return this.metricStorageRegistry.registerForCollector(r,a),a});r=r.concat(n)}return r}}class MeterProviderSharedState{viewRegistry=new ViewRegistry;metricCollectors=[];meterSharedStates=new Map;resource;constructor(e){this.resource=e}getMeterSharedState(e){const t=instrumentationScopeId(e);let r=this.meterSharedStates.get(t);return null==r&&(r=new MeterSharedState(this,e),this.meterSharedStates.set(t,r)),r}selectAggregations(e){const t=[];for(const r of this.metricCollectors)t.push([r,toAggregation(r.selectAggregation(e))]);return t}}class MetricCollector{_sharedState;_metricReader;constructor(e,t){this._sharedState=e,this._metricReader=t}async collect(e){const t=millisToHrTime$2(Date.now()),r=[],n=[],i=Array.from(this._sharedState.meterSharedStates.values()).map(async i=>{const o=await i.collect(this,t,e);null!=o?.scopeMetrics&&r.push(o.scopeMetrics),null!=o?.errors&&n.push(...o.errors)});return await Promise.all(i),{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:r},errors:n}}async forceFlush(e){await this._metricReader.forceFlush(e)}async shutdown(e){await this._metricReader.shutdown(e)}selectAggregationTemporality(e){return this._metricReader.selectAggregationTemporality(e)}selectAggregation(e){return this._metricReader.selectAggregation(e)}selectCardinalityLimit(e){return this._metricReader.selectCardinalityLimit?.(e)??2e3}}const ESCAPE=/[\^$\\.+?()[\]{}|]/g;class PatternPredicate{_matchAll;_regexp;constructor(e){"*"===e?(this._matchAll=!0,this._regexp=/.*/):(this._matchAll=!1,this._regexp=new RegExp(PatternPredicate.escapePattern(e)))}match(e){return!!this._matchAll||this._regexp.test(e)}static escapePattern(e){return`^${e.replace(ESCAPE,"\\$&").replace("*",".*")}$`}static hasWildcard(e){return e.includes("*")}}class ExactPredicate{_matchAll;_pattern;constructor(e){this._matchAll=void 0===e,this._pattern=e}match(e){return!!this._matchAll||e===this._pattern}}class InstrumentSelector{_nameFilter;_type;_unitFilter;constructor(e){this._nameFilter=new PatternPredicate(e?.name??"*"),this._type=e?.type,this._unitFilter=new ExactPredicate(e?.unit)}getType(){return this._type}getNameFilter(){return this._nameFilter}getUnitFilter(){return this._unitFilter}}class MeterSelector{_nameFilter;_versionFilter;_schemaUrlFilter;constructor(e){this._nameFilter=new ExactPredicate(e?.name),this._versionFilter=new ExactPredicate(e?.version),this._schemaUrlFilter=new ExactPredicate(e?.schemaUrl)}getNameFilter(){return this._nameFilter}getVersionFilter(){return this._versionFilter}getSchemaUrlFilter(){return this._schemaUrlFilter}}function isSelectorNotProvided(e){return null==e.instrumentName&&null==e.instrumentType&&null==e.instrumentUnit&&null==e.meterName&&null==e.meterVersion&&null==e.meterSchemaUrl}function validateViewOptions(e){if(isSelectorNotProvided(e))throw new Error("Cannot create view with no selector arguments supplied");if(null!=e.name&&(null==e?.instrumentName||PatternPredicate.hasWildcard(e.instrumentName)))throw new Error("Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter.")}class View{name;description;aggregation;attributesProcessor;instrumentSelector;meterSelector;aggregationCardinalityLimit;constructor(e){validateViewOptions(e),null!=e.attributesProcessors?this.attributesProcessor=createMultiAttributesProcessor(e.attributesProcessors):this.attributesProcessor=createNoopAttributesProcessor(),this.name=e.name,this.description=e.description,this.aggregation=toAggregation(e.aggregation??{type:AggregationType$1.DEFAULT}),this.instrumentSelector=new InstrumentSelector({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new MeterSelector({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}}class MeterProvider{_sharedState;_shutdown=!1;constructor(e){if(this._sharedState=new MeterProviderSharedState(e?.resource??defaultResource()),null!=e?.views&&e.views.length>0)for(const t of e.views)this._sharedState.viewRegistry.addView(new View(t));if(null!=e?.readers&&e.readers.length>0)for(const t of e.readers){const e=new MetricCollector(this._sharedState,t);t.setMetricProducer(e),this._sharedState.metricCollectors.push(e)}}getMeter(e,t="",r={}){return this._shutdown?(diag.warn("A shutdown MeterProvider cannot provide a Meter"),createNoopMeter()):this._sharedState.getMeterSharedState({name:e,version:t,schemaUrl:r.schemaUrl}).meter}async shutdown(e){this._shutdown?diag.warn("shutdown may only be called once per MeterProvider"):(this._shutdown=!0,await Promise.all(this._sharedState.metricCollectors.map(t=>t.shutdown(e))))}async forceFlush(e){this._shutdown?diag.warn("invalid attempt to force flush after MeterProvider shutdown"):await Promise.all(this._sharedState.metricCollectors.map(t=>t.forceFlush(e)))}}var esm$4=Object.freeze({__proto__:null,get AggregationTemporality(){return AggregationTemporality$2},get AggregationType(){return AggregationType$1},ConsoleMetricExporter:ConsoleMetricExporter,get DataPointType(){return DataPointType$2},InMemoryMetricExporter:InMemoryMetricExporter,get InstrumentType(){return InstrumentType$2},MeterProvider:MeterProvider,MetricReader:MetricReader,PeriodicExportingMetricReader:PeriodicExportingMetricReader,TimeoutError:TimeoutError$1,createAllowListAttributesProcessor:createAllowListAttributesProcessor,createDenyListAttributesProcessor:createDenyListAttributesProcessor}),require$$0$1=getAugmentedNamespace(esm$4);const SUPPRESS_TRACING_KEY$1=createContextKey("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function suppressTracing$1(e){return e.setValue(SUPPRESS_TRACING_KEY$1,!0)}function unsuppressTracing(e){return e.deleteValue(SUPPRESS_TRACING_KEY$1)}function isTracingSuppressed$1(e){return!0===e.getValue(SUPPRESS_TRACING_KEY$1)}const BAGGAGE_KEY_PAIR_SEPARATOR="=",BAGGAGE_PROPERTIES_SEPARATOR=";",BAGGAGE_ITEMS_SEPARATOR=",",BAGGAGE_HEADER="baggage",BAGGAGE_MAX_NAME_VALUE_PAIRS=180,BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=4096,BAGGAGE_MAX_TOTAL_LENGTH=8192;function serializeKeyPairs(e){return e.reduce((e,t)=>{const r=`${e}${""!==e?BAGGAGE_ITEMS_SEPARATOR:""}${t}`;return r.length>BAGGAGE_MAX_TOTAL_LENGTH?e:r},"")}function getKeyPairs(e){return e.getAllEntries().map(([e,t])=>{let r=`${encodeURIComponent(e)}=${encodeURIComponent(t.value)}`;return void 0!==t.metadata&&(r+=BAGGAGE_PROPERTIES_SEPARATOR+t.metadata.toString()),r})}function parsePairKeyValue(e){const t=e.split(BAGGAGE_PROPERTIES_SEPARATOR);if(t.length<=0)return;const r=t.shift();if(!r)return;const n=r.indexOf(BAGGAGE_KEY_PAIR_SEPARATOR);if(n<=0)return;const i=decodeURIComponent(r.substring(0,n).trim()),o=decodeURIComponent(r.substring(n+1).trim());let s;return t.length>0&&(s=baggageEntryMetadataFromString(t.join(BAGGAGE_PROPERTIES_SEPARATOR))),{key:i,value:o,metadata:s}}function parseKeyPairsIntoRecord(e){return"string"!=typeof e||0===e.length?{}:e.split(BAGGAGE_ITEMS_SEPARATOR).map(e=>parsePairKeyValue(e)).filter(e=>void 0!==e&&e.value.length>0).reduce((e,t)=>(e[t.key]=t.value,e),{})}class W3CBaggagePropagator{inject(e,t,r){const n=propagation.getBaggage(e);if(!n||isTracingSuppressed$1(e))return;const i=serializeKeyPairs(getKeyPairs(n).filter(e=>e.length<=BAGGAGE_MAX_PER_NAME_VALUE_PAIRS).slice(0,BAGGAGE_MAX_NAME_VALUE_PAIRS));i.length>0&&r.set(t,BAGGAGE_HEADER,i)}extract(e,t,r){const n=r.get(t,BAGGAGE_HEADER),i=Array.isArray(n)?n.join(BAGGAGE_ITEMS_SEPARATOR):n;if(!i)return e;const o={};if(0===i.length)return e;return i.split(BAGGAGE_ITEMS_SEPARATOR).forEach(e=>{const t=parsePairKeyValue(e);if(t){const e={value:t.value};t.metadata&&(e.metadata=t.metadata),o[t.key]=e}}),0===Object.entries(o).length?e:propagation.setBaggage(e,propagation.createBaggage(o))}fields(){return[BAGGAGE_HEADER]}}class AnchoredClock{_monotonicClock;_epochMillis;_performanceMillis;constructor(e,t){this._monotonicClock=t,this._epochMillis=e.now(),this._performanceMillis=t.now()}now(){const e=this._monotonicClock.now()-this._performanceMillis;return this._epochMillis+e}}function sanitizeAttributes$1(e){const t={};if("object"!=typeof e||null==e)return t;for(const[r,n]of Object.entries(e))isAttributeKey$1(r)?isAttributeValue$1(n)?Array.isArray(n)?t[r]=n.slice():t[r]=n:diag.warn(`Invalid attribute value set for key: ${r}`):diag.warn(`Invalid attribute key: ${r}`);return t}function isAttributeKey$1(e){return"string"==typeof e&&e.length>0}function isAttributeValue$1(e){return null==e||(Array.isArray(e)?isHomogeneousAttributeValueArray$1(e):isValidPrimitiveAttributeValue(e))}function isHomogeneousAttributeValueArray$1(e){let t;for(const r of e)if(null!=r){if(!t){if(isValidPrimitiveAttributeValue(r)){t=typeof r;continue}return!1}if(typeof r!==t)return!1}return!0}function isValidPrimitiveAttributeValue(e){switch(typeof e){case"number":case"boolean":case"string":return!0}return!1}function loggingErrorHandler$1(){return e=>{diag.error(stringifyException$1(e))}}function stringifyException$1(e){return"string"==typeof e?e:JSON.stringify(flattenException$1(e))}function flattenException$1(e){const t={};let r=e;for(;null!==r;)Object.getOwnPropertyNames(r).forEach(e=>{if(t[e])return;const n=r[e];n&&(t[e]=String(n))}),r=Object.getPrototypeOf(r);return t}let delegateHandler$1=loggingErrorHandler$1();function setGlobalErrorHandler(e){delegateHandler$1=e}function globalErrorHandler$1(e){try{delegateHandler$1(e)}catch{}}function getStringFromEnv(e){}function getBooleanFromEnv(e){}function getNumberFromEnv$1(e){}function getStringListFromEnv(e){}const _globalThis="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof global?global:{},otperformance$1=performance,VERSION$1="2.0.0",SDK_INFO={[SEMRESATTRS_TELEMETRY_SDK_NAME]:"opentelemetry",[SEMRESATTRS_PROCESS_RUNTIME_NAME]:"browser",[SEMRESATTRS_TELEMETRY_SDK_LANGUAGE]:TELEMETRYSDKLANGUAGEVALUES_WEBJS,[SEMRESATTRS_TELEMETRY_SDK_VERSION]:VERSION$1};function unrefTimer(e){}const NANOSECOND_DIGITS$1=9,NANOSECOND_DIGITS_IN_MILLIS$1=6,MILLISECONDS_TO_NANOSECONDS$1=Math.pow(10,NANOSECOND_DIGITS_IN_MILLIS$1),SECOND_TO_NANOSECONDS$1=Math.pow(10,NANOSECOND_DIGITS$1);function millisToHrTime$1(e){const t=e/1e3;return[Math.trunc(t),Math.round(e%1e3*MILLISECONDS_TO_NANOSECONDS$1)]}function getTimeOrigin$1(){let e=otperformance$1.timeOrigin;if("number"!=typeof e){const t=otperformance$1;e=t.timing&&t.timing.fetchStart}return e}function hrTime$1(e){return addHrTimes$1(millisToHrTime$1(getTimeOrigin$1()),millisToHrTime$1("number"==typeof e?e:otperformance$1.now()))}function timeInputToHrTime(e){if(isTimeInputHrTime$1(e))return e;if("number"==typeof e)return e<getTimeOrigin$1()?hrTime$1(e):millisToHrTime$1(e);if(e instanceof Date)return millisToHrTime$1(e.getTime());throw TypeError("Invalid input type")}function hrTimeDuration$1(e,t){let r=t[0]-e[0],n=t[1]-e[1];return n<0&&(r-=1,n+=SECOND_TO_NANOSECONDS$1),[r,n]}function hrTimeToTimeStamp(e){const t=NANOSECOND_DIGITS$1,r=`${"0".repeat(t)}${e[1]}Z`,n=r.substring(r.length-t-1);return new Date(1e3*e[0]).toISOString().replace("000Z",n)}function hrTimeToNanoseconds(e){return e[0]*SECOND_TO_NANOSECONDS$1+e[1]}function hrTimeToMilliseconds(e){return 1e3*e[0]+e[1]/1e6}function hrTimeToMicroseconds$1(e){return 1e6*e[0]+e[1]/1e3}function isTimeInputHrTime$1(e){return Array.isArray(e)&&2===e.length&&"number"==typeof e[0]&&"number"==typeof e[1]}function isTimeInput$1(e){return isTimeInputHrTime$1(e)||"number"==typeof e||e instanceof Date}function addHrTimes$1(e,t){const r=[e[0]+t[0],e[1]+t[1]];return r[1]>=SECOND_TO_NANOSECONDS$1&&(r[1]-=SECOND_TO_NANOSECONDS$1,r[0]+=1),r}var ExportResultCode$1;!function(e){e[e.SUCCESS=0]="SUCCESS",e[e.FAILED=1]="FAILED"}(ExportResultCode$1||(ExportResultCode$1={}));class CompositePropagator{_propagators;_fields;constructor(e={}){this._propagators=e.propagators??[],this._fields=Array.from(new Set(this._propagators.map(e=>"function"==typeof e.fields?e.fields():[]).reduce((e,t)=>e.concat(t),[])))}inject(e,t,r){for(const n of this._propagators)try{n.inject(e,t,r)}catch(e){diag.warn(`Failed to inject with ${n.constructor.name}. Err: ${e.message}`)}}extract(e,t,r){return this._propagators.reduce((e,n)=>{try{return n.extract(e,t,r)}catch(e){diag.warn(`Failed to extract with ${n.constructor.name}. Err: ${e.message}`)}return e},e)}fields(){return this._fields.slice()}}const VALID_KEY_CHAR_RANGE="[_0-9a-z-*/]",VALID_KEY=`[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`,VALID_VENDOR_KEY=`[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`,VALID_KEY_REGEX=new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`),VALID_VALUE_BASE_REGEX=/^[ -~]{0,255}[!-~]$/,INVALID_VALUE_COMMA_EQUAL_REGEX=/,|=/;function validateKey(e){return VALID_KEY_REGEX.test(e)}function validateValue(e){return VALID_VALUE_BASE_REGEX.test(e)&&!INVALID_VALUE_COMMA_EQUAL_REGEX.test(e)}const MAX_TRACE_STATE_ITEMS=32,MAX_TRACE_STATE_LEN=512,LIST_MEMBERS_SEPARATOR=",",LIST_MEMBER_KEY_VALUE_SPLITTER="=";class TraceState{_internalState=new Map;constructor(e){e&&this._parse(e)}set(e,t){const r=this._clone();return r._internalState.has(e)&&r._internalState.delete(e),r._internalState.set(e,t),r}unset(e){const t=this._clone();return t._internalState.delete(e),t}get(e){return this._internalState.get(e)}serialize(){return this._keys().reduce((e,t)=>(e.push(t+LIST_MEMBER_KEY_VALUE_SPLITTER+this.get(t)),e),[]).join(LIST_MEMBERS_SEPARATOR)}_parse(e){e.length>MAX_TRACE_STATE_LEN||(this._internalState=e.split(LIST_MEMBERS_SEPARATOR).reverse().reduce((e,t)=>{const r=t.trim(),n=r.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER);if(-1!==n){const i=r.slice(0,n),o=r.slice(n+1,t.length);validateKey(i)&&validateValue(o)&&e.set(i,o)}return e},new Map),this._internalState.size>MAX_TRACE_STATE_ITEMS&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,MAX_TRACE_STATE_ITEMS))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){const e=new TraceState;return e._internalState=new Map(this._internalState),e}}const TRACE_PARENT_HEADER="traceparent",TRACE_STATE_HEADER="tracestate",VERSION="00",VERSION_PART="(?!ff)[\\da-f]{2}",TRACE_ID_PART="(?![0]{32})[\\da-f]{32}",PARENT_ID_PART="(?![0]{16})[\\da-f]{16}",FLAGS_PART="[\\da-f]{2}",TRACE_PARENT_REGEX=new RegExp(`^\\s?(${VERSION_PART})-(${TRACE_ID_PART})-(${PARENT_ID_PART})-(${FLAGS_PART})(-.*)?\\s?$`);function parseTraceParent(e){const t=TRACE_PARENT_REGEX.exec(e);return t?"00"===t[1]&&t[5]?null:{traceId:t[2],spanId:t[3],traceFlags:parseInt(t[4],16)}:null}class W3CTraceContextPropagator{inject(e,t,r){const n=trace.getSpanContext(e);if(!n||isTracingSuppressed$1(e)||!isSpanContextValid(n))return;const i=`${VERSION}-${n.traceId}-${n.spanId}-0${Number(n.traceFlags||TraceFlags.NONE).toString(16)}`;r.set(t,TRACE_PARENT_HEADER,i),n.traceState&&r.set(t,TRACE_STATE_HEADER,n.traceState.serialize())}extract(e,t,r){const n=r.get(t,TRACE_PARENT_HEADER);if(!n)return e;const i=Array.isArray(n)?n[0]:n;if("string"!=typeof i)return e;const o=parseTraceParent(i);if(!o)return e;o.isRemote=!0;const s=r.get(t,TRACE_STATE_HEADER);if(s){const e=Array.isArray(s)?s.join(","):s;o.traceState=new TraceState("string"==typeof e?e:void 0)}return trace.setSpanContext(e,o)}fields(){return[TRACE_PARENT_HEADER,TRACE_STATE_HEADER]}}const RPC_METADATA_KEY=createContextKey("OpenTelemetry SDK Context Key RPC_METADATA");var RPCType;function setRPCMetadata(e,t){return e.setValue(RPC_METADATA_KEY,t)}function deleteRPCMetadata(e){return e.deleteValue(RPC_METADATA_KEY)}function getRPCMetadata(e){return e.getValue(RPC_METADATA_KEY)}!function(e){e.HTTP="http"}(RPCType||(RPCType={}));const objectTag$1="[object Object]",nullTag$1="[object Null]",undefinedTag$1="[object Undefined]",funcProto$1=Function.prototype,funcToString$1=funcProto$1.toString,objectCtorString$1=funcToString$1.call(Object),getPrototypeOf$1=Object.getPrototypeOf,objectProto$1=Object.prototype,hasOwnProperty$1=objectProto$1.hasOwnProperty,symToStringTag$1=Symbol?Symbol.toStringTag:void 0,nativeObjectToString$1=objectProto$1.toString;function isPlainObject$1(e){if(!isObjectLike$1(e)||baseGetTag$1(e)!==objectTag$1)return!1;const t=getPrototypeOf$1(e);if(null===t)return!0;const r=hasOwnProperty$1.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&funcToString$1.call(r)===objectCtorString$1}function isObjectLike$1(e){return null!=e&&"object"==typeof e}function baseGetTag$1(e){return null==e?void 0===e?undefinedTag$1:nullTag$1:symToStringTag$1&&symToStringTag$1 in Object(e)?getRawTag$1(e):objectToString$1(e)}function getRawTag$1(e){const t=hasOwnProperty$1.call(e,symToStringTag$1),r=e[symToStringTag$1];let n=!1;try{e[symToStringTag$1]=void 0,n=!0}catch(e){}const i=nativeObjectToString$1.call(e);return n&&(t?e[symToStringTag$1]=r:delete e[symToStringTag$1]),i}function objectToString$1(e){return nativeObjectToString$1.call(e)}const MAX_LEVEL$1=20;function merge$1(...e){let t=e.shift();const r=new WeakMap;for(;e.length>0;)t=mergeTwoObjects$1(t,e.shift(),0,r);return t}function takeValue$1(e){return isArray$1(e)?e.slice():e}function mergeTwoObjects$1(e,t,r=0,n){let i;if(!(r>MAX_LEVEL$1)){if(r++,isPrimitive$1(e)||isPrimitive$1(t)||isFunction$1(t))i=takeValue$1(t);else if(isArray$1(e)){if(i=e.slice(),isArray$1(t))for(let e=0,r=t.length;e<r;e++)i.push(takeValue$1(t[e]));else if(isObject$1(t)){const e=Object.keys(t);for(let r=0,n=e.length;r<n;r++){const n=e[r];i[n]=takeValue$1(t[n])}}}else if(isObject$1(e))if(isObject$1(t)){if(!shouldMerge$1(e,t))return t;i=Object.assign({},e);const o=Object.keys(t);for(let s=0,a=o.length;s<a;s++){const a=o[s],c=t[a];if(isPrimitive$1(c))void 0===c?delete i[a]:i[a]=c;else{const o=i[a],s=c;if(wasObjectReferenced$1(e,a,n)||wasObjectReferenced$1(t,a,n))delete i[a];else{if(isObject$1(o)&&isObject$1(s)){const r=n.get(o)||[],i=n.get(s)||[];r.push({obj:e,key:a}),i.push({obj:t,key:a}),n.set(o,r),n.set(s,i)}i[a]=mergeTwoObjects$1(i[a],c,r,n)}}}}else i=t;return i}}function wasObjectReferenced$1(e,t,r){const n=r.get(e[t])||[];for(let r=0,i=n.length;r<i;r++){const i=n[r];if(i.key===t&&i.obj===e)return!0}return!1}function isArray$1(e){return Array.isArray(e)}function isFunction$1(e){return"function"==typeof e}function isObject$1(e){return!isPrimitive$1(e)&&!isArray$1(e)&&!isFunction$1(e)&&"object"==typeof e}function isPrimitive$1(e){return"string"==typeof e||"number"==typeof e||"boolean"==typeof e||void 0===e||e instanceof Date||e instanceof RegExp||null===e}function shouldMerge$1(e,t){return!(!isPlainObject$1(e)||!isPlainObject$1(t))}class TimeoutError extends Error{constructor(e){super(e),Object.setPrototypeOf(this,TimeoutError.prototype)}}function callWithTimeout(e,t){let r;const n=new Promise(function(e,n){r=setTimeout(function(){n(new TimeoutError("Operation timed out."))},t)});return Promise.race([e,n]).then(e=>(clearTimeout(r),e),e=>{throw clearTimeout(r),e})}function urlMatches(e,t){return"string"==typeof t?e===t:!!e.match(t)}function isUrlIgnored(e,t){if(!t)return!1;for(const r of t)if(urlMatches(e,r))return!0;return!1}let Deferred$1=class{_promise;_resolve;_reject;constructor(){this._promise=new Promise((e,t)=>{this._resolve=e,this._reject=t})}get promise(){return this._promise}resolve(e){this._resolve(e)}reject(e){this._reject(e)}},BindOnceFuture$1=class{_callback;_that;_isCalled=!1;_deferred=new Deferred$1;constructor(e,t){this._callback=e,this._that=t}get isCalled(){return this._isCalled}get promise(){return this._deferred.promise}call(...e){if(!this._isCalled){this._isCalled=!0;try{Promise.resolve(this._callback.call(this._that,...e)).then(e=>this._deferred.resolve(e),e=>this._deferred.reject(e))}catch(e){this._deferred.reject(e)}}return this._deferred.promise}};const logLevelMap={ALL:DiagLogLevel.ALL,VERBOSE:DiagLogLevel.VERBOSE,DEBUG:DiagLogLevel.DEBUG,INFO:DiagLogLevel.INFO,WARN:DiagLogLevel.WARN,ERROR:DiagLogLevel.ERROR,NONE:DiagLogLevel.NONE};function diagLogLevelFromString(e){if(null==e)return;const t=logLevelMap[e.toUpperCase()];return null==t?(diag.warn(`Unknown log level "${e}", expected one of ${Object.keys(logLevelMap)}, using default`),DiagLogLevel.INFO):t}function _export$1(e,t){return new Promise(r=>{context.with(suppressTracing$1(context.active()),()=>{e.export(t,e=>{r(e)})})})}const internal$1={_export:_export$1};var esm$3=Object.freeze({__proto__:null,AnchoredClock:AnchoredClock,BindOnceFuture:BindOnceFuture$1,CompositePropagator:CompositePropagator,get ExportResultCode(){return ExportResultCode$1},get RPCType(){return RPCType},SDK_INFO:SDK_INFO,TRACE_PARENT_HEADER:TRACE_PARENT_HEADER,TRACE_STATE_HEADER:TRACE_STATE_HEADER,TimeoutError:TimeoutError,TraceState:TraceState,W3CBaggagePropagator:W3CBaggagePropagator,W3CTraceContextPropagator:W3CTraceContextPropagator,_globalThis:_globalThis,addHrTimes:addHrTimes$1,callWithTimeout:callWithTimeout,deleteRPCMetadata:deleteRPCMetadata,diagLogLevelFromString:diagLogLevelFromString,getBooleanFromEnv:getBooleanFromEnv,getNumberFromEnv:getNumberFromEnv$1,getRPCMetadata:getRPCMetadata,getStringFromEnv:getStringFromEnv,getStringListFromEnv:getStringListFromEnv,getTimeOrigin:getTimeOrigin$1,globalErrorHandler:globalErrorHandler$1,hrTime:hrTime$1,hrTimeDuration:hrTimeDuration$1,hrTimeToMicroseconds:hrTimeToMicroseconds$1,hrTimeToMilliseconds:hrTimeToMilliseconds,hrTimeToNanoseconds:hrTimeToNanoseconds,hrTimeToTimeStamp:hrTimeToTimeStamp,internal:internal$1,isAttributeValue:isAttributeValue$1,isTimeInput:isTimeInput$1,isTimeInputHrTime:isTimeInputHrTime$1,isTracingSuppressed:isTracingSuppressed$1,isUrlIgnored:isUrlIgnored,loggingErrorHandler:loggingErrorHandler$1,merge:merge$1,millisToHrTime:millisToHrTime$1,otperformance:otperformance$1,parseKeyPairsIntoRecord:parseKeyPairsIntoRecord,parseTraceParent:parseTraceParent,sanitizeAttributes:sanitizeAttributes$1,setGlobalErrorHandler:setGlobalErrorHandler,setRPCMetadata:setRPCMetadata,suppressTracing:suppressTracing$1,timeInputToHrTime:timeInputToHrTime,unrefTimer:unrefTimer,unsuppressTracing:unsuppressTracing,urlMatches:urlMatches}),AggregationTemporality$1,InstrumentType$1,DataPointType$1,AggregationType,AggregationTemporalityPreference;!function(e){e[e.DELTA=0]="DELTA",e[e.CUMULATIVE=1]="CUMULATIVE"}(AggregationTemporality$1||(AggregationTemporality$1={})),function(e){e.COUNTER="COUNTER",e.GAUGE="GAUGE",e.HISTOGRAM="HISTOGRAM",e.UP_DOWN_COUNTER="UP_DOWN_COUNTER",e.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",e.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",e.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"}(InstrumentType$1||(InstrumentType$1={})),function(e){e[e.HISTOGRAM=0]="HISTOGRAM",e[e.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",e[e.GAUGE=2]="GAUGE",e[e.SUM=3]="SUM"}(DataPointType$1||(DataPointType$1={})),function(e){e[e.DEFAULT=0]="DEFAULT",e[e.DROP=1]="DROP",e[e.SUM=2]="SUM",e[e.LAST_VALUE=3]="LAST_VALUE",e[e.EXPLICIT_BUCKET_HISTOGRAM=4]="EXPLICIT_BUCKET_HISTOGRAM",e[e.EXPONENTIAL_HISTOGRAM=5]="EXPONENTIAL_HISTOGRAM"}(AggregationType||(AggregationType={})),function(e){e[e.DELTA=0]="DELTA",e[e.CUMULATIVE=1]="CUMULATIVE",e[e.LOWMEMORY=2]="LOWMEMORY"}(AggregationTemporalityPreference||(AggregationTemporalityPreference={}));class OTLPExporterBase{_delegate;constructor(e){this._delegate=e}export(e,t){this._delegate.export(e,t)}forceFlush(){return this._delegate.forceFlush()}shutdown(){return this._delegate.shutdown()}}class OTLPExporterError extends Error{code;name="OTLPExporterError";data;constructor(e,t,r){super(e),this.data=r,this.code=t}}function validateTimeoutMillis(e){if(Number.isFinite(e)&&e>0)return e;throw new Error(`Configuration: timeoutMillis is invalid, expected number greater than 0 (actual: '${e}')`)}function wrapStaticHeadersInFunction(e){if(null!=e)return()=>e}function mergeOtlpSharedConfigurationWithDefaults(e,t,r){return{timeoutMillis:validateTimeoutMillis(e.timeoutMillis??t.timeoutMillis??r.timeoutMillis),concurrencyLimit:e.concurrencyLimit??t.concurrencyLimit??r.concurrencyLimit,compression:e.compression??t.compression??r.compression}}function getSharedConfigurationDefaults(){return{timeoutMillis:1e4,concurrencyLimit:30,compression:"none"}}class BoundedQueueExportPromiseHandler{_concurrencyLimit;_sendingPromises=[];constructor(e){this._concurrencyLimit=e}pushPromise(e){if(this.hasReachedLimit())throw new Error("Concurrency Limit reached");this._sendingPromises.push(e);const t=()=>{const t=this._sendingPromises.indexOf(e);this._sendingPromises.splice(t,1)};e.then(t,t)}hasReachedLimit(){return this._sendingPromises.length>=this._concurrencyLimit}async awaitAll(){await Promise.all(this._sendingPromises)}}function createBoundedQueueExportPromiseHandler(e){return new BoundedQueueExportPromiseHandler(e.concurrencyLimit)}function isPartialSuccessResponse(e){return Object.prototype.hasOwnProperty.call(e,"partialSuccess")}function createLoggingPartialSuccessResponseHandler(){return{handleResponse(e){null!=e&&isPartialSuccessResponse(e)&&null!=e.partialSuccess&&0!==Object.keys(e.partialSuccess).length&&diag.warn("Received Partial Success response:",JSON.stringify(e.partialSuccess))}}}class OTLPExportDelegate{_transport;_serializer;_responseHandler;_promiseQueue;_timeout;_diagLogger;constructor(e,t,r,n,i){this._transport=e,this._serializer=t,this._responseHandler=r,this._promiseQueue=n,this._timeout=i,this._diagLogger=diag.createComponentLogger({namespace:"OTLPExportDelegate"})}export(e,t){if(this._diagLogger.debug("items to be sent",e),this._promiseQueue.hasReachedLimit())return void t({code:ExportResultCode$1.FAILED,error:new Error("Concurrent export limit reached")});const r=this._serializer.serializeRequest(e);null!=r?this._promiseQueue.pushPromise(this._transport.send(r,this._timeout).then(e=>{if("success"!==e.status)"failure"===e.status&&e.error?t({code:ExportResultCode$1.FAILED,error:e.error}):"retryable"===e.status?t({code:ExportResultCode$1.FAILED,error:new OTLPExporterError("Export failed with retryable status")}):t({code:ExportResultCode$1.FAILED,error:new OTLPExporterError("Export failed with unknown error")});else{if(null!=e.data)try{this._responseHandler.handleResponse(this._serializer.deserializeResponse(e.data))}catch(t){this._diagLogger.warn("Export succeeded but could not deserialize response - is the response specification compliant?",t,e.data)}t({code:ExportResultCode$1.SUCCESS})}},e=>t({code:ExportResultCode$1.FAILED,error:e}))):t({code:ExportResultCode$1.FAILED,error:new Error("Nothing to send")})}forceFlush(){return this._promiseQueue.awaitAll()}async shutdown(){this._diagLogger.debug("shutdown started"),await this.forceFlush(),this._transport.shutdown()}}function createOtlpExportDelegate(e,t){return new OTLPExportDelegate(e.transport,e.serializer,createLoggingPartialSuccessResponseHandler(),e.promiseHandler,t.timeout)}function createOtlpNetworkExportDelegate(e,t,r){return createOtlpExportDelegate({transport:r,serializer:t,promiseHandler:createBoundedQueueExportPromiseHandler(e)},{timeout:e.timeoutMillis})}const CumulativeTemporalitySelector=()=>AggregationTemporality$1.CUMULATIVE,DeltaTemporalitySelector=e=>{switch(e){case InstrumentType$1.COUNTER:case InstrumentType$1.OBSERVABLE_COUNTER:case InstrumentType$1.GAUGE:case InstrumentType$1.HISTOGRAM:case InstrumentType$1.OBSERVABLE_GAUGE:return AggregationTemporality$1.DELTA;case InstrumentType$1.UP_DOWN_COUNTER:case InstrumentType$1.OBSERVABLE_UP_DOWN_COUNTER:return AggregationTemporality$1.CUMULATIVE}},LowMemoryTemporalitySelector=e=>{switch(e){case InstrumentType$1.COUNTER:case InstrumentType$1.HISTOGRAM:return AggregationTemporality$1.DELTA;case InstrumentType$1.GAUGE:case InstrumentType$1.UP_DOWN_COUNTER:case InstrumentType$1.OBSERVABLE_UP_DOWN_COUNTER:case InstrumentType$1.OBSERVABLE_COUNTER:case InstrumentType$1.OBSERVABLE_GAUGE:return AggregationTemporality$1.CUMULATIVE}};function chooseTemporalitySelectorFromEnvironment(){const e="cumulative".toLowerCase();return"cumulative"===e?CumulativeTemporalitySelector:"delta"===e?DeltaTemporalitySelector:"lowmemory"===e?LowMemoryTemporalitySelector:(diag.warn(`OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE is set to '${e}', but only 'cumulative' and 'delta' are allowed. Using default ('cumulative') instead.`),CumulativeTemporalitySelector)}function chooseTemporalitySelector(e){return null!=e?e===AggregationTemporalityPreference.DELTA?DeltaTemporalitySelector:e===AggregationTemporalityPreference.LOWMEMORY?LowMemoryTemporalitySelector:CumulativeTemporalitySelector:chooseTemporalitySelectorFromEnvironment()}const DEFAULT_AGGREGATION=Object.freeze({type:AggregationType.DEFAULT});function chooseAggregationSelector(e){return e?.aggregationPreference??(()=>DEFAULT_AGGREGATION)}class OTLPMetricExporterBase extends OTLPExporterBase{_aggregationTemporalitySelector;_aggregationSelector;constructor(e,t){super(e),this._aggregationSelector=chooseAggregationSelector(t),this._aggregationTemporalitySelector=chooseTemporalitySelector(t?.temporalityPreference)}selectAggregation(e){return this._aggregationSelector(e)}selectAggregationTemporality(e){return this._aggregationTemporalitySelector(e)}}function intValue(e){return e>=48&&e<=57?e-48:e>=97&&e<=102?e-87:e-55}function hexToBinary(e){const t=new Uint8Array(e.length/2);let r=0;for(let n=0;n<e.length;n+=2){const i=intValue(e.charCodeAt(n)),o=intValue(e.charCodeAt(n+1));t[r++]=i<<4|o}return t}function hrTimeToNanos(e){const t=BigInt(1e9);return BigInt(e[0])*t+BigInt(e[1])}function toLongBits(e){return{low:Number(BigInt.asUintN(32,e)),high:Number(BigInt.asUintN(32,e>>BigInt(32)))}}function encodeAsLongBits(e){return toLongBits(hrTimeToNanos(e))}function encodeAsString(e){return hrTimeToNanos(e).toString()}const encodeTimestamp="undefined"!=typeof BigInt?encodeAsString:hrTimeToNanoseconds;function identity(e){return e}function optionalHexToBinary(e){if(void 0!==e)return hexToBinary(e)}const DEFAULT_ENCODER={encodeHrTime:encodeAsLongBits,encodeSpanContext:hexToBinary,encodeOptionalSpanContext:optionalHexToBinary};function getOtlpEncoder(e){if(void 0===e)return DEFAULT_ENCODER;const t=e.useLongBits??!0,r=e.useHex??!1;return{encodeHrTime:t?encodeAsLongBits:encodeTimestamp,encodeSpanContext:r?identity:hexToBinary,encodeOptionalSpanContext:r?identity:optionalHexToBinary}}function createResource(e){return{attributes:toAttributes(e.attributes),droppedAttributesCount:0}}function createInstrumentationScope(e){return{name:e.name,version:e.version}}function toAttributes(e){return Object.keys(e).map(t=>toKeyValue(t,e[t]))}function toKeyValue(e,t){return{key:e,value:toAnyValue(t)}}function toAnyValue(e){const t=typeof e;return"string"===t?{stringValue:e}:"number"===t?Number.isInteger(e)?{intValue:e}:{doubleValue:e}:"boolean"===t?{boolValue:e}:e instanceof Uint8Array?{bytesValue:e}:Array.isArray(e)?{arrayValue:{values:e.map(toAnyValue)}}:"object"===t&&null!=e?{kvlistValue:{values:Object.entries(e).map(([e,t])=>toKeyValue(e,t))}}:{}}var AggregationTemporality,InstrumentType,DataPointType;function toResourceMetrics(e,t){const r=getOtlpEncoder(t);return{resource:createResource(e.resource),schemaUrl:void 0,scopeMetrics:toScopeMetrics(e.scopeMetrics,r)}}function toScopeMetrics(e,t){return Array.from(e.map(e=>({scope:createInstrumentationScope(e.scope),metrics:e.metrics.map(e=>toMetric(e,t)),schemaUrl:e.scope.schemaUrl})))}function toMetric(e,t){const r={name:e.descriptor.name,description:e.descriptor.description,unit:e.descriptor.unit},n=toAggregationTemporality(e.aggregationTemporality);switch(e.dataPointType){case DataPointType.SUM:r.sum={aggregationTemporality:n,isMonotonic:e.isMonotonic,dataPoints:toSingularDataPoints(e,t)};break;case DataPointType.GAUGE:r.gauge={dataPoints:toSingularDataPoints(e,t)};break;case DataPointType.HISTOGRAM:r.histogram={aggregationTemporality:n,dataPoints:toHistogramDataPoints(e,t)};break;case DataPointType.EXPONENTIAL_HISTOGRAM:r.exponentialHistogram={aggregationTemporality:n,dataPoints:toExponentialHistogramDataPoints(e,t)}}return r}function toSingularDataPoint(e,t,r){const n={attributes:toAttributes(e.attributes),startTimeUnixNano:r.encodeHrTime(e.startTime),timeUnixNano:r.encodeHrTime(e.endTime)};switch(t){case ValueType.INT:n.asInt=e.value;break;case ValueType.DOUBLE:n.asDouble=e.value}return n}function toSingularDataPoints(e,t){return e.dataPoints.map(r=>toSingularDataPoint(r,e.descriptor.valueType,t))}function toHistogramDataPoints(e,t){return e.dataPoints.map(e=>{const r=e.value;return{attributes:toAttributes(e.attributes),bucketCounts:r.buckets.counts,explicitBounds:r.buckets.boundaries,count:r.count,sum:r.sum,min:r.min,max:r.max,startTimeUnixNano:t.encodeHrTime(e.startTime),timeUnixNano:t.encodeHrTime(e.endTime)}})}function toExponentialHistogramDataPoints(e,t){return e.dataPoints.map(e=>{const r=e.value;return{attributes:toAttributes(e.attributes),count:r.count,min:r.min,max:r.max,sum:r.sum,positive:{offset:r.positive.offset,bucketCounts:r.positive.bucketCounts},negative:{offset:r.negative.offset,bucketCounts:r.negative.bucketCounts},scale:r.scale,zeroCount:r.zeroCount,startTimeUnixNano:t.encodeHrTime(e.startTime),timeUnixNano:t.encodeHrTime(e.endTime)}})}function toAggregationTemporality(e){switch(e){case AggregationTemporality.DELTA:return 1;case AggregationTemporality.CUMULATIVE:return 2}}function createExportMetricsServiceRequest(e,t){return{resourceMetrics:e.map(e=>toResourceMetrics(e,t))}}function sdkSpanToOtlpSpan(e,t){const r=e.spanContext(),n=e.status,i=e.parentSpanContext?.spanId?t.encodeSpanContext(e.parentSpanContext?.spanId):void 0;return{traceId:t.encodeSpanContext(r.traceId),spanId:t.encodeSpanContext(r.spanId),parentSpanId:i,traceState:r.traceState?.serialize(),name:e.name,kind:null==e.kind?0:e.kind+1,startTimeUnixNano:t.encodeHrTime(e.startTime),endTimeUnixNano:t.encodeHrTime(e.endTime),attributes:toAttributes(e.attributes),droppedAttributesCount:e.droppedAttributesCount,events:e.events.map(e=>toOtlpSpanEvent(e,t)),droppedEventsCount:e.droppedEventsCount,status:{code:n.code,message:n.message},links:e.links.map(e=>toOtlpLink(e,t)),droppedLinksCount:e.droppedLinksCount}}function toOtlpLink(e,t){return{attributes:e.attributes?toAttributes(e.attributes):[],spanId:t.encodeSpanContext(e.context.spanId),traceId:t.encodeSpanContext(e.context.traceId),traceState:e.context.traceState?.serialize(),droppedAttributesCount:e.droppedAttributesCount||0}}function toOtlpSpanEvent(e,t){return{attributes:e.attributes?toAttributes(e.attributes):[],name:e.name,timeUnixNano:t.encodeHrTime(e.time),droppedAttributesCount:e.droppedAttributesCount||0}}function createExportTraceServiceRequest(e,t){return{resourceSpans:spanRecordsToResourceSpans(e,getOtlpEncoder(t))}}function createResourceMap(e){const t=new Map;for(const r of e){let e=t.get(r.resource);e||(e=new Map,t.set(r.resource,e));const n=`${r.instrumentationScope.name}@${r.instrumentationScope.version||""}:${r.instrumentationScope.schemaUrl||""}`;let i=e.get(n);i||(i=[],e.set(n,i)),i.push(r)}return t}function spanRecordsToResourceSpans(e,t){const r=[],n=createResourceMap(e).entries();let i=n.next();for(;!i.done;){const[e,o]=i.value,s=[],a=o.values();let c=a.next();for(;!c.done;){const e=c.value;if(e.length>0){const r=e.map(e=>sdkSpanToOtlpSpan(e,t));s.push({scope:createInstrumentationScope(e[0].instrumentationScope),spans:r,schemaUrl:e[0].instrumentationScope.schemaUrl})}c=a.next()}const l={resource:createResource(e),scopeSpans:s,schemaUrl:void 0};r.push(l),i=n.next()}return r}!function(e){e[e.DELTA=0]="DELTA",e[e.CUMULATIVE=1]="CUMULATIVE"}(AggregationTemporality||(AggregationTemporality={})),function(e){e.COUNTER="COUNTER",e.GAUGE="GAUGE",e.HISTOGRAM="HISTOGRAM",e.UP_DOWN_COUNTER="UP_DOWN_COUNTER",e.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",e.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",e.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"}(InstrumentType||(InstrumentType={})),function(e){e[e.HISTOGRAM=0]="HISTOGRAM",e[e.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",e[e.GAUGE=2]="GAUGE",e[e.SUM=3]="SUM"}(DataPointType||(DataPointType={}));const JsonMetricsSerializer={serializeRequest:e=>{const t=createExportMetricsServiceRequest([e],{useLongBits:!1});return(new TextEncoder).encode(JSON.stringify(t))},deserializeResponse:e=>{const t=new TextDecoder;return JSON.parse(t.decode(e))}},JsonTraceSerializer={serializeRequest:e=>{const t=createExportTraceServiceRequest(e,{useHex:!0,useLongBits:!1});return(new TextEncoder).encode(JSON.stringify(t))},deserializeResponse:e=>{const t=new TextDecoder;return JSON.parse(t.decode(e))}},MAX_ATTEMPTS=5,INITIAL_BACKOFF=1e3,MAX_BACKOFF=5e3,BACKOFF_MULTIPLIER=1.5,JITTER=.2;function getJitter(){return Math.random()*(2*JITTER)-JITTER}class RetryingTransport{_transport;constructor(e){this._transport=e}retry(e,t,r){return new Promise((n,i)=>{setTimeout(()=>{this._transport.send(e,t).then(n,i)},r)})}async send(e,t){const r=Date.now()+t;let n=await this._transport.send(e,t),i=MAX_ATTEMPTS,o=INITIAL_BACKOFF;for(;"retryable"===n.status&&i>0;){i--;const t=Math.max(Math.min(o,MAX_BACKOFF)+getJitter(),0);o*=BACKOFF_MULTIPLIER;const s=n.retryInMillis??t,a=r-Date.now();if(s>a)return n;n=await this.retry(e,a,s)}return n}shutdown(){return this._transport.shutdown()}}function createRetryingTransport(e){return new RetryingTransport(e.transport)}function isExportRetryable(e){return[429,502,503,504].includes(e)}function parseRetryAfterToMills(e){if(null==e)return;const t=Number.parseInt(e,10);if(Number.isInteger(t))return t>0?1e3*t:-1;const r=new Date(e).getTime()-Date.now();return r>=0?r:0}class XhrTransport{_parameters;constructor(e){this._parameters=e}send(e,t){return new Promise(r=>{const n=new XMLHttpRequest;n.timeout=t,n.open("POST",this._parameters.url);const i=this._parameters.headers();Object.entries(i).forEach(([e,t])=>{n.setRequestHeader(e,t)}),n.ontimeout=e=>{r({status:"failure",error:new Error("XHR request timed out")})},n.onreadystatechange=()=>{n.status>=200&&n.status<=299?(diag.debug("XHR success"),r({status:"success"})):n.status&&isExportRetryable(n.status)?r({status:"retryable",retryInMillis:parseRetryAfterToMills(n.getResponseHeader("Retry-After"))}):0!==n.status&&r({status:"failure",error:new Error("XHR request failed with non-retryable status")})},n.onabort=()=>{r({status:"failure",error:new Error("XHR request aborted")})},n.onerror=()=>{r({status:"failure",error:new Error("XHR request errored")})},n.send(e)})}shutdown(){}}function createXhrTransport(e){return new XhrTransport(e)}class SendBeaconTransport{_params;constructor(e){this._params=e}send(e){return new Promise(t=>{navigator.sendBeacon(this._params.url,new Blob([e],{type:this._params.blobType}))?(diag.debug("SendBeacon success"),t({status:"success"})):t({status:"failure",error:new Error("SendBeacon failed")})})}shutdown(){}}function createSendBeaconTransport(e){return new SendBeaconTransport(e)}function createOtlpXhrExportDelegate(e,t){return createOtlpNetworkExportDelegate(e,t,createRetryingTransport({transport:createXhrTransport(e)}))}function createOtlpSendBeaconExportDelegate(e,t){return createOtlpNetworkExportDelegate(e,t,createRetryingTransport({transport:createSendBeaconTransport({url:e.url,blobType:e.headers()["Content-Type"]})}))}function validateAndNormalizeHeaders(e){return()=>{const t={};return Object.entries(e?.()??{}).forEach(([e,r])=>{void 0!==r?t[e]=String(r):diag.warn(`Header "${e}" has invalid value (${r}) and will be ignored`)}),t}}function mergeHeaders(e,t,r){const n={...r()},i={};return()=>(null!=t&&Object.assign(i,t()),null!=e&&Object.assign(i,e()),Object.assign(i,n))}function validateUserProvidedUrl(e){if(null!=e)try{return new URL(e),e}catch(t){throw new Error(`Configuration: Could not parse user-provided export URL: '${e}'`)}}function mergeOtlpHttpConfigurationWithDefaults(e,t,r){return{...mergeOtlpSharedConfigurationWithDefaults(e,t,r),headers:mergeHeaders(validateAndNormalizeHeaders(e.headers),t.headers,r.headers),url:validateUserProvidedUrl(e.url)??t.url??r.url,agentOptions:e.agentOptions??t.agentOptions??r.agentOptions}}function getHttpConfigurationDefaults(e,t){return{...getSharedConfigurationDefaults(),headers:()=>e,url:"http://localhost:4318/"+t,agentOptions:{keepAlive:!0}}}function convertLegacyBrowserHttpOptions(e,t,r){return mergeOtlpHttpConfigurationWithDefaults({url:e.url,timeoutMillis:e.timeoutMillis,headers:wrapStaticHeadersInFunction(e.headers),concurrencyLimit:e.concurrencyLimit},{},getHttpConfigurationDefaults(r,t))}function createLegacyOtlpBrowserExportDelegate(e,t,r,n){const i=!!e.headers||"function"!=typeof navigator.sendBeacon,o=convertLegacyBrowserHttpOptions(e,r,n);return i?createOtlpXhrExportDelegate(o,t):createOtlpSendBeaconExportDelegate(o,t)}class OTLPMetricExporter extends OTLPMetricExporterBase{constructor(e){super(createLegacyOtlpBrowserExportDelegate(e??{},JsonMetricsSerializer,"v1/metrics",{"Content-Type":"application/json"}),e)}}var esm$2=Object.freeze({__proto__:null,get AggregationTemporalityPreference(){return AggregationTemporalityPreference},CumulativeTemporalitySelector:CumulativeTemporalitySelector,DeltaTemporalitySelector:DeltaTemporalitySelector,LowMemoryTemporalitySelector:LowMemoryTemporalitySelector,OTLPMetricExporter:OTLPMetricExporter,OTLPMetricExporterBase:OTLPMetricExporterBase}),require$$2=getAugmentedNamespace(esm$2);Object.defineProperty(providerFactory,"__esModule",{value:!0}),providerFactory.MetricsMeterProviderFactory=void 0;const sdk_metrics_1=require$$0$1,otel_1$7=requireDist$1(),exporter_metrics_otlp_http_1=require$$2,utils_1$2=utils$1;class MetricsMeterProviderFactory{create(e,t,r){var n;const i=Object.assign(Object.assign({url:e.url,concurrencyLimit:e.concurrencyLimit,timeoutMillis:e.timeoutMillis,compression:e.compression,keepAlive:e.keepAlive},e.exporterSettings),{headers:Object.assign(Object.assign(Object.assign({},otel_1$7.Container.errorless(t.headers)),otel_1$7.Container.errorless(null===(n=e.exporterSettings)||void 0===n?void 0:n.headers)),otel_1$7.Container.errorless(e.headers))}),o=Object.assign(Object.assign({},e.readerSettings),{exportIntervalMillis:e.publishInterval});let s=[];e.metricReaders&&(s=otel_1$7.Container.errorless(()=>e.metricReaders(o,i,e,t)));let a=[];e.metricExporters&&(a=otel_1$7.Container.errorless(()=>{var r;return null===(r=e.metricExporters)||void 0===r?void 0:r.call(e,i,e,t)})),!e.url||(null==a?void 0:a.length)||(null==s?void 0:s.length)||(a=[new exporter_metrics_otlp_http_1.OTLPMetricExporter(i)]);for(const e of a)s.push(new sdk_metrics_1.PeriodicExportingMetricReader(Object.assign(Object.assign({},o),{exporter:e})));return{meterProvider:this.createMeterProvider(e,t,s,r),metricReaders:s}}createMeterProvider(e,t,r,n){var i,o,s;const a=(0,otel_1$7.loadInsightsPlugin)("base",n);a||n.error("Unable to create meter provider without loaded @interopio/insights-base package");const c=null!==(i=otel_1$7.Container.errorless(e.additionalResourceAttributes))&&void 0!==i?i:{},l=(0,utils_1$2.reduceModality)(c,null===(o=e.defaultPublishingSettings)||void 0===o?void 0:o.attributeSettings),u=Object.assign({resource:null==a?void 0:a.resourceFromAttributes(l),readers:r},e.meterProviderSettings),d=null!==(s=otel_1$7.Container.errorless(()=>{var r;return null===(r=e.meterProvider)||void 0===r?void 0:r.call(e,u,e,t)}))&&void 0!==s?s:new sdk_metrics_1.MeterProvider(u);return d}}providerFactory.MetricsMeterProviderFactory=MetricsMeterProviderFactory;var manager$2={},manager$1={};Object.defineProperty(manager$1,"__esModule",{value:!0}),manager$1.MetricsManagerValidator=void 0;const validator_1=validator;class MetricsManagerValidator{validate(e){validator_1.Validator.throwIfNullOrUndefined(e,"manager"),validator_1.Validator.throwIfNullOrUndefined(e.settings,"settings"),validator_1.Validator.throwIfNullOrUndefined(e.metricsFactory,"metricsFactory"),validator_1.Validator.throwIfNullOrUndefined(e.meterProvider,"meterProvider"),validator_1.Validator.throwIfNullOrUndefined(e.logger,"logger")}}manager$1.MetricsManagerValidator=MetricsManagerValidator;var __awaiter$1=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(manager$2,"__esModule",{value:!0}),manager$2.MetricsManager=void 0;const manager_1$1=manager$1,constants_1$1=constants$1,otel_1$6=requireDist$1();class MetricsManager{constructor(e,t,r,n,i){this.otelSettings=e,this.settings=t,this.metricsFactory=r,this.meterProvider=n,this.logger=i,this.metrics=new Map,this.started=!1,!1!==(null==e?void 0:e.logSettingsOnStartup)&&(null==i||i.info(`Starting MetricsManager with settings ${(0,otel_1$6.safeStringify)(t)}`));(new manager_1$1.MetricsManagerValidator).validate(this)}get(e){return this.getOrCreateMetric(e)}getFromSettings(e){return this.getOrCreateMetricFromSettings(e)}getObservable(e,t,r,n){return this.getOrCreateMetric(e,t,r,n)}getObservableFromSettings(e,t,r,n){return this.getOrCreateMetricFromSettings(e,t,r,n)}start(){var e;return __awaiter$1(this,void 0,void 0,function*(){try{this.createEnabledMetrics(null!==(e=this.settings.metrics)&&void 0!==e?e:[]);for(const e of this.metrics){const t=e[1];yield this.startMetric(t)}this.started=!0,this.logger.debug("metrics manager has been started")}catch(e){const t="error while starting metrics manager";this.logger.warn(t,e)}})}stop(){return __awaiter$1(this,void 0,void 0,function*(){try{for(const e of this.metrics){const t=e[1];yield this.stopMetric(t)}yield this.meterProvider.forceFlush(),this.started=!1,this.logger.debug("metrics manager has been stopped")}catch(e){const t="error while stopping metrics manager";this.logger.warn(t,e)}})}waitForFinalExport(e){return __awaiter$1(this,void 0,void 0,function*(){const t=new Date;yield Promise.all(this.meterProvider.metricReaders.map(t=>t.collect({timeoutMillis:e})));const r=e?e-((new Date).getTime()-t.getTime()):void 0;return Promise.race([new Promise(e=>r&&setTimeout(e,r)),this.meterProvider.forceFlush()])})}createEnabledMetrics(e){const t=e.filter(e=>{var t;return!this.metrics.has(null!==(t=e.name)&&void 0!==t?t:e.type)}),r=t.filter(e=>e.enabled);r.forEach(e=>this.createMetric(e))}getOrCreateMetric(e,t,r,n){var i;if(this.metrics.has(e))return this.metrics.get(e);{let o;const s=null===(i=this.settings.metrics)||void 0===i?void 0:i.find(t=>t.name===e);return s&&(o=this.createMetric(s,t,r,n)),o}}getOrCreateMetricFromSettings(e,t,r,n){var i;if(!e.name)throw new Error("settings.name not defined");return this.metrics.has(e.name)?this.metrics.get(e.name):this.createMetric(Object.assign(Object.assign({},e),{enabled:null===(i=e.enabled)||void 0===i||i}),t,r,n)}createMetric(e,t,r,n){var i;try{const o=e.additionalAttributes;e=Object.assign(Object.assign({},e),{description:e.description||constants_1$1.Defaults.DEFAULT_METRIC_DESCRIPTION,platformVersion:e.platformVersion||this.otelSettings.platformVersion||"unknown",user:e.user||this.otelSettings.userId||constants_1$1.Defaults.DEFAULT_USER,additionalAttributes:()=>Object.assign(Object.assign(Object.assign({},otel_1$6.Container.errorless(this.otelSettings.additionalAttributes)),otel_1$6.Container.errorless(this.settings.additionalAttributes)),otel_1$6.Container.errorless(o))});const s=this.metricsFactory.create(e,this.settings,t,r,n);return s&&this.metrics.set(null!==(i=e.name)&&void 0!==i?i:e.type,s),s}catch(t){const r=`error while creating metric from type: ${e.type}`;return void this.logger.warn(r,t)}}startMetric(e){return __awaiter$1(this,void 0,void 0,function*(){try{yield e.start()}catch(t){const r=`error while starting metric from type: ${e.settings.type}`;this.logger.warn(r,t)}})}stopMetric(e){return __awaiter$1(this,void 0,void 0,function*(){try{yield e.stop()}catch(t){const r=`error while stopping metric from type: ${e.settings.type}`;this.logger.warn(r,t)}})}}manager$2.MetricsManager=MetricsManager,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CustomUpDownCounterMetric=e.CustomHistogramMetric=e.init=void 0;const t=requireDist$1(),r=customHistogram;Object.defineProperty(e,"CustomHistogramMetric",{enumerable:!0,get:function(){return r.CustomHistogramMetric}});const n=customUpDownCounter;Object.defineProperty(e,"CustomUpDownCounterMetric",{enumerable:!0,get:function(){return n.CustomUpDownCounterMetric}});const i=builder$1,o=lazyProvider,s=builder,a=providerFactory,c=manager$2;e.init=function(){(0,t.registerInsightsPlugin)("metrics",()=>({newMetricsManager:(e,t,r,n)=>{var l,u;const d=function(e){const t=(new i.MetricsSettingsBuilder).withSettings(e).build();return t}(e),h=null!==(u=null===(l=e.metrics)||void 0===l?void 0:l.dependencyContainerOverride)&&void 0!==u?u:t,p=null!=r?r:function(e,t,r){return()=>(new a.MetricsMeterProviderFactory).create(e,t,r)}(d,e,n),g=new o.LazyMetricsMeterProvider(p,e.serviceName||"io.Insights"),m=function(e,t,r,n){let i=new s.MetricsFactoryBuilder(t,r,n);(null==e?void 0:e.platformMetricsEnabled)&&(i=i.withDefaults());const o=i.build();return o}(e.metrics,g,h,n);return new c.MetricsManager(e,d,m,g,n)}}))}}(dist$1);var index$1=_mergeNamespaces({__proto__:null},[dist$1]),dist={},manager={},utils={};const SUPPRESS_TRACING_KEY=createContextKey("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function suppressTracing(e){return e.setValue(SUPPRESS_TRACING_KEY,!0)}function isTracingSuppressed(e){return!0===e.getValue(SUPPRESS_TRACING_KEY)}function sanitizeAttributes(e){const t={};if("object"!=typeof e||null==e)return t;for(const r in e){if(!Object.prototype.hasOwnProperty.call(e,r))continue;if(!isAttributeKey(r)){diag.warn(`Invalid attribute key: ${r}`);continue}const n=e[r];isAttributeValue(n)?Array.isArray(n)?t[r]=n.slice():t[r]=n:diag.warn(`Invalid attribute value set for key: ${r}`)}return t}function isAttributeKey(e){return"string"==typeof e&&""!==e}function isAttributeValue(e){return null==e||(Array.isArray(e)?isHomogeneousAttributeValueArray(e):isValidPrimitiveAttributeValueType(typeof e))}function isHomogeneousAttributeValueArray(e){let t;for(const r of e){if(null==r)continue;const e=typeof r;if(e!==t){if(!t){if(isValidPrimitiveAttributeValueType(e)){t=e;continue}return!1}return!1}}return!0}function isValidPrimitiveAttributeValueType(e){switch(e){case"number":case"boolean":case"string":return!0}return!1}function loggingErrorHandler(){return e=>{diag.error(stringifyException(e))}}function stringifyException(e){return"string"==typeof e?e:JSON.stringify(flattenException(e))}function flattenException(e){const t={};let r=e;for(;null!==r;)Object.getOwnPropertyNames(r).forEach(e=>{if(t[e])return;const n=r[e];n&&(t[e]=String(n))}),r=Object.getPrototypeOf(r);return t}let delegateHandler=loggingErrorHandler();function globalErrorHandler(e){try{delegateHandler(e)}catch{}}function getNumberFromEnv(e){}const otperformance=performance,NANOSECOND_DIGITS=9,NANOSECOND_DIGITS_IN_MILLIS=6,MILLISECONDS_TO_NANOSECONDS=Math.pow(10,NANOSECOND_DIGITS_IN_MILLIS),SECOND_TO_NANOSECONDS=Math.pow(10,NANOSECOND_DIGITS);function millisToHrTime(e){const t=e/1e3;return[Math.trunc(t),Math.round(e%1e3*MILLISECONDS_TO_NANOSECONDS)]}function getTimeOrigin(){let e=otperformance.timeOrigin;if("number"!=typeof e){const t=otperformance;e=t.timing&&t.timing.fetchStart}return e}function hrTime(e){return addHrTimes(millisToHrTime(getTimeOrigin()),millisToHrTime("number"==typeof e?e:otperformance.now()))}function hrTimeDuration(e,t){let r=t[0]-e[0],n=t[1]-e[1];return n<0&&(r-=1,n+=SECOND_TO_NANOSECONDS),[r,n]}function hrTimeToMicroseconds(e){return 1e6*e[0]+e[1]/1e3}function isTimeInputHrTime(e){return Array.isArray(e)&&2===e.length&&"number"==typeof e[0]&&"number"==typeof e[1]}function isTimeInput(e){return isTimeInputHrTime(e)||"number"==typeof e||e instanceof Date}function addHrTimes(e,t){const r=[e[0]+t[0],e[1]+t[1]];return r[1]>=SECOND_TO_NANOSECONDS&&(r[1]-=SECOND_TO_NANOSECONDS,r[0]+=1),r}var ExportResultCode;!function(e){e[e.SUCCESS=0]="SUCCESS",e[e.FAILED=1]="FAILED"}(ExportResultCode||(ExportResultCode={}));const objectTag="[object Object]",nullTag="[object Null]",undefinedTag="[object Undefined]",funcProto=Function.prototype,funcToString=funcProto.toString,objectCtorString=funcToString.call(Object),getPrototypeOf=Object.getPrototypeOf,objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty,symToStringTag=Symbol?Symbol.toStringTag:void 0,nativeObjectToString=objectProto.toString;function isPlainObject(e){if(!isObjectLike(e)||baseGetTag(e)!==objectTag)return!1;const t=getPrototypeOf(e);if(null===t)return!0;const r=hasOwnProperty.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&funcToString.call(r)===objectCtorString}function isObjectLike(e){return null!=e&&"object"==typeof e}function baseGetTag(e){return null==e?void 0===e?undefinedTag:nullTag:symToStringTag&&symToStringTag in Object(e)?getRawTag(e):objectToString(e)}function getRawTag(e){const t=hasOwnProperty.call(e,symToStringTag),r=e[symToStringTag];let n=!1;try{e[symToStringTag]=void 0,n=!0}catch{}const i=nativeObjectToString.call(e);return n&&(t?e[symToStringTag]=r:delete e[symToStringTag]),i}function objectToString(e){return nativeObjectToString.call(e)}const MAX_LEVEL=20;function merge(...e){let t=e.shift();const r=new WeakMap;for(;e.length>0;)t=mergeTwoObjects(t,e.shift(),0,r);return t}function takeValue(e){return isArray(e)?e.slice():e}function mergeTwoObjects(e,t,r=0,n){let i;if(!(r>MAX_LEVEL)){if(r++,isPrimitive(e)||isPrimitive(t)||isFunction(t))i=takeValue(t);else if(isArray(e)){if(i=e.slice(),isArray(t))for(let e=0,r=t.length;e<r;e++)i.push(takeValue(t[e]));else if(isObject(t)){const e=Object.keys(t);for(let r=0,n=e.length;r<n;r++){const n=e[r];i[n]=takeValue(t[n])}}}else if(isObject(e))if(isObject(t)){if(!shouldMerge(e,t))return t;i=Object.assign({},e);const o=Object.keys(t);for(let s=0,a=o.length;s<a;s++){const a=o[s],c=t[a];if(isPrimitive(c))void 0===c?delete i[a]:i[a]=c;else{const o=i[a],s=c;if(wasObjectReferenced(e,a,n)||wasObjectReferenced(t,a,n))delete i[a];else{if(isObject(o)&&isObject(s)){const r=n.get(o)||[],i=n.get(s)||[];r.push({obj:e,key:a}),i.push({obj:t,key:a}),n.set(o,r),n.set(s,i)}i[a]=mergeTwoObjects(i[a],c,r,n)}}}}else i=t;return i}}function wasObjectReferenced(e,t,r){const n=r.get(e[t])||[];for(let r=0,i=n.length;r<i;r++){const i=n[r];if(i.key===t&&i.obj===e)return!0}return!1}function isArray(e){return Array.isArray(e)}function isFunction(e){return"function"==typeof e}function isObject(e){return!isPrimitive(e)&&!isArray(e)&&!isFunction(e)&&"object"==typeof e}function isPrimitive(e){return"string"==typeof e||"number"==typeof e||"boolean"==typeof e||void 0===e||e instanceof Date||e instanceof RegExp||null===e}function shouldMerge(e,t){return!(!isPlainObject(e)||!isPlainObject(t))}class Deferred{_promise;_resolve;_reject;constructor(){this._promise=new Promise((e,t)=>{this._resolve=e,this._reject=t})}get promise(){return this._promise}resolve(e){this._resolve(e)}reject(e){this._reject(e)}}class BindOnceFuture{_callback;_that;_isCalled=!1;_deferred=new Deferred;constructor(e,t){this._callback=e,this._that=t}get isCalled(){return this._isCalled}get promise(){return this._deferred.promise}call(...e){if(!this._isCalled){this._isCalled=!0;try{Promise.resolve(this._callback.call(this._that,...e)).then(e=>this._deferred.resolve(e),e=>this._deferred.reject(e))}catch(e){this._deferred.reject(e)}}return this._deferred.promise}}function _export(e,t){return new Promise(r=>{context.with(suppressTracing(context.active()),()=>{e.export(t,e=>{r(e)})})})}const internal={_export:_export},ExceptionEventName="exception";class SpanImpl{_spanContext;kind;parentSpanContext;attributes={};links=[];events=[];startTime;resource;instrumentationScope;_droppedAttributesCount=0;_droppedEventsCount=0;_droppedLinksCount=0;name;status={code:SpanStatusCode.UNSET};endTime=[0,0];_ended=!1;_duration=[-1,-1];_spanProcessor;_spanLimits;_attributeValueLengthLimit;_performanceStartTime;_performanceOffset;_startTimeProvided;constructor(e){const t=Date.now();this._spanContext=e.spanContext,this._performanceStartTime=otperformance.now(),this._performanceOffset=t-(this._performanceStartTime+getTimeOrigin()),this._startTimeProvided=null!=e.startTime,this._spanLimits=e.spanLimits,this._attributeValueLengthLimit=this._spanLimits.attributeValueLengthLimit||0,this._spanProcessor=e.spanProcessor,this.name=e.name,this.parentSpanContext=e.parentSpanContext,this.kind=e.kind,this.links=e.links||[],this.startTime=this._getTime(e.startTime??t),this.resource=e.resource,this.instrumentationScope=e.scope,null!=e.attributes&&this.setAttributes(e.attributes),this._spanProcessor.onStart(this,e.context)}spanContext(){return this._spanContext}setAttribute(e,t){if(null==t||this._isSpanEnded())return this;if(0===e.length)return diag.warn(`Invalid attribute key: ${e}`),this;if(!isAttributeValue(t))return diag.warn(`Invalid attribute value set for key: ${e}`),this;const{attributeCountLimit:r}=this._spanLimits;return void 0!==r&&Object.keys(this.attributes).length>=r&&!Object.prototype.hasOwnProperty.call(this.attributes,e)?(this._droppedAttributesCount++,this):(this.attributes[e]=this._truncateToSize(t),this)}setAttributes(e){for(const[t,r]of Object.entries(e))this.setAttribute(t,r);return this}addEvent(e,t,r){if(this._isSpanEnded())return this;const{eventCountLimit:n}=this._spanLimits;if(0===n)return diag.warn("No events allowed."),this._droppedEventsCount++,this;void 0!==n&&this.events.length>=n&&(0===this._droppedEventsCount&&diag.debug("Dropping extra events."),this.events.shift(),this._droppedEventsCount++),isTimeInput(t)&&(isTimeInput(r)||(r=t),t=void 0);const i=sanitizeAttributes(t);return this.events.push({name:e,attributes:i,time:this._getTime(r),droppedAttributesCount:0}),this}addLink(e){return this.links.push(e),this}addLinks(e){return this.links.push(...e),this}setStatus(e){return this._isSpanEnded()||(this.status={...e},null!=this.status.message&&"string"!=typeof e.message&&(diag.warn(`Dropping invalid status.message of type '${typeof e.message}', expected 'string'`),delete this.status.message)),this}updateName(e){return this._isSpanEnded()||(this.name=e),this}end(e){this._isSpanEnded()?diag.error(`${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`):(this._ended=!0,this.endTime=this._getTime(e),this._duration=hrTimeDuration(this.startTime,this.endTime),this._duration[0]<0&&(diag.warn("Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.",this.startTime,this.endTime),this.endTime=this.startTime.slice(),this._duration=[0,0]),this._droppedEventsCount>0&&diag.warn(`Dropped ${this._droppedEventsCount} events because eventCountLimit reached`),this._spanProcessor.onEnd(this))}_getTime(e){if("number"==typeof e&&e<=otperformance.now())return hrTime(e+this._performanceOffset);if("number"==typeof e)return millisToHrTime(e);if(e instanceof Date)return millisToHrTime(e.getTime());if(isTimeInputHrTime(e))return e;if(this._startTimeProvided)return millisToHrTime(Date.now());const t=otperformance.now()-this._performanceStartTime;return addHrTimes(this.startTime,millisToHrTime(t))}isRecording(){return!1===this._ended}recordException(e,t){const r={};"string"==typeof e?r[ATTR_EXCEPTION_MESSAGE]=e:e&&(e.code?r[ATTR_EXCEPTION_TYPE]=e.code.toString():e.name&&(r[ATTR_EXCEPTION_TYPE]=e.name),e.message&&(r[ATTR_EXCEPTION_MESSAGE]=e.message),e.stack&&(r[ATTR_EXCEPTION_STACKTRACE]=e.stack)),r[ATTR_EXCEPTION_TYPE]||r[ATTR_EXCEPTION_MESSAGE]?this.addEvent(ExceptionEventName,r,t):diag.warn(`Failed to record an exception ${e}`)}get duration(){return this._duration}get ended(){return this._ended}get droppedAttributesCount(){return this._droppedAttributesCount}get droppedEventsCount(){return this._droppedEventsCount}get droppedLinksCount(){return this._droppedLinksCount}_isSpanEnded(){if(this._ended){const e=new Error(`Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`);diag.warn(`Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`,e)}return this._ended}_truncateToLimitUtil(e,t){return e.length<=t?e:e.substring(0,t)}_truncateToSize(e){const t=this._attributeValueLengthLimit;return t<=0?(diag.warn(`Attribute value limit must be positive, got ${t}`),e):"string"==typeof e?this._truncateToLimitUtil(e,t):Array.isArray(e)?e.map(e=>"string"==typeof e?this._truncateToLimitUtil(e,t):e):e}}var SamplingDecision,TracesSamplerValues;!function(e){e[e.NOT_RECORD=0]="NOT_RECORD",e[e.RECORD=1]="RECORD",e[e.RECORD_AND_SAMPLED=2]="RECORD_AND_SAMPLED"}(SamplingDecision||(SamplingDecision={}));class AlwaysOffSampler{shouldSample(){return{decision:SamplingDecision.NOT_RECORD}}toString(){return"AlwaysOffSampler"}}class AlwaysOnSampler{shouldSample(){return{decision:SamplingDecision.RECORD_AND_SAMPLED}}toString(){return"AlwaysOnSampler"}}class ParentBasedSampler{_root;_remoteParentSampled;_remoteParentNotSampled;_localParentSampled;_localParentNotSampled;constructor(e){this._root=e.root,this._root||(globalErrorHandler(new Error("ParentBasedSampler must have a root sampler configured")),this._root=new AlwaysOnSampler),this._remoteParentSampled=e.remoteParentSampled??new AlwaysOnSampler,this._remoteParentNotSampled=e.remoteParentNotSampled??new AlwaysOffSampler,this._localParentSampled=e.localParentSampled??new AlwaysOnSampler,this._localParentNotSampled=e.localParentNotSampled??new AlwaysOffSampler}shouldSample(e,t,r,n,i,o){const s=trace.getSpanContext(e);return s&&isSpanContextValid(s)?s.isRemote?s.traceFlags&TraceFlags.SAMPLED?this._remoteParentSampled.shouldSample(e,t,r,n,i,o):this._remoteParentNotSampled.shouldSample(e,t,r,n,i,o):s.traceFlags&TraceFlags.SAMPLED?this._localParentSampled.shouldSample(e,t,r,n,i,o):this._localParentNotSampled.shouldSample(e,t,r,n,i,o):this._root.shouldSample(e,t,r,n,i,o)}toString(){return`ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`}}class TraceIdRatioBasedSampler{_ratio;_upperBound;constructor(e=0){this._ratio=e,this._ratio=this._normalize(e),this._upperBound=Math.floor(4294967295*this._ratio)}shouldSample(e,t){return{decision:isValidTraceId(t)&&this._accumulate(t)<this._upperBound?SamplingDecision.RECORD_AND_SAMPLED:SamplingDecision.NOT_RECORD}}toString(){return`TraceIdRatioBased{${this._ratio}}`}_normalize(e){return"number"!=typeof e||isNaN(e)?0:e>=1?1:e<=0?0:e}_accumulate(e){let t=0;for(let r=0;r<e.length/8;r++){const n=8*r;t=(t^parseInt(e.slice(n,n+8),16))>>>0}return t}}!function(e){e.AlwaysOff="always_off",e.AlwaysOn="always_on",e.ParentBasedAlwaysOff="parentbased_always_off",e.ParentBasedAlwaysOn="parentbased_always_on",e.ParentBasedTraceIdRatio="parentbased_traceidratio",e.TraceIdRatio="traceidratio"}(TracesSamplerValues||(TracesSamplerValues={}));const DEFAULT_RATIO=1;function loadDefaultConfig(){return{sampler:buildSamplerFromEnv(),forceFlushTimeoutMillis:3e4,generalLimits:{attributeValueLengthLimit:1/0,attributeCountLimit:128},spanLimits:{attributeValueLengthLimit:1/0,attributeCountLimit:128,linkCountLimit:128,eventCountLimit:128,attributePerEventCountLimit:128,attributePerLinkCountLimit:128}}}function buildSamplerFromEnv(){const e=TracesSamplerValues.ParentBasedAlwaysOn;switch(e){case TracesSamplerValues.AlwaysOn:return new AlwaysOnSampler;case TracesSamplerValues.AlwaysOff:return new AlwaysOffSampler;case TracesSamplerValues.ParentBasedAlwaysOn:return new ParentBasedSampler({root:new AlwaysOnSampler});case TracesSamplerValues.ParentBasedAlwaysOff:return new ParentBasedSampler({root:new AlwaysOffSampler});case TracesSamplerValues.TraceIdRatio:return new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv());case TracesSamplerValues.ParentBasedTraceIdRatio:return new ParentBasedSampler({root:new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv())});default:return diag.error(`OTEL_TRACES_SAMPLER value "${e}" invalid, defaulting to "${TracesSamplerValues.ParentBasedAlwaysOn}".`),new ParentBasedSampler({root:new AlwaysOnSampler})}}function getSamplerProbabilityFromEnv(){return diag.error(`OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${DEFAULT_RATIO}.`),DEFAULT_RATIO}const DEFAULT_ATTRIBUTE_COUNT_LIMIT=128,DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT=1/0;function mergeConfig(e){const t={sampler:buildSamplerFromEnv()},r=loadDefaultConfig(),n=Object.assign({},r,t,e);return n.generalLimits=Object.assign({},r.generalLimits,e.generalLimits||{}),n.spanLimits=Object.assign({},r.spanLimits,e.spanLimits||{}),n}function reconfigureLimits(e){const t=Object.assign({},e.spanLimits);return t.attributeCountLimit=e.spanLimits?.attributeCountLimit??e.generalLimits?.attributeCountLimit??getNumberFromEnv()??getNumberFromEnv()??DEFAULT_ATTRIBUTE_COUNT_LIMIT,t.attributeValueLengthLimit=e.spanLimits?.attributeValueLengthLimit??e.generalLimits?.attributeValueLengthLimit??getNumberFromEnv()??getNumberFromEnv()??DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,Object.assign({},e,{spanLimits:t})}class BatchSpanProcessorBase{_exporter;_maxExportBatchSize;_maxQueueSize;_scheduledDelayMillis;_exportTimeoutMillis;_isExporting=!1;_finishedSpans=[];_timer;_shutdownOnce;_droppedSpansCount=0;constructor(e,t){this._exporter=e,this._maxExportBatchSize="number"==typeof t?.maxExportBatchSize?t.maxExportBatchSize:512,this._maxQueueSize="number"==typeof t?.maxQueueSize?t.maxQueueSize:2048,this._scheduledDelayMillis="number"==typeof t?.scheduledDelayMillis?t.scheduledDelayMillis:5e3,this._exportTimeoutMillis="number"==typeof t?.exportTimeoutMillis?t.exportTimeoutMillis:3e4,this._shutdownOnce=new BindOnceFuture(this._shutdown,this),this._maxExportBatchSize>this._maxQueueSize&&(diag.warn("BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize"),this._maxExportBatchSize=this._maxQueueSize)}forceFlush(){return this._shutdownOnce.isCalled?this._shutdownOnce.promise:this._flushAll()}onStart(e,t){}onEnd(e){this._shutdownOnce.isCalled||0!==(e.spanContext().traceFlags&TraceFlags.SAMPLED)&&this._addToBuffer(e)}shutdown(){return this._shutdownOnce.call()}_shutdown(){return Promise.resolve().then(()=>this.onShutdown()).then(()=>this._flushAll()).then(()=>this._exporter.shutdown())}_addToBuffer(e){if(this._finishedSpans.length>=this._maxQueueSize)return 0===this._droppedSpansCount&&diag.debug("maxQueueSize reached, dropping spans"),void this._droppedSpansCount++;this._droppedSpansCount>0&&(diag.warn(`Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`),this._droppedSpansCount=0),this._finishedSpans.push(e),this._maybeStartTimer()}_flushAll(){return new Promise((e,t)=>{const r=[];for(let e=0,t=Math.ceil(this._finishedSpans.length/this._maxExportBatchSize);e<t;e++)r.push(this._flushOneBatch());Promise.all(r).then(()=>{e()}).catch(t)})}_flushOneBatch(){return this._clearTimer(),0===this._finishedSpans.length?Promise.resolve():new Promise((e,t)=>{const r=setTimeout(()=>{t(new Error("Timeout"))},this._exportTimeoutMillis);context.with(suppressTracing(context.active()),()=>{let n;this._finishedSpans.length<=this._maxExportBatchSize?(n=this._finishedSpans,this._finishedSpans=[]):n=this._finishedSpans.splice(0,this._maxExportBatchSize);const i=()=>this._exporter.export(n,n=>{clearTimeout(r),n.code===ExportResultCode.SUCCESS?e():t(n.error??new Error("BatchSpanProcessor: span export failed"))});let o=null;for(let e=0,t=n.length;e<t;e++){const t=n[e];t.resource.asyncAttributesPending&&t.resource.waitForAsyncAttributes&&(o??=[],o.push(t.resource.waitForAsyncAttributes()))}null===o?i():Promise.all(o).then(i,e=>{globalErrorHandler(e),t(e)})})})}_maybeStartTimer(){if(this._isExporting)return;const e=()=>{this._isExporting=!0,this._flushOneBatch().finally(()=>{this._isExporting=!1,this._finishedSpans.length>0&&(this._clearTimer(),this._maybeStartTimer())}).catch(e=>{this._isExporting=!1,globalErrorHandler(e)})};if(this._finishedSpans.length>=this._maxExportBatchSize)return e();void 0===this._timer&&(this._timer=setTimeout(()=>e(),this._scheduledDelayMillis),"number"!=typeof this._timer&&this._timer.unref())}_clearTimer(){void 0!==this._timer&&(clearTimeout(this._timer),this._timer=void 0)}}class BatchSpanProcessor extends BatchSpanProcessorBase{_visibilityChangeListener;_pageHideListener;constructor(e,t){super(e,t),this.onInit(t)}onInit(e){!0!==e?.disableAutoFlushOnDocumentHide&&"undefined"!=typeof document&&(this._visibilityChangeListener=()=>{"hidden"===document.visibilityState&&this.forceFlush().catch(e=>{globalErrorHandler(e)})},this._pageHideListener=()=>{this.forceFlush().catch(e=>{globalErrorHandler(e)})},document.addEventListener("visibilitychange",this._visibilityChangeListener),document.addEventListener("pagehide",this._pageHideListener))}onShutdown(){"undefined"!=typeof document&&(this._visibilityChangeListener&&document.removeEventListener("visibilitychange",this._visibilityChangeListener),this._pageHideListener&&document.removeEventListener("pagehide",this._pageHideListener))}}const SPAN_ID_BYTES=8,TRACE_ID_BYTES=16;class RandomIdGenerator{generateTraceId=getIdGenerator(TRACE_ID_BYTES);generateSpanId=getIdGenerator(SPAN_ID_BYTES)}const SHARED_CHAR_CODES_ARRAY=Array(32);function getIdGenerator(e){return function(){for(let t=0;t<2*e;t++)SHARED_CHAR_CODES_ARRAY[t]=Math.floor(16*Math.random())+48,SHARED_CHAR_CODES_ARRAY[t]>=58&&(SHARED_CHAR_CODES_ARRAY[t]+=39);return String.fromCharCode.apply(null,SHARED_CHAR_CODES_ARRAY.slice(0,2*e))}}class Tracer{_sampler;_generalLimits;_spanLimits;_idGenerator;instrumentationScope;_resource;_spanProcessor;constructor(e,t,r,n){const i=mergeConfig(t);this._sampler=i.sampler,this._generalLimits=i.generalLimits,this._spanLimits=i.spanLimits,this._idGenerator=t.idGenerator||new RandomIdGenerator,this._resource=r,this._spanProcessor=n,this.instrumentationScope=e}startSpan(e,t={},r=context.active()){t.root&&(r=trace.deleteSpan(r));const n=trace.getSpan(r);if(isTracingSuppressed(r)){diag.debug("Instrumentation suppressed, returning Noop Span");return trace.wrapSpanContext(INVALID_SPAN_CONTEXT)}const i=n?.spanContext(),o=this._idGenerator.generateSpanId();let s,a,c;i&&trace.isSpanContextValid(i)?(a=i.traceId,c=i.traceState,s=i):a=this._idGenerator.generateTraceId();const l=t.kind??SpanKind.INTERNAL,u=(t.links??[]).map(e=>({context:e.context,attributes:sanitizeAttributes(e.attributes)})),d=sanitizeAttributes(t.attributes),h=this._sampler.shouldSample(r,a,e,l,d,u);c=h.traceState??c;const p={traceId:a,spanId:o,traceFlags:h.decision===SamplingDecision$1.RECORD_AND_SAMPLED?TraceFlags.SAMPLED:TraceFlags.NONE,traceState:c};if(h.decision===SamplingDecision$1.NOT_RECORD){diag.debug("Recording is off, propagating context in a non-recording span");return trace.wrapSpanContext(p)}const g=sanitizeAttributes(Object.assign(d,h.attributes));return new SpanImpl({resource:this._resource,scope:this.instrumentationScope,context:r,spanContext:p,name:e,kind:l,links:u,parentSpanContext:s,attributes:g,startTime:t.startTime,spanProcessor:this._spanProcessor,spanLimits:this._spanLimits})}startActiveSpan(e,t,r,n){let i,o,s;if(arguments.length<2)return;2===arguments.length?s=t:3===arguments.length?(i=t,s=r):(i=t,o=r,s=n);const a=o??context.active(),c=this.startSpan(e,i,a),l=trace.setSpan(a,c);return context.with(l,s,void 0,c)}getGeneralLimits(){return this._generalLimits}getSpanLimits(){return this._spanLimits}}class MultiSpanProcessor{_spanProcessors;constructor(e){this._spanProcessors=e}forceFlush(){const e=[];for(const t of this._spanProcessors)e.push(t.forceFlush());return new Promise(t=>{Promise.all(e).then(()=>{t()}).catch(e=>{globalErrorHandler(e||new Error("MultiSpanProcessor: forceFlush failed")),t()})})}onStart(e,t){for(const r of this._spanProcessors)r.onStart(e,t)}onEnd(e){for(const t of this._spanProcessors)t.onEnd(e)}shutdown(){const e=[];for(const t of this._spanProcessors)e.push(t.shutdown());return new Promise((t,r)=>{Promise.all(e).then(()=>{t()},r)})}}var ForceFlushState;!function(e){e[e.resolved=0]="resolved",e[e.timeout=1]="timeout",e[e.error=2]="error",e[e.unresolved=3]="unresolved"}(ForceFlushState||(ForceFlushState={}));class BasicTracerProvider{_config;_tracers=new Map;_resource;_activeSpanProcessor;constructor(e={}){const t=merge({},loadDefaultConfig(),reconfigureLimits(e));this._resource=t.resource??defaultResource$1(),this._config=Object.assign({},t,{resource:this._resource});const r=[];e.spanProcessors?.length&&r.push(...e.spanProcessors),this._activeSpanProcessor=new MultiSpanProcessor(r)}getTracer(e,t,r){const n=`${e}@${t||""}:${r?.schemaUrl||""}`;return this._tracers.has(n)||this._tracers.set(n,new Tracer({name:e,version:t,schemaUrl:r?.schemaUrl},this._config,this._resource,this._activeSpanProcessor)),this._tracers.get(n)}forceFlush(){const e=this._config.forceFlushTimeoutMillis,t=this._activeSpanProcessor._spanProcessors.map(t=>new Promise(r=>{let n;const i=setTimeout(()=>{r(new Error(`Span processor did not completed within timeout period of ${e} ms`)),n=ForceFlushState.timeout},e);t.forceFlush().then(()=>{clearTimeout(i),n!==ForceFlushState.timeout&&(n=ForceFlushState.resolved,r(n))}).catch(e=>{clearTimeout(i),n=ForceFlushState.error,r(e)})}));return new Promise((e,r)=>{Promise.all(t).then(t=>{const n=t.filter(e=>e!==ForceFlushState.resolved);n.length>0?r(n):e()}).catch(e=>r([e]))})}shutdown(){return this._activeSpanProcessor.shutdown()}}class ConsoleSpanExporter{export(e,t){return this._sendSpans(e,t)}shutdown(){return this._sendSpans([]),this.forceFlush()}forceFlush(){return Promise.resolve()}_exportInfo(e){return{resource:{attributes:e.resource.attributes},instrumentationScope:e.instrumentationScope,traceId:e.spanContext().traceId,parentSpanContext:e.parentSpanContext,traceState:e.spanContext().traceState?.serialize(),name:e.name,id:e.spanContext().spanId,kind:e.kind,timestamp:hrTimeToMicroseconds(e.startTime),duration:hrTimeToMicroseconds(e.duration),attributes:e.attributes,status:e.status,events:e.events,links:e.links}}_sendSpans(e,t){for(const t of e)console.dir(this._exportInfo(t),{depth:3});if(t)return t({code:ExportResultCode.SUCCESS})}}class InMemorySpanExporter{_finishedSpans=[];_stopped=!1;export(e,t){if(this._stopped)return t({code:ExportResultCode.FAILED,error:new Error("Exporter has been stopped")});this._finishedSpans.push(...e),setTimeout(()=>t({code:ExportResultCode.SUCCESS}),0)}shutdown(){return this._stopped=!0,this._finishedSpans=[],this.forceFlush()}forceFlush(){return Promise.resolve()}reset(){this._finishedSpans=[]}getFinishedSpans(){return this._finishedSpans}}class SimpleSpanProcessor{_exporter;_shutdownOnce;_pendingExports;constructor(e){this._exporter=e,this._shutdownOnce=new BindOnceFuture(this._shutdown,this),this._pendingExports=new Set}async forceFlush(){await Promise.all(Array.from(this._pendingExports)),this._exporter.forceFlush&&await this._exporter.forceFlush()}onStart(e,t){}onEnd(e){if(this._shutdownOnce.isCalled)return;if(0===(e.spanContext().traceFlags&TraceFlags.SAMPLED))return;const t=this._doExport(e).catch(e=>globalErrorHandler(e));this._pendingExports.add(t),t.finally(()=>this._pendingExports.delete(t))}async _doExport(e){e.resource.asyncAttributesPending&&await(e.resource.waitForAsyncAttributes?.());const t=await internal._export(this._exporter,[e]);if(t.code!==ExportResultCode.SUCCESS)throw t.error??new Error(`SimpleSpanProcessor: span export failed (status ${t})`)}shutdown(){return this._shutdownOnce.call()}_shutdown(){return this._exporter.shutdown()}}class NoopSpanProcessor{onStart(e,t){}onEnd(e){}shutdown(){return Promise.resolve()}forceFlush(){return Promise.resolve()}}var esm$1=Object.freeze({__proto__:null,AlwaysOffSampler:AlwaysOffSampler,AlwaysOnSampler:AlwaysOnSampler,BasicTracerProvider:BasicTracerProvider,BatchSpanProcessor:BatchSpanProcessor,ConsoleSpanExporter:ConsoleSpanExporter,InMemorySpanExporter:InMemorySpanExporter,NoopSpanProcessor:NoopSpanProcessor,ParentBasedSampler:ParentBasedSampler,RandomIdGenerator:RandomIdGenerator,get SamplingDecision(){return SamplingDecision},SimpleSpanProcessor:SimpleSpanProcessor,TraceIdRatioBasedSampler:TraceIdRatioBasedSampler}),require$$0=getAugmentedNamespace(esm$1),durationFilterProcessor={};Object.defineProperty(durationFilterProcessor,"__esModule",{value:!0}),durationFilterProcessor.DurationFilterProcessor=void 0;class DurationFilterProcessor{constructor(e){this._innerProcessor=e}onStart(e,t){this._innerProcessor.onStart(e,t)}onEnd(e){const t=e.attributes.insightsMinDurationMs&&parseInt(e.attributes.insightsMinDurationMs+"",10);if(t){1e9*e.endTime[0]+e.endTime[1]-(1e9*e.startTime[0]+e.startTime[1])>=1e6*t&&this._innerProcessor.onEnd(e)}else this._innerProcessor.onEnd(e)}shutdown(){return this._innerProcessor.shutdown()}forceFlush(){return this._innerProcessor.forceFlush()}}durationFilterProcessor.DurationFilterProcessor=DurationFilterProcessor;var parentOperationSpanProcessor={};Object.defineProperty(parentOperationSpanProcessor,"__esModule",{value:!0}),parentOperationSpanProcessor.ParentOperationSpanProcessor=void 0;const api_1$1=require$$0$2;class ParentOperationSpanProcessor{constructor(e,t){this._innerProcessor=e,this.nameLimit=t}onStart(e,t){var r,n;if(this.nameLimit)try{const i=ParentOperationSpanProcessor._spanToName,o=ParentOperationSpanProcessor._spanNames,s=e.spanContext().spanId;if(!i.has(s)&&(i.set(s,e.name),this.nameLimit>0))for(o.push(e.name);o.length>this.nameLimit;)i.delete(o[0]),o.shift();const a=api_1$1.trace.getSpan(null!=t?t:api_1$1.context.active());a&&e.setAttribute("insights.parent.operation",null!==(r=a.name)&&void 0!==r?r:i.get(null===(n=a.spanContext())||void 0===n?void 0:n.spanId))}catch(e){}this._innerProcessor.onStart(e,t)}onEnd(e){this._innerProcessor.onEnd(e)}forceFlush(){return this._innerProcessor.forceFlush()}shutdown(){return this._innerProcessor.shutdown()}}parentOperationSpanProcessor.ParentOperationSpanProcessor=ParentOperationSpanProcessor,ParentOperationSpanProcessor._spanNames=[],ParentOperationSpanProcessor._spanToName=new Map;var ioInsightsSampler$1={};Object.defineProperty(ioInsightsSampler$1,"__esModule",{value:!0}),ioInsightsSampler$1.ioInsightsSampler=void 0;const otel_1$5=requireDist$1(),cyrb53=(e,t=0)=>{let r=3735928559^t,n=1103547991^t;for(let t,i=0;i<e.length;i++)t=e.charCodeAt(i),r=Math.imul(r^t,2654435761),n=Math.imul(n^t,1597334677);return r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),4294967296*(2097151&n)+(r>>>0)};class ioInsightsSampler{constructor(e,t,r,n){this.settings=e,this.defaults=t,this.filteringContextGetter=r,this.logger=n}shouldSample(e,t,r,n,i,o){var s,a,c,l,u,d,h,p,g,m,f,y;const $=otel_1$5.Container.errorless(()=>{var e;return null===(e=this.filteringContextGetter)||void 0===e?void 0:e.call(null)})||{};for(const e of this.settings||[]){let n=!0;if(n&&e.name&&(this.matchObjects("name",{name:e.name},{name:r})||(n=!1)),n&&e.attributes&&(this.matchObjects("attributes",e.attributes,i)||(n=!1)),n&&e.context&&(this.matchObjects("context",e.context,$,!0)||(n=!1)),n)return(null===(l=this.logger)||void 0===l?void 0:l.level)&&(null===(u=this.logger)||void 0===u?void 0:u.level)>=80&&(null===(d=this.logger)||void 0===d||d.verbose("sampling rule matched: "+JSON.stringify(e))),this.maybeSample(t,e.sample);(null===(s=this.logger)||void 0===s?void 0:s.level)&&(null===(a=this.logger)||void 0===a?void 0:a.level)>=80&&(null===(c=this.logger)||void 0===c||c.verbose("sampling rule didn't match: "+JSON.stringify(e)))}return(null===(h=this.logger)||void 0===h?void 0:h.level)&&(null===(p=this.logger)||void 0===p?void 0:p.level)>=80&&(null===(g=this.logger)||void 0===g||g.verbose("no sampling rule matched, will fall back to defaults "+JSON.stringify(this.defaults||{}))),this.defaults?this.maybeSample(t,this.defaults.sample||!0):((null===(m=this.logger)||void 0===m?void 0:m.level)&&(null===(f=this.logger)||void 0===f?void 0:f.level)>=80&&(null===(y=this.logger)||void 0===y||y.verbose("no sampling rule matched, no defaults - will sample")),{decision:2})}toString(){try{return"ioInsightsSampler: "+JSON.stringify({settings:this.settings,defaults:this.defaults})}catch(e){return"ioInsightsSampler: (error) "+e.message}}matchObjects(e,t,r,n){var i,o,s,a,c,l;for(const[u,d]of Object.entries(t)){const t=n?(0,otel_1$5.deep_value)(r,u):r[u];if("string"==typeof d&&"#"===d[0]&&(null==t||!new RegExp(d.substring(1),"i").test(t+"")))return(null===(i=this.logger)||void 0===i?void 0:i.level)&&(null===(o=this.logger)||void 0===o?void 0:o.level)>=80&&(null===(s=this.logger)||void 0===s||s.verbose(`matching ${e}: regex ${d} doesn't match ${t}`)),!1;if(d!==t)return(null===(a=this.logger)||void 0===a?void 0:a.level)&&(null===(c=this.logger)||void 0===c?void 0:c.level)>=80&&(null===(l=this.logger)||void 0===l||l.verbose(`matching ${e}: ${d} doesn't match ${t}`)),!1}return!0}maybeSample(e,t){var r,n,i;let o;if(!0===t||"number"==typeof t&&t>=1)o={decision:2};else if(!1===t||"number"==typeof t&&t<=0)o={decision:0};else{const r=cyrb53(e);o={decision:r/1e3-Math.floor(r/1e3)<=t?2:0}}return(null===(r=this.logger)||void 0===r?void 0:r.level)&&(null===(n=this.logger)||void 0===n?void 0:n.level)>=80&&(null===(i=this.logger)||void 0===i||i.verbose(`sampling decision with value ${t}: ${JSON.stringify(o)}`)),o}}ioInsightsSampler$1.ioInsightsSampler=ioInsightsSampler;class OTLPTraceExporter extends OTLPExporterBase{constructor(e={}){super(createLegacyOtlpBrowserExportDelegate(e,JsonTraceSerializer,"v1/traces",{"Content-Type":"application/json"}))}}var esm=Object.freeze({__proto__:null,OTLPTraceExporter:OTLPTraceExporter}),require$$6=getAugmentedNamespace(esm),require$$7=getAugmentedNamespace(esm$3);!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.saveDataInAttribute=e.isFunctionType=e.setTracerProvider=e.isFilterMatch=e.findMatchingFilters=e.isSpanEnabled=void 0;const t=require$$0,r=require$$0$2,n=require$$0$2,i=durationFilterProcessor,o=parentOperationSpanProcessor,s=ioInsightsSampler$1,a=requireDist$1(),c=require$$6,l=require$$7;e.isSpanEnabled=(e,t,r)=>{var n,i;let o;return o=e?void 0===e.enabled||e.enabled:null===(i=null!==(n=null==t?void 0:t.enabled)&&void 0!==n?n:null==r?void 0:r.enabled)||void 0===i||i,o};e.findMatchingFilters=(t,r,n)=>{let i=!1;const o={},s={source:"",context:{},enabled:!1,stopPropagationIfSpanIsDisabled:!1,level:"INFO",addContextToTrace:!1,autoSetSuccessStatus:!1,sample:0,disablePropagation:!1,disableNesting:!1,countMetric:!1,countMetricOnDisabledSpans:!1,resultMetric:!1,resultMetricOnDisabledSpans:!1,durationMetric:!1,durationMetricOnDisabledSpans:!1,canBeRoot:!1,maxAttributeDepth:0,forceChildTracing:!1,otelSpanOptions:{},minDurationMs:0,log:!1,logOnDisabledSpans:!1,overrideDefaultFilters:!1};for(const a of t)if((0,e.isFilterMatch)(a,r,n)){i=!0;for(const e of Object.keys(s))void 0===o[e]&&(o[e]=a[e])}return i?o:void 0};e.isFilterMatch=(e,t,r)=>{let n=!0;if(e.source&&e.source.startsWith("#")){if(!new RegExp(e.source.substring(1),"i").test(r))return 0}else if(e.source&&r!==e.source&&!r.startsWith(e.source+".")&&r+"."!==e.source)return 0;if(!e.context)return 1;for(const r of Object.keys(e.context)){const i=e.context[r],o=(0,a.deep_value)(t,r);if("string"!=typeof i||"#"!==i[0]){i!==o&&(n=!1);break}if(null==o||!new RegExp(i.substring(1),"i").test(o+"")){n=!1;break}}return n?2:0};e.setTracerProvider=(e,u)=>{var d,h,p,g,m,f;if(!e)throw new Error("Required arguments not provided");const y=(0,a.loadInsightsPlugin)("base",u);if(!y)return;const $=e.traces,b=null==$?void 0:$.processorSettings,w=Object.assign(Object.assign({url:$.url,concurrencyLimit:$.concurrencyLimit,timeoutMillis:$.timeoutMillis,compression:$.compression,keepAlive:$.keepAlive},$.exporterSettings),{headers:Object.assign(Object.assign(Object.assign({},a.Container.errorless(e.headers)),a.Container.errorless(null===(d=$.exporterSettings)||void 0===d?void 0:d.headers)),a.Container.errorless($.headers))}),v=a.Container.errorless(()=>{var t;return null===(t=$.spanProcessors)||void 0===t?void 0:t.call($,b,w,$,e)})||[];let S=a.Container.errorless(()=>{var t;return null===(t=$.spanExporters)||void 0===t?void 0:t.call($,"string"==typeof w?{url:w}:w,$,e)})||[];if(!(null==$?void 0:$.url)||(null==S?void 0:S.length)||(null==v?void 0:v.length)||(S=[new c.OTLPTraceExporter(w)]),(null==$?void 0:$.console)&&S.push(new t.ConsoleSpanExporter),S)for(const e of S)v.push(new t.BatchSpanProcessor(e,b));const E=[];if(v)for(const e of v)E.push(new o.ParentOperationSpanProcessor(new i.DurationFilterProcessor(e),null==$?void 0:$.parentNameLimit));const C=new t.ParentBasedSampler({root:new s.ioInsightsSampler((null==$?void 0:$.sampling)||[],null==$?void 0:$.defaults,()=>Object.assign(Object.assign({},a.Container.errorless(null==$?void 0:$.additionalResourceAttributes)),a.Container.errorless(null==$?void 0:$.additionalAttributes)),u)}),_=a.Container.errorless(()=>{var t;return null===(t=$.sampler)||void 0===t?void 0:t.call($,C,$,e)}),I=Object.assign({sampler:null!=_?_:C,resource:y.resourceFromAttributes(null!==(h=a.Container.errorless(null==$?void 0:$.additionalResourceAttributes))&&void 0!==h?h:{}),spanProcessors:E},null==$?void 0:$.tracerProviderSettings),T=null!==(p=a.Container.errorless(()=>{var t;return null===(t=$.tracerProvider)||void 0===t?void 0:t.call($,I,$,e)}))&&void 0!==p?p:new t.BasicTracerProvider(I);r.trace.disable(),r.trace.setGlobalTracerProvider(T);const A=a.Container.errorless(()=>{var t;return null===(t=$.providerRegistrationSettings)||void 0===t?void 0:t.call($,$,e)}),D=null!==(g=a.Container.errorless(()=>{var t;return"function"==typeof $.contextManager?null===(t=$.contextManager)||void 0===t?void 0:t.call($,$,e):$.contextManager}))&&void 0!==g?g:null==A?void 0:A.contextManager,x=null!==(f=null!==(m=a.Container.errorless(()=>{var t;return null===(t=$.propagator)||void 0===t?void 0:t.call($,$,e)}))&&void 0!==m?m:null==A?void 0:A.propagator)&&void 0!==f?f:new l.W3CTraceContextPropagator;return D&&(D.enable(),n.context.setGlobalContextManager(D)),r.propagation.setGlobalPropagator(x),"function"==typeof T.register&&T.register(A||{}),{tracerProvider:T,spanProcessors:E}};e.isFunctionType=e=>"function"==typeof e;e.saveDataInAttribute=(e,t,r)=>{var n;if(null!=e){"object"!=typeof e&&(e={unknownAttribute:e});for(const[i,o]of Object.entries(e)){const e=(0,a.getOTELData)(i,o,0,r);for(const[r,i]of e)"function"==typeof(null===(n=t.otelSpan)||void 0===n?void 0:n.setAttribute)?t.otelSpan.setAttribute(r,i):"object"==typeof t.attributes&&(t.attributes[r]=i)}}}}(utils);var tracingState={};Object.defineProperty(tracingState,"__esModule",{value:!0}),tracingState.TracingState=void 0;const utils_1$1=utils,otel_1$4=requireDist$1();class TracingState{constructor(e,t,r,n,i,o,s,a,c){this.source=e,this.level=t,this.span=r,this.logger=n,this.version=i,this.disablePropagation=o,this.forceChildTracing=s,this.maxAttributeDepth=a,this.context=c,this.currentSpanStatus={code:otel_1$4.SpanStatusCode.UNSET},this._startTime=new Date,this.hasEnded=!1,this.spanContextField=r.spanContext()}get startTime(){return this._startTime}get endTime(){return this._endTime}end(){return this.endSpan()}endSpan(e,t){var r;return this.hasEnded?t||null===(r=this.logger)||void 0===r||r.debug(`Span ended more than once: ${this.source}`):(this.hasEnded=!0,this._endTime=null!=e?e:new Date,this.span.end(e)),Promise.resolve()}get enabled(){return!0}get id(){return this.spanContextField.spanId}get traceId(){return this.spanContextField.traceId}set status(e){this.currentSpanStatus=Object.assign({},e),this.span.setStatus.call(this.span,e)}get status(){return this.currentSpanStatus}addEvent(e,t,r){return this.span.addEvent.call(this.span,e,t,r),this}recordException(e,t){this.span.recordException.call(this.span,e,t)}isRecording(){return this.span.isRecording.call(this.span)}updateName(e){return this.span.updateName.call(this.span,e),this}spanContext(){return this.span.spanContext.call(this.span)}addData(e,t){var r;"function"==typeof t&&(t=t()),"string"==typeof e&&(e=SpanVerbosity[e]),e>=SpanVerbosity[this.level]&&(0,utils_1$1.saveDataInAttribute)(t,{otelSpan:this.span},null!==(r=this.maxAttributeDepth)&&void 0!==r?r:5)}getPropagationInfo(){const e={traceparent:`${this.version}-${this.spanContextField.traceId}-${this.spanContextField.spanId}-0${this.spanContextField.traceFlags}`,tracestate:this.spanContextField.traceState&&String(this.spanContextField.traceState)};return this.forceChildTracing&&(e.forceTracing=!0),e}injectPropagationInfo(e){if(this.disablePropagation)return;const t=this.getPropagationInfo();t&&(e.__interopIOTracePropagationInfo=t)}}var SpanVerbosity;tracingState.TracingState=TracingState,function(e){e[e.OFF=0]="OFF",e[e.LOWEST=1]="LOWEST",e[e.DIAGNOSTIC=2]="DIAGNOSTIC",e[e.DEBUG=3]="DEBUG",e[e.INFO=4]="INFO",e[e.WARN=5]="WARN",e[e.HIGHEST=6]="HIGHEST"}(SpanVerbosity||(SpanVerbosity={}));var clickstream={};Object.defineProperty(clickstream,"__esModule",{value:!0}),clickstream.instrumentRequests=clickstream.setupClickstreamTrace=void 0;const otel_1$3=requireDist$1(),listenerMap=new WeakMap,eventRoot=new WeakMap;let clickstreamPropagationInfo=null,clickstreamTracingState=null,clickstreamTracePrefix,structure;function setupClickstreamTrace(e){var t,r,n,i,o,s,a,c,l,u,d,h,p,g,m,f,y,$;if("undefined"==typeof window)return;const b=e.applicationName;if(!e.traces||!1===e.traces.clickstream||"object"==typeof e.traces.clickstream&&!(null===(t=e.traces.clickstream)||void 0===t?void 0:t.enabled))return;structure=null!==(s="string"==typeof(null===(r=e.traces)||void 0===r?void 0:r.clickstream)?null===(n=e.traces)||void 0===n?void 0:n.clickstream:"object"==typeof(null===(i=e.traces)||void 0===i?void 0:i.clickstream)?null===(o=e.traces)||void 0===o?void 0:o.clickstream.structure:null)&&void 0!==s?s:"sibling";const w=null===(u="string"==typeof(null===(a=e.traces)||void 0===a?void 0:a.clickstream)?null:"object"==typeof(null===(c=e.traces)||void 0===c?void 0:c.clickstream)?null===(l=e.traces)||void 0===l?void 0:l.clickstream.descriptiveName:null)||void 0===u||u,v=null!==(g="string"==typeof(null===(d=e.traces)||void 0===d?void 0:d.clickstream)?null:"object"==typeof(null===(h=e.traces)||void 0===h?void 0:h.clickstream)?null===(p=e.traces)||void 0===p?void 0:p.clickstream.events:null)&&void 0!==g?g:["click"],S=null===($="string"==typeof(null===(m=e.traces)||void 0===m?void 0:m.clickstream)?null:"object"==typeof(null===(f=e.traces)||void 0===f?void 0:f.clickstream)?null===(y=e.traces)||void 0===y?void 0:y.clickstream.nestEventListeners:null)||void 0===$||$;clickstreamTracePrefix=w?"interopio.api.clickstream."+b+".":"interopio.api.clickstream.";const E=EventTarget.prototype.addEventListener,C=EventTarget.prototype.removeEventListener;for(const e of v)document.addEventListener(e,e=>{maybeStartClickstream(),getOrCreateEventRoot(e)},{capture:!0});return S&&(EventTarget.prototype.addEventListener=function(e,t,r){return t&&v.find(t=>t===e)?E.call(this,e,wrapListener(this,t,clickstreamTracePrefix),r):E.call(this,e,t,r)},EventTarget.prototype.removeEventListener=function(e,t,r){var n;if(!t||!v.find(t=>t===e))return C.call(this,e,t,r);const i=listenerMap.get(this),o=null!==(n=null==i?void 0:i.get(t))&&void 0!==n?n:t;return C.call(this,e,o,r)}),setClickstreamMarker}function getOrCreateEventRoot(e){var t;let r=eventRoot.get(e);if(r)return r;const n=e.target||{},i=getElementSelector(n),o=null===(t=null==n?void 0:n.getBoundingClientRect)||void 0===t?void 0:t.call(n),s=Object.assign(Object.assign({},i),{elementId:n.id,elementHref:n.href,elementSrc:n.src,eventType:e.type,elementBounds:{x:null==o?void 0:o.x,y:null==o?void 0:o.y,top:null==o?void 0:o.top,bottom:null==o?void 0:o.bottom,left:null==o?void 0:o.left,right:null==o?void 0:o.right,height:null==o?void 0:o.height,width:null==o?void 0:o.width}});let a;return otel_1$3.Traces.withSpan(clickstreamTracePrefix+e.type,s,clickstreamPropagationInfo,t=>("nested"===structure&&(clickstreamPropagationInfo=t.getPropagationInfo()),eventRoot.set(e,t),a=t,new Promise(r=>{setTimeout(()=>{t.end(),eventRoot.delete(e),r()},0)}))),a}function maybeStartClickstream(){clickstreamPropagationInfo||otel_1$3.Traces.withSpan(clickstreamTracePrefix+"start",{},null,{disableNesting:!0},e=>{clickstreamTracingState=e,clickstreamPropagationInfo=e.getPropagationInfo()})}function setClickstreamMarker(e,t){var r;if(maybeStartClickstream(),e){let r=null;return otel_1$3.Traces.withSpan(clickstreamTracePrefix+e,{},clickstreamPropagationInfo,e=>{if(clickstreamTracingState=e,t)for(const[r,n]of Object.entries(t))e.addData(r,n);r=e.getPropagationInfo(),"nested"===structure&&(clickstreamPropagationInfo=e.getPropagationInfo())}),Promise.resolve(r)}if(t)for(const[e,r]of Object.entries(t))null==clickstreamTracingState||clickstreamTracingState.addData(e,r);return Promise.resolve(null!==(r=null==clickstreamTracingState?void 0:clickstreamTracingState.getPropagationInfo())&&void 0!==r?r:null)}function getElementSelector(e){const t=e.tagName.toLowerCase(),r=e.id?`#${e.id}`:"",n=Array.from(e.classList).map(e=>`.${e}`).join("");return{elementTagName:t,elementIdSelector:r,elementClassSelector:n,elementSelectorString:t+r+n}}function wrapListener(e,t,r,n){let i=listenerMap.get(e);i||(i=new WeakMap,listenerMap.set(e,i));const o=i.get(t);if(o)return o;const s=function(e,...n){maybeStartClickstream();let i=getOrCreateEventRoot(e);return(()=>{var o;return(0,otel_1$3.withSpan)(r+e.type+".listener",{eventName:e.type},null!==(o=null==i?void 0:i.getPropagationInfo())&&void 0!==o?o:clickstreamPropagationInfo,"function"==typeof t?()=>null==t?void 0:t.call(this,e,...n):()=>{var r;return null===(r=t.handleEvent)||void 0===r?void 0:r.call(t,e,...n)})})()};return i.set(t,s),s}function instrumentRequests(e){try{patchFetch(e)}catch(e){}try{patchXHR()}catch(e){}}clickstream.setupClickstreamTrace=setupClickstreamTrace,clickstream.instrumentRequests=instrumentRequests;const origFetch=globalThis.fetch;function patchFetch(e){"function"==typeof origFetch&&(globalThis.fetch=function(t,r){var n,i,o;let s;const a="string"==typeof t?t:t.url?t.url:t.toString();return a===(null===(n=e.traces)||void 0===n?void 0:n.url)||a===(null===(i=e.metrics)||void 0===i?void 0:i.url)||a===(null===(o=e.logs)||void 0===o?void 0:o.url)?origFetch.call(globalThis,t,r):(otel_1$3.Traces.withSpan("interopio.api.instrumentation.fetch",{url:"string"==typeof t?t:"object"==typeof t&&t.url||String(t),method:r&&r.method||"object"==typeof t&&t.method||"GET"},e=>(s=origFetch.call(globalThis,t,r),s.then(t=>{e.addData("INFO",{statusCode:t.status,responseContentType:t.headers.get("content-type"),responseContentLength:t.headers.get("content-length")})}),s)),s)})}function patchXHR(){const e=globalThis.XMLHttpRequest&&globalThis.XMLHttpRequest.prototype,t=null==e?void 0:e.open,r=null==e?void 0:e.send;function n(e){try{return e.status}catch(e){return null}}function i(e,t){try{return e.getResponseHeader(t)}catch(e){return}}e&&t&&r&&(e.open=function(e,r,n,i,o){let s,a;n=null==n||n;const c=new Promise((e,t)=>{s=e,a=t});otel_1$3.Traces.withSpan("interopio.api.instrumentation.xhr",{method:e||"GET",url:String(r)},l=>(Object.defineProperty(this,"__netRecord",{value:{resolve:s,reject:a,ts:l},configurable:!0}),t.call(this,e,r,null==n||n,i,o),c))},e.send=function(e){const{resolve:t,reject:o,ts:s}=this.__netRecord;if(s){const e=(e,r)=>{if(this.__netRecord){if(this.__netRecord.finalized)return;this.__netRecord.finalized=!0}s.addData("INFO",{statusCode:n(this),responseContentType:i(this,"content-type"),responseContentLength:i(this,"content-length"),resultKind:e}),r&&s.recordException(r),"error"===e?o(r):t(null)};this.addEventListener("loadend",()=>e("success"),{once:!0}),this.addEventListener("error",()=>e("error",new Error("XHR network error")),{once:!0}),this.addEventListener("abort",()=>e("abort",new Error("XHR aborted")),{once:!0}),this.addEventListener("timeout",()=>e("timeout",new Error("XHR timeout")),{once:!0})}return r.call(this,e)})}var startupTrace={};Object.defineProperty(startupTrace,"__esModule",{value:!0}),startupTrace.onDomReady=startupTrace.setStartupTraceLogic=void 0;const otel_1$2=requireDist$1();function setStartupTraceLogic(e){var t,r,n,i;let o=!1;const s=null!==(t=e.startupParentSpanTimeoutMs)&&void 0!==t?t:3e3;let a=e.rootPropagationInfo;if("undefined"!=typeof window&&(a=null!=a?a:null===(r=window.glue42gd)||void 0===r?void 0:r.propagationInfo),a){(0,otel_1$2.isNode)()||onDomReady(()=>{otel_1$2.Traces.withSpan("interopio.api.appStartup.domReady",()=>{})}),e.defaults=null!==(n=e.defaults)&&void 0!==n?n:{};const t=null===(i=e.defaults)||void 0===i?void 0:i.getPropagationInfo;e.defaults.getPropagationInfo=(e,r)=>{const n=null==t?void 0:t(e,r);return n||(o?null:a||null)}}return"number"==typeof s&&s>0&&setTimeout(()=>{o||onDomReady(()=>{otel_1$2.Traces.withSpan("interopio.api.appStartup.finished",e=>{e.addData("INFO",{startupFinishedType:"timeout"})}),o=!0})},s),()=>{otel_1$2.Traces.withSpan("interopio.api.appStartup.explicitFinish",()=>{}),o||(otel_1$2.Traces.withSpan("interopio.api.appStartup.finished",e=>{e.addData("INFO",{startupFinishedType:"explicit"})}),o=!0)}}function onDomReady(e){(0,otel_1$2.isNode)()||"undefined"==typeof window||"undefined"==typeof document?e():"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e):e()}startupTrace.setStartupTraceLogic=setStartupTraceLogic,startupTrace.onDomReady=onDomReady;var constants={};Object.defineProperty(constants,"__esModule",{value:!0}),constants.Defaults=void 0,constants.Defaults={TRACE_VERSION:"00",DEFAULT_USER:"unknown-user",DEFAULT_SERVICE_NAME:"unknown-service-name",DEFAULT_SERVICE_ID:"unknown-service-id",DEFAULT_SERVICE_VERSION:"unknown-service-version",DEFAULT_PLATFORM_VERSION:"unknown-platform-version",DEFAULT_METRIC_DESCRIPTION:"unknown-metric",stopPropagationIfSpanIsDisabled:!1,countMetric:!1,durationMetric:!1,resultMetric:!1,countMetricOnDisabledSpans:!1,durationMetricOnDisabledSpans:!1,resultMetricOnDisabledSpans:!1,maxAttributeDepth:5,otelSpanOptions:{},disablePropagation:!1,addContextToTrace:!0,level:"INFO",forceChildTracing:!1,canBeRoot:!0,currentTracingStateGetterContextName:"interopio.insights.currentTracingStateGetter",minDurationMs:0,log:!1,logOnDisabledSpans:!1};var __awaiter=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})},__importDefault=commonjsGlobal$1&&commonjsGlobal$1.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(manager,"__esModule",{value:!0}),manager.TracesManager=void 0;const api_1=require$$0$2,utils_1=utils,tracingState_1=tracingState,clickstream_1=clickstream,startupTrace_1=startupTrace,constants_1=constants,otel_1$1=requireDist$1(),lodash_clonedeep_1=__importDefault(lodash_clonedeepExports);class TracesManager{constructor(e,t,r,n,i,o){var s,a,c,l,u;this.otelSettings=e,this.logger=t,this.traceLogger=r,this.store=i,this.read=o,this.started=!1,this._currentTracingState=null,this.traceLogger=null!==(s=this.traceLogger)&&void 0!==s?s:this.logger,this.settings=e.traces||{enabled:!1},this.settings.hybridContextMode=null!==(a=this.settings.hybridContextMode)&&void 0!==a&&a,!1!==e.logSettingsOnStartup&&(null==t||t.info(`Starting TracesManager with settings ${(0,otel_1$1.safeStringify)(this.settings)}`)),this.filters=this.settings.filters||[];const d=(0,utils_1.setTracerProvider)(e,this.logger);this.spanProcessors=null==d?void 0:d.spanProcessors,this.tracerProvider=null==d?void 0:d.tracerProvider;const h=this.settings.autoInstrumentations&&(0,otel_1$1.loadInsightsPlugin)("autoInstrumentations",this.logger);this.settings.autoInstrumentations&&h&&this.registerAutoInstrumentations(h),null!==this.settings.countMetric&&(this.traceMetric=null==n?void 0:n.getFromSettings({enabled:!0,description:"Counts number of hits for io.Insights spans",name:null!==(c=this.settings.countMetric)&&void 0!==c?c:"insights_trace_count",type:"custom_counter"})),null!==this.settings.resultMetric&&(this.traceMetricResult=null==n?void 0:n.getFromSettings({enabled:!0,description:"Counts results of io.Insights spans",name:null!==(l=this.settings.resultMetric)&&void 0!==l?l:"insights_trace_result",type:"custom_counter"})),null!==this.settings.durationMetric&&(this.traceMetricDuration=null==n?void 0:n.getFromSettings({enabled:!0,description:"Counts durations of io.Insights spans",name:null!==(u=this.settings.durationMetric)&&void 0!==u?u:"insights_trace_duration",type:"custom_histogram"})),(0,otel_1$1.isNode)()||!1===this.settings.instrumentDocumentLoad||(this.startupTraceFinishedFunc=(0,startupTrace_1.setStartupTraceLogic)(this.settings)),(0,otel_1$1.isNode)()||!1===this.settings.clickstream||(this.clickstreamMarkerFunc=protectMarkerFunc((0,clickstream_1.setupClickstreamTrace)(e))),(0,otel_1$1.isNode)()||!1===this.settings.instrumentRequests||(0,clickstream_1.instrumentRequests)(this.otelSettings),!(0,otel_1$1.isNode)()&&this.settings.instrumentAppLoad}registerAutoInstrumentations(e){var t,r;const n=this.settings.autoInstrumentations,i="object"==typeof n.documentLoad?n.documentLoad:void 0,o="object"==typeof n.userInteraction?n.userInteraction:void 0,s="object"==typeof n.fetch?n.fetch:void 0,a="object"==typeof n.xhr?n.xhr:void 0;null==e||e.registerInstrumentations({instrumentations:[n.documentLoad&&e.newDocumentLoadInstrumentation(i),n.userInteraction&&e.newUserInteractionInstrumentation(Object.assign(Object.assign({eventNames:["submit","click","keypress"]},o),{shouldPreventSpanCreation:(e,t,r)=>{var n;return r.setAttribute("target.id",t.id),null===(n=null==o?void 0:o.shouldPreventSpanCreation)||void 0===n?void 0:n.call(o,e,t,r)}})),n.fetch&&e.newFetchInstrumentation(s),n.xhr&&e.newXMLHttpRequestInstrumentation(Object.assign(Object.assign({},a),{ignoreUrls:!1!==n.ignoreObservabilityUrls?[...(null==a?void 0:a.ignoreUrls)||[],this.settings.url,null===(t=this.otelSettings.metrics)||void 0===t?void 0:t.url,null===(r=this.otelSettings.logs)||void 0===r?void 0:r.url].filter(e=>e):null==a?void 0:a.ignoreUrls}))].filter(e=>e)})}setFilterConfig(e){this.filters=null!=e?e:[]}get userJourneyMarker(){var e;return null!==(e=this.userJourneyMarkerFunc)&&void 0!==e?e:()=>{}}setUserJourneyMarker(e){this.userJourneyMarkerFunc=protectMarkerFunc(e)}get clickstreamMarker(){var e;return null!==(e=this.clickstreamMarkerFunc)&&void 0!==e?e:()=>{}}get startupTraceFinished(){var e;return null!==(e=this.startupTraceFinishedFunc)&&void 0!==e?e:()=>{}}waitForFinalExport(e){return Promise.race([new Promise(t=>e&&setTimeout(t,e)),Promise.allSettled((this.spanProcessors||[]).map(e=>e.forceFlush()))])}get currentTracingState(){return this.resolveCurrentTracingState()}set currentTracingState(e){this._currentTracingState=e}resolveCurrentTracingState(){if(this.settings.useOTELContextManager){const e=api_1.context.active(),t=null==e?void 0:e.getValue(Symbol.for("interopio.insights.currentTracingStateGetter"));return"function"==typeof t?t():this.settings.hybridContextMode?this._currentTracingState:null}return this._currentTracingState}withSequenceSpan(e,t,r,n){return __awaiter(this,void 0,void 0,function*(){return this.withSequenceSpanEx(e,e+".start",t,r,n)})}withSequenceSpanEx(e,t,r,n,i){return __awaiter(this,void 0,void 0,function*(){if("function"==typeof r&&(i=r,r=null),"function"==typeof n&&(i=n,n=null),!i)throw new Error("Callback must be a function, received "+typeof i);const o="string"==typeof t?t:e;let s=null;return this.read&&this.store&&(s=yield this.read(o)),s||(yield this.withSpan(o,r,null,n,e=>__awaiter(this,void 0,void 0,function*(){var t;s=e.getPropagationInfo(),s&&(yield null===(t=this.store)||void 0===t?void 0:t.call(this,o,s))}))),this.withSpan(e,r,s,n,e=>__awaiter(this,void 0,void 0,function*(){var t;const r=e.getPropagationInfo();return r&&"object"==typeof n&&"nested"===(null==n?void 0:n.structure)&&(yield null===(t=this.store)||void 0===t?void 0:t.call(this,o,r)),i(e)}))})}withSpan(e,t,r,n,i){var o,s,a,c,l,u,d,h,p,g,m,f,y,$,b,w,v;let S={};(0,utils_1.isFunctionType)(t)||(S=Object.assign({},t));const E=Object.assign(Object.assign({},otel_1$1.Container.errorless(this.settings.additionalAttributes)),S),C=Object.assign(Object.assign({},otel_1$1.Container.errorless(this.settings.additionalResourceAttributes)),E),_="t42.applogger.log"===(null===(s=null===(o=null==C?void 0:C.method)||void 0===o?void 0:o.toLowerCase)||void 0===s?void 0:s.call(o)),I="function"==typeof n?void 0:n,T=(!1!==this.settings.useDefaultFilters&&null!==(a=null==I?void 0:I.defaultFilters)&&void 0!==a?a:[]).map(t=>Object.assign(Object.assign({},t),{source:e})),A=this.filters.filter(e=>e.overrideDefaultFilters).concat(T,null!==(c=!1!==this.settings.useDefaultFilters?this.settings.defaultFilters:[])&&void 0!==c?c:[],this.filters.filter(e=>!e.overrideDefaultFilters)),D=(0,utils_1.findMatchingFilters)(A,C,e);let x=api_1.context.active(),R=null;!0!==(null==D?void 0:D.disableNesting)&&!0!==(null==I?void 0:I.disableNesting)&&(R||r&&"function"!=typeof r&&(R=otel_1$1.Traces.extractPropagationInfo(r)),R||"function"!=typeof(null==I?void 0:I.getPropagationInfo)||(R=null==I?void 0:I.getPropagationInfo(e,C)),R||(!otel_1$1.Traces.currentTracingState||!0===this.settings.useOTELContextManager&&!0!==this.settings.hybridContextMode?(this.settings.useOTELContextManager||!0===this.settings.hybridContextMode)&&(R=(null===(u=this.resolveCurrentTracingState())||void 0===u?void 0:u.getPropagationInfo())||null):(R=otel_1$1.Traces.currentTracingState.getPropagationInfo(),R||!0!==this.settings.hybridContextMode||(R=(null===(l=this.resolveCurrentTracingState())||void 0===l?void 0:l.getPropagationInfo())||null))),R||"function"!=typeof(null===(h=null===(d=this.settings)||void 0===d?void 0:d.defaults)||void 0===h?void 0:h.getPropagationInfo)||(R=null===(g=null===(p=this.settings)||void 0===p?void 0:p.defaults)||void 0===g?void 0:g.getPropagationInfo(e,C))),x=R?api_1.propagation.extract(api_1.context.active(),R):api_1.ROOT_CONTEXT;const O=this.resolveProperty("canBeRoot",D,I),P=this.started&&((null==R?void 0:R.forceTracing)||(0,utils_1.isSpanEnabled)(D,I,this.settings.defaults))&&(O||!!R),N=P&&(null!==(m=null==R?void 0:R.forceTracing)&&void 0!==m?m:this.resolveProperty("forceChildTracing",D,I)),k=this.resolveProperty("level",D,I),M=this.resolveProperty(P?"countMetric":"countMetricOnDisabledSpans",D,I),L=this.resolveProperty("maxAttributeDepth",D,I);M&&(null===(y=null===(f=this.traceMetric)||void 0===f?void 0:f.add)||void 0===y||y.call(f,1,Object.assign({source:e},(0,otel_1$1.flattenOtelAtributes)(E,L))));const F=this.resolveProperty(P?"resultMetric":"resultMetricOnDisabledSpans",D,I),j=this.resolveProperty(P?"durationMetric":"durationMetricOnDisabledSpans",D,I),U=!_&&this.resolveProperty(P?"log":"logOnDisabledSpans",D,I),B=this.resolveProperty("minDurationMs",D,I);let q;if("function"==typeof t)q=i=t;else if("function"==typeof r)q=i=r;else if("function"==typeof n)q=i=n;else{if("function"!=typeof i)throw new Error("Callback must be a function, received "+typeof i);q=i}const H=this.resolveProperty("disablePropagation",D,I),W=this.resolveProperty("addContextToTrace",D,I),G=(0,lodash_clonedeep_1.default)(null!==($=this.resolveProperty("otelSpanOptions",D,I))&&void 0!==$?$:{});if(G.attributes=null!==(b=G.attributes)&&void 0!==b?b:{},this.saveDataInAttributes({attributes:null!==(w=G.attributes)&&void 0!==w?w:{}},B,L,W,E),P){const t=api_1.trace.getTracer(e);let r=null;return x=x.setValue(Symbol.for(constants_1.Defaults.currentTracingStateGetterContextName),()=>r),t.startActiveSpan(e,G,x,t=>(r=new tracingState_1.TracingState(e,k,t,this.logger,constants_1.Defaults.TRACE_VERSION,H,N,L,x),this.saveDataInAttributes({otelSpan:t},B,L,W,E),this.handleCallbackAndResult(r,q,D,I,F,j,U,E,L)))}{let t=null;if(!this.resolveProperty("stopPropagationIfSpanIsDisabled",D,I))if(r){let e={};(0,utils_1.isFunctionType)(r)||(e=Object.assign({},r)),t=otel_1$1.Traces.extractPropagationInfo(e)}else otel_1$1.Traces.currentTracingState&&!0!==this.settings.useOTELContextManager?t=otel_1$1.Traces.currentTracingState.getPropagationInfo():this.settings.useOTELContextManager&&(R=(null===(v=this.resolveCurrentTracingState())||void 0===v?void 0:v.getPropagationInfo())||null);const n=new otel_1$1.NullTracingState(e,t,H);return x=x.setValue(Symbol.for(constants_1.Defaults.currentTracingStateGetterContextName),()=>n),api_1.context.with(x,()=>this.handleCallbackAndResult(n,q,D,I,F,j,U,E,L))}}saveDataInAttributes(e,t,r,n,i){t&&(0,utils_1.saveDataInAttribute)({insightsMinDurationMs:t},e,r),this.otelSettings.platformVersion&&(0,utils_1.saveDataInAttribute)({platformVersion:this.otelSettings.platformVersion},e,r),this.otelSettings.additionalAttributes&&(0,utils_1.saveDataInAttribute)(otel_1$1.Container.errorlessDefined(this.otelSettings.additionalAttributes,{}),e,r),this.settings.additionalAttributes&&(0,utils_1.saveDataInAttribute)(otel_1$1.Container.errorlessDefined(this.settings.additionalAttributes,{}),e,r),n&&(0,utils_1.saveDataInAttribute)(i,e,r)}handleCallbackAndResult(e,t,r,n,i,o,s,a,c){var l,u,d,h,p,g;const m=new Date;let f,y=null===(p=null!==(u=null!==(l=null==r?void 0:r.autoSetSuccessStatus)&&void 0!==l?l:null==n?void 0:n.autoSetSuccessStatus)&&void 0!==u?u:null===(h=null===(d=this.settings)||void 0===d?void 0:d.defaults)||void 0===h?void 0:h.autoSetSuccessStatus)||void 0===p||p;const $=null!==(g=otel_1$1.Traces.currentTracingState)&&void 0!==g?g:null;try{otel_1$1.Traces.currentTracingState=e;const r=t(e);return f=r&&"function"==typeof r.then&&"function"==typeof r.catch&&"function"==typeof r.finally,f?(y=!1,r.then(b.bind(this)).catch(w.bind(this)).finally(v.bind(this))):b.apply(this,[r])}catch(e){w.call(this,e)}finally{otel_1$1.Traces.currentTracingState=!0===this.settings.hybridContextMode?$:null,f||v.apply(this)}function b(t){var r;return y&&(null===(r=e.status)||void 0===r?void 0:r.code)===otel_1$1.SpanStatusCode.UNSET&&(e.status={code:otel_1$1.SpanStatusCode.OK}),t}function w(t){throw e.status={message:"string"==typeof t?t:null==t?void 0:t.message,code:otel_1$1.SpanStatusCode.ERROR},e.recordException(t),t}function v(){var t,r,n,l,u,d,h,p,g,f,y,$,b,w,v,S,E,C;if(i&&(null===(r=null===(t=this.traceMetricResult)||void 0===t?void 0:t.add)||void 0===r||r.call(t,1,Object.assign(Object.assign({source:e.source},(0,otel_1$1.flattenOtelAtributes)(a,c)),{code:e.status.code}))),o&&(null===(l=null===(n=this.traceMetricDuration)||void 0===n?void 0:n.record)||void 0===l||l.call(n,(new Date).getTime()-m.getTime(),Object.assign({source:e.source},(0,otel_1$1.flattenOtelAtributes)(a,c)))),e.endSpan(void 0,!0),s){let t="none";switch(e.level){case"OFF":t="none";break;case"LOWEST":case"DIAGNOSTIC":t="verbose";break;case"DEBUG":t="debug";break;case"INFO":t="info";break;case"WARN":t="warn";break;case"HIGHEST":t="error"}if("none"!==t){const r=null!==(h=null===(d=null===(u=null==e?void 0:e.span)||void 0===u?void 0:u.parentSpanContext)||void 0===d?void 0:d.spanId)&&void 0!==h?h:"0000000000000000",n=`${e.traceId}-${e.id}-${r}`,i=1e3*(null===(g=null===(p=e.span)||void 0===p?void 0:p.endTime)||void 0===g?void 0:g[0])+(null===(y=null===(f=e.span)||void 0===f?void 0:f.endTime)||void 0===y?void 0:y[1])/1e6-1e3*(null===(b=null===($=e.span)||void 0===$?void 0:$.startTime)||void 0===b?void 0:b[0])-(null===(v=null===(w=e.span)||void 0===w?void 0:w.startTime)||void 0===v?void 0:v[1])/1e6;this.traceLogger[t](`span ${n} ${e.source} ${null!==(E=null===(S=e.status)||void 0===S?void 0:S.code)&&void 0!==E?E:"unknown"} ${Math.floor(i)} ${JSON.stringify(null===(C=null==e?void 0:e.span)||void 0===C?void 0:C.attributes)}`)}}}}start(){return __awaiter(this,void 0,void 0,function*(){this.started=!0})}stop(){return __awaiter(this,void 0,void 0,function*(){this.started=!1})}resolveProperty(e,t,r,n){var i,o,s,a,c,l;return null!==(l=null!==(c=null!==(o=null!==(i=null==t?void 0:t[e])&&void 0!==i?i:null==r?void 0:r[e])&&void 0!==o?o:null===(a=null===(s=this.settings)||void 0===s?void 0:s.defaults)||void 0===a?void 0:a[e])&&void 0!==c?c:constants_1.Defaults[e])&&void 0!==l?l:n}}function protectMarkerFunc(e){return(t,r)=>{const n=["OFF","LOWEST","DIAGNOSTIC","DEBUG","INFO","WARN","HIGHEST"];if(void 0!==r&&("object"!=typeof r||Object.keys(r).some(e=>!n.find(t=>e===t.toUpperCase()))||Object.values(r).some(e=>"object"!=typeof e)))throw new Error('Data parameter must map from log level ("OFF", "LOWEST", "DIAGNOSTIC", "DEBUG", "INFO", "WARN", "HIGHEST") to object containing attributes to add to span.');return null==e?void 0:e(t,r)}}manager.TracesManager=TracesManager,Object.defineProperty(dist,"__esModule",{value:!0});var init_1=dist.init=void 0;const manager_1=manager,otel_1=requireDist$1();function init(){(0,otel_1.registerInsightsPlugin)("traces",()=>({newTracesManager:(e,t,r,n,i,o)=>new manager_1.TracesManager(t,e,r,n,i,o)}))}init_1=dist.init=init;var index=Object.freeze({__proto__:null,default:dist,get init(){return init_1}});export{ioConnectBrowserPlatformFactory as default};
59
+ function e(e){return"[object Object]"===Object.prototype.toString.call(e)}return hasRequiredIsPlainObject=1,Object.defineProperty(isPlainObject$3,"__esModule",{value:!0}),isPlainObject$3.isPlainObject=function(t){let r,n;if(!1===e(t))return!1;if(r=t.constructor,void 0===r)return!0;if(n=r.prototype,!1===e(n))return!1;if(!1===n.hasOwnProperty("isPrototypeOf"))return!1;return!0},isPlainObject$3}function requireSafeStringify(){if(hasRequiredSafeStringify)return safeStringify;hasRequiredSafeStringify=1,Object.defineProperty(safeStringify,"__esModule",{value:!0}),safeStringify.safeStringify=function(t){if(!t)return JSON.stringify(t);return JSON.stringify(t,(t,r)=>r&&"object"==typeof r?(0,e.isPlainObject)(r)?r:Object.prototype.toString.call(r):r)};const e=requireIsPlainObject();return safeStringify}var _null$1$1={},hasRequired_null$1,hasRequiredNullMetricsManager,hasRequiredBuilder$3;function require_null$1(){if(hasRequired_null$1)return _null$1$1;hasRequired_null$1=1,Object.defineProperty(_null$1$1,"__esModule",{value:!0}),_null$1$1.NullMetric=void 0;return _null$1$1.NullMetric=class{constructor(e,t){this.settings=e,this.logger=t,this.started=!1}start(){var e;return null===(e=this.logger)||void 0===e||e.debug(`null metric has been started instead of ${this.settings.type} one`),this.started=!0,Promise.resolve()}stop(){var e;return null===(e=this.logger)||void 0===e||e.debug(`null metric has been stopped instead of ${this.settings.type} one`),this.started=!1,Promise.resolve()}add(){}record(){}},_null$1$1}function requireNullMetricsManager(){if(hasRequiredNullMetricsManager)return nullMetricsManager;hasRequiredNullMetricsManager=1,Object.defineProperty(nullMetricsManager,"__esModule",{value:!0}),nullMetricsManager.NullMetricsManager=void 0;const e=requireNullManager$1(),t=requireSafeStringify(),r=require_null$1();class n extends e.NullManager{constructor(e,r,n){!1!==(null==r?void 0:r.logSettingsOnStartup)&&(null==n||n.info(`Starting NullMetrcsManager with settings ${(0,t.safeStringify)(e)}`)),super()}waitForFinalExport(e){return Promise.resolve()}getFromSettings(e){return new r.NullMetric(e)}get(e){return new r.NullMetric({name:e,type:e,enabled:!1,description:e})}}return nullMetricsManager.NullMetricsManager=n,nullMetricsManager}function requireBuilder$3(){if(hasRequiredBuilder$3)return builder$2;hasRequiredBuilder$3=1,Object.defineProperty(builder$2,"__esModule",{value:!0}),builder$2.MetricsManagerBuilder=void 0;const e=requireNullMetricsManager(),t=requireDist();return builder$2.MetricsManagerBuilder=class{withLogger(e){return this.logger=e,this}withSettings(e){return this.settings=e,this}withMeterProvider(e){return this.meterProviderCreateFunc=e,this}withDependencyContainer(e){return this.dependencyContainer=e,this}build(){var e,t,r,n;if((null===(e=globalThis.ioInsightsInternals)||void 0===e?void 0:e.metrics)&&!0!==(null===(t=this.settings)||void 0===t?void 0:t.definitiveInstance))return globalThis.ioInsightsInternals.metrics;const i=this.buildCore();return globalThis.ioInsightsInternals=null!==(r=globalThis.ioInsightsInternals)&&void 0!==r?r:{},globalThis.ioInsightsInternals.metrics&&!(null===(n=this.settings)||void 0===n?void 0:n.definitiveInstance)||(globalThis.ioInsightsInternals.metrics=i),i}buildCore(){var r,n,i,o;let s;if(!0!==(null===(r=this.settings)||void 0===r?void 0:r.enabled)||!0!==(null===(i=null===(n=this.settings)||void 0===n?void 0:n.metrics)||void 0===i?void 0:i.enabled)||!(s=(0,t.loadInsightsPlugin)("metrics",this.logger)))return new e.NullMetricsManager(null===(o=this.settings)||void 0===o?void 0:o.metrics,this.settings,this.logger);return s.newMetricsManager(this.settings,this.dependencyContainer,this.meterProviderCreateFunc,this.logger)}},builder$2}var builder$1$1={},nullTracesManager={},nullTracingState={},hasRequiredNullTracingState;function requireNullTracingState(){if(hasRequiredNullTracingState)return nullTracingState;hasRequiredNullTracingState=1,Object.defineProperty(nullTracingState,"__esModule",{value:!0});return nullTracingState.default=class{constructor(e,t,r){this.source=e,this.propagationInfo=t,this.disablePropagation=r,this.currentSpanStatus={code:0},this.level="OFF"}endSpan(){return Promise.resolve()}get enabled(){return!1}get id(){}get traceId(){}set status(e){this.currentSpanStatus=Object.assign({},e)}get status(){return this.currentSpanStatus}addEvent(e,t,r){return this}recordException(e,t){}isRecording(){return!1}updateName(e){return this}spanContext(){}addData(e,t){}end(){}getPropagationInfo(){return this.propagationInfo?this.propagationInfo:null}injectPropagationInfo(e){this.propagationInfo&&!this.disablePropagation&&(e.__interopIOTracePropagationInfo=this.propagationInfo)}},nullTracingState}var traces={},otelUtils={},container={},hasRequiredContainer,hasRequiredOtelUtils,hasRequiredTraces,hasRequiredNullTracesManager,hasRequiredBuilder$2;function requireContainer(){if(hasRequiredContainer)return container;hasRequiredContainer=1;var e=container&&container.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(container,"__esModule",{value:!0}),container.Container=void 0;const t=requireSafeStringify();class r{static get instance(){var e,t;return null!==(e=r._instance)&&void 0!==e?e:null===(t=null===globalThis||void 0===globalThis?void 0:globalThis.ioInsightsInternals)||void 0===t?void 0:t.instance}static get settings(){var e;return null!==(e=r._settings)&&void 0!==e?e:r.instance.settings}static set settings(e){r._settings=e}static errorless(e,t){try{if("function"!=typeof e)return e;return e()}catch(e){return r.handleErrorlessMode(e,t)}}static errorlessDefined(e,t){try{if("function"!=typeof e)return e;return e()}catch(e){return r.handleErrorlessMode(e,t)}}static errorlessAsync(t,n){return e(this,void 0,void 0,function*(){try{if("function"!=typeof t)return t;return(yield t)()}catch(e){return r.handleErrorlessMode(e,n)}})}static handleErrorlessMode(e,n){var i,o,s,a,c;let l;try{if((null==e?void 0:e.message)&&(l=(null==e?void 0:e.message)+" "+(null!==(i=null==e?void 0:e.stack)&&void 0!==i?i:(new Error).stack)),!l)try{l=(0,t.safeStringify)(e)+" "+(new Error).stack}catch(e){}if(!l)try{l=(null==e?void 0:e.toString())+" "+(new Error).stack}catch(e){}}catch(e){}l||(l="unknown "+(new Error).stack);try{if(!(null===(s=null===(o=r.instance)||void 0===o?void 0:o.settings)||void 0===s?void 0:s.errorlessMode))throw null===(a=r.instance.logger)||void 0===a||a.error("Observed error "+l),e}catch(t){throw e}try{return null===(c=r.instance.logger)||void 0===c||c.warn("Caught error "+l),n}catch(e){return n}}constructor(e,t,n,i,o){var s;this._settings=e,this._traces=t,this.metrics=n,this.logs=i,this.logger=o,this.started=!1,r._instance=this,globalThis.ioInsightsInternals=null!==(s=globalThis.ioInsightsInternals)&&void 0!==s?s:{},globalThis.ioInsightsInternals.instance=this}get traces(){var e,t;return(null===(e=null===globalThis||void 0===globalThis?void 0:globalThis.ioInsightsInternals)||void 0===e?void 0:e.traces)?null===(t=null===globalThis||void 0===globalThis?void 0:globalThis.ioInsightsInternals)||void 0===t?void 0:t.traces:this._traces}waitForFinalExport(e){var t,r,n;return Promise.allSettled([null===(t=this.traces)||void 0===t?void 0:t.waitForFinalExport(e),null===(r=this.metrics)||void 0===r?void 0:r.waitForFinalExport(e),null===(n=this.logs)||void 0===n?void 0:n.waitForFinalExport(e)])}get settings(){return this._settings}start(){return e(this,void 0,void 0,function*(){const e=this.metrics.settings.enabled?this.metrics.start():Promise.resolve(),t=this.traces.settings.enabled?this.traces.start():Promise.resolve(),r=this.logs.settings.enabled?this.logs.start():Promise.resolve();yield Promise.all([e,t,r]),this.started=!0})}stop(){return e(this,void 0,void 0,function*(){const e=this.metrics.started?this.metrics.stop():Promise.resolve(),t=this.traces.started?this.traces.stop():Promise.resolve(),r=this.logs.started?this.logs.stop():Promise.resolve();yield Promise.all([e,t,r]),this.started=!1})}}return container.Container=r,container}function requireOtelUtils(){return hasRequiredOtelUtils||(hasRequiredOtelUtils=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.extractFilteringContextFromArgs=e.deep_value=e.getOTELData=e.flattenOtelAtributes=void 0;const t=requireContainer();e.flattenOtelAtributes=(t,r)=>{if(null==t)return{};"object"!=typeof t&&(t={unknownAttribute:t});const n={};for(const[i,o]of Object.entries(t)){const t=(0,e.getOTELData)(i,o,0,r);for(const[e,r]of t)n[e]=r}return n};e.getOTELData=(e,t,i,o)=>{if((i+=1)>o)return[[e,"<depth exceeded>"]];const s=Boolean(t&&"object"==typeof t);return"number"==typeof t||"string"==typeof t||"boolean"==typeof t?[[e,t]]:n(t)?[[e,t]].concat(r(e,t,i,o)):s?r(e,t,i,o):"function"==typeof t?[]:t?[[e,t+""]]:[]};const r=(t,r,n,i)=>{const o=[];for(const[s,a]of Object.entries(r))for(const[r,c]of(0,e.getOTELData)(s,a,n,i))o.push([t+"."+r,c]);return o},n=e=>!!Array.isArray(e)&&e.every(e=>null==e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e);e.deep_value=function(e,t){if(!t)return null;for(var r=0,n=(t=t.split(".")).length;r<n;r++){if(null==e)return;e=e[t[r]]}return e};e.extractFilteringContextFromArgs=(r,n,i)=>{let o={};return"function"==typeof r.thisMapping?o=Object.assign(Object.assign({},o),t.Container.errorless(()=>r.thisMapping.apply(i,[i]))):Object.keys(r.thisMapping||{}).forEach(t=>{if(!t||!r.thisMapping)return;const n=r.thisMapping[t];o[n]=(0,e.deep_value)(i,t)}),"function"==typeof r.argMapping?o=Object.assign(Object.assign({},o),t.Container.errorless(()=>r.argMapping.apply(i,n))):Object.keys(r.argMapping||{}).forEach(t=>{if(!t||!r.argMapping)return;const i=r.argMapping[t],s=(0,e.deep_value)(n,t);"string"!=typeof s&&"number"!=typeof s||(o[i]=s)}),o}}(otelUtils)),otelUtils}function requireTraces(){if(hasRequiredTraces)return traces;hasRequiredTraces=1;var e=traces&&traces.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})},t=traces&&traces.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(traces,"__esModule",{value:!0}),traces.withSpan=void 0;const r=requireOtelUtils(),n=requireNullTracesManager(),i=t(requireNullTracingState());class o{static get instance(){var e,t;return(null===(e=null===globalThis||void 0===globalThis?void 0:globalThis.ioInsightsInternals)||void 0===e?void 0:e.traces)?null===(t=null===globalThis||void 0===globalThis?void 0:globalThis.ioInsightsInternals)||void 0===t?void 0:t.traces:(o._instance||(o._instance=new n.NullTracesManager(void 0,void 0,void 0)),o._instance)}static set instance(e){o._instance=e}static get currentTracingState(){var e;return(null===(e=o.instance)||void 0===e?void 0:e.currentTracingState)||new i.default("unknown",null,!0)}static set currentTracingState(e){o.instance&&(o.instance.currentTracingState=e)}static removePropagationInfo(e){return o.extractPropagationInfo(e,!0),e}static extractPropagationInfo(e,t){if(null==e?void 0:e.traceparent)return e;const r=null==e?void 0:e.__interopIOTracePropagationInfo;return r?(!0===t&&delete e.__interopIOTracePropagationInfo,r):null}withSequenceSpanEx(t,r,n,i,s){return e(this,void 0,void 0,function*(){return o.instance.withSequenceSpanEx(t,r,n,i,s)})}withSequenceSpan(t,r,n,i){return e(this,void 0,void 0,function*(){return o.instance.withSequenceSpan(t,r,n,i)})}static withSpan(e,t,n,i,s){return t instanceof Function||t&&!t.argMapping&&!t.thisMapping&&!t.defaults||n||i||s?o.instance.withSpan(e,t,n,i,s):function(n,i,s){let a;a=s?s.value:n;let c=function(...n){return o.withSpan(e,t?(0,r.extractFilteringContextFromArgs)(t,n,this):{},null,t,()=>a.apply(this,n))};if(o.isAsyncFunction(a)){const e=c;c=function(...t){return e.apply(this,t)},Object.defineProperty(c,Symbol.toStringTag,{value:"AsyncFunction",configurable:!0})}if(!s)return c;s.value=c}}static isAsyncFunction(e){return e&&"[object AsyncFunction]"==={}.toString.call(e)}static withSpans(e,t){for(const r in e)if("function"==typeof t[r]){const n=t[r],i=e[r];if(!i)continue;let s;s="string"==typeof i?o.withSpan(i):o.withSpan(i.source,i.decoratorOptions),t[r]=s(n)}return t}}return traces.default=o,traces.withSpan=o.withSpan,traces}function requireNullTracesManager(){if(hasRequiredNullTracesManager)return nullTracesManager;hasRequiredNullTracesManager=1;var e=nullTracesManager&&nullTracesManager.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})},t=nullTracesManager&&nullTracesManager.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(nullTracesManager,"__esModule",{value:!0}),nullTracesManager.NullTracesManager=void 0;const r=t(requireNullTracingState()),n=t(requireTraces()),i=requireNullManager$1(),o=requireSafeStringify();class s extends i.NullManager{get settings(){return this._settings||{}}set settings(e){this._settings=e}constructor(e,t,r){!1!==(null==t?void 0:t.logSettingsOnStartup)&&(null==r||r.info(`Starting NullTracesManager with settings ${(0,o.safeStringify)(e)}`)),super(),this._settings=e,this.logger=r}withSequenceSpan(t,r,n,i){return e(this,void 0,void 0,function*(){return this.withSequenceSpanEx(t,t+".start",r,n,i)})}withSequenceSpanEx(t,r,n,i,o){return e(this,void 0,void 0,function*(){return this.withSpan(t,n,null,i,o)})}get currentTracingState(){return new r.default("nullTracingState",null,!0)}set currentTracingState(e){}waitForFinalExport(e){return Promise.resolve()}withSpan(e,t,i,o,s){const a="function"==typeof t?t:"function"==typeof i?i:"function"==typeof o?o:s;if(!a)throw new Error("callback must be provided");if("function"!=typeof a)throw new Error("Callback must be a function, received "+typeof a);const c=new r.default(e,null,!0);n.default.currentTracingState=c;try{return a(c)}finally{n.default.currentTracingState=null}}setFilterConfig(e){}get startupTraceFinished(){return()=>{}}get userJourneyMarker(){return()=>{}}setUserJourneyMarker(e){}get clickstreamMarker(){return()=>{}}}return nullTracesManager.NullTracesManager=s,nullTracesManager}function requireBuilder$2(){if(hasRequiredBuilder$2)return builder$1$1;hasRequiredBuilder$2=1,Object.defineProperty(builder$1$1,"__esModule",{value:!0}),builder$1$1.TracesManagerBuilder=void 0;const e=requireNullTracesManager(),t=requireDist();return builder$1$1.TracesManagerBuilder=class{constructor(){this.traceLogger=null}withLogger(e){return this.logger=e,this}withTraceLogger(e){return this.traceLogger=e,this}withSettings(e){return this.settings=e,this}withMetrics(e){return this.metrics=e,this}withTracerProvider(e){return this.tracerProvider=e,this}withContextManager(e){var t,r;return this.settings=null!==(t=this.settings)&&void 0!==t?t:{enabled:!1},this.settings.traces=null!==(r=this.settings.traces)&&void 0!==r?r:{enabled:!1},this.settings.traces.contextManager=()=>e,this.settings.traces.useOTELContextManager=!0,this}withPropagationInfoStorage(e,t){return this.store=e,this.read=t,this}build(){var e,t,r,n;if((null===(e=globalThis.ioInsightsInternals)||void 0===e?void 0:e.traces)&&!0!==(null===(t=this.settings)||void 0===t?void 0:t.definitiveInstance))return globalThis.ioInsightsInternals.traces;const i=this.buildCore();return globalThis.ioInsightsInternals=null!==(r=globalThis.ioInsightsInternals)&&void 0!==r?r:{},globalThis.ioInsightsInternals.traces&&!(null===(n=this.settings)||void 0===n?void 0:n.definitiveInstance)||(globalThis.ioInsightsInternals.traces=i),i}buildCore(){var r,n,i,o,s,a,c,l;let u;if(this.settings.traces=null!==(r=this.settings.traces)&&void 0!==r?r:{enabled:!1},this.settings.traces.otlpExporterConfig=null!==(n=this.settings.traces.exporterSettings)&&void 0!==n?n:this.settings.traces.otlpExporterConfig,this.settings.traces.exporterSettings=null!==(i=this.settings.traces.exporterSettings)&&void 0!==i?i:this.settings.traces.otlpExporterConfig,!0!==(null===(o=this.settings)||void 0===o?void 0:o.enabled)||!0!==(null===(a=null===(s=this.settings)||void 0===s?void 0:s.traces)||void 0===a?void 0:a.enabled)||!(u=(0,t.loadInsightsPlugin)("traces",this.logger)))return new e.NullTracesManager(null===(c=this.settings)||void 0===c?void 0:c.traces,this.settings,this.logger);return u.newTracesManager(this.logger,this.settings,null!==(l=this.traceLogger)&&void 0!==l?l:this.logger,this.metrics,this.store,this.read)}},builder$1$1}var _null$3={},hasRequired_null;function require_null(){if(hasRequired_null)return _null$3;hasRequired_null=1,Object.defineProperty(_null$3,"__esModule",{value:!0}),_null$3.NullLogger=void 0;return _null$3.NullLogger=class{get level(){return 60}error(){}warn(){}info(){}debug(){}verbose(){}},_null$3}var nullManager={},hasRequiredNullManager;function requireNullManager(){if(hasRequiredNullManager)return nullManager;hasRequiredNullManager=1,Object.defineProperty(nullManager,"__esModule",{value:!0}),nullManager.NullLogsManager=void 0;const e=requireNullManager$1(),t=requireSafeStringify();class r extends e.NullManager{constructor(e,r,n){!1!==(null==r?void 0:r.logSettingsOnStartup)&&(null==n||n.info(`Starting NullLogsManager with settings ${(0,t.safeStringify)(e)}`)),super()}emit(e){return null}}return nullManager.NullLogsManager=r,nullManager}var constants$2={},hasRequiredConstants;function requireConstants(){return hasRequiredConstants||(hasRequiredConstants=1,Object.defineProperty(constants$2,"__esModule",{value:!0}),constants$2.Defaults=void 0,constants$2.Defaults={DEFAULT_USER:"unknown-user",DEFAULT_SERVICE_NAME:"unknown-service-name",DEFAULT_SERVICE_ID:"unknown-service-id",DEFAULT_SERVICE_VERSION:"unknown-service-version",DEFAULT_PLATFORM_VERSION:"unknown-platform-version"}),constants$2}var logWrapper={},hasRequiredLogWrapper;function requireLogWrapper(){if(hasRequiredLogWrapper)return logWrapper;hasRequiredLogWrapper=1,Object.defineProperty(logWrapper,"__esModule",{value:!0}),logWrapper.LogWrapper=void 0;return logWrapper.LogWrapper=class{constructor(e,t){this.logger=e,this.dropLog=t}get level(){var e;return null!==(e=this.logger.level)&&void 0!==e?e:0}error(e,...t){var r;(null===(r=this.dropLog)||void 0===r?void 0:r.call(this,50,e))||this.logger.warn(e,...t)}warn(e,...t){var r;(null===(r=this.dropLog)||void 0===r?void 0:r.call(this,50,e))||this.logger.warn(e,...t)}info(e,...t){var r;(null===(r=this.dropLog)||void 0===r?void 0:r.call(this,60,e))||this.logger.info(e,...t)}debug(e,...t){var r;(null===(r=this.dropLog)||void 0===r?void 0:r.call(this,70,e))||this.logger.debug(e,...t)}verbose(e,...t){var r;(null===(r=this.dropLog)||void 0===r?void 0:r.call(this,80,e))||this.logger.verbose(e,...t)}},logWrapper}var builder$4={},hasRequiredBuilder$1,hasRequiredBuilder;function requireBuilder$1(){if(hasRequiredBuilder$1)return builder$4;hasRequiredBuilder$1=1,Object.defineProperty(builder$4,"__esModule",{value:!0}),builder$4.LogsManagerBuilder=void 0;const e=requireDist(),t=requireNullManager();return builder$4.LogsManagerBuilder=class{withLogger(e){return this.logger=e,this}withSettings(e){return this.settings=e,this}build(){var e,t,r,n;if((null===(e=globalThis.ioInsightsInternals)||void 0===e?void 0:e.logs)&&!0!==(null===(t=this.settings)||void 0===t?void 0:t.definitiveInstance))return globalThis.ioInsightsInternals.logs;const i=this.buildCore();return globalThis.ioInsightsInternals=null!==(r=globalThis.ioInsightsInternals)&&void 0!==r?r:{},globalThis.ioInsightsInternals.logs&&!(null===(n=this.settings)||void 0===n?void 0:n.definitiveInstance)||(globalThis.ioInsightsInternals.logs=i),i}buildCore(){var r,n,i,o;let s;if(!0!==(null===(r=this.settings)||void 0===r?void 0:r.enabled)||!0!==(null===(i=null===(n=this.settings)||void 0===n?void 0:n.logs)||void 0===i?void 0:i.enabled)||!(s=(0,e.loadInsightsPlugin)("logs",this.logger)))return new t.NullLogsManager(null===(o=this.settings)||void 0===o?void 0:o.logs,this.settings,this.logger);return s.newLogsManager(this.logger,this.settings.logs,this.settings)}},builder$4}function requireBuilder(){if(hasRequiredBuilder)return builder$3;hasRequiredBuilder=1,Object.defineProperty(builder$3,"__esModule",{value:!0}),builder$3.Builder=void 0;const e=requireBuilder$3(),t=requireBuilder$2(),r=require_null(),n=requireContainer(),i=requireNullMetricsManager(),o=requireNullTracesManager(),s=requireNullManager(),a=requireConstants(),c=requireLogWrapper(),l=requireDist(),u=requireSafeStringify(),d=requireBuilder$1();class h{constructor(){this.logger=new r.NullLogger}withLogger(e){var t;e&&(this.logger=new c.LogWrapper(e,(e,t)=>{var r,n,i;return!(!(null===(r=this.settings)||void 0===r?void 0:r.suppressDoubleInitializationWarnings)||!~(t+"").indexOf("@opentelemetry/api: Attempted duplicate registration of API"))||(!(!(null===(n=this.settings)||void 0===n?void 0:n.suppressDoubleInitializationWarnings)||!~(t+"").indexOf("Current logger will overwrite one already registered"))||!(!(null===(i=this.settings)||void 0===i?void 0:i.suppressDoubleInitializationWarnings)||!~(t+"").indexOf("Current logger will be overwritten")))}));const r=(0,l.loadInsightsPlugin)("base",this.logger);if(r)if(this.logger.level){const e=null===(t=this.logger.level)||void 0===t?void 0:t.valueOf();r.diag.setLogger(this.logger,e)}else r.diag.setLogger(this.logger,70);return this}withSettings(e){return this.settings=e,n.Container.settings=e,this}withMetrics(){return this.metricsBuilder=new e.MetricsManagerBuilder,this.metricsBuilder.withLogger(this.logger),this.metricsBuilder.withSettings(Object.assign({enabled:!1},this.settings)),this.metricsBuilder}withTraces(){return this.tracesBuilder=new t.TracesManagerBuilder,this.tracesBuilder.withLogger(this.logger),this.tracesBuilder.withSettings(Object.assign({enabled:!1},this.settings)),this.tracesBuilder}withLogs(){return this.logsBuilder=new d.LogsManagerBuilder,this.logsBuilder.withLogger(this.logger),this.logsBuilder.withSettings(Object.assign({enabled:!1},this.settings)),this.logsBuilder}build(){var e,t,r,c,d,p,g,m,f;this.settings=null!==(e=this.settings)&&void 0!==e?e:{enabled:!1};const y=Object.assign({enabled:!1},this.settings);if(!1!==(null===(t=this.settings)||void 0===t?void 0:t.logSettingsOnStartup)&&this.logger.info(`Starting interop.io OTEL with settings ${(0,u.safeStringify)(this.settings)}`),0==(null===(r=this.settings)||void 0===r?void 0:r.enabled)||!(0,l.loadInsightsPlugin)("base",this.logger))return new n.Container(y,new o.NullTracesManager(this.settings.traces,y,this.logger),new i.NullMetricsManager(this.settings.metrics,y,this.logger),new s.NullLogsManager(this.settings.logs,y,this.logger),this.logger);if((null===(d=null===(c=this.settings)||void 0===c?void 0:c.metrics)||void 0===d?void 0:d.enabled)&&(null===(p=this.settings)||void 0===p?void 0:p.metrics.platformMetricsEnabled)&&!this.metricsBuilder)throw new Error("metrics.platformMetricsEnabled is true, but .withMetrics() method not called.");const $=this.settings.additionalResourceAttributes;this.settings.additionalResourceAttributes=()=>{var e,t,r,i,o,s,c,l,u,d,h,p,g,m,f,y,b,w,v,S,E,C,_,I;const T=null!==(e=n.Container.errorlessDefined($,{}))&&void 0!==e?e:{};return Object.assign(Object.assign({},T),{user:null!==(o=null!==(i=null!==(t=T.userId)&&void 0!==t?t:null===(r=this.settings)||void 0===r?void 0:r.userId)&&void 0!==i?i:T["user.id"])&&void 0!==o?o:a.Defaults.DEFAULT_USER,"user.id":null!==(u=null!==(l=null!==(s=T.userId)&&void 0!==s?s:null===(c=this.settings)||void 0===c?void 0:c.userId)&&void 0!==l?l:T["user.id"])&&void 0!==u?u:a.Defaults.DEFAULT_USER,"service.name":null!==(g=null!==(p=null!==(d=T.serviceName)&&void 0!==d?d:null===(h=this.settings)||void 0===h?void 0:h.serviceName)&&void 0!==p?p:T["service.name"])&&void 0!==g?g:a.Defaults.DEFAULT_SERVICE_NAME,"service.instance.id":null!==(b=null!==(y=null!==(m=T.serviceId)&&void 0!==m?m:null===(f=this.settings)||void 0===f?void 0:f.serviceId)&&void 0!==y?y:T["service.instance.id"])&&void 0!==b?b:a.Defaults.DEFAULT_SERVICE_ID,"service.version":null!==(E=null!==(S=null!==(w=T.serviceVersion)&&void 0!==w?w:null===(v=this.settings)||void 0===v?void 0:v.serviceVersion)&&void 0!==S?S:T["service.version"])&&void 0!==E?E:a.Defaults.DEFAULT_SERVICE_VERSION,platformVersion:null!==(I=null!==(C=T.platformVersion)&&void 0!==C?C:null===(_=this.settings)||void 0===_?void 0:_.platformVersion)&&void 0!==I?I:a.Defaults.DEFAULT_PLATFORM_VERSION})},h.maybeAddResourceAttributesToAttributes(this.settings),h.maybeAddResourceAttributesToAttributes(this.settings.logs),h.maybeAddResourceAttributesToAttributes(this.settings.metrics),h.maybeAddResourceAttributesToAttributes(this.settings.traces),h.propagateAttributeDown("useSSOAuth",this.settings,this.settings.logs),h.propagateAttributeDown("useSSOAuth",this.settings,this.settings.metrics),h.propagateAttributeDown("useSSOAuth",this.settings,this.settings.traces),h.propagateAttributeDown("useSSOAuthRawToken",this.settings,this.settings.logs),h.propagateAttributeDown("useSSOAuthRawToken",this.settings,this.settings.metrics),h.propagateAttributeDown("useSSOAuthRawToken",this.settings,this.settings.traces),h.propagateAttributesDown("headers",this.settings,this.settings.logs),h.propagateAttributesDown("headers",this.settings,this.settings.metrics),h.propagateAttributesDown("headers",this.settings,this.settings.traces),h.propagateAttributesDown("additionalAttributes",this.settings,this.settings.logs),h.propagateAttributesDown("additionalResourceAttributes",this.settings,this.settings.logs),h.propagateAttributesDown("additionalAttributes",this.settings,this.settings.metrics),h.propagateAttributesDown("additionalResourceAttributes",this.settings,this.settings.metrics),h.propagateAttributesDown("additionalAttributes",this.settings,this.settings.traces),h.propagateAttributesDown("additionalResourceAttributes",this.settings,this.settings.traces);const b=(null!==(g=this.metricsBuilder)&&void 0!==g?g:this.withMetrics()).withLogger(this.logger).withSettings(this.settings).build(),w=(null!==(m=this.tracesBuilder)&&void 0!==m?m:this.withTraces()).withLogger(this.logger).withSettings(this.settings).withMetrics(b).build();l.Traces.instance=w;const v=(null!==(f=this.logsBuilder)&&void 0!==f?f:this.withLogs()).withLogger(this.logger).withSettings(this.settings).build();return l.Logs.instance=v,new n.Container(y,w,b,v,this.logger)}static propagateAttributeDown(e,t,r){var n;r&&(r[e]=null!==(n=r[e])&&void 0!==n?n:t[e])}static propagateAttributesDown(e,t,r){var i,o;if(!r)return;const s=null!==(i=t[e])&&void 0!==i?i:{},a=null!==(o=r[e])&&void 0!==o?o:{};r[e]=()=>Object.assign(Object.assign({},n.Container.errorless(s)),n.Container.errorless(a))}static maybeAddResourceAttributesToAttributes(e){if(null==e?void 0:e.addResourceAttributesToAttributes){const t=e.additionalResourceAttributes,r=e.additionalAttributes;e.additionalAttributes=()=>Object.assign(Object.assign({},n.Container.errorless(t)),n.Container.errorless(r))}}}return builder$3.Builder=h,builder$3}var log4jsWrapper={},hasRequiredLog4jsWrapper;function requireLog4jsWrapper(){if(hasRequiredLog4jsWrapper)return log4jsWrapper;hasRequiredLog4jsWrapper=1,Object.defineProperty(log4jsWrapper,"__esModule",{value:!0}),log4jsWrapper.Log4jsWrapper=void 0;return log4jsWrapper.Log4jsWrapper=class{constructor(e){this.logger=e}get level(){return this.convert("level"in this.logger?this.logger.level:this.logger.publishLevel())}error(e,...t){this.logger.warn(e,...t)}warn(e,...t){this.logger.warn(e,...t)}info(e,...t){this.logger.info(e,...t)}debug(e,...t){this.logger.debug(e,...t)}verbose(e,...t){this.logger.trace(e,...t)}convert(e){if(void 0===e)return 60;switch("string"!=typeof e?e.levelStr.toLowerCase():e.toLowerCase()){case"off":return 0;case"error":return 30;case"warn":return 50;case"info":default:return 60;case"debug":return 70;case"trace":return 80}}},log4jsWrapper}var metricsDependencyBuilder={},nullPerfProvider={},hasRequiredNullPerfProvider,hasRequiredMetricsDependencyBuilder;function requireNullPerfProvider(){if(hasRequiredNullPerfProvider)return nullPerfProvider;hasRequiredNullPerfProvider=1,Object.defineProperty(nullPerfProvider,"__esModule",{value:!0}),nullPerfProvider.NullPerformanceProvider=void 0;return nullPerfProvider.NullPerformanceProvider=class{getAppsCPU(){return Promise.resolve(void 0)}getAppsMemory(){return Promise.resolve(void 0)}getSystemCPU(){return Promise.resolve(void 0)}getSystemMemory(){return Promise.resolve(void 0)}},nullPerfProvider}function requireMetricsDependencyBuilder(){if(hasRequiredMetricsDependencyBuilder)return metricsDependencyBuilder;hasRequiredMetricsDependencyBuilder=1,Object.defineProperty(metricsDependencyBuilder,"__esModule",{value:!0}),metricsDependencyBuilder.MetricsDependencyBuilder=void 0;const e=requireNullPerfProvider();return metricsDependencyBuilder.MetricsDependencyBuilder=class{constructor(){this.performanceProvider=new e.NullPerformanceProvider,this.instanceFocusedHandler=()=>()=>{},this.instanceStartedHandler=()=>()=>{},this.instanceStoppedHandler=()=>()=>{},this.instanceReadyHandler=()=>()=>{},this.instanceErrorHandler=()=>()=>{},this.instanceCrashHandler=()=>()=>{},this.layoutRestoredHandler=()=>()=>{},this.platformStartedHandler=()=>()=>{},this.platformErrorHandler=()=>()=>{},this.workspaceLoadedHandler=()=>()=>{},this.workspaceRestoredHandler=()=>()=>{},this.workspaceSavedHandler=()=>()=>{},this.workspaceStoppedHandler=()=>()=>{},this.workspaceSelectedHandler=()=>()=>{},this.workspaceStartedHandler=()=>()=>{},this.workspaceFrameCreatedHandler=()=>()=>{},this.workspaceFrameInitHandler=()=>()=>{},this.workspaceFramePageLoadHandler=()=>()=>{},this.workspaceFrameWorkspaceRenderHandler=()=>()=>{},this.workspaceComponentCreatedHandler=()=>()=>{},this.workspaceAppsStartedHandler=()=>()=>{},this.workspaceStartupHandler=()=>()=>{}}build(){return{performanceProvider:this.performanceProvider,instanceStartedHandler:this.instanceStartedHandler,instanceStoppedHandler:this.instanceStoppedHandler,instanceReadyHandler:this.instanceReadyHandler,instanceFocusedHandler:this.instanceFocusedHandler,instanceErrorHandler:this.instanceErrorHandler,instanceCrashHandler:this.instanceCrashHandler,layoutRestoredHandler:this.layoutRestoredHandler,platformStartedHandler:this.platformStartedHandler,platformErrorHandler:this.platformErrorHandler,workspaceLoadedHandler:this.workspaceLoadedHandler,workspaceSavedHandler:this.workspaceSavedHandler,workspaceStoppedHandler:this.workspaceStoppedHandler,workspaceSelectedHandler:this.workspaceSelectedHandler,workspaceRestoredHandler:this.workspaceRestoredHandler,workspaceStartedHandler:this.workspaceStartedHandler,workspaceStartupHandler:this.workspaceStartupHandler,workspaceFrameCreatedHandler:this.workspaceFrameCreatedHandler,workspaceFrameInitHandler:this.workspaceFrameInitHandler,workspaceFramePageLoadHandler:this.workspaceFramePageLoadHandler,workspaceFrameWorkspaceRenderHandler:this.workspaceFrameWorkspaceRenderHandler,workspaceComponentCreatedHandler:this.workspaceComponentCreatedHandler,workspaceAppsStartedHandler:this.workspaceAppsStartedHandler}}withInstanceStartedHandler(e){return this.instanceStartedHandler=e,this}withInstanceStoppedHandler(e){return this.instanceStoppedHandler=e,this}withInstanceReadyHandler(e){return this.instanceReadyHandler=e,this}withInstanceFocusedHandler(e){return this.instanceFocusedHandler=e,this}withInstanceErrorHandler(e){return this.instanceErrorHandler=e,this}withInstanceCrashHandler(e){return this.instanceCrashHandler=e,this}withLayoutRestoredHandler(e){return this.layoutRestoredHandler=e,this}withWorkspaceLoadedHandler(e){return this.workspaceLoadedHandler=e,this}withWorkspaceSavedHandler(e){return this.workspaceSavedHandler=e,this}withWorkspaceStartedHandler(e){return this.workspaceRestoredHandler=()=>()=>{},this.workspaceStartedHandler=e,this}withWorkspaceStoppedHandler(e){return this.workspaceStoppedHandler=e,this}withWorkspaceSelectedHandler(e){return this.workspaceSelectedHandler=e,this}withPlatformStartedHandler(e){return this.platformStartedHandler=e,this}withPlatformErrorHandler(e){return this.platformErrorHandler=e,this}withPerfProvider(e){return this.performanceProvider=e,this}withWorkspaceRestoredHandler(e){return this.workspaceRestoredHandler=e,this.workspaceStartedHandler=()=>()=>{},this}withWorkspaceStartupHandler(e){return this.workspaceStartupHandler=e,this}withWorkspaceFrameCreatedHandler(e){return this.workspaceFrameCreatedHandler=e,this}withWorkspaceFrameInitHandler(e){return this.workspaceFrameInitHandler=e,this}withWorkspaceFramePageLoadHandler(e){return this.workspaceFramePageLoadHandler=e,this}withWorkspaceFrameWorkspaceRenderHandler(e){return this.workspaceFrameWorkspaceRenderHandler=e,this}withWorkspaceComponentCreatedHandler(e){return this.workspaceComponentCreatedHandler=e,this}withWorkspaceAppsStartedHandler(e){return this.workspaceAppsStartedHandler=e,this}},metricsDependencyBuilder}var logs={},hasRequiredLogs;function requireLogs(){if(hasRequiredLogs)return logs;hasRequiredLogs=1,Object.defineProperty(logs,"__esModule",{value:!0}),logs.Logs=void 0;const e=requireNullManager();class t{static get instance(){var r,n;return(null===(r=null===globalThis||void 0===globalThis?void 0:globalThis.ioInsightsInternals)||void 0===r?void 0:r.logs)?null===(n=null===globalThis||void 0===globalThis?void 0:globalThis.ioInsightsInternals)||void 0===n?void 0:n.logs:(t._instance||(t._instance=new e.NullLogsManager(void 0,void 0,void 0)),t._instance)}static set instance(e){t._instance=e}static emit(e){return t.instance.emit(e)}}return logs.Logs=t,logs}var pluginLoader={},hasRequiredPluginLoader;function requirePluginLoader(){if(hasRequiredPluginLoader)return pluginLoader;hasRequiredPluginLoader=1,Object.defineProperty(pluginLoader,"__esModule",{value:!0}),pluginLoader.loadInsightsPlugin=function(t,r){if(void 0!==e.get(t))return e.get(t);if(void 0===globalThis.ioInsightsPlugins)return null;let n=globalThis.ioInsightsPlugins[t];if(!n)return null;if("function"==typeof n)try{n=n()}catch(n){return null==r||r.error(`Error loading io.Insights plugin ${t}`,n),e.set(t,null),null}return e.set(t,n),n},pluginLoader.registerInsightsPlugin=function(e,t){void 0===globalThis.ioInsightsPlugins&&(globalThis.ioInsightsPlugins={});globalThis.ioInsightsPlugins[e]=t};const e=new Map;return pluginLoader}var isNode={},hasRequiredIsNode,hasRequiredDist;function requireIsNode(){if(hasRequiredIsNode)return isNode;let e;return hasRequiredIsNode=1,Object.defineProperty(isNode,"__esModule",{value:!0}),isNode.isNode=function(){if(void 0!==e)return e;if("undefined"!=typeof window)return e=!1,!1;try{e="[object process]"===Object.prototype.toString.call(commonjsGlobal.process)}catch(t){e=!1}return e},isNode}function requireDist(){return hasRequiredDist||(hasRequiredDist=1,function(e){var t,r=dist$3&&dist$3.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),n=dist$3&&dist$3.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=dist$3&&dist$3.__importStar||(t=function(e){return t=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},t(e)},function(e){if(e&&e.__esModule)return e;var i={};if(null!=e)for(var o=t(e),s=0;s<o.length;s++)"default"!==o[s]&&r(i,e,o[s]);return n(i,e),i}),o=dist$3&&dist$3.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.SpanStatusCode=e.deep_value=e.extractFilteringContextFromArgs=e.getOTELData=e.flattenOtelAtributes=e.safeStringify=e.isNode=e.loadInsightsPlugin=e.registerInsightsPlugin=e.Logs=e.NullTracingState=e.OTEL_PI_KEY=e.withSpan=e.Traces=e.MetricsDependencyBuilder=e.NullMetric=e.Container=e.Log4jsWrapper=e.Builder=void 0;var s=requireBuilder();Object.defineProperty(e,"Builder",{enumerable:!0,get:function(){return s.Builder}});var a=requireLog4jsWrapper();Object.defineProperty(e,"Log4jsWrapper",{enumerable:!0,get:function(){return a.Log4jsWrapper}});var c=requireContainer();Object.defineProperty(e,"Container",{enumerable:!0,get:function(){return c.Container}});var l=require_null$1();Object.defineProperty(e,"NullMetric",{enumerable:!0,get:function(){return l.NullMetric}});var u=requireMetricsDependencyBuilder();Object.defineProperty(e,"MetricsDependencyBuilder",{enumerable:!0,get:function(){return u.MetricsDependencyBuilder}});const d=i(requireTraces());e.Traces=d.default,Object.defineProperty(e,"withSpan",{enumerable:!0,get:function(){return d.withSpan}}),e.OTEL_PI_KEY="__interopIOTracePropagationInfo";const h=o(requireNullTracingState());e.NullTracingState=h.default;var p=requireLogs();Object.defineProperty(e,"Logs",{enumerable:!0,get:function(){return p.Logs}});const g=requirePluginLoader();Object.defineProperty(e,"registerInsightsPlugin",{enumerable:!0,get:function(){return g.registerInsightsPlugin}}),Object.defineProperty(e,"loadInsightsPlugin",{enumerable:!0,get:function(){return g.loadInsightsPlugin}});const m=requireIsNode();Object.defineProperty(e,"isNode",{enumerable:!0,get:function(){return m.isNode}});const f=requireSafeStringify();Object.defineProperty(e,"safeStringify",{enumerable:!0,get:function(){return f.safeStringify}});const y=requireOtelUtils();var $;Object.defineProperty(e,"getOTELData",{enumerable:!0,get:function(){return y.getOTELData}}),Object.defineProperty(e,"flattenOtelAtributes",{enumerable:!0,get:function(){return y.flattenOtelAtributes}}),Object.defineProperty(e,"extractFilteringContextFromArgs",{enumerable:!0,get:function(){return y.extractFilteringContextFromArgs}}),Object.defineProperty(e,"deep_value",{enumerable:!0,get:function(){return y.deep_value}}),"undefined"!=typeof Promise&&(Promise.allSettled=Promise.allSettled||(e=>Promise.all(e.map(e=>e.then(e=>({status:"fulfilled",value:e})).catch(e=>({status:"rejected",reason:e})))))),function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"}($||(e.SpanStatusCode=$={}))}(dist$3)),dist$3}var distExports=requireDist();function setInsightsAttributes(e,t,r,n){let i=e.applicationName??"unknown-app";r&&(i=e.applicationName??r?.appName??i),n&&(i=e.applicationName??n.applicationConfig.name??i),e.applicationName=i,e.traces?.closeTrace&&r?.addCloseHandler(()=>distExports.Traces.withSpan("interopio.api.application.close",()=>{}));const o=r?.sid,s=r?.user,a=(Utils.isNode()&&process?.env?.USERNAME)??r?.env?.windowsUserName,c=(Utils.isNode()&&process?.env?.COMPUTERNAME)??r?.env?.machineName,l=n?.env??r?.env?.env,u=n?.region??r?.env?.region,d=n?.instanceId??r?.appInstanceId??"",h=r?.windowId,p={interopioCoreVersion:version$2,interopioLibVersion:t.version||version$2,host:"io.api",tracingAppName:i,tracingAppInstanceId:d,user:s,osUser:a,machine:c,env:l,region:u,windowId:h,sid:o};let g=e.additionalResourceAttributes;if("function"!=typeof g){const t=e.additionalResourceAttributes;g=()=>t}e.additionalResourceAttributes=()=>({...p,...g()})}function setDefaultTraceFilters(e){e.traces&&(e.traces.defaultFilters??=[],e.traces.defaultFilters.push({source:"interopio.api.instrumentation.fetch",canBeRoot:!1}),e.traces.defaultFilters.push({source:"interopio.api.instrumentation.xhr",canBeRoot:!1}),e.traces.defaultFilters.push({source:"interopio.api.prefs",canBeRoot:!1}),e.traces.defaultFilters.push({source:"interopio.api.layouts",canBeRoot:!1}),e.traces.defaultFilters.push({source:"interopio.api.windows",canBeRoot:!1}),e.traces.defaultFilters.push({source:"interopio.api.interop",context:{stream:"#^t42[.].*"},canBeRoot:!1,enabled:!1}),e.traces.defaultFilters.push({source:"interopio.api.interop",context:{stream:"apps.event"},canBeRoot:!1,enabled:!1}),e.traces.defaultFilters.push({source:"interopio.api.interop",context:{name:"#^t42[.].*"},canBeRoot:!1,enabled:!1}),e.traces.defaultFilters.push({source:"interopio.api.interop",context:{name:"apps.event"},canBeRoot:!1,enabled:!1}),e.traces.defaultFilters.push({source:"interopio.api.interop",context:{method:"apps.command"},canBeRoot:!1}),e.traces.defaultFilters.push({source:"interopio.api.interop",context:{method:"#^t42[.].*"},canBeRoot:!1}),e.traces.defaultFilters.push({source:"interopio.api.contexts",context:{context:"___insights_pi_storage___"},enabled:!1}),e.traces.defaultFilters.push({source:"interopio.api.contexts",context:{context:"#^t42[.].*"},canBeRoot:!1}),e.traces.defaultFilters.push({source:"interopio.api.contexts",context:{context:"#^__.*"},canBeRoot:!1}),e.traces.defaultFilters.push({source:"interopio.api.appManager",canBeRoot:!1}),e.traces.defaultFilters.push({source:"interopio.api.notifications",canBeRoot:!1}))}function prepareConfig(e,t,r){let n;if(Utils.isNode()){const e=process.env._GD_STARTING_CONTEXT_;if(e)try{n=JSON.parse(e)}catch{}}function i(){if(e.application)return e.application;if(r)return r.applicationName;if("undefined"!=typeof window&&void 0!==window.glue42electron)return window.glue42electron.application;const t=nanoid$1(10);return Utils.isNode()?n?n.applicationConfig.name:"NodeJS"+t:"undefined"!=typeof window&&"undefined"!=typeof document?document.title+` (${t})`:t}const o=function(){const o=e.gateway,s=o?.protocolVersion??3,a=o?.reconnectInterval,c=o?.reconnectAttempts;let l=o?.ws;const u=o?.sharedWorker,d=o?.inproc,h=o?.webPlatform??void 0;let p,g,m,f,y;r&&(l=r.gwURL),Utils.isNode()&&n&&n.gwURL&&(l=n.gwURL),l||u||d||(l="ws://localhost:8385");const $=i();let b=$;void 0!==r?(g=r.windowId,m=r.pid,r.env&&(f=r.env.env,y=r.env.region),b=r.application??"glue-app",p=r.appInstanceId):Utils.isNode()?(m=process.pid,n&&(f=n.env,y=n.region,p=n.instanceId)):void 0!==window?.glue42electron&&(g=window?.glue42electron.instanceId,m=window?.glue42electron.pid,f=window?.glue42electron.env,y=window?.glue42electron.region,b=window?.glue42electron.application??"glue-app",p=window?.glue42electron.instanceId);const w=e.gateway?.replaySpecs??[];w.push(ContextMessageReplaySpec);let v={application:b,applicationName:$,windowId:g,instance:p,process:m,region:y,environment:f,api:t.version||version$2};return e.identity&&(v=Object.assign(v,e.identity)),{identity:v,reconnectInterval:a,ws:l,sharedWorker:u,webPlatform:h,inproc:d,protocolVersion:s,reconnectAttempts:c,replaySpecs:w}}();let s=i();if("undefined"!=typeof window){const e=window,t=e.htmlContainer?`${e.htmlContainer.containerName}.${e.htmlContainer.application}`:e?.glue42gd?.application;t&&(s=t)}return{bus:e.bus??!1,application:s,auth:"string"==typeof e.auth?{token:e.auth}:e.auth?e.auth:Utils.isNode()&&n&&n.gwToken?{gatewayToken:n.gwToken}:e.gateway?.webPlatform?{username:"glue42",password:""}:void 0,logger:function(){let t=e.logger;const n="warn";let i;return t||(t=n),r&&(i=r.consoleLogLevel),"string"==typeof t?{console:i??t,publish:n}:{console:i??t.console??n,publish:t.publish??n}}(),connection:o,metrics:e.metrics??!0,contexts:function(){const t={reAnnounceKnownContexts:!0,subscribeOnUpdate:!0,subscribeOnGet:!0,onlyReAnnounceSubscribedContexts:!0};return void 0===e.contexts||"boolean"==typeof e.contexts&&e.contexts?t:"object"==typeof e.contexts&&{...t,...e.contexts}}(),version:t.version||version$2,libs:t.libs??[],customLogger:e.customLogger,getInsights:async function(i,o,s){const a=e.insights;if("object"!=typeof a&&"boolean"!=typeof a&&void 0!==a)throw new Error("insights/otel property should be boolean, object or unspecified");if(!1===a)return{enabled:!1};let c,l;return i?c=i.insights:Utils.isNode()&&!1!==e?.insights&&!1!==e?.insights?.enabled&&!1!==e?.insights?.requestSettings&&(c=await(o?.invoke("T42.Otel.GetConfig",void 0,n?{environment:n.env,region:n.region}:void 0,{waitTimeoutMs:0}).then(e=>e.returned).catch(e=>s?.warn("Unable to retrieve base io.Insights settings: "+(e?.message??e))))),c&&(i||n||Utils.isNode()&&("boolean"==typeof a||!a?.platformInstance))&&(c={...c,metrics:{...c?.metrics,enabled:!!c?.metrics?.enabled,platformMetricsEnabled:!1}}),l=!0===a||void 0===a?c??{enabled:!1}:deepMerge(c||{},a,{isMergeableObject:isPlainObject$1$1}),setInsightsAttributes(l,t,r,n),l.traces?.enabled&&setDefaultTraceFilters(l),l}}}function __decorate(e,t,r,n){var i,o=arguments.length,s=o<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s}"function"==typeof SuppressedError&&SuppressedError;class GW3ContextData{name;contextId;context;isAnnounced;createdByUs;joinedActivity;updateCallbacks={};activityId;sentExplicitSubscription;get hasReceivedSnapshot(){return this.snapshotPromiseWrapper.resolved}set hasReceivedSnapshot(e){e?this.snapshotPromiseWrapper.resolve():this.snapshotPromiseWrapper=new PromiseWrapper$1}get snapshotPromise(){return this.snapshotPromiseWrapper.promise}snapshotPromiseWrapper;constructor(e,t,r,n){this.contextId=e,this.name=t,this.isAnnounced=r,this.activityId=n,this.context={},this.snapshotPromiseWrapper=new PromiseWrapper$1}hasCallbacks(){return Object.keys(this.updateCallbacks).length>0}getState(){return this.isAnnounced&&this.hasCallbacks()?3:this.isAnnounced?2:this.hasCallbacks()?1:0}}var lodash_clonedeep$1={exports:{}},hasRequiredLodash_clonedeep;function requireLodash_clonedeep(){return hasRequiredLodash_clonedeep||(hasRequiredLodash_clonedeep=1,function(e,t){var r="__lodash_hash_undefined__",n=9007199254740991,i="[object Arguments]",o="[object Boolean]",s="[object Date]",a="[object Function]",c="[object GeneratorFunction]",l="[object Map]",u="[object Number]",d="[object Object]",h="[object Promise]",p="[object RegExp]",g="[object Set]",m="[object String]",f="[object Symbol]",y="[object WeakMap]",$="[object ArrayBuffer]",b="[object DataView]",w="[object Float32Array]",v="[object Float64Array]",S="[object Int8Array]",E="[object Int16Array]",C="[object Int32Array]",_="[object Uint8Array]",I="[object Uint8ClampedArray]",T="[object Uint16Array]",A="[object Uint32Array]",D=/\w*$/,x=/^\[object .+?Constructor\]$/,R=/^(?:0|[1-9]\d*)$/,O={};O[i]=O["[object Array]"]=O[$]=O[b]=O[o]=O[s]=O[w]=O[v]=O[S]=O[E]=O[C]=O[l]=O[u]=O[d]=O[p]=O[g]=O[m]=O[f]=O[_]=O[I]=O[T]=O[A]=!0,O["[object Error]"]=O[a]=O[y]=!1;var P="object"==typeof commonjsGlobal&&commonjsGlobal&&commonjsGlobal.Object===Object&&commonjsGlobal,N="object"==typeof self&&self&&self.Object===Object&&self,k=P||N||Function("return this")(),M=t&&!t.nodeType&&t,L=M&&e&&!e.nodeType&&e,F=L&&L.exports===M;function j(e,t){return e.set(t[0],t[1]),e}function U(e,t){return e.add(t),e}function B(e,t,r,n){for(var i=-1,o=e?e.length:0;++i<o;)r=t(r,e[i],i,e);return r}function q(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(e){}return t}function H(e){var t=-1,r=Array(e.size);return e.forEach(function(e,n){r[++t]=[n,e]}),r}function W(e,t){return function(r){return e(t(r))}}function G(e){var t=-1,r=Array(e.size);return e.forEach(function(e){r[++t]=e}),r}var J,K=Array.prototype,V=Function.prototype,z=Object.prototype,X=k["__core-js_shared__"],Y=(J=/[^.]+$/.exec(X&&X.keys&&X.keys.IE_PROTO||""))?"Symbol(src)_1."+J:"",Z=V.toString,Q=z.hasOwnProperty,ee=z.toString,te=RegExp("^"+Z.call(Q).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),re=F?k.Buffer:void 0,ne=k.Symbol,ie=k.Uint8Array,oe=W(Object.getPrototypeOf,Object),se=Object.create,ae=z.propertyIsEnumerable,ce=K.splice,le=Object.getOwnPropertySymbols,ue=re?re.isBuffer:void 0,de=W(Object.keys,Object),he=Le(k,"DataView"),pe=Le(k,"Map"),ge=Le(k,"Promise"),me=Le(k,"Set"),fe=Le(k,"WeakMap"),ye=Le(Object,"create"),$e=qe(he),be=qe(pe),we=qe(ge),ve=qe(me),Se=qe(fe),Ee=ne?ne.prototype:void 0,Ce=Ee?Ee.valueOf:void 0;function _e(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function Ie(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function Te(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function Ae(e){this.__data__=new Ie(e)}function De(e,t){var r=We(e)||function(e){return function(e){return function(e){return!!e&&"object"==typeof e}(e)&&Ge(e)}(e)&&Q.call(e,"callee")&&(!ae.call(e,"callee")||ee.call(e)==i)}(e)?function(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}(e.length,String):[],n=r.length,o=!!n;for(var s in e)!Q.call(e,s)||o&&("length"==s||Ue(s,n))||r.push(s);return r}function xe(e,t,r){var n=e[t];Q.call(e,t)&&He(n,r)&&(void 0!==r||t in e)||(e[t]=r)}function Re(e,t){for(var r=e.length;r--;)if(He(e[r][0],t))return r;return-1}function Oe(e,t,r,n,h,y,x){var R;if(n&&(R=y?n(e,h,y,x):n(e)),void 0!==R)return R;if(!Ve(e))return e;var P=We(e);if(P){if(R=function(e){var t=e.length,r=e.constructor(t);t&&"string"==typeof e[0]&&Q.call(e,"index")&&(r.index=e.index,r.input=e.input);return r}(e),!t)return function(e,t){var r=-1,n=e.length;t||(t=Array(n));for(;++r<n;)t[r]=e[r];return t}(e,R)}else{var N=je(e),k=N==a||N==c;if(Je(e))return function(e,t){if(t)return e.slice();var r=new e.constructor(e.length);return e.copy(r),r}(e,t);if(N==d||N==i||k&&!y){if(q(e))return y?e:{};if(R=function(e){return"function"!=typeof e.constructor||Be(e)?{}:(t=oe(e),Ve(t)?se(t):{});var t}(k?{}:e),!t)return function(e,t){return ke(e,Fe(e),t)}(e,function(e,t){return e&&ke(t,ze(t),e)}(R,e))}else{if(!O[N])return y?e:{};R=function(e,t,r,n){var i=e.constructor;switch(t){case $:return Ne(e);case o:case s:return new i(+e);case b:return function(e,t){var r=t?Ne(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.byteLength)}(e,n);case w:case v:case S:case E:case C:case _:case I:case T:case A:return function(e,t){var r=t?Ne(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}(e,n);case l:return function(e,t,r){var n=t?r(H(e),!0):H(e);return B(n,j,new e.constructor)}(e,n,r);case u:case m:return new i(e);case p:return function(e){var t=new e.constructor(e.source,D.exec(e));return t.lastIndex=e.lastIndex,t}(e);case g:return function(e,t,r){var n=t?r(G(e),!0):G(e);return B(n,U,new e.constructor)}(e,n,r);case f:return a=e,Ce?Object(Ce.call(a)):{}}var a}(e,N,Oe,t)}}x||(x=new Ae);var M=x.get(e);if(M)return M;if(x.set(e,R),!P)var L=r?function(e){return function(e,t,r){var n=t(e);return We(e)?n:function(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e}(n,r(e))}(e,ze,Fe)}(e):ze(e);return function(e,t){for(var r=-1,n=e?e.length:0;++r<n&&!1!==t(e[r],r,e););}(L||e,function(i,o){L&&(i=e[o=i]),xe(R,o,Oe(i,t,r,n,o,e,x))}),R}function Pe(e){return!(!Ve(e)||(t=e,Y&&Y in t))&&(Ke(e)||q(e)?te:x).test(qe(e));var t}function Ne(e){var t=new e.constructor(e.byteLength);return new ie(t).set(new ie(e)),t}function ke(e,t,r,n){r||(r={});for(var i=-1,o=t.length;++i<o;){var s=t[i];xe(r,s,e[s])}return r}function Me(e,t){var r=e.__data__;return function(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}(t)?r["string"==typeof t?"string":"hash"]:r.map}function Le(e,t){var r=function(e,t){return null==e?void 0:e[t]}(e,t);return Pe(r)?r:void 0}_e.prototype.clear=function(){this.__data__=ye?ye(null):{}},_e.prototype.delete=function(e){return this.has(e)&&delete this.__data__[e]},_e.prototype.get=function(e){var t=this.__data__;if(ye){var n=t[e];return n===r?void 0:n}return Q.call(t,e)?t[e]:void 0},_e.prototype.has=function(e){var t=this.__data__;return ye?void 0!==t[e]:Q.call(t,e)},_e.prototype.set=function(e,t){return this.__data__[e]=ye&&void 0===t?r:t,this},Ie.prototype.clear=function(){this.__data__=[]},Ie.prototype.delete=function(e){var t=this.__data__,r=Re(t,e);return!(r<0)&&(r==t.length-1?t.pop():ce.call(t,r,1),!0)},Ie.prototype.get=function(e){var t=this.__data__,r=Re(t,e);return r<0?void 0:t[r][1]},Ie.prototype.has=function(e){return Re(this.__data__,e)>-1},Ie.prototype.set=function(e,t){var r=this.__data__,n=Re(r,e);return n<0?r.push([e,t]):r[n][1]=t,this},Te.prototype.clear=function(){this.__data__={hash:new _e,map:new(pe||Ie),string:new _e}},Te.prototype.delete=function(e){return Me(this,e).delete(e)},Te.prototype.get=function(e){return Me(this,e).get(e)},Te.prototype.has=function(e){return Me(this,e).has(e)},Te.prototype.set=function(e,t){return Me(this,e).set(e,t),this},Ae.prototype.clear=function(){this.__data__=new Ie},Ae.prototype.delete=function(e){return this.__data__.delete(e)},Ae.prototype.get=function(e){return this.__data__.get(e)},Ae.prototype.has=function(e){return this.__data__.has(e)},Ae.prototype.set=function(e,t){var r=this.__data__;if(r instanceof Ie){var n=r.__data__;if(!pe||n.length<199)return n.push([e,t]),this;r=this.__data__=new Te(n)}return r.set(e,t),this};var Fe=le?W(le,Object):function(){return[]},je=function(e){return ee.call(e)};function Ue(e,t){return!!(t=null==t?n:t)&&("number"==typeof e||R.test(e))&&e>-1&&e%1==0&&e<t}function Be(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||z)}function qe(e){if(null!=e){try{return Z.call(e)}catch(e){}try{return e+""}catch(e){}}return""}function He(e,t){return e===t||e!=e&&t!=t}(he&&je(new he(new ArrayBuffer(1)))!=b||pe&&je(new pe)!=l||ge&&je(ge.resolve())!=h||me&&je(new me)!=g||fe&&je(new fe)!=y)&&(je=function(e){var t=ee.call(e),r=t==d?e.constructor:void 0,n=r?qe(r):void 0;if(n)switch(n){case $e:return b;case be:return l;case we:return h;case ve:return g;case Se:return y}return t});var We=Array.isArray;function Ge(e){return null!=e&&function(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=n}(e.length)&&!Ke(e)}var Je=ue||function(){return!1};function Ke(e){var t=Ve(e)?ee.call(e):"";return t==a||t==c}function Ve(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function ze(e){return Ge(e)?De(e):function(e){if(!Be(e))return de(e);var t=[];for(var r in Object(e))Q.call(e,r)&&"constructor"!=r&&t.push(r);return t}(e)}e.exports=function(e){return Oe(e,!0,!0)}}(lodash_clonedeep$1,lodash_clonedeep$1.exports)),lodash_clonedeep$1.exports}lodash_clonedeep$1.exports;var lodash_clonedeepExports$1=requireLodash_clonedeep(),cloneDeep=getDefaultExportFromCjs(lodash_clonedeepExports$1);function applyContextDelta(e,t,r){try{if(r?.canPublish("trace")&&r?.trace(`applying context delta ${JSON.stringify(t)} on context ${JSON.stringify(e)}`),!t)return e;if(t.reset)return e={...t.reset};if(e=deepClone(e,void 0),t.commands){for(const r of t.commands)"remove"===r.type?deletePath(e,r.path):"set"===r.type&&setValueToPath(e,r.value,r.path);return e}const n=t.added,i=t.updated,o=t.removed;return n&&Object.keys(n).forEach(t=>{e[t]=n[t]}),i&&Object.keys(i).forEach(t=>{mergeObjectsProperties(t,e,i)}),o&&o.forEach(t=>{delete e[t]}),distExports.Traces.removePropagationInfo(e),e}catch(n){return r?.error(`error applying context delta ${JSON.stringify(t)} on context ${JSON.stringify(e)}`,n),e}}function deepClone(e,t){return cloneDeep(e)}const mergeObjectsProperties=(e,t,r)=>{const n=r[e];if(void 0===n)return t;const i=t[e];return i&&n?"string"==typeof i||"number"==typeof i||"boolean"==typeof i||"string"==typeof n||"number"==typeof n||"boolean"==typeof n||Array.isArray(i)||Array.isArray(n)?(t[e]=n,t):(t[e]=Object.assign({},i,n),t):(t[e]=n,t)};function deepEqual(e,t){if(e===t)return!0;if(!(e instanceof Object&&t instanceof Object))return!1;if(e.constructor!==t.constructor)return!1;for(const r in e)if(e.hasOwnProperty(r)){if(!t.hasOwnProperty(r))return!1;if(e[r]!==t[r]){if("object"!=typeof e[r])return!1;if(!deepEqual(e[r],t[r]))return!1}}for(const r in t)if(t.hasOwnProperty(r)&&!e.hasOwnProperty(r))return!1;return!0}function setValueToPath(e,t,r){const n=r.split("."),i=["__proto__","constructor","prototype"];let o;for(o=0;o<n.length-1;o++){const t=n[o];if(i.includes(t))throw new Error(`The provided path ${r} is invalid. It cannot contain segment/key that is equal to one of the following values: ${i}.`);e[t]||(e[t]={}),"object"!=typeof e[t]&&(e[t]={}),e=e[t]}e[n[o]]=t}function isSubset(e,t){return Object.keys(t).every(r=>"object"==typeof t[r]?isSubset(e?.[r]||{},t[r]||{}):t[r]===e?.[r])}function deletePath(e,t){const r=t.split(".");let n;for(n=0;n<r.length-1;n++){if(!e[r[n]])return;e=e[r[n]]}delete e[r[n]]}class GW3Bridge{ERROR_URI_FAILURE="global.errors.failure";ERROR_URI_INVALID_CONTEXT="global.errors.invalid_context";_logger;_connection;_trackAllContexts;_reAnnounceKnownContexts;_subscribeOnUpdate;_subscribeOnGet;_onlyReAnnounceSubscribedContexts;_gw3Session;_contextNameToData={};_gw3Subscriptions=[];_nextCallbackSubscriptionNumber=0;_creationPromises={};_contextNameToId={};_contextIdToName={};_protocolVersion=void 0;_contextsTempCache={};_contextsSubscriptionsCache=[];_systemContextsSubKey;get protocolVersion(){if(!this._protocolVersion){const e=this._connection.availableDomains.find(e=>"context"===e.uri);this._protocolVersion=e?.version??1}return this._protocolVersion}get setPathSupported(){return this.protocolVersion>=2}constructor(e){this._connection=e.connection,this._logger=e.logger,this._trackAllContexts=e.trackAllContexts,this._reAnnounceKnownContexts=e.reAnnounceKnownContexts,this._subscribeOnUpdate=e.subscribeOnUpdate??!0,this._subscribeOnGet=e.subscribeOnGet??!0,this._onlyReAnnounceSubscribedContexts=e.onlyReAnnounceSubscribedContexts??!0,this._gw3Session=this._connection.domain("global",[GW_MESSAGE_CONTEXT_CREATED,GW_MESSAGE_SUBSCRIBED_CONTEXT,GW_MESSAGE_CONTEXT_DESTROYED,GW_MESSAGE_CONTEXT_UPDATED]),this._gw3Session.disconnected(this.resetState.bind(this)),this._gw3Session.onJoined(e=>{if(e)return this._reAnnounceKnownContexts?void this.reInitiateState().then(()=>this._connection.setLibReAnnounced({name:"contexts"})).catch(e=>{this._logger.warn(`Error while re-announcing contexts: ${JSON.stringify(e)}`)}):(this._contextsTempCache={},this._connection.setLibReAnnounced({name:"contexts"}))}),this.subscribeToContextCreatedMessages(),this.subscribeToContextUpdatedMessages(),this.subscribeToContextDestroyedMessages(),this._connection.replayer?.drain(ContextMessageReplaySpec.name,e=>{const t=e.type;t&&(t===GW_MESSAGE_CONTEXT_CREATED||t===GW_MESSAGE_CONTEXT_ADDED||t===GW_MESSAGE_ACTIVITY_CREATED?this.handleContextCreatedMessage(e):t===GW_MESSAGE_SUBSCRIBED_CONTEXT||t===GW_MESSAGE_CONTEXT_UPDATED||t===GW_MESSAGE_JOINED_ACTIVITY?this.handleContextUpdatedMessage(e):t!==GW_MESSAGE_CONTEXT_DESTROYED&&t!==GW_MESSAGE_ACTIVITY_DESTROYED||this.handleContextDestroyedMessage(e))})}dispose(){for(const e of this._gw3Subscriptions)this._connection.off(e);this._gw3Subscriptions.length=0;for(const e in this._contextNameToData)this._contextNameToId.hasOwnProperty(e)&&delete this._contextNameToData[e]}createContext(e,t){if(e in this._creationPromises)return this._creationPromises[e];const r=distExports.Traces.currentTracingState;return r.addData("INFO",{context:e}),r.addData("DIAGNOSTIC",{data:t}),t=deepClone(t),r.injectPropagationInfo(t),this._creationPromises[e]=this._gw3Session.send({type:GW_MESSAGE_CREATE_CONTEXT,domain:"global",name:e,data:t,lifetime:"retained"}).then(r=>{this._contextNameToId[e]=r.context_id,this._contextIdToName[r.context_id]=e;const n=this._contextNameToData[e]||new GW3ContextData(r.context_id,e,!0,void 0);return n.isAnnounced=!0,n.name=e,n.contextId=r.context_id,n.context=r.data||deepClone(t),n.hasReceivedSnapshot=!0,this._contextNameToData[e]=n,delete this._creationPromises[e],n.sentExplicitSubscription=!0,n.createdByUs=!0,this.subscribe(e,()=>{}),r.context_id}),this._creationPromises[e]}all(){return Object.keys(this._contextNameToData).filter(e=>this._contextNameToData[e].isAnnounced)}async update(e,t){t&&(t=deepClone(t));const r=distExports.Traces.currentTracingState;e in this._creationPromises&&(await this._creationPromises[e],distExports.Traces.currentTracingState=r);const n=this._contextNameToData[e];if(r.addData("DIAGNOSTIC",{data:n}),r.addData("DEBUG",{delta:t}),!n||!n.isAnnounced)return void await this.createContext(e,t);const i=await this.get(n.name);distExports.Traces.currentTracingState=r,distExports.Traces.removePropagationInfo(i);const o=this.setPathSupported?this.calculateContextDeltaV2(i,t):this.calculateContextDeltaV1(i,t);if(!(Object.keys(o.added).length||Object.keys(o.updated).length||o.removed.length||o.commands?.length))return Promise.resolve();const s=deepClone(o);r.injectPropagationInfo(s);const a=await this._gw3Session.send({type:GW_MESSAGE_UPDATE_CONTEXT,domain:"global",context_id:n.contextId,delta:s},{},{skipPeerId:!1});distExports.Traces.currentTracingState=r,!this._subscribeOnUpdate||n.sentExplicitSubscription||n.activityId||this.subscribe(e,()=>{}),(this._subscribeOnUpdate||n.sentExplicitSubscription||n.activityId)&&(await n.snapshotPromise,distExports.Traces.currentTracingState=r,this.handleUpdated(n,o,{updaterId:a.peer_id}))}async set(e,t){t&&(t=deepClone(t));const r=distExports.Traces.currentTracingState;e in this._creationPromises&&(await this._creationPromises[e],distExports.Traces.currentTracingState=r);const n=this._contextNameToData[e];if(r.addData("DIAGNOSTIC",{data:n}),r.injectPropagationInfo(t),!n||!n.isAnnounced)return this.createContext(e,t);const i=await this._gw3Session.send({type:GW_MESSAGE_UPDATE_CONTEXT,domain:"global",context_id:n.contextId,delta:{reset:t}},{},{skipPeerId:!1});distExports.Traces.currentTracingState=r,!this._subscribeOnUpdate||n.sentExplicitSubscription||n.activityId||this.subscribe(e,()=>{}),(this._subscribeOnUpdate||n.sentExplicitSubscription||n.activityId)&&this.handleUpdated(n,{reset:t,added:{},removed:[],updated:{}},{updaterId:i.peer_id})}setPath(e,t,r){return this.setPathSupported?this.setPaths(e,[{path:t,value:r}]):Promise.reject(new Error("contexts.setPath operation is not supported, use version 3.10 or later"))}async setPaths(e,t){if(!this.setPathSupported)return Promise.reject(new Error("contexts.setPaths operation is not supported, use version 3.10 or later"));t&&(t=deepClone(t));const r=distExports.Traces.currentTracingState;e in this._creationPromises&&(await this._creationPromises[e],distExports.Traces.currentTracingState=r);const n=this._contextNameToData[e];r.addData("DIAGNOSTIC",{data:n}),r.addData("DEBUG",{pathValues:t});const i={[distExports.OTEL_PI_KEY]:void 0};if(r.injectPropagationInfo(i),i[distExports.OTEL_PI_KEY]&&t.push({path:distExports.OTEL_PI_KEY,value:i[distExports.OTEL_PI_KEY]}),!n||!n.isAnnounced){const r={};for(const e of t)setValueToPath(r,e.value,e.path);return this.createContext(e,r)}const o=[];for(const e of t)null===e.value?o.push({type:"remove",path:e.path}):o.push({type:"set",path:e.path,value:e.value});const s=await this._gw3Session.send({type:GW_MESSAGE_UPDATE_CONTEXT,domain:"global",context_id:n.contextId,delta:{commands:o}},{},{skipPeerId:!1});distExports.Traces.currentTracingState=r,!this._subscribeOnUpdate||n.sentExplicitSubscription||n.activityId||this.subscribe(e,()=>{}),(this._subscribeOnUpdate||n.sentExplicitSubscription||n.activityId)&&(await n.snapshotPromise,distExports.Traces.currentTracingState=r,this.handleUpdated(n,{added:{},removed:[],updated:{},commands:o},{updaterId:s.peer_id}))}async get(e){const t=distExports.Traces.currentTracingState;t.addData("INFO",{context:e}),e in this._creationPromises&&(await this._creationPromises[e],distExports.Traces.currentTracingState=t);const r=this._contextNameToData[e];if(!r||!r.isAnnounced)return!r&&this._subscribeOnGet&&this.subscribeInner(e,()=>{}),Promise.resolve({});if(r&&!r.sentExplicitSubscription)return new Promise((t,r)=>{this.subscribeInner(e,(e,r,n,i)=>{distExports.Traces.removePropagationInfo(e),this._subscribeOnGet||this.unsubscribe(i),t(e)}).catch(e=>{this.isInvalidContextError(e)?t({}):r(e)})});await r.snapshotPromise;const n=r?.context??{};return distExports.Traces.removePropagationInfo(n),Promise.resolve(deepClone(n))}isInvalidContextError(e){return e.reason_uri===this.ERROR_URI_INVALID_CONTEXT||e.reason_uri===this.ERROR_URI_FAILURE&&e.reason?.startsWith("Unable to find context with id")}async subscribeInner(e,t,r){const n=distExports.Traces.currentTracingState;e in this._creationPromises&&(await this._creationPromises[e],distExports.Traces.currentTracingState=n);const i=void 0===r?this._nextCallbackSubscriptionNumber:r;void 0===r&&(this._nextCallbackSubscriptionNumber+=1,this._contextsSubscriptionsCache.push({contextName:e,subKey:i,callback:t}));let o=this._contextNameToData[e];if(!o||!o.isAnnounced)return o=o||new GW3ContextData(void 0,e,!1,void 0),this._contextNameToData[e]=o,o.updateCallbacks[i]=t,Promise.resolve(i);const s=o.hasCallbacks();if(o.updateCallbacks[i]=t,s){if(o.hasReceivedSnapshot&&!r){const e=deepClone(o.context);t(e,e,[],i)}return Promise.resolve(i)}if(o.joinedActivity||o.createdByUs){if(o.hasReceivedSnapshot&&!r){const e=deepClone(o.context);t(e,e,[],i)}return Promise.resolve(i)}if(o.context&&o.sentExplicitSubscription){if(o.hasReceivedSnapshot&&!r){const e=deepClone(o.context);t(e,e,[],i)}return Promise.resolve(i)}return this.sendSubscribe(o).then(()=>i,()=>(this.unsubscribe(i,!0),i))}async subscribe(e,t,r){const n=this.all().includes(e);distExports.Traces.currentTracingState.addData("INFO",{context:e,contextExists:n});return this.subscribeInner(e,async(...r)=>distExports.withSpan("interopio.api.contexts.bridge.subscribe.callback",{context:e},r?.[5],n=>(distExports.Traces.removePropagationInfo(r?.[0]),distExports.Traces.removePropagationInfo(r?.[1]),n.addData("INFO",{context:e}),n.addData("DEBUG",{delta:r?.[1]}),n.addData("DEBUG",{removed:r?.[2]}),n.addData("DIAGNOSTIC",{data:r?.[0]}),t(r?.[0],r?.[1],r?.[2],r?.[3],r?.[4]))),r)}unsubscribe(e,t){t||(this._contextsSubscriptionsCache=this._contextsSubscriptionsCache.filter(t=>t.subKey!==e));for(const t of Object.keys(this._contextNameToData)){const r=this._contextNameToData[t];if(!r)continue;const n=r.hasCallbacks();delete r.updateCallbacks[e],r.isAnnounced&&n&&!r.hasCallbacks()&&r.sentExplicitSubscription&&(r.hasReceivedSnapshot=!1,r.context={},this.sendUnsubscribe(r).catch(()=>{})),r.isAnnounced||r.hasCallbacks()||(delete this._contextNameToData[t],delete this._contextNameToId[t],r.contextId&&delete this._contextIdToName[r.contextId])}}async destroy(e){const t=distExports.Traces.currentTracingState;t.addData("INFO",{context:e}),e in this._creationPromises&&(await this._creationPromises[e],distExports.Traces.currentTracingState=t);const r=this._contextNameToData[e],n=r?.contextId;return r&&n?this._gw3Session.send({type:GW_MESSAGE_DESTROY_CONTEXT,domain:"global",context_id:r.contextId}).then(()=>{}):Promise.reject(`context with ${e} does not exist`)}handleUpdated(e,t,r){const n=e.context;e.context=applyContextDelta(e.context,t,this._logger),this._contextNameToData[e.name]!==e||deepEqual(n,e.context)||this.invokeUpdateCallbacks(e,t,r)}subscribeToContextCreatedMessages(){const e=[GW_MESSAGE_CONTEXT_ADDED,GW_MESSAGE_CONTEXT_CREATED,GW_MESSAGE_ACTIVITY_CREATED];for(const t of e){const e=this._connection.on(t,this.handleContextCreatedMessage.bind(this));this._gw3Subscriptions.push(e)}}handleContextCreatedMessage(e){const t=e.type;t===GW_MESSAGE_ACTIVITY_CREATED?(this._contextNameToId[e.activity_id]=e.context_id,this._contextIdToName[e.context_id]=e.activity_id):t===GW_MESSAGE_CONTEXT_ADDED&&(this._contextNameToId[e.name]=e.context_id,this._contextIdToName[e.context_id]=e.name);const r=this._contextIdToName[e.context_id];if(!r)throw new Error("Received created event for context with unknown name: "+e.context_id);if(!this._contextNameToId[r])throw new Error("Received created event for context with unknown id: "+e.context_id);let n=this._contextNameToData[r];if(n){if(n.isAnnounced)return;if(!n.hasCallbacks())throw new Error("Assertion failure: contextData.hasCallbacks()");n.isAnnounced=!0,n.contextId=e.context_id,n.activityId=e.activity_id,n.sentExplicitSubscription||this.sendSubscribe(n).catch(()=>{})}else this._contextNameToData[r]=new GW3ContextData(e.context_id,r,!0,e.activity_id),this._trackAllContexts&&this.subscribe(r,()=>{}).then(e=>this._systemContextsSubKey=e)}subscribeToContextUpdatedMessages(){const e=[GW_MESSAGE_CONTEXT_UPDATED,GW_MESSAGE_SUBSCRIBED_CONTEXT,GW_MESSAGE_JOINED_ACTIVITY];for(const t of e){const e=this._connection.on(t,this.handleContextUpdatedMessage.bind(this));this._gw3Subscriptions.push(e)}}handleContextUpdatedMessage(e){const t=e.type,r=e.context_id;let n=this._contextNameToData[this._contextIdToName[r]];const i=!n||!n.isAnnounced;if(t===GW_MESSAGE_JOINED_ACTIVITY)n||(n=this._contextNameToData[e.activity_id]||new GW3ContextData(r,e.activity_id,!0,e.activity_id)),this._contextNameToData[e.activity_id]=n,this._contextIdToName[r]=e.activity_id,this._contextNameToId[e.activity_id]=r,n.contextId=r,n.isAnnounced=!0,n.activityId=e.activity_id,n.joinedActivity=!0;else if(!n||!n.isAnnounced)return void(t===GW_MESSAGE_SUBSCRIBED_CONTEXT?(n=n||new GW3ContextData(r,e.name,!0,void 0),n.sentExplicitSubscription=!0,this._contextNameToData[e.name]=n,this._contextIdToName[r]=e.name,this._contextNameToId[e.name]=r):this._logger.error(`Received 'update' for unknown context: ${r}`));const o=n.context;if(n.hasReceivedSnapshot=!0,t===GW_MESSAGE_SUBSCRIBED_CONTEXT)n.context=e.data??{};else if(t===GW_MESSAGE_JOINED_ACTIVITY)n.context=e.context_snapshot??{};else{if(t!==GW_MESSAGE_CONTEXT_UPDATED)throw new Error("Unrecognized context update message "+t);n.context=applyContextDelta(n.context,e.delta,this._logger)}!i&&deepEqual(n.context,o)&&t!==GW_MESSAGE_SUBSCRIBED_CONTEXT||this.invokeUpdateCallbacks(n,e.delta??e.data,{updaterId:e.updater_id})}invokeUpdateCallbacks(e,t,r){if((t=t||{added:{},updated:{},reset:{},removed:[]}).commands){t.added=t.updated=t.reset={},t.removed=[];for(const e of t.commands)"remove"===e.type?(-1===e.path.indexOf(".")&&t.removed.push(e.path),setValueToPath(t.updated,null,e.path)):"set"===e.type&&setValueToPath(t.updated,e.value,e.path)}for(const n in e.updateCallbacks)if(e.updateCallbacks.hasOwnProperty(n))try{const i=e.updateCallbacks[n],o=deepClone({...t.added,...t.updated,...t.reset});i(deepClone(e.context),o,t.removed,parseInt(n,10),r,distExports.Traces.extractPropagationInfo(t))}catch(e){this._logger.debug("callback error: "+JSON.stringify(e))}}subscribeToContextDestroyedMessages(){const e=[GW_MESSAGE_CONTEXT_DESTROYED,GW_MESSAGE_ACTIVITY_DESTROYED];for(const t of e){const e=this._connection.on(t,this.handleContextDestroyedMessage.bind(this));this._gw3Subscriptions.push(e)}}handleContextDestroyedMessage(e){let t,r;if(e.type===GW_MESSAGE_ACTIVITY_DESTROYED){if(r=e.activity_id,t=this._contextNameToId[r],!t)return void this._logger.error(`Received 'destroyed' for unknown activity: ${e.activity_id}`)}else if(t=e.context_id,r=this._contextIdToName[t],!r)return void this._logger.error(`Received 'destroyed' for unknown context: ${e.context_id}`);delete this._contextIdToName[t],delete this._contextNameToId[r];const n=this._contextNameToData[r];delete this._contextNameToData[r],n&&n.isAnnounced||this._logger.error(`Received 'destroyed' for unknown context: ${t}`)}async sendSubscribe(e){e.sentExplicitSubscription=!0;try{return void await this._gw3Session.send({type:GW_MESSAGE_SUBSCRIBE_CONTEXT,domain:"global",context_id:e.contextId})}catch(t){throw e.sentExplicitSubscription=!1,t}}async sendUnsubscribe(e){const t=e.sentExplicitSubscription;e.sentExplicitSubscription=!1;try{return void await this._gw3Session.send({type:GW_MESSAGE_UNSUBSCRIBE_CONTEXT,domain:"global",context_id:e.contextId})}catch(r){throw e.sentExplicitSubscription=t,r}}calculateContextDeltaV1(e,t){const r={added:{},updated:{},removed:[],reset:void 0};if(e)for(const n of Object.keys(e))-1===Object.keys(t).indexOf(n)||null===t[n]||deepEqual(e[n],t[n])||(r.updated[n]=t[n]);for(const n of Object.keys(t))e&&-1!==Object.keys(e).indexOf(n)?null===t[n]&&r.removed.push(n):null!==t[n]&&(r.added[n]=t[n]);return r}calculateContextDeltaV2(e,t){const r={added:{},updated:{},removed:[],reset:void 0,commands:[]};for(const n of Object.keys(t))if(null!==t[n]){deepEqual(e?e[n]:null,t[n])||r.commands?.push({type:"set",path:n,value:t[n]})}else r.commands?.push({type:"remove",path:n});return r}resetState(){for(const e of this._gw3Subscriptions)this._connection.off(e);this._systemContextsSubKey&&(this.unsubscribe(this._systemContextsSubKey,!0),delete this._systemContextsSubKey),this._gw3Subscriptions=[],this._contextNameToId={},this._contextIdToName={},delete this._protocolVersion,this._contextsTempCache=Object.keys(this._contextNameToData).reduce((e,t)=>{const r=this._contextNameToData[t];return(!this._onlyReAnnounceSubscribedContexts||r.hasReceivedSnapshot)&&(e[t]=this._contextNameToData[t].context),e},{}),this._contextNameToData={}}async reInitiateState(){this.subscribeToContextCreatedMessages(),this.subscribeToContextUpdatedMessages(),this.subscribeToContextDestroyedMessages(),this._connection.replayer?.drain(ContextMessageReplaySpec.name,e=>{const t=e.type;t&&(t===GW_MESSAGE_CONTEXT_CREATED||t===GW_MESSAGE_CONTEXT_ADDED||t===GW_MESSAGE_ACTIVITY_CREATED?this.handleContextCreatedMessage(e):t===GW_MESSAGE_SUBSCRIBED_CONTEXT||t===GW_MESSAGE_CONTEXT_UPDATED||t===GW_MESSAGE_JOINED_ACTIVITY?this.handleContextUpdatedMessage(e):t!==GW_MESSAGE_CONTEXT_DESTROYED&&t!==GW_MESSAGE_ACTIVITY_DESTROYED||this.handleContextDestroyedMessage(e))}),await Promise.all(this._contextsSubscriptionsCache.map(e=>this.subscribe(e.contextName,e.callback,e.subKey))),await this.flushQueue();for(const e in this._contextsTempCache){if("object"!=typeof this._contextsTempCache[e]||0===Object.keys(this._contextsTempCache[e]).length)continue;const t=this._contextsTempCache[e];this._logger.info(`Re-announcing known context: ${e}`),await this.flushQueue(),await this.update(e,t)}this._contextsTempCache={},this._logger.info("Contexts are re-announced")}flushQueue(){return new Promise(e=>setTimeout(()=>e(),0))}}__decorate([distExports.withSpan("interopio.api.contexts.bridge.create",{argMapping:["context"]})],GW3Bridge.prototype,"createContext",null),__decorate([distExports.withSpan("interopio.api.contexts.bridge.update",{argMapping:["context"]})],GW3Bridge.prototype,"update",null),__decorate([distExports.withSpan("interopio.api.contexts.bridge.set",{argMapping:["context"]})],GW3Bridge.prototype,"set",null),__decorate([distExports.withSpan("interopio.api.contexts.bridge.setPaths",{argMapping:["context"]})],GW3Bridge.prototype,"setPaths",null),__decorate([distExports.withSpan("interopio.api.contexts.bridge.get",{argMapping:["context"]})],GW3Bridge.prototype,"get",null),__decorate([distExports.withSpan("interopio.api.contexts.bridge.subscribe",{argMapping:["context"]})],GW3Bridge.prototype,"subscribe",null),__decorate([distExports.withSpan("interopio.api.contexts.bridge.destroy",{argMapping:["context"]})],GW3Bridge.prototype,"destroy",null);class ContextsModule{initTime;initStartTime;initEndTime;_bridge;constructor(e){this._bridge=new GW3Bridge(e)}all(){return this._bridge.all()}update(e,t){return this.checkName(e),this.checkData(t),this._bridge.update(e,t)}set(e,t){return this.checkName(e),this.checkData(t),this._bridge.set(e,t)}setPath(e,t,r){this.checkName(e),this.checkPath(t);return""===t?(this.checkData(r),this.set(e,r)):this._bridge.setPath(e,t,r)}setPaths(e,t){if(this.checkName(e),!Array.isArray(t))throw new Error("Please provide the paths as an array of PathValues!");for(const{path:e,value:r}of t){this.checkPath(e);""===e&&this.checkData(r)}return this._bridge.setPaths(e,t)}subscribe(e,t){if(this.checkName(e),"function"!=typeof t)throw new Error("Please provide the callback as a function!");return this._bridge.subscribe(e,(e,r,n,i,o)=>t(e,r,n,()=>this._bridge.unsubscribe(i),o)).then(e=>()=>{this._bridge.unsubscribe(e)})}get(e){return this.checkName(e),this._bridge.get(e)}ready(){return Promise.resolve(this)}destroy(e){return this.checkName(e),this._bridge.destroy(e)}get setPathSupported(){return this._bridge.setPathSupported}checkName(e){if("string"!=typeof e||""===e)throw new Error("Please provide the name as a non-empty string!")}checkPath(e){if("string"!=typeof e)throw new Error("Please provide the path as a dot delimited string!")}checkData(e){if("object"!=typeof e)throw new Error("Please provide the data as an object!")}}function promisify(e,t,r){return"function"!=typeof t&&"function"!=typeof r?e:("function"!=typeof t?t=()=>{}:"function"!=typeof r&&(r=()=>{}),e.then(t,r))}function rejectAfter(e=0,t,r){let n;const i=()=>{n&&clearTimeout(n)};return t.then(()=>{i()}).catch(()=>{i()}),new Promise((t,i)=>{n=setTimeout(()=>i(r),e)})}__decorate([distExports.withSpan("interopio.api.contexts.module.update",{argMapping:["context"]})],ContextsModule.prototype,"update",null),__decorate([distExports.withSpan("interopio.api.contexts.module.set",{argMapping:["context"]})],ContextsModule.prototype,"set",null),__decorate([distExports.withSpan("interopio.api.contexts.module.setPaths",{argMapping:["context"]})],ContextsModule.prototype,"setPaths",null),__decorate([distExports.withSpan("interopio.api.contexts.module.subscribe",{argMapping:["context"]})],ContextsModule.prototype,"subscribe",null),__decorate([distExports.withSpan("interopio.api.contexts.module.destroy",{argMapping:["context"]})],ContextsModule.prototype,"destroy",null);var ok=function(e){return{ok:!0,result:e}},err=function(e){return{ok:!1,error:e}},asPromise=function(e){return!0===e.ok?Promise.resolve(e.result):Promise.reject(e.error)},withDefault=function(e,t){return!0===t.ok?t.result:e},withException=function(e){if(!0===e.ok)return e.result;throw e.error},map=function(e,t){return!0===t.ok?ok(e(t.result)):t},map2=function(e,t,r){return!1===t.ok?t:!1===r.ok?r:ok(e(t.result,r.result))},mapError=function(e,t){return!0===t.ok?t:err(e(t.error))},andThen=function(e,t){return!0===t.ok?e(t.result):t},__assign=function(){return __assign=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var i in t=arguments[r])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},__assign.apply(this,arguments)};function __rest(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(n=Object.getOwnPropertySymbols(e);i<n.length;i++)t.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(r[n[i]]=e[n[i]])}return r}function isEqual(e,t){if(e===t)return!0;if(null===e&&null===t)return!0;if(typeof e!=typeof t)return!1;if("object"==typeof e){if(Array.isArray(e)){if(!Array.isArray(t))return!1;if(e.length!==t.length)return!1;for(var r=0;r<e.length;r++)if(!isEqual(e[r],t[r]))return!1;return!0}var n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(r=0;r<n.length;r++){if(!t.hasOwnProperty(n[r]))return!1;if(!isEqual(e[n[r]],t[n[r]]))return!1}return!0}}var isJsonArray=function(e){return Array.isArray(e)},isJsonObject=function(e){return"object"==typeof e&&null!==e&&!isJsonArray(e)},typeString=function(e){switch(typeof e){case"string":return"a string";case"number":return"a number";case"boolean":return"a boolean";case"undefined":return"undefined";case"object":return e instanceof Array?"an array":null===e?"null":"an object";default:return JSON.stringify(e)}},expectedGot=function(e,t){return"expected "+e+", got "+typeString(t)},printPath=function(e){return e.map(function(e){return"string"==typeof e?"."+e:"["+e+"]"}).join("")},prependAt=function(e,t){var r=t.at,n=__rest(t,["at"]);return __assign({at:e+(r||"")},n)},Decoder=function(){function e(t){var r=this;this.decode=t,this.run=function(e){return mapError(function(t){return{kind:"DecoderError",input:e,at:"input"+(t.at||""),message:t.message||""}},r.decode(e))},this.runPromise=function(e){return asPromise(r.run(e))},this.runWithException=function(e){return withException(r.run(e))},this.map=function(t){return new e(function(e){return map(t,r.decode(e))})},this.andThen=function(t){return new e(function(e){return andThen(function(r){return t(r).decode(e)},r.decode(e))})},this.where=function(t,n){return r.andThen(function(r){return t(r)?e.succeed(r):e.fail(n)})}}return e.string=function(){return new e(function(e){return"string"==typeof e?ok(e):err({message:expectedGot("a string",e)})})},e.number=function(){return new e(function(e){return"number"==typeof e?ok(e):err({message:expectedGot("a number",e)})})},e.boolean=function(){return new e(function(e){return"boolean"==typeof e?ok(e):err({message:expectedGot("a boolean",e)})})},e.constant=function(t){return new e(function(e){return isEqual(e,t)?ok(t):err({message:"expected "+JSON.stringify(t)+", got "+JSON.stringify(e)})})},e.object=function(t){return new e(function(e){if(isJsonObject(e)&&t){var r={};for(var n in t)if(t.hasOwnProperty(n)){var i=t[n].decode(e[n]);if(!0!==i.ok)return void 0===e[n]?err({message:"the key '"+n+"' is required but was not present"}):err(prependAt("."+n,i.error));void 0!==i.result&&(r[n]=i.result)}return ok(r)}return isJsonObject(e)?ok(e):err({message:expectedGot("an object",e)})})},e.array=function(t){return new e(function(e){if(isJsonArray(e)&&t){return e.reduce(function(e,r,n){return map2(function(e,t){return e.concat([t])},e,function(e,r){return mapError(function(e){return prependAt("["+r+"]",e)},t.decode(e))}(r,n))},ok([]))}return isJsonArray(e)?ok(e):err({message:expectedGot("an array",e)})})},e.tuple=function(t){return new e(function(e){if(isJsonArray(e)){if(e.length!==t.length)return err({message:"expected a tuple of length "+t.length+", got one of length "+e.length});for(var r=[],n=0;n<t.length;n++){var i=t[n].decode(e[n]);if(!i.ok)return err(prependAt("["+n+"]",i.error));r[n]=i.result}return ok(r)}return err({message:expectedGot("a tuple of length "+t.length,e)})})},e.union=function(t,r){for(var n=[],i=2;i<arguments.length;i++)n[i-2]=arguments[i];return e.oneOf.apply(e,[t,r].concat(n))},e.intersection=function(t,r){for(var n=[],i=2;i<arguments.length;i++)n[i-2]=arguments[i];return new e(function(e){return[t,r].concat(n).reduce(function(t,r){return map2(Object.assign,t,r.decode(e))},ok({}))})},e.anyJson=function(){return new e(function(e){return ok(e)})},e.unknownJson=function(){return new e(function(e){return ok(e)})},e.dict=function(t){return new e(function(e){if(isJsonObject(e)){var r={};for(var n in e)if(e.hasOwnProperty(n)){var i=t.decode(e[n]);if(!0!==i.ok)return err(prependAt("."+n,i.error));r[n]=i.result}return ok(r)}return err({message:expectedGot("an object",e)})})},e.optional=function(t){return new e(function(e){return null==e?ok(void 0):t.decode(e)})},e.oneOf=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return new e(function(e){for(var r=[],n=0;n<t.length;n++){var i=t[n].decode(e);if(!0===i.ok)return i;r[n]=i.error}var o=r.map(function(e){return"at error"+(e.at||"")+": "+e.message}).join('", "');return err({message:'expected a value matching one of the decoders, got the errors ["'+o+'"]'})})},e.withDefault=function(t,r){return new e(function(e){return ok(withDefault(t,r.decode(e)))})},e.valueAt=function(t,r){return new e(function(e){for(var n=e,i=0;i<t.length;i++){if(void 0===n)return err({at:printPath(t.slice(0,i+1)),message:"path does not exist"});if("string"==typeof t[i]&&!isJsonObject(n))return err({at:printPath(t.slice(0,i+1)),message:expectedGot("an object",n)});if("number"==typeof t[i]&&!isJsonArray(n))return err({at:printPath(t.slice(0,i+1)),message:expectedGot("an array",n)});n=n[t[i]]}return mapError(function(e){return void 0===n?{at:printPath(t),message:"path does not exist"}:prependAt(printPath(t),e)},r.decode(n))})},e.succeed=function(t){return new e(function(e){return ok(t)})},e.fail=function(t){return new e(function(e){return err({message:t})})},e.lazy=function(t){return new e(function(e){return t().decode(e)})},e}(),string$2=Decoder.string,number$2=Decoder.number,boolean$2=Decoder.boolean,anyJson=Decoder.anyJson;Decoder.unknownJson;var constant=Decoder.constant,object=Decoder.object,array$1=Decoder.array;Decoder.tuple,Decoder.dict;var optional$1=Decoder.optional;Decoder.oneOf;var union$1=Decoder.union;Decoder.intersection,Decoder.withDefault,Decoder.valueAt,Decoder.succeed;var fail$1=Decoder.fail;Decoder.lazy;const functionCheck=(e,t)=>{const r=typeof e;return"function"===r?anyJson():fail$1(`The provided argument as ${t} should be of type function, provided: ${r}`)},nonEmptyStringDecoder=string$2().where(e=>e.length>0,"Expected a non-empty string"),nonNegativeNumberDecoder=number$2().where(e=>e>=0,"Expected a non-negative number or 0"),methodDefinitionDecoder=object({name:nonEmptyStringDecoder,objectTypes:optional$1(array$1(nonEmptyStringDecoder)),displayName:optional$1(string$2()),accepts:optional$1(string$2()),returns:optional$1(string$2()),description:optional$1(string$2()),version:optional$1(nonNegativeNumberDecoder),supportsStreaming:optional$1(boolean$2()),flags:optional$1(object()),getServers:optional$1(anyJson().andThen(e=>functionCheck(e,"method definition getServers")))}),methodFilterDecoder=union$1(nonEmptyStringDecoder,methodDefinitionDecoder),instanceDecoder=object({application:optional$1(nonEmptyStringDecoder),applicationName:optional$1(nonEmptyStringDecoder),pid:optional$1(nonNegativeNumberDecoder),machine:optional$1(nonEmptyStringDecoder),user:optional$1(nonEmptyStringDecoder),environment:optional$1(nonEmptyStringDecoder),region:optional$1(nonEmptyStringDecoder),service:optional$1(nonEmptyStringDecoder),instance:optional$1(nonEmptyStringDecoder),windowId:optional$1(nonEmptyStringDecoder),peerId:optional$1(nonEmptyStringDecoder),isLocal:optional$1(boolean$2()),api:optional$1(nonEmptyStringDecoder),getMethods:optional$1(anyJson().andThen(e=>functionCheck(e,"instance getMethods"))),getStreams:optional$1(anyJson().andThen(e=>functionCheck(e,"instance getStreams")))}),targetDecoder=union$1(constant("best"),constant("all"),constant("skipMine"),instanceDecoder,array$1(instanceDecoder)),invokeOptionsDecoder=object({waitTimeoutMs:optional$1(nonNegativeNumberDecoder),methodResponseTimeoutMs:optional$1(nonNegativeNumberDecoder)});var InvokeStatus;!function(e){e[e.Success=0]="Success",e[e.Error=1]="Error"}(InvokeStatus||(InvokeStatus={}));class Client{protocol;repo;instance;configuration;constructor(e,t,r,n){this.protocol=e,this.repo=t,this.instance=r,this.configuration=n}subscribe(e,t,r,n,i){const o=distExports.Traces.currentTracingState;o.addData("INFO",{stream:Utils.getMethodName(e)}),o.addData("INFO",{options:t});const s=(e,r,n,o)=>{t.methodResponseTimeout=t.methodResponseTimeout??t.waitTimeoutMs,this.protocol.client.subscribe(r,t,e,n,o,i)},a=new Promise((r,n)=>{const i=e=>{r(e)},o=e=>{n(e)};if(!e)return void n("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");let a;if(a="string"==typeof e?{name:e}:e,!a.name)return void n("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");void 0===t&&(t={});let c=t.target;if(void 0===c&&(c="best"),"string"==typeof c&&"all"!==c&&"best"!==c)return void n(new Error(`"${c}" is not a valid target. Valid targets are "all", "best", or an instance.`));void 0===t.methodResponseTimeout&&(t.methodResponseTimeout=t.method_response_timeout,void 0===t.methodResponseTimeout&&(t.methodResponseTimeout=this.configuration.methodResponseTimeout)),void 0===t.waitTimeoutMs&&(t.waitTimeoutMs=t.wait_for_method_timeout,void 0===t.waitTimeoutMs&&(t.waitTimeoutMs=this.configuration.waitTimeoutMs));let l=0,u=this.getServerMethodsByFilterAndTarget(a,c);if(u.length>0)s(u,u[0].methods[0],i,o);else{const r=()=>{if(c&&t.waitTimeoutMs)if(l+=500,u=this.getServerMethodsByFilterAndTarget(a,c),u.length>0){const e=u[0].methods[0];s(u,e,i,o)}else if(l>=t.waitTimeoutMs){s(u,"string"==typeof e?{name:e}:e,i,o)}else setTimeout(r,500)};setTimeout(r,500)}});return promisify(a,r,n)}servers(e){const t=void 0===e?void 0:{...e};return this.getServers(t).map(e=>e.server.instance)}methods(e){return e="string"==typeof e?{name:e}:{...e},this.getMethods(e)}methodsForInstance(e){return this.getMethodsForInstance(e)}methodAdded(e){return this.repo.onMethodAdded(e)}methodRemoved(e){return this.repo.onMethodRemoved(e)}serverAdded(e){return this.repo.onServerAdded(e)}serverRemoved(e){return this.repo.onServerRemoved((t,r)=>{e(t,r)})}serverMethodAdded(e){return this.repo.onServerMethodAdded((t,r)=>{e({server:t,method:r})})}serverMethodRemoved(e){return this.repo.onServerMethodRemoved((t,r)=>{e({server:t,method:r})})}async invoke(e,t,r,n,i,o){const s=distExports.Traces.currentTracingState;s.addData("INFO",{method:Utils.getMethodName(e)}),s.addData("INFO",{target:r,additionalOptions:n}),s.addData("DIAGNOSTIC",{arguments:t});return promisify((async()=>{const s="string"==typeof e?{name:e}:{...e};t||(t={}),r||(r="best"),n||(n={});const a=methodFilterDecoder.run(s);if(!a.ok){const e=`The provided 'method' argument is invalid. Error: ${JSON.stringify(a.error)}.`;return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}if("object"!=typeof t){const e="The provided 'argumentObj' argument is invalid. Error: The argumentObj should be an instance of an object";return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}const c=targetDecoder.run(r);if(!c.ok){const e=`The provided 'target' argument is invalid. Error: ${JSON.stringify(c.error)}.`;return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}const l=invokeOptionsDecoder.run(n);if(!l.ok){const e=`The provided 'options' argument is invalid. Error: ${JSON.stringify(l.error)}.`;return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}if(i&&"function"!=typeof i){const e="The provided 'success' function is invalid. Error: The success should be a valid function";return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}if(o&&"function"!=typeof o){const e="The provided 'error' function is invalid. Error: The error should be a valid function";return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}void 0===n.methodResponseTimeoutMs&&(n.methodResponseTimeoutMs=n.method_response_timeout,void 0===n.methodResponseTimeoutMs&&(n.methodResponseTimeoutMs=this.configuration.methodResponseTimeout)),void 0===n.waitTimeoutMs&&(n.waitTimeoutMs=n.wait_for_method_timeout,void 0===n.waitTimeoutMs&&(n.waitTimeoutMs=this.configuration.waitTimeoutMs));let u=this.getServerMethodsByFilterAndTarget(s,r);if(0===u.length)try{u=await this.tryToAwaitForMethods(s,r,n)}catch(n){const i=`Can not find a method matching ${JSON.stringify(e)} with server filter ${JSON.stringify(r)}`;return Promise.reject(this.generateInvalidInputInvocationResult(i,s,t))}const d=n.methodResponseTimeoutMs??3e4,h=n,p=u.map(e=>this.getServerInvokePromise(e.methods[0],e.server,t,h,d)),g=await Promise.all(p),m=this.getInvocationResultObj(g,s,t);return g.every(e=>e.status===InvokeStatus.Error)?Promise.reject(m):m})(),i,o)}async getServerInvokePromise(e,t,r,n,i){const o=nanoid$1(10),s=distExports.Traces.currentTracingState;r&&(r=deepClone(r),s.injectPropagationInfo(r)),s.addData("INFO",{server:t?.id,instance:t?.instance}),s.addData("INFO",{invocationId:o});const a=this.protocol.client.invoke(o,e,r,t,n),c=await Promise.race([a,rejectAfter(i,a,{invocationId:o,message:`Invocation timeout (${i} ms) reached for method name: ${e?.name}, target instance: ${JSON.stringify(t.instance)}, options: ${JSON.stringify(n)}`,status:InvokeStatus.Error})]);return s.addData("DIAGNOSTIC",{returnValue:c}),c}generateInvalidInputInvocationResult(e,t,r){const n={...t,getServers:()=>[],supportsStreaming:!1,objectTypes:t.objectTypes??[],flags:t.flags?.metadata??{}},i={invocationId:nanoid$1(10),status:InvokeStatus.Error,message:e};return this.getInvocationResultObj([i],n,r)}getInvocationResultObj(e,t,r){distExports.Traces.removePropagationInfo(r);const n=e.filter(e=>e.status===InvokeStatus.Success).reduce((e,n)=>e=[...e,{executed_by:n.instance,returned:n.result,called_with:r,method:t,message:n.message,status:n.status}],[]),i=e.filter(e=>e.status===InvokeStatus.Error).reduce((e,n)=>e=[...e,{executed_by:n.instance,called_with:r,name:t.name,message:n.message}],[]),o=e[0];return{method:t,called_with:r,returned:o.result,executed_by:o.instance,all_return_values:n,all_errors:i,message:o.message,status:o.status}}tryToAwaitForMethods(e,t,r){return new Promise((n,i)=>{if(0===r.waitTimeoutMs)return void i();let o=0;const s=setInterval(()=>{o+=500;const a=this.getServerMethodsByFilterAndTarget(e,t);if(a.length>0)clearInterval(s),n(a);else if(o>=(r.waitTimeoutMs||1e4))return clearInterval(s),void i()},500)})}filterByTarget(e,t){if("string"!=typeof e){let r;r=Array.isArray(e)?e:[e];return r.reduce((e,r)=>{const n=t.filter(e=>this.instanceMatch(r,e.server.instance));return e.concat(n)},[])}if("all"===e)return[...t];if("best"===e){const e=t.find(e=>e.server.instance.isLocal);if(e)return[e];if(void 0!==t[0])return[t[0]]}else if("skipMine"===e)return t.filter(({server:e})=>e.instance.peerId!==this.instance.peerId);return[]}instanceMatch(e,t){return e?.peerId&&e?.instance&&delete(e={...e}).peerId,this.containsProps(e,t)}methodMatch(e,t){return this.containsProps(e,t)}containsProps(e,t){return Object.keys(e).filter(t=>void 0!==e[t]&&null!==e[t]&&"function"!=typeof e[t]&&"object_types"!==t&&"display_name"!==t&&"id"!==t&&"gatewayId"!==t&&"identifier"!==t&&"_"!==t[0]).every(r=>{let n;const i=e[r],o=t[r];switch(r){case"objectTypes":n=(i||[]).every(e=>(o||[]).includes(e));break;case"flags":n=isSubset(o||{},i||{});break;default:n=String(i).toLowerCase()===String(o).toLowerCase()}return n})}getMethods(e){if(void 0===e)return this.repo.getMethods();return this.repo.getMethods().filter(t=>this.methodMatch(e,t))}getMethodsForInstance(e){const t=this.repo.getServers().filter(t=>this.instanceMatch(e,t.instance));if(0===t.length)return[];let r={};return 1===t.length?r=t[0].methods:t.forEach(e=>{Object.keys(e.methods).forEach(t=>{const n=e.methods[t];r[n.identifier]=n})}),Object.keys(r).map(e=>r[e])}getServers(e){const t=this.repo.getServers();return void 0===e?t.map(e=>({server:e,methods:[]})):t.reduce((t,r)=>{const n=Object.values(r.methods).filter(t=>this.methodMatch(e,t));return n.length>0&&t.push({server:r,methods:n}),t},[])}getServerMethodsByFilterAndTarget(e,t){const r=this.getServers(e);return this.filterByTarget(t,r)}}__decorate([distExports.withSpan("interopio.api.interop.stream.subscribe",{argMapping:e=>({stream:Utils.getMethodName(e)})})],Client.prototype,"subscribe",null),__decorate([distExports.withSpan("interopio.api.interop.invoke",{argMapping:e=>({method:Utils.getMethodName(e)})})],Client.prototype,"invoke",null),__decorate([distExports.withSpan("interopio.api.interop.invoke.server",{argMapping:{"0.name":"method"}})],Client.prototype,"getServerInvokePromise",null);class ServerSubscription{protocol;repoMethod;subscription;constructor(e,t,r){this.protocol=e,this.repoMethod=t,this.subscription=r}get stream(){if(!this.repoMethod.stream)throw new Error("no stream");return this.repoMethod.stream}get arguments(){return this.subscription.arguments||{}}get branchKey(){return this.subscription.branchKey}get instance(){if(!this.subscription.instance)throw new Error("no instance");return this.subscription.instance}close(){this.protocol.server.closeSingleSubscription(this.repoMethod,this.subscription)}push(e){this.protocol.server.pushDataToSingle(this.repoMethod,this.subscription,e)}}let Request$1=class{protocol;repoMethod;requestContext;arguments;instance;constructor(e,t,r){this.protocol=e,this.repoMethod=t,this.requestContext=r,this.arguments=r.arguments,this.instance=r.instance}accept(){this.protocol.server.acceptRequestOnBranch(this.requestContext,this.repoMethod,"")}acceptOnBranch(e){this.protocol.server.acceptRequestOnBranch(this.requestContext,this.repoMethod,e)}reject(e){this.protocol.server.rejectRequest(this.requestContext,this.repoMethod,e)}},ServerStreaming$1=class{protocol;server;constructor(e,t){this.protocol=e,this.server=t,e.server.onSubRequest((e,t)=>this.handleSubRequest(e,t)),e.server.onSubAdded((e,t)=>this.handleSubAdded(e,t)),e.server.onSubRemoved((e,t)=>this.handleSubRemoved(e,t))}handleSubRequest(e,t){if(!t||!t.streamCallbacks||"function"!=typeof t.streamCallbacks.subscriptionRequestHandler)return;const r=new Request$1(this.protocol,t,e);t.streamCallbacks.subscriptionRequestHandler(r)}handleSubAdded(e,t){if(!t||!t.streamCallbacks||"function"!=typeof t.streamCallbacks.subscriptionAddedHandler)return;const r=new ServerSubscription(this.protocol,t,e);t.streamCallbacks.subscriptionAddedHandler(r)}handleSubRemoved(e,t){if(!t||!t.streamCallbacks||"function"!=typeof t.streamCallbacks.subscriptionRemovedHandler)return;const r=new ServerSubscription(this.protocol,t,e);t.streamCallbacks.subscriptionRemovedHandler(r)}};class ServerBranch{key;protocol;repoMethod;constructor(e,t,r){this.key=e,this.protocol=t,this.repoMethod=r}subscriptions(){return this.protocol.server.getSubscriptionList(this.repoMethod,this.key).map(e=>new ServerSubscription(this.protocol,this.repoMethod,e))}close(){this.protocol.server.closeAllSubscriptions(this.repoMethod,this.key)}push(e){this.protocol.server.pushData(this.repoMethod,e,[this.key])}}class ServerStream{_protocol;_repoMethod;_server;name;constructor(e,t,r){this._protocol=e,this._repoMethod=t,this._server=r,this.name=this._repoMethod.definition.name}branches(e){const t=this._protocol.server.getBranchList(this._repoMethod);return e?t.indexOf(e)>-1?new ServerBranch(e,this._protocol,this._repoMethod):void 0:t.map(e=>new ServerBranch(e,this._protocol,this._repoMethod))}branch(e){return this.branches(e)}subscriptions(){return this._protocol.server.getSubscriptionList(this._repoMethod).map(e=>new ServerSubscription(this._protocol,this._repoMethod,e))}get definition(){const e=this._repoMethod.definition;return{accepts:e.accepts,description:e.description,displayName:e.displayName,name:e.name,objectTypes:e.objectTypes,returns:e.returns,supportsStreaming:e.supportsStreaming,flags:e.flags?.metadata}}async close(){return this._protocol.server.closeAllSubscriptions(this._repoMethod),this._server.unregister(this._repoMethod.definition,!0)}push(e,t){if("string"!=typeof t&&!Array.isArray(t)&&void 0!==t)throw new Error("invalid branches should be string or string array");if("object"!=typeof e)throw new Error("Invalid arguments. Data must be an object.");const r=distExports.Traces.currentTracingState;r.addData("INFO",{stream:this?.name,branches:t}),r.addData("DIAGNOSTIC",{data:e}),e=deepClone(e),r.injectPropagationInfo(e),this._protocol.server.pushData(this._repoMethod,e,t)}updateRepoMethod(e){this._repoMethod=e}}__decorate([distExports.withSpan("interopio.api.interop.stream.close",{thisMapping:{name:"stream"}})],ServerStream.prototype,"close",null),__decorate([distExports.withSpan("interopio.api.interop.stream.push",{thisMapping:{name:"stream"}})],ServerStream.prototype,"push",null);class Server{protocol;serverRepository;streaming;invocations=0;currentlyUnregistering={};constructor(e,t){this.protocol=e,this.serverRepository=t,this.streaming=new ServerStreaming$1(e,this),this.protocol.server.onInvoked(this.onMethodInvoked.bind(this))}createStream(e,t,r,n,i){const o=new Promise((r,n)=>{if(!e)return void n("The stream name must be unique! Please, provide either a unique string for a stream name to “glue.interop.createStream()” or a “methodDefinition” object with a unique “name” property for the stream.");let o;if(o="string"==typeof e?{name:""+e}:{...e},!o.name)return n(`The “name” property is required for the “streamDefinition” object and must be unique. Stream definition: ${JSON.stringify(o)}`);if(this.serverRepository.getList().some(e=>e.definition.name===o.name))return n(`A stream with the name "${o.name}" already exists! Please, provide a unique name for the stream.`);o.supportsStreaming=!0,t||(t={}),"function"!=typeof t.subscriptionRequestHandler&&(t.subscriptionRequestHandler=e=>{e.accept()});const s=this.serverRepository.add({definition:o,streamCallbacks:t,protocolState:{}});this.protocol.server.createStream(s).then(()=>{let e;i?(e=i,i.updateRepoMethod(s)):e=new ServerStream(this.protocol,s,this),s.stream=e,r(e)}).catch(e=>{s.repoId&&this.serverRepository.remove(s.repoId),n(e)})});return promisify(o,r,n)}register(e,t){if(!e)return Promise.reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");if(distExports.Traces.currentTracingState.addData("INFO",{method:Utils.getMethodName(e)}),"function"!=typeof t)return Promise.reject(`The second parameter must be a callback function. Method: ${Utils.getMethodName(e)}`);const r=async(e,r)=>{try{const n=t(e.args,e.instance);if(n&&"function"==typeof n.then){const e=distExports.Traces.currentTracingState,t=await n;distExports.Traces.currentTracingState=e,r(void 0,t)}else r(void 0,n)}catch(e){r(e??"",e??"")}};return r.userCallback=t,this.registerCore(e,r)}registerAsync(e,t){if(!e)return Promise.reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");if(distExports.Traces.currentTracingState.addData("INFO",{method:Utils.getMethodName(e)}),"function"!=typeof t)return Promise.reject(`The second parameter must be a callback function. Method: ${Utils.getMethodName(e)}`);const r=async(e,r)=>{try{let n=!1;const i=e=>{n||r(void 0,e),n=!0},o=e=>{n||(e||(e=""),r(e,e)),n=!0},s=t(e.args,e.instance,i,o);s&&"function"==typeof s.then&&s.then(i).catch(o)}catch(e){r(e,void 0)}};return r.userCallbackAsync=t,this.registerCore(e,r)}async unregister(e,t=!1){if(void 0===e)return Promise.reject("Please, provide either a unique string for a name or an object containing a “name” property.");if(distExports.Traces.currentTracingState.addData("INFO",{method:Utils.getMethodName(e)}),"function"==typeof e)return void await this.unregisterWithPredicate(e,t);let r;if(r="string"==typeof e?{name:e}:e,void 0===r.name)return Promise.reject("Method name is required. Cannot find a method if the method name is undefined!");const n=this.serverRepository.getList().find(e=>e.definition.name===r.name&&(e.definition.supportsStreaming||!1)===t);if(!n)return Promise.reject(`Method with a name "${r.name}" does not exist or is not registered by your application!`);await this.removeMethodsOrStreams([n])}async unregisterWithPredicate(e,t){const r=this.serverRepository.getList().filter(t=>e(t.definition)).filter(e=>(e.definition.supportsStreaming||!1)===t);if(!r||0===r.length)return Promise.reject(`Could not find a ${t?"stream":"method"} matching the specified condition!`);await this.removeMethodsOrStreams(r)}removeMethodsOrStreams(e){const t=[];return e.forEach(e=>{const r=this.protocol.server.unregister(e).then(()=>{e.repoId&&this.serverRepository.remove(e.repoId)});t.push(r),this.addAsCurrentlyUnregistering(e.definition.name,r)}),Promise.all(t)}async addAsCurrentlyUnregistering(e,t){const r=new Promise(e=>setTimeout(e,5e3));this.currentlyUnregistering[e]=Promise.race([t,r]).then(()=>{delete this.currentlyUnregistering[e]})}async registerCore(e,t){let r;if(r="string"==typeof e?{name:""+e}:{...e},!r.name)return Promise.reject(`Please, provide a (unique) string value for the “name” property in the “methodDefinition” object: ${JSON.stringify(e)}`);await this.currentlyUnregistering[r.name];if(this.serverRepository.getList().some(e=>e.definition.name===r.name))return Promise.reject(`A method with the name "${r.name}" already exists! Please, provide a unique name for the method.`);if(r.supportsStreaming)return Promise.reject(`When you create methods with “glue.interop.register()” or “glue.interop.registerAsync()” the property “supportsStreaming” cannot be “true”. If you want “${r.name}” to be a stream, please use the “glue.interop.createStream()” method.`);const n=this.serverRepository.add({definition:r,theFunction:t,protocolState:{}});return this.protocol.server.register(n).catch(e=>{throw n?.repoId&&this.serverRepository.remove(n.repoId),e})}onMethodInvoked(e,t,r){const n=distExports.Traces.extractPropagationInfo(r.args,!0);distExports.withSpan("interopio.api.interop.register.callback",{method:e?.definition?.name},n,n=>{if(n.addData("INFO",{method:e?.definition?.name}),n.addData("INFO",{invocationId:t}),n.addData("INFO",{invoker:r?.instance}),n.addData("DIAGNOSTIC",{arguments:r?.args}),!e||!e.theFunction)return void(n.status={code:distExports.SpanStatusCode.ERROR,message:"Required argument 'methodToExecute' is missing."});let i;const o=new Promise(e=>{i=e});return e.theFunction(r,(r,o)=>{if(null!=r){if(r.message&&"string"==typeof r.message)r=r.message;else if("string"!=typeof r)try{r=JSON.stringify(r)}catch(e){r=`un-stringifyable error in onMethodInvoked! Top level prop names: ${Object.keys(r)}`}n.status={code:distExports.SpanStatusCode.ERROR,message:r},n.recordException(r)}o?("object"!=typeof o||Array.isArray(o))&&(o={_value:o}):o={},n.addData("DIAGNOSTIC",{returnValue:o}),this.protocol.server.methodInvocationResult(e,t,r,o),i()}),o})}}__decorate([distExports.withSpan("interopio.api.interop.stream.create",{argMapping:e=>({stream:Utils.getMethodName(e)})})],Server.prototype,"createStream",null),__decorate([distExports.withSpan("interopio.api.interop.register",{argMapping:e=>({method:Utils.getMethodName(e)})})],Server.prototype,"register",null),__decorate([distExports.withSpan("interopio.api.interop.register.async",{argMapping:e=>({method:Utils.getMethodName(e)})})],Server.prototype,"registerAsync",null),__decorate([distExports.withSpan("interopio.api.interop.unregister",{argMapping:e=>({method:Utils.getMethodName(e)})})],Server.prototype,"unregister",null);class InstanceWrapper{wrapped={};constructor(e,t,r){this.wrapped.getMethods=function(){return e.methodsForInstance(this)},this.wrapped.getStreams=function(){return e.methodsForInstance(this).filter(e=>e.supportsStreaming)},t&&this.refreshWrappedObject(t),r&&(r.loggedIn(()=>{this.refresh(r)}),this.refresh(r))}unwrap(){return this.wrapped}refresh(e){if(!e)return;const t=e?.resolvedIdentity,r=Object.assign({},t??{},{peerId:e?.peerId});this.refreshWrappedObject(r)}refreshWrappedObject(e){Object.keys(e).forEach(t=>{this.wrapped[t]=e[t]}),this.wrapped.user=e.user,this.wrapped.instance=e.instance,this.wrapped.application=e.application??nanoid$1(10),this.wrapped.applicationName=e.applicationName,this.wrapped.pid=e.pid??e.process??Math.floor(1e10*Math.random()),this.wrapped.machine=e.machine,this.wrapped.environment=e.environment,this.wrapped.region=e.region,this.wrapped.windowId=e.windowId,this.wrapped.isLocal=e.isLocal??!0,this.wrapped.api=e.api,this.wrapped.service=e.service,this.wrapped.peerId=e.peerId}}const hideMethodSystemFlags=e=>({...e,flags:e.flags.metadata||{}});class ClientRepository{logger;API;servers={};myServer;methodsCount={};callbacks=CallbackRegistryFactory();constructor(e,t){this.logger=e,this.API=t;const r=this.API.instance.peerId;this.myServer={id:r,methods:{},instance:this.API.instance,wrapper:this.API.unwrappedInstance},this.servers[r]=this.myServer}addServer(e,t){this.logger.debug(`adding server ${t}`);const r=this.servers[t];if(r)return r.id;const n=new InstanceWrapper(this.API,e),i={id:t,methods:{},instance:n.unwrap(),wrapper:n};return this.servers[t]=i,this.callbacks.execute("onServerAdded",i.instance),t}removeServerById(e,t){const r=this.servers[e];r?(this.logger.debug(`removing server ${e}`),Object.keys(r.methods).forEach(t=>{this.removeServerMethod(e,t)}),delete this.servers[e],this.callbacks.execute("onServerRemoved",r.instance,t)):this.logger.warn(`not aware of server ${e}, my state ${JSON.stringify(Object.keys(this.servers))}`)}addServerMethod(e,t){const r=this.servers[e];if(!r)throw new Error("server does not exists");if(r.methods[t.id])return;const n=this.createMethodIdentifier(t),i={identifier:n,gatewayId:t.id,name:t.name,displayName:t.display_name,description:t.description,version:t.version,objectTypes:t.object_types||[],accepts:t.input_signature,returns:t.result_signature,supportsStreaming:void 0!==t.flags&&t.flags.streaming,flags:t.flags??{},getServers:()=>this.getServersByMethod(n)};i.object_types=i.objectTypes,i.display_name=i.displayName,r.methods[t.id]=i;const o=hideMethodSystemFlags(i);return this.methodsCount[n]||(this.methodsCount[n]=0,this.callbacks.execute("onMethodAdded",o)),this.methodsCount[n]=this.methodsCount[n]+1,this.callbacks.execute("onServerMethodAdded",r.instance,o),i}removeServerMethod(e,t){const r=this.servers[e];if(!r)throw new Error("server does not exists");const n=r.methods[t];delete r.methods[t];const i=hideMethodSystemFlags(n);this.methodsCount[n.identifier]=this.methodsCount[n.identifier]-1,0===this.methodsCount[n.identifier]&&this.callbacks.execute("onMethodRemoved",i),this.callbacks.execute("onServerMethodRemoved",r.instance,i)}getMethods(){return this.extractMethodsFromServers(Object.values(this.servers)).map(hideMethodSystemFlags)}getServers(){return Object.values(this.servers).map(this.hideServerMethodSystemFlags)}onServerAdded(e){const t=this.callbacks.add("onServerAdded",e),r=this.getServers().map(e=>e.instance);return this.returnUnsubWithDelayedReplay(t,r,e)}onMethodAdded(e){const t=this.callbacks.add("onMethodAdded",e),r=this.getMethods();return this.returnUnsubWithDelayedReplay(t,r,e)}onServerMethodAdded(e){const t=this.callbacks.add("onServerMethodAdded",e);let r=!1;const n=this.getServers();return setTimeout(()=>{n.forEach(t=>{const n=t.methods;Object.keys(n).forEach(i=>{r||e(t.instance,n[i])})})},0),()=>{r=!0,t()}}onMethodRemoved(e){return this.callbacks.add("onMethodRemoved",e)}onServerRemoved(e){return this.callbacks.add("onServerRemoved",e)}onServerMethodRemoved(e){return this.callbacks.add("onServerMethodRemoved",e)}getServerById(e){if(this.servers[e])return this.hideServerMethodSystemFlags(this.servers[e])}reset(){Object.keys(this.servers).forEach(e=>{this.removeServerById(e,"reset")}),this.servers={[this.myServer.id]:this.myServer},this.methodsCount={}}createMethodIdentifier(e){const t=e.input_signature??"",r=e.result_signature??"";return(e.name+t+r).toLowerCase()}getServersByMethod(e){const t=[];return Object.values(this.servers).forEach(r=>{Object.values(r.methods).forEach(n=>{n.identifier===e&&t.push(r.instance)})}),t}returnUnsubWithDelayedReplay(e,t,r){let n=!1;return setTimeout(()=>{t.forEach(e=>{n||r(e)})},0),()=>{n=!0,e()}}hideServerMethodSystemFlags(e){const t={};return Object.entries(e.methods).forEach(([e,r])=>{t[e]=hideMethodSystemFlags(r)}),{...e,methods:t}}extractMethodsFromServers(e){return Object.values(e).reduce((e,t)=>[...e,...Object.values(t.methods)],[])}}class ServerRepository{nextId=0;methods=[];add(e){return e.repoId=String(this.nextId),this.nextId+=1,this.methods.push(e),e}remove(e){if("string"!=typeof e)return new TypeError("Expecting a string");this.methods=this.methods.filter(t=>t.repoId!==e)}getById(e){if("string"==typeof e)return this.methods.find(t=>t.repoId===e)}getList(){return this.methods.map(e=>e)}length(){return this.methods.length}reset(){this.methods=[]}}const SUBSCRIPTION_REQUEST="onSubscriptionRequest",SUBSCRIPTION_ADDED="onSubscriptionAdded",SUBSCRIPTION_REMOVED="onSubscriptionRemoved";class ServerStreaming{session;repository;serverRepository;logger;ERR_URI_SUBSCRIPTION_FAILED="com.tick42.agm.errors.subscription.failure";callbacks=CallbackRegistryFactory();nextStreamId=0;constructor(e,t,r,n){this.session=e,this.repository=t,this.serverRepository=r,this.logger=n,e.on("add-interest",e=>{this.handleAddInterest(e)}),e.on("remove-interest",e=>{this.handleRemoveInterest(e)})}acceptRequestOnBranch(e,t,r){if("string"!=typeof r&&(r=""),"object"!=typeof t.protocolState.subscriptionsMap)throw new TypeError("The streaming method is missing its subscriptions.");if(!Array.isArray(t.protocolState.branchKeyToStreamIdMap))throw new TypeError("The streaming method is missing its branches.");const n=this.getStreamId(t,r),i=e.msg.subscription_id,o={id:i,arguments:e.arguments,instance:e.instance,branchKey:r,streamId:n,subscribeMsg:e.msg};t.protocolState.subscriptionsMap[i]=o,this.session.sendFireAndForget({type:"accepted",subscription_id:i,stream_id:n}).catch(e=>{this.logger.warn(`Failed to send accepted message for subscription ${i}: ${JSON.stringify(e)}`)}),this.callbacks.execute(SUBSCRIPTION_ADDED,o,t)}rejectRequest(e,t,r){"string"!=typeof r&&(r=""),this.sendSubscriptionFailed("Subscription rejected by user. "+r,e.msg.subscription_id)}pushData(e,t,r){if("object"!=typeof e||!Array.isArray(e.protocolState.branchKeyToStreamIdMap))return;if("object"!=typeof t)throw new Error("Invalid arguments. Data must be an object.");"string"==typeof r?r=[r]:(!Array.isArray(r)||r.length<=0)&&(r=[]);const n=e.protocolState.branchKeyToStreamIdMap.filter(e=>!r||0===r.length||r.indexOf(e.key)>=0).map(e=>e.streamId);n.forEach(e=>{const r={type:"publish",stream_id:e,data:t};this.session.sendFireAndForget(r).catch(t=>{this.logger.warn(`Failed to send publish message for stream ${e}: ${JSON.stringify(t)}`)})})}pushDataToSingle(e,t,r){if("object"!=typeof r)throw new Error("Invalid arguments. Data must be an object.");const n={type:"post",subscription_id:t.id,data:r};this.session.sendFireAndForget(n).catch(e=>{this.logger.warn(`Failed to send post message for subscription ${t.id}: ${JSON.stringify(e)}`)})}closeSingleSubscription(e,t){e.protocolState.subscriptionsMap&&delete e.protocolState.subscriptionsMap[t.id];const r={type:"drop-subscription",subscription_id:t.id,reason:"Server dropping a single subscription"};this.session.sendFireAndForget(r).catch(e=>{this.logger.warn(`Failed to send drop-subscription message for subscription ${t.id}: ${JSON.stringify(e)}`)}),this.callbacks.execute(SUBSCRIPTION_REMOVED,t,e)}closeMultipleSubscriptions(e,t){if("object"!=typeof e||"object"!=typeof e.protocolState.subscriptionsMap)return;if(!e.protocolState.subscriptionsMap)return;const r=e.protocolState.subscriptionsMap;let n=Object.keys(r).map(e=>r[e]);"string"==typeof t&&(n=n.filter(e=>e.branchKey===t)),n.forEach(e=>{delete r[e.id];const t={type:"drop-subscription",subscription_id:e.id,reason:"Server dropping all subscriptions on stream_id: "+e.streamId};this.session.sendFireAndForget(t).catch(t=>{this.logger.warn(`Failed to send drop-subscription message for subscription ${e.id}: ${JSON.stringify(t)}`)})})}getSubscriptionList(e,t){if("object"!=typeof e)return[];let r=[];if(!e.protocolState.subscriptionsMap)return[];const n=e.protocolState.subscriptionsMap,i=Object.keys(n).map(e=>n[e]);return r="string"!=typeof t?i:i.filter(e=>e.branchKey===t),r}getBranchList(e){if("object"!=typeof e)return[];if(!e.protocolState.subscriptionsMap)return[];const t=e.protocolState.subscriptionsMap,r=Object.keys(t).map(e=>t[e]),n=[];return r.forEach(e=>{let t="";"object"==typeof e&&"string"==typeof e.branchKey&&(t=e.branchKey),-1===n.indexOf(t)&&n.push(t)}),n}onSubAdded(e){this.onSubscriptionLifetimeEvent(SUBSCRIPTION_ADDED,e)}onSubRequest(e){this.onSubscriptionLifetimeEvent(SUBSCRIPTION_REQUEST,e)}onSubRemoved(e){this.onSubscriptionLifetimeEvent(SUBSCRIPTION_REMOVED,e)}handleRemoveInterest(e){const t=this.serverRepository.getById(e.method_id);if("string"!=typeof e.subscription_id||"object"!=typeof t)return;if(!t.protocolState.subscriptionsMap)return;if("object"!=typeof t.protocolState.subscriptionsMap[e.subscription_id])return;const r=t.protocolState.subscriptionsMap[e.subscription_id];delete t.protocolState.subscriptionsMap[e.subscription_id],this.callbacks.execute(SUBSCRIPTION_REMOVED,r,t)}onSubscriptionLifetimeEvent(e,t){this.callbacks.add(e,t)}getNextStreamId(){return this.nextStreamId+++""}handleAddInterest(e){const t=this.repository.getServerById(e.caller_id),r=t?.instance??{},n={msg:e,arguments:e.arguments_kv||{},instance:r},i=this.serverRepository.getById(e.method_id);if(void 0===i){const t="No method with id "+e.method_id+" on this server.";return void this.sendSubscriptionFailed(t,e.subscription_id)}i.protocolState.subscriptionsMap&&i.protocolState.subscriptionsMap[e.subscription_id]?this.sendSubscriptionFailed("A subscription with id "+e.subscription_id+" already exists.",e.subscription_id):this.callbacks.execute(SUBSCRIPTION_REQUEST,n,i)}sendSubscriptionFailed(e,t){const r={type:"error",reason_uri:this.ERR_URI_SUBSCRIPTION_FAILED,reason:e,request_id:t};this.session.sendFireAndForget(r).catch(e=>{this.logger.warn(`Failed to send subscription failed message for subscription ${t}: ${JSON.stringify(e)}`)})}getStreamId(e,t){if("string"!=typeof t&&(t=""),!e.protocolState.branchKeyToStreamIdMap)throw new Error(`streaming ${e.definition.name} method without protocol state`);const r=e.protocolState.branchKeyToStreamIdMap.filter(e=>e.key===t)[0];let n=r?r.streamId:void 0;return"string"==typeof n&&""!==n||(n=this.getNextStreamId(),e.protocolState.branchKeyToStreamIdMap.push({key:t,streamId:n})),n}}class ServerProtocol{session;clientRepository;serverRepository;logger;callbacks=CallbackRegistryFactory();streaming;constructor(e,t,r,n){this.session=e,this.clientRepository=t,this.serverRepository=r,this.logger=n,this.streaming=new ServerStreaming(e,t,r,n.subLogger("streaming")),this.session.on("invoke",e=>this.handleInvokeMessage(e))}createStream(e){return e.protocolState.subscriptionsMap={},e.protocolState.branchKeyToStreamIdMap=[],this.register(e,!0)}register(e,t){const r=e.definition,n=Object.assign({},{metadata:r.flags??{}},{streaming:t||!1}),i={type:"register",methods:[{id:e.repoId,name:r.name,display_name:r.displayName,description:r.description,version:r.version,flags:n,object_types:r.objectTypes||r.object_types,input_signature:r.accepts,result_signature:r.returns,restrictions:void 0}]};return this.session.send(i,{methodId:e.repoId}).then(()=>{this.logger.debug("registered method "+e.definition.name+" with id "+e.repoId)}).catch(t=>{throw this.logger.warn(`failed to register method ${e.definition.name} with id ${e.repoId} - ${JSON.stringify(t)}`),t})}onInvoked(e){this.callbacks.add("onInvoked",e)}methodInvocationResult(e,t,r,n){let i;i=r||""===r?{type:"error",request_id:t,reason_uri:"agm.errors.client_error",reason:r,context:n,peer_id:void 0}:{type:"yield",invocation_id:t,peer_id:this.session.peerId,result:n,request_id:void 0},this.session.sendFireAndForget(i).catch(r=>{this.logger.warn(`Failed to send method invocation result for method ${e.definition.name} invocation ${t} - ${JSON.stringify(r)}`)})}async unregister(e){const t={type:"unregister",methods:[e.repoId]};await this.session.send(t)}getBranchList(e){return this.streaming.getBranchList(e)}getSubscriptionList(e,t){return this.streaming.getSubscriptionList(e,t)}closeAllSubscriptions(e,t){this.streaming.closeMultipleSubscriptions(e,t)}pushData(e,t,r){this.streaming.pushData(e,t,r)}pushDataToSingle(e,t,r){this.streaming.pushDataToSingle(e,t,r)}closeSingleSubscription(e,t){this.streaming.closeSingleSubscription(e,t)}acceptRequestOnBranch(e,t,r){this.streaming.acceptRequestOnBranch(e,t,r)}rejectRequest(e,t,r){this.streaming.rejectRequest(e,t,r)}onSubRequest(e){this.streaming.onSubRequest(e)}onSubAdded(e){this.streaming.onSubAdded(e)}onSubRemoved(e){this.streaming.onSubRemoved(e)}handleInvokeMessage(e){const t=e.invocation_id,r=e.caller_id,n=e.method_id,i=e.arguments_kv,o=this.serverRepository.getList().filter(e=>e.repoId===n)[0];if(void 0===o)return;const s=this.clientRepository.getServerById(r)?.instance,a={args:i,instance:s};this.callbacks.execute("onInvoked",o,t,a)}}class UserSubscription{repository;subscriptionData;get requestArguments(){return this.subscriptionData.params.arguments||{}}get servers(){return this.subscriptionData.trackedServers.reduce((e,t)=>{if(t.subscriptionId){const r=this.repository.getServerById(t.serverId)?.instance;r&&e.push(r)}return e},[])}get serverInstance(){return this.servers[0]}get stream(){return this.subscriptionData.method}constructor(e,t){this.repository=e,this.subscriptionData=t}onData(e){if("function"!=typeof e)throw new TypeError("The data callback must be a function.");this.subscriptionData.handlers.onData.push(e),1===this.subscriptionData.handlers.onData.length&&this.subscriptionData.queued.data.length>0&&this.subscriptionData.queued.data.forEach(t=>{e(t)})}onClosed(e){if("function"!=typeof e)throw new TypeError("The callback must be a function.");this.subscriptionData.handlers.onClosed.push(e)}onFailed(e){}onConnected(e){if("function"!=typeof e)throw new TypeError("The callback must be a function.");this.subscriptionData.handlers.onConnected.push(e)}close(){this.subscriptionData.close()}setNewSubscription(e){this.subscriptionData=e}}class TimedCache{config;cache=[];timeoutIds=[];constructor(e){this.config=e}add(e){const t=nanoid$1(10);this.cache.push({id:t,element:e});const r=setTimeout(()=>{const e=this.cache.findIndex(e=>e.id===t);e<0||this.cache.splice(e,1)},this.config.ELEMENT_TTL_MS);this.timeoutIds.push(r)}flush(){const e=this.cache.map(e=>e.element);return this.timeoutIds.forEach(e=>clearInterval(e)),this.cache=[],this.timeoutIds=[],e}}const STATUS_AWAITING_ACCEPT="awaitingAccept",STATUS_SUBSCRIBED="subscribed",ERR_MSG_SUB_FAILED="Subscription failed.",ERR_MSG_SUB_REJECTED="Subscription rejected.",ON_CLOSE_MSG_SERVER_INIT="ServerInitiated",ON_CLOSE_MSG_CLIENT_INIT="ClientInitiated";class ClientStreaming{session;repository;logger;subscriptionsList={};timedCache=new TimedCache({ELEMENT_TTL_MS:1e4});subscriptionIdToLocalKeyMap={};nextSubLocalKey=0;constructor(e,t,r){this.session=e,this.repository=t,this.logger=r,e.on("subscribed",this.handleSubscribed),e.on("event",this.handleEventData),e.on("subscription-cancelled",this.handleSubscriptionCancelled)}subscribe(e,t,r,n,i,o){if(distExports.Traces.removePropagationInfo(t.arguments),0===r.length)return void i({method:e,called_with:t.arguments,message:ERR_MSG_SUB_FAILED+" No available servers matched the target params."});const s=this.getNextSubscriptionLocalKey(),a=this.registerSubscription(s,e,t,n,i,t.methodResponseTimeout||1e4,o);"object"==typeof a?r.forEach(r=>{const n=r.server.id,i=r.methods.find(t=>t.name===e.name);if(!i)return void this.logger.error(`can not find method ${e.name} for target ${r.server.id}`);a.trackedServers.push({serverId:n,subscriptionId:void 0});const o={type:"subscribe",server_id:n,method_id:i.gatewayId,arguments_kv:t.arguments};this.session.send(o,{serverId:n,subLocalKey:s}).then(e=>this.handleSubscribed(e)).catch(e=>this.handleErrorSubscribing(e))}):i({method:e,called_with:t.arguments,message:ERR_MSG_SUB_FAILED+" Unable to register the user callbacks."})}drainSubscriptions(){const e=Object.values(this.subscriptionsList);return this.subscriptionsList={},this.subscriptionIdToLocalKeyMap={},e}drainSubscriptionsCache(){return this.timedCache.flush()}getNextSubscriptionLocalKey(){const e=this.nextSubLocalKey;return this.nextSubLocalKey+=1,e}registerSubscription(e,t,r,n,i,o,s){const a={localKey:e,status:STATUS_AWAITING_ACCEPT,method:t,params:r,success:n,error:i,trackedServers:[],handlers:{onData:s?.handlers.onData||[],onClosed:s?.handlers.onClosed||[],onConnected:s?.handlers.onConnected||[]},queued:{data:[],closers:[]},timeoutId:void 0,close:()=>this.closeSubscription(e),subscription:s?.subscription};return s||(r.onData&&a.handlers.onData.push(r.onData),r.onClosed&&a.handlers.onClosed.push(r.onClosed),r.onConnected&&a.handlers.onConnected.push(r.onConnected)),this.subscriptionsList[e]=a,a.timeoutId=setTimeout(()=>{if(void 0===this.subscriptionsList[e])return;const n=this.subscriptionsList[e];n.status===STATUS_AWAITING_ACCEPT?(i({method:t,called_with:r.arguments,message:ERR_MSG_SUB_FAILED+" Subscription attempt timed out after "+o+" ms."}),delete this.subscriptionsList[e]):n.status===STATUS_SUBSCRIBED&&n.trackedServers.length>0&&(n.trackedServers=n.trackedServers.filter(e=>void 0!==e.subscriptionId),delete n.timeoutId,n.trackedServers.length<=0&&(this.callOnClosedHandlers(n),delete this.subscriptionsList[e]))},o),a}handleErrorSubscribing=e=>{const t=e._tag,r=t.subLocalKey,n=this.subscriptionsList[r];if("object"==typeof n&&(n.trackedServers=n.trackedServers.filter(e=>e.serverId!==t.serverId),n.trackedServers.length<=0)){if(clearTimeout(n.timeoutId),n.status===STATUS_AWAITING_ACCEPT){const t="string"==typeof e.reason&&""!==e.reason?' Publisher said "'+e.reason+'".':" No reason given.",r="object"==typeof n.params.arguments?JSON.stringify(n.params.arguments):"{}";n.error({message:ERR_MSG_SUB_REJECTED+t+" Called with:"+r,called_with:distExports.Traces.removePropagationInfo(n.params.arguments),method:n.method})}else n.status===STATUS_SUBSCRIBED&&this.callOnClosedHandlers(n);delete this.subscriptionsList[r]}};handleSubscribed=e=>{const t=e._tag.subLocalKey,r=this.subscriptionsList[t];if("object"!=typeof r)return;const n=e._tag.serverId,i=r.trackedServers.filter(e=>e.serverId===n)[0];if("object"!=typeof i)return;i.subscriptionId=e.subscription_id,this.subscriptionIdToLocalKeyMap[e.subscription_id]=t;const o=r.status===STATUS_AWAITING_ACCEPT;if(r.status=STATUS_SUBSCRIBED,o){let e=!1,t=r.subscription;t?(t.setNewSubscription(r),r.success(t),e=!0):(t=new UserSubscription(this.repository,r),r.subscription=t,r.success(t));for(const n of r.handlers.onConnected)try{n(t.serverInstance,e)}catch(e){}}};handleEventData=e=>{const t=this.subscriptionIdToLocalKeyMap[e.subscription_id];if(void 0===t)return;const r=this.subscriptionsList[t];if("object"!=typeof r)return;const n=r.trackedServers.filter(t=>t.subscriptionId===e.subscription_id);if(1!==n.length)return;const i=e.oob,o=n[0].serverId,s=this.repository.getServerById(o),a=r.handlers.onData,c=r.queued.data,l={data:e.data,server:s?.instance??{},requestArguments:r.params.arguments,message:void 0,private:i},u=distExports.Traces.extractPropagationInfo(l.data,!0),d=r?.method?.name;distExports.withSpan("interopio.api.interop.stream.onData",{method:d,stream:d},u,()=>{const e=distExports.Traces.currentTracingState;e.addData("INFO",{method:d}),e.addData("INFO",{stream:d}),e.addData("INFO",{handlerCount:a?.length}),e.addData("DIAGNOSTIC",{data:l}),a.length>0?a.forEach(e=>{"function"==typeof e&&e(deepClone(l))}):c.push(deepClone(l))})};handleSubscriptionCancelled=e=>{const t=this.subscriptionIdToLocalKeyMap[e.subscription_id];if(void 0===t)return;const r=this.subscriptionsList[t];if("object"!=typeof r)return;const n=r.trackedServers.length-1;r.trackedServers=r.trackedServers.filter(t=>t.subscriptionId!==e.subscription_id||(r.queued.closers.push(t.serverId),!1)),r.trackedServers.length===n&&(r.trackedServers.length<=0&&(this.timedCache.add(r),clearTimeout(r.timeoutId),this.callOnClosedHandlers(r),delete this.subscriptionsList[t]),delete this.subscriptionIdToLocalKeyMap[e.subscription_id])};callOnClosedHandlers(e,t){const r=e.queued.closers.length,n=r>0?e.queued.closers[r-1]:null;let i;void 0!==n&&"string"==typeof n&&(i=this.repository.getServerById(n)?.instance??{}),e.handlers.onClosed.forEach(r=>{"function"==typeof r&&r({message:t||ON_CLOSE_MSG_SERVER_INIT,requestArguments:e.params.arguments||{},server:i,stream:e.method})})}closeSubscription(e){const t=this.subscriptionsList[e];"object"==typeof t&&(t.trackedServers.forEach(e=>{void 0!==e.subscriptionId&&(t.queued.closers.push(e.serverId),this.session.sendFireAndForget({type:"unsubscribe",subscription_id:e.subscriptionId,reason_uri:"",reason:ON_CLOSE_MSG_CLIENT_INIT}).catch(t=>{this.logger.warn(`Error sending unsubscribe for subscription id ${e.subscriptionId}: ${JSON.stringify(t)}`)}),delete this.subscriptionIdToLocalKeyMap[e.subscriptionId])}),t.trackedServers=[],this.callOnClosedHandlers(t,ON_CLOSE_MSG_CLIENT_INIT),delete this.subscriptionsList[e])}}class ClientProtocol{session;repository;logger;streaming;constructor(e,t,r){this.session=e,this.repository=t,this.logger=r,e.on("peer-added",e=>this.handlePeerAdded(e)),e.on("peer-removed",e=>this.handlePeerRemoved(e)),e.on("methods-added",e=>this.handleMethodsAddedMessage(e)),e.on("methods-removed",e=>this.handleMethodsRemovedMessage(e)),this.streaming=new ClientStreaming(e,t,r)}subscribe(e,t,r,n,i,o){this.streaming.subscribe(e,t,r,n,i,o)}invoke(e,t,r,n){const i=n.id,o={type:"call",server_id:i,method_id:t.gatewayId,arguments_kv:r};return this.session.send(o,{invocationId:e,serverId:i}).then(e=>this.handleResultMessage(e)).catch(e=>this.handleInvocationError(e))}drainSubscriptions(){return this.streaming.drainSubscriptions()}drainSubscriptionsCache(){return this.streaming.drainSubscriptionsCache()}handlePeerAdded(e){const t=e.new_peer_id,r=e.identity,n=!e.meta||e.meta.local,i=Number(r.process),o={...r,pid:isNaN(i)?r.process:i,peerId:t,isLocal:n};this.repository.addServer(o,t)}handlePeerRemoved(e){const t=e.removed_id,r=e.reason;this.repository.removeServerById(t,r)}handleMethodsAddedMessage(e){const t=e.server_id;e.methods.forEach(e=>{this.repository.addServerMethod(t,e)})}handleMethodsRemovedMessage(e){const t=e.server_id,r=e.methods,n=this.repository.getServerById(t);if(n){Object.keys(n.methods).forEach(e=>{const i=n.methods[e];r.indexOf(i.gatewayId)>-1&&this.repository.removeServerMethod(t,e)})}}handleResultMessage(e){const t=e._tag.invocationId,r=e.result,n=e._tag.serverId,i=this.repository.getServerById(n);return{invocationId:t,result:r,instance:i?.instance,status:InvokeStatus.Success,message:""}}handleInvocationError(e){if(this.logger.debug(`handle invocation error ${JSON.stringify(e)}`),"_tag"in e){const t=e._tag.invocationId,r=e._tag.serverId,n=this.repository.getServerById(r),i=e.reason;return{invocationId:t,result:e.context,instance:n?.instance,status:InvokeStatus.Error,message:i}}return{invocationId:"",message:e.message,status:InvokeStatus.Error,error:e}}}function gW3ProtocolFactory(e,t,r,n,i,o){const s=i.logger.subLogger("gw3-protocol");let a;const c=new Promise(e=>{a=e}),l=t.domain("agm",["subscribed"]),u=new ServerProtocol(l,r,n,s.subLogger("server")),d=new ClientProtocol(l,r,s.subLogger("client"));return l.onJoined(i=>{r.addServer(e,t.peerId),i?async function(){s.info("reconnected - will replay registered methods and subscriptions"),d.drainSubscriptionsCache().forEach(e=>{const t=e.method,r=Object.assign({},e.params);s.info(`trying to soft-re-subscribe to method ${t.name}, with params: ${JSON.stringify(r)}`),o.client.subscribe(t,r,void 0,void 0,e).then(()=>s.info(`soft-subscribing to method ${t.name} DONE`)).catch(e=>s.warn(`subscribing to method ${t.name} failed: ${JSON.stringify(e)}}`))});const e=[],t=d.drainSubscriptions();for(const r of t){const t=r.method,n=Object.assign({},r.params);s.info(`trying to re-subscribe to method ${t.name}, with params: ${JSON.stringify(n)}`),e.push(o.client.subscribe(t,n,void 0,void 0,r).then(()=>s.info(`subscribing to method ${t.name} DONE`)))}const r=n.getList();n.reset();for(const t of r){const r=t.definition;t.stream?e.push(o.server.createStream(r,t.streamCallbacks,void 0,void 0,t.stream).then(()=>s.info(`subscribing to method ${r.name} DONE`)).catch(()=>s.warn(`subscribing to method ${r.name} FAILED`))):t?.theFunction?.userCallback?e.push(o.register(r,t.theFunction.userCallback).then(()=>s.info(`registering method ${r.name} DONE`)).catch(()=>s.warn(`registering method ${r.name} FAILED`))):t?.theFunction?.userCallbackAsync&&e.push(o.registerAsync(r,t.theFunction.userCallbackAsync).then(()=>s.info(`registering method ${r.name} DONE`)).catch(()=>s.warn(`registering method ${r.name} FAILED`)))}await Promise.all(e),s.info("Interop is re-announced")}().then(()=>t.setLibReAnnounced({name:"interop"})).catch(e=>s.warn(`Error while re-announcing interop: ${JSON.stringify(e)}`)):a&&(a({client:d,server:u}),a=void 0)}),l.onLeft(()=>{r.reset()}),l.join(),c}class Interop{instance;readyPromise;client;server;unwrappedInstance;protocol;clientRepository;serverRepository;constructor(e){if(void 0===e)throw new Error("configuration is required");if(void 0===e.connection)throw new Error("configuration.connections is required");const t=e.connection;let r;if("number"!=typeof e.methodResponseTimeout&&(e.methodResponseTimeout=3e4),"number"!=typeof e.waitTimeoutMs&&(e.waitTimeoutMs=3e4),this.unwrappedInstance=new InstanceWrapper(this,void 0,t),this.instance=this.unwrappedInstance.unwrap(),this.clientRepository=new ClientRepository(e.logger.subLogger("cRep"),this),this.serverRepository=new ServerRepository,3!==t.protocolVersion)throw new Error(`protocol ${t.protocolVersion} not supported`);r=gW3ProtocolFactory(this.instance,t,this.clientRepository,this.serverRepository,e,this),this.readyPromise=r.then(t=>(this.protocol=t,this.client=new Client(this.protocol,this.clientRepository,this.instance,e),this.server=new Server(this.protocol,this.serverRepository),this))}ready(){return this.readyPromise}serverRemoved(e){return this.client.serverRemoved(e)}serverAdded(e){return this.client.serverAdded(e)}serverMethodRemoved(e){return this.client.serverMethodRemoved(e)}serverMethodAdded(e){return this.client.serverMethodAdded(e)}methodRemoved(e){return this.client.methodRemoved(e)}methodAdded(e){return this.client.methodAdded(e)}methodsForInstance(e){return this.client.methodsForInstance(e)}methods(e){return this.client.methods(e)}servers(e){return this.client.servers(e)}subscribe(e,t,r,n){return this.client.subscribe(e,t,r,n)}createStream(e,t,r,n){return this.server.createStream(e,t,r,n)}unregister(e){return this.server.unregister(e)}registerAsync(e,t){return this.server.registerAsync(e,t)}register(e,t){return this.server.register(e,t)}invoke(e,t,r,n,i,o){return this.client.invoke(e,t,r,n,i,o)}waitForMethod(e){const t=new PromiseWrapper$1,r=this.client.methodAdded(n=>{n.name===e&&(r(),t.resolve(n))});return t.promise}}const successMessages=["subscribed","success"],RECONNECT_STABILIZATION_MS=500,MAX_PENDING_PUBLISHES=1e4;class MessageBus{connection;logger;session;subscriptions;readyPromise;resubscribeInProgress;pendingPublishes=[];canDrain=!1;drainInProgress=!1;sessionGeneration=0;constructor(e,t){this.connection=e,this.logger=t,this.subscriptions=[],this.session=e.domain("bus",successMessages),this.readyPromise=this.session.join(),this.readyPromise.then(()=>{this.watchOnEvent()}),this.session.onLeft(()=>{this.canDrain=!1,this.sessionGeneration++}),this.session.onJoined(e=>{this.sessionGeneration++;const t=this.sessionGeneration,r=this.resubscribeInProgress??Promise.resolve();this.resubscribeInProgress=r.then(async()=>{try{if(e&&(await this.resubscribe(),await this.sleep(RECONNECT_STABILIZATION_MS)),this.sessionGeneration!==t)return;this.canDrain=!0,this.tryDrain()}catch(e){this.logger.error(`bus: error during onJoined chain: ${JSON.stringify(e)}`)}})})}sleep(e){return new Promise(t=>setTimeout(t,e))}ready(){return this.readyPromise}publish=(e,t,r)=>{this.publishCore(e,t,r)};publishCore(e,t,r){const{routingKey:n,target:i}=r||{},o=distExports.Traces.currentTracingState;if(o.addData("INFO",{topic:e}),o.addData("DIAGNOSTIC",{data:t}),o.addData("INFO",{routingKey:n,target:i}),t=deepClone(t),o.injectPropagationInfo(t),this.pendingPublishes.push({topic:e,data:t,options:r?deepClone(r):void 0}),this.pendingPublishes.length>MAX_PENDING_PUBLISHES){const e=this.pendingPublishes.length-MAX_PENDING_PUBLISHES;this.pendingPublishes.splice(0,e),this.logger.warn(`bus: outbox exceeded ${MAX_PENDING_PUBLISHES}, dropped ${e} oldest publish(es)`)}1!==this.pendingPublishes.length||this.canDrain?this.canDrain||this.logger.debug(`bus: queued publish to ${e} (${this.pendingPublishes.length} pending)`):this.logger.info(`bus: started buffering publishes (first topic: ${e})`),this.tryDrain()}isTransportError(e){return null!=e&&("object"!=typeof e||!e.request_id&&!e.domain)}async tryDrain(){if(!this.drainInProgress&&this.canDrain){this.drainInProgress=!0;try{let e=0;for(;this.pendingPublishes.length>0&&this.canDrain;){const t=this.pendingPublishes[0],{routingKey:r,target:n}=t.options||{},i=this.removeEmptyValues({type:"publish",topic:t.topic,data:t.data,peer_id:this.connection.peerId,routing_key:r,target_identity:n});try{await this.session.sendFireAndForget(i),this.pendingPublishes.shift(),e++}catch(e){if(this.isTransportError(e)){this.logger.info(`bus: drain paused at ${t.topic} due to transport error (${this.pendingPublishes.length} pending)`);break}this.pendingPublishes.shift(),this.logger.error(`bus: failed to publish to ${t.topic}: ${JSON.stringify(e)}`)}}e>0&&0===this.pendingPublishes.length&&this.logger.debug(`bus: drained ${e} publish(es)`)}finally{this.drainInProgress=!1}}}subscribe=(e,t,r)=>this.subscribeCore(e,t,r);subscribeCore(e,t,r){return new Promise((n,i)=>{const{routingKey:o,target:s}=r||{},a=distExports.Traces.currentTracingState;a.addData("INFO",{topic:e}),a.addData("INFO",{routingKey:o,target:s});const c=this.removeEmptyValues({type:"subscribe",topic:e,peer_id:this.connection.peerId,routing_key:o,source:s});this.session.send(c).then(r=>{const{subscription_id:i}=r;a.addData("INFO",{subscription_id:i});const c={subscription_id:i,topic:e,routingKey:o,source:s,callback:function(...r){const n=distExports.Traces.extractPropagationInfo(r?.[0],!0);distExports.withSpan("interopio.api.bus.subscribe.callback",{topic:e},n,n=>{n.addData("INFO",{topic:e,subscription_id:c.subscription_id}),n.addData("DIAGNOSTIC",{data:r?.[0]}),t.apply(this,r)})}};this.subscriptions.push(c),n({unsubscribe:()=>{const e=c.subscription_id;return this.subscriptions=this.subscriptions.filter(t=>t.subscription_id!==e),this.session.send({type:"unsubscribe",subscription_id:e,peer_id:this.connection.peerId}).catch(t=>{this.logger.warn(`Failed to send unsubscribe request for ${e}: ${JSON.stringify(t)}`)}),Promise.resolve()}})}).catch(e=>i(e))})}watchOnEvent=()=>{this.session.on("event",e=>{const{data:t,subscription_id:r}=e,n=e["publisher-identity"],i=this.subscriptions.find(e=>e.subscription_id===r);i&&(i.source?this.keysMatch(i.source,n)&&i.callback(t,i.topic,n):i.callback(t,i.topic,n))})};async resubscribe(){const e=[...this.subscriptions];this.logger.info(`bus: re-subscribing ${e.length} subscription(s) after reconnect`);for(const t of e)if(this.subscriptions.includes(t))try{const e=this.removeEmptyValues({type:"subscribe",topic:t.topic,peer_id:this.connection.peerId,routing_key:t.routingKey,source:t.source}),r=await this.session.send(e);t.subscription_id=r.subscription_id}catch(e){this.logger.error(`bus: failed to re-subscribe to topic "${t.topic}": ${JSON.stringify(e)}`)}}removeEmptyValues(e){const t={};return Object.keys(e).forEach(r=>{void 0!==e[r]&&null!==e[r]&&(t[r]=e[r])}),t}keysMatch(e,t){const r=Object.keys(e);let n=!0;return r.forEach(r=>{e[r]!==t[r]&&(n=!1)}),n}}function replaceComplexProperties(e){if(!isPrimitiveOrFunction(e))for(const t in e){if(!Object.prototype.hasOwnProperty.call(e,t))continue;const r=e[t];isPrimitiveOrFunction(r)||(isPlainObject$1$1(r)||Array.isArray(r)?replaceComplexProperties(r):e[t]=r?.constructor?.name||r.toString())}}function isPrimitiveOrFunction(e){return!e||(e!==Object(e)||"function"==typeof e)}async function loadInsightsPlugins(e,t){try{(await Promise.resolve().then(function(){return index$2})).init()}catch{e.warn("@interopio/insights-base plugin failed to load, insights will be disabled")}if(t.metrics?.enabled)try{(await Promise.resolve().then(function(){return index$1})).init()}catch{e.warn("@interopio/insights-metrics plugin failed to load, insights metrics functionality will be disabled")}if(t.traces?.enabled)try{(await Promise.resolve().then(function(){return index})).init()}catch{e.warn("@interopio/insights-traces plugin failed to load, insights traces functionality will be disabled")}}__decorate([distExports.withSpan("interopio.api.bus.publish",{argMapping:["topic"]})],MessageBus.prototype,"publishCore",null),__decorate([distExports.withSpan("interopio.api.bus.subscribe",{argMapping:["topic"]})],MessageBus.prototype,"subscribeCore",null);const IOConnectCoreFactory=(e,t)=>{const r="object"==typeof window?window.iodesktop??window.glue42gd:void 0,n="object"==typeof window?window.gdPreloadPromise??Promise.resolve():Promise.resolve(),i=new PromiseWrapper$1,o=timer("glue"),s=prepareConfig(e=e||{},t=t||{},r);let a,c,l,u,d,h,p,g;const m={};function f(e,t,r){g=l.canPublish("trace"),g&&l.trace(`registering ${e} module`);const n=n=>{if(t.initTime=r.stop(),t.initEndTime=r.endTime,t.marks=r.marks,!g)return;const i=n?`${e} failed - ${n.message}`:`${e} is ready - ${r.endTime-r.startTime}`;l.trace(i)};t.initStartTime=r.startTime,t.ready?t.ready().then(()=>{n()}).catch(e=>{const t="string"==typeof e?new Error(e):e;n(t)}):n(),Array.isArray(e)||(e=[e]),e.forEach(e=>{m[e]=t,IOConnectCoreFactory[e]=t})}function y(){const e=timer("metrics"),t=s.metrics,n=r?.getMetricsPublishingEnabled,i=s.connection.identity,o=n||(()=>!0),c=("boolean"!=typeof t&&t.disableAutoAppSystem)??!1;return u=metrics$1({connection:t?a:void 0,logger:l.subLogger("metrics"),canUpdateMetric:o,system:"Glue42",service:i?.service??r?.applicationName??s.application,instance:i?.instance??i?.windowId??nanoid$1(10),disableAutoAppSystem:c,pagePerformanceMetrics:"boolean"!=typeof t?t?.pagePerformanceMetrics:void 0}),f("metrics",u,e),Promise.resolve()}function $(){const e=timer("interop"),t={connection:a,logger:l.subLogger("interop")};return c=new Interop(t),Logger.Interop=c,f(["interop","agm"],c,e),Promise.resolve()}function b(){const e=s.activities&&3===a.protocolVersion;if(s.contexts||e){const e=timer("contexts");d=new ContextsModule({connection:a,logger:l.subLogger("contexts"),trackAllContexts:"object"==typeof s.contexts&&s.contexts.trackAllContexts,reAnnounceKnownContexts:"object"==typeof s.contexts&&s.contexts.reAnnounceKnownContexts,subscribeOnGet:"object"!=typeof s.contexts||s.contexts.subscribeOnGet,subscribeOnUpdate:"object"!=typeof s.contexts||s.contexts.subscribeOnUpdate,onlyReAnnounceSubscribedContexts:"object"!=typeof s.contexts||s.contexts.onlyReAnnounceSubscribedContexts}),f("contexts",d,e)}else{const e=a.replayer;e&&e.drain(ContextMessageReplaySpec.name)}return Promise.resolve()}async function w(){if(!s.bus)return Promise.resolve();const e=timer("bus");return h=new MessageBus(a,l.subLogger("bus")),f("bus",h,e),Promise.resolve()}function v(e){try{return e.forEach(e=>{!function(e,t){const r=timer(e),n=t(m);n&&f(e,n,r)}(e.name,e.create)}),Promise.resolve()}catch(e){return Promise.reject(e)}}return n.then(function(){const e=timer("logger");return l=new Logger(`${s.connection.identity?.application}`,void 0,s.customLogger),l.consoleLevel(s.logger.console),l.publishLevel(s.logger.publish),l.canPublish("debug")&&l.debug("initializing glue..."),f("logger",l,e),Promise.resolve(void 0)}).then(function(){const e=timer("connection");a=new Connection(s.connection,l.subLogger("connection"));let t=Promise.resolve(s.auth);return s.connection&&!s.auth&&(r?t=r.getGWToken().then(e=>({gatewayToken:e})):"undefined"!=typeof window&&window?.glue42electron?"string"==typeof window.glue42electron.gwToken&&(t=Promise.resolve({gatewayToken:window.glue42electron.gwToken})):t=Promise.reject("You need to provide auth information")),t.then(t=>{let r;if(e.mark("auth-promise-resolved"),"[object Object]"!==Object.prototype.toString.call(t))throw new Error("Invalid auth object - "+JSON.stringify(t));return r=t,a.login(r)}).then(()=>(f("connection",a,e),s)).catch(e=>{throw a&&a.logout(),e})}).then(()=>Promise.all([y(),$(),b(),w()])).then(()=>c.readyPromise).then(()=>async function(){const t="T42.ACS.RegisterInstance";if(Utils.isNode()&&"undefined"==="undefined".env._GD_STARTING_CONTEXT_&&void 0!==e?.application&&c.methods({name:t}).length>0)try{await c.invoke(t,{appName:e?.application,pid:process.pid})}catch(e){const t=e;l.error(`Cannot register as an instance: ${JSON.stringify(t.message)}`)}}()).then(()=>async function(t){const n=timer("insights"),o=await s.getInsights(r,t,l);s.insights=o;try{const e=new distExports.Builder,t=l.subLogger("insights");o.enabled&&await loadInsightsPlugins(t,o),e.withSettings(o),e.withLogger(new distExports.Log4jsWrapper(t)),e.withMetrics();const r="___insights_pi_storage___";e.withTraces().withTraceLogger(new distExports.Log4jsWrapper(t.subLogger("traces"))).withPropagationInfoStorage((e,t)=>d?.update(r,{[e.replace(/[.]/g,"_!_")]:{pi:t}}),e=>d?.get(r)?.then(t=>t[e.replace(/[.]/g,"_!_")]?.pi)??Promise.resolve(null));const s=e.build();return await s.start(),f("insights",s,n),distExports.Traces.withSpan("interopio.api.startup",()=>i.promise),p=s,Promise.resolve()}catch(e){if(n.stop(),l?.error("Error initializing insights",e),o.failOnInitError)throw e;return Promise.resolve()}finally{replaceComplexProperties(s?.insights),replaceComplexProperties(e?.insights)}}(c)).then(()=>v(s.libs||[])).then(function(){const e=Object.keys(m).map(e=>{const t=m[e];return t.ready?t.ready():Promise.resolve()});return Promise.all(e)}).then(function(){const n={coreVersion:version$2,version:s.version};o.stop();const g={feedback:e=>{c&&c.invoke("T42.ACS.Feedback",e,"best")},info:n,logger:l,interop:c,agm:c,connection:a,metrics:u,contexts:d,insights:p,bus:h,version:s.version,userConfig:e,done:()=>(l?.info("done called by user..."),a.logout())};if(g.performance={get glueVer(){return s.version},get glueConfig(){return JSON.stringify(e)},get browser(){return window.performance.timing.toJSON()},get memory(){return window.performance.memory},get initTimes(){const e=getAllTimers();return Object.keys(e).map(t=>{const r=e[t];return{name:t,duration:r.endTime-r.startTime,marks:r.marks,startTime:r.startTime,endTime:r.endTime}})}},Object.keys(m).forEach(e=>{const t=m[e];g[e]=t}),g.config={},Object.keys(s).forEach(e=>{g.config[e]=s[e]}),t&&t.extOptions&&Object.keys(t.extOptions).forEach(e=>{g.config[e]=t?.extOptions[e]}),t?.enrichGlue&&t.enrichGlue(g),r&&r.updatePerfData&&r.updatePerfData(g.performance),g.agm){const e=(e,t,r)=>function(){return g.logger.warn(`glue.js - 'glue.agm.${t}' method is deprecated, use 'glue.interop.${r}' instead.`),e.apply(g.agm,arguments)},t=g.agm;t.method_added=e(g.agm.methodAdded,"method_added","methodAdded"),t.method_removed=e(g.agm.methodRemoved,"method_removed","methodRemoved"),t.server_added=e(g.agm.serverAdded,"server_added","serverAdded"),t.server_method_aded=e(g.agm.serverMethodAdded,"server_method_aded","serverMethodAdded"),t.server_method_removed=e(g.agm.serverMethodRemoved,"server_method_removed","serverMethodRemoved")}return i.resolve(),g}).catch(e=>(i.reject({err:e}),Promise.reject({err:e,libs:m})))};"undefined"!=typeof window&&(window.IOConnectCore=IOConnectCoreFactory),IOConnectCoreFactory.version=version$2,IOConnectCoreFactory.default=IOConnectCoreFactory;const PromiseWrap=(e,t,r)=>new Promise((n,i)=>{let o=!0;const s=setTimeout(()=>{if(!o)return;o=!1;i(r||`Promise timeout hit: ${t}`)},t);e().then(e=>{o&&(o=!1,clearTimeout(s),n(e))}).catch(e=>{o&&(o=!1,clearTimeout(s),i(e))})}),PromisePlus=(e,t,r)=>new Promise((n,i)=>{const o=setTimeout(()=>{i(r||`Promise timeout hit: ${t}`)},t);new Promise(e).then(e=>{clearTimeout(o),n(e)}).catch(e=>{clearTimeout(o),i(e)})});var version$1="4.4.1";class GlueController{portsBridge;sessionStorage;_config;_systemGlue;_contextsTrackingGlue;_clientGlue;_systemStream;_workspacesStream;_platformClientWindowId;_systemSettings;constructor(e,t){this.portsBridge=e,this.sessionStorage=t}get logger(){return logger.get("glue.controller")}get workspaces(){return this._clientGlue.workspaces?this._clientGlue.workspaces:ioError.raiseError("Cannot access the Workspaces API")}get isWorkspacesEnabled(){return!!this._clientGlue.workspaces}get me(){return this._clientGlue.interop.instance}get platformVersion(){return version$1}get clientGlue(){return this._clientGlue}get contextsTrackingGlue(){return this._contextsTrackingGlue}get systemGlue(){return this._systemGlue}get platformWindowId(){return this._platformClientWindowId.slice()}async start(e){this._config=e;const t=this.sessionStorage.getSystemSettings();if(!t)return ioError.raiseError("Cannot initiate the glue controller, because the system settings are not defined");this._systemSettings=t,this._systemGlue=await this.initSystemGlue(e.browser),logger.setLogger(this._systemGlue.logger),this.logger?.debug(`system glue initialized successfully with config ${JSON.stringify(e.browser)}`),this._contextsTrackingGlue=await this.setUpCtxTracking(e),this.logger?.debug("glueController started successfully")}async initClientGlue(e,t,r,n){this.logger?.debug(`initializing client glue with config: ${JSON.stringify(e)}, factory: ${t?"custom":"default"}, isWorkspaceFrame: ${r}, platformApi: ${n?"provided":"none"}`);const i=await this.portsBridge.createInternalClient();this.registerClientWindow(r);const o={application:"Platform",gateway:{webPlatform:{port:i,windowId:this.platformWindowId}}},s=Object.assign({},e,o);return this._clientGlue=t?await t(s):await iOConnectBrowserFactory(s),this._clientGlue.webPlatform=n,this.logger?.debug("client glue initialized successfully"),this._clientGlue}async createPlatformSystemMethod(e){await this.createMethodAsync(GlueWebPlatformControlName,e)}async createPlatformSystemStream(){this._systemStream=await this.createStream(GlueWebPlatformStreamName)}async createSystemStream(e){return this.createStream(e)}async createWorkspacesStream(){this._workspacesStream=await this.createStream(GlueWebPlatformWorkspacesStreamName)}async createWorkspacesEventsReceiver(e){await this._systemGlue.interop.register(GlueWorkspacesEventsReceiverName,t=>e(t))}pushSystemMessage(e,t,r){if(!this._systemStream)return ioError.raiseError(`Cannot push data to domain: ${e}, because the system stream is not created`);this._systemStream.push({domain:e,operation:t,data:r})}pushWorkspacesMessage(e){if(!this._workspacesStream)return ioError.raiseError("Cannot push data to domain: workspaces, because the workspaces stream is not created");this._workspacesStream.push({data:e})}async callFrame(e,t,r){const n={operation:e.name,operationArguments:t},i=`Internal Platform->Frame Communication Error. Attempted calling workspace frame: ${r} for operation ${e.name} `;if(e.dataDecoder){const t=e.dataDecoder.run(n.operationArguments);if(!t.ok)return ioError.raiseError(`${i} OutBound validation failed: ${JSON.stringify(t.error)}`)}const o=GlueWorkspaceFrameClientControlName,s=await this.transmitMessage(o,n,i,{windowId:r},{methodResponseTimeoutMs:DEFAULT_METHOD_RESPONSE_TIMEOUT_MS$1,waitTimeoutMs:DEFAULT_WAIT_TIMEOUT_MS});if(e.resultDecoder){const t=e.resultDecoder.run(s);if(!t.ok)return ioError.raiseError(`${i} Result validation failed: ${JSON.stringify(t.error)}`)}return s}async isFrameOperationSupported(e,t){try{return!0===(await this.callFrame({name:"operationCheck",execute:()=>Promise.resolve()},{operation:e},t)).isSupported}catch{return!1}}isValidWindowId(e){if(!e)return!1;return[...this.sessionStorage.getAllWindowsData(),...this.sessionStorage.getAllNonGlue()].some(t=>t.windowId===e)}async sendShutDownSignals(){const e=this.clientGlue.windows.list().filter(e=>e.id!==this.platformWindowId);await Promise.all(e.map(e=>e.close()));const t={domain:"system",operation:"platformShutdown"},r=`Internal Platform-> ${t.domain} Domain Communication Error. Attempted sending shutdown signal to all clients.`,n=this.getLocalServers().filter(t=>e.every(e=>e.id!==t.windowId)).map(e=>({instance:e.instance}));try{await this.transmitMessage(GlueClientControlName,t,r,n,{methodResponseTimeoutMs:DEFAULT_METHOD_RESPONSE_TIMEOUT_MS$1,waitTimeoutMs:DEFAULT_WAIT_TIMEOUT_MS})}catch(e){console.warn("Failed to send shutdown signal to all clients",e)}}shutdown(){this.systemGlue.connection.logout(),this.contextsTrackingGlue?.connection.logout(),this.clientGlue.connection.logout()}async checkClientOperationSupport(e,t,r){try{return await this.callInstance(e,{name:"operationCheck",execute:async()=>{}},{operation:t.name},r)}catch(e){return{isSupported:!1}}}async callInstance(e,t,r,n,i){return this.callClient(e,t,r,n,"instance",i)}async callWindow(e,t,r,n,i){return this.callClient(e,t,r,n,"window",i)}async callClient(e,t,r,n,i="window",o){const s=t.name,a={domain:e,operation:s,data:r},c={...n,isLocal:!0},l=`Internal Platform-> ${e} Domain Communication Error. Attempted calling client ${i}: ${JSON.stringify(c)} for operation ${s}.`;if(t.dataDecoder){const e=t.dataDecoder.run(a.data);if(!e.ok)return ioError.raiseError(`${l} OutBound validation failed: ${JSON.stringify(e.error)}`)}const u=await this.transmitMessage(GlueClientControlName,a,l,c,{methodResponseTimeoutMs:DEFAULT_METHOD_RESPONSE_TIMEOUT_MS$1,waitTimeoutMs:DEFAULT_WAIT_TIMEOUT_MS,...o});if(t.resultDecoder){const e=t.resultDecoder.run(u);if(!e.ok)return ioError.raiseError(`${l} Result validation failed when calling ${i}: ${JSON.stringify(c)} for operation ${s}: ${JSON.stringify(e.error)}`)}return u}setStartContext(e,t,r){return PromisePlus((n,i)=>{let o;const s=waitFor(2,()=>{n(),o()}),a=`___${r}___${e}`;(this._clientGlue.contexts.all().some(e=>e===a)?this.waitContextDestroy(a):Promise.resolve()).then(()=>this._clientGlue.contexts.subscribe(a,s)).then(e=>(o=e,this._systemGlue.contexts.set(a,t))).then(s).catch(i)},1e4,`Timed out waiting to set the ${r} context for: ${e}`)}waitContextDestroy(e){return new Promise((t,r)=>{let n=0;const i=setInterval(()=>{const o=this._clientGlue.contexts.all().some(t=>t===e);if(++n,!o)return clearInterval(i),void t();50===n&&(clearInterval(i),r(`Timed out waiting for context: ${e} to disappear`))},100)})}async clearContext(e,t){const r=`___${t}___${e}`,n=this._systemGlue.contexts.all().some(e=>e===r);n&&await this._systemGlue.contexts.destroy(r)}async preserveAllWorkspaceWindowsContext(e){const t=this.sessionStorage.pickWorkspaceClients(t=>t.workspaceId===e);for(const e of t){const t=await this._systemGlue.contexts.get(`___window___${e.windowId}`);t&&("object"!=typeof t||Object.keys(t).length)&&await this._systemGlue.contexts.set(`___window-hibernation___${e.windowId}`,t)}}async pullHibernatedContext(e){const t=`___window-hibernation___${e}`,r=this._systemGlue.contexts.all().some(e=>e===t);if(!r)return;const n=await this._systemGlue.contexts.get(t);return await this._systemGlue.contexts.destroy(t),n}getServers(){return this._clientGlue.interop.servers()}getLocalServers(){return this.getServers().filter(e=>e.isLocal)}subscribeForServerAdded(e){return this._clientGlue.interop.serverAdded(e)}subscribeForMethodAdded(e){return this._clientGlue.interop.methodAdded(e)}invokeMethod(e,t,r,n,i,o){return this._clientGlue.interop.invoke(e,t,r,n,i,o)}setContext(e,t){return this._systemGlue.contexts.set(e,t)}destroyContext(e){return this._systemGlue.contexts.destroy(e)}getAllContexts(){return this._clientGlue.contexts.all()}switchTransport(e,t){if("contextsTrack"===t)return this._contextsTrackingGlue?this._contextsTrackingGlue.connection.switchTransport(e):Promise.resolve({success:!0});return("system"===t?this._systemGlue:this._clientGlue).connection.switchTransport(e)}onDisconnected(e){return this._systemGlue.connection.disconnected(e)}getSystemGlueTransportName(){return this._systemGlue.connection.transport.name()}async importLayout(e){await this._clientGlue.layouts.import([e],"merge")}async getLayout(e){return await this._clientGlue.layouts.get(e,"Global")}async openWindow(e){this._clientGlue.windows.list().find(t=>t.name===e.name)&&(e.name=`${e.name}-${nanoid$3(7)}`);const t={context:e.context,top:e.bounds?.top,left:e.bounds?.left,width:e.bounds?.width,height:e.bounds?.height,layoutComponentId:e.layoutComponentId};return await this._clientGlue.windows.open(e.name,e.url,t)}async startApp(e){const t={waitForAGMReady:!1,top:e.bounds?.top,left:e.bounds?.left,width:e.bounds?.width,height:e.bounds?.height,layoutComponentId:e.layoutComponentId,channelId:e.channelId};return await this._clientGlue.appManager.application(e.name).start(e.context,t)}async getOrCreateWorkspaceFrame({bounds:e,layoutComponentId:t,frameId:r}){return r?await this.workspaces.getFrame(e=>e.id===r):await this.workspaces.createEmptyFrame({frameConfig:{bounds:e||void 0},layoutComponentId:t||void 0})}getAppNameByInstanceId(e){return this._clientGlue.interop.servers().find(t=>t.instance===e)?.application}getAllWindowNames(){return this._clientGlue.windows.list().map(e=>e.name)}getAllOpenedIds(){return this._clientGlue.windows.list().map(e=>e.id)}getAllOtherNonPlatformWindows(e){return this._clientGlue.windows.list().filter(t=>"Platform"!==t.name&&t.id!==e)}async getAllOpenedFrameIds(){return(await this.workspaces.getAllFrames()).map(e=>e.id)}getAllApplicationNames(){return this._clientGlue.appManager.applications().map(e=>e.name)}getAllApplications(){return this._clientGlue.appManager.applications()}getAllLayoutsSummaries(){return this._clientGlue.layouts.getAll("Global")}getAllWorkspacesSummaries(){return this._clientGlue.layouts.getAll("Workspace")}async getWorkspaceWindowById(e){return this._clientGlue.workspaces?.getWindow(t=>t.id===e)}getWindowById(e){return this._clientGlue.windows.list().find(t=>t.id===e)}async getAllWorkspacesFrames(){return await this.workspaces.getAllFrames()}async getWorkspacesByFrameId(e){return await this.workspaces.getAllWorkspaces(t=>t.frameId===e)}registerProvider(e){return this._clientGlue.search?this._clientGlue.search.registerProvider(e):ioError.raiseError("Cannot start the search provider for Glue42 Core Plus, because the Search API is missing")}async processServerApplicationsData(e){const t=e,r=await this._clientGlue.appManager.inMemory.import(t,"merge");r.errors&&r.errors.length&&r.errors.forEach(e=>{this.logger?.warn(`App: ${e.app} was not imported, because of error: ${e.error}`)})}async initSystemGlue(e){const t=await this.portsBridge.createInternalClient(),r=e?.systemLogger?.level??"warn",n=await IOConnectCoreFactory({application:"Platform-System",gateway:{webPlatform:{port:t}},logger:r,customLogger:e?.systemLogger?.customLogger,identity:{instance:this._systemSettings.systemInstanceId}});return this.logger?.debug("system glue initialized successfully"),n}async setUpCtxTracking(e){if(this._config.connection.preferred)return await this.initContextsTrackingGlue({reAnnounceKnownContexts:!0,trackAllContexts:!0},e)}async initContextsTrackingGlue(e,t){this.logger?.debug(`initializing contexts tracking glue with contexts settings - ${JSON.stringify(e)}`);const r=await this.portsBridge.createInternalClient(),n=await IOConnectCoreFactory({application:"Platform-Contexts-Track",gateway:{webPlatform:{port:r}},logger:t?.browser?.systemLogger?.level??"warn",customLogger:t?.browser?.systemLogger?.customLogger,contexts:e,identity:{instance:this._systemSettings.ctxTrackInstanceId}});return this.logger?.debug("contexts tracking glue initialized successfully"),n}registerClientWindow(e){const t=window.name?window.name:`g42-${nanoid$3(10)}`;if(e){const e=this.sessionStorage.getPlatformFrame();if(this._platformClientWindowId=e?e.windowId:t,!e){const e={windowId:this.platformWindowId,active:!0,isPlatform:!0};this.sessionStorage.saveFrameData(e)}return void(window.name=this.platformWindowId)}const r=this.sessionStorage.getWindowDataByName("Platform");this._platformClientWindowId=r?r.windowId:t,r||this.sessionStorage.saveWindowData({name:"Platform",windowId:this.platformWindowId}),window.name=this.platformWindowId}async createMethodAsync(e,t){await this._systemGlue.interop.registerAsync(e,t)}async createStream(e){return this._systemGlue.interop.createStream(e)}async transmitMessage(e,t,r,n,i){let o;try{if(o=await this._systemGlue.interop.invoke(e,t,n,i),!o)throw new Error(`${r} Received unsupported result from the client - empty result`);if(!Array.isArray(o.all_return_values)||0===o.all_return_values.length)throw new Error(`${r} Received unsupported result from the client - empty values collection`)}catch(e){if(e&&e.all_errors&&e.all_errors.length){const t=e.all_errors[0].message;return ioError.raiseError(`${r} -> Inner message: ${t}`)}return ioError.raiseError(`${r} -> Inner message: ${e.message}`)}return o.all_return_values[0].returned}}class PortsBridge{gateway;sessionStorage;windowsStateController;ioc;registry=CallbackRegistryFactory$2();transactionsController;allPorts={};allClients=[];unLoadStarted=!1;isPreferredActivated=!1;activePreferredTransportConfig;_communicationId;startUpPromise;startupResolve;_genericMessageHandler;_unloaderHandler;connectionConfig;constructor(e,t,r,n){this.gateway=e,this.sessionStorage=t,this.windowsStateController=r,this.ioc=n,this.transactionsController=this.ioc.transactionsController}get logger(){return logger.get("ports.bridge.controller")}shutdown(){window.removeEventListener("message",this._genericMessageHandler),window.removeEventListener("pagehide",this._unloaderHandler),this.registry.clear(),this.allPorts={},this.allClients=[],this.isPreferredActivated=!1,this.unLoadStarted=!1}async configure(e){this.connectionConfig=e.connection,this.startUpPromise=new Promise(e=>{this.startupResolve=e});const t=this.sessionStorage.getSystemSettings();if(!t)return ioError.raiseError("Cannot initiate the platform port bridge, because the system settings are not defined");this._communicationId=t.systemInstanceId,await this.gateway.start(e?.gateway,e?.user),this.setupListeners()}start(){this.startupResolve()}async createInternalClient(){const e=this.ioc.createMessageChannel();return await this.gateway.setupInternalClient(e.port1),e.port2}onClientUnloaded(e){return this.registry.add("client-unloaded",e)}async handleExtConnectionRequest(e,t){const r=e.glue42core;if(!!!r.parentWindowId){const e=r.clientId,t={windowId:e,name:e};await this.ioc.windowsController.processNewWindow(t)}await this.gateway.connectExtClient(t,(e,t)=>{this.removeClient({clientId:e},t)});const n=this.sessionStorage.getWindowDataByName("Platform")?.windowId,i={glue42core:{type:Glue42CoreMessageTypes.connectionAccepted.name,parentWindowId:n,appName:"ext-no-app",clientId:r.clientId,clientType:"child"}};this.allPorts[r.clientId]=t,t.postMessage(i)}setActivePreferredTransportConfig(e){"secondary"!==e.type?delete this.activePreferredTransportConfig:this.activePreferredTransportConfig=e}setPreferredActivated(){this.isPreferredActivated=!0}async switchAllClientsTransport(e){const t=Object.keys(this.allPorts).map(t=>this.sendClientPortRequest({type:Glue42CoreMessageTypes.transportSwitchRequest.name,timeout:defaultClientPortRequestTimeoutMS,clientId:t,args:{switchSettings:e}}));await Promise.all(t)}async checkClientsPreferredLogic(){const e=Object.keys(this.allPorts).map(e=>this.sendClientPortRequest({type:Glue42CoreMessageTypes.checkPreferredLogic.name,timeout:defaultClientPreferredLogicTestTimeoutMS,clientId:e}));try{return await Promise.all(e),{success:!0}}catch(e){return{success:!1}}}async checkClientsPreferredConnection(e){const t=Object.keys(this.allPorts).map(t=>this.sendClientPortRequest({type:Glue42CoreMessageTypes.checkPreferredConnection.name,args:{url:e},timeout:defaultClientPortRequestTimeoutMS,clientId:t}));try{return await Promise.all(t),{success:!0}}catch(e){return{success:!1}}}removeGwClient(e){const t=this.allClients.find(t=>t.bridgeInstanceId===e);t&&(this.allClients=this.allClients.filter(t=>t.bridgeInstanceId!==e),t.client.close(),this.allPorts[t.clientId]&&delete this.allPorts[t.clientId])}unloader(){this.unLoadStarted=!0;for(const e in this.allPorts)this.allPorts[e].postMessage({type:"platformUnload"});this.sessionStorage.handlePlatformUnloadCleanup()}genericMessageHandler(e){if(e.data?.type===FDC3HelloRequestType)return void this.processFDC3WebRequest(e);const t=e.data?.glue42core;t&&!this.unLoadStarted&&(t.type!==Glue42CoreMessageTypes.connectionRequest.name?t.type!==Glue42CoreMessageTypes.platformPing.name?t.type!==Glue42CoreMessageTypes.parentPing.name||this.startUpPromise.then(()=>this.handleParentPing(e.source,e.origin)):this.startUpPromise.then(()=>this.handlePlatformPing(e.source,e.origin)):this.startUpPromise.then(()=>this.handleRemoteConnectionRequest(e.source,e.origin,t.clientId,t.clientType,t.bridgeInstanceId,t.selfAssignedWindowId)))}async handleRemoteConnectionRequest(e,t,r,n,i,o){if(checkIsOriginBlocked(t,this.connectionConfig.blockList)){const r=`Origin '${t}' is blocked by the Platform.`;return this.rejectClientConnection(e,r,t)}const s=this.ioc.createMessageChannel(),a=await this.gateway.connectClient(s.port1);this.setupGwClientPort({client:a,clientId:r,clientPort:s.port1}),this.allClients.push({client:a,bridgeInstanceId:i,clientId:r,source:e});const c=this.sessionStorage.getBridgeInstanceData(i),l=c?.appName,u=this.sessionStorage.getWindowDataByName("Platform")?.windowId,d={glue42core:{type:Glue42CoreMessageTypes.connectionAccepted.name,port:s.port2,connectionProtocolVersion:connectionProtocolVersion,communicationId:this._communicationId,isPreferredActivated:this.isPreferredActivated,parentWindowId:u,appName:l,clientId:r,clientType:n}};o&&await this.ioc.windowsController.registerSelfAssignedWindow({windowId:o,name:o},o),e.postMessage(d,t,[s.port2])}rejectClientConnection(e,t,r){this.logger?.error(t);const n={glue42core:{type:Glue42CoreMessageTypes.connectionRejected.name,error:t}};e.postMessage(n,r)}processFDC3WebRequest(e){const t=this.windowsStateController.getAll().find(t=>t.window===e.source);if(!t)return void this.logger?.warn("[Browser Platform] FDC3 Hello request received from an unknown source, ignoring it.");const r={type:FDC3HelloResponseType,meta:{connectionAttemptUuid:e.data?.meta.connectionAttemptUuid,timestamp:(new Date).toISOString()},payload:{iframeUrl:`${window.fdc3ProxyUrl??FDC3ProxyUrl}?parentId=${t.windowId}`}};e.source.postMessage(r,e.origin)}handleParentPing(e,t){const r={glue42core:{type:Glue42CoreMessageTypes.parentReady.name}};e.postMessage(r,t)}handlePlatformPing(e,t){const r={glue42core:{type:Glue42CoreMessageTypes.platformReady.name}};e.postMessage(r,t)}removeClient(e,t,r){const{clientId:n,ownWindowId:i}=e;this.allPorts[n]&&!r&&delete this.allPorts[n];const o=this.allClients.find(e=>e.clientId===n);if(!o)return void this.logger?.warn(`Received client unload for unknown client: ${n}, ignoring it`);if(this.allClients=this.allClients.filter(e=>e.clientId!==n),o.client.close(),!t)return;const s={windowId:i,win:o.source};this.registry.execute("client-unloaded",s)}setupGwClientPort(e){this.allPorts[e.clientId]&&this.allPorts[e.clientId].onmessage&&(this.allPorts[e.clientId].onmessage=null),this.allPorts[e.clientId]=e.clientPort,e.clientPort.onmessage=t=>{const r=t.data?.glue42core,n=r?.type;if(n!==Glue42CoreMessageTypes.clientUnload.name&&n!==Glue42CoreMessageTypes.gatewayDisconnect.name){if(n===Glue42CoreMessageTypes.transportSwitchResponse.name){return void(r.args.success?this.transactionsController.completeTransaction(r.transactionId):this.transactionsController.failTransaction(r.transactionId,`The client: ${e.clientId} could not connect using the provided transport config.`))}if(n===Glue42CoreMessageTypes.getCurrentTransport.name){const t=r.transactionId;return void e.clientPort.postMessage({type:Glue42CoreMessageTypes.getCurrentTransportResponse.name,args:{transportState:this.getCurrentTransportState()},transactionId:t})}if(n===Glue42CoreMessageTypes.checkPreferredLogicResponse.name)return this.transactionsController.completeTransaction(r.transactionId);if(n===Glue42CoreMessageTypes.checkPreferredConnectionResponse.name){const t=r.args;return t.error?this.transactionsController.failTransaction(r.transactionId,t.error):t.live?this.transactionsController.completeTransaction(r.transactionId):this.transactionsController.failTransaction(r.transactionId,`Client ${e.clientId} could not connect to the preferred WS.`)}this.allClients.every(t=>t.client!==e.client)?this.logger?.trace(`Ignoring a protocol message, because the destination client has been disconnected: ${JSON.stringify(t.data)}`):e.client.send(t.data)}else this.removeClient(r.data,!0,r.type===Glue42CoreMessageTypes.gatewayDisconnect.name)}}getCurrentTransportState(){const e=this.ioc.glueController.getSystemGlueTransportName();return{transportName:e,type:e===webPlatformTransportName?"default":"secondary",transportConfig:e===webPlatformTransportName?void 0:this.activePreferredTransportConfig?.transportConfig}}sendClientPortRequest(e){const t=this.allPorts[e.clientId];if(!t)return ioError.raiseError(`Cannot sent port request: ${e.type} to ${e.clientId}, because there is no such client`);const r=this.transactionsController.createTransaction(e.type,e.timeout||defaultClientPortRequestTimeoutMS),n=e.type,i=e.args;return t.postMessage({type:n,args:i,transactionId:r.id}),r.lock}setupListeners(){this._genericMessageHandler=this.genericMessageHandler.bind(this),window.addEventListener("message",this._genericMessageHandler),this._unloaderHandler=this.unloader.bind(this),window.addEventListener("pagehide",this._unloaderHandler)}}const windowOperationDecoder=oneOf$1(constant$2("openWindow"),constant$2("windowHello"),constant$2("getUrl"),constant$2("getTitle"),constant$2("setTitle"),constant$2("moveResize"),constant$2("focus"),constant$2("close"),constant$2("getBounds"),constant$2("getFrameBounds"),constant$2("registerWorkspaceWindow"),constant$2("unregisterWorkspaceWindow"),constant$2("operationCheck"),constant$2("focusChange"),constant$2("getChannel"),constant$2("setZoomFactor"),constant$2("refresh")),openWindowConfigDecoder=object$2({name:nonEmptyStringDecoder$2,url:nonEmptyStringDecoder$2,options:optional$3(windowOpenSettingsDecoder)});object$2({windowId:nonEmptyStringDecoder$2,name:nonEmptyStringDecoder$2});const simpleWindowDecoder=object$2({windowId:nonEmptyStringDecoder$2}),windowBoundsResultDecoder=object$2({windowId:nonEmptyStringDecoder$2,bounds:windowBoundsDecoder}),frameWindowBoundsResultDecoder=object$2({bounds:windowBoundsDecoder}),windowUrlResultDecoder=object$2({windowId:nonEmptyStringDecoder$2,url:nonEmptyStringDecoder$2}),windowMoveResizeConfigDecoder=object$2({windowId:nonEmptyStringDecoder$2,top:optional$3(number$4()),left:optional$3(number$4()),width:optional$3(nonNegativeNumberDecoder$2),height:optional$3(nonNegativeNumberDecoder$2),relative:optional$3(boolean$3())}),windowTitleConfigDecoder=object$2({windowId:nonEmptyStringDecoder$2,title:string$4()}),windowChannelResultDecoder=object$2({channel:optional$3(nonEmptyStringDecoder$2)}),windowZoomFactorConfigDecoder=object$2({windowId:nonEmptyStringDecoder$2,factorIndex:nonNegativeNumberDecoder$2}),workspacesOperationDecoder=oneOf$1(constant$2("isWindowInWorkspace"),constant$2("createWorkspace"),constant$2("createFrame"),constant$2("initFrame"),constant$2("getAllFramesSummaries"),constant$2("getFrameSummary"),constant$2("getAllWorkspacesSummaries"),constant$2("getWorkspaceSnapshot"),constant$2("getAllLayoutsSummaries"),constant$2("openWorkspace"),constant$2("deleteLayout"),constant$2("saveLayout"),constant$2("importLayout"),constant$2("exportAllLayouts"),constant$2("restoreItem"),constant$2("maximizeItem"),constant$2("focusItem"),constant$2("closeItem"),constant$2("closeWorkspace"),constant$2("resizeItem"),constant$2("moveFrame"),constant$2("getFrameSnapshot"),constant$2("forceLoadWindow"),constant$2("ejectWindow"),constant$2("setItemTitle"),constant$2("moveWindowTo"),constant$2("addWindow"),constant$2("addContainer"),constant$2("bundleWorkspace"),constant$2("bundleItem"),constant$2("changeFrameState"),constant$2("getFrameState"),constant$2("getFrameBounds"),constant$2("frameHello"),constant$2("hibernateWorkspace"),constant$2("resumeWorkspace"),constant$2("getWorkspacesConfig"),constant$2("lockWorkspace"),constant$2("lockContainer"),constant$2("lockWindow"),constant$2("pinWorkspace"),constant$2("unpinWorkspace"),constant$2("getWorkspaceIcon"),constant$2("setWorkspaceIcon"),constant$2("checkStarted"),constant$2("getPlatformFrameId"),constant$2("getWorkspaceWindowsOnLayoutSaveContext"),constant$2("getWorkspacesLayouts"),constant$2("setMaximizationBoundary"),constant$2("operationCheck"),constant$2("getWorkspaceWindowFrameBounds"),constant$2("focusChange"),constant$2("bringBackToWorkspace"),constant$2("showChannelsLink")),frameHelloDecoder=object$2({windowId:optional$3(nonEmptyStringDecoder$2)}),workspaceWindowDataDecoder=object$2({name:nonEmptyStringDecoder$2,windowId:nonEmptyStringDecoder$2,frameId:nonEmptyStringDecoder$2,workspaceId:optional$3(nonEmptyStringDecoder$2),appName:optional$3(nonEmptyStringDecoder$2),context:optional$3(anyJson$2()),title:optional$3(nonEmptyStringDecoder$2),channelId:optional$3(nonEmptyStringDecoder$2)}),isWindowInSwimlaneResultDecoder=object$2({inWorkspace:boolean$3()}),allParentDecoder=oneOf$1(constant$2("workspace"),constant$2("row"),constant$2("column"),constant$2("group")),subParentDecoder=oneOf$1(constant$2("row"),constant$2("column"),constant$2("group")),frameStateDecoder=oneOf$1(constant$2("maximized"),constant$2("minimized"),constant$2("normal"));object$2({saveLayout:optional$3(boolean$3())});const deleteLayoutConfigDecoder=object$2({name:nonEmptyStringDecoder$2}),swimlaneWindowDefinitionDecoder=object$2({type:optional$3(constant$2("window")),appName:optional$3(nonEmptyStringDecoder$2),windowId:optional$3(nonEmptyStringDecoder$2),context:optional$3(anyJson$2())}),strictSwimlaneWindowDefinitionDecoder=object$2({type:constant$2("window"),appName:optional$3(nonEmptyStringDecoder$2),windowId:optional$3(nonEmptyStringDecoder$2),context:optional$3(anyJson$2())}),parentDefinitionDecoder=object$2({type:optional$3(subParentDecoder),children:optional$3(lazy(()=>array$3(oneOf$1(swimlaneWindowDefinitionDecoder,parentDefinitionDecoder)))),config:optional$3(anyJson$2())}),groupDefinitionConfigDecoder=object$2({minWidth:optional$3(number$4()),maxWidth:optional$3(number$4()),minHeight:optional$3(number$4()),maxHeight:optional$3(number$4()),allowExtract:optional$3(boolean$3()),allowReorder:optional$3(boolean$3()),allowDrop:optional$3(boolean$3()),allowDropHeader:optional$3(boolean$3()),allowDropLeft:optional$3(boolean$3()),allowDropTop:optional$3(boolean$3()),allowDropRight:optional$3(boolean$3()),allowDropBottom:optional$3(boolean$3()),showMaximizeButton:optional$3(boolean$3()),showEjectButton:optional$3(boolean$3()),showAddWindowButton:optional$3(boolean$3())}),rowDefinitionConfigDecoder=object$2({minHeight:optional$3(number$4()),maxHeight:optional$3(number$4()),allowDrop:optional$3(boolean$3()),allowSplitters:optional$3(boolean$3()),isPinned:optional$3(boolean$3()),maximizationBoundary:optional$3(boolean$3())}),columnDefinitionConfigDecoder=object$2({minWidth:optional$3(number$4()),maxWidth:optional$3(number$4()),allowDrop:optional$3(boolean$3()),allowSplitters:optional$3(boolean$3()),isPinned:optional$3(boolean$3()),maximizationBoundary:optional$3(boolean$3())}),strictColumnDefinitionDecoder=object$2({type:constant$2("column"),children:optional$3(lazy(()=>array$3(oneOf$1(strictSwimlaneWindowDefinitionDecoder,strictParentDefinitionDecoder)))),config:optional$3(columnDefinitionConfigDecoder)}),strictRowDefinitionDecoder=object$2({type:constant$2("row"),children:optional$3(lazy(()=>array$3(oneOf$1(strictSwimlaneWindowDefinitionDecoder,strictParentDefinitionDecoder)))),config:optional$3(rowDefinitionConfigDecoder)}),strictGroupDefinitionDecoder=object$2({type:constant$2("group"),children:optional$3(lazy(()=>array$3(oneOf$1(strictSwimlaneWindowDefinitionDecoder,strictParentDefinitionDecoder)))),config:optional$3(groupDefinitionConfigDecoder)}),strictParentDefinitionDecoder=oneOf$1(strictGroupDefinitionDecoder,strictColumnDefinitionDecoder,strictRowDefinitionDecoder);oneOf$1(string$4().where(e=>"maximized"===e.toLowerCase(),"Expected a case insensitive variation of 'maximized'"),string$4().where(e=>"normal"===e.toLowerCase(),"Expected a case insensitive variation of 'normal'"));const newFrameConfigDecoder=object$2({bounds:optional$3(object$2({left:optional$3(number$4()),top:optional$3(number$4()),width:optional$3(nonNegativeNumberDecoder$2),height:optional$3(nonNegativeNumberDecoder$2)})),frameId:optional$3(nonEmptyStringDecoder$2)}),loadStrategyDecoder=oneOf$1(constant$2("direct"),constant$2("delayed"),constant$2("lazy")),restoreWorkspaceConfigDecoder=object$2({app:optional$3(nonEmptyStringDecoder$2),context:optional$3(anyJson$2()),loadStrategy:optional$3(loadStrategyDecoder),title:optional$3(nonEmptyStringDecoder$2),reuseWorkspaceId:optional$3(nonEmptyStringDecoder$2),frameId:optional$3(nonEmptyStringDecoder$2),lockdown:optional$3(boolean$3()),activateFrame:optional$3(boolean$3()),newFrame:optional$3(oneOf$1(newFrameConfigDecoder,boolean$3())),noTabHeader:optional$3(boolean$3()),inMemoryLayout:optional$3(boolean$3()),isPinned:optional$3(boolean$3()),icon:optional$3(nonEmptyStringDecoder$2),isSelected:optional$3(boolean$3()),positionIndex:optional$3(nonNegativeNumberDecoder$2)}),openWorkspaceConfigDecoder=object$2({name:nonEmptyStringDecoder$2,restoreOptions:optional$3(restoreWorkspaceConfigDecoder)}),workspaceDefinitionDecoder=object$2({children:optional$3(array$3(oneOf$1(swimlaneWindowDefinitionDecoder,parentDefinitionDecoder))),context:optional$3(anyJson$2()),config:optional$3(object$2({title:optional$3(nonEmptyStringDecoder$2),position:optional$3(nonNegativeNumberDecoder$2),isFocused:optional$3(boolean$3()),loadStrategy:optional$3(loadStrategyDecoder),noTabHeader:optional$3(boolean$3()),allowDrop:optional$3(boolean$3()),allowDropLeft:optional$3(boolean$3()),allowDropTop:optional$3(boolean$3()),allowDropRight:optional$3(boolean$3()),allowDropBottom:optional$3(boolean$3()),allowExtract:optional$3(boolean$3()),allowWindowReorder:optional$3(boolean$3()),allowSystemHibernation:optional$3(boolean$3()),showSaveButton:optional$3(boolean$3()),allowWorkspaceTabReorder:optional$3(boolean$3()),allowWorkspaceTabExtract:optional$3(boolean$3()),showCloseButton:optional$3(boolean$3()),allowSplitters:optional$3(boolean$3()),positionIndex:optional$3(nonNegativeNumberDecoder$2)})),frame:optional$3(object$2({reuseFrameId:optional$3(nonEmptyStringDecoder$2),newFrame:optional$3(oneOf$1(boolean$3(),newFrameConfigDecoder))}))});object$2({type:allParentDecoder,definition:optional$3(oneOf$1(workspaceDefinitionDecoder,parentDefinitionDecoder))});const workspaceCreateConfigDecoder=intersection(workspaceDefinitionDecoder,object$2({saveConfig:optional$3(object$2({saveLayout:optional$3(boolean$3())}))})),getFrameSummaryConfigDecoder=object$2({itemId:nonEmptyStringDecoder$2}),frameSummaryDecoder=object$2({id:nonEmptyStringDecoder$2,isFocused:optional$3(boolean$3()),isInitialized:optional$3(boolean$3()),initializationContext:optional$3(object$2({context:optional$3(anyJson$2())}))});object$2({id:nonEmptyStringDecoder$2,frameId:nonEmptyStringDecoder$2,positionIndex:number$4(),title:nonEmptyStringDecoder$2,focused:boolean$3(),layoutName:optional$3(nonEmptyStringDecoder$2),isSelected:optional$3(boolean$3())}),object$2({type:subParentDecoder,id:nonEmptyStringDecoder$2,frameId:nonEmptyStringDecoder$2,workspaceId:nonEmptyStringDecoder$2,positionIndex:number$4()});const eventTypeDecoder=oneOf$1(constant$2("frame"),constant$2("workspace"),constant$2("container"),constant$2("window"));object$2({type:eventTypeDecoder,branch:nonEmptyStringDecoder$2}),oneOf$1(constant$2("opened"),constant$2("closing"),constant$2("closed"),constant$2("focus"),constant$2("added"),constant$2("loaded"),constant$2("removed"),constant$2("childrenUpdate"),constant$2("containerChange"),constant$2("maximized"),constant$2("restored"),constant$2("minimized"),constant$2("normal"),constant$2("selected"),constant$2("lock-configuration-changed"),constant$2("hibernated"),constant$2("resumed"),constant$2("tab-reordered"));const workspaceConfigResultDecoder=object$2({frameId:nonEmptyStringDecoder$2,title:nonEmptyStringDecoder$2,positionIndex:nonNegativeNumberDecoder$2,name:nonEmptyStringDecoder$2,layoutName:optional$3(nonEmptyStringDecoder$2),isHibernated:boolean$3(),isSelected:boolean$3(),lastActive:number$4(),allowDrop:optional$3(boolean$3()),allowExtract:optional$3(boolean$3()),allowWindowReorder:optional$3(boolean$3()),allowSystemHibernation:optional$3(boolean$3()),allowSplitters:optional$3(boolean$3()),showCloseButton:optional$3(boolean$3()),showSaveButton:optional$3(boolean$3()),allowWorkspaceTabReorder:optional$3(boolean$3()),allowDropLeft:optional$3(boolean$3()),allowDropTop:optional$3(boolean$3()),allowDropRight:optional$3(boolean$3()),allowDropBottom:optional$3(boolean$3()),showAddWindowButtons:optional$3(boolean$3()),showEjectButtons:optional$3(boolean$3()),showWindowCloseButtons:optional$3(boolean$3()),minWidth:optional$3(number$4()),maxWidth:optional$3(number$4()),minHeight:optional$3(number$4()),maxHeight:optional$3(number$4()),widthInPx:optional$3(number$4()),heightInPx:optional$3(number$4())}),baseChildSnapshotConfigDecoder=object$2({frameId:nonEmptyStringDecoder$2,workspaceId:nonEmptyStringDecoder$2,positionIndex:number$4()}),parentSnapshotConfigDecoder=anyJson$2(),swimlaneWindowSnapshotConfigDecoder=intersection(baseChildSnapshotConfigDecoder,object$2({windowId:optional$3(nonEmptyStringDecoder$2),isMaximized:optional$3(boolean$3()),isFocused:boolean$3(),isSelected:optional$3(boolean$3()),title:optional$3(string$4()),appName:optional$3(nonEmptyStringDecoder$2),context:optional$3(anyJson$2()),channel:optional$3(nonEmptyStringDecoder$2),instanceId:optional$3(nonEmptyStringDecoder$2)})),childSnapshotResultDecoder=object$2({id:optional$3(nonEmptyStringDecoder$2),config:oneOf$1(parentSnapshotConfigDecoder,swimlaneWindowSnapshotConfigDecoder),children:optional$3(lazy(()=>array$3(childSnapshotResultDecoder))),type:oneOf$1(constant$2("window"),constant$2("row"),constant$2("column"),constant$2("group"))}),workspaceSnapshotResultDecoder=object$2({id:nonEmptyStringDecoder$2,config:workspaceConfigResultDecoder,children:array$3(childSnapshotResultDecoder),frameSummary:frameSummaryDecoder,context:optional$3(anyJson$2())}),customWorkspaceChildSnapshotDecoder=object$2({id:nonEmptyStringDecoder$2,config:oneOf$1(parentSnapshotConfigDecoder,swimlaneWindowSnapshotConfigDecoder),children:optional$3(lazy(()=>array$3(customWorkspaceChildSnapshotDecoder))),type:oneOf$1(constant$2("window"),constant$2("row"),constant$2("column"),constant$2("group"))}),groupLayoutItemDecoder=object$2({type:constant$2("group"),config:anyJson$2(),children:array$3(oneOf$1(windowLayoutItemDecoder))}),columnLayoutItemDecoder=object$2({type:constant$2("column"),config:anyJson$2(),children:array$3(oneOf$1(groupLayoutItemDecoder,windowLayoutItemDecoder,lazy(()=>columnLayoutItemDecoder),lazy(()=>rowLayoutItemDecoder)))}),rowLayoutItemDecoder=object$2({type:constant$2("row"),config:anyJson$2(),children:array$3(oneOf$1(columnLayoutItemDecoder,groupLayoutItemDecoder,windowLayoutItemDecoder,lazy(()=>rowLayoutItemDecoder)))}),workspaceLayoutDecoder=object$2({name:nonEmptyStringDecoder$2,type:constant$2("Workspace"),metadata:optional$3(anyJson$2()),components:array$3(object$2({type:constant$2("Workspace"),application:optional$3(nonEmptyStringDecoder$2),state:object$2({config:anyJson$2(),context:anyJson$2(),children:array$3(oneOf$1(rowLayoutItemDecoder,columnLayoutItemDecoder,groupLayoutItemDecoder,windowLayoutItemDecoder))})}))}),workspacesLayoutImportConfigDecoder=object$2({layout:workspaceLayoutDecoder,mode:oneOf$1(constant$2("replace"),constant$2("merge"))}),exportedLayoutsResultDecoder=object$2({layouts:array$3(workspaceLayoutDecoder)}),frameSummaryResultDecoder=frameSummaryDecoder,frameSummariesResultDecoder=object$2({summaries:array$3(frameSummaryResultDecoder)}),workspaceSummaryResultDecoder=object$2({id:nonEmptyStringDecoder$2,config:workspaceConfigResultDecoder}),workspaceSummariesResultDecoder=object$2({summaries:array$3(workspaceSummaryResultDecoder)}),frameSnapshotResultDecoder=object$2({id:nonEmptyStringDecoder$2,config:anyJson$2(),workspaces:array$3(workspaceSnapshotResultDecoder)}),layoutSummaryDecoder=object$2({name:nonEmptyStringDecoder$2}),layoutSummariesDecoder=object$2({summaries:array$3(layoutSummaryDecoder)}),simpleWindowOperationSuccessResultDecoder=object$2({windowId:nonEmptyStringDecoder$2}),voidResultDecoder=anyJson$2(),frameStateResultDecoder=object$2({state:frameStateDecoder}),frameBoundsDecoder=object$2({top:number$4(),left:number$4(),width:nonNegativeNumberDecoder$2,height:nonNegativeNumberDecoder$2}),frameBoundsResultDecoder=object$2({bounds:frameBoundsDecoder}),resizeConfigDecoder=object$2({width:optional$3(nonNegativeNumberDecoder$2),height:optional$3(nonNegativeNumberDecoder$2),relative:optional$3(boolean$3())}),moveConfigDecoder=object$2({top:optional$3(number$4()),left:optional$3(number$4()),relative:optional$3(boolean$3())}),simpleItemConfigDecoder=object$2({itemId:nonEmptyStringDecoder$2}),ejectWindowDataDecoder=object$2({itemId:nonEmptyStringDecoder$2,windowId:optional$3(nonEmptyStringDecoder$2)}),frameSnapshotConfigDecoder=object$2({itemId:nonEmptyStringDecoder$2,excludeIds:optional$3(boolean$3())}),frameStateConfigDecoder=object$2({frameId:nonEmptyStringDecoder$2,requestedState:frameStateDecoder}),setItemTitleConfigDecoder=object$2({itemId:nonEmptyStringDecoder$2,title:nonEmptyStringDecoder$2}),moveWindowConfigDecoder=object$2({itemId:nonEmptyStringDecoder$2,containerId:nonEmptyStringDecoder$2}),resizeItemConfigDecoder=intersection(simpleItemConfigDecoder,resizeConfigDecoder),moveFrameConfigDecoder=intersection(simpleItemConfigDecoder,moveConfigDecoder);object$2({id:nonEmptyStringDecoder$2,type:subParentDecoder});const addWindowConfigDecoder=object$2({definition:swimlaneWindowDefinitionDecoder,parentId:nonEmptyStringDecoder$2,parentType:allParentDecoder}),addContainerConfigDecoder=object$2({definition:strictParentDefinitionDecoder,parentId:nonEmptyStringDecoder$2,parentType:allParentDecoder}),addItemResultDecoder=object$2({itemId:nonEmptyStringDecoder$2,windowId:optional$3(nonEmptyStringDecoder$2)});object$2({live:boolean$3()});const bundleWorkspaceConfigDecoder=object$2({type:oneOf$1(constant$2("row"),constant$2("column")),workspaceId:nonEmptyStringDecoder$2}),bundleItemConfigDecoder=object$2({type:oneOf$1(constant$2("row"),constant$2("column")),itemId:nonEmptyStringDecoder$2}),workspaceSelectorDecoder=object$2({workspaceId:nonEmptyStringDecoder$2}),containerSummaryResultDecoder=object$2({itemId:nonEmptyStringDecoder$2,config:parentSnapshotConfigDecoder});object$2({frameSummary:frameSummaryDecoder,frameBounds:optional$3(frameBoundsDecoder)}),object$2({workspaceSummary:workspaceSummaryResultDecoder,frameSummary:frameSummaryDecoder,frameBounds:optional$3(frameBoundsDecoder)}),object$2({containerSummary:containerSummaryResultDecoder}),object$2({windowSummary:object$2({itemId:nonEmptyStringDecoder$2,parentId:nonEmptyStringDecoder$2,config:swimlaneWindowSnapshotConfigDecoder})});const workspaceLayoutSaveConfigDecoder=object$2({name:nonEmptyStringDecoder$2,workspaceId:nonEmptyStringDecoder$2,saveContext:optional$3(boolean$3()),saveWindowContexts:optional$3(boolean$3())}),lockWorkspaceDecoder=object$2({workspaceId:nonEmptyStringDecoder$2,config:optional$3(object$2({allowDrop:optional$3(boolean$3()),allowDropLeft:optional$3(boolean$3()),allowDropTop:optional$3(boolean$3()),allowDropRight:optional$3(boolean$3()),allowDropBottom:optional$3(boolean$3()),allowExtract:optional$3(boolean$3()),allowWindowReorder:optional$3(boolean$3()),allowSystemHibernation:optional$3(boolean$3()),allowSplitters:optional$3(boolean$3()),showCloseButton:optional$3(boolean$3()),showSaveButton:optional$3(boolean$3()),allowWorkspaceTabReorder:optional$3(boolean$3()),showWindowCloseButtons:optional$3(boolean$3()),showEjectButtons:optional$3(boolean$3()),showAddWindowButtons:optional$3(boolean$3())}))}),lockWindowDecoder=object$2({windowPlacementId:nonEmptyStringDecoder$2,config:optional$3(object$2({allowExtract:optional$3(boolean$3()),allowReorder:optional$3(boolean$3()),showCloseButton:optional$3(boolean$3())}))}),lockRowDecoder=object$2({itemId:nonEmptyStringDecoder$2,type:constant$2("row"),config:optional$3(object$2({allowDrop:optional$3(boolean$3()),allowSplitters:optional$3(boolean$3())}))}),lockColumnDecoder=object$2({itemId:nonEmptyStringDecoder$2,type:constant$2("column"),config:optional$3(object$2({allowDrop:optional$3(boolean$3()),allowSplitters:optional$3(boolean$3())}))}),lockGroupDecoder=object$2({itemId:nonEmptyStringDecoder$2,type:constant$2("group"),config:optional$3(object$2({allowExtract:optional$3(boolean$3()),allowReorder:optional$3(boolean$3()),allowDrop:optional$3(boolean$3()),allowDropHeader:optional$3(boolean$3()),allowDropLeft:optional$3(boolean$3()),allowDropTop:optional$3(boolean$3()),allowDropRight:optional$3(boolean$3()),allowDropBottom:optional$3(boolean$3()),showMaximizeButton:optional$3(boolean$3()),showEjectButton:optional$3(boolean$3()),showAddWindowButton:optional$3(boolean$3())}))}),lockContainerDecoder=oneOf$1(lockColumnDecoder,lockGroupDecoder,lockRowDecoder),pinWorkspaceDecoder=object$2({workspaceId:nonEmptyStringDecoder$2,icon:optional$3(nonEmptyStringDecoder$2)}),setWorkspaceIconDecoder=object$2({workspaceId:nonEmptyStringDecoder$2,icon:optional$3(nonEmptyStringDecoder$2)}),workspaceIconDecoder=object$2({icon:optional$3(nonEmptyStringDecoder$2)});object$2({applicationName:optional$3(string$4()),frameConfig:optional$3(newFrameConfigDecoder),context:optional$3(object$2()),layoutComponentId:optional$3(nonEmptyStringDecoder$2)});const restoreWorkspaceDefinitionDecoder=object$2({name:nonEmptyStringDecoder$2,restoreOptions:optional$3(restoreWorkspaceConfigDecoder)});object$2({frameId:nonEmptyStringDecoder$2,workspaces:array$3(oneOf$1(workspaceDefinitionDecoder,restoreWorkspaceDefinitionDecoder))});const getWorkspaceWindowsOnLayoutSaveContextConfigDecoder=object$2({layoutType:oneOf$1(constant$2("Global"),constant$2("Workspace")),layoutName:nonEmptyStringDecoder$2,windowIds:array$3(nonEmptyStringDecoder$2),context:optional$3(anyJson$2()),instances:optional$3(array$3(nonEmptyStringDecoder$2)),ignoreInstances:optional$3(array$3(nonEmptyStringDecoder$2)),ignoreContexts:optional$3(boolean$3()),saveWindowContexts:optional$3(boolean$3())}),setMaximizationBoundaryConfigDecoder=object$2({itemId:nonEmptyStringDecoder$2,enabled:boolean$3()}),workspaceWindowOnSaveDataDecoder=object$2({windowId:nonEmptyStringDecoder$2,windowContext:optional$3(anyJson$2())}),getWorkspaceWindowsOnLayoutSaveContextResult=object$2({windowsOnSaveData:array$3(workspaceWindowOnSaveDataDecoder)}),getWorkspacesLayoutsConfigDecoder=object$2({frameId:nonEmptyStringDecoder$2,layoutName:nonEmptyStringDecoder$2,layoutType:oneOf$1(constant$2("Global"),constant$2("Workspace")),context:optional$3(anyJson$2()),ignoreContexts:optional$3(boolean$3()),saveWindowContexts:optional$3(boolean$3())}),getWorkspacesLayoutsResponseDecoder=object$2({workspaces:array$3(workspaceSnapshotResultDecoder)}),showChannelsLinkDecoder=object$2({windowId:nonEmptyStringDecoder$2,frameId:nonEmptyStringDecoder$2,channelsNames:array$3(nonEmptyStringDecoder$2)}),ZOOM_FACTORS=Object.freeze({0:24,1:33,2:50,3:67,4:75,5:80,6:90,7:100,8:110,9:125,10:150,11:175,12:200,13:250,14:300,15:400,16:500});class WindowsController{glueController;sessionController;stateController;ioc;started=!1;clientResponseTimeoutMs;defaultBounds;explicitClosingWindowIds={};connectionConfig;refreshLocks={};operations={openWindow:{name:"openWindow",execute:this.openWindow.bind(this),dataDecoder:openWindowConfigDecoder},windowHello:{name:"windowHello",execute:this.handleWindowHello.bind(this)},getBounds:{name:"getBounds",dataDecoder:simpleWindowDecoder,resultDecoder:windowBoundsResultDecoder,execute:this.handleGetBounds.bind(this)},getFrameBounds:{name:"getFrameBounds",dataDecoder:simpleWindowDecoder,resultDecoder:frameWindowBoundsResultDecoder,execute:this.handleGetBounds.bind(this)},getUrl:{name:"getUrl",dataDecoder:simpleWindowDecoder,resultDecoder:windowUrlResultDecoder,execute:this.handleGetUrl.bind(this)},moveResize:{name:"moveResize",dataDecoder:windowMoveResizeConfigDecoder,execute:this.handleMoveResize.bind(this)},focus:{name:"focus",dataDecoder:simpleWindowDecoder,execute:this.handleFocus.bind(this)},close:{name:"close",dataDecoder:simpleWindowDecoder,execute:this.handleClose.bind(this)},getTitle:{name:"getTitle",dataDecoder:simpleWindowDecoder,resultDecoder:windowTitleConfigDecoder,execute:this.handleGetTitle.bind(this)},setTitle:{name:"setTitle",dataDecoder:windowTitleConfigDecoder,execute:this.handleSetTitle.bind(this)},registerWorkspaceWindow:{name:"registerWorkspaceWindow",dataDecoder:workspaceWindowDataDecoder,execute:this.registerWorkspaceWindow.bind(this)},unregisterWorkspaceWindow:{name:"unregisterWorkspaceWindow",dataDecoder:simpleWindowDecoder,execute:this.handleWorkspaceClientRemoval.bind(this)},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)},focusChange:{name:"focusChange",dataDecoder:focusEventDataDecoder,execute:this.handleFocusEvent.bind(this)},getChannel:{name:"getChannel",dataDecoder:simpleWindowDecoder,resultDecoder:windowChannelResultDecoder,execute:this.handleGetChannel.bind(this)},setZoomFactor:{name:"setZoomFactor",dataDecoder:windowZoomFactorConfigDecoder,execute:this.handleSetZoomFactor.bind(this)},refresh:{name:"refresh",dataDecoder:simpleWindowDecoder,execute:this.handleRefresh.bind(this)}};constructor(e,t,r,n){this.glueController=e,this.sessionController=t,this.stateController=r,this.ioc=n}get logger(){return logger.get("windows.controller")}get moveResizeOperation(){return this.operations.moveResize}get getFrameBoundsOperation(){return this.operations.getFrameBounds}get setTitleOperation(){return this.operations.setTitle}get getBoundsOperation(){return this.operations.getBounds}handlePlatformShutdown(){this.started=!1}async start(e){this.clientResponseTimeoutMs=e.windows.windowResponseTimeoutMs,this.defaultBounds=e.windows.defaultWindowOpenBounds,this.started=!0,this.connectionConfig=e.connection,this.stateController.onWindowDisappeared(e=>this.cleanUpWindow(e).catch(t=>this.logger?.warn(`error while cleaning up window ${e}: ${t?.message}`)))}ready(){return Promise.resolve()}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this windows control message, because the controller has not been started");const t=e.data,r=e.commandId,n=windowOperationDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This window request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`Windows request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`Windows request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}async getWindowTitle(e,t){return(await this.handleGetTitle({windowId:e},t)).title}async getWindowBounds(e,t){return(await this.handleGetBounds({windowId:e},t)).bounds}async processNewWindow(e,t,r){this.logger?.trace(`processing a new window with id: ${e.windowId} and name: ${e.name}`),this.sessionController.saveWindowData(e),r&&this.stateController.add(r,e.windowId),t&&(this.logger?.trace(`setting the context for window ${e.windowId}`),await this.glueController.setStartContext(e.windowId,t,"window")),this.emitStreamData("windowAdded",e)}async handleWorkspaceClientRemoval(e){this.sessionController.removeEjectedWindowId(e.windowId),await this.cleanUpWindow(e.windowId),this.ioc.portsBridge.removeGwClient(e.windowId)}handleClientUnloaded(e,t){if(this.logger?.trace(`handling unloading of ${e}`),e&&!this.explicitClosingWindowIds[e]){if(!t||t.closed)return this.logger?.trace(`${e} detected as closed, processing window cleanup`),void this.cleanUpWindow(e).catch(t=>this.logger?.warn(`error while cleaning up window ${e}: ${t.message}`));this.logger?.trace(`${e} detected as not closed, adding to state controller`),this.stateController.add(t,e)}}setExplicitClosingWindowId(e){this.explicitClosingWindowIds[e]=!0}async cleanUpWindow(e){this.stateController.remove(e);if(this.sessionController.fullWindowClean(e)){try{await this.glueController.clearContext(e,"window")}catch(t){this.logger?.warn(`error while clearing the context of window ${e}: ${t?.message}`)}this.emitStreamData("windowRemoved",{windowId:e}),delete this.explicitClosingWindowIds[e],await this.waitEventFlush()}}async registerSelfAssignedWindow(e,t){this.logger?.trace(`[${t}] handling workspace window registration with id: ${e.windowId} and name: ${e.name}`),this.sessionController.saveWindowData({windowId:e.windowId,name:e.name,selfAssigned:!0}),this.sessionController.saveNonGlue({windowId:e.windowId}),this.emitStreamData("windowAdded",{windowId:e.windowId,name:e.name}),this.logger?.trace(`[${t}] workspace window registered successfully with id ${e.windowId} and name ${e.name}`)}async registerWorkspaceWindow(e,t){this.logger?.trace(`[${t}] handling workspace window registration with id: ${e.windowId} and name: ${e.name}`),this.sessionController.removeEjectedWindowId(e.windowId),e.channelId&&this.sessionController.addWindowChannel(e.windowId,e.channelId),this.sessionController.saveWindowData({windowId:e.windowId,name:e.name,initialChannelId:e.channelId}),this.sessionController.saveWorkspaceClient({windowId:e.windowId,frameId:e.frameId,initialTitle:e.title,workspaceId:e.workspaceId}),this.sessionController.saveNonGlue({windowId:e.windowId});const r=await this.glueController.pullHibernatedContext(e.windowId),n=e.context||r;n&&await this.glueController.setStartContext(e.windowId,n,"window"),this.emitStreamData("windowAdded",{windowId:e.windowId,name:e.name}),this.logger?.trace(`[${t}] workspace window registered successfully with id ${e.windowId} and name ${e.name}`)}async handleFocusEvent(e,t){this.logger?.trace(`[${t}] handling focus event from window id: ${e.windowId} and hasFocus: ${e.hasFocus}`),this.emitStreamData("focusChange",e),this.logger?.trace(`[${t}] focus event from window id: ${e.windowId} and hasFocus: ${e.hasFocus} handled`)}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}emitStreamData(e,t){this.logger?.trace(`sending notification of event: ${e} with data: ${JSON.stringify(t)}`),this.glueController.pushSystemMessage("windows",e,t)}async openWindow(e,t){if(this.sessionController.getWindowDataByName(e.name))return ioError.raiseError(`Cannot open a window with name: ${e.name}, because a window with that name already exists.`);if(checkIsOriginBlocked(e.url,this.connectionConfig.blockList))return ioError.raiseError(`Cannot open a window with url: ${e.url}, because its origin is blocked by the Platform`);this.logger?.trace(`[${t}] handling open command with a valid name: ${e.name}, url: ${e.url} and options: ${JSON.stringify(e.options)}`);const r=await this.getStartingBounds(e,t),n=e.options?.windowId??`g42-${nanoid$3(10)}`,i={name:e.name,windowId:n,initialBounds:r,initialUrl:e.url,initialContext:e.options?.context,layoutComponentId:e.options?.layoutComponentId},o=`left=${r.left},top=${r.top},width=${r.width},height=${r.height}`;this.logger?.trace(`[${t}] calling native window open with bounds: ${o}`);const s=window.open(e.url,i.windowId,o);return s?(await this.processNewWindow(i,e.options?.context,s),this.logger?.trace(`[${t}] the new window is opened, saved in session, state and announced, responding to the caller`),i):ioError.raiseError(`Cannot open window with url: ${e.url} and name: ${e.name}. The most likely reason is that the user has not approved popups or has a blocker.`)}async handleWindowHello(e,t){if(this.logger?.trace(`[${t}] handling a hello message from a real windowId: ${e.windowId}`),e.windowId){this.stateController.remove(e.windowId),this.sessionController.removeNonGlue({windowId:e.windowId});const r=this.sessionController.getWorkspaceClientById(e.windowId);if(r&&r.initialTitle){const n=e.windowId,i=r.initialTitle;PromiseWrap(()=>this.glueController.callWindow("windows",this.operations.setTitle,{windowId:n,title:i},{windowId:n}),this.clientResponseTimeoutMs).catch(e=>this.logger?.trace(`[${t}] error while setting the workspace window title: ${e.message}`))}}const r=!(!e.windowId||!this.sessionController.getFrameData(e.windowId)),n=this.sessionController.getAllWindowsData().map(e=>({windowId:e.windowId,name:e.name}));this.logger?.trace(`[${t}] a full list of all current windows has been compiled, sending it to the caller`);const i=e.windowId?this.refreshLocks[e.windowId]:void 0;return i&&e.windowId&&(i.open(),delete this.refreshLocks[e.windowId]),{windows:n,isWorkspaceFrame:r}}handleGetUrl(e,t){if(!this.sessionController.getWindowDataById(e.windowId))return ioError.raiseError(`Cannot get the url of window: ${e.windowId}, because it does not exist for the platform`);this.logger?.trace(`[${t}] handling a get url request for window ${e.windowId}`);const r=`Cannot get the url of window: ${e.windowId}, because it is either a non-glue window or it hasn't initiated it's glue yet`;return PromiseWrap(()=>this.glueController.callWindow("windows",this.operations.getUrl,e,{windowId:e.windowId}),this.clientResponseTimeoutMs,r)}handleGetTitle(e,t){if(!this.sessionController.getWindowDataById(e.windowId))return ioError.raiseError(`Cannot get the title of window: ${e.windowId}, because it does not exist for the platform`);this.logger?.trace(`[${t}] handling a get title request for window ${e.windowId}`);const r=`Cannot get the title of window: ${e.windowId}, because it is either a non-glue window or it hasn't initiated it's glue yet`;return PromiseWrap(()=>this.glueController.callWindow("windows",this.operations.getTitle,e,{windowId:e.windowId}),this.clientResponseTimeoutMs,r)}async handleSetTitle(e,t){if(!this.sessionController.getWindowDataById(e.windowId))return ioError.raiseError(`Cannot set the title of window: ${e.windowId}, because it does not exist for the platform`);this.sessionController.getWorkspaceClientById(e.windowId)&&await this.ioc.workspacesController.setItemTitle({itemId:e.windowId,title:e.title},t),this.logger?.trace(`[${t}] handling a set title request for window ${e.windowId} and title: ${e.title}`);const r=`Cannot set the title of window: ${e.windowId}, because it is either a non-glue window or it hasn't initiated it's glue yet`;await PromiseWrap(()=>this.glueController.callWindow("windows",this.operations.setTitle,e,{windowId:e.windowId}),this.clientResponseTimeoutMs,r)}async handleMoveResize(e,t){if(this.sessionController.getWorkspaceClientById(e.windowId))return ioError.raiseError(`Cannot move resize window id ${e.windowId}, because it is in a workspace. Consider using the workspaces API to get more control`);const r=this.sessionController.getWindowDataById(e.windowId);if(!r)return ioError.raiseError(`Cannot move resize window: ${e.windowId}, because it does not exist for the platform`);if("Platform"===r.name)return ioError.raiseError("Move-resizing the main application is not allowed");this.logger?.trace(`[${t}] handling a move resize request for window ${e.windowId} and data: ${JSON.stringify(e)}`);const n=`Cannot move resize window: ${e.windowId}, because it is either a non-glue window or it hasn't initiated it's glue yet`;await PromiseWrap(()=>this.glueController.callWindow("windows",this.operations.moveResize,e,{windowId:e.windowId}),this.clientResponseTimeoutMs,n),await this.pause(500)}handleGetBounds(e,t){if(this.sessionController.getWorkspaceClientById(e.windowId))return ioError.raiseError(`Cannot get bounds of window id ${e.windowId}, because it is in a workspace. Consider using the workspaces API to get more info`);if(!this.sessionController.getWindowDataById(e.windowId))return ioError.raiseError(`Cannot get the bounds of window: ${e.windowId}, because it does not exist for the platform`);this.logger?.trace(`[${t}] handling a get bounds request for window ${e.windowId}`);const r=`Cannot get the bounds of window: ${e.windowId}, because it is either a non-glue window or it hasn't initiated it's glue yet`;return PromiseWrap(()=>this.glueController.callWindow("windows",this.operations.getBounds,e,{windowId:e.windowId}),this.clientResponseTimeoutMs,r)}async handleFocus(e,t){if(this.sessionController.getWorkspaceClientById(e.windowId))return ioError.raiseError(`Cannot focus window id ${e.windowId}, because it is in a workspace. Consider using the workspaces API to get more control`);const r=this.sessionController.getWindowDataById(e.windowId);if(!r)return ioError.raiseError(`Cannot focus window: ${e.windowId}, because it is not known by the platform`);this.logger?.trace(`[${t}] handling a focus request for window ${e.windowId}`),window.open(void 0,r.windowId)}async handleClose(e,t){if(this.sessionController.getWorkspaceClientById(e.windowId))return this.logger?.trace(`[${t}] this window is detected as a workspace window, closing via the workspaces controller`),void await this.ioc.workspacesController.closeItem({itemId:e.windowId},t);if(this.sessionController.getInstanceData(e.windowId))return this.logger?.trace(`[${t}] this window is detected as an application instance, closing via the appManager controller`),void await this.ioc.applicationsController.handleInstanceStop({id:e.windowId},t);const r=this.sessionController.getWindowDataById(e.windowId);return r?"Platform"===r.name?ioError.raiseError("Closing the main application is not allowed"):r.selfAssigned?ioError.raiseError("Closing self-assigned windows (windows not opened by the Glue API) is not allowed"):(this.logger?.trace(`[${t}] handling a close request for window ${e.windowId}`),window.open(void 0,r.windowId)?.close(),await this.cleanUpWindow(r.windowId),void this.logger?.trace(`[${t}] window ${e.windowId} has been closed, removed from session, state and announced`)):ioError.raiseError(`Cannot close window: ${e.windowId}, because it is not known by the platform`)}async getStartingBounds(e,t){const r={top:e.options?.top??this.defaultBounds.top,left:e.options?.left??this.defaultBounds.left,height:e.options?.height??this.defaultBounds.height,width:e.options?.width??this.defaultBounds.width};if(!e.options?.relativeTo)return r;const n=e.options.relativeTo,i=this.sessionController.getWindowDataById(n);if(!i)return r;try{const n=(await this.handleGetBounds({windowId:i.windowId},t)).bounds,o=e.options.relativeDirection??"right";return getRelativeBounds(r,n,o)}catch(e){return r}}pause(e){return new Promise(t=>setTimeout(t,e))}handleGetChannel(e,t){this.logger?.trace(`[${t}] handling a get channel request for window ${e.windowId}`);if(!this.sessionController.getWindowDataById(e.windowId))return ioError.raiseError(`Cannot get the channel of window: ${e.windowId}, because it does not exist for the platform`);const r=`Cannot get the channel of window: ${e.windowId}, because it is either a non-glue window or it hasn't initiated it's glue yet`;return PromiseWrap(()=>this.glueController.callWindow("windows",this.operations.getChannel,e,{windowId:e.windowId}),this.clientResponseTimeoutMs,r)}async handleSetZoomFactor(e,t){this.logger?.trace(`[${t}] handling a set zoom factor request for window ${e.windowId} and factor: ${ZOOM_FACTORS[e.factorIndex]}`);if(!this.sessionController.getWindowDataById(e.windowId))return ioError.raiseError(`Cannot set the zoom factor of window: ${e.windowId}, because it does not exist for the platform`);const r=`Cannot set the zoom factor of window: ${e.windowId}, because it is either a non-glue window or it hasn't initiated it's glue yet`;await PromiseWrap(()=>this.glueController.callWindow("windows",this.operations.setZoomFactor,e,{windowId:e.windowId}),this.clientResponseTimeoutMs,r),this.emitStreamData("zoomFactorChange",e)}async handleRefresh(e,t){this.logger?.trace(`[${t}] handling a refresh request for window ${e.windowId}`);const r=this.sessionController.getWindowDataById(e.windowId);if(!r)return ioError.raiseError(`Cannot refresh window: ${e.windowId}, because it does not exist for the platform`);if("Platform"===r.name)return ioError.raiseError("Refreshing the main application is not allowed");const n=`Cannot refresh window: ${e.windowId}, because it is either a non-glue window or it hasn't initiated it's glue yet`,{isSupported:i}=await this.glueController.checkClientOperationSupport("windows",this.operations.refresh,{instance:e.windowId});if(!i)return ioError.raiseError(`[${t}] Cannot handle refresh request, because the target instance does not support the operation`);await PromiseWrap(()=>this.glueController.callWindow("windows",this.operations.refresh,e,{windowId:e.windowId}),this.clientResponseTimeoutMs,n);const o=this.createRefreshLock();this.refreshLocks[e.windowId]=o,await o.lock}createRefreshLock(){let e;const t=PromisePlus(t=>{e=t},3e3,"The refresh lock was not opened in time, this is most likely a bug in the platform");if(!e)throw new Error("The open function for the refresh lock was not initialized properly");return{open:e,lock:t}}waitEventFlush(){return new Promise(e=>setTimeout(e,10))}}class SessionStorageController{cache={};sessionStorage;windowsNamespace="g42_core_windows";instancesNamespace="g42_core_instances";bridgeInstancesNamespace="g42_core_bridge";nonGlueNamespace="g42_core_nonglue";workspaceWindowsNamespace="g42_core_workspace_clients";workspaceFramesNamespace="g42_core_workspace_frames";workspaceHibernationNamespace="g42_core_workspace_hibernation";globalLayoutsNamespace="g42_core_layouts_global";workspaceLayoutsNamespace="g42_core_layouts_workspace";appDefsNamespace="g42_core_app_definitions";appDefsInmemoryNamespace="g42_core_app_definitions_inmemory";notificationsNamespace="g42_core_notifications";prefsRestSchedulerNamespace="g42_core_prefs_rest_scheduler";layoutsSystemNamespace="g42_core_layouts_system";systemNamespace="g42_system";workspaceFrameCache="g42_workspace_frame_cache";channelsNamespace="g42_core_channels";ejectedWindowIdsNamespace="g42_core_ejected_windows";allNamespaces=[this.bridgeInstancesNamespace,this.windowsNamespace,this.instancesNamespace,this.nonGlueNamespace,this.workspaceWindowsNamespace,this.workspaceFramesNamespace,this.globalLayoutsNamespace,this.workspaceLayoutsNamespace,this.appDefsNamespace,this.workspaceHibernationNamespace,this.appDefsInmemoryNamespace,this.notificationsNamespace,this.prefsRestSchedulerNamespace,this.workspaceFrameCache,this.channelsNamespace,this.ejectedWindowIdsNamespace];get logger(){return logger.get("session.storage")}start(){this.sessionStorage=window.sessionStorage,this.allNamespaces.forEach(e=>{this.getItem(e)||this.setItem(e,JSON.stringify([]))})}shutdown(){this.allNamespaces.forEach(e=>{this.setItem(e,JSON.stringify([]))}),this.removeItem(this.systemNamespace),this.removeItem(this.layoutsSystemNamespace)}getSystemSettings(){const e=this.getItem(this.systemNamespace);if(e)return JSON.parse(e)}setSystemSettings(e){this.setItem(this.systemNamespace,JSON.stringify(e))}getLayoutsSystemData(){const e=this.getItem(this.layoutsSystemNamespace);return e?JSON.parse(e):{}}setLayoutsSystemData(e){this.setItem(this.layoutsSystemNamespace,JSON.stringify(e))}getTimeout(e){const t=this.getNamespaceData(this.workspaceHibernationNamespace);return t.find(t=>t.workspaceId===e)?.timeout}removeTimeout(e){const t=this.getNamespaceData(this.workspaceHibernationNamespace);t.find(t=>t.workspaceId===e)&&this.setItem(this.workspaceHibernationNamespace,JSON.stringify(t.filter(t=>t.workspaceId!==e)))}saveTimeout(e,t){const r=this.getNamespaceData(this.workspaceHibernationNamespace);r.some(t=>t.workspaceId===e)||(r.push({workspaceId:e,timeout:t}),this.setItem(this.workspaceHibernationNamespace,JSON.stringify(r)))}exportClearTimeouts(){const e=this.getNamespaceData(this.workspaceHibernationNamespace);return this.setItem(this.workspaceHibernationNamespace,JSON.stringify([])),e}getAllApps(e){const t="remote"===e?this.appDefsNamespace:this.appDefsInmemoryNamespace;return this.getNamespaceData(t)}overwriteApps(e,t){const r="remote"===t?this.appDefsNamespace:this.appDefsInmemoryNamespace;this.setItem(r,JSON.stringify(e))}removeApp(e,t){const r="remote"===t?this.appDefsNamespace:this.appDefsInmemoryNamespace,n=this.getAllApps(t),i=n.find(t=>t.name===e);return i&&this.setItem(r,JSON.stringify(n.filter(t=>t.name!==e))),i}getLayoutSnapshot(e){const t="Global"===e?this.globalLayoutsNamespace:this.workspaceLayoutsNamespace;return{layouts:this.getNamespaceData(t)}}saveLayoutSnapshot(e,t){const r="Global"===t?this.globalLayoutsNamespace:this.workspaceLayoutsNamespace;this.setItem(r,JSON.stringify(e.layouts))}saveFrameData(e){const t=this.getNamespaceData(this.workspaceFramesNamespace);t.some(t=>t.windowId===e.windowId)||(t.push(e),this.setItem(this.workspaceFramesNamespace,JSON.stringify(t)))}getPlatformFrame(){return this.getAllFrames().find(e=>e.isPlatform)}getAllFrames(){return this.getNamespaceData(this.workspaceFramesNamespace)}getFrameData(e){return this.getAllFrames().find(t=>t.windowId===e)}setFrameActive(e){const t=this.getAllFrames(),r=t.find(t=>t.windowId===e);r&&!r.active&&(r.active=!0,this.setItem(this.workspaceFramesNamespace,JSON.stringify(t)))}removeFrameData(e){return!!e&&this.doRemove(e,this.workspaceFramesNamespace)}saveWorkspaceClient(e){const t=this.getNamespaceData(this.workspaceWindowsNamespace);t.some(t=>t.windowId===e.windowId)||(t.push(e),this.setItem(this.workspaceWindowsNamespace,JSON.stringify(t)))}getWorkspaceClientById(e){return this.getNamespaceData(this.workspaceWindowsNamespace).find(t=>t.windowId===e)}pickWorkspaceClients(e){return this.getNamespaceData(this.workspaceWindowsNamespace).filter(e)}removeWorkspaceClient(e){return!!e&&this.doRemove(e,this.workspaceWindowsNamespace)}getAllNonGlue(){return this.getNamespaceData(this.nonGlueNamespace)}saveNonGlue(e){const t=this.getNamespaceData(this.nonGlueNamespace);return t.some(t=>t.windowId===e.windowId)?(this.logger?.trace(`did not save this data: ${JSON.stringify(e)}, because an entry with this id already exists`),!1):(this.logger?.trace(`saving non glue window with id: ${e.windowId}`),t.push(e),this.setItem(this.nonGlueNamespace,JSON.stringify(t)),!0)}removeNonGlue(e){return!(!e||!e.windowId)&&(this.logger?.trace(`removing non glue window with id: ${e.windowId}`),this.doRemove(e.windowId,this.nonGlueNamespace))}saveBridgeInstanceData(e){const t=this.getNamespaceData(this.bridgeInstancesNamespace);t.some(t=>t.windowId===e.windowId)?this.logger?.trace(`did not save this data: ${JSON.stringify(e)}, because an entry with this id already exists`):(this.logger?.trace(`saving new instance with id: ${e.windowId} and app name: ${e.appName}`),t.push(e),this.setItem(this.bridgeInstancesNamespace,JSON.stringify(t)))}getBridgeInstanceData(e){return this.getNamespaceData(this.bridgeInstancesNamespace).find(t=>t.windowId===e)}removeBridgeInstanceData(e){const t=this.getNamespaceData(this.bridgeInstancesNamespace);this.setItem(this.bridgeInstancesNamespace,JSON.stringify(t.filter(t=>t.windowId!==e)))}saveInstanceData(e){const t=this.getNamespaceData(this.instancesNamespace);t.some(t=>t.id===e.id)?this.logger?.trace(`did not save this data: ${JSON.stringify(e)}, because an entry with this id already exists`):(this.logger?.trace(`saving new instance with id: ${e.id} and app name: ${e.applicationName}`),t.push(e),this.setItem(this.instancesNamespace,JSON.stringify(t)))}removeInstance(e){this.logger?.trace(`removing instance with id: ${e}`);const t=this.getAllInstancesData();this.setItem(this.instancesNamespace,JSON.stringify(t.filter(t=>t.id!==e))),this.removeBridgeInstanceData(e)}getInstanceData(e){return this.getAllInstancesData().find(t=>t.id===e)}getAllInstancesData(){return this.getNamespaceData(this.instancesNamespace)}removeNotification(e){const t=this.getNamespaceData(this.notificationsNamespace);t.find(t=>t.id===e)&&this.setItem(this.notificationsNamespace,JSON.stringify(t.filter(t=>t.id!==e)))}saveNewNotification(e){const t=this.getAllNotifications();if(t.some(t=>t.id===e.id))return ioError.raiseError(`Notification with id ${e.id} already exists`);this.logger?.trace(`saving notification with id: ${e.id}`),t.push(e),this.setItem(this.notificationsNamespace,JSON.stringify(t))}updateNotification(e){const t=this.getAllNotifications(),r=t.findIndex(t=>t.id===e.id);if(-1===r)return ioError.raiseError(`Notification with id ${e.id} does not exist`);this.logger?.trace(`updating notification with id: ${e.id}`),t[r]=e,this.setItem(this.notificationsNamespace,JSON.stringify(t))}getNotification(e){return this.getAllNotifications().find(t=>t.id===e)}getAllNotifications(){return this.getNamespaceData(this.notificationsNamespace)}savePrefsRestSchedulerCache(e){const t=this.getAllPrefsRestSchedulerCache();t.some(t=>t.app===e.app)?this.logger?.trace(`did not save this data: ${JSON.stringify(e)}, because an entry with this app already exists`):(this.logger?.trace(`saving prefs rest scheduler cache for app: ${e.app}`),t.push(e),this.setItem(this.prefsRestSchedulerNamespace,JSON.stringify(t)))}getAllPrefsRestSchedulerCache(){return this.getNamespaceData(this.prefsRestSchedulerNamespace)}clearAllPrefsRestSchedulerCache(){this.setItem(this.prefsRestSchedulerNamespace,JSON.stringify([]))}saveWindowData(e){const t=this.getAllWindowsData();t.some(t=>t.name===e.name)?this.logger?.trace(`did not save this data: ${JSON.stringify(e)}, because an entry with this name already exists`):(this.logger?.trace(`saving window with id: ${e.windowId} and name: ${e.name}`),t.push(e),this.setItem(this.windowsNamespace,JSON.stringify(t)))}getAllWindowsData(){return this.getNamespaceData(this.windowsNamespace)}getWindowDataById(e){return this.getAllWindowsData().find(t=>t.windowId===e)}getWindowDataByName(e){return this.getAllWindowsData().find(t=>t.name===e)}removeWindowData(e){return!!e&&(this.logger?.trace(`removing window with id: ${e}`),this.doRemove(e,this.windowsNamespace))}fullWindowClean(e){const t=this.removeWindowData(e),r=this.removeNonGlue({windowId:e}),n=this.removeWorkspaceClient(e);return t||r||n}addWindowChannel(e,t){const r=this.getNamespaceData(this.channelsNamespace),n=r.findIndex(t=>t.windowId===e);if(-1===n)return this.logger?.trace(`no channel data found for window with id: ${e}, creating new entry`),r.push({windowId:e,channels:[t]}),this.setItem(this.channelsNamespace,JSON.stringify(r));this.logger?.trace(`adding channel data for window with id: ${e}`),r[n].channels=Array.from(new Set([...r[n].channels||[],t])),this.setItem(this.channelsNamespace,JSON.stringify(r))}setChannelsForWindow(e,t){const r=this.getNamespaceData(this.channelsNamespace),n=r.findIndex(t=>t.windowId===e);if(-1===n)return this.logger?.trace(`no channel data found for window with id: ${e}, creating new entry`),r.push({windowId:e,channels:t}),this.setItem(this.channelsNamespace,JSON.stringify(r));this.logger?.trace(`adding channels data for window with id: ${e}`),r[n].channels=Array.from(new Set(t)),this.setItem(this.channelsNamespace,JSON.stringify(r))}setAdditionalChannelForWindow(e,t){const r=this.getNamespaceData(this.channelsNamespace),n=r.findIndex(t=>t.windowId===e);if(-1===n)return this.logger?.trace(`no channel data found for window with id: ${e}, creating new entry`),r.push({windowId:e,channels:[t]}),this.setItem(this.channelsNamespace,JSON.stringify(r));this.logger?.trace(`add additional channel data for window with id: ${e}`),r[n].channels=Array.from(new Set([...r[n].channels??[],t])),this.setItem(this.channelsNamespace,JSON.stringify(r))}addChannelRestrictionsByWindowId(e,t){const r=this.getNamespaceData(this.channelsNamespace),n=r.findIndex(t=>t.windowId===e);if(-1===n)return this.logger?.trace(`no channel data found for window with id: ${e}, creating new entry with restrictions`),r.push({windowId:e,restrictions:[t]}),this.setItem(this.channelsNamespace,JSON.stringify(r));this.logger?.trace(`channel data found for window with id: ${e}, updating restrictions`);const i=r[n].restrictions?.some(e=>e.name===t.name);r[n].restrictions=i?[t]:[...r[n].restrictions||[],t],this.setItem(this.channelsNamespace,JSON.stringify(r))}addAllChannelsRestrictionsByWindowId(e,t){const r=this.getNamespaceData(this.channelsNamespace),n=r.findIndex(t=>t.windowId===e);if(-1===n)return this.logger?.trace(`no channel data found for window with id: ${e}, creating new entry with restrictions`),r.push({windowId:e,restrictions:t}),this.setItem(this.channelsNamespace,JSON.stringify(r));this.logger?.trace(`channel data found for window with id: ${e}, updating restrictions`),r[n].restrictions=t,this.setItem(this.channelsNamespace,JSON.stringify(r))}addEjectedWindowId(e){const t=this.getNamespaceData(this.ejectedWindowIdsNamespace),r=Array.from(new Set([...t,e]));this.setItem(this.ejectedWindowIdsNamespace,JSON.stringify(r))}removeEjectedWindowId(e){const t=this.getNamespaceData(this.ejectedWindowIdsNamespace).filter(t=>t!==e);this.setItem(this.ejectedWindowIdsNamespace,JSON.stringify(t))}getEjectedWindowIds(){return this.getNamespaceData(this.ejectedWindowIdsNamespace)}getWindowChannelData(e){return this.getNamespaceData(this.channelsNamespace).find(t=>t.windowId===e)}getAllWindowsChannelData(){return this.getNamespaceData(this.channelsNamespace)}removeWindowChannelData(e){return!!e&&this.doRemove(e,this.channelsNamespace)}handlePlatformUnloadCleanup(){const e=this.getNamespaceData(this.workspaceWindowsNamespace);if(!e.length)return;this.getAllWindowsData().forEach(t=>{const r=e.find(e=>e.windowId===t.windowId);if(!r)return;const n=this.getFrameData(r.frameId);n?.isPlatform&&(this.fullWindowClean(t.windowId),this.removeWindowChannelData(t.windowId),this.removeInstance(t.windowId))})}doRemove(e,t){const r=this.getNamespaceData(t).reduce((t,r)=>(r.windowId===e?t.removed=!0:t.newData.push(r),t),{removed:!1,newData:[]});return this.setItem(t,JSON.stringify(r.newData)),r.removed}getNamespaceData(e){const t=this.getItem(e);return t?JSON.parse(t):[]}getItem(e){const t=this.sessionStorage.getItem(e);return t?(this.cache[e]=t,t):(this.doFullRecovery(),this.cache[e])}setItem(e,t){this.cache[e]=t,this.sessionStorage.setItem(e,t)}removeItem(e){delete this.cache[e],this.sessionStorage.removeItem(e)}doFullRecovery(){this.logger?.warn("Session storage is empty or corrupted, performing full recovery from in-memory cache");this.allNamespaces.filter(e=>e!==this.systemNamespace&&e!==this.layoutsSystemNamespace).forEach(e=>{const t=this.cache[e]??JSON.stringify([]);this.setItem(e,t)}),this.setItem(this.systemNamespace,this.cache[this.systemNamespace]??JSON.stringify({})),this.setItem(this.layoutsSystemNamespace,this.cache[this.layoutsSystemNamespace]??JSON.stringify({})),this.logger?.info("Full recovery completed, session storage is now restored from in-memory cache")}}class WindowsStateController{sessionStorage;registry=CallbackRegistryFactory$2();checkIntervalMs=500;childrenToCheck=[];checkerCancelled=!1;currentTimeout;constructor(e){this.sessionStorage=e}get logger(){return logger.get("state.controller")}start(){this.checkerCancelled=!1;const e=this.sessionStorage.getAllNonGlue(),t=this.sessionStorage.pickWorkspaceClients(()=>!0);this.logger?.debug(`starting state controller with ${e.length} non-glue windows and ${t.length} workspace clients from previous session`);e.filter(e=>t.every(t=>t.windowId!==e.windowId)).forEach(e=>{this.logger?.trace(`detected non glue window with id ${e.windowId} from previous session, attempting reference refresh`);const t=window.open(void 0,e.windowId);t&&this.childrenToCheck.push({window:t,windowId:e.windowId})}),this.checkWindows(),this.logger?.debug(`state controller startup completed with ${this.childrenToCheck.length} windows to monitor`)}add(e,t){this.logger?.trace(`adding window id: ${t} to non glue state checking`);this.sessionStorage.saveNonGlue({windowId:t})&&this.childrenToCheck.push({window:e,windowId:t})}getAll(){return this.logger?.trace("getting all non glue windows"),this.childrenToCheck}remove(e){this.logger?.trace(`removing window id: ${e} from non glue state checking`),this.sessionStorage.removeNonGlue({windowId:e}),this.childrenToCheck=this.childrenToCheck.filter(t=>t.windowId!==e)}cancel(){this.logger?.debug("cancelling state controller"),this.currentTimeout&&clearTimeout(this.currentTimeout),this.checkerCancelled=!0,this.registry.clear()}onWindowDisappeared(e){return this.registry.add("window-disappear",e)}checkWindows(){this.checkerCancelled||(this.childrenToCheck.forEach(e=>{if(!e.window||e.window.closed)return this.logger?.trace(`non glue window ${e.windowId} has disappeared, removing from collections and announcing.`),this.remove(e.windowId),void this.registry.execute("window-disappear",e.windowId)}),this.currentTimeout=setTimeout(this.checkWindows.bind(this),this.checkIntervalMs))}}const intentsOperationTypesDecoder=oneOf$1(constant$2("findIntent"),constant$2("getIntents"),constant$2("raise"),constant$2("operationCheck"),constant$2("filterHandlers"),constant$2("getIntentsByHandler")),intentHandlerDecoder=object$2({applicationName:nonEmptyStringDecoder$2,applicationTitle:optional$3(string$4()),applicationDescription:optional$3(string$4()),applicationIcon:optional$3(string$4()),type:oneOf$1(constant$2("app"),constant$2("instance")),displayName:optional$3(string$4()),contextTypes:optional$3(array$3(nonEmptyStringDecoder$2)),instanceId:optional$3(string$4()),instanceTitle:optional$3(string$4()),resultType:optional$3(nonEmptyStringDecoder$2),customConfig:optional$3(object$2())}),intentDecoder=object$2({name:nonEmptyStringDecoder$2,handlers:array$3(intentHandlerDecoder)}),intentTargetDecoder=oneOf$1(constant$2("startNew"),constant$2("reuse"),object$2({app:optional$3(nonEmptyStringDecoder$2),instance:optional$3(nonEmptyStringDecoder$2)})),intentContextDecoder=object$2({type:optional$3(nonEmptyStringDecoder$2),data:optional$3(object$2())}),intentsDecoder=array$3(intentDecoder),wrappedIntentsDecoder=object$2({intents:intentsDecoder}),wrappedIntentFilterDecoder=object$2({filter:optional$3(object$2({name:optional$3(nonEmptyStringDecoder$2),contextType:optional$3(nonEmptyStringDecoder$2),resultType:optional$3(nonEmptyStringDecoder$2)}))});object$2({applicationName:nonEmptyStringDecoder$2,applicationIcon:optional$3(string$4()),instanceId:optional$3(string$4())});const applicationStartOptionsDecoder=object$2({top:optional$3(number$4()),left:optional$3(number$4()),width:optional$3(nonNegativeNumberDecoder$2),height:optional$3(nonNegativeNumberDecoder$2),relativeTo:optional$3(nonEmptyStringDecoder$2),relativeDirection:optional$3(windowRelativeDirectionDecoder),waitForAGMReady:optional$3(boolean$3()),channelId:optional$3(nonEmptyStringDecoder$2)}),intentRequestDecoder=object$2({intent:nonEmptyStringDecoder$2,target:optional$3(intentTargetDecoder),context:optional$3(intentContextDecoder),options:optional$3(applicationStartOptionsDecoder),handlers:optional$3(array$3(intentHandlerDecoder)),timeout:optional$3(nonNegativeNumberDecoder$2),waitUserResponseIndefinitely:optional$3(boolean$3()),clearSavedHandler:optional$3(boolean$3())}),resolverConfigDecoder=object$2({enabled:optional$3(boolean$3()),appName:string$4(),waitResponseTimeout:number$4()}),intentResultDecoder=object$2({request:intentRequestDecoder,handler:intentHandlerDecoder,result:anyJson$2()}),resolverResponseDecoder=object$2({intent:nonEmptyStringDecoder$2,handler:intentHandlerDecoder,correlationId:optional$3(string$4()),userSettings:object$2({preserveChoice:optional$3(boolean$3())})}),handlerExclusionCriteriaApplicationNameDecoder=object$2({applicationName:nonEmptyStringDecoder$2}),handlerExclusionCriteriaInstanceIdDecoder=object$2({instanceId:nonEmptyStringDecoder$2}),handlerExclusionCriteriaDecoder=oneOf$1(handlerExclusionCriteriaApplicationNameDecoder,handlerExclusionCriteriaInstanceIdDecoder),handlerFilterDecoder=object$2({title:optional$3(nonEmptyStringDecoder$2),openResolver:optional$3(boolean$3()),timeout:optional$3(nonNegativeNumberDecoder$2),intent:optional$3(nonEmptyStringDecoder$2),contextTypes:optional$3(array$3(nonEmptyStringDecoder$2)),resultType:optional$3(nonEmptyStringDecoder$2),applicationNames:optional$3(array$3(nonEmptyStringDecoder$2)),excludeList:optional$3(array$3(handlerExclusionCriteriaDecoder))}),filterHandlersResultDecoder=object$2({handlers:array$3(intentHandlerDecoder)}),embeddedResolverConfigDecoder=object$2({enabled:boolean$3(),initialCaller:object$2({instanceId:nonEmptyStringDecoder$2})}),filterHandlersWithResolverConfigDecoder=object$2({filterHandlersRequest:handlerFilterDecoder,resolverConfig:resolverConfigDecoder,embeddedResolverConfig:optional$3(embeddedResolverConfigDecoder)}),intentInfoDecoder=object$2({intent:nonEmptyStringDecoder$2,contextTypes:optional$3(array$3(nonEmptyStringDecoder$2)),description:optional$3(nonEmptyStringDecoder$2),displayName:optional$3(nonEmptyStringDecoder$2),icon:optional$3(nonEmptyStringDecoder$2),resultType:optional$3(nonEmptyStringDecoder$2)}),getIntentsResultDecoder=object$2({intents:array$3(intentInfoDecoder)}),raiseIntentRequestDecoder=object$2({intentRequest:intentRequestDecoder,resolverConfig:resolverConfigDecoder,embeddedResolverConfig:optional$3(embeddedResolverConfigDecoder)}),appManagerOperationTypesDecoder=oneOf$1(constant$2("appHello"),constant$2("applicationStart"),constant$2("instanceStop"),constant$2("registerWorkspaceApp"),constant$2("unregisterWorkspaceApp"),constant$2("export"),constant$2("import"),constant$2("remove"),constant$2("clear"),constant$2("registerRemoteApps"),constant$2("operationCheck")),basicInstanceDataDecoder=object$2({id:nonEmptyStringDecoder$2}),instanceDataDecoder=object$2({id:nonEmptyStringDecoder$2,applicationName:nonEmptyStringDecoder$2}),applicationDataDecoder=object$2({name:nonEmptyStringDecoder$2,type:nonEmptyStringDecoder$2.where(e=>"window"===e,"Expected a value of window"),createOptions:applicationDetailsDecoder,instances:array$3(instanceDataDecoder),userProperties:optional$3(anyJson$2()),title:optional$3(nonEmptyStringDecoder$2),version:optional$3(nonEmptyStringDecoder$2),icon:optional$3(string$4()),caption:optional$3(nonEmptyStringDecoder$2),fdc3:optional$3(anyJson$2())}),appHelloSuccessDecoder$1=object$2({apps:array$3(applicationDataDecoder),initialChannelId:optional$3(nonEmptyStringDecoder$2)}),appHelloDecoder=object$2({windowId:optional$3(nonEmptyStringDecoder$2)}),originAppDecoder=object$2({interopInstance:nonEmptyStringDecoder$2,name:optional$3(nonEmptyStringDecoder$2)}),startReasonDecoder=object$2({originApp:originAppDecoder,intentRequest:optional$3(intentRequestDecoder)}),applicationStartConfigDecoder=object$2({name:nonEmptyStringDecoder$2,id:optional$3(nonEmptyStringDecoder$2),context:optional$3(anyJson$2()),top:optional$3(number$4()),left:optional$3(number$4()),width:optional$3(nonNegativeNumberDecoder$2),height:optional$3(nonNegativeNumberDecoder$2),relativeTo:optional$3(nonEmptyStringDecoder$2),relativeDirection:optional$3(oneOf$1(constant$2("top"),constant$2("left"),constant$2("right"),constant$2("bottom"))),waitForAGMReady:optional$3(boolean$3()),forceChromeTab:optional$3(boolean$3()),layoutComponentId:optional$3(nonEmptyStringDecoder$2),channelId:optional$3(nonEmptyStringDecoder$2),startReason:optional$3(startReasonDecoder)}),appsImportOperationDecoder=object$2({definitions:array$3(allApplicationDefinitionsDecoder),mode:oneOf$1(constant$2("replace"),constant$2("merge"))}),appRemoveConfigDecoder=object$2({name:nonEmptyStringDecoder$2}),appsExportOperationDecoder=object$2({definitions:array$3(glueCoreAppDefinitionDecoder)}),appsRemoteRegistrationDecoder=object$2({definitions:array$3(allApplicationDefinitionsDecoder)});class ApplicationsController{glueController;sessionStorage;stateController;appDirectory;managerController;ioc;registry=CallbackRegistryFactory$2();config;connectionConfig;applicationStartTimeoutMs=15e3;managerAppsCheckCount=0;started=!1;defaultBounds;explicitClosingInstanceIds={};isManagerConfigured;locks={};operations={appHello:{name:"appHello",dataDecoder:appHelloDecoder,resultDecoder:appHelloSuccessDecoder$1,execute:this.handleAppHello.bind(this)},applicationStart:{name:"applicationStart",dataDecoder:applicationStartConfigDecoder,resultDecoder:instanceDataDecoder,execute:this.handleApplicationStart.bind(this)},instanceStop:{name:"instanceStop",dataDecoder:basicInstanceDataDecoder,execute:this.handleInstanceStop.bind(this)},registerWorkspaceApp:{name:"registerWorkspaceApp",dataDecoder:workspaceWindowDataDecoder,execute:this.registerWorkspaceApp.bind(this)},unregisterWorkspaceApp:{name:"unregisterWorkspaceApp",dataDecoder:simpleWindowDecoder,execute:this.unregisterWorkspaceApp.bind(this)},import:{name:"import",dataDecoder:appsImportOperationDecoder,execute:this.handleImport.bind(this)},remove:{name:"remove",dataDecoder:appRemoveConfigDecoder,execute:this.handleRemove.bind(this)},export:{name:"export",resultDecoder:appsExportOperationDecoder,execute:this.handleExport.bind(this)},clear:{name:"clear",execute:this.handleClear.bind(this)},registerRemoteApps:{name:"registerRemoteApps",dataDecoder:appsRemoteRegistrationDecoder,execute:this.handleRegisterRemoteApps.bind(this)},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)}};constructor(e,t,r,n,i,o){this.glueController=e,this.sessionStorage=t,this.stateController=r,this.appDirectory=n,this.managerController=i,this.ioc=o}get logger(){return logger.get("applications.controller")}handlePlatformShutdown(){this.managerAppsCheckCount=0,this.locks={},this.started=!1,this.appDirectory.stop()}async start(e){this.defaultBounds=e.windows.defaultWindowOpenBounds,this.logger?.trace("initializing applications"),this.config=e.applications,this.connectionConfig=e.connection,this.isManagerConfigured=!!e.manager?.url,await this.appDirectory.start({config:e.applications,appsStateChange:e=>this.emitStreamData("appDirectoryStateChange",e),sequelizer:this.ioc.createSequelizer(),isManagerConfigured:this.isManagerConfigured}),this.started=!0,this.stateController.onWindowDisappeared(e=>this.processInstanceClosed(e).catch(e=>this.logger?.warn(`error while processing instance closed: ${e?.message}`))),this.logger?.trace("initialization is completed")}async ready(){if(!this.isManagerConfigured)return;const e=this.managerController.getAllApps();await this.confirmApps(e)}async confirmApps(e){const t=this.glueController.clientGlue,r=e.every(e=>{const r=e.appId??e.name;return!!t.appManager.application(r)});return++this.managerAppsCheckCount,r?this.logger?.trace("all manager applications are loaded, proceeding"):this.managerAppsCheckCount>10?ioError.raiseError("not all manager applications are loaded after 10 checks, stopping the process"):(this.logger?.trace("not all manager applications are loaded, waiting for them to be loaded"),await wait(500),this.confirmApps(e))}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this windows control message, because the controller has not been started");const t=e.data,r=e.commandId,n=appManagerOperationTypesDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This appManager request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`AppManager request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`AppManager request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}handleClientUnloaded(e,t){if(this.logger?.trace(`handling unloading of ${e}`),e&&!this.explicitClosingInstanceIds[e])return!t||t.closed?(this.logger?.trace(`${e} detected as closed, processing instance closed`),void this.processInstanceClosed(e).catch(e=>this.logger?.warn(`error while processing instance closed: ${e.message}`))):void this.logger?.trace(`${e} detected as not closed, skipping instance closed procedure`)}async unregisterWorkspaceApp(e){this.sessionStorage.removeEjectedWindowId(e.windowId),this.ioc.windowsController.setExplicitClosingWindowId(e.windowId),this.explicitClosingInstanceIds[e.windowId]=!0,await this.processInstanceClosed(e.windowId),await this.ioc.windowsController.cleanUpWindow(e.windowId),this.ioc.portsBridge.removeGwClient(e.windowId)}async handleApplicationStart(e,t){this.logger?.trace(`[${t}] handling application start command for application: ${e.name}`);const r=new Date,n=(await this.appDirectory.getAll()).find(t=>t.name===e.name);if(!n)return ioError.raiseError(`Cannot start an instance of application: ${e.name}, because it is not found.`);if(checkIsOriginBlocked(n.createOptions.url,this.connectionConfig.blockList))return ioError.raiseError(`Cannot start an instance of application: ${e.name}, because its origin is blocked by the Platform`);const i={id:e.id??`g42-${nanoid$3(10)}`,applicationName:e.name},o=await this.getStartingBounds(n.createOptions,e,t),s=e.forceChromeTab?void 0:`left=${o.left},top=${o.top},width=${o.width},height=${o.height}`;this.logger?.trace(`[${t}] open arguments are valid, opening to bounds: ${s}`);const a=window.open(n.createOptions.url,i.id,s);if(!a)return ioError.raiseError(`Cannot start an instance with url: ${n.createOptions.url} for application: ${e.name}. The most likely reason is that the user has not approved popups or has a blocker.`);this.sessionStorage.saveBridgeInstanceData({windowId:i.id,appName:i.applicationName});const c={data:i,context:e.context};if(await this.processNewInstance(c),this.logger?.trace(`[${t}] the new window has been opened successfully with id: ${i.id}, checking for AGM ready and notifying windows`),e.waitForAGMReady&&(this.logger?.trace(`[${t}] wait for AGM is set, configuring the lock`),this.setLock(i.id)),await this.notifyWindows(n.createOptions.url,i,o,a,e.context,e.layoutComponentId,e.channelId),e.channelId&&this.sessionStorage.addWindowChannel(i.id,e.channelId),this.locks[i.id])try{await PromiseWrap(()=>this.locks[i.id]?.keyOne,this.applicationStartTimeoutMs)}catch(t){return delete this.locks[i.id],ioError.raiseError(`Application start for ${e.name} timed out waiting for client to initialize Glue`)}this.logger?.trace(`[${t}] the windows controller has been successfully notified`),this.logger?.trace(`[${t}] the new instance with id ${i.id} has been saved, announced and context set, lifting key two and responding to caller`),this.locks[i.id]?.openKeyTwo();const l=this.glueController.getLocalServers().find(({instance:e})=>i.id===e),u={start:r,end:new Date};return this.registry.execute("instance-started",{id:i.id,api:l?.api,applicationName:i.applicationName,startup:u}),i}onInstanceStarted(e){return"function"!=typeof e?ioError.raiseError("onInstanceStarted requires a single argument of type function"):this.registry.add("instance-started",e)}async processInstanceClosed(e){if(!e)return;const t=this.sessionStorage.getInstanceData(e);if(t){delete this.locks[t.id],this.sessionStorage.removeInstance(t.id);try{await this.glueController.clearContext(e,"instance")}catch(t){this.logger?.warn(`error while clearing the context of instance ${e}: ${t?.message}`)}this.emitStreamData("instanceStopped",t),await this.waitEventFlush(),delete this.explicitClosingInstanceIds[t.id]}}async notifyWindows(e,t,r,n,i,o,s){const a={windowId:t.id,name:`${t.applicationName}_${t.id}`,initialUrl:e,initialContext:i,initialBounds:r,layoutComponentId:o,initialChannelId:s};await this.ioc.windowsController.processNewWindow(a,i,n)}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}async handleAppHello(e,t){this.logger?.trace(`[${t}] handling hello message for id: ${e.windowId}`),e.windowId&&this.locks[e.windowId]&&(this.logger?.trace(`[${t}] found an app lock, unlocking key one and waiting for the second one`),this.locks[e.windowId].openKeyOne(),await this.locks[e.windowId].keyTwo,delete this.locks[e.windowId],this.logger?.trace(`[${t}] the lock is lifted, proceeding`));const r=this.sessionStorage.getAllInstancesData(),n=(await this.appDirectory.getAll()).map(e=>{const t=r.filter(t=>t.applicationName===e.name);return{...e,instances:t}});if(e.windowId){this.logger?.trace(`[${t}] there is a valid windowId, removing ${e.windowId} from the state controller`),this.stateController.remove(e.windowId);const r=n.find(t=>t.instances.some(t=>t.id===e.windowId)),i=!!this.sessionStorage.getWorkspaceClientById(e.windowId);if(r?.title&&!i){const n=e.windowId,i=r.title;PromiseWrap(()=>this.glueController.callWindow("windows",this.ioc.windowsController.setTitleOperation,{windowId:n,title:i},{windowId:n}),2e4).catch(e=>this.logger?.trace(`[${t}] error while setting the application instance title: ${e.message}`))}}if(!e.windowId){this.logger?.trace(`[${t}] no windowId was provided, returning all apps without initialChannelId`);return{apps:n}}const i=this.sessionStorage.getWindowDataById(e.windowId),o=this.sessionStorage.getWindowChannelData(e.windowId),s=o?o.channels?.[0]:i?.initialChannelId,a={apps:n,initialChannelId:s};return this.logger?.trace(`[${t}] compiled a list of all active applications and instances and returning it to the caller with initialChannelId: ${s}`),a}async handleInstanceStop(e,t){this.logger?.trace(`[${t}] handling stop command for instance: ${e.id}`);if(this.sessionStorage.getWorkspaceClientById(e.id))return this.logger?.trace(`[${t}] this instance is detected as a workspace window, closing via the workspaces controller`),void await this.ioc.workspacesController.closeItem({itemId:e.id},t);if(!this.sessionStorage.getInstanceData(e.id))return ioError.raiseError(`Cannot close instance: ${e.id}, because it is not known by the platform`);const r=this.sessionStorage.getWindowDataById(e.id);if(!r)return ioError.raiseError(`Cannot close instance: ${e.id}, because it's window is not known by the platform`);this.ioc.windowsController.setExplicitClosingWindowId(e.id),this.explicitClosingInstanceIds[e.id]=!0,window.open(void 0,r.windowId)?.close(),await this.processInstanceClosed(e.id),await this.ioc.windowsController.cleanUpWindow(e.id),this.logger?.trace(`[${t}] instance ${e.id} has been closed, removed from store, announced stopped and notified windows, responding to caller`)}async handleRegisterRemoteApps(e,t){if(this.logger?.trace(`[${t}] handling remote bypass command`),this.config.remote)return ioError.raiseError(`[${t}] cannot accept remote apps from the protocol, because there is an active remote configuration.`);await this.appDirectory.processAppDefinitions(e.definitions,{mode:"replace",type:"remote"}),this.logger?.trace(`[${t}] remote bypass command completed`)}async handleImport(e,t){this.logger?.trace(`[${t}] handling import command`),await this.appDirectory.processAppDefinitions(e.definitions,{type:"inmemory",mode:e.mode}),this.logger?.trace(`[${t}] import command completed`)}async handleRemove(e,t){this.logger?.trace(`[${t}] handling remove command for ${e.name}`);const r=await this.appDirectory.removeInMemory(e.name);r&&(this.logger?.trace(`definition ${r.name} removed successfully`),this.emitStreamData("appDirectoryStateChange",{appsRemoved:[r],appsAdded:[],appsChanged:[]}))}async handleExport(e,t){this.logger?.trace(`[${t}] handling export command`);const r=await this.appDirectory.exportInMemory();return this.logger?.trace(`[${t}] export command successful`),{definitions:r}}async handleClear(e,t){this.logger?.trace(`[${t}] handling clear command`),await this.appDirectory.processAppDefinitions([],{type:"inmemory",mode:"replace"}),this.logger?.trace(`[${t}] all in-memory apps are cleared`)}setLock(e){const t={},r=new Promise(e=>{t.openKeyOne=e}),n=new Promise(e=>{t.openKeyTwo=e});t.keyOne=r,t.keyTwo=n,this.locks[e]=t}async registerWorkspaceApp(e,t){if(!e.appName)return ioError.raiseError(`Cannot register application with config: ${JSON.stringify(e)}, because no app name was found`);const r=await this.appDirectory.getAll();if(e.appName===defaultNoAppWindowComponentAppName$1)return await this.ioc.windowsController.registerWorkspaceWindow(e,t);if(!r.some(t=>t.name===e.appName))return ioError.raiseError(`Cannot register application with config: ${JSON.stringify(e)}, because no app with this name name was found`);this.sessionStorage.removeEjectedWindowId(e.windowId),e.channelId&&this.sessionStorage.addWindowChannel(e.windowId,e.channelId),this.sessionStorage.saveBridgeInstanceData({windowId:e.windowId,appName:e.appName}),this.logger?.trace(`[${t}] processing valid workspace application registration with id ${e.windowId}, app name ${e.appName} and frame ${e.frameId}`),e.context&&await this.glueController.setStartContext(e.windowId,e.context,"instance");const n={id:e.windowId,applicationName:e.appName};this.sessionStorage.saveInstanceData(n),this.emitStreamData("instanceStarted",n),this.logger?.trace(`[${t}] instance registration is completed and announced, calling windows registration`),await this.ioc.windowsController.registerWorkspaceWindow(e,t)}async processNewInstance(e){e.context&&await this.glueController.setStartContext(e.data.id,e.context,"instance"),this.sessionStorage.saveInstanceData(e.data),this.emitStreamData("instanceStarted",e.data)}emitStreamData(e,t){this.logger?.trace(`sending notification of event: ${e} with data: ${JSON.stringify(t)}`),this.glueController.pushSystemMessage("appManager",e,t)}async getStartingBounds(e,t,r){const n={top:t.top??e.top??this.defaultBounds.top,left:t.left??e.left??this.defaultBounds.left,width:t.width??e.width??this.defaultBounds.width,height:t.height??e.height??this.defaultBounds.height};if(!t.relativeTo)return n;try{const e=await this.ioc.windowsController.getWindowBounds(t.relativeTo,r),i=t.relativeDirection??"right";return getRelativeBounds(n,e,i)}catch(e){return n}}waitEventFlush(){return new Promise(e=>setTimeout(e,10))}}const layoutsOperationTypesDecoder=oneOf$1(constant$2("get"),constant$2("getAll"),constant$2("export"),constant$2("import"),constant$2("remove"),constant$2("save"),constant$2("restore"),constant$2("rename"),constant$2("getGlobalPermissionState"),constant$2("checkGlobalActivated"),constant$2("requestGlobalPermission"),constant$2("operationCheck"),constant$2("getDefaultGlobal"),constant$2("setDefaultGlobal"),constant$2("clearDefaultGlobal"),constant$2("updateMetadata"),constant$2("getCurrent")),newLayoutOptionsDecoder=object$2({name:nonEmptyStringDecoder$2,context:optional$3(anyJson$2()),metadata:optional$3(anyJson$2()),instances:optional$3(array$3(nonEmptyStringDecoder$2)),ignoreInstances:optional$3(array$3(nonEmptyStringDecoder$2)),setAsCurrent:optional$3(boolean$3()),ignoreContexts:optional$3(boolean$3()),saveWindowContexts:optional$3(boolean$3())}),restoreOptionsDecoder=object$2({name:nonEmptyStringDecoder$2,context:optional$3(anyJson$2()),closeRunningInstance:optional$3(boolean$3()),closeMe:optional$3(boolean$3()),timeout:optional$3(nonNegativeNumberDecoder$2)}),simpleLayoutConfigDecoder=object$2({name:nonEmptyStringDecoder$2,type:layoutTypeDecoder}),getAllLayoutsConfigDecoder=object$2({type:layoutTypeDecoder}),saveLayoutConfigDecoder=object$2({layout:newLayoutOptionsDecoder}),renameLayoutConfigDecoder=object$2({layout:glueLayoutDecoder,newName:nonEmptyStringDecoder$2}),layoutResultDecoder=object$2({status:nonEmptyStringDecoder$2}),updateLayoutMetadataConfigDecoder=object$2({layout:glueLayoutDecoder}),restoreLayoutConfigDecoder=object$2({layout:restoreOptionsDecoder}),allLayoutsFullConfigDecoder=object$2({layouts:array$3(glueLayoutDecoder)}),importModeDecoder=oneOf$1(constant$2("replace"),constant$2("merge")),layoutsImportConfigDecoder=object$2({layouts:array$3(glueLayoutDecoder),mode:importModeDecoder,skipManagerRequest:optional$3(boolean$3())}),allLayoutsSummariesResultDecoder=object$2({summaries:array$3(layoutSummaryDecoder$1)});object$2({layout:glueLayoutDecoder});const optionalSimpleLayoutResult=object$2({layout:optional$3(glueLayoutDecoder)}),setDefaultGlobalConfigDecoder=object$2({name:nonEmptyStringDecoder$2});object$2({layoutType:oneOf$1(constant$2("Global"),constant$2("Workspace")),layoutName:nonEmptyStringDecoder$2,context:optional$3(anyJson$2()),instances:optional$3(array$3(nonEmptyStringDecoder$2)),ignoreInstances:optional$3(array$3(nonEmptyStringDecoder$2))}),object$2({windowContext:optional$3(anyJson$2())});const fullSaveRequestResponseDecoder=object$2({bounds:windowBoundsDecoder,windowContext:optional$3(anyJson$2()),url:nonEmptyStringDecoder$2,name:nonEmptyStringDecoder$2,application:nonEmptyStringDecoder$2,windowId:nonEmptyStringDecoder$2,initialContext:optional$3(anyJson$2())});object$2({windowContext:optional$3(anyJson$2()),windowId:nonEmptyStringDecoder$2,frameId:nonEmptyStringDecoder$2}),object$2({windows:array$3(fullSaveRequestResponseDecoder)});const permissionStateResultDecoder=object$2({state:oneOf$1(constant$2("prompt"),constant$2("denied"),constant$2("granted"))}),simpleAvailabilityResultDecoder=object$2({isAvailable:boolean$3()}),defaultNoAppWindowComponentAppName="no-app-window",defaultPermissionTimeoutMS=25e3,defaultRestHeaders$1={"Content-Type":"application/json",Accept:"application/json"},defaultRestRequestTimeoutMS$1=3e4,layoutEventOperations={added:"layoutAdded",changed:"layoutChanged",removed:"layoutRemoved",renamed:"layoutRenamed"},getWindowManagementPermissionStatus=async e=>{try{return await navigator.permissions.query({name:"window-management"})}catch(t){e?.warn(extractErrorMsg$1(t));return await navigator.permissions.query({name:"window-placement"})}};class LayoutsController{glueController;globalBuilder;globalRestorer;localStore;managerStore;restStore;sessionStore;registry=CallbackRegistryFactory$2();unsubFuncs=[];started=!1;store;operations={get:{name:"get",dataDecoder:simpleLayoutConfigDecoder,resultDecoder:optionalSimpleLayoutResult,execute:this.handleGetLayout.bind(this)},getAll:{name:"getAll",dataDecoder:getAllLayoutsConfigDecoder,resultDecoder:allLayoutsSummariesResultDecoder,execute:this.handleGetAll.bind(this)},getCurrent:{name:"getCurrent",resultDecoder:optionalSimpleLayoutResult,execute:this.handleGetCurrentLayout.bind(this)},export:{name:"export",dataDecoder:getAllLayoutsConfigDecoder,resultDecoder:allLayoutsFullConfigDecoder,execute:this.handleExport.bind(this)},import:{name:"import",dataDecoder:layoutsImportConfigDecoder,execute:this.handleImport.bind(this)},remove:{name:"remove",dataDecoder:simpleLayoutConfigDecoder,execute:this.handleRemove.bind(this)},rename:{name:"rename",dataDecoder:renameLayoutConfigDecoder,resultDecoder:layoutResultDecoder,execute:this.handleRename.bind(this)},save:{name:"save",dataDecoder:saveLayoutConfigDecoder,execute:this.handleSave.bind(this)},restore:{name:"restore",dataDecoder:restoreLayoutConfigDecoder,execute:this.handleRestore.bind(this)},getGlobalPermissionState:{name:"getGlobalPermissionState",resultDecoder:permissionStateResultDecoder,execute:this.handleGetGlobalPermissionState.bind(this)},requestGlobalPermission:{name:"requestGlobalPermission",resultDecoder:simpleAvailabilityResultDecoder,execute:this.handleRequestGlobalPermission.bind(this)},checkGlobalActivated:{name:"checkGlobalActivated",resultDecoder:simpleAvailabilityResultDecoder,execute:this.handleCheckGlobalActivated.bind(this)},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)},getDefaultGlobal:{name:"getDefaultGlobal",resultDecoder:optionalSimpleLayoutResult,execute:this.handleGetDefaultGlobal.bind(this)},setDefaultGlobal:{name:"setDefaultGlobal",dataDecoder:setDefaultGlobalConfigDecoder,execute:this.handleSetDefaultGlobal.bind(this)},clearDefaultGlobal:{name:"clearDefaultGlobal",execute:this.handleClearDefaultGlobal.bind(this)},updateMetadata:{name:"updateMetadata",dataDecoder:updateLayoutMetadataConfigDecoder,execute:this.handleUpdateMetadata.bind(this)}};constructor(e,t,r,n,i,o,s){this.glueController=e,this.globalBuilder=t,this.globalRestorer=r,this.localStore=n,this.managerStore=i,this.restStore=o,this.sessionStore=s}get logger(){return logger.get("layouts.controller")}handlePlatformShutdown(){this.started=!1,this.unsubFuncs.forEach(e=>e()),this.unsubFuncs=[],this.store.stop()}async start(e){this.store=this.getStore(e),this.setupStoreListeners(),await this.store.start(e),this.started=!0,this.logger?.trace("initialization is completed")}ready(){return Promise.resolve()}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this windows control message, because the controller has not been started");const t=e.data,r=e.commandId,n=layoutsOperationTypesDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This layouts request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`Layouts request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r,e.callerId,e.callerType),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`Layouts request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}async handleSave(e,t){this.logger?.trace(`[${t}] handling save layout with config: ${JSON.stringify(e)}`),await this.checkRequestPermission("save"),this.logger?.trace(`[${t}] the required permissions are granted, proceeding.`);const r=await this.globalBuilder.saveGlobalLayout(e,t);return(e.layout.setAsCurrent??!0)&&this.sessionStore.setLayoutsSystemData({currentLayoutName:r.name}),this.logger?.trace(`[${t}] layout ${e.layout.name} was saved successfully`),{layout:r}}async handleRestore(e,t,r,n){this.logger?.trace(`[${t}] handling restore layout with config: ${JSON.stringify(e)}`),await this.checkRequestPermission("restore",e.layout.timeout);const i=new Date,o=await this.get("Global",e.layout.name,t);if(!o)return ioError.raiseError(`Layout with name "${e.layout.name}" and type: "Global" cannot be found`);await this.globalRestorer.restoreGlobalLayout(e,t,r,n);const s=new Date;this.registry.execute("layout-restored",{layoutName:e.layout.name,startTime:i,endTime:s}),await this.emitData({operation:"layoutRestored",layout:o}),this.logger?.trace(`[${t}] layout ${e.layout.name} was restored successfully`)}onLayoutRestored(e){return"function"!=typeof e?ioError.raiseError("onLayoutRestored requires a single argument of type function"):this.registry.add("layout-restored",e)}async handleGetAll(e,t){this.logger?.trace(`[${t}] handling get all layout summaries request for type: ${e.type}`);const r=(await this.store.getAllLayouts(e.type,t)).map(e=>({name:e.name,type:e.type,context:e.context,metadata:e.metadata}));return this.logger?.trace(`[${t}] all summaries have been compiled, responding to caller`),{summaries:r}}async handleGetCurrentLayout(e,t){this.logger?.trace(`[${t}] handling get current layout request`);const{currentLayoutName:r}=this.sessionStore.getLayoutsSystemData(),n=r?await this.get("Global",r,t):void 0;return this.logger?.trace(`[${t}] request completed, responding to the caller with layout with name: ${r}`),{layout:n}}async handleExport(e,t){this.logger?.trace(`[${t}] handling get all layout full request for type: ${e.type}`);const r=await this.store.getAllLayouts(e.type,t);return this.logger?.trace(`[${t}] full layouts collection have been compiled, responding to caller`),{layouts:r}}async handleImport(e,t){this.logger?.trace(`[${t}] handling mass import request for layout names: ${e.layouts.map(e=>e.name).join(", ")}`);const r=e.layouts.filter(e=>"Workspace"===e.type),n=e.layouts.filter(e=>"Global"===e.type).map(e=>({...e,token:e.token??generateLayoutToken()}));await this.store.saveLayouts(r,n,e.mode,t),this.logger?.trace(`[${t}] mass import completed, responding to caller`)}async handleRemove(e,t){this.logger?.trace(`[${t}] handling remove request for ${JSON.stringify(e)}`);const r=await this.get(e.type,e.name,t);r?(await this.store.deleteLayout(r,t),this.logger?.trace(`[${t}] layout with name "${e.name}" and type: "${e.type}" has been removed`)):this.logger?.trace(`[${t}] layout with name "${e.name}" and type: "${e.type}" cannot be found and therefore cannot be removed`)}async handleRename(e,t){this.logger?.trace(`[${t}] handling rename request for ${JSON.stringify(e)}`);const r=e.layout.name;if(e.newName===r)return this.logger?.trace(`[${t}] The provided new layout name ${e.newName} is the same as the current one.`),{status:"Success"};const n=await this.get(e.layout.type,r,t);if(!n){const n=`layout with name "${r}" and type: "${e.layout.type}" cannot be found`;return this.logger?.trace(`[${t}] ${n}`),{status:n}}return await this.store.renameLayout(n,e.newName,t)}async handleUpdateMetadata(e,t){this.logger?.trace(`[${t}] handling update metadata request for ${JSON.stringify(e)}`);const r=await this.get(e.layout.type,e.layout.name,t);if(!r)return ioError.raiseError(`Layout with name "${e.layout.name}" and type: "${e.layout.type}" cannot be found`);const n={...r,metadata:e.layout.metadata};return"Global"===r.type?await this.store.saveLayouts([],[n],"merge",t):await this.store.saveLayouts([n],[],"merge",t)}async handleGetLayout(e,t){this.logger?.trace(`[${t}] handling get layout request for name: ${e.name} and type: ${e.type}`);const r=(await this.store.getAllLayouts(e.type,t)).find(t=>t.name===e.name);return this.logger?.trace(`[${t}] request completed, responding to the caller`),{layout:r}}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}async handleGetGlobalPermissionState(e,t){this.logger?.trace(`[${t}] handling Get Global Permission State request`);const{state:r}=await getWindowManagementPermissionStatus(this.logger);return this.logger?.trace(`[${t}] request completed with state: ${r}, responding to the caller`),{state:r}}async handleRequestGlobalPermission(e,t){this.logger?.trace(`[${t}] handling Request Global Permission command`);const{state:r}=await getWindowManagementPermissionStatus(this.logger);if("granted"===r)return{isAvailable:!0};if("denied"===r)return{isAvailable:!1};try{return await window.getScreenDetails(),this.logger?.trace(`[${t}] request completed, responding to the caller`),{isAvailable:!0}}catch(e){return this.logger?.trace(`[${t}] request completed, responding to the caller`),{isAvailable:!1}}}async handleCheckGlobalActivated(e,t){return this.logger?.trace(`[${t}] handling Check Global Activated request`),this.logger?.trace(`[${t}] request completed, responding to the caller`),{isAvailable:!0}}async handleGetDefaultGlobal(e,t){this.logger?.trace(`[${t}] handling Get Default Global request`);return{layout:await this.store.getDefaultLayout(t)}}async handleSetDefaultGlobal(e,t){this.logger?.trace(`[${t}] handling Set Default Global request for name: ${e.name}`);const r=(await this.store.getAllLayouts("Global",t)).find(t=>t.name===e.name);if(!r)return ioError.raiseError(`Layout ${e.name} does not exist`);await this.store.setDefaultLayout(e.name,t),await this.emitData({operation:"defaultLayoutChanged",layout:{name:r.name}})}async handleClearDefaultGlobal(e,t){this.logger?.trace(`[${t}] handling Clear Default Global request`),await this.store.clearDefaultLayout(t),await this.emitData({operation:"defaultLayoutChanged"}),this.logger?.trace(`[${t}] request completed, responding to the caller`)}updateCurrentLayoutIfNeeded(e){if("Global"!==e.layout.type)return;const t=this.sessionStore.getLayoutsSystemData(),r=e.operation===layoutEventOperations.renamed&&t.currentLayoutName===e.layout.prevName,n=e.operation===layoutEventOperations.removed&&t.currentLayoutName===e.layout.name;(r||n)&&(r&&(t.currentLayoutName=e.layout.name),n&&(t.currentLayoutName=void 0),this.sessionStore.setLayoutsSystemData(t))}async emitData(e){this.logger?.trace(`sending notification of event: ${e.operation} with data: ${JSON.stringify(e)}`),this.glueController.pushSystemMessage("layouts",e.operation,e.layout)}async announceEvents(e){let t=0;for(const r of e)++t,t%10==0&&await this.waitEventFlush(),await this.emitData(r)}async get(e,t,r){return(await this.store.getAllLayouts(e,r)).find(r=>r.name===t&&r.type===e)}waitEventFlush(){return new Promise(e=>setTimeout(e,10))}async checkRequestPermission(e,t=defaultPermissionTimeoutMS){if(window.gtf)return;const{state:r}=await getWindowManagementPermissionStatus(this.logger);switch(r){case"granted":return;case"prompt":try{return void await PromiseWrap(()=>window.getScreenDetails(),t,"Timeout waiting for user permission for Multi-Screen Window Placement")}catch(t){return ioError.raiseError(`Cannot complete operation ${e} for Global Layouts, because the user has not granted the Multi-Screen Window Placement permission`)}case"denied":return ioError.raiseError(`Cannot complete operation ${e} for Global Layouts, because the user has denied the Multi-Screen Window Placement permission`)}}setupStoreListeners(){const e=this.store.onLayoutsAdded(e=>{this.announceEvents(e.map(e=>({operation:layoutEventOperations.added,layout:e}))).catch(e=>this.logger?.warn(extractErrorMsg$1(e)))}),t=this.store.onLayoutsChanged(e=>{this.announceEvents(e.map(e=>({operation:layoutEventOperations.changed,layout:e}))).catch(e=>this.logger?.warn(extractErrorMsg$1(e)))}),r=this.store.onLayoutsRemoved(e=>{const t=layoutEventOperations.removed;this.announceEvents(e.map(e=>({operation:t,layout:e}))).catch(e=>this.logger?.warn(extractErrorMsg$1(e))),e.forEach(e=>this.updateCurrentLayoutIfNeeded({operation:t,layout:e}))}),n=this.store.onLayoutsRenamed(e=>{const t=layoutEventOperations.renamed;this.announceEvents(e.map(e=>({operation:t,layout:e}))).catch(e=>this.logger?.warn(extractErrorMsg$1(e))),e.forEach(e=>this.updateCurrentLayoutIfNeeded({operation:t,layout:e}))});this.unsubFuncs.push(e,t,r,n)}getStore(e){const t=e.layouts?.mode,r=!(!e?.manager?.url||!e?.manager?.features?.layoutsStore),n=!!e?.layouts?.rest?.url;return!t&&r?this.managerStore:!t&&n?this.restStore:t||r?"idb"===t||"session"===t?(this.checkForConflictingLocalSettings(n),this.localStore):"rest"===t&&n?this.restStore:"rest"!==t||n?"manager"===t&&r?this.managerStore:"manager"!==t||r?ioError.raiseError("Cannot set layouts store."):ioError.raiseError("The layouts store is configured to be managed, but the manager is not configured."):ioError.raiseError("The layouts store is configured to be rest, but the rest url is not configured."):this.localStore}checkForConflictingLocalSettings(e){if(e)return ioError.raiseError("Layouts store is configured to be local, but the rest url is also configured. Please either remove de-config rest or set the layouts store to be rest.")}}const instanceOfAny=(e,t)=>t.some(t=>e instanceof t);let idbProxyableTypes,cursorAdvanceMethods;function getIdbProxyableTypes(){return idbProxyableTypes||(idbProxyableTypes=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function getCursorAdvanceMethods(){return cursorAdvanceMethods||(cursorAdvanceMethods=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const cursorRequestMap=new WeakMap,transactionDoneMap=new WeakMap,transactionStoreNamesMap=new WeakMap,transformCache=new WeakMap,reverseTransformCache=new WeakMap;function promisifyRequest(e){const t=new Promise((t,r)=>{const n=()=>{e.removeEventListener("success",i),e.removeEventListener("error",o)},i=()=>{t(wrap(e.result)),n()},o=()=>{r(e.error),n()};e.addEventListener("success",i),e.addEventListener("error",o)});return t.then(t=>{t instanceof IDBCursor&&cursorRequestMap.set(t,e)}).catch(()=>{}),reverseTransformCache.set(t,e),t}function cacheDonePromiseForTransaction(e){if(transactionDoneMap.has(e))return;const t=new Promise((t,r)=>{const n=()=>{e.removeEventListener("complete",i),e.removeEventListener("error",o),e.removeEventListener("abort",o)},i=()=>{t(),n()},o=()=>{r(e.error||new DOMException("AbortError","AbortError")),n()};e.addEventListener("complete",i),e.addEventListener("error",o),e.addEventListener("abort",o)});transactionDoneMap.set(e,t)}let idbProxyTraps={get(e,t,r){if(e instanceof IDBTransaction){if("done"===t)return transactionDoneMap.get(e);if("objectStoreNames"===t)return e.objectStoreNames||transactionStoreNamesMap.get(e);if("store"===t)return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return wrap(e[t])},set:(e,t,r)=>(e[t]=r,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function replaceTraps(e){idbProxyTraps=e(idbProxyTraps)}function wrapFunction(e){return e!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?getCursorAdvanceMethods().includes(e)?function(...t){return e.apply(unwrap(this),t),wrap(cursorRequestMap.get(this))}:function(...t){return wrap(e.apply(unwrap(this),t))}:function(t,...r){const n=e.call(unwrap(this),t,...r);return transactionStoreNamesMap.set(n,t.sort?t.sort():[t]),wrap(n)}}function transformCachableValue(e){return"function"==typeof e?wrapFunction(e):(e instanceof IDBTransaction&&cacheDonePromiseForTransaction(e),instanceOfAny(e,getIdbProxyableTypes())?new Proxy(e,idbProxyTraps):e)}function wrap(e){if(e instanceof IDBRequest)return promisifyRequest(e);if(transformCache.has(e))return transformCache.get(e);const t=transformCachableValue(e);return t!==e&&(transformCache.set(e,t),reverseTransformCache.set(t,e)),t}const unwrap=e=>reverseTransformCache.get(e);function openDB(e,t,{blocked:r,upgrade:n,blocking:i,terminated:o}={}){const s=indexedDB.open(e,t),a=wrap(s);return n&&s.addEventListener("upgradeneeded",e=>{n(wrap(s.result),e.oldVersion,e.newVersion,wrap(s.transaction),e)}),r&&s.addEventListener("blocked",e=>r(e.oldVersion,e.newVersion,e)),a.then(e=>{o&&e.addEventListener("close",()=>o()),i&&e.addEventListener("versionchange",e=>i(e.oldVersion,e.newVersion,e))}).catch(()=>{}),a}function deleteDB(e,{blocked:t}={}){const r=indexedDB.deleteDatabase(e);return t&&r.addEventListener("blocked",e=>t(e.oldVersion,e)),wrap(r).then(()=>{})}const readMethods=["get","getKey","getAll","getAllKeys","count"],writeMethods=["put","add","delete","clear"],cachedMethods=new Map;function getMethod(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(cachedMethods.get(t))return cachedMethods.get(t);const r=t.replace(/FromIndex$/,""),n=t!==r,i=writeMethods.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!i&&!readMethods.includes(r))return;const o=async function(e,...t){const o=this.transaction(e,i?"readwrite":"readonly");let s=o.store;return n&&(s=s.index(t.shift())),(await Promise.all([s[r](...t),i&&o.done]))[0]};return cachedMethods.set(t,o),o}replaceTraps(e=>({...e,get:(t,r,n)=>getMethod(t,r)||e.get(t,r,n),has:(t,r)=>!!getMethod(t,r)||e.has(t,r)}));class IDBController{_database;defaultDBName="glue42core";dbName=this.defaultDBName;dbVersion=3;globalLayoutsObjectStoreName="globalLayouts";prefsObjectStoreName="prefs";serviceWorkerObjectStoreName="serviceWorker";workspaceLayoutsObjectStoreName="workspaceLayouts";constructor(){"indexedDB"in window||ioError.raiseError("Cannot initialize the local storage, because IndexedDB is not supported")}get database(){return this._database?this._database:ioError.raiseError("There is no open database")}async start(e){e?.id&&(this.dbName=e?.id);const t=await openDB(this.dbName,this.dbVersion,{upgrade:this.setUpDB.bind(this)});this._database=t}stop(){this.database.close(),delete this._database,this.dbName=this.defaultDBName}getAllLayouts(e){const t=this.getLayoutsObjectStoreName(e);return this.database.getAll(t)}deleteLayout(e,t){const r=this.getLayoutsObjectStoreName(t);return this.database.delete(r,e)}clearLayouts(e){const t=this.getLayoutsObjectStoreName(e);return this.database.clear(t)}getLayout(e,t){const r=this.getLayoutsObjectStoreName(t);return this.database.get(r,e)}storeLayout(e){runDecoderWithIOError(glueLayoutDecoder,e);const t=this.getLayoutsObjectStoreName(e.type);return this.database.put(t,e,e.name)}async renameLayout(e,t){runDecoderWithIOError(glueLayoutDecoder,e);const r=this.getLayoutsObjectStoreName(e.type),n=this.database.transaction(r,"readwrite");await Promise.all([n.store.delete(t),n.store.put(e,e.name),n.done])}getLayoutsObjectStoreName(e){switch(e){case"Workspace":return this.workspaceLayoutsObjectStoreName;case"Global":return this.globalLayoutsObjectStoreName;default:return ioError.raiseError(`The provided layout type is not recognized: ${e}`)}}clearServiceWorker(){return this.database.clear(this.serviceWorkerObjectStoreName)}storeServiceWorker(e){return this.database.put(this.serviceWorkerObjectStoreName,e,"workerData")}async clearAllPrefs(e){const t=(await this.getAllPrefs()).map(({app:t})=>({app:t,data:{},lastUpdate:e})),r=this.database.transaction(this.prefsObjectStoreName,"readwrite");return await Promise.all([...t.map(e=>r.store.put(e,e.app)),r.done]),t}getAllPrefs(){return this.database.getAll(this.prefsObjectStoreName)}getPrefs(e){return this.database.get(this.prefsObjectStoreName,e)}deletePrefs(e){return this.database.delete(this.prefsObjectStoreName,e)}async replaceAllPrefs(e){const t=this.database.transaction(this.prefsObjectStoreName,"readwrite");return await t.store.clear(),await Promise.all([...e.map(e=>t.store.put(e,e.app)),t.done]),e}async setPrefs(e){return await this.database.put(this.prefsObjectStoreName,e,e.app),e}async updatePrefs(e){const t=await this.database.get(this.prefsObjectStoreName,e.app),r=t?{app:e.app,data:{...t.data,...e.data},lastUpdate:e.lastUpdate}:e;return this.setPrefs(r)}setUpDB(e){e.objectStoreNames.contains(this.workspaceLayoutsObjectStoreName)||e.createObjectStore(this.workspaceLayoutsObjectStoreName),e.objectStoreNames.contains(this.globalLayoutsObjectStoreName)||e.createObjectStore(this.globalLayoutsObjectStoreName),e.objectStoreNames.contains(this.serviceWorkerObjectStoreName)||e.createObjectStore(this.serviceWorkerObjectStoreName),e.objectStoreNames.contains(this.prefsObjectStoreName)||e.createObjectStore(this.prefsObjectStoreName)}}const defaultLoadingConfig={defaultStrategy:"direct",delayed:{batch:1,initialOffsetInterval:1e3,interval:5e3},showDelayedIndicator:!1};class WorkspacesController{framesController;glueController;stateController;hibernationWatcher;sequelizer;sessionStorageController;ioc;registry=CallbackRegistryFactory$2();_started=!1;settings;defaultWindowOpenBounds;connectionConfig;operations={frameHello:{name:"frameHello",dataDecoder:frameHelloDecoder,execute:this.handleFrameHello.bind(this)},isWindowInWorkspace:{name:"isWindowInWorkspace",dataDecoder:simpleItemConfigDecoder,resultDecoder:isWindowInSwimlaneResultDecoder,execute:this.isWindowInWorkspace.bind(this)},createWorkspace:{name:"createWorkspace",dataDecoder:workspaceCreateConfigDecoder,resultDecoder:workspaceSnapshotResultDecoder,execute:this.createWorkspace.bind(this)},createFrame:{name:"createFrame",resultDecoder:frameSummaryResultDecoder,execute:this.createFrame.bind(this)},initFrame:{name:"initFrame",resultDecoder:voidResultDecoder,execute:this.initFrame.bind(this)},getAllFramesSummaries:{name:"getAllFramesSummaries",resultDecoder:frameSummariesResultDecoder,execute:this.getAllFramesSummaries.bind(this)},getFrameSummary:{name:"getFrameSummary",dataDecoder:getFrameSummaryConfigDecoder,resultDecoder:frameSummaryDecoder,execute:this.getFrameSummary.bind(this)},getAllWorkspacesSummaries:{name:"getAllWorkspacesSummaries",resultDecoder:workspaceSummariesResultDecoder,execute:this.getAllWorkspacesSummaries.bind(this)},getWorkspaceSnapshot:{name:"getWorkspaceSnapshot",dataDecoder:simpleItemConfigDecoder,resultDecoder:workspaceSnapshotResultDecoder,execute:this.getWorkspaceSnapshot.bind(this)},getAllLayoutsSummaries:{name:"getAllLayoutsSummaries",resultDecoder:layoutSummariesDecoder,execute:this.getAllLayoutsSummaries.bind(this)},openWorkspace:{name:"openWorkspace",dataDecoder:openWorkspaceConfigDecoder,resultDecoder:workspaceSnapshotResultDecoder,execute:this.openWorkspace.bind(this)},deleteLayout:{name:"deleteLayout",dataDecoder:deleteLayoutConfigDecoder,resultDecoder:voidResultDecoder,execute:this.deleteLayout.bind(this)},saveLayout:{name:"saveLayout",dataDecoder:workspaceLayoutSaveConfigDecoder,resultDecoder:workspaceLayoutDecoder,execute:this.saveLayout.bind(this)},importLayout:{name:"importLayout",dataDecoder:workspacesLayoutImportConfigDecoder,resultDecoder:voidResultDecoder,execute:this.importLayout.bind(this)},exportAllLayouts:{name:"exportAllLayouts",resultDecoder:exportedLayoutsResultDecoder,execute:this.exportAllLayouts.bind(this)},restoreItem:{name:"restoreItem",dataDecoder:simpleItemConfigDecoder,resultDecoder:voidResultDecoder,execute:this.restoreItem.bind(this)},maximizeItem:{name:"maximizeItem",dataDecoder:simpleItemConfigDecoder,resultDecoder:voidResultDecoder,execute:this.maximizeItem.bind(this)},focusItem:{name:"focusItem",dataDecoder:simpleItemConfigDecoder,resultDecoder:voidResultDecoder,execute:this.focusItem.bind(this)},closeItem:{name:"closeItem",dataDecoder:simpleItemConfigDecoder,resultDecoder:voidResultDecoder,execute:this.closeItem.bind(this)},closeWorkspace:{name:"closeWorkspace",dataDecoder:simpleItemConfigDecoder,resultDecoder:voidResultDecoder,execute:this.closeWorkspace.bind(this)},resizeItem:{name:"resizeItem",dataDecoder:resizeItemConfigDecoder,resultDecoder:voidResultDecoder,execute:this.resizeItem.bind(this)},changeFrameState:{name:"changeFrameState",dataDecoder:frameStateConfigDecoder,resultDecoder:voidResultDecoder,execute:this.changeFrameState.bind(this)},getFrameState:{name:"getFrameState",dataDecoder:simpleItemConfigDecoder,resultDecoder:frameStateResultDecoder,execute:this.getFrameState.bind(this)},getFrameBounds:{name:"getFrameBounds",dataDecoder:simpleItemConfigDecoder,resultDecoder:frameBoundsResultDecoder,execute:this.getFrameBounds.bind(this)},moveFrame:{name:"moveFrame",dataDecoder:moveFrameConfigDecoder,resultDecoder:voidResultDecoder,execute:this.moveFrame.bind(this)},getFrameSnapshot:{name:"getFrameSnapshot",dataDecoder:frameSnapshotConfigDecoder,resultDecoder:frameSnapshotResultDecoder,execute:this.getFrameSnapshot.bind(this)},forceLoadWindow:{name:"forceLoadWindow",dataDecoder:simpleItemConfigDecoder,resultDecoder:simpleWindowOperationSuccessResultDecoder,execute:this.forceLoadWindow.bind(this)},ejectWindow:{name:"ejectWindow",dataDecoder:ejectWindowDataDecoder,resultDecoder:simpleWindowOperationSuccessResultDecoder,execute:this.ejectWindow.bind(this)},setItemTitle:{name:"setItemTitle",dataDecoder:setItemTitleConfigDecoder,resultDecoder:voidResultDecoder,execute:this.setItemTitle.bind(this)},moveWindowTo:{name:"moveWindowTo",dataDecoder:moveWindowConfigDecoder,resultDecoder:voidResultDecoder,execute:this.moveWindowTo.bind(this)},addWindow:{name:"addWindow",dataDecoder:addWindowConfigDecoder,resultDecoder:addItemResultDecoder,execute:this.addWindow.bind(this)},addContainer:{name:"addContainer",dataDecoder:addContainerConfigDecoder,resultDecoder:addItemResultDecoder,execute:this.addContainer.bind(this)},bundleWorkspace:{name:"bundleWorkspace",dataDecoder:bundleWorkspaceConfigDecoder,resultDecoder:voidResultDecoder,execute:this.bundleWorkspace.bind(this)},bundleItem:{name:"bundleItem",dataDecoder:bundleItemConfigDecoder,resultDecoder:voidResultDecoder,execute:this.bundleItem.bind(this)},hibernateWorkspace:{name:"hibernateWorkspace",dataDecoder:workspaceSelectorDecoder,resultDecoder:voidResultDecoder,execute:this.hibernateWorkspace.bind(this)},resumeWorkspace:{name:"resumeWorkspace",dataDecoder:workspaceSelectorDecoder,resultDecoder:voidResultDecoder,execute:this.resumeWorkspace.bind(this)},getWorkspacesConfig:{name:"getWorkspacesConfig",resultDecoder:workspacesConfigDecoder,execute:this.getWorkspacesConfiguration.bind(this)},lockWorkspace:{name:"lockWorkspace",dataDecoder:lockWorkspaceDecoder,resultDecoder:voidResultDecoder,execute:this.lockWorkspace.bind(this)},lockWindow:{name:"lockWindow",dataDecoder:lockWindowDecoder,resultDecoder:voidResultDecoder,execute:this.lockWindow.bind(this)},lockContainer:{name:"lockContainer",dataDecoder:lockContainerDecoder,resultDecoder:voidResultDecoder,execute:this.lockContainer.bind(this)},pinWorkspace:{name:"pinWorkspace",dataDecoder:pinWorkspaceDecoder,resultDecoder:voidResultDecoder,execute:this.pinWorkspace.bind(this)},unpinWorkspace:{name:"unpinWorkspace",dataDecoder:workspaceSelectorDecoder,resultDecoder:voidResultDecoder,execute:this.unpinWorkspace.bind(this)},getWorkspaceIcon:{name:"getWorkspaceIcon",dataDecoder:workspaceSelectorDecoder,resultDecoder:workspaceIconDecoder,execute:this.getWorkspaceIcon.bind(this)},setWorkspaceIcon:{name:"setWorkspaceIcon",dataDecoder:setWorkspaceIconDecoder,resultDecoder:voidResultDecoder,execute:this.setWorkspaceIcon.bind(this)},checkStarted:{name:"checkStarted",execute:this.handleCheckStarted.bind(this)},getPlatformFrameId:{name:"getPlatformFrameId",execute:this.handleGetPlatformFrameId.bind(this)},getWorkspacesLayouts:{name:"getWorkspacesLayouts",dataDecoder:getWorkspacesLayoutsConfigDecoder,resultDecoder:getWorkspacesLayoutsResponseDecoder,execute:this.handleGetWorkspacesLayouts.bind(this)},getWorkspaceWindowsOnLayoutSaveContext:{name:"getWorkspaceWindowsOnLayoutSaveContext",dataDecoder:getWorkspaceWindowsOnLayoutSaveContextConfigDecoder,resultDecoder:getWorkspaceWindowsOnLayoutSaveContextResult,execute:this.handleGetWorkspaceWindowsOnLayoutSaveContext.bind(this)},setMaximizationBoundary:{name:"setMaximizationBoundary",dataDecoder:setMaximizationBoundaryConfigDecoder,resultDecoder:voidResultDecoder,execute:this.handleSetMaximizationBoundary.bind(this)},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)},getWorkspaceWindowFrameBounds:{name:"getWorkspaceWindowFrameBounds",resultDecoder:frameBoundsResultDecoder,dataDecoder:simpleItemConfigDecoder,execute:this.getWorkspaceWindowFrameBounds.bind(this)},focusChange:{name:"focusChange",dataDecoder:focusEventDataDecoder,execute:this.handleFocusEvent.bind(this)},bringBackToWorkspace:{name:"bringBackToWorkspace",dataDecoder:bringBackToWorkspaceDataDecoder,execute:this.handleBringBackToWorkspace.bind(this)},showChannelsLink:{name:"showChannelsLink",dataDecoder:showChannelsLinkDecoder,resultDecoder:voidResultDecoder,execute:this.showChannelsLink.bind(this)}};constructor(e,t,r,n,i,o,s){this.framesController=e,this.glueController=t,this.stateController=r,this.hibernationWatcher=n,this.sequelizer=i,this.sessionStorageController=o,this.ioc=s}get started(){return this._started}set started(e){this._started=e}handlePlatformShutdown(){this.started=!1,this.hibernationWatcher.stop(),this.framesController.stop()}async start(e){e.workspaces?(this.connectionConfig=e.connection,this.settings=this.applyDefaults(e.workspaces),this.defaultWindowOpenBounds=e.windows.defaultWindowOpenBounds,this.settings.hibernation&&this.hibernationWatcher.start(this,this.settings.hibernation),await Promise.all([this.glueController.createWorkspacesStream(),this.glueController.createWorkspacesEventsReceiver(this.bridgeWorkspaceEvent.bind(this))]),this.started=!0):this.started=!1}async configurePostStart(){await this.framesController.start(this.settings,this.defaultWindowOpenBounds,this.operations.getFrameSummary),this.stateController.onWindowDisappeared(e=>this.framesController.handleFrameDisappeared(e))}get logger(){return logger.get("workspaces.controller")}ready(){return Promise.resolve()}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this workspaces control message, because the controller has not been started");const t=e.data,r=e.commandId,n=workspacesOperationDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This workspace request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`Workspace request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`Workspace request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}handleClientUnloaded(e,t){this.logger?.trace(`handling unloading of ${e}`),t&&!t.closed||(this.logger?.trace(`${e} detected as closed, checking if frame and processing close`),this.framesController.handleFrameDisappeared(e))}bridgeWorkspaceEvent(e){if(this.glueController.pushWorkspacesMessage(e),"opened"===e.action&&"workspace"===e.type){const{workspaceSummary:t}=e.payload;this.registry.execute("workspace-started",{layoutName:t.config.layoutName})}if("closed"===e.action&&"workspace"===e.type){const{workspaceSummary:t}=e.payload;this.glueController.clearContext(t.id,"workspace"),this.registry.execute("workspace-closed",{layoutName:t.config.layoutName})}this.settings.hibernation&&this.hibernationWatcher.notifyEvent(e)}onWorkspaceClosed(e){return"function"!=typeof e?ioError.raiseError("onWorkspaceClosed requires a single argument of type function"):this.registry.add("workspace-closed",e)}onWorkspaceStarted(e){return"function"!=typeof e?ioError.raiseError("onWorkspaceStarted requires a single argument of type function"):this.registry.add("workspace-started",e)}onWorkspaceSaved(e){return"function"!=typeof e?ioError.raiseError("onWorkspaceSaved requires a single argument of type function"):this.registry.add("workspace-saved",e)}async closeWorkspace(e,t){return this.sequelizer.enqueue(async()=>{this.logger?.trace(`[${t}] handling closeWorkspace request with config ${JSON.stringify(e)}`);const r=e.itemId,n=(await this.getAllWorkspacesSummaries({},t)).summaries,i=n.find(e=>e.id===r);if(!i)return ioError.raiseError(`Cannot close workspace with id: ${r}, because it is unknown to the platform`);const o=i.config.frameId,s=1===n.filter(e=>e.config.frameId===o).length,a=this.glueController.platformWindowId;if(s&&o===a&&this.logger?.info(`[${t}] this is the last workspace in the platform frame, cannot close the platform frame.`),s&&o!==a)return this.logger?.trace(`[${t}] this is the last workspace in frame ${o}, closing the frame`),await this.framesController.closeFrame(o),void this.logger?.trace(`[${t}] the frame window is closed`);this.logger?.trace(`[${t}] targeting frame ${o} for closing workspace ${r}`),await this.glueController.callFrame(this.operations.closeItem,e,o),this.logger?.trace(`[${t}] frame ${o} gave a success signal, responding to caller`)})}async closeFrame(e,t){return this.sequelizer.enqueue(async()=>{this.logger?.trace(`[${t}] handling closeFrame request with config ${JSON.stringify(e)}`),await this.framesController.closeFrame(e.itemId),this.logger?.trace(`[${t}] the frame window is closed`)})}async closeItem(e,t){this.logger?.trace(`[${t}] handling closeItem request with config ${JSON.stringify(e)}`);const r=this.framesController.getAll().find(t=>t.windowId===e.itemId);if(r)return await this.closeFrame(e,t);const n=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeting frame ${n.windowId}`),await this.glueController.callFrame(this.operations.closeItem,e,n.windowId),this.logger?.trace(`[${t}] frame ${n.windowId} gave a success signal, responding to caller`)}async setItemTitle(e,t){this.logger?.trace(`[${t}] handling setItemTitle request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.setItemTitle,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async hibernateWorkspace(e,t){this.logger?.trace(`[${t}] handling hibernateWorkspace request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.workspaceId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.preserveAllWorkspaceWindowsContext(e.workspaceId),await this.glueController.callFrame(this.operations.hibernateWorkspace,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async getWorkspacesConfiguration(e,t){return this.logger?.trace(`[${t}] handling getWorkspacesConfiguration request`),this.settings}async getWorkspaceWindowFrameBounds(e,t){this.logger?.trace(`[${t}] handling getWorkspaceWindowFrameBounds request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.itemId}),n=await this.glueController.callWindow("windows",this.ioc.windowsController.getFrameBoundsOperation,{windowId:r.windowId},{windowId:r.windowId});return this.logger?.trace(`[${t}] getWorkspaceWindowFrameBounds completed`),{bounds:n.bounds}}async getAllFramesSummaries(e,t){if(this.logger?.trace(`[${t}] handling getAllFramesSummaries request`),!this.started)return{summaries:[]};const r=await this.framesController.getAll();this.logger?.trace(`[${t}] sending getFrameSummary to all known frames: ${r.join(", ")}`);const n=(await Promise.all(r.map(e=>this.glueController.callFrame(this.operations.getFrameSummary,{itemId:e.windowId},e.windowId)))).filter(e=>"none"!==e.id);return this.logger?.trace(`[${t}] all frames responded, returning to caller`),{summaries:n}}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}async handleFrameHello(e,t){this.logger?.trace(`[${t}] handling handleFrameHello command with config: ${JSON.stringify(e)}`),e.windowId&&this.framesController.processNewHello(e.windowId)}async isWindowInWorkspace(e,t){this.logger?.trace(`[${t}] handling isWindowInWorkspace command with config: ${JSON.stringify(e)}`);const r=this.framesController.getAll();this.logger?.trace(`[${t}] sending isWindowInWorkspace to all known frames: ${JSON.stringify(r.join(", "))}`);const n=(await Promise.all(r.map(t=>this.glueController.callFrame(this.operations.isWindowInWorkspace,e,t.windowId)))).some(e=>e.inWorkspace);return this.logger?.trace(`[${t}] all frames responded, returning ${n} to the caller`),{inWorkspace:n}}async createWorkspace(e,t){this.logger?.trace(`[${t}] handling createWorkspace command`);const r=this.getBlockedAppNames(e.children??[],t);if(r.length)return ioError.raiseError(`Cannot complete 'createWorkspace' operation because there're app origins blocked by the Platform. Blocked names: ${JSON.stringify(r)}`);const n={frameId:e.frame?.reuseFrameId,newFrame:e.frame?.newFrame,itemId:e.config?.reuseWorkspaceId},i=await this.framesController.getFrameInstance(n);this.logger?.trace(`[${t}] calling frame: ${i.windowId}, based on selection config: ${JSON.stringify(n)}`);const o=await this.glueController.callFrame(this.operations.createWorkspace,e,i.windowId);return this.logger?.trace(`[${t}] frame ${i.windowId} responded with a valid snapshot, returning to caller`),o}async createFrame(e,t){this.logger?.trace(`[${t}] handling createFrame command`);const r=await this.framesController.openFrame(e.frameConfig,e.layoutComponentId);this.logger?.trace(`[${t}] calling frame: ${r.windowId}}`);const n=await this.glueController.callFrame(this.operations.createFrame,e,r.windowId);return this.logger?.trace(`[${t}] frame ${r.windowId} responded returning to caller`),n}async initFrame(e,t){this.logger?.trace(`[${t}] handling initFrame command`);const r={frameId:e.frameId},n=await this.framesController.getFrameInstance(r);this.logger?.trace(`[${t}] calling frame: ${n.windowId}, based on selection config: ${JSON.stringify(r)}`);const i=await this.filterWorkspacesWithInstanceRestrictions(e.workspaces,t),o={...e,workspaces:i};await this.glueController.callFrame(this.operations.initFrame,o,n.windowId),this.logger?.trace(`[${t}] frame ${n.windowId} responded returning to caller`)}async getFrameSummary(e,t){this.logger?.trace(`[${t}] handling getFrameSummary request for config: ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] forwarding getFrameSummary to frame ${r.windowId}`);const n=await this.glueController.callFrame(this.operations.getFrameSummary,e,r.windowId);return this.logger?.trace(`[${t}] frame ${r.windowId} responded with a valid summary, returning to caller`),n}async getAllWorkspacesSummaries(e,t){this.logger?.trace(`[${t}] handling getAllWorkspacesSummaries request`);const r=this.framesController.getAll();this.logger?.trace(`[${t}] sending getAllWorkspacesSummaries to all known frames: ${r.join(", ")}`);const n=(await Promise.all(r.map(e=>this.glueController.callFrame(this.operations.getAllWorkspacesSummaries,{},e.windowId)))).reduce((e,t)=>(e.push(...t.summaries),e),[]);return this.logger?.trace(`[${t}] all frames responded, results were aggregated, returning to caller`),{summaries:n}}async getWorkspaceSnapshot(e,t){this.logger?.trace(`[${t}] handling getWorkspaceSnapshot for config: ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeting frame ${r.windowId}`);const n=await this.glueController.callFrame(this.operations.getWorkspaceSnapshot,e,r.windowId);return this.logger?.trace(`[${t}] frame ${r.windowId} responded with a valid snapshot, retuning to caller`),n}async handleCheckStarted(e,t){return this.logger?.trace(`[${t}] handling handleCheckStarted request`),this.logger?.trace(`[${t}] the controller has been started, responding to caller`),{started:!0}}async handleGetPlatformFrameId(e,t){this.logger?.trace(`[${t}] handling GetPlatformFrameId request`);const r=this.framesController.getPlatformFrameSessionData();return this.logger?.trace(`[${t}] GetPlatformFrameId completed, responding to caller`),{id:r?.windowId}}async getFrameSessionData(e,t){this.logger?.trace(`[${t}] handling getFrameSessionData request`);const r=this.framesController.getFrameConfig(e.frameId);return this.logger?.trace(`[${t}] getFrameSessionData completed, responding to caller`),r}async handleGetWorkspacesLayouts(e,t){this.logger?.trace(`[${t}] handling handleGetWorkspacesLayouts request for frame: ${e.frameId} for layout: ${e.layoutName} of type: ${e.layoutType} and config: ${JSON.stringify(e)}`);const r=await this.glueController.callFrame(this.operations.getWorkspacesLayouts,e,e.frameId);if(this.logger?.trace(`[${t}] handleGetWorkspacesLayouts request completed for frame: ${e.frameId} for layout: ${e.layoutName} of type: ${e.layoutType} and config: ${JSON.stringify(e)}`),!e.ignoreContexts)return this.logger?.info(`[${t}] 'ignoreContexts' flag not set on layout save request, returning workspace and window contexts as received from frame ${e.frameId}`),r;return await this.checkIsIgnoreContextsOnLayoutSaveSupported(e.frameId,t)?(this.logger?.info(`[${t}] Returning workspaces layouts response as received from frame ${e.frameId}.`),r):(this.clearWorkspaceAndWindowsContexts(r.workspaces),this.logger?.info(`[${t}] Returning workspaces layouts response after clearing workspace and window contexts in the Platform`),r)}async getFrameBounds(e,t){this.logger?.trace(`[${t}] handling getFrameBounds request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({frameId:e.itemId}),n=await this.glueController.callWindow("windows",this.ioc.windowsController.getFrameBoundsOperation,{windowId:r.windowId},{windowId:r.windowId});return this.logger?.trace(`[${t}] getFrameBounds completed`),{bounds:n.bounds}}async showChannelsLink(e,t){this.logger?.trace(`[${t}] - received 'showChannelsLink' signal for windowId ${e.windowId}`);const r=await this.framesController.getFrameInstance({frameId:e.frameId});if(!r)return ioError.raiseError(`[${t}] - frame ${e.frameId} not found, cannot show channels link`);await this.glueController.callFrame(this.operations.showChannelsLink,e,r.windowId),this.logger?.trace(`[${t}] - frame ${r.windowId} gave a success signal, responding to caller`)}async getAllLayoutsSummaries(e,t){this.logger?.trace(`[${t}] handling getAllLayoutsSummaries command`);const r=(await this.ioc.layoutsController.handleGetAll({type:"Workspace"},t)).summaries.map(e=>({name:e.name}));return this.logger?.trace(`[${t}] all layouts retrieved and mapped, returning to caller`),{summaries:r}}async openWorkspace(e,t){this.logger?.trace(`[${t}] handling openWorkspace command for name: ${e.name}`);const r={frameId:e.restoreOptions?.frameId,newFrame:e.restoreOptions?.newFrame,itemId:e.restoreOptions?.reuseWorkspaceId},n=await this.tryFocusExistingWorkspace(e.name,t),i=await this.framesController.getFrameInstance(r);return n?await this.getWorkspaceSnapshot({itemId:n},t):await this.glueController.callFrame(this.operations.openWorkspace,e,i.windowId)}async deleteLayout(e,t){this.logger?.trace(`[${t}] handling deleteLayout request for name: ${e.name}`),await this.ioc.layoutsController.handleRemove({name:e.name,type:"Workspace"},t),this.logger?.trace(`[${t}] layouts reported this layout as deleted, responding to caller`)}async saveLayout(e,t){this.logger?.trace(`[${t}] handling saveLayout request for workspace ${e.workspaceId} and name ${e.name}`);const r=await this.framesController.getFrameInstance({itemId:e.workspaceId});this.logger?.trace(`[${t}] forwarding request to frame ${r.windowId}`);const n=(await this.glueController.callFrame(this.operations.getWorkspaceSnapshot,{itemId:e.workspaceId},r.windowId)).config.layoutName,i=await this.glueController.callFrame(this.operations.saveLayout,e,r.windowId);return this.logger?.trace(`[${t}] frame ${r.windowId} responded with a valid layout, returning to caller`),this.registry.execute("workspace-saved",{layoutName:i.name,oldLayoutName:n}),i}async importLayout(e,t){this.logger?.trace(`[${t}] handling importLayout command for layout ${e.layout.name}`),await this.ioc.layoutsController.handleImport({layouts:[e.layout],mode:e.mode},t),this.logger?.trace(`[${t}] the layouts controller successfully imported the layout, responding to caller`)}async exportAllLayouts(e,t){this.logger?.trace(`[${t}] handling exportAllLayouts request`);return await this.ioc.layoutsController.handleExport({type:"Workspace"},t)}async restoreItem(e,t){this.logger?.trace(`[${t}] handling restoreItem request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.restoreItem,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async maximizeItem(e,t){this.logger?.trace(`[${t}] handling maximizeItem request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.maximizeItem,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async focusItem(e,t){this.logger?.trace(`[${t}] handling focusItem request with config ${JSON.stringify(e)}`);const r=this.framesController.getAll().find(t=>t.windowId===e.itemId);if(r)return this.logger?.trace(`[${t}] this is targeted at a frame, focusing the frame`),void window.open(void 0,r.windowId);const n=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeting frame ${n.windowId}`),await this.glueController.callFrame(this.operations.focusItem,e,n.windowId),this.logger?.trace(`[${t}] frame ${n.windowId} gave a success signal, responding to caller`)}async resizeItem(e,t){this.logger?.trace(`[${t}] handling resizeItem request with config ${JSON.stringify(e)}`);const r=this.framesController.getAll().find(t=>t.windowId===e.itemId);if(r){this.logger?.trace(`[${t}] detected targeted item is frame, building window resize config`);const n={windowId:e.itemId,width:e.width,height:e.height,relative:e.relative};return await this.glueController.callWindow("windows",this.ioc.windowsController.moveResizeOperation,n,{windowId:r.windowId}),void this.logger?.trace(`[${t}] window resize responded with success, returning to caller`)}const n=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeted item is not a frame, it is located in frame ${n.windowId}`),await this.glueController.callFrame(this.operations.resizeItem,e,n.windowId),this.logger?.trace(`[${t}] frame ${n.windowId} gave a success signal, responding to caller`)}async getFrameSnapshot(e,t){this.logger?.trace(`[${t}] handling getFrameSnapshot request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeting frame ${r.windowId}`);const n=await this.glueController.callFrame(this.operations.getFrameSnapshot,e,r.windowId);return this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`),n}async forceLoadWindow(e,t){this.logger?.trace(`[${t}] handling forceLoadWindow request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeting frame ${r.windowId}`);const n=await this.glueController.callFrame(this.operations.forceLoadWindow,e,r.windowId);return this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`),n}async ejectWindow(e,t){this.logger?.trace(`[${t}] handling ejectWindow request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance(e);e.windowId&&this.sessionStorageController.addEjectedWindowId(e.windowId),this.logger?.trace(`[${t}] targeting frame ${r.windowId}`);const n=await this.glueController.callFrame(this.operations.ejectWindow,e,r.windowId);return this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`),n}async moveWindowTo(e,t){this.logger?.trace(`[${t}] handling moveWindowTo request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.moveWindowTo,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async addWindow(e,t){if(this.logger?.trace(`[${t}] handling addWindow request with config ${JSON.stringify(e)}`),e.definition.appName&&this.checkIfOriginBlockedByAppName(e.definition.appName))return ioError.raiseError(`Cannot complete 'addWindow' operation - origin of app '${e.definition.appName}' is blocked by the Platform`);const r=await this.framesController.getFrameInstance({itemId:e.parentId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`);const n=await this.glueController.callFrame(this.operations.addWindow,e,r.windowId);return this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal: ${JSON.stringify(n)}, responding to caller`),n}checkIfOriginBlockedByAppName(e){const t=this.glueController.getAllApplications().find(t=>t.name===e);return t?checkIsOriginBlocked(t.userProperties.details.url,this.connectionConfig.blockList):ioError.raiseError(`Application with name: ${e} does not exist`)}extractAppNamesFromConfig(e,t=[]){if("window"===e.type&&e.appName)return t.push(e.appName),t;for(const r of e.children||[])this.extractAppNamesFromConfig(r,t);return t}getBlockedAppNames(e,t){const r=[];for(const t of e)this.extractAppNamesFromConfig(t,r);this.logger?.trace(`[${t}] filtering blocked apps from all gathered appNames: ${JSON.stringify(r)}`);const n=r.filter(e=>this.checkIfOriginBlockedByAppName(e));return this.logger?.trace(`[${t}] blocked app names: ${JSON.stringify(n)}`),n}async addContainer(e,t){this.logger?.trace(`[${t}] handling addContainer request with config ${JSON.stringify(e)}`);const r=this.getBlockedAppNames(e.definition.children??[],t);if(r.length)return ioError.raiseError(`Cannot complete 'addContainer' operation because there're app origins blocked by the Platform. Blocked names: ${JSON.stringify(r)}`);const n=await this.framesController.getFrameInstance({itemId:e.parentId});this.logger?.trace(`[${t}] targeting frame ${n.windowId}`);const i=await this.glueController.callFrame(this.operations.addContainer,e,n.windowId);return this.logger?.trace(`[${t}] frame ${n.windowId} gave a success signal: ${JSON.stringify(i)}, responding to caller`),i}async bundleWorkspace(e,t){this.logger?.trace(`[${t}] handling bundleWorkspace request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.workspaceId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.bundleWorkspace,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async bundleItem(e,t){this.logger?.trace(`[${t}] handling bundleItem request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.itemId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.bundleItem,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async resumeWorkspace(e,t){this.logger?.trace(`[${t}] handling resumeWorkspace request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.workspaceId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.resumeWorkspace,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async lockWorkspace(e,t){this.logger?.trace(`[${t}] handling lockWorkspace request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.workspaceId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.lockWorkspace,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async lockContainer(e,t){this.logger?.trace(`[${t}] handling lockContainer request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.itemId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.lockContainer,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async lockWindow(e,t){this.logger?.trace(`[${t}] handling lockWindow request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.windowPlacementId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.lockWindow,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async pinWorkspace(e,t){this.logger?.trace(`[${t}] handling pinWorkspace request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.workspaceId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.pinWorkspace,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async unpinWorkspace(e,t){this.logger?.trace(`[${t}] handling unpinWorkspace request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.workspaceId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.unpinWorkspace,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async getWorkspaceIcon(e,t){this.logger?.trace(`[${t}] handling getWorkspaceIcon request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.workspaceId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`);const n=await this.glueController.callFrame(this.operations.getWorkspaceIcon,e,r.windowId);return this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`),n}async setWorkspaceIcon(e,t){this.logger?.trace(`[${t}] handling setWorkspaceIcon request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.workspaceId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.setWorkspaceIcon,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async handleGetWorkspaceWindowsOnLayoutSaveContext(e,t){this.logger?.trace(`[${t}] handling GetWorkspaceWindowsOnLayoutSaveContext request with config: ${JSON.stringify(e)}`);const r=await Promise.all(e.windowIds.map(async t=>({windowId:t,windowContext:await this.getWorkspaceWindowOnLayoutSaveData(t,e)})));return this.logger?.trace(`[${t}] operation GetWorkspaceWindowsOnLayoutSaveContext completed responding`),{windowsOnSaveData:r}}async handleSetMaximizationBoundary(e,t){this.logger?.trace(`[${t}] handling setMaximizationBoundary request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.setMaximizationBoundary,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async changeFrameState(e,t){return ioError.raiseError("Frame states are not supported in Glue42 Core")}async getFrameState(e,t){return ioError.raiseError("Frame states are not supported in Glue42 Core")}async handleFocusEvent(e,t){this.logger?.trace(`[${t}] handling focus event from frame id: ${e.windowId} and hasFocus: ${e.hasFocus}`);try{await this.framesController.getFrameInstance({frameId:e.windowId})}catch(r){return void this.logger?.trace(`[${t}] ignoring focus event for unrecognized frame with id: ${e.windowId}`)}const r={type:"frame",action:"focus",payload:{frameSummary:{id:e.windowId,isFocused:e.hasFocus}}};this.bridgeWorkspaceEvent(r),this.logger?.trace(`[${t}] focus event from frame id: ${e.windowId} and hasFocus: ${e.hasFocus} handled`)}async moveFrame(e,t){this.logger?.trace(`[${t}] handling moveFrame command with config: ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({frameId:e.itemId}),n={windowId:e.itemId,top:e.top,left:e.left,relative:e.relative};await this.glueController.callWindow("windows",this.ioc.windowsController.moveResizeOperation,n,{windowId:r.windowId}),this.logger?.trace(`[${t}] frame with id ${r.windowId} was successfully moved, responding to caller`)}applyDefaults(e){const t=e?.hibernation||{},r=deepMerge$1(defaultLoadingConfig,e?.loadingStrategy||{});return{...e,loadingStrategy:r,hibernation:t}}async getWorkspaceWindowOnLayoutSaveData(e,t){if(this.ioc.sessionController.getAllNonGlue().some(t=>t.windowId===e))return this.ioc.layoutsBuilder.getNonGlueWindowContext(t,e);return this.ioc.sessionController.getWorkspaceClientById(e)?this.ioc.layoutsBuilder.getGlueClientWindowContextOnSaveRequest(t,e):ioError.raiseError(`Cannot ask window: ${e} for on layout save request, because it is not a known workspace window`)}async handleBringBackToWorkspace({windowId:e},t){this.logger?.trace(`[${t}] - received 'bringBackToWorkspace' signal for windowId ${e}`);if(!this.glueController.getWindowById(e))return ioError.raiseError(`Cannot bring back window with id ${e} to workspace because it is not known by the platform`);this.sessionStorageController.addEjectedWindowId(e);const r=await this.glueController.clientGlue.contexts.get(`___window___${e}`);if(!r||!Object.keys(r).length||!r.___io___?.ejectedWindow)return ioError.raiseError(`Cannot bring back window with id ${e} to workspace because it was never a part from one`);const{___io___:{ejectedWindow:n}}=r,i=await this.framesController.getFrameInstance({itemId:n.frameId}),o={definition:{type:"group",children:[{windowId:e,type:"window"}]},parentType:"workspace",parentId:n.workspaceId},s=await this.glueController.callFrame(this.operations.addContainer,o,i.windowId);this.logger?.trace(`[${t}] - frame ${i.windowId} gave a success signal: ${JSON.stringify(s)}`)}async tryFocusExistingWorkspace(e,t){const r=await this.ioc.layoutsController.handleGetLayout({name:e,type:"Workspace"},t);if(!this.hasInstanceRestriction(r.layout))return;const n=(await this.getAllWorkspacesSummaries({},t)).summaries.find(t=>t.config.layoutName===e);return n?(await this.focusItem({itemId:n.id},t),n.id):void 0}hasInstanceRestriction(e){if(!e)return!1;const t=e.components[0];return!1===t.state?.config?.allowMultiple}async filterWorkspacesWithInstanceRestrictions(e,t){const r=await this.getAllWorkspacesSummaries({},t),n=await Promise.all(e.map(e=>e).filter(e=>e.name).map(e=>this.ioc.layoutsController.handleGetLayout({name:e.name,type:"Workspace"},t))),i=e.filter((e,t,i)=>{if(!this.isRestoreWorkspaceDefinition(e))return!0;const o=n.find(t=>t.layout?.name===e.name)?.layout;if(!this.hasInstanceRestriction(o))return!0;const s=r.summaries.find(t=>t.config.layoutName===e.name),a=e!==i.find(t=>this.isRestoreWorkspaceDefinition(t)&&t.name===e.name);return!s&&!a},[]);return i}isRestoreWorkspaceDefinition(e){return!!e.name}async checkIsIgnoreContextsOnLayoutSaveSupported(e,t){const r=await this.glueController.isFrameOperationSupported("isIgnoreContextsOnLayoutSaveSupported",e);return this.logger?.info(`[${t}] Frame ${e} ${r?"supports":"does NOT support"} 'ignoreContexts' flag on layout save requests`),r}clearWorkspaceAndWindowsContexts(e){e.forEach(e=>{e.context={},this.clearWorkspaceChildrenContexts(e.children)})}clearWorkspaceChildrenContexts(e){e.forEach(e=>{"window"!==e.type?this.clearWorkspaceChildrenContexts(e.children):e.config.context={}})}}const INTENTS_RESOLVER_INTEROP_PREFIX="T42.Intents.Resolver.Control.",INTENTS_RESOLVER_WIDTH=400,INTENTS_RESOLVER_HEIGHT=400,DEFAULT_METHOD_RESPONSE_TIMEOUT_MS=6e4,DEFAULT_RAISE_TIMEOUT_MS=9e4,DEFAULT_PICK_HANDLER_BY_TIMEOUT_MS=9e4,ERRORS=errors.intents;class IntentsController{glueController;legacyResolverController;appDirectory;windowsController;prefsController;uiController;operations={getIntents:{name:"getIntents",resultDecoder:wrappedIntentsDecoder,execute:this.getWrappedIntents.bind(this)},findIntent:{name:"findIntent",dataDecoder:wrappedIntentFilterDecoder,resultDecoder:wrappedIntentsDecoder,execute:this.findIntent.bind(this)},raise:{name:"raise",dataDecoder:raiseIntentRequestDecoder,resultDecoder:intentResultDecoder,execute:this.raise.bind(this)},filterHandlers:{name:"filterHandlers",dataDecoder:filterHandlersWithResolverConfigDecoder,resultDecoder:filterHandlersResultDecoder,execute:this.filterHandlers.bind(this)},getIntentsByHandler:{name:"getIntentsByHandler",dataDecoder:intentHandlerDecoder,resultDecoder:getIntentsResultDecoder,execute:this.getIntentsByHandler.bind(this)},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)}};started=!1;isIntentsSharingEnabledViaBridge=!1;constructor(e,t,r,n,i,o){this.glueController=e,this.legacyResolverController=t,this.appDirectory=r,this.windowsController=n,this.prefsController=i,this.uiController=o}get logger(){return logger.get("intents.controller")}handlePlatformShutdown(){this.started=!1}async start(e){this.started=!0;const t=e.gateway?.bridge;this.isIntentsSharingEnabledViaBridge=!!t?.url&&!1!==t.intents?.enabled}ready(){return Promise.resolve()}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this intents control message, because the controller has not been started");const t=e.data,r=e.commandId,n=e.callerId,i=e.callerType,o=intentsOperationTypesDecoder.run(e.operation);if(!o.ok)return ioError.raiseError(`This intents request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(o.error)}`);const s=o.result,a=this.operations[s].dataDecoder?.run(t);if(a&&!a.ok)return ioError.raiseError(`Intents request for ${s} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(a.error)}`);this.logger?.debug(`[${r}] ${s} command is valid with data: ${JSON.stringify(t)}`);const c=await this.operations[s].execute(t,r,n,i),l=this.operations[s].resultDecoder?.run(c);return l&&!l.ok?ioError.raiseError(`Intents request for ${s} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(l.error)}`):(this.logger?.trace(`[${r}] ${s} command was executed successfully`),c)}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}extractAppIntents(e){const t={},r=e.filter(e=>e.intents.length>0);for(const e of r)for(const r of e.intents){t[r.name]||(t[r.name]=[]);const n={applicationName:e.name,applicationTitle:e.title,applicationDescription:e.caption,displayName:r.displayName,contextTypes:r.contexts,applicationIcon:e.icon,type:"app",resultType:r.resultType,customConfig:r.customConfig};t[r.name].push(n)}return t}async getInstanceIntents(e,t){const r={},n=this.isIntentsSharingEnabledViaBridge?this.glueController.getServers():this.glueController.getLocalServers();for(const i of n){const n=(i.getMethods?.()||[]).filter(e=>e.name.startsWith(GlueWebIntentsPrefix));await Promise.all(n.map(async n=>{const o=n.name.replace(GlueWebIntentsPrefix,"");r[o]=r[o]??[];const s={apps:e,server:i,method:n,commandId:t,intentName:o},a=this.glueController.isValidWindowId(s.server.windowId)?await this.getInstanceIntentHandler(s):this.getInstanceIntentHandlerWithInvalidWindowId(s);r[o].push(a)}))}return r}getInstanceIntentHandlerWithInvalidWindowId({server:e,method:t,apps:r,intentName:n}){const i=this.glueController.clientGlue.appManager.instances().find(t=>t.id===e.instance),o=t.flags.intent;if(!i)return{instanceId:e.instance,applicationName:e.application??e.applicationName??"",applicationIcon:o.icon,applicationTitle:"",applicationDescription:o.description,displayName:o.displayName,contextTypes:o.contextTypes,instanceTitle:e.instance,type:"instance",resultType:o.resultType,customConfig:o.customConfig};const{application:s}=i,a=r.find(e=>e.name===s.name)?.intents?.find(e=>e.name===n);return{instanceId:e.instance,applicationName:s.name,applicationIcon:o.icon??s.icon,applicationTitle:s.title??"",applicationDescription:o.description??s.caption,displayName:o.displayName??a?.displayName,contextTypes:o.contextTypes??a?.contexts,instanceTitle:"",type:"instance",resultType:o.resultType??a?.resultType}}async getInstanceIntentHandler({apps:e,intentName:t,server:r,method:n,commandId:i}){const o=e.find(e=>e.name===r.application),s=o?.intents?.find(e=>e.name===t)||void 0,a=n.flags.intent,c=await this.windowsController.getWindowTitle(r.windowId??"",i);return{instanceId:r.windowId||r.instance,applicationName:r.application||"",applicationIcon:a.icon||o?.icon,applicationTitle:o?.title||"",applicationDescription:a.description||o?.caption,displayName:a.displayName||s?.displayName,contextTypes:a.contextTypes||s?.contexts,instanceTitle:c,type:"instance",resultType:s?.resultType||a.resultType,customConfig:a.customConfig}}mergeIntentStores(e,t){const r={};for(const n of new Set([...Object.keys(e),...Object.keys(t)]))r[n]=[...e[n]||[],...t[n]||[]];return r}wrapIntents(e){return{intents:e}}async getIntents(e){const t=(await this.appDirectory.getAll()).map(e=>({name:e.name,title:e.title||"",icon:e.icon,caption:e.caption,intents:e.userProperties.intents??[]})),r=this.extractAppIntents(t);this.logger?.trace(`[${e}] got app intents`);const n=await this.getInstanceIntents(t,e);this.logger?.trace(`[${e}] got instance intents`);const i=this.mergeIntentStores(r,n);return Object.keys(i).map(e=>({name:e,handlers:i[e]}))}async getWrappedIntents(e){this.logger?.trace(`[${e}] handling getIntents command`);const t=await this.getIntents(e);return this.logger?.trace(`[${e}] getIntents command completed`),this.wrapIntents(t)}async findIntent(e,t){this.logger?.trace(`[${t}] handling findIntent command`);const r=e.filter;let n=await this.getIntents(t);if(!r)return this.wrapIntents(n);if("string"==typeof r)return this.wrapIntents(n.filter(e=>e.name===r));if(r.contextType){const e=r.contextType.toLowerCase();n=n.filter(t=>t.handlers.some(t=>t.contextTypes?.some(t=>t.toLowerCase()===e)))}if(r.name&&(n=n.filter(e=>e.name===r.name)),r.resultType){const e=r.resultType.toLowerCase();n=n.filter(t=>t.handlers.some(t=>t.resultType?.toLowerCase()===e))}return this.logger?.trace(`[${t}] findIntent command completed`),this.wrapIntents(n)}async getIntent(e,t){return(await this.getIntents(t)).find(t=>t.name===e)}async startApp(e,t){const r={...t.options??{},originIntentRequest:t};return(await this.glueController.clientGlue.appManager.application(e).start(t.context,r)).id}async raiseIntent(e,t,r,n){this.logger?.trace(`[${t}] handling raiseIntent command with intentRequest: ${JSON.stringify(e)}`);const i=e.intent,o=await this.getIntent(i,t);if(!o)return ioError.raiseError(`Intent ${i} not found!`);this.logger?.trace(`Raised intent definition: ${JSON.stringify(o)}`);const s=e.handlers?this.findHandlerByFilter(e.handlers,{type:"app"}):this.findHandlerByFilter(o.handlers,{type:"app"}),a=e.handlers?this.findHandlerByFilter(e.handlers,{type:"instance"}):this.findHandlerByFilter(o.handlers,{type:"instance"});let c;if(e.target&&"reuse"!==e.target||(c=a||s),"startNew"===e.target&&(c=s),"object"==typeof e.target&&e.target.app&&(c=this.findHandlerByFilter(o.handlers,{app:e.target.app})),"object"==typeof e.target&&e.target.instance&&(c=this.findHandlerByFilter(o.handlers,{instance:e.target.instance,app:e.target.app})),!c)return ioError.raiseError(`Can not raise intent for request ${JSON.stringify(e)} - can not find intent handler!`);return await this.raiseIntentToTargetHandler({request:e,handler:c,commandId:t,callerId:r,timeout:n})}findHandlerByFilter(e,t){return t.type?e.find(e=>e.type===t.type):t.instance?e.find(e=>t.app?e.applicationName===t.app&&e.instanceId===t.instance:e.instanceId===t.instance):t.app?e.find(e=>e.applicationName===t.app):void 0}async raiseIntentToTargetHandler({handler:e,request:t,callerId:r,commandId:n,timeout:i}){this.logger?.trace(`Raising intent to target handler:${JSON.stringify(e)}`);const o=e.instanceId?Promise.resolve(e.instanceId):this.startApp(e.applicationName,t).catch(e=>{const t=e instanceof Error||"string"==typeof e?e:JSON.stringify(e);return ioError.raiseError(`${ERRORS.TARGET_INSTANCE_UNAVAILABLE}. Reason: ${t}`)}),s=await o,a=`${GlueWebIntentsPrefix}${t.intent}`;this.logger?.trace(`Searching for interop server offering method ${a}`);const c={methodResponseTimeoutMs:i?i+1e3:DEFAULT_METHOD_RESPONSE_TIMEOUT_MS,waitTimeoutMs:i?i+1e3:DEFAULT_METHOD_RESPONSE_TIMEOUT_MS},l=this.glueController.invokeMethod(a,{...t.context,_initialCallerId:r},{instance:s},c).catch(e=>ioError.raiseError(`${ERRORS.INTENT_HANDLER_REJECTION}. Reason: ${e instanceof Error?e:JSON.stringify(e)}`)),u=await l;return this.logger?.trace(`[${n}] raiseIntent command completed. Returning result: ${JSON.stringify(u)}`),{request:t,handler:{...e,instanceId:s,type:"instance"},result:u.returned}}async raise(e,t,r,n){if(this.logger?.trace(`[${t}] Receive raise command with config: ${JSON.stringify(e)}`),!r)return ioError.raiseError(`${ERRORS.CALLER_NOT_DEFINED} for 'raise' command with request ${JSON.stringify(e)}`);const i=e.intentRequest.timeout||DEFAULT_RAISE_TIMEOUT_MS,o={instanceId:void 0},s=this.coreRaiseIntent.bind(this,{request:e,resolverInstance:o,timeout:i,commandId:t,callerId:this.getCallerIdByCallerType(r,n)});return e.intentRequest.waitUserResponseIndefinitely?s():PromiseWrap(s,i,`${ERRORS.TIMEOUT_HIT} - waited ${i}ms for 'raise' to resolve`)}async handleRaiseWithEmbeddedResolver({intentRequest:e,initialCaller:t,timeout:r,commandId:n}){this.logger?.trace(`[${n}] handling raise command with embedded resolver`);const i=e.waitUserResponseIndefinitely?MAX_SET_TIMEOUT_DELAY:r,o={commandId:n,config:{intentRequest:e,timeout:i},methodResponseTimeoutMs:i,initialCaller:t},s=await this.uiController.openResolver(o);s.isClosed&&ioError.raiseError(`${ERRORS.USER_CANCELLED}`),s.isExpired&&ioError.raiseError(`${ERRORS.TIMEOUT_HIT} - waited ${r}ms for user to choose an intent handler`);const a=s.userChoice?.handler;if(!a)return ioError.raiseError(`${ERRORS.HANDLER_NOT_FOUND}`);if(!!s.userChoice?.userSettings.preserveChoice)try{this.logger?.trace(`[${n}] - User wants to preserve the chosen of handler: ${JSON.stringify(a)}`),await this.preserveUserChoice({initialCaller:t,commandId:n,handler:a,intentName:e.intent})}catch(e){this.logger?.warn(`[${n}] - Prefs API threw the following error: ${e}. Handler won't be preserved`)}return this.handleRaiseToTargetHandler(e,a,n,t.instanceId,r)}async coreRaiseIntent({request:e,resolverInstance:t,timeout:r,commandId:n,callerId:i}){const{resolverConfig:o,intentRequest:s,embeddedResolverConfig:a}=e,c=(await this.findIntent({filter:{name:s.intent}},n)).intents.find(e=>e.name===s.intent);if(!c)return ioError.raiseError(`${ERRORS.INTENT_NOT_FOUND} with name ${s.intent}`);this.logger?.trace(`[${n}] Intent to be handled: ${JSON.stringify(c)}`);const{open:l,reason:u}=this.checkIfResolverShouldBeOpenedForRaise(c,s,o,a);if(!l)return this.logger?.trace(`[${n}] Intent Resolver UI won't be used. Reason: ${u}`),this.handleRaiseWithoutResolver({request:e,commandId:n,callerId:i,timeout:r});if(this.logger?.trace(`[${n}] Starting Intent Resolver app for intent request: ${JSON.stringify(e)}`),a?.enabled)return this.logger?.trace(`[${n}] Handling 'raise' with embedded intent resolver`),this.handleRaiseWithEmbeddedResolver({intentRequest:s,initialCaller:a.initialCaller,timeout:r,commandId:n});if(o){this.logger?.trace(`[${n}] Handling 'raise' with legacy intent resolver`);const o=this.handleRaiseWithLegacyResolver({request:e,commandId:n,resolverInstance:t,callerId:i,timeout:r});return o.catch(()=>t.instanceId&&this.legacyResolverController.stopResolverInstance(t.instanceId)),o}return ioError.raiseError(`Couldn't complete 'raise' operation with request: ${JSON.stringify(s)}`)}async handleRaiseToTargetHandler(e,t,r,n,i){const o=`with timeout of ${e.timeout??DEFAULT_RAISE_TIMEOUT_MS}ms`;if(this.logger?.trace(`Raising intent to target handler: ${JSON.stringify(t)} ${o}`),e.waitUserResponseIndefinitely)return PromiseWrap(()=>this.raiseIntentToTargetHandler({request:e,handler:{...t,type:t.instanceId?"instance":"app"},commandId:r,timeout:i,callerId:n}),i,`${ERRORS.INTENT_DELIVERY_FAILED} - waited ${i}ms for client to handle the raised intent`);const s=await this.raiseIntentToTargetHandler({request:e,handler:{...t,type:t.instanceId?"instance":"app"},commandId:r,callerId:n,timeout:i});return this.logger?.trace(`Result from raise() method for intent ${JSON.stringify(e.intent)}: ${JSON.stringify(s)}`),s}async handleRaiseWithoutResolver({request:e,commandId:t,callerId:r,timeout:n}){const{intentRequest:i}=e;return i.waitUserResponseIndefinitely?PromiseWrap(()=>this.raiseIntent(i,t,r,n),n,`${ERRORS.TIMEOUT_HIT} - waited ${n}ms for 'raise' to resolve`):this.raiseIntent(i,t,r,n)}async handleRaiseWithLegacyResolver(e){const{request:t,callerId:r,commandId:n,resolverInstance:i,timeout:o}=e,s=await this.legacyResolverController.startResolverApp({request:t.intentRequest,resolverConfig:t.resolverConfig,callerId:r,commandId:n,resolverInstance:i,method:"raise"});return this.handleRaiseToTargetHandler(t.intentRequest,s,n,r,o)}async preserveUserChoice({initialCaller:e,commandId:t,filter:r,intentName:n,handler:i}){const o=e.instanceId===this.glueController.me.instance?this.prefsController.platformAppName:this.glueController.getAppNameByInstanceId(e.instanceId);if(!o)return;this.logger?.info(`[${t}] - Saving user's choice of handler for '${o}' app`);const s=await this.prefsController.get({app:o},t),a=s.prefs.data?.intents??{},c={...s.prefs.data,intents:{...a,[n]:{handler:i,filter:r}}};await this.prefsController.update({app:o,data:c},t)}checkIfIntentHasMoreThanOneHandler(e,t){const r=t.handlers||e.handlers;if(!t.target)return r.length>1;if("reuse"===t.target)return r.filter(e=>"instance"===e.type&&e.instanceId).length>1||e.handlers.filter(e=>"app"===e.type).length>1;if("startNew"===t.target)return r.filter(e=>"app"===e.type).length>1;if(t.target.instance)return!1;if(t.target.app){const e=t.target.app;return r.filter(t=>t.applicationName===e&&t.instanceId).length>1}return!1}checkIfResolverShouldBeOpenedForRaise(e,t,r,n){if(!this.checkIfIntentHasMoreThanOneHandler(e,t))return{open:!1,reason:"Raised intent has only one handler"};if(n?.enabled)return{open:!0};const i=this.checkIfResolverShouldBeOpenByResolverConfig(r);return i.open?{open:!0}:i}checkIfResolverShouldBeOpenedForFilterHandlers(e,t,r,n){return 1===e.length?{open:!1,reason:`There's only one valid intent handler for filter ${JSON.stringify(t)}`}:!1===t.openResolver?{open:!1,reason:"Intents resolver is disabled by IntentHandler filter"}:n?.enabled?{open:!0}:this.checkIfResolverShouldBeOpenByResolverConfig(r)}checkIfResolverShouldBeOpenByResolverConfig(e){if(!e.enabled)return{open:!1,reason:"Intent Resolver is disabled. Raising intent to first found handler"};return this.glueController.clientGlue.appManager.application(e.appName)?{open:!0}:{open:!1,reason:`Application with name ${e.appName} not found`}}async filterHandlers(e,t,r,n){if(this.logger?.trace(`[${t}] Receive 'filterHandlers' command with request: ${JSON.stringify(e)}`),!r)return ioError.raiseError("Cannot preform 'filterHandlers' - callerId is not defined");const{filterHandlersRequest:i,resolverConfig:o,embeddedResolverConfig:s}=e,a=await this.getIntents(t),c=this.filterHandlersBy(a,i);if(!c?.length)return{handlers:[]};const{open:l,reason:u}=this.checkIfResolverShouldBeOpenedForFilterHandlers(c,i,o,s);if(!l)return this.logger?.trace(`[${t}] Intent Resolver UI won't be used. Reason: ${u}`),{handlers:c};const d=i.timeout||DEFAULT_PICK_HANDLER_BY_TIMEOUT_MS;if(s?.enabled)return this.logger?.trace(`[${t}] Handling 'filterHandlers' with embedded intent resolver`),PromiseWrap(()=>this.handleFilterHandlersWithEmbeddedResolver({commandId:t,handlerFilter:i,initialCaller:s.initialCaller,timeout:d}),d,`${ERRORS.TIMEOUT_HIT} - waited ${d}ms for 'filterHandlers' to resolve`);const h={instanceId:void 0};return{handlers:[await PromiseWrap(()=>this.legacyResolverController.startResolverApp({request:i,resolverConfig:o,commandId:t,callerId:this.getCallerIdByCallerType(r,n),resolverInstance:h,method:"filterHandlers"}),d,`Timeout of ${d}ms hit for 'filterHandlers' request with filter: ${JSON.stringify(e.filterHandlersRequest)}`)]}}async handleFilterHandlersWithEmbeddedResolver({commandId:e,handlerFilter:t,initialCaller:r,timeout:n}){const i={commandId:e,config:{handlerFilter:t,timeout:n},methodResponseTimeoutMs:n,initialCaller:r},o=await this.uiController.openResolver(i);o.isClosed&&ioError.raiseError(`${ERRORS.USER_CANCELLED}`),o.isExpired&&ioError.raiseError(`${ERRORS.TIMEOUT_HIT} - waited ${n}ms for user to choose an intent handler`);const{handler:s,intent:a}=o.userChoice??{};if(!s)return ioError.raiseError(`${ERRORS.HANDLER_NOT_FOUND}`);if(!a)return ioError.raiseError(`${ERRORS.INTENT_NOT_FOUND} for handlerFilter: ${JSON.stringify(t)}`);if(!!o.userChoice?.userSettings.preserveChoice)try{this.logger?.trace(`[${e}] - User wants to preserve the chosen of handler: ${JSON.stringify(s)}`);const n={applicationNames:t.applicationNames,contextTypes:t.contextTypes,resultType:t.resultType};await this.preserveUserChoice({initialCaller:r,commandId:e,handler:s,intentName:a,filter:n})}catch(t){this.logger?.warn(`[${e}] - Prefs API threw the following error: ${t}. Handler won't be preserved`)}return{handlers:[s]}}filterHandlersBy(e,t){const r=e.filter(e=>{if(!t.intent||t.intent===e.name){if(t.excludeList&&(e.handlers=this.excludeIntentHandlers(e,t.excludeList)),t.resultType){const r=e.handlers.filter(e=>e.resultType&&e.resultType===t.resultType);if(!r.length)return;e.handlers=r}if(t.contextTypes){const r=e.handlers.filter(e=>t.contextTypes?.every(t=>e.contextTypes?.includes(t)));if(!r.length)return;e.handlers=r}if(t.applicationNames){const r=e.handlers.filter(e=>t.applicationNames?.includes(e.applicationName));if(!r.length)return;e.handlers=r}return e}}),n=r.map(e=>e.handlers).flat(1);return n.filter((e,t)=>t===n.findIndex(t=>e.instanceId?e.instanceId===t.instanceId:!t.instanceId&&t.applicationName===e.applicationName))}excludeIntentHandlers(e,t){return e.handlers.filter(e=>!t.some(t=>"applicationName"in t?t.applicationName===e.applicationName:"instanceId"in t&&t.instanceId===e.instanceId))}async getIntentsByHandler(e,t){this.logger?.log(`[${t}] - Receive 'getIntents' command with request: ${JSON.stringify(e)}`);const r=runDecoderWithIOError(intentHandlerDecoder,e),n=await this.getIntents(t);clearNullUndefined(r),this.logger?.info(`[${t}] - extracting valid intents for the passed handler`);const i=this.extractIntentsWithInfoByHandler(n,r);return this.logger?.info(`[${t}] - returning intents for handler ${JSON.stringify(e)}`),{intents:i}}isHandlerValid(e,t){return Object.keys(e).every(r=>"contextTypes"===r?e.contextTypes?.every(e=>t.contextTypes?.includes(e)):t[r]===e[r])}extractIntentsWithInfoByHandler(e,t){return e.reduce((e,r)=>(r.handlers.forEach(n=>{if(!this.isHandlerValid(t,n))return;const i={intent:r.name,contextTypes:n.contextTypes,description:n.applicationDescription,displayName:n.displayName,icon:n.applicationIcon,resultType:n.resultType};e.push(i)}),e),[])}getCallerIdByCallerType(e,t){return"plugin"===t?this.glueController.me.instance??"":e}}const channelOperationDecoder=oneOf$1(constant$2("appHello"),constant$2("addChannel"),constant$2("removeChannel"),constant$2("operationCheck"),constant$2("getMyChannel"),constant$2("getWindowIdsOnChannel"),constant$2("getWindowIdsWithChannels"),constant$2("joinChannel"),constant$2("restrict"),constant$2("getRestrictions"),constant$2("restrictAll"),constant$2("notifyChannelsChanged"),constant$2("leaveChannel"),constant$2("requestChannelSelector"),constant$2("getMode")),leaveChannelDecoder=object$2({windowId:nonEmptyStringDecoder$2,channelName:optional$3(nonEmptyStringDecoder$2)}),channelsChangedDecoder=object$2({windowId:nonEmptyStringDecoder$2,channelNames:array$3(nonEmptyStringDecoder$2)}),modeDecoder=oneOf$1(constant$2("single"),constant$2("multi")),getChannelsModeDecoder=object$2({mode:modeDecoder}),channelFDC3DisplayMetadataDecoder=object$2({color:optional$3(nonEmptyStringDecoder$2),icon:optional$3(nonEmptyStringDecoder$2),name:optional$3(nonEmptyStringDecoder$2),glyph:optional$3(nonEmptyStringDecoder$2)}),channelFdc3MetaDecoder=object$2({id:nonEmptyStringDecoder$2,displayMetadata:optional$3(channelFDC3DisplayMetadataDecoder)}),channelMetaDecoder=object$2({color:nonEmptyStringDecoder$2,fdc3:optional$3(channelFdc3MetaDecoder)}),channelDefinitionDecoder=object$2({name:nonEmptyStringDecoder$2,meta:channelMetaDecoder,data:optional$3(anyJson$2())}),removeChannelDataDecoder=object$2({name:nonEmptyStringDecoder$2}),getMyChanelResultDecoder=object$2({channel:optional$3(nonEmptyStringDecoder$2)}),getWindowIdsOnChannelDataDecoder=object$2({channel:nonEmptyStringDecoder$2}),getWindowIdsOnChannelResultDecoder=object$2({windowIds:array$3(nonEmptyStringDecoder$2)}),getWindowIdsWithChannelsResultDecoder=object$2({windowIdsWithChannels:array$3(object$2({application:nonEmptyStringDecoder$2,channel:optional$3(nonEmptyStringDecoder$2),windowId:nonEmptyStringDecoder$2}))}),windowWithChannelFilterDecoder=object$2({application:optional$3(nonEmptyStringDecoder$2),channels:optional$3(array$3(nonEmptyStringDecoder$2)),windowIds:optional$3(array$3(nonEmptyStringDecoder$2))}),wrappedWindowWithChannelFilterDecoder=object$2({filter:optional$3(windowWithChannelFilterDecoder)}),joinChannelDataDecoder=object$2({channel:nonEmptyStringDecoder$2,windowId:nonEmptyStringDecoder$2}),channelRestrictionConfigWithWindowIdDecoder=object$2({name:nonEmptyStringDecoder$2,read:boolean$3(),write:boolean$3(),windowId:nonEmptyStringDecoder$2}),restrictionConfigDataDecoder=object$2({config:channelRestrictionConfigWithWindowIdDecoder}),getRestrictionsDataDecoder=object$2({windowId:nonEmptyStringDecoder$2}),restrictionsConfigDecoder=object$2({read:boolean$3(),write:boolean$3(),windowId:nonEmptyStringDecoder$2}),restrictAllDataDecoder=object$2({restrictions:restrictionsConfigDecoder}),channelRestrictionsDecoder=object$2({name:nonEmptyStringDecoder$2,read:boolean$3(),write:boolean$3(),windowId:optional$3(nonEmptyStringDecoder$2)}),restrictionsDecoder=object$2({channels:array$3(channelRestrictionsDecoder)}),requestChannelSelectorConfigDecoder=object$2({windowId:nonEmptyStringDecoder$2,channelsNames:array$3(nonEmptyStringDecoder$2)}),appHelloDataDecoder=object$2({windowId:nonEmptyStringDecoder$2}),appHelloSuccessDecoder=object$2({mode:modeDecoder,channels:array$3(nonEmptyStringDecoder$2),restrictions:array$3(channelRestrictionsDecoder)});class ChannelsController{glueController;sessionController;workspacesController;mode;operations={appHello:{name:"appHello",dataDecoder:appHelloDataDecoder,execute:this.handleAppHello.bind(this),resultDecoder:appHelloSuccessDecoder},addChannel:{name:"addChannel",execute:this.addChannel.bind(this),dataDecoder:channelDefinitionDecoder},removeChannel:{name:"removeChannel",execute:this.removeChannel.bind(this),dataDecoder:removeChannelDataDecoder},getMyChannel:{name:"getMyChannel",execute:async()=>{},resultDecoder:getMyChanelResultDecoder},getWindowIdsOnChannel:{name:"getWindowIdsOnChannel",execute:this.handleGetWindowIdsOnChannel.bind(this),dataDecoder:getWindowIdsOnChannelDataDecoder,resultDecoder:getWindowIdsOnChannelResultDecoder},getWindowIdsWithChannels:{name:"getWindowIdsWithChannels",execute:this.handleGetWindowIdsWithChannels.bind(this),dataDecoder:wrappedWindowWithChannelFilterDecoder,resultDecoder:getWindowIdsWithChannelsResultDecoder},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)},joinChannel:{name:"joinChannel",dataDecoder:joinChannelDataDecoder,execute:this.handleJoinChannel.bind(this)},restrict:{name:"restrict",dataDecoder:restrictionConfigDataDecoder,execute:this.restrict.bind(this)},getRestrictions:{name:"getRestrictions",dataDecoder:getRestrictionsDataDecoder,execute:this.getRestrictions.bind(this),resultDecoder:restrictionsDecoder},restrictAll:{name:"restrictAll",dataDecoder:restrictAllDataDecoder,execute:this.restrictAll.bind(this)},notifyChannelsChanged:{name:"notifyChannelsChanged",execute:this.handleChannelsChanged.bind(this),dataDecoder:channelsChangedDecoder},leaveChannel:{name:"leaveChannel",dataDecoder:leaveChannelDecoder,execute:this.handleLeaveChannel.bind(this)},requestChannelSelector:{name:"requestChannelSelector",dataDecoder:requestChannelSelectorConfigDecoder,execute:this.handleRequestChannelSelector.bind(this)},getMode:{name:"getMode",resultDecoder:getChannelsModeDecoder,execute:this.handleGetMode.bind(this)}};constructor(e,t,r){this.glueController=e,this.sessionController=t,this.workspacesController=r}get logger(){return logger.get("channels.controller")}async start(e){const t=e.channels.definitions;this.logger?.trace("initializing channels"),this.mode=e.channels.mode,this.logger?.trace(`initializing channels with mode: ${this.mode}`),await this.setupChannels(t),this.logger?.trace("initialization is completed")}ready(){return Promise.resolve()}async handleControl(e){const t=e.data,r=e.commandId,n=e.callerId,i=channelOperationDecoder.run(e.operation);if(!i.ok)return ioError.raiseError(`This channels request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(i.error)}`);const o=i.result,s=this.operations[o].dataDecoder?.run(t);if(s&&!s.ok)return ioError.raiseError(`Channels request for ${o} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(s.error)}`);this.logger?.debug(`[${r}] ${o} command is valid with data: ${JSON.stringify(t)}`);const a=await this.operations[o].execute(t,r,n),c=this.operations[o].resultDecoder?.run(a);return c&&!c.ok?ioError.raiseError(`Channels request for ${o} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(c.error)}`):(this.logger?.trace(`[${r}] ${o} command was executed successfully`),a)}handleClientUnloaded(e,t){this.logger?.trace(`[${e}] - Received client unloaded event for windowId: ${e}`);this.sessionController.getEjectedWindowIds().includes(e)?this.logger?.trace(`[${e}] - A workspace window with ID ${e} is being ejected or brought back to workspace. Keeping track of it.`):t&&!t.closed||(this.sessionController.removeEjectedWindowId(e),this.sessionController.removeWindowChannelData(e),this.logger?.trace(`[${e}] - Client unloaded event processed. Removed from Session Storage successfully`))}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}async handleAppHello({windowId:e},t){this.logger?.trace(`[${t}] - Received 'appHello' message for window with ID: ${e}`);this.checkIfValidWindowOrInteropInstanceId(e)||ioError.raiseError(`[${t}] - Cannot complete 'appHello' operation - received invalid window ID: ${e}`);const r=this.sessionController.getWindowChannelData(e);return this.logger?.trace(`[${t}] - Session data for window with ID ${e}: ${JSON.stringify(r)}`),{mode:this.mode,channels:r?.channels||[],restrictions:r?.restrictions||[]}}async handleLeaveChannel(e,t){this.trace(`[${t}] handling leaveChannel command with windowId: ${e.windowId}`,t);this.checkIfValidWindowOrInteropInstanceId(e.windowId)||ioError.raiseError(`[${t}] - Cannot complete 'leaveChannel' operation - received invalid window ID: ${e.windowId}`),this.removeChannelsFromSessionStorage(e.windowId,e.channelName),await this.glueController.callWindow("channels",this.operations.leaveChannel,e,{instance:e.windowId}),this.trace(`[${t}] successfully left the channel on window with ID "${e.windowId}"`,t)}removeChannelsFromSessionStorage(e,t){const r=this.sessionController.getWindowChannelData(e);if(!r?.channels?.length)return void this.logger?.trace(`No channels data found for window with id: ${e}, nothing to remove`);const n=t?r.channels.filter(e=>e!==t):[];this.sessionController.setChannelsForWindow(e,n)}async setupChannels(e){await Promise.all(e.map(e=>this.addChannel(e)))}async addChannel(e,t){this.trace(`[${t}] handling addChannel command with a valid name: ${e.name}, color: ${e.meta.color} and data: ${JSON.stringify(e.data)}`,t);const r={name:e.name,meta:e.meta,data:e.data||{}},n=this.createContextName(r.name);this.trace(`[${t}] setting a new channel context with name: ${n}`,t),await this.glueController.setContext(n,r),this.trace(`[${t}] channel context with name: ${n} created successfully`,t)}async removeChannel({name:e},t){this.trace(`[${t}] handling removeChannel command with a valid name: ${e}`,t);const r=this.createContextName(e);await this.glueController.destroyContext(r),this.trace(`[${t}] channel context with name: ${r} destroyed successfully`,t)}async getWindowChannel(e,t){if(!await this.checkIfAppHelloSupported(e))return this.trace(`[${t}] client is outdated and does not support platform session storage, falling back to window call`,t),this.glueController.callWindow("channels",this.operations.getMyChannel,{},{instance:e});const r=this.sessionController.getWindowChannelData(e),n=r?.channels?.[0];return{channel:n}}async handleGetWindowIdsOnChannel({channel:e},t){this.trace(`[${t}] handling getWindowIdsOnChannel command with channel: ${e}`,t);const r=this.glueController.getLocalServers().reduce((e,{windowId:t})=>t?[...e,t]:e,[]);this.trace(`[${t}] compiled a list of the IDs of all the windows that will be called: [${r.join(", ")}]`,t);const n=await Promise.all(r.map(async e=>{const{channel:r}=await this.getWindowChannel(e,t);return{channel:r,windowId:e}})),i=n.filter(t=>t.channel===e).map(({windowId:e})=>e);return this.trace(`[${t}] compiled a list of all windowIds that are on the "${e}" channel and returning it to the caller: [${i.join(", ")}]`,t),{windowIds:i}}async handleGetWindowIdsWithChannels({filter:e},t){this.trace(`[${t}] handling getWindowIdsWithChannels command with filter: ${JSON.stringify(e)}`,t);const r=this.glueController.getLocalServers(),n=this.glueController.getAllApplicationNames(),i=r.filter(({windowId:e})=>e);this.trace(`[${t}] compiled a list of the IDs of all the windows that will be called: [${i.map(({windowId:e})=>e).join(", ")}]`,t);const o=await Promise.all(i.map(async({applicationName:e,windowId:r})=>{const{channel:i}=await this.getWindowChannel(r,t);return{application:e&&n.includes(e)?e:"no-app-window",...i?{channel:i}:{},windowId:r}}));let s=o;return e?(e.application&&(this.trace(`[${t}] filtering windows by application: ${e.application}`,t),s=s.filter(({application:t})=>t===e.application)),e.channels&&(this.trace(`[${t}] filtering windows by channels: [${e.channels.join(", ")}]`,t),s=s.filter(({channel:t})=>t&&e.channels?.includes(t))),e.windowIds&&(this.trace(`[${t}] filtering windows by windowIds: [${e.windowIds.join(", ")}]`,t),s=s.filter(({windowId:t})=>e.windowIds?.includes(t))),this.trace(`[${t}] compiled a list of all windowIds with channels and returning it to the caller: ${JSON.stringify(s)}`,t),{windowIdsWithChannels:s}):(this.trace(`[${t}] compiled a list of all windowIds with channels and returning it to the caller: ${JSON.stringify(s)}`,t),{windowIdsWithChannels:s})}async handleChannelsChanged(e,t){this.trace(`[${t}] handling notifyChannelsChanged command with data: ${JSON.stringify(e)}`,t),this.glueController.pushSystemMessage("windows","notifyChannelsChanged",e),this.trace(`[${t}] successfully notified all windows about the channel change`,t)}async handleRequestChannelSelector(e,t){this.trace(`[${t}] handling requestChannelSelector command with windowId: ${e.windowId} and initial channels: ${e.channelsNames?.join(", ")}`,t);const r=this.sessionController.getWorkspaceClientById(e.windowId);if(!r)return ioError.raiseError(`Failed to display channel selector on window with ID "${e.windowId}", because the provided windowId is not a workspace window.`);await this.workspacesController.showChannelsLink({windowId:r.windowId,frameId:r.frameId,channelsNames:e.channelsNames},t),this.trace(`[${t}] successfully notified all windows about the channel change`,t)}async handleGetMode(){return{mode:this.mode}}async handleJoinChannel({channel:e,windowId:t},r){this.trace(`[${r}] handling joinChannel command with channel: ${e} and windowId: ${t}`,r);this.checkIfValidWindowOrInteropInstanceId(t)||ioError.raiseError(`[${r}] - Cannot complete 'joinChannel' operation - received invalid window ID: ${t}`),"single"===this.mode?this.sessionController.setChannelsForWindow(t,[e]):this.sessionController.setAdditionalChannelForWindow(t,e),await this.glueController.callWindow("channels",this.operations.joinChannel,{channel:e,windowId:t},{instance:t}),this.trace(`[${r}] successfully joined "${e}" channel on window with ID "${t}"`,r)}createContextName(e){return`${ChannelContextPrefix}${e}`}trace(e,t){t&&this.logger?.trace(e)}async restrict({config:e},t,r){this.trace(`[${t}] received restrict command with config ${JSON.stringify(e)} from callerId: ${r}`,t);this.checkIfValidWindowOrInteropInstanceId(e.windowId)||ioError.raiseError(`[${t}] - Cannot complete 'restrict' operation - received invalid window ID: ${e.windowId}`),this.sessionController.addChannelRestrictionsByWindowId(e.windowId,e),await this.glueController.callWindow("channels",this.operations.restrict,{config:e},{instance:e.windowId})}async getRestrictions({windowId:e},t,r){this.trace(`[${t}] received getRestrictions command for window with id ${e} from callerId: ${r}`,t);this.checkIfValidWindowOrInteropInstanceId(e)||ioError.raiseError(`[${t}] - Cannot complete 'getRestrictions' operation - received invalid window ID: ${e}`);if(!await this.checkIfAppHelloSupported(e))return this.logger?.trace(`[${t}] - Client's restrictions are saved in its own session storage. Calling it to get restrictions.`),this.glueController.callWindow("channels",this.operations.getRestrictions,{windowId:e},{instance:e});const n=this.sessionController.getWindowChannelData(e);return{channels:n?.restrictions||[]}}async restrictAll({restrictions:e},t,r){this.trace(`[${t}] received restrictAll command with config ${JSON.stringify(e)} from callerId: ${r}`,t);return this.checkIfValidWindowOrInteropInstanceId(e.windowId)||ioError.raiseError(`[${t}] - Cannot complete 'restrictAll' operation - received invalid window ID: ${e.windowId}`),this.addAllChannelRestrictionsInSessionStorage(e.windowId,e),this.glueController.callWindow("channels",this.operations.restrictAll,{restrictions:e},{instance:e.windowId})}addAllChannelRestrictionsInSessionStorage(e,t){const r=this.glueController.getAllContexts().filter(e=>e.startsWith(ChannelContextPrefix)).map(e=>e.replace(ChannelContextPrefix,"")),n=r.map(e=>({name:e,...t}));this.sessionController.addAllChannelsRestrictionsByWindowId(e,n)}checkIfValidWindowOrInteropInstanceId(e){if(this.glueController.isValidWindowId(e))return!0;if(this.glueController.platformWindowId===e)return!0;return!!this.glueController.getLocalServers().some(t=>t.instance===e)}async checkIfAppHelloSupported(e){try{return(await this.glueController.checkClientOperationSupport("channels",this.operations.appHello,{instance:e})).isSupported}catch(t){return this.logger?.trace(`Client with windowId: ${e} does NOT support 'appHello' message.`),!1}}}class FramesController{sessionController;glueController;ioc;config;defaultBounds;frameSummaryOperation;locks={};defaultFrameHelloTimeoutMs=15e3;_handleUnload;constructor(e,t,r){this.sessionController=e,this.glueController=t,this.ioc=r}get myFrameId(){return this.glueController.platformWindowId}stop(){this._handleUnload&&window.removeEventListener("pagehide",this._handleUnload)}async start(e,t,r){this.config=e,this.defaultBounds=t,this.frameSummaryOperation=r}async openFrame(e,t){const r="object"==typeof e?e.bounds??{}:{},n=r.top??this.defaultBounds.top,i=r.left??this.defaultBounds.left,o=r.width??this.defaultBounds.width,s=r.height??this.defaultBounds.height,a="object"==typeof e&&e?.frameId?e.frameId:`g42-${nanoid$3(10)}`;if(this.sessionController.getAllFrames().some(e=>e.windowId===a))return ioError.raiseError(`Cannot open a frame with id: ${a}, because a frame with this id already exists`);const c={windowId:a,active:!1,isPlatform:!1,layoutComponentId:t},l=`left=${i},top=${n},width=${o},height=${s}`,u=(await this.getWorkspacesUrls()).workspacesUrl.current,d=u.includes("?")?`${u}&emptyFrame=true`:`${u}?emptyFrame=true`;if(!window.open(d,c.windowId,l))return ioError.raiseError("Cannot open a new workspace frame, because the user has not allowed popups or uses a blocker");this.sessionController.saveFrameData(c);try{return await this.waitHello(c.windowId),{windowId:c.windowId}}catch(e){return delete this.locks[c.windowId],ioError.raiseError("Cannot open a new frame, because the workspace frame app did not send a hello in time")}}async closeFrame(e){if(this.myFrameId===e)return ioError.raiseError("Cannot close the platform frame, because it is the current frame");this.sessionController.getFrameData(e)&&(this.handleFrameDisappeared(e),window.open(void 0,e)?.close())}processNewHello(e){this.sessionController.getFrameData(e)&&(this.sessionController.setFrameActive(e),this.locks[e]?.lift())}handleFrameDisappeared(e){this.sessionController.getFrameData(e)&&(this.sessionController.removeFrameData(e),this.clearAllWorkspaceWindows(e))}getAll(){return this.sessionController.getAllFrames().filter(e=>e.active).map(e=>({windowId:e.windowId}))}async getFrameInstance(e){if(e){if(["frameId","itemId","newFrame"].reduce((t,r)=>(e[r]&&t.push(r),t),[]).length>1)return ioError.raiseError(`Cannot retrieve the frame, because of over-specification: the provided selection object must have either 1 or none of the possible properties: ${JSON.stringify(e)}`)}const t=this.getAll();if(e?.frameId){const r=t.find(t=>t.windowId===e.frameId);return r||ioError.raiseError(`Cannot retrieve a frame with Id: ${e.frameId}, because it is not known by the platform`)}return e?.itemId?this.getFrameByItemId(e.itemId,t):e?.newFrame?this.openFrame(e.newFrame):t.length?this.getLastOpenedFrame():this.openFrame()}getPlatformFrameSessionData(){return this.sessionController.getAllFrames().find(e=>e.isPlatform)}getFrameConfig(e){return this.sessionController.getAllFrames().find(t=>t.windowId===e)}clearAllWorkspaceWindows(e){this.sessionController.pickWorkspaceClients(t=>t.frameId===e).forEach(e=>{this.ioc.applicationsController.unregisterWorkspaceApp({windowId:e.windowId})})}async waitHello(e){return PromisePlus(t=>{this.locks[e]={lift:t}},this.defaultFrameHelloTimeoutMs,"Frame hello timed out")}getLastOpenedFrame(){const e=this.sessionController.getAllFrames().filter(e=>e.active);return e[e.length-1]}async getFrameByItemId(e,t){if(!t.length)return ioError.raiseError(`Cannot get frame by item id for: ${e}, because not frames were found`);for(const r of t){if("none"!==(await this.glueController.callFrame(this.frameSummaryOperation,{itemId:e},r.windowId)).id)return r}return ioError.raiseError(`Cannot find frame for item: ${e}`)}getWorkspacesUrls(){return new URL(window.location.href).protocol.includes("extension")?new Promise(e=>{chrome.storage.local.get("workspacesUrl",t=>{e(t)})}):Promise.resolve({workspacesUrl:{current:this.config.src,default:this.config.src}})}}class WorkspaceHibernationWatcher{session;sequelizer;workspacesController;settings;running;constructor(e,t){this.session=e,this.sequelizer=t}get logger(){return logger.get("workspaces.hibernation")}stop(){this.running=!1}start(e,t){this.logger?.trace(`starting the hibernation watcher with following settings: ${JSON.stringify(this.settings)}`),this.running=!0,this.workspacesController=e,this.settings=t;const r=this.session.exportClearTimeouts();this.settings?.idleWorkspaces?.idleMSThreshold&&r.forEach(e=>this.buildTimer(e.workspaceId)),this.logger?.trace("The hibernation watcher has started successfully")}notifyEvent(e){"window"===e.type&&this.handleWorkspaceWindowEvent(e),"workspace"===e.type&&this.handleWorkspaceEvent(e)}handleWorkspaceWindowEvent(e){("opened"===e.action||"added"===e.action)&&(this.sequelizer.enqueue(()=>this.checkMaximumAmountCore()),this.addTimersForWorkspacesInFrame(e.payload.windowSummary.config.frameId))}handleWorkspaceEvent(e){const t="selected"===e.action,r="lock-configuration-changed"===e.action,n=e.payload;if(!("selected"===e.action||"opened"===e.action||"lock-configuration-changed"===e.action))return;this.sequelizer.enqueue(()=>this.checkMaximumAmountCore());const i=n.workspaceSummary.config.allowSystemHibernation;if(!(t||r&&i))return;const o=this.session.getTimeout(n.workspaceSummary.id);o&&(clearTimeout(o),this.session.removeTimeout(n.workspaceSummary.id)),this.addTimersForWorkspacesInFrame(n.frameSummary.id)}compare(e,t){return e.config.lastActive>t.config.lastActive?1:e.config.lastActive<t.config.lastActive?-1:0}async checkMaximumAmountCore(){const e=this.settings?.maximumActiveWorkspaces?.threshold;if(this.logger?.trace(`Checking for maximum active workspaces rule. The threshold is ${e}`),"number"!=typeof e)return;const t=nanoid$3(10),r=(await this.workspacesController.getAllWorkspacesSummaries({},t)).summaries.map(e=>this.workspacesController.getWorkspaceSnapshot({itemId:e.id},t)),n=(await Promise.all(r)).filter(e=>!this.isWorkspaceHibernated(e.config)&&!this.isWorkspaceEmpty(e)),i=n.filter(e=>this.isSystemHibernationAllowed(e));if(n.length<=e)return;this.logger?.trace(`Found ${i.length} eligible for hibernation workspaces`);const o=i.sort(this.compare).slice(0,n.length-e).map(e=>this.tryHibernateWorkspace(e.id));await Promise.all(o)}async tryHibernateWorkspace(e){try{const t=await this.workspacesController.getWorkspaceSnapshot({itemId:e},nanoid$3(10));if(!this.canBeHibernated(t))return;this.logger?.trace(`trying to hibernate workspace ${e}`),await this.workspacesController.hibernateWorkspace({workspaceId:e},nanoid$3(10)),this.logger?.trace(`workspace ${e} was hibernated successfully`)}catch(e){this.logger?.trace(e)}}canBeHibernated(e){const t=this.isWorkspaceHibernated(e.config),r=this.isWorkspaceSelected(e.config),n=this.isWorkspaceEmpty(e),i=this.isSystemHibernationAllowed(e);return!t&&!r&&!n&&i}isWorkspaceHibernated(e){return e.isHibernated}isWorkspaceSelected(e){return e.isSelected}isWorkspaceEmpty(e){return!e.children.length}isSystemHibernationAllowed(e){const{allowSystemHibernation:t}=e.config;return"boolean"!=typeof t||t}async getWorkspacesInFrame(e){const t=(await this.workspacesController.getAllWorkspacesSummaries({},nanoid$3(10))).summaries.reduce((t,r)=>(r.config.frameId===e&&t.push(this.workspacesController.getWorkspaceSnapshot({itemId:r.id},nanoid$3(10))),t),[]);return await Promise.all(t)}async addTimersForWorkspacesInFrame(e){if(!this.settings?.idleWorkspaces?.idleMSThreshold)return;(await this.getWorkspacesInFrame(e)).forEach(e=>{this.canBeHibernated(e)&&!this.session.getTimeout(e.id)&&(this.buildTimer(e.id),this.logger?.trace(`Starting workspace idle timer ( ${this.settings?.idleWorkspaces?.idleMSThreshold}ms ) for workspace ${e.id}`))})}buildTimer(e){const t=window.setTimeout(()=>{this.running&&(this.logger?.trace(`Timer triggered will try to hibernated ${e}`),this.tryHibernateWorkspace(e),this.session.removeTimeout(e))},this.settings?.idleWorkspaces?.idleMSThreshold);this.session.saveTimeout(e,t)}}class SystemController{session;workspacesController;glueController;pluginsController;profileData;environment;base={};started=!1;errorPort=errorChannel.port2;registry=CallbackRegistryFactory$2();platformOperations=["cleanupClientsOnWorkspaceFrameUnregister"];operations={getEnvironment:{name:"getEnvironment",resultDecoder:anyDecoder,execute:this.handleGetEnvironment.bind(this)},getBase:{name:"getBase",resultDecoder:anyDecoder,execute:this.handleGetBase.bind(this)},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)},workspacesInitCheck:{name:"workspacesInitCheck",resultDecoder:workspacesInitCheckResultDecoder,execute:this.handleWorkspacesInitCheck.bind(this)},clientError:{name:"clientError",dataDecoder:clientErrorDataDecoder,execute:this.handleClientError.bind(this)},systemHello:{name:"systemHello",resultDecoder:systemHelloSuccessDecoder,execute:this.handleSystemHello.bind(this)},getProfileData:{name:"getProfileData",execute:this.handleGetProfileData.bind(this)}};constructor(e,t,r,n){this.session=e,this.workspacesController=t,this.glueController=r,this.pluginsController=n}get logger(){return logger.get("system.controller")}handlePlatformShutdown(){this.started=!1,this.registry.clear()}async start(e){this.environment=e.environment,this.base={workspaces:{frameCache:e.workspacesFrameCache},workspacesFrameCache:e.workspacesFrameCache,communicationId:this.session.getSystemSettings()?.systemInstanceId,platformVersion:version$1,connectionProtocolVersion:connectionProtocolVersion,fdc3:{webProxyUrl:FDC3ProxyUrl}},this.profileData=e.profileData,this.errorPort.onmessage=e=>{this.registry.execute("platform-error",{message:e.data})},this.started=!0}ready(){return Promise.resolve()}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this system control message, because the controller has not been started");const t=e.data,r=e.commandId,n=e.callerId,i=systemOperationTypesDecoder.run(e.operation);if(!i.ok)return ioError.raiseError(`This system request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(i.error)}`);const o=i.result,s=this.operations[o].dataDecoder?.run(t);if(s&&!s.ok)return ioError.raiseError(`System request for ${o} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(s.error)}`);this.logger?.debug(`[${r}] ${o} command is valid with data: ${JSON.stringify(t)}`);const a=await this.operations[o].execute(t,r,n),c=this.operations[o].resultDecoder?.run(a);return c&&!c.ok?ioError.raiseError(`System request for ${o} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(c.error)}`):(this.logger?.trace(`[${r}] ${o} command was executed successfully`),a)}onPlatformError(e){return this.registry.add("platform-error",e)}onClientError(e){return this.registry.add("client-error",e)}setProfileData(e){this.profileData=e}async handleOperationCheck(e){const t=Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase()),r=this.platformOperations.some(t=>t.toLowerCase()===e.operation.toLowerCase());return{isSupported:t||r}}async handleGetEnvironment(){return this.environment}async handleGetProfileData(){if(!this.profileData)return;return{...this.profileData,plugins:this.pluginsController.registeredPlugins.map(e=>({name:e.name,version:e.version}))}}async handleGetBase(){return this.base}async handleWorkspacesInitCheck(){return{initialized:this.workspacesController.started}}async handleClientError({message:e},t,r){this.logger?.trace(`[${t}] received clientError command with message ${e} from callerId: ${r}`),this.glueController.clientGlue?r&&r===this.glueController.me.instance?this.registry.execute("platform-error",{message:e}):this.registry.execute("client-error",{message:e,callerId:r}):this.registry.execute("platform-error",{message:e})}async handleSystemHello(){return{isClientErrorOperationSupported:!0}}}class AppDirectory{remoteWatcher;manager;cache;unsubFuncs=[];maxAllowedApplicationsInStore=1e4;baseEventFlushDurationMs=10;appsStateChange;sequelizer;isManagerConfigured;constructor(e,t,r){this.remoteWatcher=e,this.manager=t,this.cache=r}stop(){this.unsubFuncs.forEach(e=>e()),this.unsubFuncs=[]}async start(e){if(this.logger?.trace("Starting the application directory"),this.appsStateChange=e.appsStateChange,this.sequelizer=e.sequelizer,await this.cache.start(e.config.remote),e.config.local?.length&&(this.logger?.trace("Detected local applications, parsing..."),await this.processAppDefinitions(e.config.local,{type:"inmemory",mode:"merge"})),e.isManagerConfigured&&(this.isManagerConfigured=e.isManagerConfigured,this.setupManagerListeners(),this.logger?.trace("Detected manager configuration, starting the watcher...")),e.config.remote){this.logger?.trace("Detected remote app store configuration, starting the watcher...");try{await this.remoteWatcher.start(e.config.remote,e=>this.processAppDefinitions(e,{type:"remote",mode:"replace"}))}catch(e){return this.handleRemoteConnectionFailure(e)}}}processAppDefinitions(e,t){return this.sequelizer.enqueue(async()=>{const r=e.map(e=>this.parseDefinition(e)),n=[...await this.cache.getAllRemoteApps(),...await this.cache.getAllMemoryApps()],i=this[t.mode](n,r);if(i.readyApps.length>this.maxAllowedApplicationsInStore)return ioError.raiseError("Cannot save the app definitions, because the total number exceeds 10000, which is the limit.");const o="remote"===t.type?this.cache.saveRemoteApps.bind(this.cache):this.cache.saveMemoryApps.bind(this.cache);await o(i.readyApps),await this.announceApps(i)})}getAll(){return this.sequelizer.enqueue(async()=>{const e=new Map,t=await this.cache.getAllMemoryApps(),r=await this.cache.getAllRemoteApps(),n=this.isManagerConfigured?this.manager.getAllApps().map(this.parseDefinition):[];return r.forEach(t=>e.set(t.name,t)),n.forEach(t=>e.set(t.name,t)),t.forEach(t=>e.set(t.name,t)),Array.from(e.values())})}exportInMemory(){return this.sequelizer.enqueue(async()=>(await this.cache.getAllMemoryApps()).map(this.reverseParseDefinition))}removeInMemory(e){return this.sequelizer.enqueue(async()=>this.cache.removeMemoryApp(e))}merge(e,t){const r={readyApps:[],addedApps:[],changedApps:[],removedApps:[]},n=e.reduce((e,t)=>(e[t.name]=t,e),{});return t.forEach(e=>n[e.name]&&!objEqualFast(e,n[e.name])?(n[e.name]=e,void r.changedApps.push(e)):n[e.name]?void 0:(n[e.name]=e,void r.addedApps.push(e))),r.readyApps=Object.values(n),r}replace(e,t){const r={readyApps:[],addedApps:[],changedApps:[],removedApps:[]},n=e.reduce((e,t)=>(e[t.name]=t,e),{});return t.forEach(e=>{n[e.name]||r.addedApps.push(e),n[e.name]&&!objEqualFast(e,n[e.name])&&r.changedApps.push(e),n[e.name]&&(n[e.name].isChecked=!0)}),r.removedApps=e.filter(e=>!e.isChecked),r.readyApps=t,r}reverseParseDefinition(e){const{details:t,intents:r,hidden:n,...i}=e.userProperties;void 0!==r&&(i.intents=r),void 0!==n&&(i.hidden=n);const o={name:e.name,type:e.type,details:t,customProperties:i},s={title:e.title,version:e.version,icon:e.icon,caption:e.caption,intents:r,hidden:n,fdc3:e.fdc3};for(const[e,t]of Object.entries(s))void 0!==t&&(o[e]=t);return o}parseDefinition(e){const t=["name","title","version","customProperties","icon","caption","type"],r=Object.fromEntries(Object.entries(e).filter(([e])=>!t.includes(e))),{isFdc3:n}=fdc3.isFdc3Definition(e);let i;if(n)i=fdc3.parseToBrowserBaseAppData(e);else{const t=e.details;i={createOptions:t,type:e.type||"window",name:e.name,title:e.title,version:e.version,icon:e.icon,caption:e.caption,userProperties:{...r,...e.customProperties}},i.userProperties.details||(i.userProperties.details=t)}return Object.keys(i).forEach(e=>void 0===i[e]&&delete i[e]),i}get logger(){return logger.get("applications.remote.directory")}async announceApps(e){const t={appsAdded:e.addedApps,appsChanged:e.changedApps,appsRemoved:e.removedApps};this.logger?.trace(`announcing a change in the app directory state: ${JSON.stringify(t)}`),this.appsStateChange(t),await this.waitEventFlush()}setupManagerListeners(){const e=this.manager.onAppsAdded(e=>{this.announceApps({addedApps:e.map(this.parseDefinition),changedApps:[],removedApps:[],readyApps:[]}).catch(e=>this.logger?.warn(extractErrorMsg$1(e)))}),t=this.manager.onAppsDeleted(e=>{this.announceApps({addedApps:[],changedApps:[],removedApps:e.map(this.parseDefinition),readyApps:[]}).catch(e=>this.logger?.warn(extractErrorMsg$1(e)))}),r=this.manager.onAppsChanged(e=>{this.announceApps({addedApps:[],changedApps:e.map(this.parseDefinition),removedApps:[],readyApps:[]}).catch(e=>this.logger?.warn(extractErrorMsg$1(e)))});this.unsubFuncs.push(e,t,r)}waitEventFlush(){return new Promise(e=>setTimeout(e,this.baseEventFlushDurationMs))}async handleRemoteConnectionFailure(e){const t=await this.cache.getAllRemoteApps();if(!t?.length)return ioError.raiseError(`The connection to the remote app store failed and there are no cached entries, cannot continue. Error: ${extractErrorMsg$1(e)}`);this.logger?.warn(`The connection to the remote app store failed, but there are cached entries, continuing with the cached apps. Error: ${extractErrorMsg$1(e)}`)}}const defaultRemoteWatcherHeaders={"Content-Type":"application/json",Accept:"application/json"},defaultRemoteWatcherRequestTimeoutMS=3e3,fetchTimeout=(e,t=defaultFetchTimeoutMs,r=new AbortController)=>new Promise((n,i)=>{const o={signal:r.signal};let s=!1;const a=setTimeout(()=>{s=!0,i(new Error(`Fetch request for: ${JSON.stringify(e)} timed out at: ${t} milliseconds`)),r.abort()},t);fetch(e,o).then(e=>{s||(clearTimeout(a),n(e))}).catch(e=>{s||(clearTimeout(a),i(e))})});class RemoteWatcher{scheduler;handleApps;config;constructor(e){this.scheduler=e}async start(e,t){this.handleApps=t,this.config=this.prepareConfig(e);const r=this.doInitialRequest();if(this.configureScheduler(),this.config.waitInitialResponse)return this.logger?.info("Waiting for the initial response from the remote app store before proceeding"),void await r;r.catch(e=>this.logger?.error("The initial request to the remote app store failed",e))}getRequest(){const e=new Headers;for(const t in defaultRemoteWatcherHeaders)e.append(t,defaultRemoteWatcherHeaders[t]);for(const t in this.config.customHeaders)this.logger?.trace("Custom headers detected and set"),e.append(t,this.config.customHeaders[t]);const t={method:"GET",headers:e,mode:"cors",cache:"default"},r=this.config.getRequestInit?.({url:this.config.url,requestInit:t});return new Request(this.config.url,{...t,...r})}get logger(){return logger.get("applications.remote.directory")}prepareConfig(e){const t={...e,requestTimeout:e.requestTimeout??defaultRemoteWatcherRequestTimeoutMS,customHeaders:e.customHeaders??{},getRequestInit:e.getRequestInit??(()=>({})),waitInitialResponse:e.waitInitialResponse??!0};return t.cache?.enabled&&!t.pollingInterval?ioError.raiseError("Polling interval is required when cache is enabled"):t.pollingInterval&&t.pollingInterval<5e3?ioError.raiseError("Polling interval must be at least 5000ms"):t}configureScheduler(){if(!this.config.pollingInterval)return void this.logger?.info("Polling interval is not set, skipping scheduler setup");const e="applications:get:all";if(this.scheduler.checkEntryExists(e))return;const t={key:e,getRequest:()=>this.getRequest(),timeout:this.config.requestTimeout,refreshIntervalMS:this.config.pollingInterval,onData:this.processGetAllAppsUpdate.bind(this),onError:e=>this.logger?.error("Error during get all application definitions from scheduler",e)};this.scheduler.register(t)}async processGetAllAppsUpdate(e){if(!e||!Array.isArray(e.applications))return this.logger?.warn("The remote response was either empty or did not contain an applications collection");this.logger?.trace("There is a valid response from the app store, processing definitions...");const t=e.applications.reduce((e,t)=>{const r=allApplicationDefinitionsDecoder.run(t);return r.ok?e.push(t):this.logger?.warn(`Removing applications definition with name: ${t.name} from the remote response, because of validation error: ${JSON.stringify(r.error)}`),e},[]);await this.handleApps(t)}async doInitialRequest(){try{const e=this.getRequest(),t=await fetchTimeout(e,this.config.requestTimeout),r=await t.json();await this.processGetAllAppsUpdate(r)}catch(e){return ioError.raiseError("Error during initial request to get all applications",e)}}}class ServiceWorkerController{idbController;registry=CallbackRegistryFactory$2();_serviceWorkerRegistration;channel;_broadcastMessageHandler;constructor(e){this.idbController=e}get logger(){return logger.get("service.worker.web.platform")}get serviceWorkerRegistration(){return this._serviceWorkerRegistration?this._serviceWorkerRegistration:ioError.raiseError("Accessing missing service worker registration object. This is caused because the application is trying to raise a persistent notification, which requires a service worker. Please provide a service worker config when initializing GlueWebPlatform.")}shutdown(){this.channel?.removeEventListener("message",this._broadcastMessageHandler),this.registry.clear()}async connect(e){if(e.serviceWorker){if(this.logger?.info("Detected service worker definition, connecting..."),!e.serviceWorker.url&&void 0===e.serviceWorker.registrationPromise)return ioError.raiseError("The service worker config is defined, but it is missing a url or a registration promise, please provide one or the other");if(e.serviceWorker.url&&void 0!==e.serviceWorker.registrationPromise)return ioError.raiseError("The service worker is over-specified, there is both defined url and a registration promise, please provide one or the other");await this.prepareSwDb(),this._serviceWorkerRegistration=e.serviceWorker.url?await this.registerWorker(e.serviceWorker.url):await this.waitRegistration(e.serviceWorker.registrationPromise),this._serviceWorkerRegistration&&this.setUpBroadcastChannelConnection(),this.logger?.info("Service worker connection completed.")}}async showNotification(e,t){const r=Object.assign({},e,{title:void 0,clickInterop:void 0,actions:void 0});r.actions=e.actions?.map(e=>({action:e.action,title:e.title,icon:e.icon}));const n={focusPlatformOnDefaultClick:e.focusPlatformOnDefaultClick,clickInterop:e.clickInterop,actions:e.actions,id:t};r.data?r.data.glueData=n:r.data={glueData:n},await this.serviceWorkerRegistration.showNotification(e.title,r)}notifyReady(){this._serviceWorkerRegistration&&this.channel.postMessage({platformStarted:!0})}onNotificationClick(e){return this.registry.add("notification-click",e)}onNotificationClose(e){return this.registry.add("notification-close",e)}setUpBroadcastChannelConnection(){this.channel=new BroadcastChannel(serviceWorkerBroadcastChannelName),this._broadcastMessageHandler=this.broadcastMessageHandler.bind(this),this.channel.addEventListener("message",this._broadcastMessageHandler)}broadcastMessageHandler(e){const t=e.data,r=t?.messageType;if(r)if("ping"!==r){if("notificationClick"===r){const e=t.action,r=t.glueData;return void this.registry.execute("notification-click",{action:e,glueData:r})}if("notificationClose"===r){const e=t.action,r=t.glueData;return void this.registry.execute("notification-close",{action:e,glueData:r})}"notificationError"!==r||this.logger?.error(`Service worker error when raising notification: ${t.error}`)}else this.channel.postMessage({pong:!0})}async registerWorker(e){if("serviceWorker"in navigator)try{return await navigator.serviceWorker.register(e)}catch(e){const t="string"==typeof e?e:JSON.stringify(e.message);this.logger?.warn(t)}else this.logger?.warn(`A defined service worker has not been registered at ${e} because this browser does not support it.`)}async waitRegistration(e){if("function"!=typeof e.then||"function"!=typeof e.catch)return ioError.raiseError("The provided service worker registration promise is not a promise");const t=await e;return"function"!=typeof t.showNotification?ioError.raiseError("The provided registration promise is a promise, but it resolved with an object which does not appear to be a ServiceWorkerRegistration"):t}async prepareSwDb(){await this.idbController.clearServiceWorker(),await this.idbController.storeServiceWorker({platformUrl:window.location.href})}}const setNotificationDefaults=e=>{e.showToast="boolean"!=typeof e.showToast||e.showToast,e.showInPanel="boolean"!=typeof e.showInPanel||e.showInPanel,e.timestamp=void 0===e.timestamp?Date.now():e.timestamp,e.state=void 0===e.state?"Active":e.state},notificationsOperationDecoder=oneOf$1(constant$2("raiseNotification"),constant$2("requestPermission"),constant$2("getPermission"),constant$2("operationCheck"),constant$2("list"),constant$2("clear"),constant$2("click"),constant$2("clearAll"),constant$2("configure"),constant$2("getConfiguration"),constant$2("setState"),constant$2("clearOld"),constant$2("getActiveCount")),interopActionSettingsDecoder=object$2({method:nonEmptyStringDecoder$2,arguments:optional$3(anyJson$2()),target:optional$3(oneOf$1(constant$2("all"),constant$2("best")))}),glue42NotificationActionDecoder=object$2({action:string$4(),title:nonEmptyStringDecoder$2,icon:optional$3(string$4()),interop:optional$3(interopActionSettingsDecoder)}),notificationStateDecoder=oneOf$1(constant$2("Active"),constant$2("Acknowledged"),constant$2("Seen"),constant$2("Closed"),constant$2("Stale"),constant$2("Snoozed"),constant$2("Processing")),glue42NotificationOptionsDecoder=object$2({title:nonEmptyStringDecoder$2,clickInterop:optional$3(interopActionSettingsDecoder),actions:optional$3(array$3(glue42NotificationActionDecoder)),focusPlatformOnDefaultClick:optional$3(boolean$3()),badge:optional$3(string$4()),body:optional$3(string$4()),data:optional$3(anyJson$2()),dir:optional$3(oneOf$1(constant$2("auto"),constant$2("ltr"),constant$2("rtl"))),icon:optional$3(string$4()),image:optional$3(string$4()),lang:optional$3(string$4()),renotify:optional$3(boolean$3()),requireInteraction:optional$3(boolean$3()),silent:optional$3(boolean$3()),tag:optional$3(string$4()),timestamp:optional$3(nonNegativeNumberDecoder$2),vibrate:optional$3(array$3(number$4())),severity:optional$3(oneOf$1(constant$2("Low"),constant$2("None"),constant$2("Medium"),constant$2("High"),constant$2("Critical"))),showToast:optional$3(boolean$3()),showInPanel:optional$3(boolean$3()),state:optional$3(notificationStateDecoder)}),glue42NotificationOptionsWithDefaultsDecoder=object$2({title:nonEmptyStringDecoder$2,clickInterop:optional$3(interopActionSettingsDecoder),actions:optional$3(array$3(glue42NotificationActionDecoder)),focusPlatformOnDefaultClick:optional$3(boolean$3()),badge:optional$3(string$4()),body:optional$3(string$4()),data:optional$3(anyJson$2()),dir:optional$3(oneOf$1(constant$2("auto"),constant$2("ltr"),constant$2("rtl"))),icon:optional$3(string$4()),image:optional$3(string$4()),lang:optional$3(string$4()),renotify:optional$3(boolean$3()),requireInteraction:optional$3(boolean$3()),silent:optional$3(boolean$3()),tag:optional$3(string$4()),timestamp:nonNegativeNumberDecoder$2,vibrate:optional$3(array$3(number$4())),severity:optional$3(oneOf$1(constant$2("Low"),constant$2("None"),constant$2("Medium"),constant$2("High"),constant$2("Critical"))),showToast:boolean$3(),showInPanel:boolean$3(),state:optional$3(notificationStateDecoder)}),raiseNotificationDecoder=object$2({settings:glue42NotificationOptionsDecoder,id:nonEmptyStringDecoder$2}),raiseNotificationResultDecoder=object$2({settings:glue42NotificationOptionsWithDefaultsDecoder}),permissionRequestResultDecoder=object$2({permissionGranted:boolean$3()}),permissionQueryResultDecoder=object$2({permission:oneOf$1(constant$2("default"),constant$2("granted"),constant$2("denied"))}),simpleNotificationSelectDecoder=object$2({id:nonEmptyStringDecoder$2}),notificationClickConfigDecoder=object$2({id:nonEmptyStringDecoder$2,action:optional$3(nonEmptyStringDecoder$2)}),notificationsDataDecoder=object$2({id:nonEmptyStringDecoder$2,title:nonEmptyStringDecoder$2,clickInterop:optional$3(interopActionSettingsDecoder),actions:optional$3(array$3(glue42NotificationActionDecoder)),focusPlatformOnDefaultClick:optional$3(boolean$3()),badge:optional$3(string$4()),body:optional$3(string$4()),data:optional$3(anyJson$2()),dir:optional$3(oneOf$1(constant$2("auto"),constant$2("ltr"),constant$2("rtl"))),icon:optional$3(string$4()),image:optional$3(string$4()),lang:optional$3(string$4()),renotify:optional$3(boolean$3()),requireInteraction:optional$3(boolean$3()),silent:optional$3(boolean$3()),tag:optional$3(string$4()),timestamp:optional$3(nonNegativeNumberDecoder$2),vibrate:optional$3(array$3(number$4())),severity:optional$3(oneOf$1(constant$2("Low"),constant$2("None"),constant$2("Medium"),constant$2("High"),constant$2("Critical"))),showToast:optional$3(boolean$3()),showInPanel:optional$3(boolean$3()),state:optional$3(notificationStateDecoder)}),allNotificationsDataDecoder=object$2({notifications:array$3(notificationsDataDecoder)}),notificationsConfigurationDecoder=object$2({enable:optional$3(boolean$3()),enableToasts:optional$3(boolean$3()),sourceFilter:optional$3(notificationFilterDecoder),showNotificationBadge:optional$3(boolean$3())}),notificationsConfigurationProtocolDecoder=object$2({configuration:notificationsConfigurationDecoder}),notificationsActiveCountDecoder=object$2({count:number$4()}),notificationSetStateRequestDecoder=object$2({id:nonEmptyStringDecoder$2,state:notificationStateDecoder}),prefsNotificationsDecoder=object$2({config:notificationsConfigurationDecoder});class NotificationsController{glueController;serviceWorkerController;session;localStorage;prefsController;started=!1;isInExtension=!1;clearNotificationOnClick;extNotificationConfig;systemUnsubFuncs=[];_chromeClickedHandler;_chromeButtonClickedHandler;_chromeClosedHandler;operations={raiseNotification:{name:"raiseNotification",execute:this.handleRaiseNotification.bind(this),dataDecoder:raiseNotificationDecoder,resultDecoder:raiseNotificationResultDecoder},requestPermission:{name:"requestPermission",resultDecoder:permissionRequestResultDecoder,execute:this.handleRequestPermission.bind(this)},getPermission:{name:"getPermission",resultDecoder:permissionQueryResultDecoder,execute:this.handleGetPermission.bind(this)},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)},list:{name:"list",resultDecoder:allNotificationsDataDecoder,execute:this.handleList.bind(this)},click:{name:"click",dataDecoder:notificationClickConfigDecoder,execute:this.handleClick.bind(this)},clear:{name:"clear",dataDecoder:simpleNotificationSelectDecoder,execute:this.handleClear.bind(this)},clearAll:{name:"clearAll",execute:this.handleClearAll.bind(this)},configure:{name:"configure",dataDecoder:notificationsConfigurationProtocolDecoder,execute:this.handleConfigure.bind(this)},getActiveCount:{name:"getActiveCount",resultDecoder:notificationsActiveCountDecoder,execute:this.handleGetActiveCount.bind(this)},getConfiguration:{name:"getConfiguration",resultDecoder:notificationsConfigurationProtocolDecoder,execute:this.handleGetConfiguration.bind(this)},setState:{name:"setState",dataDecoder:notificationSetStateRequestDecoder,execute:this.handleSetState.bind(this)},clearOld:{name:"clearOld",execute:this.handleClearOld.bind(this)}};constructor(e,t,r,n,i){this.glueController=e,this.serviceWorkerController=t,this.session=r,this.localStorage=n,this.prefsController=i}get logger(){return logger.get("notifications.controller")}get config(){const e=this.localStorage.getNotificationsConfig();return e||ioError.raiseError("The notifications configuration has not been set.")}get currentActiveCount(){return this.session.getAllNotifications().reduce((e,t)=>"Active"===t.state?e+1:e,0)}handlePlatformShutdown(){this.started=!1;new URL(window.location.href).protocol.includes("extension")&&this.removeExtensionNotificationsListeners(),this.systemUnsubFuncs.forEach(e=>e()),this.systemUnsubFuncs=[]}async start(){this.clearNotificationOnClick=this.config.clearNotificationOnClick;new URL(window.location.href).protocol.includes("extension")&&await this.setupExtensionNotifications(),this.listenForServiceWorkerNotificationEvents(),this.started=!0}async setupInitialConfig(){const e=this.prefsController.storeType;if(!e||"local"===e)return void this.logger?.info("The notifications service will use the local storage for the notifications configuration");let t;try{t=await this.glueController.clientGlue.prefs.get(systemPrefsAppName)}catch(e){return void this.logger?.warn(`Failed to get the system preferences for the notifications service: ${e}, falling back to local storage`)}const r=t?.data[notificationsPrefsKey];if(!r)return void this.logger?.info("The system preferences for the notifications service are not set in prefs, falling back to local storage");const n=prefsNotificationsDecoder.run(r);if(!n.ok)return void this.logger?.error(`The system preferences from Prefs for the notifications service did not pass validation: ${JSON.stringify(n.error)}, falling back to local storage`);const i=n.result.config;this.localStorage.updateNotificationsConfig(i)}ready(){return Promise.resolve()}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this notifications control message, because the controller has not been started");const t=e.data,r=e.commandId,n=e.callerId,i=notificationsOperationDecoder.run(e.operation);if(!i.ok)return ioError.raiseError(`This notifications request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(i.error)}`);const o=i.result,s=this.operations[o].dataDecoder?.run(t);if(s&&!s.ok)return ioError.raiseError(`Notifications request for ${o} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(s.error)}`);this.logger?.debug(`[${r}] ${o} command is valid with data: ${JSON.stringify(t)}`);const a=await this.operations[o].execute(t,r,n),c=this.operations[o].resultDecoder?.run(a);return c&&!c.ok?ioError.raiseError(`Notifications request for ${o} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(c.error)}`):(this.logger?.trace(`[${r}] ${o} command was executed successfully`),a)}async handleConfigure({configuration:e},t,r=""){if(this.logger?.trace(`[${t}] handling a notification configure message with data: ${JSON.stringify(e)}`),this.validateServiceAccess(r,!0),this.localStorage.updateNotificationsConfig(e),this.glueController.pushSystemMessage("notifications","configurationChanged",{configuration:this.config}),"local"!==this.prefsController.storeType){const e={config:this.config};this.glueController.clientGlue.prefs.update({[notificationsPrefsKey]:e},{app:systemPrefsAppName}).catch(e=>{this.logger?.warn(`Failed to update the notifications configuration in prefs: ${e} - the settings are only updated in the local storage`)})}this.logger?.trace(`[${t}] handling a notification configure message completed`)}async handleGetActiveCount(e,t){return this.logger?.trace(`[${t}] handling a get active count message`),{count:this.currentActiveCount}}async handleGetConfiguration(e,t){this.logger?.trace(`[${t}] handling a get notification configure message`);const r={...this.config};return this.logger?.trace(`[${t}] handling a get notification configure message completed`),{configuration:r}}async handleList(e,t){this.logger?.trace(`[${t}] handling a list notification message`);const r=this.session.getAllNotifications();return this.logger?.trace(`[${t}] list notification message completed`),{notifications:r}}async handleSetState({id:e,state:t},r){this.logger?.trace(`[${r}] handling a set state notification message with data: ${JSON.stringify({id:e,state:t})}`);const n=this.session.getNotification(e);if(!n)return ioError.raiseError(`Cannot set state of a notification: ${e}, because it doesn't exist`);const i=this.currentActiveCount;n.state=t,this.session.updateNotification(n),this.glueController.pushSystemMessage("notifications","stateChange",{id:e,state:t}),this.syncActiveCount(i)}async handleClick(e,t){this.logger?.trace(`[${t}] handling a click notification message with data: ${JSON.stringify(e)}`);const r=this.session.getNotification(e.id);return r?e.action&&r.actions?.every(t=>t.action!==e.action)?ioError.raiseError(`Cannot click action ${e.action} of ${e.id}, because that notification does not have that action`):(this.handleNotificationClick({notification:r,action:e.action}),void this.logger?.trace(`[${t}] handling a click notification message completed`)):ioError.raiseError(`Cannot click a notification: ${e.id}, because it doesn't exist`)}async handleClear(e,t){this.logger?.trace(`[${t}] handling a clear notification message with data: ${JSON.stringify(e)}`);const r=this.currentActiveCount;this.removeNotification(e.id),this.syncActiveCount(r),this.logger?.trace(`[${t}] handling a clear notification message completed`)}async handleClearAll(e,t){this.logger?.trace(`[${t}] handling a clearAll notifications message`);const r=this.session.getAllNotifications(),n=r.reduce((e,t)=>"Active"===t.state?e+1:e,0);r.forEach(e=>this.removeNotification(e.id)),this.syncActiveCount(n),this.logger?.trace(`[${t}] handling a clearAll notification message completed`)}async handleClearOld(e,t){this.logger?.trace(`[${t}] handling a clearOld notifications message`);const r=this.session.getAllNotifications(),n=r.reduce((e,t)=>"Active"===t.state?e+1:e,0);r.filter(e=>"Active"!==e.state).forEach(e=>this.removeNotification(e.id)),this.syncActiveCount(n),this.logger?.trace(`[${t}] handling a clearOld notification message completed`)}async handleRaiseNotification({settings:e,id:t},r,n=""){if(this.logger?.trace(`[${r}] handling a raise notification message with a title: ${e.title}`),!this.config.enable)return ioError.raiseError("Cannot raise a notification, because the notifications service is disabled");this.validateServiceAccess(n);const i=this.currentActiveCount;setNotificationDefaults(e),this.processNewNotification(e,t);const o=this.config.enableToasts?!!e.showToast:this.config.enableToasts;await this.showToast({settings:e,id:t},o,r);const s={definition:Object.assign({},e,{title:void 0,clickInterop:void 0,actions:void 0}),id:t};return setTimeout(()=>this.glueController.pushSystemMessage("notifications","notificationShow",s),0),this.logger?.trace(`[${r}] notification with a title: ${e.title} was successfully raised`),this.syncActiveCount(i),{settings:e}}async showToast({settings:e,id:t},r,n){if(!r)return;if(this.isInExtension)return void await this.raiseExtensionToast(e,t,n);e.actions&&e.actions.length?await this.raiseActionsToast(e,t,n):this.raiseSimpleToast(e,t,n)}async handleGetPermission(e,t){this.logger?.trace(`[${t}] handling a get permission message`);const r=Notification.permission;return this.logger?.trace(`[${t}] permission for raising notifications is: ${r}`),{permission:r}}async handleRequestPermission(e,t){this.logger?.trace(`[${t}] handling a request permission message`);let r=Notification.permission;"granted"!==r&&(r=await Notification.requestPermission());const n="granted"===r;return this.logger?.trace(`[${t}] permission for raising notifications is: ${r}`),{permissionGranted:n}}validateServiceAccess(e,t){const r=this.glueController.getAppNameByInstanceId(e)||"";if(t&&e===this.glueController.me.instance)return;if(this.config.sourceFilter.blocked.includes(r))return ioError.raiseError(`Cannot complete the notifications operation, because the caller app: ${r} is blocked from the notifications service`);const n=this.config.sourceFilter.allowed.includes("*"),i=this.config.sourceFilter.allowed.includes(r);return n||i?void 0:ioError.raiseError(`Cannot complete the notifications operation, because the caller app: ${r} is not present in the allowed list of the notifications service`)}async raiseSimpleToast(e,t,r){this.logger?.trace(`[${r}] notification with a title: ${e.title} was found to be non-persistent and therefore will be raised with the native notifications API`);const n=Object.assign({},e,{title:void 0,clickInterop:void 0}),i=new Notification(e.title,n);i.onclick=()=>{e.focusPlatformOnDefaultClick&&window.focus();const r=this.session.getNotification(t);r&&this.handleNotificationClick({action:"",notification:r})},i.onclose=()=>{const e=this.currentActiveCount;this.removeNotification(t),this.syncActiveCount(e)}}async raiseActionsToast(e,t,r){this.logger?.trace(`[${r}] notification with a title: ${e.title} was found to be persistent and therefore the service worker will be instructed to raise it.`),await this.serviceWorkerController.showNotification(e,t)}raiseExtensionToast(e,t,r){return new Promise((n,i)=>{if(this.logger?.trace(`[${r}] notification with a title: ${e.title} will be raised with the native extension notifications API, because the platform is running in extension mode`),!this.extNotificationConfig)return i("Cannot raise a notification, because the environment settings for the extension mode are missing.");const o=e.actions?e.actions.map(e=>({title:e.title,iconUrl:e.icon})):void 0,s={type:"basic",iconUrl:e.icon||this.extNotificationConfig.defaultIcon,title:e.title,message:e.body||this.extNotificationConfig.defaultMessage,silent:e.silent,requireInteraction:e.requireInteraction,imageUrl:e.image,buttons:o};chrome.notifications.create(t,s,()=>n())})}async setupExtensionNotifications(){this.isInExtension=!0,this.extNotificationConfig=(await this.getExtNotificationsConfig()).notifications,this.listenForExtensionNotificationsEvents()}listenForExtensionNotificationsEvents(){this._chromeClickedHandler=this.chromeClickedHandler.bind(this),chrome.notifications.onClicked.addListener(this._chromeClickedHandler),this._chromeButtonClickedHandler=this.chromeButtonClickedHandler.bind(this),chrome.notifications.onButtonClicked.addListener(this._chromeButtonClickedHandler),this._chromeClosedHandler=this.chromeClosedHandler.bind(this),chrome.notifications.onClosed.addListener(this._chromeClosedHandler)}removeExtensionNotificationsListeners(){chrome.notifications.onClicked.removeListener(this._chromeClickedHandler),chrome.notifications.onButtonClicked.removeListener(this._chromeButtonClickedHandler),chrome.notifications.onClosed.removeListener(this._chromeClosedHandler)}chromeClickedHandler(e){const t=this.session.getNotification(e);t&&this.handleNotificationClick({notification:t})}chromeButtonClickedHandler(e,t){const r=this.session.getNotification(e);if(!r)return;if(!r.actions)return;const n=r.actions[t].action;this.handleNotificationClick({action:n,notification:r})}chromeClosedHandler(e){const t=this.currentActiveCount;this.removeNotification(e),this.syncActiveCount(t)}listenForServiceWorkerNotificationEvents(){const e=this.serviceWorkerController.onNotificationClick(e=>{const t=this.session.getNotification(e.glueData.id);t&&this.handleNotificationClick({action:e.action,notification:t})}),t=this.serviceWorkerController.onNotificationClose(e=>{const t=this.currentActiveCount;this.removeNotification(e.glueData.id),this.syncActiveCount(t)});this.systemUnsubFuncs.push(e),this.systemUnsubFuncs.push(t)}getExtNotificationsConfig(){return new Promise(e=>{chrome.storage.local.get("notifications",t=>{e(t)})})}handleNotificationClick(e){!e.action&&e.notification.clickInterop&&this.callDefinedInterop(e.notification.clickInterop);const t=e.action?e.notification.actions?.find(t=>t.action===e.action):null;t&&t.interop&&this.callDefinedInterop(t.interop),e.notification.data?.glueData&&delete e.notification.data.glueData;const r={definition:e.notification,action:e.action,id:e.notification.id};if(this.clearNotificationOnClick){const t=this.currentActiveCount;this.removeNotification(e.notification.id),this.syncActiveCount(t)}this.glueController.pushSystemMessage("notifications","notificationClick",r)}callDefinedInterop(e){const t=e.method,r=e.arguments,n=e.target;this.glueController.invokeMethod(t,r,n).catch(e=>{const t="string"==typeof e?e:JSON.stringify(e.message);this.logger?.warn(`The interop invocation defined in the clickInterop was rejected, reason: ${t}`)})}processNewNotification(e,t){const r={id:t,...e};this.session.saveNewNotification(r),this.glueController.pushSystemMessage("notifications","notificationRaised",{notification:r})}removeNotification(e){this.session.removeNotification(e),this.glueController.pushSystemMessage("notifications","notificationClosed",{id:e})}syncActiveCount(e){const t=this.currentActiveCount;e!==t&&this.glueController.pushSystemMessage("notifications","activeCountChange",{count:t})}}const extensionOperationTypesDecoder=oneOf$1(constant$2("clientHello"),constant$2("operationCheck")),clientHelloResponseDecoder=object$2({widget:object$2({inject:boolean$3()})}),clientHelloDecoder=object$2({windowId:optional$3(nonEmptyStringDecoder$2)});class ExtensionController{session;started=!1;operations={clientHello:{name:"appHello",resultDecoder:clientHelloResponseDecoder,dataDecoder:clientHelloDecoder,execute:this.handleClientHello.bind(this)},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)}};constructor(e){this.session=e}get logger(){return logger.get("extension.controller")}handlePlatformShutdown(){this.started=!1}async start(){this.started=!0,this.logger?.trace("initialization is completed")}ready(){return Promise.resolve()}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this extension control message, because the controller has not been started");const t=e.data,r=e.commandId,n=extensionOperationTypesDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This extension request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`Extension request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`Extension request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}async handleClientHello(e,t){this.logger?.trace(`[${t}] handling client hello command`);const r=(await this.getWidgetConfig()).widget,n={widget:{inject:!(!!e.windowId&&!!this.session.getFrameData(e.windowId))&&(!!r&&r.enable)}};return this.logger?.trace(`[${t}] responding to client hello command with: ${JSON.stringify(n)}`),n}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}getWidgetConfig(){return new URL(window.location.href).protocol.includes("extension")?new Promise(e=>{chrome.storage.local.get("widget",t=>{e(t)})}):Promise.resolve({widget:{enable:!1}})}}class AsyncSequelizer{minSequenceInterval;queue=[];isExecutingQueue=!1;constructor(e=0){this.minSequenceInterval=e}enqueue(e){return new Promise((t,r)=>{this.queue.push({action:e,resolve:t,reject:r}),this.executeQueue()})}async executeQueue(){if(!this.isExecutingQueue){for(this.isExecutingQueue=!0;this.queue.length;){const e=this.queue.shift();if(!e)return void(this.isExecutingQueue=!1);try{const t=await e.action();e.resolve(t)}catch(t){e.reject(t)}await this.intervalBreak()}this.isExecutingQueue=!1}}intervalBreak(){return new Promise(e=>setTimeout(e,this.minSequenceInterval))}}class PreferredConnectionController{glueController;portsBridge;sequelizer;registry=CallbackRegistryFactory$2();unsub;discoveryInterval;shouldForceTransfer;preferredUrl;preferredAuth;stopped=!1;constructor(e,t,r){this.glueController=e,this.portsBridge=t,this.sequelizer=r}get logger(){return logger.get("preferred.connection.controller")}shutdown(){this.stopped=!0,this.registry.clear()}async start(e){this.logger?.trace(`Starting the preferred connection with config: ${JSON.stringify(e)}`),this.stopped=!1,this.portsBridge.setPreferredActivated(),e.preferred&&(this.preferredUrl=e.preferred.url,this.preferredAuth=Object.assign({},{provider:"core"},e.preferred.auth),this.shouldForceTransfer="boolean"==typeof e.preferred.forceIncompleteSwitch&&e.preferred.forceIncompleteSwitch,this.discoveryInterval="number"==typeof e.preferred.discoveryIntervalMS?e.preferred.discoveryIntervalMS:defaultPreferredDiscoveryIntervalMS,this.logger?.trace("Starting the initial preferred connection check"),await this.connectPreferred(),this.logger?.trace("The preferred connection controller initiated."))}onReconnect(e){return this.registry.add("system-reconnect",e)}async connectPreferred(e,t,r){if(this.stopped&&!e)return;const n=await this.checkPreFlight(t);if(!n.ready&&e)return ioError.raiseError("The provided preferred connection is not ready.");if(!n.ready)return this.logger?.trace("The preflight is not ready, restarting the preferred tracking."),void wait(this.discoveryInterval).then(()=>this.connectPreferred(e,t,r));const i={type:"secondary",transportConfig:Object.assign({url:t||this.preferredUrl},{auth:r||this.preferredAuth})};if(this.logger?.trace("Switching the system glue."),this.stopped)return;if(!(await this.glueController.switchTransport(i,"system")).success)return this.logger?.trace("The switch attempt was not successful, revered to default."),void wait(this.discoveryInterval).then(()=>this.connectPreferred(e,t,r));this.portsBridge.setActivePreferredTransportConfig(i),this.logger?.trace("The switch to the preferred connection was successful, transferring all children.");try{await this.changeClientsConnection(i)}catch(n){return this.logger?.warn(`Some platform clients could not connect to the preferred connection, reverting all to the default connection. Reason: ${JSON.stringify(n)}`),void this.fullDefaultRevert().then(()=>wait(this.discoveryInterval).then(()=>this.connectPreferred(e,t,r))).catch(()=>wait(this.discoveryInterval).then(()=>this.connectPreferred(e,t,r)))}this.logger?.trace("The platform is now fully connected to the preferred connection, hooking up disconnection logic."),this.registry.execute("system-reconnect");const o=this.glueController.onDisconnected(()=>this.handleDisconnected(o,e));this.unsub=o}async revertToDefault(){this.unsub&&(this.unsub(),delete this.unsub),await this.fullDefaultRevert()}async fullDefaultRevert(){await this.glueController.switchTransport({type:"default"},"system"),this.portsBridge.setActivePreferredTransportConfig({type:"default"}),await this.changeClientsConnection({type:"default"})}handleDisconnected(e,t){this.logger?.trace("The platform has been disconnected from the preferred transport, reverting all to the default one."),e(),this.fullDefaultRevert().then(()=>{this.registry.execute("system-reconnect"),this.logger?.trace("The platform reversion to default completed, restarting the preferred tracking."),t||wait(this.discoveryInterval).then(()=>this.connectPreferred())}).catch(()=>wait(this.discoveryInterval).then(()=>this.connectPreferred()))}changeClientsConnection(e){return this.sequelizer.enqueue(async()=>{try{await Promise.all([this.glueController.switchTransport(e,"client"),this.portsBridge.switchAllClientsTransport(e)])}catch(e){if(this.logger?.trace(`Some clients could not connect to the preferred transport with error: ${JSON.stringify(e)}`),!this.shouldForceTransfer)return this.logger?.trace("The platform is not forcing a transfer in cases of errors, re-throwing."),ioError.raiseError(e);this.logger?.trace("The platform is forcing a transfer regardless of the errors.")}await this.glueController.switchTransport(e,"contextsTrack")})}checkPreferredConnection(e){return new Promise(t=>{const r=new WebSocket(e);r.onerror=()=>t({live:!1}),r.onopen=()=>{r.close(),t({live:!0})}})}async checkPreFlight(e){this.logger?.trace("Starting the preflight check");if(!(await this.checkPreferredConnection(e||this.preferredUrl)).live)return this.logger?.trace("The preferred connection is not live."),{ready:!1};this.logger?.trace(`Found a live preferred connection at: ${e||this.preferredUrl}, testing the availability of transport switching logic in all current clients`);const t=await this.portsBridge.checkClientsPreferredLogic();if(this.logger?.trace(`The logic check returned: ${JSON.stringify(t)}`),!t.success&&!this.shouldForceTransfer)return this.logger?.trace("The preflight check is marked as not ready"),{ready:!1};this.logger?.trace("Checking the possibility of all clients to connect to the preferred connection");const r=await this.portsBridge.checkClientsPreferredConnection(e||this.preferredUrl);return this.logger?.trace(`The connection check returned: ${JSON.stringify(r)}`),r.success||this.shouldForceTransfer?(this.logger?.trace("The preflight check is marked as ready"),{ready:!0}):(this.logger?.trace("The preflight check is marked as not ready"),{ready:!1})}}class TransactionsController{transactionLocks={};get logger(){return logger.get("transactions.controller")}completeTransaction(e,t){if("string"!=typeof e)return ioError.raiseError(`Cannot complete the transaction, because the provided id is not a string: ${JSON.stringify(e)}`);const r=this.transactionLocks[e];r?r.lift(t):this.logger?.warn(`Cannot mark a transaction as complete, because there is not lock with id ${e}`)}failTransaction(e,t){const r=this.transactionLocks[e];r?r.fail(t):this.logger?.warn(`Cannot mark a transaction as failed, because there is not lock with id ${e}`)}createTransaction(e,t){const r={},n=nanoid$3(10),i=new Promise((i,o)=>{let s=!0;r.lift=e=>{s=!1,delete this.transactionLocks[n],i(e)},r.fail=e=>{s=!1,delete this.transactionLocks[n],o(e)},setTimeout(()=>{s&&(s=!1,this.logger?.warn(`Transaction for operation: ${e} timed out.`),delete this.transactionLocks[n],o(`Transaction for operation: ${e} timed out.`))},t)});return r.lock=i,r.id=n,this.transactionLocks[n]=r,r}}class InterceptionController{interceptions=[];shutdown(){this.interceptions=[]}async registerInterceptor(e,t){runDecoderWithIOError(interceptorRegistrationRequestDecoder,e),runDecoderWithIOError(nonEmptyStringDecoder$2,t);const r=e.interceptions.reduce((e,t)=>(this.interceptions.some(e=>e.domain===t.domain&&e.operation===t.operation)&&e.push({domain:t.domain,operation:t.operation}),e),[]);if(r.length){const e=r.map(e=>`${e.domain} - ${e.operation}`).join(", ");return ioError.raiseError(`Interception registration is rejected, because the following collisions where found: ${e}`)}e.interceptions.forEach(r=>{this.interceptions.push({domain:r.domain,operation:r.operation,callInterceptor:e.callInterceptor,registrantName:t})})}getOperationInterceptor(e){const t=this.interceptions.find(t=>t.domain===e.domain&&t.operation===e.operation);if(t)return{name:t.registrantName,intercept:t.callInterceptor}}}class PluginsController{interceptionController;glueController;handlePluginMessage;platformApi;allPlugins;registeredPlugins=[];constructor(e,t){this.interceptionController=e,this.glueController=t}get logger(){return logger.get("plugins.controller")}async shutdown(){this.logger?.debug(`starting plugins shutdown for all plugins: [${this.allPlugins.map(e=>e.name).join(", ")}]`),this.allPlugins.forEach(e=>{if(e.stop)try{e.stop()}catch(t){this.logger?.warn(`Plugin: ${e.name} threw while onPlatformShutdown -> ${extractErrorMsg$1(t)}`)}}),this.allPlugins=[],this.registeredPlugins=[],this.logger?.debug("plugins shutdown completed")}async start(e){if(this.logger?.debug(`initializing plugins with ${JSON.stringify((e.plugins??[]).map(e=>e.name))} plugins`),!e.plugins)return;if(this.allPlugins=e.plugins,this.handlePluginMessage=e.handlePluginMessage,this.platformApi=e.api,!e.plugins||!e.plugins.length)return;const t=[],r=[];for(const n of e.plugins){const e=this.startPlugin(n);n.critical&&(t.push(e),r.push(n.name))}this.logger?.debug(`waiting for ${t.length} critical plugins to start: [${r.join(", ")}]`),await Promise.all(t),this.logger?.debug(`all critical plugins started successfully [${r.join(", ")}]`)}async startPlugin(e){this.logger?.debug(`starting plugin with definition: ${JSON.stringify(e)}`);try{const t=this.buildPlatformControls(e.name,this.platformApi);this.validatePlugin(e.name),await e.start(this.glueController.clientGlue,e.config,t),this.registerPlugin(e.name,e.version??"N/A"),this.logger?.debug(`plugin '${e.name}' started successfully`)}catch(t){this.logger?.error(`plugin '${e.name}' failed to start with error: ${extractErrorMsg$1(t)}`);const r="string"==typeof t?t:JSON.stringify(t.message),n=`Plugin: ${e.name} threw while initiating: ${r}`;if(e.critical)return ioError.raiseError(n);this.logger?.warn(n)}}buildPlatformControls(e,t){return{control:t=>this.handlePluginMessage(t,e),logger:logger.get(e),platformApi:t,interception:{register:t=>this.interceptionController.registerInterceptor(t,e)},system:{sendControl:t=>this.handlePluginMessage(t,e)}}}validatePlugin(e){if(this.registeredPlugins.some(t=>t.name===e))throw new Error(`Plugin: ${e} is already registered`)}registerPlugin(e,t){this.registeredPlugins.push({name:e,version:t})}}class DomainsController{systemController;windowsController;applicationsController;layoutsController;workspacesController;intentsController;channelsController;notificationsController;extensionController;searchController;themesController;managerController;prefsController;otelController;uiController;defaultDomainNames=["system","windows","appManager","layouts","workspaces","intents","channels","notifications","extension","search","themes","prefs","otel","ui"];domains;constructor(e,t,r,n,i,o,s,a,c,l,u,d,h,p,g){this.systemController=e,this.windowsController=t,this.applicationsController=r,this.layoutsController=n,this.workspacesController=i,this.intentsController=o,this.channelsController=s,this.notificationsController=a,this.extensionController=c,this.searchController=l,this.themesController=u,this.managerController=d,this.prefsController=h,this.otelController=p,this.uiController=g,this.setDomains()}setDomains(){this.domains={system:{name:"system",libController:this.systemController},windows:{name:"windows",libController:this.windowsController},appManager:{name:"appManager",libController:this.applicationsController},layouts:{name:"layouts",libController:this.layoutsController},workspaces:{name:"workspaces",libController:this.workspacesController},intents:{name:"intents",libController:this.intentsController},channels:{name:"channels",libController:this.channelsController},notifications:{name:"notifications",libController:this.notificationsController},extension:{name:"extension",libController:this.extensionController},search:{name:"search",libController:this.searchController},themes:{name:"themes",libController:this.themesController},manager:{name:"manager",libController:this.managerController},prefs:{name:"prefs",libController:this.prefsController},otel:{name:"otel",libController:this.otelController},ui:{name:"ui",libController:this.uiController}}}get logger(){return logger.get("domains.controller")}shutdown(){Object.values(this.domains).forEach(e=>e.libController.handlePlatformShutdown?e.libController.handlePlatformShutdown():null),this.domains={system:{name:"system",libController:this.systemController},windows:{name:"windows",libController:this.windowsController},appManager:{name:"appManager",libController:this.applicationsController},layouts:{name:"layouts",libController:this.layoutsController},workspaces:{name:"workspaces",libController:this.workspacesController},intents:{name:"intents",libController:this.intentsController},channels:{name:"channels",libController:this.channelsController},notifications:{name:"notifications",libController:this.notificationsController},extension:{name:"extension",libController:this.extensionController},search:{name:"search",libController:this.searchController},themes:{name:"themes",libController:this.themesController},prefs:{name:"prefs",libController:this.prefsController},otel:{name:"otel",libController:this.otelController},ui:{name:"ui",libController:this.uiController}}}setProfileData(e){this.systemController.setProfileData(e)}async setNotificationsData(){await this.notificationsController.setupInitialConfig()}async setThemesData(){await this.themesController.setupInitialThemes()}validateDomain(e){const t=this.domains[e];if(!t)return ioError.raiseError(`Accessing a missing domain: ${e}.`);const r=t.domainNameDecoder?t.domainNameDecoder:libDomainDecoder;runDecoderWithIOError(r,e)}async startAllDomains(e){this.logger?.trace("Starting all domains lib controllers"),await Promise.all(Object.values(this.domains).map(t=>t.libController.start(e))),this.logger?.trace("All domains have been initialized")}async configurePostStartAllDomains(){this.logger?.trace("Starting all domains lib controllers"),await Promise.all(Object.values(this.domains).filter(e=>!!e.libController.configurePostStart).map(e=>e.libController.configurePostStart&&e.libController.configurePostStart())),this.logger?.trace("All domains have been initialized")}notifyDomainsClientUnloaded(e){this.logger?.trace(`detected unloading of client: ${e.windowId}, notifying all controllers`),Object.values(this.domains).forEach(t=>{try{t.libController.handleClientUnloaded?.(e.windowId,e.win)}catch(r){const n="string"==typeof r?r:JSON.stringify(r.message),i=t.name;this.logger?.error(`${i} controller threw when handling unloaded client ${e.windowId} with error message: ${n}`)}})}executeControlMessage(e){const t=this.domains[e.domain];return t?t.libController.handleControl(e):ioError.raiseError(`Cannot process message for domain: ${e.domain} and operation ${e.operation}, because no domain can service it.`)}registerDynamicDomain(e){return Object.values(this.domains).map(e=>e.name).some(t=>t===e.name)?ioError.raiseError(`Cannot register a domain with name: ${e.name}, because it is already registered`):e.libController&&e.libController.start&&e.libController.handleControl&&e.libController.handleClientUnloaded?e.domainNameDecoder?void(this.domains[e.name]=e):ioError.raiseError(`Cannot register a domain with name: ${e.name}, because it does not have a domain decoder`):ioError.raiseError(`Cannot register a domain with name: ${e.name}, because it does not have a valid libController`)}unregisterDynamicDomain(e){if(this.defaultDomainNames.some(t=>t===e))return ioError.raiseError(`Cannot unregister a domain: ${e}, because it is a reserved default domain`);delete this.domains[e]}async domainsReady(){this.logger?.trace("Verifying all domains lib controllers ready"),await Promise.all(Object.values(this.domains).map(e=>e.libController.ready())),this.logger?.trace("All domains have signaled ready")}}class LegacyResolverController{glueController;workspacesController;windowsController;prefsController;intentsResolverResponsePromises={};constructor(e,t,r,n){this.glueController=e,this.workspacesController=t,this.windowsController=r,this.prefsController=n}get logger(){return logger.get("intents.resolver.controller")}async startResolverApp({request:e,resolverConfig:t,commandId:r,callerId:n,resolverInstance:i,method:o}){this.logger?.trace(`[${r}] Intents Resolver UI with app name ${t.appName} will be used for request: ${JSON.stringify(e)}`);const s=await this.registerResponseMethod();this.logger?.trace(`[${r}] Registered interop method ${s}`);const a=this.buildStartContext(o,e,s,n),c=await this.buildStartOptions(n,r);this.logger?.trace(`[${r}] Starting Intents Resolver UI with context: ${JSON.stringify(a)} and options: ${c}`);const l=this.glueController.clientGlue.appManager.application(t.appName).start(a,c).catch(e=>ioError.raiseError(`${ERRORS.RESOLVER_UNAVAILABLE}. Reason: ${e instanceof Error||"string"==typeof e?e:JSON.stringify(e)}`)),u=await l;i.instanceId=u.id,this.logger?.trace(`[${r}] Intents Resolver instance with id ${u.id} opened`),this.subscribeOnInstanceStopped(u,o);const d="raise"===o?`for intent request ${JSON.stringify(e)}`:`for '${o}' method with filter ${JSON.stringify(e)}`,h=`${ERRORS.RESOLVER_TIMEOUT} - waited ${t.waitResponseTimeout}ms for the user the choose a handler ${d}`;this.createResponsePromise({intent:"raise"===o?e.intent:void 0,instanceId:u.id,responseMethodName:s,timeout:t.waitResponseTimeout,errorMsg:h});try{return await this.handleInstanceResponse({request:e,instanceId:u.id,method:o,commandId:r,caller:a.initialCaller})}catch(e){return this.stopResolverInstance(i.instanceId),ioError.raiseError(e)}}stopResolverInstance(e){const t=this.glueController.clientGlue.appManager.instances().find(t=>t.id===e);t&&t.stop().catch(e=>this.logger?.warn(e))}async handleInstanceResponse({method:e,caller:t,commandId:r,instanceId:n,request:i}){const o=await this.intentsResolverResponsePromises[n].promise,s="raise"===e?`for intent ${o.intent} `:"";if(this.logger?.trace(`[${r}] Intent handler chosen ${s}: ${JSON.stringify(o.handler)}. Stopping resolver instance with id ${n}`),this.stopResolverInstance(n),this.logger?.trace(`[${r}] Instance with id ${n} successfully stopped`),!o?.userSettings?.preserveChoice)return o.handler;try{await this.saveUserChoice({intent:o.intent,handler:o.handler,filter:"filterHandlers"===e?{applicationNames:i.applicationNames,contextTypes:i.contextTypes,resultType:i.resultType}:void 0,caller:t},r)}catch(e){this.logger?.warn(`[${r}] - Prefs API threw the following error: ${e}`)}return o.handler}async registerResponseMethod(){const e=INTENTS_RESOLVER_INTEROP_PREFIX+nanoid$3(10);return await this.glueController.clientGlue.interop.register(e,(e,t)=>this.responseHandler(e,t)),e}createResponsePromise({instanceId:e,intent:t,responseMethodName:r,timeout:n,errorMsg:i}){let o=()=>{},s=()=>{};const a=PromisePlus((e,t)=>{o=e,s=t},n,i);this.intentsResolverResponsePromises[e]={intent:t,resolve:o,reject:s,promise:a,methodName:r}}buildStartContext(e,t,r,n){const i={callerId:this.glueController.clientGlue.interop.instance.instance,methodName:r,resolverApi:"1.0"},o=this.glueController.getLocalServers().find(e=>e.instance===n);if(!o)throw new Error(`Cannot find window with id: ${n} - the client which sent the "raise" command is no longer opened`);const s=o.application??o.applicationName,a={applicationName:s,applicationTitle:s?this.glueController.clientGlue.appManager.application(s)?.title:"",id:n};return"raise"===e?{...i,initialCaller:a,intent:t}:{...i,initialCaller:a,handlerFilter:t}}async buildStartOptions(e,t){const r=await this.getTargetBounds(e,t);return r?{top:(r.height-INTENTS_RESOLVER_HEIGHT)/2+r.top,left:(r.width-INTENTS_RESOLVER_WIDTH)/2+r.left,width:INTENTS_RESOLVER_WIDTH,height:INTENTS_RESOLVER_HEIGHT}:ioError.raiseError(`[${t}] Cannot find window with id: ${e} - the client which sent the "raise" command is no longer opened`)}async getTargetBounds(e,t){const r=await this.tryGetWindowBasedBounds(e,t)??await this.tryGetWorkspaceBasedBounds(e,t);if(r)return this.logger?.trace(`[${t}] Opening Intents Resolver UI with bounds: ${JSON.stringify(r)}`),r;const n={top:window.screen.availTop??0,left:window.screen.availLeft??0,width:window.screen.width,height:window.screen.height};return this.logger?.trace(`[${t}] Opening Intents Resolver UI relative to my screen bounds: ${JSON.stringify(n)}`),n}async tryGetWindowBasedBounds(e,t){const r=this.glueController.clientGlue.windows.findById(e),n=this.getServerInstanceByWindowId(e);if(!r&&!n)return ioError.raiseError(`Client with id "${e}" does not exist`);if(!r&&n)return this.getWindowBoundsByServerInstance(n,e,t);if(!r)return ioError.raiseError(`Client with id "${e}" does not exist`);try{const n=await r.getBounds();return this.logger?.trace(`[${t}] Opening the resolver UI with bounds: ${JSON.stringify(n)}, relative to a window with id: ${e}`),n}catch(r){return void this.logger?.trace(`[${t}] Failure to get bounds of a window with id ${e}. Error: ${JSON.stringify(r)}`)}}getServerInstanceByWindowId(e){return this.glueController.getLocalServers().find(t=>t.instance===e)}async getWindowBoundsByServerInstance(e,t,r){try{const{bounds:r}=await this.glueController.callWindow("windows",this.windowsController.getBoundsOperation,{windowId:t},{instance:e.instance});return r}catch(t){this.logger?.trace(`[${r}] Failure to get bounds of a window with instance ${e.instance}. Error: ${JSON.stringify(t)}`)}}async tryGetWorkspaceBasedBounds(e,t){try{const{bounds:r}=await this.workspacesController.getWorkspaceWindowFrameBounds({itemId:e},t);return this.logger?.trace(`[${t}] Opening the resolver UI relative to my workspace frame window bounds: ${JSON.stringify(r)}`),r}catch(e){this.logger?.trace(`[${t}] Failure to get my workspace frame window bounds. Error: ${JSON.stringify(e)}`)}}responseHandler(e,t){const r=resolverResponseDecoder.run(e),n=t.instance;return n?r.ok?(this.logger?.trace(`Intent Resolver instance with id ${n} send a valid response: ${JSON.stringify(r.result)}`),this.intentsResolverResponsePromises[n].resolve(e)):(this.logger?.trace(`Intent Resolver instance with id ${n} sent an invalid response. Error: ${JSON.stringify(r.error)}`),this.intentsResolverResponsePromises[n].reject(r.error.message),void this.stopResolverInstance(n)):ioError.raiseError("Cannot find instance id for the response of the intent resolver")}subscribeOnInstanceStopped(e,t){const{application:r}=e,n=r.onInstanceStopped(r=>{if(r.id!==e.id)return;const i=this.intentsResolverResponsePromises[r.id];if(!i)return n();const o="raise"===t?`raised intent ${i.intent}`:`'${t}' method`,s=`${ERRORS.USER_CANCELLED} for ${o}`;i.reject(s),this.cleanUpIntentResolverPromise(r.id),n()})}async cleanUpIntentResolverPromise(e){const t=this.intentsResolverResponsePromises[e];if(!t)return;this.glueController.clientGlue.interop.unregister(t.methodName).catch(e=>this.logger?.warn(e)),delete this.intentsResolverResponsePromises[e]}async saveUserChoice({intent:e,handler:t,filter:r,caller:n},i){const o="Platform"===n.applicationName?this.prefsController.platformAppName:n.applicationName;this.logger?.info(`[${i}] - Saving user's choice of handler for '${o}' app`);const s=await this.prefsController.get({app:o},i),a=s.prefs.data?.intents??{},c={...s.prefs.data,intents:{...a,[e]:{handler:t,filter:r}}};await this.prefsController.update({app:o,data:c},i)}}class LicenseController{verifyLicense(e){if(!e||"string"!=typeof e)return{valid:!1};const t=KEYUTIL_1.getKey(publicLicKey);return{valid:KJUR_1.jws.JWS.verifyJWT(e,t,{alg:["RS256"]})}}getLicensePayload(e){if(!e)return ioError.raiseError("No license key was provided");const t=KJUR_1.jws.JWS.readSafeJSONString(b64utoutf8_1(e.split(".")[1]));return t&&"string"==typeof t.type&&"number"==typeof t.expiration?(t.type=t.type.toLowerCase(),t):ioError.raiseError("The license key payload is invalid")}isPlatformOriginAllowed(e,t=[]){if(!t.length||t.includes("*"))return!0;if("localhost"===e.hostname)return!0;return t.some(t=>pm(t)(e.origin))}checkExpired(e){return!(!e||"number"!=typeof e)&&e<=Date.now()}}class Builder{glueController;sessionStore;windowsController;workspacesController;constructor(e,t,r,n){this.glueController=e,this.sessionStore=t,this.windowsController=r,this.workspacesController=n}get logger(){return logger.get("layouts.builder")}async saveGlobalLayout(e,t){const r=await this.getRawWindowsLayoutData({layoutType:"Global",layoutName:e.layout.name,context:e.layout.context,instances:e.layout.instances,ignoreInstances:e.layout.ignoreInstances,ignoreContexts:e.layout.ignoreContexts,saveWindowContexts:e.layout.saveWindowContexts},t);this.logger?.trace(`[${t}] received valid data for the eligible windows`);const n=await this.glueController.getLayout(e.layout.name),i=n?await this.updateLayout(n,e.layout,r.windows,t):await this.buildNewLayout(e.layout,r.windows,t);return this.logger?.trace(`[${t}] the layout object was constructed, importing.`),await this.glueController.importLayout(i),this.logger?.trace(`[${t}] the import for layout: ${i.name} was completed, responding.`),i}async getGlueClientWindowContextOnSaveRequest(e,t){if(e.ignoreContexts)return{};const r=`Cannot fetch the layout save data from window with id: ${t}`,n=await PromiseWrap(async()=>{try{return await this.glueController.callWindow("layouts",{name:"clientSaveRequest",execute:async()=>{}},e,{windowId:t})}catch{return{}}},15e3,r);return n.windowContext?n.windowContext:e.saveWindowContexts?this.getWebWindowContext(t):{}}async getNonGlueWindowContext(e,t){return e.ignoreContexts?{}:e.saveWindowContexts?this.getWebWindowContext(t):{}}async getWebWindowContext(e){const t=this.glueController.getWindowById(e);return await(t?.getContext())??{}}async updateLayout(e,t,r,n){this.logger?.trace(`[${n}] updating an existing layout with name ${t.name}`),e.context=t.context??{},e.metadata=t.metadata??{},e.token=e.token??generateLayoutToken();const i=r.filter(e=>!!e.layoutComponentId).map(e=>e.layoutComponentId),o=this.getLayoutIdOccurrenceMap(i),s=r.map(t=>this.generateWindowComponent(e,t,o,n));this.logger?.trace(`[${n}] the window components are completed, we have ${s.length} windows for the layout`);const a=this.getBaseSaveRequestFromSaveConfig(t),c=e.components.filter(e=>"workspaceFrame"===e.type),l=await this.compileWorkspacesFrameComponents(c,a,n);return this.logger?.trace(`[${n}] the workspaces frame components are completed, we have ${l.length} frames for the layout`),e.components=[],e.components.push(...s),e.components.push(...l),e}async buildNewLayout(e,t,r){this.logger?.trace(`[${r}] build a brand new layout with name ${e.name}`);const n={name:e.name,type:"Global",context:e.context??{},metadata:e.metadata??{},components:[],token:generateLayoutToken(),version:2},i=t.map(e=>this.buildNewWindowComponent(e,r));this.logger?.trace(`[${r}] the window components are completed, we have ${i.length} windows for the layout`);const o=this.getBaseSaveRequestFromSaveConfig(e),s=await this.compileWorkspacesFrameComponents([],o,r);return this.logger?.trace(`[${r}] the workspaces frame components are completed, we have ${s.length} frames for the layout`),n.components.push(...i),n.components.push(...s),n}getBaseSaveRequestFromSaveConfig(e){return{layoutName:e.name,layoutType:"Global",context:e.context,ignoreContexts:e.ignoreContexts,saveWindowContexts:e.saveWindowContexts}}async getRawWindowsLayoutData(e,t){this.logger?.trace(`[${t}] handling send save requests for layout: ${e.layoutName} to instances: ${e.instances?.join(", ")}`);const r={windows:[...await Promise.all(this.getEligibleGlueWindows(e.instances,e.ignoreInstances).map(r=>this.buildRawGlueWindowData(r,e,t))),...await Promise.all(this.getEligibleNonGlueWindows(e.instances,e.ignoreInstances).map(t=>this.buildRawNonGlueWindowData(t,e)))]};return this.logger?.trace(`[${t}] request completed, responding to the caller`),r}async buildRawGlueWindowData(e,t,r){if(!e.initialUrl)return ioError.raiseError(`Missing URL for client: ${e.name}`);const n=await this.getGlueClientWindowContextOnSaveRequest(t,e.windowId),i=this.sessionStore.getAllInstancesData().find(t=>t.id===e.windowId),o=await this.windowsController.getWindowBounds(e.windowId,r),s=await this.glueController.callWindow("channels",{name:"getMyChannel",execute:async()=>{}},{},{windowId:e.windowId});return{bounds:o,windowContext:n,url:e.initialUrl,name:e.name,application:i?i.applicationName:defaultNoAppWindowComponentAppName,initialContext:t.ignoreContexts?{}:e.initialContext,windowId:e.windowId,layoutComponentId:e.layoutComponentId,channelId:s.channel}}async buildRawNonGlueWindowData(e,t){if(!e.initialUrl)return ioError.raiseError(`Missing URL for client: ${e.name}`);const r=this.sessionStore.getAllInstancesData().find(t=>t.id===e.windowId),n=await this.getNonGlueWindowContext(t,e.windowId);return{bounds:e.initialBounds??defaultPlatformConfig.windows.defaultWindowOpenBounds,windowContext:n,url:e.initialUrl,name:e.name,application:r?r.applicationName:defaultNoAppWindowComponentAppName,initialContext:t.ignoreContexts?{}:e.initialContext,windowId:e.windowId,layoutComponentId:e.layoutComponentId}}getEligibleNonGlueWindows(e,t){const r=this.getAllEligibleWindows(e,t),n=this.sessionStore.getAllNonGlue(),i=this.sessionStore.pickWorkspaceClients(()=>!0);return r.filter(e=>n.some(t=>t.windowId===e.windowId)&&i.every(t=>t.windowId!==e.windowId))}getEligibleGlueWindows(e,t){const r=this.getAllEligibleWindows(e,t),n=this.sessionStore.getAllNonGlue(),i=this.sessionStore.pickWorkspaceClients(()=>!0);return r.filter(e=>i.every(t=>t.windowId!==e.windowId)&&n.every(t=>t.windowId!==e.windowId))}getAllEligibleWindows(e,t){let r=this.sessionStore.getAllWindowsData().filter(e=>"Platform"!==e.name);if(e&&e.length){const t=this.glueController.getLocalServers().filter(t=>e.some(e=>t.instance===e));r=r.filter(e=>t.some(t=>t.windowId===e.windowId))}if(t&&t.length){const e=this.glueController.getLocalServers().filter(e=>t.some(t=>e.instance===t));r=r.filter(t=>e.every(e=>e.windowId!==t.windowId))}return r}updateExistingWindowComponent(e,t,r){return this.logger?.trace(`[${r}] performing a soft update on am existing component ${e.application} with id ${e.state.instanceId}`),e.state.context=t.windowContext?t.windowContext:e.state.context,e.state.bounds=t.bounds,e.state.createArgs.context=t.initialContext?t.initialContext:e.state.createArgs?.context,e.state.instanceId=e.state.instanceId?e.state.instanceId:t.windowId,e.state.channelId=t.channelId,e}buildNewWindowComponent(e,t){return this.logger?.trace(`[${t}] building a brand new component ${e.application} with id ${e.windowId}`),{type:"window",componentType:"application",application:e.application,state:{context:e.windowContext??{},bounds:e.bounds,createArgs:{name:e.name,url:e.url,context:e.initialContext??{}},windowState:"Normal",restoreState:"Normal",restoreSettings:{groupId:"glue_42_core",groupZOrder:0},instanceId:e.windowId,isSticky:!0,isCollapsed:!1,channelId:e.channelId}}}async compileWorkspacesFrameComponents(e,t,r){this.logger?.trace(`[${r}] requesting information about all running workspaces frames`);const n=await this.getAllFramesSnapshotsWithBounds(t,r);this.logger?.trace(`[${r}] got information on ${n.length} frames, composing the frame components`);const i=n.filter(e=>!!e.config?.layoutComponentId).map(e=>e.config.layoutComponentId),o=this.getLayoutIdOccurrenceMap(i);return n.map(t=>this.generateFrameComponent(t,e,o,r))}getLayoutIdOccurrenceMap(e){const t={};return e.forEach(e=>{t[e]?t[e]=1+t[e]:t[e]=1}),t}softUpdateFrameComponent(e,t,r,n){return this.logger?.trace(`[${n}] performing a soft update on am existing frame component ${e.state.instanceId}`),e.state.bounds=t.bounds,e.state.selectedWorkspace=-1===r?0:r,e.state.workspaces=t.snapshot.workspaces,e.state.context=Object.assign({},e.state.context,{isPlatform:t.config.isPlatform}),e}createNewFrameComponent(e,t,r){return this.logger?.trace(`[${r}] building a new frame component ${e.snapshot.id}`),{type:"workspaceFrame",application:"workspaces-demo",componentType:"application",state:{context:{isPlatform:e.config.isPlatform},bounds:e.bounds,instanceId:e.snapshot.id,selectedWorkspace:-1===t?0:t,workspaces:e.snapshot.workspaces,restoreState:"Normal",windowState:"Normal"}}}generateWindowComponent(e,t,r,n){const i=e.components.find(e=>"window"===e.type&&e.state.instanceId===t.layoutComponentId),o=t.layoutComponentId?r[t.layoutComponentId]:0;return i&&o<2?this.updateExistingWindowComponent(i,t,n):this.buildNewWindowComponent(t,n)}generateFrameComponent(e,t,r,n){const i=e.snapshot.workspaces.findIndex(e=>e?.config?.isSelected),o=t.find(t=>t.state.instanceId===e.config.layoutComponentId),s=e.config.layoutComponentId?r[e.config.layoutComponentId]:0;return o&&s<2?this.softUpdateFrameComponent(o,e,i,n):this.createNewFrameComponent(e,i,n)}async getAllFramesSnapshotsWithBounds(e,t){const r=(await this.workspacesController.getAllFramesSummaries(void 0,t)).summaries||[];return await Promise.all(r.map(async r=>{const n=await this.workspacesController.handleGetWorkspacesLayouts({frameId:r.id,...e},t),i=await this.workspacesController.getFrameSessionData({frameId:r.id},t);return{bounds:(await this.workspacesController.getFrameBounds({itemId:r.id},t)).bounds,snapshot:{id:r.id,workspaces:n.workspaces,config:{}},config:{isPlatform:i?.isPlatform,layoutComponentId:i?.layoutComponentId}}}))}}class Restorer{glueController;validator;resetter;workspacesController;sessionStore;constructor(e,t,r,n,i){this.glueController=e,this.validator=t,this.resetter=r,this.workspacesController=n,this.sessionStore=i}get logger(){return logger.get("layouts.restorer")}async restoreGlobalLayout(e,t,r,n){const i=await this.glueController.getLayout(e.layout.name);if(!i)return ioError.raiseError(`Cannot restore layout: ${e.layout.name}, because it was not found in this platform`);if("Global"!==i.type)return ioError.raiseError(`Cannot restore layout: ${e.layout.name}, because it is not a Global Layout`);if(!r||!n)return ioError.raiseError(`Cannot restore layout: ${e.layout.name}, because the callerId or callerType are missing`);await this.validator.doInitialValidation(i,t),this.logger?.trace(`[${t}] the initial validation of the compliancy of the layout was completed`),await this.closeInstances(n,r,t,e.layout.closeMe,e.layout.closeRunningInstances),this.logger?.trace(`[${t}] closed all necessary running instances`),await this.restore(i,e,t);const o=this.sessionStore.getLayoutsSystemData();o.currentLayoutName=i.name,this.sessionStore.setLayoutsSystemData(o),this.logger?.trace(`[${t}] the layout ${i.name} was restored`)}async closeInstances(e,t,r,n,i){(void 0===i||i)&&await this.resetter.closeAllExceptCaller(t,r);(n||void 0===n&&void 0===i||void 0===n&&i)&&await this.resetter.closeCaller(e,t,r)}async restore(e,t,r){this.logger?.trace(`[${r}] starting the restore process of ${e.name}`);const n=await this.canPlatformFrameAcceptComponent(r)?this.pickComponentForPlatformFrame(e.components.filter(e=>"workspaceFrame"===e.type)):null,i=Promise.all(e.components.map(i=>{if("window"===i.type)return this.restoreWindowComponent(i,r,e.context,t.layout.context);if("workspaceFrame"===i.type){const o=n===i;return this.restoreWorkspaceFrameComponent(i,r,e.context,t.layout.context,o)}}));await i}async restoreWindowComponent(e,t,r,n){this.logger?.trace(`[${t}] restoring window component ${e.application} with id ${e.state.instanceId} and bounds: ${JSON.stringify(e.state.bounds)}`);const i=Object.assign({},r,e.state.context,e.state.createArgs.context,n),o=e.state.channelId,s=e.state.bounds,a=await this.checkTargetBoundsPossible(s);a.isPossible||this.logger?.warn(`Restoring ${e.application} not possible with the saved bounds, falling back to default bounds`);const c=a.isPossible?s:void 0;this.logger?.trace(`[${t}] calling the respective glue open/start method`);const l=e.application===defaultNoAppWindowComponentAppName?this.glueController.openWindow({name:e.state.createArgs.name,url:e.state.createArgs.url,layoutComponentId:e.state.instanceId,context:i,bounds:c}):this.glueController.startApp({name:e.application,layoutComponentId:e.state.instanceId,context:i,bounds:c});this.logger?.trace(`[${t}] the component was started`);const u=await l;o&&await this.glueController.callWindow("channels",{name:"joinChannel",execute:async()=>{}},{windowId:u.id,channel:o},{instance:u.id}).catch(console.error)}async restoreWorkspaceFrameComponent(e,t,r,n,i){this.logger?.trace(`[${t}] restoring workspace frame component $with id ${e.state.instanceId} and bounds: ${JSON.stringify(e.state.bounds)}`);const o=i?(await this.getPlatformFrame(t))?.id:void 0,s=await this.createFrameWithWorkspaceComponents(e,o);this.logger?.trace(`[${t}] the frame was restored, selecting the correct workspace`);const a=await s.workspaces();await(a[e.state.selectedWorkspace]?.focus()),this.logger?.trace(`[${t}] the correct workspace was selected, restoring the workspaces context`);const c=Object.assign({},r,n);await Promise.all(a.map(e=>e.updateContext(c))),this.logger?.trace(`[${t}] the frame component ${e.state.instanceId} is restored`)}async canPlatformFrameAcceptComponent(e){const t=await this.getPlatformFrame(e);if(!t)return!1;const r=await t.workspaces();return 1===r.length&&0===r[0].getAllWindows().length}pickComponentForPlatformFrame(e){if(0===e.length)return;return e.find(e=>e.state.context?.isPlatform)||e[0]}async checkTargetBoundsPossible(e){if(window.gtf)return{isPossible:!0};return(await window.getScreenDetails()).screens.find(t=>{const r=e.left>=t.left&&e.left<=t.left+t.width,n=e.top>=t.top&&e.top<=t.top+t.height;return r&&n})?{isPossible:!0}:{isPossible:!1}}async getPlatformFrame(e){if(!this.glueController.isWorkspacesEnabled)return;if(!await this.workspacesController.handleCheckStarted(void 0,e))return;const t=(await this.workspacesController.handleGetPlatformFrameId({},e)).id;return t?this.glueController.getOrCreateWorkspaceFrame({frameId:t}):void 0}async createFrameWithWorkspaceComponents(e,t){const r=await this.glueController.getOrCreateWorkspaceFrame({frameId:t,bounds:e.state.bounds,layoutComponentId:e.state.instanceId});return await this.glueController.invokeMethod(GlueWorkspaceFrameClientControlName,{operation:"initFrameFromSnapshot",operationArguments:{workspaces:e.state.workspaces,keepWorkspaces:[]}},{windowId:r.id}),r}}class LayoutValidator{glueController;workspacesController;constructor(e,t){this.glueController=e,this.workspacesController=t}async doInitialValidation(e,t){this.validateRequiredApplicationsExistence(e),await this.validateWorkspaceConfigurationInPlatform(e,t),this.validateNoAppNameAndUrl(e)}async doFinalValidation(e){this.validateWindowNamesCollision(e),this.validateInstanceIdCollision(e),await this.validateWorkspaceFramesIdCollisions(e)}validateWindowNamesCollision(e){const t=e.components.filter(e=>"window"===e.type&&e.application===defaultNoAppWindowComponentAppName&&!!e.state.createArgs.name).map(e=>e.state.createArgs.name),r=this.glueController.getAllWindowNames(),n=t.filter(e=>r.some(t=>e===t));if(n.length)return ioError.raiseError(`Cannot restore layout: ${e.name}, because there are window names collisions: ${n.join(", ")}`)}validateInstanceIdCollision(e){const t=e.components.filter(e=>"window"===e.type&&!!e.state.instanceId).map(e=>e.state.instanceId),r=this.glueController.getAllOpenedIds(),n=t.filter(e=>r.some(t=>e===t));if(n.length)return ioError.raiseError(`Cannot restore layout: ${e.name}, because there are instances ids collisions: ${n.join(", ")}`)}async validateWorkspaceFramesIdCollisions(e){if(e.components.every(e=>"workspaceFrame"!==e.type))return;const t=await this.glueController.getAllOpenedFrameIds(),r=e.components.filter(e=>"workspaceFrame"===e.type).map(e=>e.state.instanceId).filter(e=>t.some(t=>e===t));return r.length?ioError.raiseError(`Cannot restore layout: ${e.name}, because there are frame ids collisions: ${r.join(", ")}`):void 0}validateNoAppNameAndUrl(e){const t=e.components.filter(e=>"window"===e.type&&e.application===defaultNoAppWindowComponentAppName).filter(e=>!("window"!==e.type||e.state.createArgs.name&&e.state.createArgs.url));if(!t.length)return;const r=t.map(e=>JSON.stringify(e.state.createArgs)).join(", ");return ioError.raiseError(`Cannot restore layout: ${e.name}, because it has window components, which are not defined applications and are missing name or url, provided insufficient createArgs are: ${r}`)}validateRequiredApplicationsExistence(e){const t=this.glueController.getAllApplicationNames(),r=e.components.filter(e=>"window"===e.type&&e.application!==defaultNoAppWindowComponentAppName).map(e=>e.application);if(r.push(...this.getRequiredAppNamesFromWorkspaceFrameComponents(e)),!r.length)return;const n=r.filter(e=>t.every(t=>t!==e));return n.length?ioError.raiseError(`Cannot restore layout: ${e.name}, because some required applications are not registered with this platform: ${n.join(", ")}`):void 0}async validateWorkspaceConfigurationInPlatform(e,t){if(e.components.every(e=>"Workspace"!==e.type||"workspaceFrame"!==e.type))return;const r=(await this.workspacesController.handleCheckStarted({},t))?.started;return r?void 0:ioError.raiseError(`Cannot restore layout: ${e.name}, because this platform does not have a valid Workspaces configuration`)}getRequiredAppNamesFromWorkspaceFrameComponents(e){const t=[];for(const r of e.components)if("workspaceFrame"===r.type){const e=r.state.workspaces.reduce((e,t)=>(e.push(...this.getAllAppNamesFromChildren(t.children)),e),[]);t.push(...e)}return t}getAllAppNamesFromChildren(e){const t=e.filter(e=>"window"===e.type&&!!e.config.appName&&e.config.appName!==defaultNoAppWindowComponentAppName).map(e=>e.config.appName);for(const r of e)"window"!==r.type&&t.push(...this.getAllAppNamesFromChildren(r.children));return t}}class Resetter{glueController;workspacesController;constructor(e,t){this.glueController=e,this.workspacesController=t}get logger(){return logger.get("layouts.resetter")}async closeAllExceptCaller(e,t){const r=this.glueController.getAllOtherNonPlatformWindows(e);await Promise.all(r.map(async e=>{if(this.glueController.isWorkspacesEnabled){if(await this.glueController.getWorkspaceWindowById(e.id))return}return e.close()})),this.glueController.isWorkspacesEnabled&&await this.closeNecessaryWorkspacesFrames(e,t)}async closeCaller(e,t,r){if("plugin"===e)return;if(await this.glueController.getWorkspaceWindowById(t))return void await this.cleanupWorkspaceCaller(t,r);const n=this.glueController.getWindowById(t);n&&"Platform"!==n.name?await n.close():this.logger?.warn("The close caller was missing, is an iframe or is a platform")}async closeNecessaryWorkspacesFrames(e,t){const r=(await this.workspacesController.handleGetPlatformFrameId({},t)).id;let n=await this.glueController.getAllWorkspacesFrames();r&&(n=n.filter(e=>e.id!==r),await this.cleanUpFrameExceptCaller(r,e));const i=await this.glueController.getWorkspaceWindowById(e);i&&(n=n.filter(e=>e.id!==i.frameId),await this.cleanUpFrameExceptCaller(i.frameId,e)),await Promise.all(n.map(e=>e.close()))}async cleanUpFrameExceptCaller(e,t){const r=await this.glueController.getWorkspacesByFrameId(e),n=r.filter(e=>!e.getWindow(e=>e.id===t)),i=r.find(e=>e.getWindow(e=>e.id===t));await Promise.all(n.map(e=>e.close()));const o=i?i.getAllWindows(e=>e.id!==t):[];await Promise.all(o.map(e=>e.close()))}async cleanupWorkspaceCaller(e,t){const r=(await this.workspacesController.handleGetPlatformFrameId({},t)).id,n=await this.glueController.getWorkspaceWindowById(e);n&&(n.frameId!==r?await n.frame.close():await n.workspace.close())}}const searchOperationDecoder=oneOf$1(constant$2("operationCheck"));class SearchController{glueController;appsRepo;layoutsRepo;workspacesRepo;started=!1;repos=[];provider;activeQueries={};unsubFuncs=[];operations={operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)}};constructor(e,t,r,n){this.glueController=e,this.appsRepo=t,this.layoutsRepo=r,this.workspacesRepo=n}get logger(){return logger.get("notifications.controller")}get providerName(){return`io.Connect Browser Platform ${this.glueController.me.instance}`}handlePlatformShutdown(){this.started=!1,this.unsubFuncs.forEach(e=>e()),this.unsubFuncs=[],this.repos=[],this.activeQueries={},this.provider?.unregister()}async configurePostStart(){if(this.repos.push(this.appsRepo),this.repos.push(this.layoutsRepo),!this.glueController.isWorkspacesEnabled)return;this.repos.push(this.workspacesRepo);const e=this.repos.map(e=>({name:e.type,displayName:e.displayType})),t={name:this.providerName,types:e};if(this.logger?.trace(`Registering the platform as a provider with name: ${t.name} and types: ${JSON.stringify(t.types?.join(", "))}.`),this.provider=await this.glueController.registerProvider(t),!this.provider)return ioError.raiseError("The platform was not registered successfully as a provider.");this.logger?.trace("The platform was registered successfully as a provider.");const r=this.provider.onQuery(e=>{this.processQuery(e).then(()=>this.markQueryDone(e)).catch(t=>this.markQueryError(e,t))}),n=this.provider.onQueryCancel(this.processQueryCancel.bind(this));this.unsubFuncs.push(r),this.unsubFuncs.push(n),this.started=!0,this.logger?.info("The module started successfully.")}async start(){this.logger?.info("Starting the Global Search provider.")}ready(){return Promise.resolve()}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this search control message, because the controller has not been started");const t=e.data,r=e.commandId,n=searchOperationDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This search request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`Search request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`Search request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}async processQuery(e){this.logger?.info(`Processing a new query for: ${e.search}`),this.activeQueries[e.id]={allowedResultsCount:e.providerLimits?.maxResults||Number.MAX_SAFE_INTEGER};const t=e.types?this.repos.filter(t=>e.types?.some(e=>e.name===t.type)):this.repos;await Promise.all(t.map(t=>this.callRepo(t,e)))}async callRepo(e,t){const r=await this.getRepoResults(e,t);this.activeQueries[t.id]&&r&&this.sendResults(r,t)}async getRepoResults(e,t){try{return await e.getResults(t)}catch(e){return void this.markQueryError(t,e)}}sendResults(e,t){try{e.forEach(e=>{this.activeQueries[t.id]&&(this.activeQueries[t.id].allowedResultsCount?(--this.activeQueries[t.id].allowedResultsCount,t.sendResult(e)):this.markQueryDone(t))})}catch(e){this.logger?.warn(`Failed sending results for query: ${t.search} with an error: ${extractErrorMsg$1(e)}`)}}markQueryDone(e){this.activeQueries[e.id]&&(this.logger?.info(`The query for: ${e.search} is completed`),delete this.activeQueries[e.id],e.done())}markQueryError(e,t){this.activeQueries[e.id]&&(this.logger?.warn(`The query for: ${e.search} ended with an error: ${extractErrorMsg$1(t)}`),delete this.activeQueries[e.id],e.error(extractErrorMsg$1(t)))}processQueryCancel(e){delete this.activeQueries[e.id]}}class ApplicationsRepository{glueController;type="application";displayType="Applications";constructor(e){this.glueController=e}getResults(e){const t=new Set,r={count:Math.min(e.providerLimits?.maxResultsPerType||Number.MAX_SAFE_INTEGER,e.providerLimits?.maxResults||Number.MAX_SAFE_INTEGER)},n=this.glueController.getAllApplications();if(n.filter(t=>checkMatch(r,()=>!!t.title?.toLowerCase().includes(e.search.toLowerCase()))).forEach(e=>t.add(e)),!r.count)return Promise.resolve(this.transformApps(t));if(n.filter(t=>checkMatch(r,()=>!!t.caption?.toLowerCase().includes(e.search.toLowerCase()))).forEach(e=>t.add(e)),!r.count)return Promise.resolve(this.transformApps(t));return n.filter(t=>checkMatch(r,()=>t.name.toLowerCase().includes(e.search.toLowerCase()))).forEach(e=>t.add(e)),Promise.resolve(this.transformApps(t))}transformApps(e){const t=[];for(const r of e.values())t.push({type:{name:this.type,displayName:this.displayType},id:r.name,displayName:r.title,description:r.caption,iconURL:r.icon});return t}}class LayoutsRepository{glueController;type="layout";displayType="Layouts";constructor(e){this.glueController=e}async getResults(e){const t=new Set,r={count:Math.min(e.providerLimits?.maxResultsPerType||Number.MAX_SAFE_INTEGER,e.providerLimits?.maxResults||Number.MAX_SAFE_INTEGER)};return(await this.glueController.getAllLayoutsSummaries()).filter(t=>checkMatch(r,()=>t.name.toLowerCase().includes(e.search.toLowerCase()))).forEach(e=>t.add(e)),this.transformLayouts(t)}transformLayouts(e){const t=[];for(const r of e.values())t.push({type:{name:this.type,displayName:this.displayType},id:r.name,displayName:r.name});return t}}class WorkspacesRepository{glueController;type="workspace";displayType="Workspaces";constructor(e){this.glueController=e}async getResults(e){const t=new Set,r={count:Math.min(e.providerLimits?.maxResultsPerType||Number.MAX_SAFE_INTEGER,e.providerLimits?.maxResults||Number.MAX_SAFE_INTEGER)};return(await this.glueController.getAllWorkspacesSummaries()).filter(t=>checkMatch(r,()=>t.name.toLowerCase().includes(e.search.toLowerCase()))).forEach(e=>t.add(e)),this.transformWorkspaces(t)}transformWorkspaces(e){const t=[];for(const r of e.values())t.push({type:{name:this.type,displayName:this.displayType},id:r.name,displayName:r.name});return t}}class LocalStoreController{localStorage;defaultGlobalLayoutNamespace="g42_core_plus_default_global_layout";themesNamespace="g42_core_plus_themes";notificationsNamespace="g42_core_notifications_config";restSchedulerNamespace="g42_core_rest_scheduler";username="g42_public";constructor(){this.localStorage=window.localStorage}start(e){e?.id&&(this.username=e.id);if(!this.localStorage.getItem(this.username)){const e={[this.defaultGlobalLayoutNamespace]:{},[this.themesNamespace]:[],[this.restSchedulerNamespace]:{}};this.localStorage.setItem(this.username,JSON.stringify(e))}}stop(){this.username="g42_public"}saveThemeIfMissing(e){const t=this.getData(this.themesNamespace)||[];t.some(t=>t.theme.name===e.theme.name)||(t.push(e),this.saveData(this.themesNamespace,t))}getAllThemes(){return this.getData(this.themesNamespace)||[]}markThemeSelected(e,t){const r=this.getData(this.themesNamespace)||[],n=r.find(t=>t.theme.name===e);return n?(r.forEach(e=>{e.selected=!1,e.isUserSelected=!1}),n.selected=!0,n.isUserSelected=!!t,this.saveData(this.themesNamespace,r),n.theme):ioError.raiseError(`Cannot mark theme: ${e} as selected, because it doesn't exist`)}getRestSchedulerEntry(e){return this.getAllRestSchedulerEntries()[e]}getAllRestSchedulerEntries(){return this.getData(this.restSchedulerNamespace)||{}}saveRestSchedulerEntry(e){const t=this.getAllRestSchedulerEntries();t[e.key]=e,this.saveData(this.restSchedulerNamespace,t)}clearRestSchedulerEntries(){this.saveData(this.restSchedulerNamespace,{})}deleteRestSchedulerEntry(e){const t=this.getAllRestSchedulerEntries();delete t[e],this.saveData(this.restSchedulerNamespace,t)}getDefaultGlobalLayoutName(){const e=this.getData(this.defaultGlobalLayoutNamespace);return e?.name}saveDefaultGlobalLayout(e){this.saveData(this.defaultGlobalLayoutNamespace,{name:e})}clearDefaultGlobalLayout(){this.saveData(this.defaultGlobalLayoutNamespace,{})}getNotificationsConfig(){return this.getData(this.notificationsNamespace)}setNotificationsConfig(e){this.saveData(this.notificationsNamespace,e)}updateNotificationsConfig(e){const t=this.getNotificationsConfig();if(!t)return ioError.raiseError("Cannot update notifications config, because it doesn't exist");this.setNotificationsConfig(deepMerge$1(t,e,{arrayMerge:(e,t)=>t}))}getData(e){const t=this.localStorage.getItem(this.username);return t?JSON.parse(t)[e]:ioError.raiseError(`Cannot get data for namespace: ${e}, because the user data is missing`)}saveData(e,t){const r=this.localStorage.getItem(this.username);if(!r)return ioError.raiseError(`Cannot set data for namespace: ${e}, because the user data is missing`);const n=JSON.parse(r);n[e]=t,this.localStorage.setItem(this.username,JSON.stringify(n))}}const themesOperationDecoder=oneOf$1(constant$2("getCurrent"),constant$2("list"),constant$2("select"),constant$2("operationCheck")),themeDecoder=object$2({displayName:nonEmptyStringDecoder$2,name:nonEmptyStringDecoder$2}),simpleThemeResponseDecoder=object$2({theme:themeDecoder}),allThemesResponseDecoder=object$2({themes:array$3(themeDecoder)}),selectThemeConfigDecoder=object$2({name:nonEmptyStringDecoder$2}),themesStoreDataDecoder=object$2({theme:themeDecoder,selected:boolean$3(),isUserSelected:boolean$3()}),prefsThemesDecoder=object$2({themes:array$3(themesStoreDataDecoder)}),GlueCorePlusThemesStream="T42.Core.Plus.Themes.Stream",lightTheme={name:"light",displayName:"Light"},darkTheme={name:"dark",displayName:"Dark"};class ThemesController{glueController;localStore;prefsStore;started=!1;themesStream;config;initResolve;initPromise=PromisePlus(e=>{this.initResolve=e},3e4,"Themes controller initialization timed out");operations={getCurrent:{name:"getCurrent",resultDecoder:simpleThemeResponseDecoder,execute:this.handleGetCurrent.bind(this)},list:{name:"list",resultDecoder:allThemesResponseDecoder,execute:this.handleList.bind(this)},select:{name:"select",dataDecoder:selectThemeConfigDecoder,execute:this.handleSelect.bind(this)},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)}};constructor(e,t,r){this.glueController=e,this.localStore=t,this.prefsStore=r}get logger(){return logger.get("themes.controller")}async start(e){this.started=!0,this.config=e.themes,this.themesStream=await this.glueController.createSystemStream(GlueCorePlusThemesStream)}async setupInitialThemes(){this.localStore.saveThemeIfMissing({theme:lightTheme,selected:!1,isUserSelected:!1}),this.localStore.saveThemeIfMissing({theme:darkTheme,selected:!1,isUserSelected:!1}),await this.applyInitialTheme(),this.initResolve()}handlePlatformShutdown(){this.started=!1,this.themesStream.close()}ready(){return Promise.resolve()}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this themes control message, because the controller has not been started");await this.initPromise;const t=e.data,r=e.commandId,n=themesOperationDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This themes request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`Themes request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`Themes request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}handleClientUnloaded(){}async applyInitialTheme(){const e=this.prefsStore.storeType;if(!e||"local"===e)return this.logger?.info("The themes service will use the local storage for the themes data"),void this.applyDefaultThemeIfNoUserSelection();let t;try{t=await this.glueController.clientGlue.prefs.get(systemPrefsAppName)}catch(e){return this.logger?.warn(`Failed to get system preferences for themes service: ${e}, falling back to local storage`),void this.applyDefaultThemeIfNoUserSelection()}const r=t?.data[themesPrefsKey];if(!r?.themes?.length)return this.logger?.info("The system preferences for the themes service are not set in prefs, falling back to local storage"),void this.applyDefaultThemeIfNoUserSelection();const n=prefsThemesDecoder.run(r);if(!n.ok)return this.logger?.error(`The system preferences from Prefs for the themes service did not pass validation: ${JSON.stringify(n.error)}, falling back to local storage`),void this.applyDefaultThemeIfNoUserSelection();const i=n.result.themes.find(e=>e.isUserSelected),o=i?.theme.name??this.getDefaultTheme(),s=this.localStore.markThemeSelected(o,!!i);this.themesStream.push({theme:s})}applyDefaultThemeIfNoUserSelection(){if(this.localStore.getAllThemes().some(e=>e.isUserSelected))return;const e=this.localStore.markThemeSelected(this.getDefaultTheme(),!1);this.themesStream.push({theme:e})}getDefaultTheme(){return"os"===this.config.defaultTheme?this.getOsTheme():this.config.defaultTheme===lightTheme.name?lightTheme.name:darkTheme.name}async saveThemesToPrefs(){const e={[themesPrefsKey]:{themes:this.localStore.getAllThemes()}};await this.glueController.clientGlue.prefs.update(e,{app:systemPrefsAppName})}async handleGetCurrent(e,t){this.logger?.trace(`[${t}] handling a getCurrent message`);const r=this.getSelectedTheme();return r?{theme:r}:ioError.raiseError("No selected theme found!")}async handleList(e,t){this.logger?.trace(`[${t}] handling a list message`);return{themes:this.localStore.getAllThemes().map(e=>e.theme)}}async handleSelect(e,t){this.logger?.trace(`[${t}] handling a select message`);const r=this.getSelectedTheme();if(r?.name===e.name)return void this.logger?.debug(`[${t}] The selected theme is already applied, no need to proceed further`);const n=this.localStore.markThemeSelected(e.name,!0);this.themesStream.push({theme:n}),"local"!==this.prefsStore.storeType&&this.saveThemesToPrefs().catch(e=>{this.logger?.warn(`Failed to sync themes to prefs: ${e} - the themes data is only updated in the local storage`)})}getSelectedTheme(){return this.localStore.getAllThemes().find(e=>e.selected)?.theme}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}getOsTheme(){return window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}}function bind(e,t){return function(){return e.apply(t,arguments)}}const{toString:toString}=Object.prototype,{getPrototypeOf:getPrototypeOf$2}=Object,{iterator:iterator,toStringTag:toStringTag}=Symbol,kindOf=(e=>t=>{const r=toString.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),kindOfTest=e=>(e=e.toLowerCase(),t=>kindOf(t)===e),typeOfTest=e=>t=>typeof t===e,{isArray:isArray$2}=Array,isUndefined=typeOfTest("undefined");function isBuffer(e){return null!==e&&!isUndefined(e)&&null!==e.constructor&&!isUndefined(e.constructor)&&isFunction$3(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const isArrayBuffer=kindOfTest("ArrayBuffer");function isArrayBufferView(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&isArrayBuffer(e.buffer),t}const isString=typeOfTest("string"),isFunction$3=typeOfTest("function"),isNumber=typeOfTest("number"),isObject$3=e=>null!==e&&"object"==typeof e,isBoolean=e=>!0===e||!1===e,isPlainObject$2=e=>{if("object"!==kindOf(e))return!1;const t=getPrototypeOf$2(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||toStringTag in e||iterator in e)},isEmptyObject=e=>{if(!isObject$3(e)||isBuffer(e))return!1;try{return 0===Object.keys(e).length&&Object.getPrototypeOf(e)===Object.prototype}catch(e){return!1}},isDate=kindOfTest("Date"),isFile=kindOfTest("File"),isReactNativeBlob=e=>!(!e||void 0===e.uri),isReactNative=e=>e&&void 0!==e.getParts,isBlob=kindOfTest("Blob"),isFileList=kindOfTest("FileList"),isStream=e=>isObject$3(e)&&isFunction$3(e.pipe);function getGlobal$1(){return"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0!==global?global:{}}const G=getGlobal$1(),FormDataCtor=void 0!==G.FormData?G.FormData:void 0,isFormData=e=>{if(!e)return!1;if(FormDataCtor&&e instanceof FormDataCtor)return!0;const t=getPrototypeOf$2(e);if(!t||t===Object.prototype)return!1;if(!isFunction$3(e.append))return!1;const r=kindOf(e);return"formdata"===r||"object"===r&&isFunction$3(e.toString)&&"[object FormData]"===e.toString()},isURLSearchParams=kindOfTest("URLSearchParams"),[isReadableStream,isRequest,isResponse,isHeaders]=["ReadableStream","Request","Response","Headers"].map(kindOfTest),trim=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function forEach(e,t,{allOwnKeys:r=!1}={}){if(null==e)return;let n,i;if("object"!=typeof e&&(e=[e]),isArray$2(e))for(n=0,i=e.length;n<i;n++)t.call(null,e[n],n,e);else{if(isBuffer(e))return;const i=r?Object.getOwnPropertyNames(e):Object.keys(e),o=i.length;let s;for(n=0;n<o;n++)s=i[n],t.call(null,e[s],s,e)}}function findKey(e,t){if(isBuffer(e))return null;t=t.toLowerCase();const r=Object.keys(e);let n,i=r.length;for(;i-- >0;)if(n=r[i],t===n.toLowerCase())return n;return null}const _global$1="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,isContextDefined=e=>!isUndefined(e)&&e!==_global$1;function merge$2(){const{caseless:e,skipUndefined:t}=isContextDefined(this)&&this||{},r={},n=(n,i)=>{if("__proto__"===i||"constructor"===i||"prototype"===i)return;const o=e&&findKey(r,i)||i;isPlainObject$2(r[o])&&isPlainObject$2(n)?r[o]=merge$2(r[o],n):isPlainObject$2(n)?r[o]=merge$2({},n):isArray$2(n)?r[o]=n.slice():t&&isUndefined(n)||(r[o]=n)};for(let e=0,t=arguments.length;e<t;e++)arguments[e]&&forEach(arguments[e],n);return r}const extend=(e,t,r,{allOwnKeys:n}={})=>(forEach(t,(t,n)=>{r&&isFunction$3(t)?Object.defineProperty(e,n,{value:bind(t,r),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(e,n,{value:t,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:n}),e),stripBOM=e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits=(e,t,r,n)=>{e.prototype=Object.create(t.prototype,n),Object.defineProperty(e.prototype,"constructor",{value:e,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject=(e,t,r,n)=>{let i,o,s;const a={};if(t=t||{},null==e)return t;do{for(i=Object.getOwnPropertyNames(e),o=i.length;o-- >0;)s=i[o],n&&!n(s,e,t)||a[s]||(t[s]=e[s],a[s]=!0);e=!1!==r&&getPrototypeOf$2(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},endsWith=(e,t,r)=>{e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;const n=e.indexOf(t,r);return-1!==n&&n===r},toArray=e=>{if(!e)return null;if(isArray$2(e))return e;let t=e.length;if(!isNumber(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},isTypedArray=(e=>t=>e&&t instanceof e)("undefined"!=typeof Uint8Array&&getPrototypeOf$2(Uint8Array)),forEachEntry=(e,t)=>{const r=(e&&e[iterator]).call(e);let n;for(;(n=r.next())&&!n.done;){const r=n.value;t.call(e,r[0],r[1])}},matchAll=(e,t)=>{let r;const n=[];for(;null!==(r=e.exec(t));)n.push(r);return n},isHTMLForm=kindOfTest("HTMLFormElement"),toCamelCase=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(e,t,r){return t.toUpperCase()+r}),hasOwnProperty$2=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),isRegExp=kindOfTest("RegExp"),reduceDescriptors=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),n={};forEach(r,(r,i)=>{let o;!1!==(o=t(r,i,e))&&(n[i]=o||r)}),Object.defineProperties(e,n)},freezeMethods=e=>{reduceDescriptors(e,(t,r)=>{if(isFunction$3(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;const n=e[r];isFunction$3(n)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")}))})},toObjectSet=(e,t)=>{const r={},n=e=>{e.forEach(e=>{r[e]=!0})};return isArray$2(e)?n(e):n(String(e).split(t)),r},noop=()=>{},toFiniteNumber=(e,t)=>null!=e&&Number.isFinite(e=+e)?e:t;function isSpecCompliantForm(e){return!!(e&&isFunction$3(e.append)&&"FormData"===e[toStringTag]&&e[iterator])}const toJSONObject=e=>{const t=new Array(10),r=(e,n)=>{if(isObject$3(e)){if(t.indexOf(e)>=0)return;if(isBuffer(e))return e;if(!("toJSON"in e)){t[n]=e;const i=isArray$2(e)?[]:{};return forEach(e,(e,t)=>{const o=r(e,n+1);!isUndefined(o)&&(i[t]=o)}),t[n]=void 0,i}}return e};return r(e,0)},isAsyncFn=kindOfTest("AsyncFunction"),isThenable=e=>e&&(isObject$3(e)||isFunction$3(e))&&isFunction$3(e.then)&&isFunction$3(e.catch),_setImmediate=(setImmediateSupported="function"==typeof setImmediate,postMessageSupported=isFunction$3(_global$1.postMessage),setImmediateSupported?setImmediate:postMessageSupported?(token=`axios@${Math.random()}`,callbacks=[],_global$1.addEventListener("message",({source:e,data:t})=>{e===_global$1&&t===token&&callbacks.length&&callbacks.shift()()},!1),e=>{callbacks.push(e),_global$1.postMessage(token,"*")}):e=>setTimeout(e));var setImmediateSupported,postMessageSupported,token,callbacks;const asap="undefined"!=typeof queueMicrotask?queueMicrotask.bind(_global$1):_setImmediate,isIterable=e=>null!=e&&isFunction$3(e[iterator]);var utils$3={isArray:isArray$2,isArrayBuffer:isArrayBuffer,isBuffer:isBuffer,isFormData:isFormData,isArrayBufferView:isArrayBufferView,isString:isString,isNumber:isNumber,isBoolean:isBoolean,isObject:isObject$3,isPlainObject:isPlainObject$2,isEmptyObject:isEmptyObject,isReadableStream:isReadableStream,isRequest:isRequest,isResponse:isResponse,isHeaders:isHeaders,isUndefined:isUndefined,isDate:isDate,isFile:isFile,isReactNativeBlob:isReactNativeBlob,isReactNative:isReactNative,isBlob:isBlob,isRegExp:isRegExp,isFunction:isFunction$3,isStream:isStream,isURLSearchParams:isURLSearchParams,isTypedArray:isTypedArray,isFileList:isFileList,forEach:forEach,merge:merge$2,extend:extend,trim:trim,stripBOM:stripBOM,inherits:inherits,toFlatObject:toFlatObject,kindOf:kindOf,kindOfTest:kindOfTest,endsWith:endsWith,toArray:toArray,forEachEntry:forEachEntry,matchAll:matchAll,isHTMLForm:isHTMLForm,hasOwnProperty:hasOwnProperty$2,hasOwnProp:hasOwnProperty$2,reduceDescriptors:reduceDescriptors,freezeMethods:freezeMethods,toObjectSet:toObjectSet,toCamelCase:toCamelCase,noop:noop,toFiniteNumber:toFiniteNumber,findKey:findKey,global:_global$1,isContextDefined:isContextDefined,isSpecCompliantForm:isSpecCompliantForm,toJSONObject:toJSONObject,isAsyncFn:isAsyncFn,isThenable:isThenable,setImmediate:_setImmediate,asap:asap,isIterable:isIterable};let AxiosError$1=class e extends Error{static from(t,r,n,i,o,s){const a=new e(t.message,r||t.code,n,i,o);return a.cause=t,a.name=t.name,null!=t.status&&null==a.status&&(a.status=t.status),s&&Object.assign(a,s),a}constructor(e,t,r,n,i){super(e),Object.defineProperty(this,"message",{value:e,enumerable:!0,writable:!0,configurable:!0}),this.name="AxiosError",this.isAxiosError=!0,t&&(this.code=t),r&&(this.config=r),n&&(this.request=n),i&&(this.response=i,this.status=i.status)}toJSON(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:utils$3.toJSONObject(this.config),code:this.code,status:this.status}}};AxiosError$1.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE",AxiosError$1.ERR_BAD_OPTION="ERR_BAD_OPTION",AxiosError$1.ECONNABORTED="ECONNABORTED",AxiosError$1.ETIMEDOUT="ETIMEDOUT",AxiosError$1.ERR_NETWORK="ERR_NETWORK",AxiosError$1.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS",AxiosError$1.ERR_DEPRECATED="ERR_DEPRECATED",AxiosError$1.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE",AxiosError$1.ERR_BAD_REQUEST="ERR_BAD_REQUEST",AxiosError$1.ERR_CANCELED="ERR_CANCELED",AxiosError$1.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT",AxiosError$1.ERR_INVALID_URL="ERR_INVALID_URL",AxiosError$1.ERR_FORM_DATA_DEPTH_EXCEEDED="ERR_FORM_DATA_DEPTH_EXCEEDED";var httpAdapter=null;function isVisitable(e){return utils$3.isPlainObject(e)||utils$3.isArray(e)}function removeBrackets(e){return utils$3.endsWith(e,"[]")?e.slice(0,-2):e}function renderKey(e,t,r){return e?e.concat(t).map(function(e,t){return e=removeBrackets(e),!r&&t?"["+e+"]":e}).join(r?".":""):t}function isFlatArray(e){return utils$3.isArray(e)&&!e.some(isVisitable)}const predicates=utils$3.toFlatObject(utils$3,{},null,function(e){return/^is[A-Z]/.test(e)});function toFormData$1(e,t,r){if(!utils$3.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const n=(r=utils$3.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(e,t){return!utils$3.isUndefined(t[e])})).metaTokens,i=r.visitor||d,o=r.dots,s=r.indexes,a=r.Blob||"undefined"!=typeof Blob&&Blob,c=void 0===r.maxDepth?100:r.maxDepth,l=a&&utils$3.isSpecCompliantForm(t);if(!utils$3.isFunction(i))throw new TypeError("visitor must be a function");function u(e){if(null===e)return"";if(utils$3.isDate(e))return e.toISOString();if(utils$3.isBoolean(e))return e.toString();if(!l&&utils$3.isBlob(e))throw new AxiosError$1("Blob is not supported. Use a Buffer instead.");return utils$3.isArrayBuffer(e)||utils$3.isTypedArray(e)?l&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function d(e,r,i){let a=e;if(utils$3.isReactNative(t)&&utils$3.isReactNativeBlob(e))return t.append(renderKey(i,r,o),u(e)),!1;if(e&&!i&&"object"==typeof e)if(utils$3.endsWith(r,"{}"))r=n?r:r.slice(0,-2),e=JSON.stringify(e);else if(utils$3.isArray(e)&&isFlatArray(e)||(utils$3.isFileList(e)||utils$3.endsWith(r,"[]"))&&(a=utils$3.toArray(e)))return r=removeBrackets(r),a.forEach(function(e,n){!utils$3.isUndefined(e)&&null!==e&&t.append(!0===s?renderKey([r],n,o):null===s?r:r+"[]",u(e))}),!1;return!!isVisitable(e)||(t.append(renderKey(i,r,o),u(e)),!1)}const h=[],p=Object.assign(predicates,{defaultVisitor:d,convertValue:u,isVisitable:isVisitable});if(!utils$3.isObject(e))throw new TypeError("data must be an object");return function e(r,n,o=0){if(!utils$3.isUndefined(r)){if(o>c)throw new AxiosError$1("Object is too deeply nested ("+o+" levels). Max depth: "+c,AxiosError$1.ERR_FORM_DATA_DEPTH_EXCEEDED);if(-1!==h.indexOf(r))throw Error("Circular reference detected in "+n.join("."));h.push(r),utils$3.forEach(r,function(r,s){!0===(!(utils$3.isUndefined(r)||null===r)&&i.call(t,r,utils$3.isString(s)?s.trim():s,n,p))&&e(r,n?n.concat(s):[s],o+1)}),h.pop()}}(e),t}function encode$1(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"};return encodeURIComponent(e).replace(/[!'()~]|%20/g,function(e){return t[e]})}function AxiosURLSearchParams(e,t){this._pairs=[],e&&toFormData$1(e,this,t)}const prototype=AxiosURLSearchParams.prototype;function encode(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function buildURL(e,t,r){if(!t)return e;const n=r&&r.encode||encode,i=utils$3.isFunction(r)?{serialize:r}:r,o=i&&i.serialize;let s;if(s=o?o(t,i):utils$3.isURLSearchParams(t)?t.toString():new AxiosURLSearchParams(t,i).toString(n),s){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+s}return e}prototype.append=function(e,t){this._pairs.push([e,t])},prototype.toString=function(e){const t=e?function(t){return e.call(this,t,encode$1)}:encode$1;return this._pairs.map(function(e){return t(e[0])+"="+t(e[1])},"").join("&")};class InterceptorManager{constructor(){this.handlers=[]}use(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){utils$3.forEach(this.handlers,function(t){null!==t&&e(t)})}}var transitionalDefaults={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0},URLSearchParams$1="undefined"!=typeof URLSearchParams?URLSearchParams:AxiosURLSearchParams,FormData$2="undefined"!=typeof FormData?FormData:null,Blob$1="undefined"!=typeof Blob?Blob:null,platform$1={isBrowser:!0,classes:{URLSearchParams:URLSearchParams$1,FormData:FormData$2,Blob:Blob$1},protocols:["http","https","file","blob","url","data"]};const hasBrowserEnv="undefined"!=typeof window&&"undefined"!=typeof document,_navigator="object"==typeof navigator&&navigator||void 0,hasStandardBrowserEnv=hasBrowserEnv&&(!_navigator||["ReactNative","NativeScript","NS"].indexOf(_navigator.product)<0),hasStandardBrowserWebWorkerEnv="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,origin=hasBrowserEnv&&window.location.href||"http://localhost";var utils$2=Object.freeze({__proto__:null,hasBrowserEnv:hasBrowserEnv,hasStandardBrowserEnv:hasStandardBrowserEnv,hasStandardBrowserWebWorkerEnv:hasStandardBrowserWebWorkerEnv,navigator:_navigator,origin:origin}),platform={...utils$2,...platform$1};function toURLEncodedForm(e,t){return toFormData$1(e,new platform.classes.URLSearchParams,{visitor:function(e,t,r,n){return platform.isNode&&utils$3.isBuffer(e)?(this.append(t,e.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)},...t})}function parsePropPath(e){return utils$3.matchAll(/\w+|\[(\w*)]/g,e).map(e=>"[]"===e[0]?"":e[1]||e[0])}function arrayToObject(e){const t={},r=Object.keys(e);let n;const i=r.length;let o;for(n=0;n<i;n++)o=r[n],t[o]=e[o];return t}function formDataToJSON(e){function t(e,r,n,i){let o=e[i++];if("__proto__"===o)return!0;const s=Number.isFinite(+o),a=i>=e.length;if(o=!o&&utils$3.isArray(n)?n.length:o,a)return utils$3.hasOwnProp(n,o)?n[o]=utils$3.isArray(n[o])?n[o].concat(r):[n[o],r]:n[o]=r,!s;n[o]&&utils$3.isObject(n[o])||(n[o]=[]);return t(e,r,n[o],i)&&utils$3.isArray(n[o])&&(n[o]=arrayToObject(n[o])),!s}if(utils$3.isFormData(e)&&utils$3.isFunction(e.entries)){const r={};return utils$3.forEachEntry(e,(e,n)=>{t(parsePropPath(e),n,r,0)}),r}return null}const own=(e,t)=>null!=e&&utils$3.hasOwnProp(e,t)?e[t]:void 0;function stringifySafely(e,t,r){if(utils$3.isString(e))try{return(t||JSON.parse)(e),utils$3.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(r||JSON.stringify)(e)}const defaults={transitional:transitionalDefaults,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const r=t.getContentType()||"",n=r.indexOf("application/json")>-1,i=utils$3.isObject(e);i&&utils$3.isHTMLForm(e)&&(e=new FormData(e));if(utils$3.isFormData(e))return n?JSON.stringify(formDataToJSON(e)):e;if(utils$3.isArrayBuffer(e)||utils$3.isBuffer(e)||utils$3.isStream(e)||utils$3.isFile(e)||utils$3.isBlob(e)||utils$3.isReadableStream(e))return e;if(utils$3.isArrayBufferView(e))return e.buffer;if(utils$3.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let o;if(i){const t=own(this,"formSerializer");if(r.indexOf("application/x-www-form-urlencoded")>-1)return toURLEncodedForm(e,t).toString();if((o=utils$3.isFileList(e))||r.indexOf("multipart/form-data")>-1){const r=own(this,"env"),n=r&&r.FormData;return toFormData$1(o?{"files[]":e}:e,n&&new n,t)}}return i||n?(t.setContentType("application/json",!1),stringifySafely(e)):e}],transformResponse:[function(e){const t=own(this,"transitional")||defaults.transitional,r=t&&t.forcedJSONParsing,n=own(this,"responseType"),i="json"===n;if(utils$3.isResponse(e)||utils$3.isReadableStream(e))return e;if(e&&utils$3.isString(e)&&(r&&!n||i)){const r=!(t&&t.silentJSONParsing)&&i;try{return JSON.parse(e,own(this,"parseReviver"))}catch(e){if(r){if("SyntaxError"===e.name)throw AxiosError$1.from(e,AxiosError$1.ERR_BAD_RESPONSE,this,null,own(this,"response"));throw e}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:platform.classes.FormData,Blob:platform.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};utils$3.forEach(["delete","get","head","post","put","patch"],e=>{defaults.headers[e]={}});const ignoreDuplicateOf=utils$3.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]);var parseHeaders=e=>{const t={};let r,n,i;return e&&e.split("\n").forEach(function(e){i=e.indexOf(":"),r=e.substring(0,i).trim().toLowerCase(),n=e.substring(i+1).trim(),!r||t[r]&&ignoreDuplicateOf[r]||("set-cookie"===r?t[r]?t[r].push(n):t[r]=[n]:t[r]=t[r]?t[r]+", "+n:n)}),t};const $internals=Symbol("internals"),INVALID_HEADER_VALUE_CHARS_RE=/[^\x09\x20-\x7E\x80-\xFF]/g;function trimSPorHTAB(e){let t=0,r=e.length;for(;t<r;){const r=e.charCodeAt(t);if(9!==r&&32!==r)break;t+=1}for(;r>t;){const t=e.charCodeAt(r-1);if(9!==t&&32!==t)break;r-=1}return 0===t&&r===e.length?e:e.slice(t,r)}function normalizeHeader(e){return e&&String(e).trim().toLowerCase()}function sanitizeHeaderValue(e){return trimSPorHTAB(e.replace(INVALID_HEADER_VALUE_CHARS_RE,""))}function normalizeValue(e){return!1===e||null==e?e:utils$3.isArray(e)?e.map(normalizeValue):sanitizeHeaderValue(String(e))}function parseTokens(e){const t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=r.exec(e);)t[n[1]]=n[2];return t}const isValidHeaderName=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function matchHeaderValue(e,t,r,n,i){return utils$3.isFunction(n)?n.call(this,t,r):(i&&(t=r),utils$3.isString(t)?utils$3.isString(n)?-1!==t.indexOf(n):utils$3.isRegExp(n)?n.test(t):void 0:void 0)}function formatHeader(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,r)=>t.toUpperCase()+r)}function buildAccessors(e,t){const r=utils$3.toCamelCase(" "+t);["get","set","has"].forEach(n=>{Object.defineProperty(e,n+r,{value:function(e,r,i){return this[n].call(this,t,e,r,i)},configurable:!0})})}let AxiosHeaders$1=class{constructor(e){e&&this.set(e)}set(e,t,r){const n=this;function i(e,t,r){const i=normalizeHeader(t);if(!i)throw new Error("header name must be a non-empty string");const o=utils$3.findKey(n,i);(!o||void 0===n[o]||!0===r||void 0===r&&!1!==n[o])&&(n[o||t]=normalizeValue(e))}const o=(e,t)=>utils$3.forEach(e,(e,r)=>i(e,r,t));if(utils$3.isPlainObject(e)||e instanceof this.constructor)o(e,t);else if(utils$3.isString(e)&&(e=e.trim())&&!isValidHeaderName(e))o(parseHeaders(e),t);else if(utils$3.isObject(e)&&utils$3.isIterable(e)){let r,n,i={};for(const t of e){if(!utils$3.isArray(t))throw TypeError("Object iterator must return a key-value pair");i[n=t[0]]=(r=i[n])?utils$3.isArray(r)?[...r,t[1]]:[r,t[1]]:t[1]}o(i,t)}else null!=e&&i(t,e,r);return this}get(e,t){if(e=normalizeHeader(e)){const r=utils$3.findKey(this,e);if(r){const e=this[r];if(!t)return e;if(!0===t)return parseTokens(e);if(utils$3.isFunction(t))return t.call(this,e,r);if(utils$3.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=normalizeHeader(e)){const r=utils$3.findKey(this,e);return!(!r||void 0===this[r]||t&&!matchHeaderValue(this,this[r],r,t))}return!1}delete(e,t){const r=this;let n=!1;function i(e){if(e=normalizeHeader(e)){const i=utils$3.findKey(r,e);!i||t&&!matchHeaderValue(r,r[i],i,t)||(delete r[i],n=!0)}}return utils$3.isArray(e)?e.forEach(i):i(e),n}clear(e){const t=Object.keys(this);let r=t.length,n=!1;for(;r--;){const i=t[r];e&&!matchHeaderValue(this,this[i],i,e,!0)||(delete this[i],n=!0)}return n}normalize(e){const t=this,r={};return utils$3.forEach(this,(n,i)=>{const o=utils$3.findKey(r,i);if(o)return t[o]=normalizeValue(n),void delete t[i];const s=e?formatHeader(i):String(i).trim();s!==i&&delete t[i],t[s]=normalizeValue(n),r[s]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return utils$3.forEach(this,(r,n)=>{null!=r&&!1!==r&&(t[n]=e&&utils$3.isArray(r)?r.join(", "):r)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+": "+t).join("\n")}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const r=new this(e);return t.forEach(e=>r.set(e)),r}static accessor(e){const t=(this[$internals]=this[$internals]={accessors:{}}).accessors,r=this.prototype;function n(e){const n=normalizeHeader(e);t[n]||(buildAccessors(r,e),t[n]=!0)}return utils$3.isArray(e)?e.forEach(n):n(e),this}};function transformData(e,t){const r=this||defaults,n=t||r,i=AxiosHeaders$1.from(n.headers);let o=n.data;return utils$3.forEach(e,function(e){o=e.call(r,o,i.normalize(),t?t.status:void 0)}),i.normalize(),o}function isCancel$1(e){return!(!e||!e.__CANCEL__)}AxiosHeaders$1.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),utils$3.reduceDescriptors(AxiosHeaders$1.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[r]=e}}}),utils$3.freezeMethods(AxiosHeaders$1);let CanceledError$1=class extends AxiosError$1{constructor(e,t,r){super(null==e?"canceled":e,AxiosError$1.ERR_CANCELED,t,r),this.name="CanceledError",this.__CANCEL__=!0}};function settle(e,t,r){const n=r.config.validateStatus;r.status&&n&&!n(r.status)?t(new AxiosError$1("Request failed with status code "+r.status,[AxiosError$1.ERR_BAD_REQUEST,AxiosError$1.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):e(r)}function parseProtocol(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function speedometer(e,t){e=e||10;const r=new Array(e),n=new Array(e);let i,o=0,s=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),l=n[s];i||(i=c),r[o]=a,n[o]=c;let u=s,d=0;for(;u!==o;)d+=r[u++],u%=e;if(o=(o+1)%e,o===s&&(s=(s+1)%e),c-i<t)return;const h=l&&c-l;return h?Math.round(1e3*d/h):void 0}}function throttle(e,t){let r,n,i=0,o=1e3/t;const s=(t,o=Date.now())=>{i=o,r=null,n&&(clearTimeout(n),n=null),e(...t)};return[(...e)=>{const t=Date.now(),a=t-i;a>=o?s(e,t):(r=e,n||(n=setTimeout(()=>{n=null,s(r)},o-a)))},()=>r&&s(r)]}const progressEventReducer=(e,t,r=3)=>{let n=0;const i=speedometer(50,250);return throttle(r=>{const o=r.loaded,s=r.lengthComputable?r.total:void 0,a=null!=s?Math.min(o,s):o,c=Math.max(0,a-n),l=i(c);n=Math.max(n,a);e({loaded:a,total:s,progress:s?a/s:void 0,bytes:c,rate:l||void 0,estimated:l&&s?(s-a)/l:void 0,event:r,lengthComputable:null!=s,[t?"download":"upload"]:!0})},r)},progressEventDecorator=(e,t)=>{const r=null!=e;return[n=>t[0]({lengthComputable:r,total:e,loaded:n}),t[1]]},asyncDecorator=e=>(...t)=>utils$3.asap(()=>e(...t));var isURLSameOrigin=platform.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,platform.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(platform.origin),platform.navigator&&/(msie|trident)/i.test(platform.navigator.userAgent)):()=>!0,cookies=platform.hasStandardBrowserEnv?{write(e,t,r,n,i,o,s){if("undefined"==typeof document)return;const a=[`${e}=${encodeURIComponent(t)}`];utils$3.isNumber(r)&&a.push(`expires=${new Date(r).toUTCString()}`),utils$3.isString(n)&&a.push(`path=${n}`),utils$3.isString(i)&&a.push(`domain=${i}`),!0===o&&a.push("secure"),utils$3.isString(s)&&a.push(`SameSite=${s}`),document.cookie=a.join("; ")},read(e){if("undefined"==typeof document)return null;const t=document.cookie.match(new RegExp("(?:^|; )"+e+"=([^;]*)"));return t?decodeURIComponent(t[1]):null},remove(e){this.write(e,"",Date.now()-864e5,"/")}}:{write(){},read:()=>null,remove(){}};function isAbsoluteURL(e){return"string"==typeof e&&/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function combineURLs(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function buildFullPath(e,t,r){let n=!isAbsoluteURL(t);return e&&(n||!1===r)?combineURLs(e,t):t}const headersToObject=e=>e instanceof AxiosHeaders$1?{...e}:e;function mergeConfig$2(e,t){t=t||{};const r=Object.create(null);function n(e,t,r,n){return utils$3.isPlainObject(e)&&utils$3.isPlainObject(t)?utils$3.merge.call({caseless:n},e,t):utils$3.isPlainObject(t)?utils$3.merge({},t):utils$3.isArray(t)?t.slice():t}function i(e,t,r,i){return utils$3.isUndefined(t)?utils$3.isUndefined(e)?void 0:n(void 0,e,0,i):n(e,t,0,i)}function o(e,t){if(!utils$3.isUndefined(t))return n(void 0,t)}function s(e,t){return utils$3.isUndefined(t)?utils$3.isUndefined(e)?void 0:n(void 0,e):n(void 0,t)}function a(r,i,o){return utils$3.hasOwnProp(t,o)?n(r,i):utils$3.hasOwnProp(e,o)?n(void 0,r):void 0}Object.defineProperty(r,"hasOwnProperty",{value:Object.prototype.hasOwnProperty,enumerable:!1,writable:!0,configurable:!0});const c={url:o,method:o,data:o,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,allowedSocketPaths:s,responseEncoding:s,validateStatus:a,headers:(e,t,r)=>i(headersToObject(e),headersToObject(t),0,!0)};return utils$3.forEach(Object.keys({...e,...t}),function(n){if("__proto__"===n||"constructor"===n||"prototype"===n)return;const o=utils$3.hasOwnProp(c,n)?c[n]:i,s=o(utils$3.hasOwnProp(e,n)?e[n]:void 0,utils$3.hasOwnProp(t,n)?t[n]:void 0,n);utils$3.isUndefined(s)&&o!==a||(r[n]=s)}),r}var resolveConfig=e=>{const t=mergeConfig$2({},e),r=e=>utils$3.hasOwnProp(t,e)?t[e]:void 0,n=r("data");let i=r("withXSRFToken");const o=r("xsrfHeaderName"),s=r("xsrfCookieName");let a=r("headers");const c=r("auth"),l=r("baseURL"),u=r("allowAbsoluteUrls"),d=r("url");if(t.headers=a=AxiosHeaders$1.from(a),t.url=buildURL(buildFullPath(l,d,u),e.params,e.paramsSerializer),c&&a.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),utils$3.isFormData(n))if(platform.hasStandardBrowserEnv||platform.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(utils$3.isFunction(n.getHeaders)){const e=n.getHeaders(),t=["content-type","content-length"];Object.entries(e).forEach(([e,r])=>{t.includes(e.toLowerCase())&&a.set(e,r)})}if(platform.hasStandardBrowserEnv){utils$3.isFunction(i)&&(i=i(t));if(!0===i||null==i&&isURLSameOrigin(t.url)){const e=o&&s&&cookies.read(s);e&&a.set(o,e)}}return t};const isXHRAdapterSupported="undefined"!=typeof XMLHttpRequest;var xhrAdapter=isXHRAdapterSupported&&function(e){return new Promise(function(t,r){const n=resolveConfig(e);let i=n.data;const o=AxiosHeaders$1.from(n.headers).normalize();let s,a,c,l,u,{responseType:d,onUploadProgress:h,onDownloadProgress:p}=n;function g(){l&&l(),u&&u(),n.cancelToken&&n.cancelToken.unsubscribe(s),n.signal&&n.signal.removeEventListener("abort",s)}let m=new XMLHttpRequest;function f(){if(!m)return;const n=AxiosHeaders$1.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders());settle(function(e){t(e),g()},function(e){r(e),g()},{data:d&&"text"!==d&&"json"!==d?m.response:m.responseText,status:m.status,statusText:m.statusText,headers:n,config:e,request:m}),m=null}m.open(n.method.toUpperCase(),n.url,!0),m.timeout=n.timeout,"onloadend"in m?m.onloadend=f:m.onreadystatechange=function(){m&&4===m.readyState&&(0!==m.status||m.responseURL&&0===m.responseURL.indexOf("file:"))&&setTimeout(f)},m.onabort=function(){m&&(r(new AxiosError$1("Request aborted",AxiosError$1.ECONNABORTED,e,m)),m=null)},m.onerror=function(t){const n=t&&t.message?t.message:"Network Error",i=new AxiosError$1(n,AxiosError$1.ERR_NETWORK,e,m);i.event=t||null,r(i),m=null},m.ontimeout=function(){let t=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded";const i=n.transitional||transitionalDefaults;n.timeoutErrorMessage&&(t=n.timeoutErrorMessage),r(new AxiosError$1(t,i.clarifyTimeoutError?AxiosError$1.ETIMEDOUT:AxiosError$1.ECONNABORTED,e,m)),m=null},void 0===i&&o.setContentType(null),"setRequestHeader"in m&&utils$3.forEach(o.toJSON(),function(e,t){m.setRequestHeader(t,e)}),utils$3.isUndefined(n.withCredentials)||(m.withCredentials=!!n.withCredentials),d&&"json"!==d&&(m.responseType=n.responseType),p&&([c,u]=progressEventReducer(p,!0),m.addEventListener("progress",c)),h&&m.upload&&([a,l]=progressEventReducer(h),m.upload.addEventListener("progress",a),m.upload.addEventListener("loadend",l)),(n.cancelToken||n.signal)&&(s=t=>{m&&(r(!t||t.type?new CanceledError$1(null,e,m):t),m.abort(),m=null)},n.cancelToken&&n.cancelToken.subscribe(s),n.signal&&(n.signal.aborted?s():n.signal.addEventListener("abort",s)));const y=parseProtocol(n.url);y&&-1===platform.protocols.indexOf(y)?r(new AxiosError$1("Unsupported protocol "+y+":",AxiosError$1.ERR_BAD_REQUEST,e)):m.send(i||null)})};const composeSignals=(e,t)=>{const{length:r}=e=e?e.filter(Boolean):[];if(t||r){let r,n=new AbortController;const i=function(e){if(!r){r=!0,s();const t=e instanceof Error?e:this.reason;n.abort(t instanceof AxiosError$1?t:new CanceledError$1(t instanceof Error?t.message:t))}};let o=t&&setTimeout(()=>{o=null,i(new AxiosError$1(`timeout of ${t}ms exceeded`,AxiosError$1.ETIMEDOUT))},t);const s=()=>{e&&(o&&clearTimeout(o),o=null,e.forEach(e=>{e.unsubscribe?e.unsubscribe(i):e.removeEventListener("abort",i)}),e=null)};e.forEach(e=>e.addEventListener("abort",i));const{signal:a}=n;return a.unsubscribe=()=>utils$3.asap(s),a}},streamChunk=function*(e,t){let r=e.byteLength;if(r<t)return void(yield e);let n,i=0;for(;i<r;)n=i+t,yield e.slice(i,n),i=n},readBytes=async function*(e,t){for await(const r of readStream(e))yield*streamChunk(r,t)},readStream=async function*(e){if(e[Symbol.asyncIterator])return void(yield*e);const t=e.getReader();try{for(;;){const{done:e,value:r}=await t.read();if(e)break;yield r}}finally{await t.cancel()}},trackStream=(e,t,r,n)=>{const i=readBytes(e,t);let o,s=0,a=e=>{o||(o=!0,n&&n(e))};return new ReadableStream({async pull(e){try{const{done:t,value:n}=await i.next();if(t)return a(),void e.close();let o=n.byteLength;if(r){let e=s+=o;r(e)}e.enqueue(new Uint8Array(n))}catch(e){throw a(e),e}},cancel:e=>(a(e),i.return())},{highWaterMark:2})},DEFAULT_CHUNK_SIZE=65536,{isFunction:isFunction$2}=utils$3,globalFetchAPI=(({Request:e,Response:t})=>({Request:e,Response:t}))(utils$3.global),{ReadableStream:ReadableStream$1,TextEncoder:TextEncoder$1}=utils$3.global,test=(e,...t)=>{try{return!!e(...t)}catch(e){return!1}},factory$2=e=>{e=utils$3.merge.call({skipUndefined:!0},globalFetchAPI,e);const{fetch:t,Request:r,Response:n}=e,i=t?isFunction$2(t):"function"==typeof fetch,o=isFunction$2(r),s=isFunction$2(n);if(!i)return!1;const a=i&&isFunction$2(ReadableStream$1),c=i&&("function"==typeof TextEncoder$1?(l=new TextEncoder$1,e=>l.encode(e)):async e=>new Uint8Array(await new r(e).arrayBuffer()));var l;const u=o&&a&&test(()=>{let e=!1;const t=new r(platform.origin,{body:new ReadableStream$1,method:"POST",get duplex(){return e=!0,"half"}}),n=t.headers.has("Content-Type");return null!=t.body&&t.body.cancel(),e&&!n}),d=s&&a&&test(()=>utils$3.isReadableStream(new n("").body)),h={stream:d&&(e=>e.body)};i&&["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!h[e]&&(h[e]=(t,r)=>{let n=t&&t[e];if(n)return n.call(t);throw new AxiosError$1(`Response type '${e}' is not supported`,AxiosError$1.ERR_NOT_SUPPORT,r)})});const p=async(e,t)=>{const n=utils$3.toFiniteNumber(e.getContentLength());return null==n?(async e=>{if(null==e)return 0;if(utils$3.isBlob(e))return e.size;if(utils$3.isSpecCompliantForm(e)){const t=new r(platform.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return utils$3.isArrayBufferView(e)||utils$3.isArrayBuffer(e)?e.byteLength:(utils$3.isURLSearchParams(e)&&(e+=""),utils$3.isString(e)?(await c(e)).byteLength:void 0)})(t):n};return async e=>{let{url:i,method:s,data:a,signal:c,cancelToken:l,timeout:g,onDownloadProgress:m,onUploadProgress:f,responseType:y,headers:$,withCredentials:b="same-origin",fetchOptions:w}=resolveConfig(e),v=t||fetch;y=y?(y+"").toLowerCase():"text";let S=composeSignals([c,l&&l.toAbortSignal()],g),E=null;const C=S&&S.unsubscribe&&(()=>{S.unsubscribe()});let _;try{if(f&&u&&"get"!==s&&"head"!==s&&0!==(_=await p($,a))){let e,t=new r(i,{method:"POST",body:a,duplex:"half"});if(utils$3.isFormData(a)&&(e=t.headers.get("content-type"))&&$.setContentType(e),t.body){const[e,r]=progressEventDecorator(_,progressEventReducer(asyncDecorator(f)));a=trackStream(t.body,DEFAULT_CHUNK_SIZE,e,r)}}utils$3.isString(b)||(b=b?"include":"omit");const t=o&&"credentials"in r.prototype;if(utils$3.isFormData(a)){const e=$.getContentType();e&&/^multipart\/form-data/i.test(e)&&!/boundary=/i.test(e)&&$.delete("content-type")}const c={...w,signal:S,method:s.toUpperCase(),headers:$.normalize().toJSON(),body:a,duplex:"half",credentials:t?b:void 0};E=o&&new r(i,c);let l=await(o?v(E,w):v(i,c));const g=d&&("stream"===y||"response"===y);if(d&&(m||g&&C)){const e={};["status","statusText","headers"].forEach(t=>{e[t]=l[t]});const t=utils$3.toFiniteNumber(l.headers.get("content-length")),[r,i]=m&&progressEventDecorator(t,progressEventReducer(asyncDecorator(m),!0))||[];l=new n(trackStream(l.body,DEFAULT_CHUNK_SIZE,r,()=>{i&&i(),C&&C()}),e)}y=y||"text";let I=await h[utils$3.findKey(h,y)||"text"](l,e);return!g&&C&&C(),await new Promise((t,r)=>{settle(t,r,{data:I,headers:AxiosHeaders$1.from(l.headers),status:l.status,statusText:l.statusText,config:e,request:E})})}catch(t){if(C&&C(),t&&"TypeError"===t.name&&/Load failed|fetch/i.test(t.message))throw Object.assign(new AxiosError$1("Network Error",AxiosError$1.ERR_NETWORK,e,E,t&&t.response),{cause:t.cause||t});throw AxiosError$1.from(t,t&&t.code,e,E,t&&t.response)}}},seedCache=new Map,getFetch=e=>{let t=e&&e.env||{};const{fetch:r,Request:n,Response:i}=t,o=[n,i,r];let s,a,c=o.length,l=seedCache;for(;c--;)s=o[c],a=l.get(s),void 0===a&&l.set(s,a=c?new Map:factory$2(t)),l=a;return a};getFetch();const knownAdapters={http:httpAdapter,xhr:xhrAdapter,fetch:{get:getFetch}};utils$3.forEach(knownAdapters,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(e){}Object.defineProperty(e,"adapterName",{value:t})}});const renderReason=e=>`- ${e}`,isResolvedHandle=e=>utils$3.isFunction(e)||null===e||!1===e;function getAdapter$1(e,t){e=utils$3.isArray(e)?e:[e];const{length:r}=e;let n,i;const o={};for(let s=0;s<r;s++){let r;if(n=e[s],i=n,!isResolvedHandle(n)&&(i=knownAdapters[(r=String(n)).toLowerCase()],void 0===i))throw new AxiosError$1(`Unknown adapter '${r}'`);if(i&&(utils$3.isFunction(i)||(i=i.get(t))))break;o[r||"#"+s]=i}if(!i){const e=Object.entries(o).map(([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build"));let t=r?e.length>1?"since :\n"+e.map(renderReason).join("\n"):" "+renderReason(e[0]):"as no adapter specified";throw new AxiosError$1("There is no suitable adapter to dispatch the request "+t,"ERR_NOT_SUPPORT")}return i}var adapters={getAdapter:getAdapter$1,adapters:knownAdapters};function throwIfCancellationRequested(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new CanceledError$1(null,e)}function dispatchRequest(e){throwIfCancellationRequested(e),e.headers=AxiosHeaders$1.from(e.headers),e.data=transformData.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return adapters.getAdapter(e.adapter||defaults.adapter,e)(e).then(function(t){return throwIfCancellationRequested(e),t.data=transformData.call(e,e.transformResponse,t),t.headers=AxiosHeaders$1.from(t.headers),t},function(t){return isCancel$1(t)||(throwIfCancellationRequested(e),t&&t.response&&(t.response.data=transformData.call(e,e.transformResponse,t.response),t.response.headers=AxiosHeaders$1.from(t.response.headers))),Promise.reject(t)})}const VERSION$6="1.15.2",validators$1={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{validators$1[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const deprecatedWarnings={};function assertOptions(e,t,r){if("object"!=typeof e)throw new AxiosError$1("options must be an object",AxiosError$1.ERR_BAD_OPTION_VALUE);const n=Object.keys(e);let i=n.length;for(;i-- >0;){const o=n[i],s=Object.prototype.hasOwnProperty.call(t,o)?t[o]:void 0;if(s){const t=e[o],r=void 0===t||s(t,o,e);if(!0!==r)throw new AxiosError$1("option "+o+" must be "+r,AxiosError$1.ERR_BAD_OPTION_VALUE);continue}if(!0!==r)throw new AxiosError$1("Unknown option "+o,AxiosError$1.ERR_BAD_OPTION)}}validators$1.transitional=function(e,t,r){function n(e,t){return"[Axios v"+VERSION$6+"] Transitional option '"+e+"'"+t+(r?". "+r:"")}return(r,i,o)=>{if(!1===e)throw new AxiosError$1(n(i," has been removed"+(t?" in "+t:"")),AxiosError$1.ERR_DEPRECATED);return t&&!deprecatedWarnings[i]&&(deprecatedWarnings[i]=!0,console.warn(n(i," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,i,o)}},validators$1.spelling=function(e){return(t,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};var validator$1={assertOptions:assertOptions,validators:validators$1};const validators=validator$1.validators;let Axios$1=class{constructor(e){this.defaults=e||{},this.interceptors={request:new InterceptorManager,response:new InterceptorManager}}async request(e,t){try{return await this._request(e,t)}catch(e){if(e instanceof Error){let t={};Error.captureStackTrace?Error.captureStackTrace(t):t=new Error;const r=(()=>{if(!t.stack)return"";const e=t.stack.indexOf("\n");return-1===e?"":t.stack.slice(e+1)})();try{if(e.stack){if(r){const t=r.indexOf("\n"),n=-1===t?-1:r.indexOf("\n",t+1),i=-1===n?"":r.slice(n+1);String(e.stack).endsWith(i)||(e.stack+="\n"+r)}}else e.stack=r}catch(e){}}throw e}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=mergeConfig$2(this.defaults,t);const{transitional:r,paramsSerializer:n,headers:i}=t;void 0!==r&&validator$1.assertOptions(r,{silentJSONParsing:validators.transitional(validators.boolean),forcedJSONParsing:validators.transitional(validators.boolean),clarifyTimeoutError:validators.transitional(validators.boolean),legacyInterceptorReqResOrdering:validators.transitional(validators.boolean)},!1),null!=n&&(utils$3.isFunction(n)?t.paramsSerializer={serialize:n}:validator$1.assertOptions(n,{encode:validators.function,serialize:validators.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),validator$1.assertOptions(t,{baseUrl:validators.spelling("baseURL"),withXsrfToken:validators.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let o=i&&utils$3.merge(i.common,i[t.method]);i&&utils$3.forEach(["delete","get","head","post","put","patch","common"],e=>{delete i[e]}),t.headers=AxiosHeaders$1.concat(o,i);const s=[];let a=!0;this.interceptors.request.forEach(function(e){if("function"==typeof e.runWhen&&!1===e.runWhen(t))return;a=a&&e.synchronous;const r=t.transitional||transitionalDefaults;r&&r.legacyInterceptorReqResOrdering?s.unshift(e.fulfilled,e.rejected):s.push(e.fulfilled,e.rejected)});const c=[];let l;this.interceptors.response.forEach(function(e){c.push(e.fulfilled,e.rejected)});let u,d=0;if(!a){const e=[dispatchRequest.bind(this),void 0];for(e.unshift(...s),e.push(...c),u=e.length,l=Promise.resolve(t);d<u;)l=l.then(e[d++],e[d++]);return l}u=s.length;let h=t;for(;d<u;){const e=s[d++],t=s[d++];try{h=e(h)}catch(e){t.call(this,e);break}}try{l=dispatchRequest.call(this,h)}catch(e){return Promise.reject(e)}for(d=0,u=c.length;d<u;)l=l.then(c[d++],c[d++]);return l}getUri(e){return buildURL(buildFullPath((e=mergeConfig$2(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}};utils$3.forEach(["delete","get","head","options"],function(e){Axios$1.prototype[e]=function(t,r){return this.request(mergeConfig$2(r||{},{method:e,url:t,data:(r||{}).data}))}}),utils$3.forEach(["post","put","patch"],function(e){function t(t){return function(r,n,i){return this.request(mergeConfig$2(i||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:r,data:n}))}}Axios$1.prototype[e]=t(),Axios$1.prototype[e+"Form"]=t(!0)});let CancelToken$1=class e{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise(function(e){t=e});const r=this;this.promise.then(e=>{if(!r._listeners)return;let t=r._listeners.length;for(;t-- >0;)r._listeners[t](e);r._listeners=null}),this.promise.then=e=>{let t;const n=new Promise(e=>{r.subscribe(e),t=e}).then(e);return n.cancel=function(){r.unsubscribe(t)},n},e(function(e,n,i){r.reason||(r.reason=new CanceledError$1(e,n,i),t(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let t;const r=new e(function(e){t=e});return{token:r,cancel:t}}};function spread$1(e){return function(t){return e.apply(null,t)}}function isAxiosError$1(e){return utils$3.isObject(e)&&!0===e.isAxiosError}const HttpStatusCode$1={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};function createInstance(e){const t=new Axios$1(e),r=bind(Axios$1.prototype.request,t);return utils$3.extend(r,Axios$1.prototype,t,{allOwnKeys:!0}),utils$3.extend(r,t,null,{allOwnKeys:!0}),r.create=function(t){return createInstance(mergeConfig$2(e,t))},r}Object.entries(HttpStatusCode$1).forEach(([e,t])=>{HttpStatusCode$1[t]=e});const axios=createInstance(defaults);axios.Axios=Axios$1,axios.CanceledError=CanceledError$1,axios.CancelToken=CancelToken$1,axios.isCancel=isCancel$1,axios.VERSION=VERSION$6,axios.toFormData=toFormData$1,axios.AxiosError=AxiosError$1,axios.Cancel=axios.CanceledError,axios.all=function(e){return Promise.all(e)},axios.spread=spread$1,axios.isAxiosError=isAxiosError$1,axios.mergeConfig=mergeConfig$2,axios.AxiosHeaders=AxiosHeaders$1,axios.formToJSON=e=>formDataToJSON(utils$3.isHTMLForm(e)?new FormData(e):e),axios.getAdapter=adapters.getAdapter,axios.HttpStatusCode=HttpStatusCode$1,axios.default=axios;const{Axios:Axios,AxiosError:AxiosError,CanceledError:CanceledError,isCancel:isCancel,CancelToken:CancelToken,VERSION:VERSION$5,all:all,Cancel:Cancel,isAxiosError:isAxiosError,spread:spread,toFormData:toFormData,AxiosHeaders:AxiosHeaders,HttpStatusCode:HttpStatusCode,formToJSON:formToJSON,getAdapter:getAdapter,mergeConfig:mergeConfig$1}=axios;class InvalidTokenError extends Error{}function b64DecodeUnicode(e){return decodeURIComponent(atob(e).replace(/(.)/g,(e,t)=>{let r=t.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r}))}function base64UrlDecode(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return b64DecodeUnicode(t)}catch(e){return atob(t)}}function jwtDecode(e,t){if("string"!=typeof e)throw new InvalidTokenError("Invalid token specified: must be a string");t||(t={});const r=!0===t.header?0:1,n=e.split(".")[r];if("string"!=typeof n)throw new InvalidTokenError(`Invalid token specified: missing part #${r+1}`);let i;try{i=base64UrlDecode(n)}catch(e){throw new InvalidTokenError(`Invalid token specified: invalid base64 for part #${r+1} (${e.message})`)}try{return JSON.parse(i)}catch(e){throw new InvalidTokenError(`Invalid token specified: invalid json for part #${r+1} (${e.message})`)}}InvalidTokenError.prototype.name="InvalidTokenError";var browser="object"==typeof self?self.FormData:window.FormData,FormData$1=getDefaultExportFromCjs$2(browser);function $constructor(e,t,r){function n(r,n){if(r._zod||Object.defineProperty(r,"_zod",{value:{def:n,constr:s,traits:new Set},enumerable:!1}),r._zod.traits.has(e))return;r._zod.traits.add(e),t(r,n);const i=s.prototype,o=Object.keys(i);for(let e=0;e<o.length;e++){const t=o[e];t in r||(r[t]=i[t].bind(r))}}const i=r?.Parent??Object;class o extends i{}function s(e){var t;const i=r?.Parent?new o:this;n(i,e),(t=i._zod).deferred??(t.deferred=[]);for(const e of i._zod.deferred)e();return i}return Object.defineProperty(o,"name",{value:e}),Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:t=>!!(r?.Parent&&t instanceof r.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}class $ZodAsyncError extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const globalConfig={};function config(e){return globalConfig}function jsonStringifyReplacer(e,t){return"bigint"==typeof t?t.toString():t}function cached(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function nullish(e){return null==e}function cleanRegex(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}const EVALUATING=Symbol("evaluating");function defineLazy(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==EVALUATING)return void 0===n&&(n=EVALUATING,n=r()),n},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}const captureStackTrace="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function isObject$2(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function clone(e,t,r){const n=new e._zod.constr(t??e._zod.def);return t&&!r?.parent||(n._zod.parent=e),n}function normalizeParams(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(void 0!==t?.error)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}function optionalKeys(e){return Object.keys(e).filter(t=>"optional"===e[t]._zod.optin&&"optional"===e[t]._zod.optout)}function aborted(e,t=0){if(!0===e.aborted)return!0;for(let r=t;r<e.issues.length;r++)if(!0!==e.issues[r]?.continue)return!0;return!1}function prefixIssues(e,t){return t.map(t=>{var r;return(r=t).path??(r.path=[]),t.path.unshift(e),t})}function unwrapMessage(e){return"string"==typeof e?e:e?.message}function finalizeIssue(e,t,r){const n={...e,path:e.path??[]};if(!e.message){const i=unwrapMessage(e.inst?._zod.def?.error?.(e))??unwrapMessage(t?.error?.(e))??unwrapMessage(r.customError?.(e))??unwrapMessage(r.localeError?.(e))??"Invalid input";n.message=i}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function getLengthableOrigin(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}const initializer=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,jsonStringifyReplacer,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},$ZodError=$constructor("$ZodError",initializer),$ZodRealError=$constructor("$ZodError",initializer,{Parent:Error}),_parse=e=>(t,r,n,i)=>{const o=n?Object.assign(n,{async:!1}):{async:!1},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new $ZodAsyncError;if(s.issues.length){const t=new(i?.Err??e)(s.issues.map(e=>finalizeIssue(e,o,config())));throw captureStackTrace(t,i?.callee),t}return s.value},parse=_parse($ZodRealError),_parseAsync=e=>async(t,r,n,i)=>{const o=n?Object.assign(n,{async:!0}):{async:!0};let s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){const t=new(i?.Err??e)(s.issues.map(e=>finalizeIssue(e,o,config())));throw captureStackTrace(t,i?.callee),t}return s.value},parseAsync=_parseAsync($ZodRealError),_safeParse=e=>(t,r,n)=>{const i=n?{...n,async:!1}:{async:!1},o=t._zod.run({value:r,issues:[]},i);if(o instanceof Promise)throw new $ZodAsyncError;return o.issues.length?{success:!1,error:new(e??$ZodError)(o.issues.map(e=>finalizeIssue(e,i,config())))}:{success:!0,data:o.value}},safeParse=_safeParse($ZodRealError),_safeParseAsync=e=>async(t,r,n)=>{const i=n?Object.assign(n,{async:!0}):{async:!0};let o=t._zod.run({value:r,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(e=>finalizeIssue(e,i,config())))}:{success:!0,data:o.value}},safeParseAsync=_safeParseAsync($ZodRealError),dateSource="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",date$1=new RegExp(`^${dateSource}$`);function timeSource(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function datetime$1(e){const t=timeSource({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const n=`${t}(?:${r.join("|")})`;return new RegExp(`^${dateSource}T(?:${n})$`)}const string$1=e=>new RegExp(`^${e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*"}$`),number$1=/^-?\d+(?:\.\d+)?/,boolean$1=/^(?:true|false)$/i,_null$2=/^null$/i,_undefined$2=/^undefined$/i,$ZodCheck=$constructor("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),$ZodCheckMinLength=$constructor("$ZodCheckMinLength",(e,t)=>{var r;$ZodCheck.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!nullish(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const r=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const n=r.value;if(n.length>=t.minimum)return;const i=getLengthableOrigin(n);r.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),$ZodCheckStringFormat=$constructor("$ZodCheckStringFormat",(e,t)=>{var r,n;$ZodCheck.init(e,t),e._zod.onattach.push(e=>{const r=e._zod.bag;r.format=t.format,t.pattern&&(r.patterns??(r.patterns=new Set),r.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),version={major:4,minor:1,patch:13},$ZodType=$constructor("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=version;const n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(const t of n)for(const r of t._zod.onattach)r(e);if(0===n.length)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const t=(e,t,r)=>{let n,i=aborted(e);for(const o of t){if(o._zod.def.when){if(!o._zod.def.when(e))continue}else if(i)continue;const t=e.issues.length,s=o._zod.check(e);if(s instanceof Promise&&!1===r?.async)throw new $ZodAsyncError;if(n||s instanceof Promise)n=(n??Promise.resolve()).then(async()=>{await s;e.issues.length!==t&&(i||(i=aborted(e,t)))});else{if(e.issues.length===t)continue;i||(i=aborted(e,t))}}return n?n.then(()=>e):e},r=(r,i,o)=>{if(aborted(r))return r.aborted=!0,r;const s=t(i,n,o);if(s instanceof Promise){if(!1===o.async)throw new $ZodAsyncError;return s.then(t=>e._zod.parse(t,o))}return e._zod.parse(s,o)};e._zod.run=(i,o)=>{if(o.skipChecks)return e._zod.parse(i,o);if("backward"===o.direction){const t=e._zod.parse({value:i.value,issues:[]},{...o,skipChecks:!0});return t instanceof Promise?t.then(e=>r(e,i,o)):r(t,i,o)}const s=e._zod.parse(i,o);if(s instanceof Promise){if(!1===o.async)throw new $ZodAsyncError;return s.then(e=>t(e,n,o))}return t(s,n,o)}}e["~standard"]={validate:t=>{try{const r=safeParse(e,t);return r.success?{value:r.data}:{issues:r.error?.issues}}catch(r){return safeParseAsync(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}}),$ZodString=$constructor("$ZodString",(e,t)=>{$ZodType.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??string$1(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch(n){}return"string"==typeof r.value||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),$ZodStringFormat=$constructor("$ZodStringFormat",(e,t)=>{$ZodCheckStringFormat.init(e,t),$ZodString.init(e,t)}),$ZodISODateTime=$constructor("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=datetime$1(t)),$ZodStringFormat.init(e,t)}),$ZodISODate=$constructor("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=date$1),$ZodStringFormat.init(e,t)}),$ZodNumber=$constructor("$ZodNumber",(e,t)=>{$ZodType.init(e,t),e._zod.pattern=e._zod.bag.pattern??number$1,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch(e){}const i=r.value;if("number"==typeof i&&!Number.isNaN(i)&&Number.isFinite(i))return r;const o="number"==typeof i?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...o?{received:o}:{}}),r}}),$ZodBoolean=$constructor("$ZodBoolean",(e,t)=>{$ZodType.init(e,t),e._zod.pattern=boolean$1,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Boolean(r.value)}catch(e){}const i=r.value;return"boolean"==typeof i||r.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),r}}),$ZodUndefined=$constructor("$ZodUndefined",(e,t)=>{$ZodType.init(e,t),e._zod.pattern=_undefined$2,e._zod.values=new Set([void 0]),e._zod.optin="optional",e._zod.optout="optional",e._zod.parse=(t,r)=>{const n=t.value;return void 0===n||t.issues.push({expected:"undefined",code:"invalid_type",input:n,inst:e}),t}}),$ZodNull=$constructor("$ZodNull",(e,t)=>{$ZodType.init(e,t),e._zod.pattern=_null$2,e._zod.values=new Set([null]),e._zod.parse=(t,r)=>{const n=t.value;return null===n||t.issues.push({expected:"null",code:"invalid_type",input:n,inst:e}),t}}),$ZodUnknown=$constructor("$ZodUnknown",(e,t)=>{$ZodType.init(e,t),e._zod.parse=e=>e});function handleArrayResult(e,t,r){e.issues.length&&t.issues.push(...prefixIssues(r,e.issues)),t.value[r]=e.value}const $ZodArray=$constructor("$ZodArray",(e,t)=>{$ZodType.init(e,t),e._zod.parse=(r,n)=>{const i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),r;r.value=Array(i.length);const o=[];for(let e=0;e<i.length;e++){const s=i[e],a=t.element._zod.run({value:s,issues:[]},n);a instanceof Promise?o.push(a.then(t=>handleArrayResult(t,r,e))):handleArrayResult(a,r,e)}return o.length?Promise.all(o).then(()=>r):r}});function handlePropertyResult(e,t,r,n){e.issues.length&&t.issues.push(...prefixIssues(r,e.issues)),void 0===e.value?r in n&&(t.value[r]=void 0):t.value[r]=e.value}function normalizeDef(e){const t=Object.keys(e.shape);for(const r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const r=optionalKeys(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function handleCatchall(e,t,r,n,i,o){const s=[],a=i.keySet,c=i.catchall._zod,l=c.def.type;for(const i in t){if(a.has(i))continue;if("never"===l){s.push(i);continue}const o=c.run({value:t[i],issues:[]},n);o instanceof Promise?e.push(o.then(e=>handlePropertyResult(e,r,i,t))):handlePropertyResult(o,r,i,t)}return s.length&&r.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:o}),e.length?Promise.all(e).then(()=>r):r}const $ZodObject=$constructor("$ZodObject",(e,t)=>{$ZodType.init(e,t);const r=Object.getOwnPropertyDescriptor(t,"shape");if(!r?.get){const e=t.shape;Object.defineProperty(t,"shape",{get:()=>{const r={...e};return Object.defineProperty(t,"shape",{value:r}),r}})}const n=cached(()=>normalizeDef(t));defineLazy(e._zod,"propValues",()=>{const e=t.shape,r={};for(const t in e){const n=e[t]._zod;if(n.values){r[t]??(r[t]=new Set);for(const e of n.values)r[t].add(e)}}return r});const i=isObject$2,o=t.catchall;let s;e._zod.parse=(t,r)=>{s??(s=n.value);const a=t.value;if(!i(a))return t.issues.push({expected:"object",code:"invalid_type",input:a,inst:e}),t;t.value={};const c=[],l=s.shape;for(const e of s.keys){const n=l[e]._zod.run({value:a[e],issues:[]},r);n instanceof Promise?c.push(n.then(r=>handlePropertyResult(r,t,e,a))):handlePropertyResult(n,t,e,a)}return o?handleCatchall(c,a,t,r,n.value,e):c.length?Promise.all(c).then(()=>t):t}});function handleUnionResults(e,t,r,n){for(const r of e)if(0===r.issues.length)return t.value=r.value,t;const i=e.filter(e=>!aborted(e));return 1===i.length?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(e=>e.issues.map(e=>finalizeIssue(e,n,config())))}),t)}const $ZodUnion=$constructor("$ZodUnion",(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),defineLazy(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),defineLazy(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),defineLazy(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){const e=t.options.map(e=>e._zod.pattern);return new RegExp(`^(${e.map(e=>cleanRegex(e.source)).join("|")})$`)}});const r=1===t.options.length,n=t.options[0]._zod.run;e._zod.parse=(i,o)=>{if(r)return n(i,o);let s=!1;const a=[];for(const e of t.options){const t=e._zod.run({value:i.value,issues:[]},o);if(t instanceof Promise)a.push(t),s=!0;else{if(0===t.issues.length)return t;a.push(t)}}return s?Promise.all(a).then(t=>handleUnionResults(t,i,e,o)):handleUnionResults(a,i,e,o)}});function handleOptionalResult(e,t){return e.issues.length&&void 0===t?{issues:[],value:void 0}:e}const $ZodOptional=$constructor("$ZodOptional",(e,t)=>{$ZodType.init(e,t),e._zod.optin="optional",e._zod.optout="optional",defineLazy(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),defineLazy(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${cleanRegex(e.source)})?$`):void 0}),e._zod.parse=(e,r)=>{if("optional"===t.innerType._zod.optin){const n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(t=>handleOptionalResult(t,e.value)):handleOptionalResult(n,e.value)}return void 0===e.value?e:t.innerType._zod.run(e,r)}});var _a;class $ZodRegistry{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){const r=t[0];if(this._map.set(e,r),r&&"object"==typeof r&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const r={...this.get(t)??{}};delete r.id;const n={...r,...this._map.get(e)};return Object.keys(n).length?n:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function registry(){return new $ZodRegistry}function _string(e,t){return new e({type:"string",...normalizeParams(t)})}function _isoDateTime(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...normalizeParams(t)})}function _isoDate(e,t){return new e({type:"string",format:"date",check:"string_format",...normalizeParams(t)})}function _number(e,t){return new e({type:"number",checks:[],...normalizeParams(t)})}function _boolean(e,t){return new e({type:"boolean",...normalizeParams(t)})}function _undefined$1(e,t){return new e({type:"undefined",...normalizeParams(t)})}function _null$1(e,t){return new e({type:"null",...normalizeParams(t)})}function _unknown(e){return new e({type:"unknown"})}function _minLength(e,t){return new $ZodCheckMinLength({check:"min_length",...normalizeParams(t),minimum:e})}(_a=globalThis).__zod_globalRegistry??(_a.__zod_globalRegistry=registry());const ZodMiniType=$constructor("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");$ZodType.init(e,t),e.def=t,e.type=t.type,e.parse=(t,r)=>parse(e,t,r,{callee:e.parse}),e.safeParse=(t,r)=>safeParse(e,t,r),e.parseAsync=async(t,r)=>parseAsync(e,t,r,{callee:e.parseAsync}),e.safeParseAsync=async(t,r)=>safeParseAsync(e,t,r),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),e.clone=(t,r)=>clone(e,t,r),e.brand=()=>e,e.register=(t,r)=>(t.add(e,r),e)}),ZodMiniString=$constructor("ZodMiniString",(e,t)=>{$ZodString.init(e,t),ZodMiniType.init(e,t)});function string(e){return _string(ZodMiniString,e)}const ZodMiniStringFormat=$constructor("ZodMiniStringFormat",(e,t)=>{$ZodStringFormat.init(e,t),ZodMiniString.init(e,t)}),ZodMiniNumber=$constructor("ZodMiniNumber",(e,t)=>{$ZodNumber.init(e,t),ZodMiniType.init(e,t)});function number(e){return _number(ZodMiniNumber,e)}const ZodMiniBoolean=$constructor("ZodMiniBoolean",(e,t)=>{$ZodBoolean.init(e,t),ZodMiniType.init(e,t)});function boolean(e){return _boolean(ZodMiniBoolean,e)}const ZodMiniUndefined=$constructor("ZodMiniUndefined",(e,t)=>{$ZodUndefined.init(e,t),ZodMiniType.init(e,t)});function _undefined(e){return _undefined$1(ZodMiniUndefined,e)}const ZodMiniNull=$constructor("ZodMiniNull",(e,t)=>{$ZodNull.init(e,t),ZodMiniType.init(e,t)});function _null(e){return _null$1(ZodMiniNull,e)}const ZodMiniUnknown=$constructor("ZodMiniUnknown",(e,t)=>{$ZodUnknown.init(e,t),ZodMiniType.init(e,t)});function unknown(){return _unknown(ZodMiniUnknown)}const ZodMiniArray=$constructor("ZodMiniArray",(e,t)=>{$ZodArray.init(e,t),ZodMiniType.init(e,t)});function array(e,t){return new ZodMiniArray({type:"array",element:e,...normalizeParams(t)})}const ZodMiniObject=$constructor("ZodMiniObject",(e,t)=>{$ZodObject.init(e,t),ZodMiniType.init(e,t),defineLazy(e,"shape",()=>t.shape)});function looseObject(e,t){return new ZodMiniObject({type:"object",shape:e,catchall:unknown(),...normalizeParams(t)})}const ZodMiniUnion=$constructor("ZodMiniUnion",(e,t)=>{$ZodUnion.init(e,t),ZodMiniType.init(e,t)});function union(e,t){return new ZodMiniUnion({type:"union",options:e,...normalizeParams(t)})}const ZodMiniOptional=$constructor("ZodMiniOptional",(e,t)=>{$ZodOptional.init(e,t),ZodMiniType.init(e,t)});function optional(e){return new ZodMiniOptional({type:"optional",innerType:e})}const ZodMiniISODateTime=$constructor("ZodMiniISODateTime",(e,t)=>{$ZodISODateTime.init(e,t),ZodMiniStringFormat.init(e,t)});function datetime(e){return _isoDateTime(ZodMiniISODateTime,e)}const ZodMiniISODate=$constructor("ZodMiniISODate",(e,t)=>{$ZodISODate.init(e,t),ZodMiniStringFormat.init(e,t)});function date(e){return _isoDate(ZodMiniISODate,e)}var clientCapabilities=[{capability:"ADMIN_API_V2_APP_ADD",introducedInVersion:"1.5.0"},{capability:"ADMIN_API_V2_APP_ADD_OR_UPDATE",introducedInVersion:"1.5.0"},{capability:"ADMIN_API_V2_APP_UPDATE",introducedInVersion:"1.5.0"},{capability:"ADMIN_API_V2_LAYOUT_ADD",introducedInVersion:"1.5.0"},{capability:"ADMIN_API_V2_LAYOUT_ADD_OR_UPDATE",introducedInVersion:"1.5.0"},{capability:"ADMIN_API_V2_LAYOUT_UPDATE",introducedInVersion:"1.5.0"},{capability:"METRICS_ENDPOINTS_DB_CONNECTIVITY",introducedInVersion:"1.7.0"},{capability:"API_V2_SERVER_INFO_ENHANCED",introducedInVersion:"2.0.0"},{capability:"HTTP_TEST",introducedInVersion:"2.0.0"}],clientCapabilitiesByName=new Map;for(const e of clientCapabilities)clientCapabilitiesByName.set(e.capability,e);var BaseAPI=class{constructor(e){this.options=e,this.setOptions(e)}_responseSuccessCallback;_responseErrorCallback;_errorsInterceptorsId;_headersInterceptorId;_serverInfoWrapper={initialized:!1};axiosInstance;setOptions(e){if(!e.auth)throw new Error("please provide auth info");this.options=e,this._errorsInterceptorsId&&this.axiosInstance?.interceptors?.response?.eject(this._errorsInterceptorsId),this._headersInterceptorId&&this.axiosInstance?.interceptors?.request?.eject(this._headersInterceptorId);const t=this.getBaseHeaders(e);this.axiosInstance=axios.create({transformResponse:e.transformResponse,baseURL:e.baseUrl,headers:t,timeout:this.options.requestTimeout,withCredentials:e?.auth?.includeCredentials,validateStatus:this.defaultIsStatusCodeValid,maxContentLength:1/0,maxBodyLength:1/0}),this._errorsInterceptorsId=this.axiosInstance?.interceptors?.response?.use(e=>{try{this._responseSuccessCallback?.(e)}catch{}return e},e=>{try{this._responseErrorCallback?.(e)}catch{}return Promise.reject(e)}),this._headersInterceptorId=this.axiosInstance?.interceptors?.request?.use(async e=>{const t=this.getBaseHeaders(this.options);for(const[r,n]of Object.entries(t))e.headers.set(r,n);if(this.options.getHeaders){const t=await this.options.getHeaders({...e,method:e.method,url:e.url,body:e.data})??{};for(const[r,n]of Object.entries(t))e.headers.set(r,n)}return e},e=>Promise.reject(e))}async whoAmI(){return(await this.axiosInstance.get("/whoami")).data}onResponseSuccessCallback(e){this._responseSuccessCallback=e}onResponseErrorCallback(e){this._responseErrorCallback=e}async initialize(){try{const e=await this.axiosInstance.get("/v2/server/info");this.initializeServerInfo(e.data)}catch(e){if(404===(e?.response?.status??e?.status))return console.warn('Warning: The "GET /v2/server/info" endpoint returned a status code of 404. This means that the io.Manager server is version is < 1.5.0. Proceeding with an empty set of capabilities.'),void this.initializeServerInfo({version:"< 1.5.0",capabilities:[],licenseInfo:{licenseSupported:!1},base:void 0,machine:void 0,start:void 0});throw e}}get serverInfo(){return this._serverInfoWrapper.initialized||this.throwNotInitialized(),this._serverInfoWrapper}hasCapability(e){return this._serverInfoWrapper.initialized||this.throwNotInitialized(),this._serverInfoWrapper.capabilitiesByName.has(e)}async unloadClient(e,t){if(!e||!t)return;const r=new Headers({...this.getBaseHeaders(this.options),...await(this.options.getHeaders?.({method:"POST",url:`${this.options.baseUrl}/user/goodbye`}))}),n=new Request(`${this.options.baseUrl}/user/goodbye`,{method:"POST",headers:r,mode:"cors",cache:"default",keepalive:!0,body:JSON.stringify({session:e})});window.fetch(n)}getHeaders(e){return this.getBaseHeaders(e)}getBaseHeaders(e){const t={};if(e.auth?.username&&(t.user=e.auth.username),(e.auth?.basic?.username||e.auth?.basic?.password)&&(t.Authorization=`Basic ${this.toBase64(`${e.auth.basic.username}:${e.auth.basic.password}`)}`),e.auth?.token?.bearer&&(t.Authorization=`Bearer ${e.auth.token.bearer}`),e.headers)for(const r of Object.keys(e.headers))t[r]=e.headers[r];return t}initializeServerInfo(e){const t=new Map;for(const r of e.capabilities)t.set(r.capability,r);if("2.0.0"===e.version){const e={capability:"HTTP_TEST",introducedInVersion:"2.0.0"};t.set(e.capability,e)}Object.assign(this._serverInfoWrapper,{initialized:!0,capabilitiesByName:t,...e})}ensureCapability(e){if(this.options.disableCapabilityCheck)return;this._serverInfoWrapper.initialized||this.throwNotInitialized();if(!this._serverInfoWrapper.capabilitiesByName.get(e)){const t=clientCapabilitiesByName.get(e);if(!t)throw new Error(`Client capability "${e}" not found.`);throw new Error(`io.Manager server version "${this.serverInfo.version}" doesn't support capability "${e}" which was introduced in version "${t.introducedInVersion}".`)}}throwNotInitialized(){throw new Error("You need to call initialize() first, before calling this API.")}toBase64(e){return"undefined"!=typeof window?window.btoa(e):Buffer.from(e,"utf-8").toString("base64")}defaultIsStatusCodeValid(e){return e<400}};function customEncodeURIComponent(e){return decodeURIComponent(e)!==e?e:encodeURIComponent(e)}var PromiseWrapper=class{static delay(e){return new Promise(t=>setTimeout(t,e))}resolve=()=>{};reject=()=>{};promise;rejected=!1;resolved=!1;get ended(){return this.rejected||this.resolved}constructor(){this.promise=new Promise((e,t)=>{this.resolve=t=>{this.resolved=!0,e(t)},this.reject=e=>{this.rejected=!0,t(e)}})}};function debugSanitizeValue(e){switch(typeof e){case"number":case"bigint":case"boolean":return e;case"string":return`Sanitized(type=string, length=${e.length})`;case"function":return`Sanitized(type=function, name=${e.name||"anonymous"})`;case"object":return null===e?"Sanitized(type=object, value=null)":e instanceof Date||e instanceof RegExp?e:`Sanitized(type=object, propertyCount=${Object.keys(e).length})`;default:return`Sanitized(type=${typeof e})`}}var RequestLogger=class{constructor(e,t,r,n){this.logger=e,this.logLevel=t,this.disableLogSanitization=r,this.logHTTPHeaders=n}shouldLogRequest(){return this.logger.isLevelEnabled(this.logLevel)}logRequest(e){if(!this.shouldLogRequest())return;const t=e();let r=`Calling endpoint "${t.endpointName}" (${t.operationName})`,n=!1;if(t.pathParameters&&Object.keys(t.pathParameters).length>0){const e=structuredClone(t.pathParameters);n&&(r+=" and"),r+=` with path parameters: ${JSON.stringify(e)}`,n=!0}if(t.queryParameters&&Object.keys(t.queryParameters).length>0){const e=structuredClone(t.queryParameters);n&&(r+=" and"),r+=` with query parameters: ${JSON.stringify(e)}`,n=!0}if(t.requestBody){const e=structuredClone(t.requestBody);if(!this.disableLogSanitization)for(const r of t.sanitizeRequestBodyProperties??[]){const t=e[r];t&&(e[r]=debugSanitizeValue(t))}n&&(r+=" and"),r+=` with request body: ${JSON.stringify(e)}`,n=!0}this.logger.log(this.logLevel,r)}logResponse(e){if(!this.shouldLogRequest())return;const t=e();let r=`Endpoint "${t.endpointName}" (${t.operationName}) returned status code of ${t.response.statusCode} and response body`;if("string"==typeof t.response.body)r+=" (string): ",r+=t.response.body;else if("boolean"==typeof t.response.body)r+=" (boolean): ",r+=t.response.body.toString();else if("number"==typeof t.response.body)r+=" (number): ",r+=t.response.body.toString();else if(void 0===t.response.body)r+=" is undefined";else if(null===t.response.body)r+=" is null";else if("object"==typeof t.response.body){const e=structuredClone(t.response.body);if(!this.disableLogSanitization)for(const r of t.sanitizeResponseBodyProperties??[]){const t=e[r];t&&(e[r]=debugSanitizeValue(t))}r+=" (object): ",r+=JSON.stringify(e)}else r+=" is something strange";this.logger.log(this.logLevel,r)}logRequestHeaders(e){if(!this.shouldLogRequest())return;if(!this.logHTTPHeaders)return;if(!this.disableLogSanitization)return;const t=e();this.logger.log(this.logLevel,`Using request headers: ${JSON.stringify(t)}`)}logResponseHeaders(e){if(!this.shouldLogRequest())return;if(!this.logHTTPHeaders)return;if(!this.disableLogSanitization)return;const t=e();this.logger.log(this.logLevel,`Received response headers: ${JSON.stringify(t)}`)}};function extendedOptional(e){return optional(union([e,_null(),_undefined()]))}function anyIsoDate(){return union([datetime({offset:!0,local:!0}),date()])}var zodHelpers={extendedOptional:extendedOptional,anyIsoDate:anyIsoDate};looseObject({name:string(),base:string(),version:string(),start:zodHelpers.anyIsoDate(),status:string()}),looseObject({id:string(),email:zodHelpers.extendedOptional(string()),groups:array(string()),apps:array(string())});var App2=looseObject({definition:looseObject({}),name:string(),disabled:boolean(),public:boolean(),accessList:zodHelpers.extendedOptional(array(string())),createdBy:string(),createdOn:zodHelpers.anyIsoDate(),lastModifiedBy:zodHelpers.extendedOptional(string()),lastModifiedOn:zodHelpers.extendedOptional(zodHelpers.anyIsoDate())});looseObject({items:array(App2),total:number()}),looseObject({items:array(App2),total:number()});var AddOrUpdateAppRequest2=looseObject({definition:looseObject({}),name:string(),disabled:boolean(),public:boolean(),accessList:zodHelpers.extendedOptional(array(string()))});looseObject({apps:array(AddOrUpdateAppRequest2)}),looseObject({application:App2}),looseObject({definition:looseObject({}),name:string(),disabled:boolean(),public:boolean(),accessList:zodHelpers.extendedOptional(array(string()))}),looseObject({definition:looseObject({}),name:string(),disabled:boolean(),public:boolean(),accessList:zodHelpers.extendedOptional(array(string()))});var Layout2=looseObject({definition:string(),id:string(),type:string(),name:string(),owner:zodHelpers.extendedOptional(string()),public:boolean(),disabled:boolean(),accessList:zodHelpers.extendedOptional(array(string())),createdBy:string(),createdOn:zodHelpers.anyIsoDate(),lastModifiedBy:zodHelpers.extendedOptional(string()),lastModifiedOn:zodHelpers.extendedOptional(zodHelpers.anyIsoDate()),default:zodHelpers.extendedOptional(boolean())});looseObject({items:array(Layout2),total:number()}),looseObject({definition:string(),id:zodHelpers.extendedOptional(string()),type:string(),name:string(),owner:zodHelpers.extendedOptional(string()),public:boolean(),disabled:boolean(),accessList:zodHelpers.extendedOptional(array(string())),default:zodHelpers.extendedOptional(boolean())}),looseObject({layout:Layout2}),looseObject({definition:string(),type:string(),name:string(),owner:zodHelpers.extendedOptional(string()),public:boolean(),disabled:boolean(),accessList:zodHelpers.extendedOptional(array(string())),default:zodHelpers.extendedOptional(boolean())}),looseObject({definition:string(),id:zodHelpers.extendedOptional(string()),type:string(),name:string(),owner:zodHelpers.extendedOptional(string()),public:boolean(),disabled:boolean(),accessList:zodHelpers.extendedOptional(array(string())),default:zodHelpers.extendedOptional(boolean())});var Group=looseObject({name:string()});looseObject({items:array(Group),total:number()}),looseObject({canGetUserGroups:boolean(),canGetAllGroups:boolean(),canAddGroup:boolean(),canRemoveGroup:boolean(),canAddUserToGroup:boolean(),canRemoveUserFromGroup:boolean()}),looseObject({name:string()});var RefreshRequestLastDataInfoOthers=looseObject({groups:zodHelpers.extendedOptional(array(string()))}),RefreshRequestLastDataInfo=looseObject({checksum:zodHelpers.extendedOptional(string()),last:number(),other:zodHelpers.extendedOptional(RefreshRequestLastDataInfoOthers)}),RefreshRequestCategory=looseObject({include:boolean(),latestDataInfo:zodHelpers.extendedOptional(RefreshRequestLastDataInfo)}),RefreshDataRequest=looseObject({applications:zodHelpers.extendedOptional(RefreshRequestCategory),layouts:zodHelpers.extendedOptional(RefreshRequestCategory),commands:zodHelpers.extendedOptional(RefreshRequestCategory),configs:zodHelpers.extendedOptional(RefreshRequestCategory)}),ApplicationRefreshResponseData=looseObject({data:zodHelpers.extendedOptional(array(looseObject({}))),hasChanges:boolean(),info:zodHelpers.extendedOptional(RefreshRequestLastDataInfo)}),UserLayoutDefinition=looseObject({definition:string(),id:string(),type:string(),name:string(),owner:zodHelpers.extendedOptional(string()),default:zodHelpers.extendedOptional(boolean())}),LayoutRefreshResponseData=looseObject({hasChanges:boolean(),data:zodHelpers.extendedOptional(array(UserLayoutDefinition)),info:zodHelpers.extendedOptional(RefreshRequestLastDataInfo)}),CommandStatus2=string().check(_minLength(1)),ResultType2=string().check(_minLength(1)),Command2=looseObject({status:CommandStatus2,resultType:zodHelpers.extendedOptional(ResultType2),traceContext:zodHelpers.extendedOptional(looseObject({})),id:string(),user:string(),session:string(),machine:string(),createdBy:string(),createdAt:number(),command:string(),commandParams:zodHelpers.extendedOptional(string()),resultData:zodHelpers.extendedOptional(looseObject({})),resultAt:zodHelpers.extendedOptional(number())}),CommandRefreshResponseData=looseObject({hasChanges:boolean(),data:zodHelpers.extendedOptional(array(Command2)),info:zodHelpers.extendedOptional(RefreshRequestLastDataInfo)}),ConfigRefreshResponseData=looseObject({hasChanges:boolean(),data:zodHelpers.extendedOptional(array(looseObject({}))),info:zodHelpers.extendedOptional(RefreshRequestLastDataInfo)}),RefreshDataResponse=looseObject({applications:zodHelpers.extendedOptional(ApplicationRefreshResponseData),layouts:zodHelpers.extendedOptional(LayoutRefreshResponseData),commands:zodHelpers.extendedOptional(CommandRefreshResponseData),config:zodHelpers.extendedOptional(ConfigRefreshResponseData)});looseObject({session:string(),user:string(),email:zodHelpers.extendedOptional(string()),exp:number(),iat:number()}),looseObject({version:string()});var ConnectBrowserPlatformInfo=looseObject({version:string()});looseObject({platform:ConnectBrowserPlatformInfo});var ConnectBrowserInfo=looseObject({platform:ConnectBrowserPlatformInfo}),ConnectInfo=looseObject({version:string(),core:zodHelpers.extendedOptional(ConnectBrowserInfo),build:string(),region:string(),env:string()}),OSInfo=looseObject({name:zodHelpers.extendedOptional(string()),version:zodHelpers.extendedOptional(string()),arch:zodHelpers.extendedOptional(string())}),Bounds=looseObject({x:zodHelpers.extendedOptional(number()),y:zodHelpers.extendedOptional(number()),width:zodHelpers.extendedOptional(number()),height:zodHelpers.extendedOptional(number())}),Display=looseObject({bounds:zodHelpers.extendedOptional(Bounds),workingArea:zodHelpers.extendedOptional(Bounds),dpi:zodHelpers.extendedOptional(number()),isPrimary:zodHelpers.extendedOptional(boolean()),aspectRatio:zodHelpers.extendedOptional(string()),scaleFactor:zodHelpers.extendedOptional(number())}),BrowserInfo=looseObject({name:string(),version:string(),engine:string()}),MachineInfo=looseObject({user:string(),name:zodHelpers.extendedOptional(string()),os:zodHelpers.extendedOptional(OSInfo),displays:zodHelpers.extendedOptional(array(Display)),browser:zodHelpers.extendedOptional(BrowserInfo)}),HelloRequest=looseObject({glue:ConnectInfo,machine:zodHelpers.extendedOptional(MachineInfo),initialDataRequest:zodHelpers.extendedOptional(RefreshDataRequest),includeServerInfo:zodHelpers.extendedOptional(boolean())}),ServerCapability2=string().check(_minLength(1)),ServerCapabilityWithMetadata2=looseObject({capability:ServerCapability2,introducedInVersion:string()}),LicenseType2=string().check(_minLength(1)),LicenseOrganization=looseObject({displayName:string(),identifier:string()}),LicensePayload=looseObject({type:LicenseType2,licensee:string(),expiration:number(),organization:LicenseOrganization,email:string(),issuedBy:string()}),LicenseInfo2=looseObject({licensePayload:LicensePayload,isExpired:boolean(),licenseSupported:boolean()}),ServerInfoResponse2=looseObject({capabilities:array(ServerCapabilityWithMetadata2),version:string(),licenseInfo:zodHelpers.extendedOptional(LicenseInfo2),base:zodHelpers.extendedOptional(string()),start:zodHelpers.extendedOptional(zodHelpers.anyIsoDate()),machine:zodHelpers.extendedOptional(string()),inactiveSessionTimeoutInSeconds:zodHelpers.extendedOptional(number())}),HelloResponse=looseObject({token:string(),data:RefreshDataResponse,serverInfo:zodHelpers.extendedOptional(ServerInfoResponse2),sessionNotPersisted:zodHelpers.extendedOptional(boolean())}),GoodbyeRequest=looseObject({session:string()}),RefreshTokenRequest=looseObject({token:string()}),RefreshTokenResponse=looseObject({token:string()}),SaveUserLayoutRequest=looseObject({definition:string(),id:zodHelpers.extendedOptional(string()),type:string(),name:string(),default:zodHelpers.extendedOptional(boolean())}),RenameLayoutRequest=looseObject({newName:string()}),SetDefaultLayoutRequest=looseObject({id:zodHelpers.extendedOptional(string())}),AddCommandResultRequest=looseObject({result:looseObject({})}),AddCommandFileResultRequest=looseObject({fileName:string(),contents:string()});looseObject({result:zodHelpers.extendedOptional(looseObject({}))});var AppPreferences=looseObject({data:looseObject({}),id:string(),app:string(),user:string(),lastUpdate:zodHelpers.anyIsoDate()}),AddOrUpdatePrefsRequest=looseObject({data:looseObject({}),merge:boolean(),id:zodHelpers.extendedOptional(string()),app:zodHelpers.extendedOptional(string()),user:zodHelpers.extendedOptional(string())});looseObject({attachment:string(),description:string()});var Feedback=looseObject({id:string(),date:zodHelpers.anyIsoDate(),user:string(),session:string(),description:string(),attachment:string(),reviewed:boolean(),comment:zodHelpers.extendedOptional(string())}),HttpTestRequest=looseObject({}),HttpTestResponse=looseObject({requestBody:looseObject({}),statusCode:number(),customHeader:zodHelpers.extendedOptional(string())}),LayoutIdentifier=looseObject({id:zodHelpers.extendedOptional(string()),name:zodHelpers.extendedOptional(string()),type:zodHelpers.extendedOptional(string())}),User2=looseObject({layouts:zodHelpers.extendedOptional(array(LayoutIdentifier)),id:string(),email:zodHelpers.extendedOptional(string()),password:zodHelpers.extendedOptional(string()),apps:array(string()),groups:array(string()),lastUpdated:zodHelpers.extendedOptional(number()),firstName:zodHelpers.extendedOptional(string()),lastName:zodHelpers.extendedOptional(string())});looseObject({items:array(User2),total:number()}),looseObject({items:array(User2),total:number()});var AddUserRequest=looseObject({layouts:zodHelpers.extendedOptional(array(LayoutIdentifier)),id:string(),email:zodHelpers.extendedOptional(string()),password:zodHelpers.extendedOptional(string()),apps:array(string()),groups:array(string()),lastUpdated:zodHelpers.extendedOptional(number()),firstName:zodHelpers.extendedOptional(string()),lastName:zodHelpers.extendedOptional(string())});looseObject({users:array(AddUserRequest)}),looseObject({user:User2}),looseObject({layouts:zodHelpers.extendedOptional(array(LayoutIdentifier)),apps:zodHelpers.extendedOptional(array(string()))});var UserAppStatusExplain2=string().check(_minLength(1)),UserAppStatus=looseObject({explain:UserAppStatusExplain2,app:App2,available:boolean(),explainMore:zodHelpers.extendedOptional(string())});looseObject({apps:array(UserAppStatus)}),looseObject({app:string()}),looseObject({layouts:array(Layout2)}),looseObject({id:LayoutIdentifier}),looseObject({user:string(),groups:array(string())}),looseObject({groups:array(string())});var Machine=looseObject({id:string(),user:string(),name:zodHelpers.extendedOptional(string()),os:zodHelpers.extendedOptional(OSInfo),displays:zodHelpers.extendedOptional(array(Display)),browser:zodHelpers.extendedOptional(BrowserInfo)});looseObject({items:array(Command2),total:number()}),looseObject({command:Command2}),looseObject({resultType:zodHelpers.extendedOptional(ResultType2),traceContext:zodHelpers.extendedOptional(looseObject({})),session:string(),command:string(),commandParams:zodHelpers.extendedOptional(string())}),looseObject({id:string()});var CommandType2=string().check(_minLength(1));looseObject({type:CommandType2,paramsExamples:looseObject({}),description:string(),supportedVersions:array(string())}),looseObject({type:CommandType2,paramsExample:zodHelpers.extendedOptional(string()),description:string()}),looseObject({version:string(),core:zodHelpers.extendedOptional(ConnectBrowserInfo),build:string(),region:string(),env:string()});var UserSession2=looseObject({id:string(),user:string(),start:zodHelpers.anyIsoDate(),end:zodHelpers.extendedOptional(zodHelpers.anyIsoDate()),glue:ConnectInfo,machine:string(),lastDataFetch:zodHelpers.extendedOptional(zodHelpers.anyIsoDate()),closed:zodHelpers.extendedOptional(boolean()),closeReason:zodHelpers.extendedOptional(string())});looseObject({items:array(UserSession2),total:number()});var CleanSessionsAction2=string().check(_minLength(1));looseObject({action:CleanSessionsAction2,all:zodHelpers.extendedOptional(boolean()),lastFetchThresholdInMinutes:zodHelpers.extendedOptional(number()),createdBefore:zodHelpers.extendedOptional(zodHelpers.anyIsoDate())}),looseObject({itemsCount:number()}),looseObject({items:array(Machine),total:number()});var ClientCrashInfo=looseObject({_companyName:string(),_productName:string(),_version:string(),build:string(),env:string(),guid:string(),machine:string(),osArch:string(),osPlatform:string(),osUser:string(),osVersion:string(),osarch:string(),pid:string(),plat:string(),platform:string(),process_type:string(),prod:string(),ptype:string(),region:string(),session:string(),user:string(),ver:string(),version:string(),filename:string(),isStoredCompressed:boolean()}),ClientCrash=looseObject({id:string(),date:zodHelpers.anyIsoDate(),user:zodHelpers.extendedOptional(string()),info:ClientCrashInfo,reviewed:boolean(),comment:zodHelpers.extendedOptional(string())});looseObject({items:array(ClientCrash),total:number()}),looseObject({upload_file_minidump:string(),_companyName:string(),_productName:string(),_version:string(),build:string(),env:string(),guid:string(),machine:string(),osArch:string(),osPlatform:string(),osUser:string(),osVersion:string(),osarch:string(),pid:string(),plat:string(),platform:string(),process_type:string(),prod:string(),ptype:string(),region:string(),session:string(),user:string(),ver:string(),version:string(),filename:string()}),looseObject({comment:zodHelpers.extendedOptional(string()),reviewed:boolean()}),looseObject({version:string(),started:string(),name:string(),machine:string()});var AppsDataSummary=looseObject({total:number()}),LayoutsDataSummary=looseObject({total:number(),common:number(),private:number()}),CrashesDataSummary=looseObject({total:number(),notReviewed:number()}),FeedbacksDataSummary=looseObject({total:number(),notReviewed:number()}),CommandsDataSummary=looseObject({total:number()}),UsersDataSummary=looseObject({total:number()}),SessionsDataSummary=looseObject({active:number()}),PrefsDataSummary=looseObject({total:number()});looseObject({apps:AppsDataSummary,layouts:LayoutsDataSummary,crashes:CrashesDataSummary,feedbacks:FeedbacksDataSummary,commands:CommandsDataSummary,users:UsersDataSummary,sessions:SessionsDataSummary,prefs:PrefsDataSummary}),looseObject({items:array(Feedback),total:number()}),looseObject({comment:zodHelpers.extendedOptional(string()),reviewed:boolean()}),looseObject({items:array(AppPreferences),total:number()});var AuditLogEntityType2=string().check(_minLength(1)),AuditLogOperation2=string().check(_minLength(1)),AuditLogRequest=looseObject({body:looseObject({}),action:string(),path:string(),params:string(),query:string()}),AuditLogResponse=looseObject({status:string(),body:looseObject({})}),AuditLog=looseObject({entityType:AuditLogEntityType2,operation:AuditLogOperation2,newValue:zodHelpers.extendedOptional(looseObject({})),oldValue:zodHelpers.extendedOptional(looseObject({})),id:string(),user:zodHelpers.extendedOptional(string()),parent:zodHelpers.extendedOptional(string()),date:zodHelpers.anyIsoDate(),session:zodHelpers.extendedOptional(string()),server:string(),entityId:zodHelpers.extendedOptional(string()),entityDisplayName:zodHelpers.extendedOptional(string()),operationComment:zodHelpers.extendedOptional(string()),request:zodHelpers.extendedOptional(AuditLogRequest),response:zodHelpers.extendedOptional(AuditLogResponse)});looseObject({items:array(AuditLog),total:number()}),looseObject({all:zodHelpers.extendedOptional(boolean()),createdBefore:zodHelpers.extendedOptional(zodHelpers.anyIsoDate())}),looseObject({version:string(),group:string(),user:string()});var ConfigEntry=looseObject({contents:looseObject({}),meta:zodHelpers.extendedOptional(looseObject({})),merge:zodHelpers.extendedOptional(boolean())});looseObject({"system.json":zodHelpers.extendedOptional(ConfigEntry),"themes.json":zodHelpers.extendedOptional(ConfigEntry),"stickywindows.json":zodHelpers.extendedOptional(ConfigEntry),"channels.json":zodHelpers.extendedOptional(ConfigEntry),"logger.json":zodHelpers.extendedOptional(ConfigEntry)});var ConnectSystemConfigIdentifier=looseObject({version:string(),group:string(),user:string()}),ConnectConfigs=looseObject({"system.json":zodHelpers.extendedOptional(ConfigEntry),"themes.json":zodHelpers.extendedOptional(ConfigEntry),"stickywindows.json":zodHelpers.extendedOptional(ConfigEntry),"channels.json":zodHelpers.extendedOptional(ConfigEntry),"logger.json":zodHelpers.extendedOptional(ConfigEntry)}),ConnectSystemConfigEntry=looseObject({identifier:ConnectSystemConfigIdentifier,configs:ConnectConfigs,weight:zodHelpers.extendedOptional(number())});looseObject({items:array(ConnectSystemConfigEntry),total:number()}),looseObject({identifiers:array(ConnectSystemConfigIdentifier),configs:ConnectConfigs}),looseObject({identifier:ConnectSystemConfigIdentifier,exact:boolean()}),looseObject({identifier:ConnectSystemConfigIdentifier,configs:ConnectConfigs,weight:zodHelpers.extendedOptional(number())});var ConnectConfigKey2=string().check(_minLength(1));looseObject({config:ConnectConfigKey2,identifier:ConnectSystemConfigIdentifier}),looseObject({type:string().check(_minLength(1)),data:array(looseObject({}))}),looseObject({isValid:boolean(),errors:array(looseObject({}))});var TextFilterType2=string().check(_minLength(1)),TextFilterCondition=looseObject({filterType:string().check(_minLength(1)),type:TextFilterType2,filter:string(),in:zodHelpers.extendedOptional(array(string()))}),NumberFilterType2=string().check(_minLength(1)),NumberFilterCondition=looseObject({filterType:string().check(_minLength(1)),type:NumberFilterType2,filter:zodHelpers.extendedOptional(number()),filterTo:zodHelpers.extendedOptional(number())}),DateFilterType2=string().check(_minLength(1)),DateFilterCondition=looseObject({filterType:string().check(_minLength(1)),type:DateFilterType2,dateFrom:zodHelpers.extendedOptional(string()),dateTo:zodHelpers.extendedOptional(string())}),BooleanFilterType2=string().check(_minLength(1)),BooleanFilterCondition=looseObject({filterType:string().check(_minLength(1)),type:BooleanFilterType2,filter:boolean()}),LogicalConditionOperator2=string().check(_minLength(1));looseObject({condition1:zodHelpers.extendedOptional(union([TextFilterCondition,NumberFilterCondition,DateFilterCondition,BooleanFilterCondition,looseObject({})])),condition2:zodHelpers.extendedOptional(union([TextFilterCondition,NumberFilterCondition,DateFilterCondition,BooleanFilterCondition,looseObject({})])),operator:zodHelpers.extendedOptional(LogicalConditionOperator2)});var SortOrderEnum2=string().check(_minLength(1)),SortOrder=looseObject({sort:SortOrderEnum2,colId:string()}),DataRequestOffset=looseObject({start:number(),count:number()});looseObject({filter:zodHelpers.extendedOptional(looseObject({})),ORFilters:zodHelpers.extendedOptional(array(looseObject({}))),groupKeys:zodHelpers.extendedOptional(array(string())),rowGroupCols:zodHelpers.extendedOptional(array(string())),sort:zodHelpers.extendedOptional(array(SortOrder)),offset:zodHelpers.extendedOptional(DataRequestOffset),excludeFields:zodHelpers.extendedOptional(array(string()))});var ZodSchemas={RefreshDataRequest:RefreshDataRequest,UserLayoutDefinition:UserLayoutDefinition,Command:Command2,RefreshDataResponse:RefreshDataResponse,HelloRequest:HelloRequest,HelloResponse:HelloResponse,GoodbyeRequest:GoodbyeRequest,RefreshTokenRequest:RefreshTokenRequest,RefreshTokenResponse:RefreshTokenResponse,SaveUserLayoutRequest:SaveUserLayoutRequest,RenameLayoutRequest:RenameLayoutRequest,SetDefaultLayoutRequest:SetDefaultLayoutRequest,AddCommandResultRequest:AddCommandResultRequest,AddCommandFileResultRequest:AddCommandFileResultRequest,AppPreferences:AppPreferences,AddOrUpdatePrefsRequest:AddOrUpdatePrefsRequest,Feedback:Feedback,HttpTestRequest:HttpTestRequest,HttpTestResponse:HttpTestResponse},RequestValidator=class{constructor(e){this.options=e}async validateRequestBody(e){if(this.options.disableRequestBodyValidation)return;const{requestBody:t,schema:r,operationName:n,endpointName:i}=e(),o=await r.safeParseAsync(t,{reportInput:!0});if(!o.success)throw new IOManagerRequestValidationError(`Request body schema validation failed for endpoint "${i}" (${n})`,{cause:o.error,schema:r})}async validateResponseBody(e){if(this.options.disableResponseBodyValidation)return;const{responseBody:t,schema:r,operationName:n,endpointName:i}=e(),o=await r.safeParseAsync(t,{reportInput:!0});if(!o.success)throw new IOManagerRequestValidationError(`Response body schema validation failed for endpoint "${i}" (${n})`,{cause:o.error,schema:r})}},IOManagerRequestValidationError=class extends Error{#l;validationErrors;constructor(e,t){super(e,t),this.name="IOManagerRequestValidationError",this.#l=t,this.validationErrors=JSON.stringify(this.#l.cause.issues)}getZodError(){return this.#l.cause}getSchema(){return this.#l.schema}},ClientAPI=class extends BaseAPI{sessionTokenString;sessionToken;requestLogger;requestValidator;constructor(e){super(e),this.setOptions(e)}setOptions(e){super.setOptions(e),this.sessionTokenString&&this.updateToken(this.sessionTokenString),e.logger&&(this.requestLogger=new RequestLogger(e.logger,e.requestLoggerLevel??"trace",e.disableLogSanitization??!1,e.logHTTPHeaders??!1)),this.requestValidator=new RequestValidator({disableLogSanitization:e.disableLogSanitization??!1,disableRequestBodyValidation:e.disableRequestBodyValidation??!1,disableResponseBodyValidation:e.disableResponseBodyValidation??!1})}unload(){this.sessionToken&&this.sessionTokenString&&this.unloadClient(this.sessionToken.session,this.sessionTokenString)}async refreshData(e,t){const r="POST",n="/user",i=`${r} ${n}`,o="refreshData";this.requestLogger?.logRequest(()=>({endpointName:i,operationName:o,requestBody:e})),await this.requestValidator.validateRequestBody(()=>({requestBody:e,schema:ZodSchemas.RefreshDataRequest,operationName:o,endpointName:i}));const s=await this.sendRequest({method:r,url:n,body:e,...t});return this.requestLogger?.logResponse(()=>({endpointName:i,operationName:o,response:s})),this.fixRefreshDataResponse(s?.body),await this.requestValidator.validateResponseBody(()=>({responseBody:s.body,schema:ZodSchemas.RefreshDataResponse,operationName:o,endpointName:i})),s.body}async getApps(e){const t="/user/apps",r=`GET ${t}`,n="getApps";this.requestLogger?.logRequest(()=>({endpointName:r,operationName:n}));const i=await this.sendRequest({method:"GET",url:t,...e});return this.requestLogger?.logResponse(()=>({endpointName:r,operationName:n,response:i})),await this.requestValidator.validateResponseBody(()=>({responseBody:i.body,schema:array(looseObject({})),operationName:n,endpointName:r})),i.body}async getLayouts(e){const t="/user/layouts",r=`GET ${t}`,n="getLayouts";this.requestLogger?.logRequest(()=>({endpointName:r,operationName:n}));const i=await this.sendRequest({method:"GET",url:t,...e});return this.requestLogger?.logResponse(()=>({endpointName:r,operationName:n,response:i})),this.fixLayouts(i.body),await this.requestValidator.validateResponseBody(()=>({responseBody:i.body,schema:array(ZodSchemas.UserLayoutDefinition),operationName:n,endpointName:r})),i.body}async saveLayout(e,t){const r="POST",n="/user/layouts",i=`${r} ${n}`,o="saveLayout";this.requestLogger?.logRequest(()=>({endpointName:i,operationName:o,requestBody:e})),await this.requestValidator.validateRequestBody(()=>({requestBody:e,schema:ZodSchemas.SaveUserLayoutRequest,operationName:o,endpointName:i}));const s=await this.sendRequest({method:r,url:n,body:e,...t});return this.requestLogger?.logResponse(()=>({endpointName:i,operationName:o,response:s})),this.fixLayout(s.body),await this.requestValidator.validateResponseBody(()=>({responseBody:s.body,schema:ZodSchemas.UserLayoutDefinition,operationName:o,endpointName:i})),s.body}async deleteUserLayout(e,t){const r="DELETE",n=`${r} /user/layouts/:id`,i="deleteUserLayout";this.requestLogger?.logRequest(()=>({endpointName:n,operationName:i,pathParameters:{id:e}}));const o=await this.sendRequest({method:r,url:`/user/layouts/${customEncodeURIComponent(e)}`,...t});this.requestLogger?.logResponse(()=>({endpointName:n,operationName:i,response:o}))}async deleteAllUserLayouts(e){const t="DELETE",r="/user/layouts/",n=`${t} ${r}`,i="deleteAllUserLayouts";this.requestLogger?.logRequest(()=>({endpointName:n,operationName:i}));const o=await this.sendRequest({method:t,url:r,...e});return this.requestLogger?.logResponse(()=>({endpointName:n,operationName:i,response:o})),this.fixLayouts(o.body),await this.requestValidator.validateResponseBody(()=>({responseBody:o.body,schema:array(ZodSchemas.UserLayoutDefinition),operationName:i,endpointName:n})),o.body}async renameLayout(e,t,r){const n="POST",i=`${n} /user/layouts/:id/rename`,o="renameLayout",s={newName:t};this.requestLogger?.logRequest(()=>({endpointName:i,operationName:o,pathParameters:{id:e},requestBody:s})),await this.requestValidator.validateRequestBody(()=>({requestBody:s,schema:ZodSchemas.RenameLayoutRequest,operationName:o,endpointName:i}));const a=await this.sendRequest({method:n,url:`/user/layouts/${customEncodeURIComponent(e)}/rename`,body:s,...r});return this.requestLogger?.logResponse(()=>({endpointName:i,operationName:o,response:a})),this.fixLayout(a.body),await this.requestValidator.validateResponseBody(()=>({responseBody:a.body,schema:ZodSchemas.UserLayoutDefinition,operationName:o,endpointName:i})),a.body}async getDefaultLayout(e){const t="/user/layouts/default",r=`GET ${t}`,n="getDefaultLayout";this.requestLogger?.logRequest(()=>({endpointName:r,operationName:n}));const i=await this.sendRequest({method:"GET",url:t,...e});if(this.requestLogger?.logResponse(()=>({endpointName:r,operationName:n,response:i})),204!==i.statusCode)return await this.requestValidator.validateResponseBody(()=>({responseBody:i.body,schema:ZodSchemas.UserLayoutDefinition,operationName:n,endpointName:r})),this.fixLayout(i.body),i.body}async setDefaultLayout(e,t){const r="POST",n="/user/layouts/default",i=`${r} ${n}`,o="setDefaultLayout",s={id:e};this.requestLogger?.logRequest(()=>({endpointName:i,operationName:o,requestBody:s})),await this.requestValidator.validateRequestBody(()=>({requestBody:s,schema:ZodSchemas.SetDefaultLayoutRequest,operationName:o,endpointName:i}));const a=await this.sendRequest({method:r,url:n,body:s,...t});if(this.requestLogger?.logResponse(()=>({endpointName:i,operationName:o,response:a})),204!==a.statusCode)return this.fixLayout(a.body),await this.requestValidator.validateResponseBody(()=>({responseBody:a.body,schema:zodHelpers.extendedOptional(ZodSchemas.UserLayoutDefinition),operationName:o,endpointName:i})),a.body}async openSession(e,t,r,n){const i="POST",o="/user/hello",s=`${i} ${o}`,a="openSession",c={machine:e,glue:t,...r??{}},l={"serverx-token":""};this.requestLogger?.logRequest(()=>({endpointName:s,operationName:a,requestBody:c,headers:l})),await this.requestValidator.validateRequestBody(()=>({requestBody:c,schema:ZodSchemas.HelloRequest,operationName:a,endpointName:s}));const u=await this.sendRequest({method:i,url:o,body:c,headers:l,...n});this.requestLogger?.logResponse(()=>({endpointName:s,operationName:a,response:u,sanitizeResponseBodyProperties:["token"]})),this.fixRefreshDataResponse(u?.body?.data),await this.requestValidator.validateResponseBody(()=>({responseBody:u.body,schema:ZodSchemas.HelloResponse,operationName:a,endpointName:s}));const d=this.updateToken(u.body.token);return u.body.serverInfo&&this.initializeServerInfo(u.body.serverInfo),{...u.body,token:d}}async closeSession(e,t){if(!(e=e??this.sessionToken.session))throw new Error("no active session");const r="POST",n="/user/goodbye",i=`${r} ${n}`,o="closeSession",s={session:e},a={"serverx-token":""};this.requestLogger?.logRequest(()=>({endpointName:i,operationName:o,requestBody:s,headers:a})),await this.requestValidator.validateRequestBody(()=>({requestBody:s,schema:ZodSchemas.GoodbyeRequest,operationName:o,endpointName:i}));const c=await this.sendRequest({method:r,url:n,body:s,headers:a,...t});this.requestLogger?.logResponse(()=>({endpointName:i,operationName:o,response:c}))}async refreshToken(e){const t="POST",r="/user/refresh",n=`${t} ${r}`,i="refreshToken",o={token:this.sessionTokenString};this.requestLogger?.logRequest(()=>({endpointName:n,operationName:i,requestBody:o,sanitizeRequestBodyProperties:["token"]})),await this.requestValidator.validateRequestBody(()=>({requestBody:o,schema:ZodSchemas.RefreshTokenRequest,operationName:i,endpointName:n}));const s=await this.sendRequest({method:t,url:r,body:o,...e});return this.requestLogger?.logResponse(()=>({endpointName:n,operationName:i,response:s,sanitizeResponseBodyProperties:["token"]})),await this.requestValidator.validateResponseBody(()=>({responseBody:s.body,schema:ZodSchemas.RefreshTokenResponse,operationName:i,endpointName:n})),this.updateToken(s.body.token)}async getCommands(e){const t="GET /user/commands/:session",r="getCommands";this.requestLogger?.logRequest(()=>({endpointName:t,operationName:r,pathParameters:{session:this.sessionToken.session}}));const n=await this.sendRequest({method:"GET",url:`/user/commands/${customEncodeURIComponent(this.sessionToken.session)}`,...e});return this.requestLogger?.logResponse(()=>({endpointName:t,operationName:r,response:n})),await this.requestValidator.validateResponseBody(()=>({responseBody:n.body,schema:array(ZodSchemas.Command),operationName:r,endpointName:t})),n.body}async setCommandResult(e,t,r){const n="POST",i=`${n} /user/commands/:commandId`,o="setCommandResult";this.requestLogger?.logRequest(()=>({endpointName:i,operationName:o,pathParameters:{commandId:e},requestBody:t})),await this.requestValidator.validateRequestBody(()=>({requestBody:t,schema:ZodSchemas.AddCommandResultRequest,operationName:o,endpointName:i}));const s=await this.sendRequest({method:n,url:`/user/commands/${customEncodeURIComponent(e)}`,body:t,...r});this.requestLogger?.logResponse(()=>({endpointName:i,operationName:o,response:s}))}async setCommandFileResult(e,t,r,n){const i="POST",o=`${i} /user/commands/:commandId/file`,s="setCommandFileResult",a={fileName:t,contents:r};this.requestLogger?.logRequest(()=>({endpointName:o,operationName:s,pathParameters:{commandId:e},requestBody:a,sanitizeRequestBodyProperties:["contents"]})),await this.requestValidator.validateRequestBody(()=>({requestBody:a,schema:ZodSchemas.AddCommandFileResultRequest,operationName:s,endpointName:o}));const c=await this.sendRequest({method:i,url:`/user/commands/${customEncodeURIComponent(e)}/file`,body:a,...n});this.requestLogger?.logResponse(()=>({endpointName:o,operationName:s,response:c}))}async getPrefs(e,t,r){const n="GET /user/prefs/:app",i="getPrefs";let o=`/user/prefs/${customEncodeURIComponent(e)}`;const s=new URLSearchParams;t&&s.set("last",t.getTime().toString()),o+=`?${s.toString()}`,this.requestLogger?.logRequest(()=>({endpointName:n,operationName:i,pathParameters:{app:e},queryParameters:Object.fromEntries(s.entries())}));const a=await this.sendRequest({method:"GET",url:o,validateStatusCode:e=>e<400||404===e,...r});return this.requestLogger?.logResponse(()=>({endpointName:n,operationName:i,response:a})),404===a.statusCode&&(a.body=void 0),await this.requestValidator.validateResponseBody(()=>({responseBody:a.body,schema:zodHelpers.extendedOptional(ZodSchemas.AppPreferences),operationName:i,endpointName:n})),a.body}async getAllPrefs(e){const t="/user/prefs/",r=`GET ${t}`,n="getAllPrefs";this.requestLogger?.logRequest(()=>({endpointName:r,operationName:n}));const i=await this.sendRequest({method:"GET",url:t,...e});return this.requestLogger?.logResponse(()=>({endpointName:r,operationName:n,response:i})),await this.requestValidator.validateResponseBody(()=>({responseBody:i.body,schema:array(ZodSchemas.AppPreferences),operationName:n,endpointName:r})),i.body}async setPrefs(e,t){const r="POST",n="/user/prefs/",i=`${r} ${n}`,o="setPrefs";this.requestLogger?.logRequest(()=>({endpointName:i,operationName:o,requestBody:e})),await this.requestValidator.validateRequestBody(()=>({requestBody:e,schema:ZodSchemas.AddOrUpdatePrefsRequest,operationName:o,endpointName:i}));const s=await this.sendRequest({method:r,url:n,body:e,...t});return this.requestLogger?.logResponse(()=>({endpointName:i,operationName:o,response:s})),this.fixSetPrefsResponse(s?.body),await this.requestValidator.validateResponseBody(()=>({responseBody:s.body,schema:ZodSchemas.AppPreferences,operationName:o,endpointName:i})),s.body}async deletePrefs(e,t){const r="DELETE",n=`${r} /user/prefs/:app`,i="deletePrefs";this.requestLogger?.logRequest(()=>({endpointName:n,operationName:i,pathParameters:{app:e}}));const o=await this.sendRequest({method:r,url:`/user/prefs/${customEncodeURIComponent(e)}`,...t});this.requestLogger?.logResponse(()=>({endpointName:n,operationName:i,response:o}))}async deleteAllPrefs(e){const t="DELETE",r="/user/prefs/",n=`${t} ${r}`,i="deleteAllPrefs";this.requestLogger?.logRequest(()=>({endpointName:n,operationName:i}));const o=await this.sendRequest({method:t,url:r,...e});this.requestLogger?.logResponse(()=>({endpointName:n,operationName:i,response:o}))}async addFeedback(e,t,r){const n="POST",i="/user/feedbacks",o=`${n} ${i}`,s="addFeedback",a=new FormData$1;a.append("description",e),a.append("attachment",t),this.requestLogger?.logRequest(()=>({endpointName:o,operationName:s}));const c=await this.sendRequest({method:n,url:i,body:a,json:!1,...r});return this.requestLogger?.logResponse(()=>({endpointName:o,operationName:s,response:c})),await this.requestValidator.validateResponseBody(()=>({responseBody:c.body,schema:ZodSchemas.Feedback,operationName:s,endpointName:o})),c.body}async httpTest(e,t,r,n){this.ensureCapability("HTTP_TEST");const i="POST",o="/user/http-test",s=`${i} ${o}`,a="httpTest",c=new URLSearchParams;c.append("statusCode",e?.toString());const l=`${o}?${c.toString()}`,u={};r&&(u["X-Custom-IOManager-Header"]=r),this.requestLogger?.logRequest(()=>({endpointName:s,operationName:a,requestBody:t,queryParams:Object.fromEntries(c.entries()),headers:u})),await this.requestValidator.validateRequestBody(()=>({requestBody:t,schema:zodHelpers.extendedOptional(ZodSchemas.HttpTestRequest),operationName:a,endpointName:s}));const d=await this.sendRequest({method:i,url:l,body:t,headers:u,validateStatusCode:()=>!0,...n});return this.requestLogger?.logResponse(()=>({endpointName:s,operationName:a,response:d})),await this.requestValidator.validateResponseBody(()=>({responseBody:d.body,schema:ZodSchemas.HttpTestResponse,operationName:a,endpointName:s})),d}fixRefreshDataResponse(e){"string"==typeof e?.config?.info?.last&&(e.config.info.last=Number(e.config.info.last)),"string"==typeof e?.commands?.info?.last&&(e.commands.info.last=Number(e.commands.info.last)),"string"==typeof e?.applications?.info?.last&&(e.applications.info.last=Number(e.applications.info.last)),"string"==typeof e?.layouts?.info?.last&&(e.layouts.info.last=Number(e.layouts.info.last)),this.fixLayouts(e?.layouts?.data)}fixSetPrefsResponse(e){"string"==typeof e?.data&&(e.data=JSON.parse(e.data))}fixLayouts(e){if(Array.isArray(e))for(const t of e)this.fixLayout(t)}fixLayout(e){if(!e)return;let t;function r(){if(!t)try{t=JSON.parse(e.definition)}catch{}}"string"!=typeof e.name&&(r(),e.name="string"==typeof t?.name?t.name:""),"string"!=typeof e.type&&(r(),e.type="string"==typeof t?.type?t.type:"")}updateToken(e){return this.sessionToken=jwtDecode(e),this.sessionTokenString=e,this.options.headers=this.options.headers??{},this.options.headers["serverx-token"]=e,this.sessionToken}async sendRequest(e){return this.options.req?this.callCustomRequestImplementation(e):this.callAxiosRequestImplementation(e)}async callAxiosRequestImplementation(e){const t=await this.axiosInstance.request({method:e.method,url:e.url,headers:e.headers,timeout:e.timeout,data:e.body,validateStatus:e.validateStatusCode??this.defaultIsStatusCodeValid});return{body:t.data,statusCode:t.status,headers:t.headers}}async callCustomRequestImplementation(e){if(!this.options.req)throw new Error("this.options.req is falsy.");const t={...e,method:e.method?.toLowerCase(),baseUrl:e.baseUrl??this.options.baseUrl,url:this.resolveFullUrl(e.url,e.baseUrl??this.options.baseUrl),json:e.json??!0,timeout:e.timeout??this.options.requestTimeout},r={...this.getBaseHeaders(this.options)??{},...await(this.options.getHeaders?.(t)),...e.headers??{}};t.headers=r,this.interceptCustomRequest?.(t),this.requestLogger?.logRequestHeaders(()=>t.headers);const n=new PromiseWrapper;return this.options.req(t,(r,i)=>{if(r)if(this.interceptCustomResponseError){const e=this.interceptCustomResponseError?.(t,r,void 0);n.reject(e)}else n.reject(r);else{if(i?.body){const e=this.options?.transformResponse;i.body=e?.(i.body,i.headers)??i.body}this.requestLogger?.logResponseHeaders(()=>i?.headers);const r=e.validateStatusCode??this.defaultIsStatusCodeValid;if(i?.statusCode&&!r(i.statusCode)){const e=new CustomRequestError(`Request failed with status code ${i.statusCode}`),r=Math.floor(i.statusCode/100);if(4===r?e.code="ERR_BAD_REQUEST":5===r&&(e.code="ERR_BAD_RESPONSE"),this.interceptCustomResponseError){const r=this.interceptCustomResponseError?.(t,e,i);n.reject(r)}else n.reject(e)}else this.interceptCustomResponse?.(t,i),n.resolve(i)}}),n.promise}resolveFullUrl(e,t){let r=e;r.startsWith("/")&&(r=r.substring(1));let n=t;return n.endsWith("/")||(n+="/"),new URL(r,n).href}interceptCustomRequest;interceptCustomResponse;interceptCustomResponseError},CustomRequestError=class extends Error{code;status},SanitizedIOManagerApiError=class e extends Error{code;status;isSessionExpired;isCustomTimeoutError;validationErrors;request;responseBodyError;static fromAxiosError(t){const r=Number(t?.response?.status),n=t?.response?.data;let i;if(t?.message)i=t?.message;else if("errors"in t&&t?.errors&&Array.isArray(t?.errors)){const e=t?.errors?.map(e=>e?.message).filter(e=>e);e.length&&(i=e.join(", "))}const o=new e(i);if(o.name="SanitizedIOManagerApiError",o.stack=t?.stack,t instanceof IOManagerRequestValidationError){const e=t;o.validationErrors=e.validationErrors}Number.isFinite(r)&&(o.status=r),t?.code&&(o.code=t?.code),o.request={baseUrl:t?.config?.baseURL,url:t?.config?.url,method:t?.config?.method};const s=400===r&&"invalid-glue42-server-token"===n?.error?.message;return s&&(o.isSessionExpired=s),o.responseBodyError=n?.error,o}static fromCustomRequestError(t,r,n){const i=Number(r?.statusCode),o=r?.body,s=new e(n?.message);if(s.name="SanitizedIOManagerApiError",s.stack=n?.stack,n instanceof IOManagerRequestValidationError){const e=n;s.validationErrors=e.validationErrors}let a;Number.isFinite(i)&&(s.status=i),n?.code?s.code=n?.code:n?.message?.includes("net::ERR_CONNECTION_REFUSED")&&(s.code="ECONNREFUSED"),t.baseUrl&&t.url.startsWith(t.baseUrl)?(a=t.url.slice(t.baseUrl.length),a.startsWith("/")||(a=`/${a}`)):a=t.url,s.request={baseUrl:t.baseUrl,url:a,method:t.method};const c=400===i&&"invalid-glue42-server-token"===o?.error?.message;return c&&(s.isSessionExpired=c),s.responseBodyError=o?.error,n.isCustomTimeoutError&&(s.isCustomTimeoutError=n.isCustomTimeoutError),s}},CachedClientAPI=class extends ClientAPI{get connectionState(){return{isConnected:this._isConnected,baseUrl:this.options.baseUrl,serverEnabled:!0,cacheEnabled:this.options.enableCaching,disconnectionError:this._disconnectionError}}get token(){return this.sessionToken?this.sessionToken:this.options.enableCaching?this._cachedToken:void 0}_callbacks=CallbackRegistryFactory$2();_isConnected=!1;_refreshTokenIntervalId;_refreshDataIntervalId;_slowestRequests=[];_statParams;_lastApplicationsInfo;_lastLayoutsInfo;_lastCommandsInfo;_lastConfigsInfo;_lastApplicationsData;_lastLayoutsData;_lastConfigsData;_cachedToken;_disconnectionError;_sessionNotPersisted;_cachedClientRequestInterceptor;_cachedClientResponseInterceptor;get logger(){return this.options.logger}get cache(){if(!this.options.enableCaching)throw new Error("Accessing the cache is not allowed when caching is disabled.");return this.options.managerCache}constructor(e){super(e),this.setOptions(e)}setOptions(e){e.refresh??={},e.refresh.applications??=!0,e.refresh.layouts??=!0,e.refresh.commands??=!0,e.refresh.configs??=!1,super.setOptions(e);const t=e=>{const t={startTime:this.getNowMs(),startTimeDate:new Date,operation:`${e.method} ${e.url}`};e.__perf=t},r=e=>{const t=e.__perf;t.endTime=this.getNowMs(),t.duration=t.endTime-t.startTime,this._slowestRequests.push(t),this._slowestRequests.sort((e,t)=>t.duration-e.duration),this._slowestRequests.length>5&&this._slowestRequests.pop()};this._cachedClientRequestInterceptor&&this.axiosInstance.interceptors?.request?.eject(this._cachedClientRequestInterceptor),this._cachedClientRequestInterceptor=this.axiosInstance.interceptors.request.use(e=>(t(e),e),e=>e?.config?.method?Promise.reject(SanitizedIOManagerApiError.fromAxiosError(e)):Promise.reject(e)),this.interceptCustomRequest=e=>{t(e)},this._cachedClientResponseInterceptor&&this.axiosInstance.interceptors?.response?.eject(this._cachedClientResponseInterceptor),this._cachedClientResponseInterceptor=this.axiosInstance.interceptors.response.use(e=>(r(e.config),e),e=>(r(e.config),e?.config?.method?Promise.reject(SanitizedIOManagerApiError.fromAxiosError(e)):Promise.reject(e))),this.interceptCustomResponse=e=>{r(e)},this.interceptCustomResponseError=(e,t,n)=>(r(e),SanitizedIOManagerApiError.fromCustomRequestError(e,n,t))}async start(...e){this._statParams=e;const t=this._statParams[2]??={};let r;t.initialDataRequest??=this.createRefreshDataRequest(!0),t.includeServerInfo=!0,this.logger.info(`Initiating connection to ${this.options.baseUrl}`);let n=!1;try{let e;if(this.logger.info("Opening a session..."),this.options.enableCaching){const i=await this.cache.get("session");if(i&&(this._cachedToken=i.value),r=await this.readDataCache(t.initialDataRequest),n=Boolean(i&&r),n){const t=[...this._statParams];t[3]??={},t[3].timeout=this.options.openSessionRequestTimeout,e=await super.openSession(...t)}else e=await this.retryStart(...this._statParams)}else e=await this.retryStart(...this._statParams);return this.logger.info(`Session opened. Initial data received: ${this.getSnapshotSummary(e.data).join(", ")}`),this._sessionNotPersisted=e.sessionNotPersisted,e.sessionNotPersisted&&this.logger.warn("Session was opened in read-only mode and was not persisted on the server."),this.writeToFields(e.data),this.options.enableCaching&&(this.logger.info("Writing session info to cache."),await this.cache.set("session",e.token),await this.cache.set("sessionNotPersisted",e.sessionNotPersisted),await this.writeDataCache(e.data)),this.notifyConnected(),this.startTokenTimer(),this.startDataTimer(),e}catch(e){if(this.notifyDisconnected(e),!this.options.enableCaching)throw this.logger.error("Failed to open a session.",e),e;if(!n)throw this.logger.error("Failed to open a session. Cache miss.",e),e;this.logger.warn("Failed to open a session. Proceeding from cache.",e);const t=await this.cache.get("sessionNotPersisted");return t?.value&&this.logger.warn("Cached session was opened in read-only mode and was not persisted on the server."),this.writeToFields(r),this.startTokenTimer(),this.startDataTimer(),{token:this._cachedToken,data:r}}}async stop(){this.stopTokenTimer(),this.stopDataTimer(),this.logger.info("Slowest requests:");for(const e of this._slowestRequests)this.logger.info(`${e.startTimeDate.toISOString()} - operation: ${e.operation}, duration (ms): ${e.duration}`);this.logger.info("Closing session."),await super.closeSession(void 0,{timeout:this.options.closeSessionRequestTimeout})}onConnectedStateChanged(e){return this._callbacks.add("onConnectedStateChanged",e)}async onAppsChanged(e){const t=this._callbacks.add("onAppsChanged",e);try{this._lastApplicationsData&&(this.logger.debug("Calling onAppsChanged",this._lastApplicationsData),this._callbacks.execute("onAppsChanged",this._lastApplicationsData))}catch(e){throw t(),e}return t}async onLayoutsChanged(e){const t=this._callbacks.add("onLayoutsChanged",e);try{this._lastLayoutsData&&(this.logger.debug("Calling onLayoutsChanged",this._lastLayoutsData),this._callbacks.execute("onLayoutsChanged",this._lastLayoutsData))}catch(e){throw t(),e}return t}async onCommandsReceived(e){return this._callbacks.add("onCommandsReceived",e)}async onConfigsChanged(e){const t=this._callbacks.add("onConfigsChanged",e);try{this._lastConfigsData&&(this.logger.debug("Calling onConfigsChanged",this._lastConfigsData),this._callbacks.execute("onConfigsChanged",this._lastConfigsData))}catch(e){throw t(),e}return t}openSession(...e){throw new Error("Calling `openSession` directly is not supported. Call `start` instead.")}closeSession(...e){throw new Error("Calling `closeSession` directly is not supported. Call `stop` instead.")}async refreshData(...e){this.logger.isTraceEnabled()?this.logger.trace(`Requesting data changes: ${JSON.stringify(e[0])}`):this.logger.info(`Requesting data changes: ${JSON.stringify(this.sanitizeGroups(e[0]))}`);let t=!1;try{const r=await this.handleAuth(async r=>(t=Boolean(r),r?r.data:await super.refreshData(...e)));if(this.notifyConnected(),r&&!t){const e=this.getSnapshotSummary(r);e.length?this.logger.info(`Data received: ${e.join(", ")}`):this.logger.info("No new data was received."),this.writeToFields(r),this.options.enableCaching&&await this.writeDataCache(r)}return r}catch(t){if(this.notifyDisconnected(t),!this.options.enableCaching)throw this.logger.debug("Refresh data request failed.",t),t;const r=await this.readDataCache(e[0]);if(!r)throw this.logger.debug("Refresh data request failed. Cache miss.",t),t;return this.logger.warn("Refresh data request failed. Returning data from cache.",t),r}}async refreshToken(...e){this.logger.info("Refreshing session token.");try{const t=await this.handleAuth(()=>super.refreshToken(...e));return this.notifyConnected(),this.options.enableCaching&&(this.logger.info("Writing session info to cache."),await this.cache.set("session",t)),t}catch(e){throw this.notifyDisconnected(e),this.logger.debug("Refresh token request failed.",e),e}}async getPrefs(...e){const t=e[0];try{const r=await this.handleAuth(()=>super.getPrefs(...e));return this.notifyConnected(),this.options.enableCaching&&await this.updateAllPreferencesCache(t,r),r}catch(e){if(this.notifyDisconnected(e),!this.options.enableCaching)throw this.logger.debug("getPrefs request failed.",e),e;const r=await this.cache.get("prefs_data");if(!r)throw this.logger.debug("getPrefs request failed. Cache miss.",e),e;this.logger.debug("getPrefs request failed. Returning data from cache.",e);const n=r.value.find(e=>e.app===t);return n&&"string"==typeof n?.data&&(n.data=JSON.parse(n.data)),n}}getAllPrefs(...e){return this.handleRead("getAllPrefs","prefs_data",()=>super.getAllPrefs(...e))}getDefaultLayout(...e){return this.handleRead("getDefaultLayout","read_getDefaultLayout",()=>super.getDefaultLayout(...e))}whoAmI(...e){return this.handleRead("whoAmI","read_whoAmI",()=>super.whoAmI(...e))}async getLayouts(...e){const t=await this.handleRead("getLayouts","layouts_data",()=>super.getLayouts(...e));return this._lastLayoutsData=t,this._callbacks.execute("onLayoutsChanged",t),t}getLastLayouts(){return this._lastLayoutsData}getLastApps(){return this._lastApplicationsData}async getApps(...e){const t=await this.handleRead("getApps","applications_data",()=>super.getApps(...e));return this._lastApplicationsData=t,this._callbacks.execute("onAppsChanged",t),t}async getCommands(...e){const t=await this.handleAuth(()=>super.getCommands(...e));return this._callbacks.execute("onCommandsReceived",t),t}setPrefs(...e){return this.handleWrite("setPrefs","write_setPrefs",()=>super.setPrefs(...e))}setCommandResult(...e){return this.handleWrite("setCommandResult","write_setCommandResult",()=>super.setCommandResult(...e))}addFeedback(...e){return this.handleWrite("addFeedback","write_addFeedback",()=>super.addFeedback(...e))}setDefaultLayout(...e){return this.handleWrite("setDefaultLayout","write_setDefaultLayout",()=>super.setDefaultLayout(...e))}deleteAllPrefs(...e){return this.handleWrite("deleteAllPrefs","write_deleteAllPrefs",()=>super.deleteAllPrefs(...e))}deleteAllUserLayouts(...e){return this.handleWrite("deleteAllUserLayouts","write_deleteAllUserLayouts",()=>super.deleteAllUserLayouts(...e))}setCommandFileResult(...e){return this.handleWrite("setCommandFileResult","write_setCommandFileResult",()=>super.setCommandFileResult(...e))}saveLayout(...e){return this.handleWrite("saveLayout","write_saveLayout",()=>super.saveLayout(...e))}renameLayout(...e){return this.handleWrite("renameLayout","write_renameLayout",()=>super.renameLayout(...e))}deletePrefs(...e){return this.handleWrite("deletePrefs","write_deletePrefs",()=>super.deletePrefs(...e))}deleteUserLayout(...e){return this.handleWrite("deleteUserLayout","write_deleteUserLayout",()=>super.deleteUserLayout(...e))}notifyDisconnected(e){if(this._isConnected){this._isConnected=!1,this._disconnectionError=e,this.logger.warn("io.Manager connection state changed: disconnected.",e);const t={isConnected:this._isConnected,baseUrl:this.options.baseUrl,serverEnabled:!0,cacheEnabled:this.options.enableCaching,disconnectionError:e};this._callbacks.execute("onConnectedStateChanged",t)}}notifyConnected(){if(!this._isConnected){this._isConnected=!0,this._disconnectionError=void 0,this.logger.info("io.Manager connection state changed: connected.");const e={isConnected:this._isConnected,baseUrl:this.options.baseUrl,serverEnabled:!0,cacheEnabled:this.options.enableCaching};this._callbacks.execute("onConnectedStateChanged",e)}}async refreshTokenTimeout(){try{this.options.asyncSequelizer?await this.options.asyncSequelizer.enqueue(async()=>{await this.refreshToken()}):await this.refreshToken()}catch(e){this.logger.warn("Refresh token request failed.",e)}finally{this.startTokenTimer()}}async refreshDataTimeout(){const e=this.createRefreshDataRequest();try{this.options.asyncSequelizer?await this.options.asyncSequelizer.enqueue(async()=>{await this.refreshData(e)}):await this.refreshData(e)}catch(e){this.logger.warn("Refresh data request failed.",e)}finally{this.startDataTimer()}}createRefreshDataRequest(e){return{applications:{include:Boolean(this.options.refresh?.applications),latestDataInfo:e?void 0:this._lastApplicationsInfo},layouts:{include:Boolean(this.options.refresh?.layouts),latestDataInfo:e?void 0:this._lastLayoutsInfo},commands:{include:Boolean(this.options.refresh?.commands),latestDataInfo:e?void 0:this._lastCommandsInfo},configs:{include:Boolean(this.options.refresh?.configs),latestDataInfo:e?void 0:this._lastConfigsInfo}}}startTokenTimer(){this.logger.info(`Starting the session token refresh timer for ${this.options.tokenRefreshInterval}s`),this._refreshTokenIntervalId=setTimeout(this.refreshTokenTimeout.bind(this),1e3*this.options.tokenRefreshInterval)}startDataTimer(){this.logger.info(`Starting data refresh timer for ${this.options.fetchInterval}s`),this._refreshDataIntervalId=setTimeout(this.refreshDataTimeout.bind(this),1e3*this.options.fetchInterval)}async recreateSession(e){if(this.logger.debug("Opening a session..."),e&&!this._sessionNotPersisted)try{this.logger.debug("Closing old session."),await super.closeSession(e,{timeout:this.options.closeSessionRequestTimeout}),this.logger.debug("Old session closed.")}catch(e){this.logger.debug("Failed to close old session.",e)}const t=await super.openSession(...this._statParams);return this.logger.info(`Session opened. Initial data received: ${this.getSnapshotSummary(t.data).join(", ")}`),this._sessionNotPersisted=t.sessionNotPersisted,t.sessionNotPersisted&&this.logger.warn("Session was opened in read-only mode and was not persisted on the server."),this.writeToFields(t.data),this.options.enableCaching&&(this.logger.info("Writing session info to cache."),await this.cache.set("session",t.token),await this.cache.set("sessionNotPersisted",t.sessionNotPersisted),await this.writeDataCache(t.data)),t}stopTokenTimer(){this.logger.info("Stopping the session token refresh timer."),this._refreshTokenIntervalId&&clearTimeout(this._refreshTokenIntervalId)}stopDataTimer(){this.logger.info("Stopping the data refresh timer."),this._refreshDataIntervalId&&clearTimeout(this._refreshDataIntervalId)}writeToFields(e){e.applications?.hasChanges&&(this._lastApplicationsData=e.applications.data,this._lastApplicationsInfo=e.applications.info,this._callbacks.execute("onAppsChanged",e.applications.data)),e.layouts?.hasChanges&&(this._lastLayoutsData=e.layouts.data,this._lastLayoutsInfo=e.layouts.info,this._callbacks.execute("onLayoutsChanged",e.layouts.data)),e.config?.hasChanges&&(this._lastConfigsData=e.config.data,this._lastConfigsInfo=e.config.info,this._callbacks.execute("onConfigsChanged",e.config.data)),e.commands?.hasChanges&&(this._lastCommandsInfo=e.commands.info,this._callbacks.execute("onCommandsReceived",e.commands.data))}async writeDataCache(e){e.applications?.hasChanges&&(await this.cache.set("applications_data",e.applications.data),await this.cache.set("applications_info",e.applications.info)),e.layouts?.hasChanges&&(await this.cache.set("layouts_data",e.layouts.data),await this.cache.set("layouts_info",e.layouts.info)),e.config?.hasChanges&&(await this.cache.set("config_data",e.config.data),await this.cache.set("config_info",e.config.info)),e.commands?.hasChanges&&await this.cache.set("commands_info",e.commands.info)}async readDataCache(e){const t={};if(!0===e.applications?.include){const r=await this.cache.get("applications_info");if(!r)return void this.logger.debug('readDataCache: Could not find "applications_info" in cache.');if(this.lastDataInfoEquals(e.applications?.latestDataInfo,r.value))t.applications={hasChanges:!1};else{const e=await this.cache.get("applications_data");t.applications={hasChanges:!0,data:e?.value,info:r.value}}}if(!0===e.layouts?.include){const r=await this.cache.get("layouts_info");if(!r)return void this.logger.debug('readDataCache: Could not find "layouts_info" in cache.');if(this.lastDataInfoEquals(e.layouts?.latestDataInfo,r.value))t.layouts={hasChanges:!1};else{const e=await this.cache.get("layouts_data");t.layouts={hasChanges:!0,data:e?.value,info:r.value}}}if(!0===e.configs?.include){const r=await this.cache.get("config_info");if(!r)return void this.logger.debug('readDataCache: Could not find "config_info" in cache.');if(this.lastDataInfoEquals(e.configs?.latestDataInfo,r.value))t.config={hasChanges:!1};else{const e=await this.cache.get("config_data");t.config={hasChanges:!0,data:e?.value,info:r.value}}}return t}async updateAllPreferencesCache(e,t){const r=await this.cache.get("prefs_data");let n=r?.value||[];if(t){const r=n.findIndex(t=>t.app===e);-1!==r?n[r]=t:n.push(t)}else n=n.filter(t=>t.app!==e);await this.cache.set("prefs_data",n)}lastDataInfoEquals(e,t){return!(!e||!t)&&(e.checksum===t.checksum||Number(e.last)===Number(t.last))}async handleRead(e,t,r){this.logger.debug(`calling handleRead operationName=${e} cacheKey=${t}`);try{const e=await this.handleAuth(r);return this.notifyConnected(),this.options.enableCaching&&await this.cache.set(t,e),e}catch(r){if(this.notifyDisconnected(r),!this.options.enableCaching)throw this.logger.debug(`${e} request failed.`,r),r;const n=await this.cache.get(t);if(!n)throw this.logger.debug(`${e} request failed. Cache miss.`,r),r;if(this.logger.debug(`${e} request failed. Returning data from cache.`,r),"prefs_data"===t){const e=n.value;if(e)for(const t of e)"string"==typeof t.data&&(t.data=JSON.parse(t.data))}return n.value}}async handleWrite(e,t,r){this.logger.debug(`calling handleWrite operationName=${e} cacheKey=${t}`);try{const e=await this.handleAuth(r);return this.notifyConnected(),e}catch(t){const r=t;throw this.logger.debug(`${e} request failed.`,t),"ReadOnlyRequestViolationError"!==r.responseBodyError?.type&&this.notifyDisconnected(t),t}}async retryStart(...e){let t=0;for(;;)try{return t>0&&this.logger.info(`Opening a session [retry ${t} of ${this.options.startRetries}]`),await super.openSession(...e)}catch(e){if(t>=this.options.startRetries)throw e;this.logger.warn(`Failed to open a session. Retrying after ${this.options.startRetryInterval}s.`,e),t+=1,await new Promise(e=>setTimeout(e,1e3*this.options.startRetryInterval))}}getSnapshotSummary(e){const t=[];return e.applications?.hasChanges&&t.push(`applications (${e.applications.data?.length})`),e.layouts?.hasChanges&&t.push(`layouts (${e.layouts.data?.length})`),e.commands?.hasChanges&&t.push(`commands (${e.commands.data?.length})`),e.config?.hasChanges&&t.push(`remote configs (${e.config.data?.length})`),t}async handleAuth(e){let t;if(!this.sessionToken||!this.sessionTokenString||this._sessionNotPersisted){let e;if(this.sessionToken||this.logger.info("Session is not open (started from cache). Opening a session..."),this._sessionNotPersisted&&this.logger.info("Session is not persisted on the server (server was in read-only mode when it created it). Opening a new session..."),this.options.enableCaching){const t=await this.cache.get("session");e=t?.value?.session}try{t=await this.recreateSession(e)}catch(e){throw this.logger.warn("Failed to open a session.",e),e}}try{return await e(t)}catch(r){if(r?.isSessionExpired){try{this.logger.warn("Session expired. Opening a new session...",r),t=await this.recreateSession(this.sessionToken?.session)}catch(e){throw this.logger.warn("Failed to re-open the session.",e),r}return await e(t)}throw r}}getNowMs(){return this.options.getNowMs?this.options.getNowMs():Number(new Date)}sanitizeGroups(e){if(null==e)return e;if("object"!=typeof e)return e;const t=structuredClone(e);function r(e){return e?Array.isArray(e)?`__REMOVED(length=${e.length})`:"__REMOVED(NON_ARRAY_TRUTHY_VALUE)":"__REMOVED(falsy)"}return function e(t){if(null!=t&&"object"==typeof t)if(Array.isArray(t))for(const r of t)e(r);else for(const n in t)t.hasOwnProperty(n)&&("groups"===n?t[n]=r(t[n]):e(t[n]))}(t),t}};const managerOperationDecoder=oneOf$1(constant$2("operationCheck")),DEFAULT_RESPONSE_TIMEOUT_MS=1e4,PREFS_CACHE_KEY="prefs_data",LAYOUTS_CACHE_KEY="layouts_data",DEFAULT_LAYOUT_CACHE_KEY="read_getDefaultLayout",PREFS_CHANGED_EVENT_KEY="onPrefsChanged",APPS_ADDED_EVENT_KEY="onAppsAdded",APPS_DELETED_EVENT_KEY="onAppsDeleted",APPS_CHANGED_EVENT_KEY="onAppsChanged",LAYOUTS_CHANGED_EVENT_KEY="onLayoutsChanged",LAYOUTS_ADDED_EVENT_KEY="onLayoutsAdded",LAYOUTS_REMOVED_EVENT_KEY="onLayoutsRemoved",LAYOUTS_RENAMED_EVENT_KEY="onLayoutsRenamed",CONNECTED_STATE_CHANGED_EVENT_KEY="onConnectedStateChanged",GET_CONNECTION_STATE_METHOD_NAME="T42.IOManager.GetConnectionState",FETCH_DATA_METHOD_NAME="T42.IOManager.FetchData",CONNECTION_STATE_STREAM_NAME="T42.IOManager.ConnectionState",defaultDataRefreshIntervalMS=6e4,defaultTokenRefreshIntervalMS=36e5;class ManagerController{identity;glueController;sequelizer;buildClient;buildCache;started=!1;name="io.Manager Client";globalConfig;config;unloadCallback;callbacks=CallbackRegistryFactory$2();lastApps=[];lastLayouts=[];lastLayoutIdsByKey=new Map;client;managerCache;connectionStateStream;get managerConnectionState(){const e={serverEnabled:!1,isConnected:!1};return this.config?this.client.connectionState:e}operations={operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)}};constructor(e,t,r,n,i){this.identity=e,this.glueController=t,this.sequelizer=r,this.buildClient=n,this.buildCache=i,this.unloadCallback=this.handleUnload.bind(this),window.addEventListener("pagehide",this.unloadCallback)}get logger(){return logger.get("manager.controller")}get isStarted(){return this.started}get isCritical(){return this.config?.critical??!0}ready(){return Promise.resolve()}handlePlatformShutdown(){this.started=!1,window.removeEventListener("pagehide",this.unloadCallback),this.handleUnload(),this.managerCache?.dispose()}async configurePostStart(){if(await this.registerInteropMethods(),!this.config)return;const e=this.globalConfig?.user?.id||"__no_user__";this.managerCache=this.buildCache(this.config,e),await this.managerCache.initialize();const t={baseUrl:this.config.url,auth:this.config.auth,headers:this.config.headers,getHeaders:this.config.getHeaders,fetchInterval:(this.config.fetchIntervalMS||defaultDataRefreshIntervalMS)/1e3,tokenRefreshInterval:(this.config.tokenRefreshIntervalMS||defaultTokenRefreshIntervalMS)/1e3,startRetries:0,startRetryInterval:1e4,refresh:{applications:Boolean(this.config.features?.applicationsStore??!0),layouts:Boolean(this.config.features?.layoutsStore??!0),commands:!1,configs:!1},requestTimeout:this.config.requests?.timeout??this.config.responseTimeoutMS??DEFAULT_RESPONSE_TIMEOUT_MS,openSessionRequestTimeout:this.config.requests?.openSessionTimeout??DEFAULT_RESPONSE_TIMEOUT_MS,closeSessionRequestTimeout:this.config.requests?.closeSessionTimeout??DEFAULT_RESPONSE_TIMEOUT_MS,enableCaching:!0,managerCache:this.managerCache,asyncSequelizer:this.sequelizer,logger:this.createManagerLogger()};this.client=this.buildClient(t),this.logger?.trace("The client API is ready.");const r=await this.identity.getMachineInfo(e),n=this.identity.getGlueInfo();this.logger?.trace(`Opening a session for machine: ${JSON.stringify(r)} and glue: ${JSON.stringify(n)}`),this.client.onConnectedStateChanged(this.handleOnConnectedStateChanged.bind(this)),await this.client.onAppsChanged(this.handleOnAppsChanged.bind(this)),await this.client.onLayoutsChanged(this.handleOnLayoutsChanged.bind(this)),await this.client.start(r,n),this.config.features?.preferencesStore&&await this.client.getAllPrefs(),this.started=!0,this.logger?.info(`Module ${this.name} started`)}async start(e){e.manager&&(this.globalConfig=e,this.config=e.manager,this.logger?.info("Starting the Manager controller."))}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this manager control message, because the controller has not been started");const t=e.data,r=e.commandId,n=managerOperationDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This manager request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`Manager request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`Manager request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}onConnectedStateChanged(e){return this.callbacks.add(CONNECTED_STATE_CHANGED_EVENT_KEY,e)}async saveLayouts(e,t,r){return this.sequelizer.enqueue(async()=>{let n;if(r&&this.logger?.trace(`[${r}] handling "saveLayouts" request | mode=${t}`),n="replace"===t?await this.client.deleteAllUserLayouts():await this.getAllCachedLayouts(),e.length){const t=new Map;for(const e of n)t.set(this.getLayoutKey(e),e);for(const r of e){const e={type:r.type,name:r.name,definition:JSON.stringify(r)},n=await this.client.saveLayout(e);t.set(this.getLayoutKey(r),n)}n=Array.from(t.values()),await this.managerCache.set(LAYOUTS_CACHE_KEY,n)}this.handleOnLayoutsChanged(n),r&&this.logger?.trace(`[${r}] request completed, layouts saved`)})}async renameLayout(e,t,r,n){return this.sequelizer.enqueue(async()=>{n&&this.logger?.trace(`[${n}] handling "renameLayout" request | oldName=${e}, newName=${t}, type=${r}`);const i=this.lastLayoutIdsByKey.get(this.getLayoutKey({name:e,type:r}));if(!i)throw new Error(`Layout with name="${e}" and type="${r}" not found.`);const o=await this.client.renameLayout(i,t),s={id:o.id,name:o.name,type:o.type,definition:o.definition};let a=await this.getAllCachedLayouts();a=a.filter(e=>e.id!==i),a.push(s),await this.managerCache.set(LAYOUTS_CACHE_KEY,a),this.setLastLayouts(a,this.parseLayouts(a));const c=this.parseLayouts([s]).map(t=>({...t,prevName:e}));this.callbacks.execute(LAYOUTS_RENAMED_EVENT_KEY,c),n&&this.logger?.trace(`[${n}] request completed, layout renamed`)})}async deleteLayout(e,t,r){return this.sequelizer.enqueue(async()=>{r&&this.logger?.trace(`[${r}] handling "deleteLayout" request | layoutName=${e}, type=${t}`);const n=this.lastLayoutIdsByKey.get(this.getLayoutKey({name:e,type:t}));if(!n)throw new Error(`Layout with name="${e}" and type="${t}" not found.`);await this.client.deleteUserLayout(n);let i=await this.getAllCachedLayouts();i=i.filter(e=>e.id!==n),await this.managerCache.set(LAYOUTS_CACHE_KEY,i),this.handleOnLayoutsChanged(i),r&&this.logger?.trace(`[${r}] request completed, layout deleted`)})}async getAllLayouts(e,t){t&&this.logger?.trace(`[${t}] handling "getAllLayouts" request | type=${e}`);const r=this.lastLayouts.filter(t=>t.type===e);return t&&this.logger?.trace(`[${t}] request completed, layouts retrieved`),r}async getLayout(e,t,r){r&&this.logger?.trace(`[${r}] handling "getLayout" request | layoutName=${e}, type=${t}`);const n=this.lastLayouts.find(r=>r.name===e&&r.type===t);return r&&this.logger?.trace(`[${r}] request completed, layout retrieved`),n}onLayoutsChanged(e){return this.callbacks.add(LAYOUTS_CHANGED_EVENT_KEY,e)}onLayoutsAdded(e){return this.callbacks.add(LAYOUTS_ADDED_EVENT_KEY,e)}onLayoutsRemoved(e){return this.callbacks.add(LAYOUTS_REMOVED_EVENT_KEY,e)}onLayoutsRenamed(e){return this.callbacks.add(LAYOUTS_RENAMED_EVENT_KEY,e)}async clearDefaultLayout(e){return this.sequelizer.enqueue(async()=>{e&&this.logger?.trace(`[${e}] handling "clearDefaultLayout" request`);const t=await this.client.setDefaultLayout();await this.managerCache.set(DEFAULT_LAYOUT_CACHE_KEY,t),e&&this.logger?.trace(`[${e}] request completed, default layout cleared`)})}async getDefaultLayout(e){return this.sequelizer.enqueue(async()=>{e&&this.logger?.trace(`[${e}] handling "getDefaultLayout" request`);const t=await this.client.getDefaultLayout();if(!t)return;const r="string"==typeof t.definition?JSON.parse(t.definition):t.definition,n=glueLayoutDecoder.run(r);if(!n.ok)throw n.error;return e&&this.logger?.trace(`[${e}] request completed, default layout retrieved`),r})}async setDefaultLayout(e,t){return this.sequelizer.enqueue(async()=>{t&&this.logger?.trace(`[${t}] handling "setDefaultLayout" request`);const r=this.lastLayoutIdsByKey.get(this.getLayoutKey({name:e,type:"Global"}));if(!r)throw new Error(`Layout with name="${e}" and type="Global" not found.`);const n=await this.client.setDefaultLayout(r);await this.managerCache.set(DEFAULT_LAYOUT_CACHE_KEY,n),t&&this.logger?.trace(`[${t}] request completed, default layout set`)})}getAllApps(){return this.lastApps}onAppsAdded(e){return this.callbacks.add(APPS_ADDED_EVENT_KEY,e)}onAppsDeleted(e){return this.callbacks.add(APPS_DELETED_EVENT_KEY,e)}onAppsChanged(e){return this.callbacks.add(APPS_CHANGED_EVENT_KEY,e)}async getPrefs(e,t){return this.config?.features?.preferencesStore?this.sequelizer.enqueue(async()=>{t&&this.logger?.trace(`[${t}] handling "getPrefs" request for app=${e}`);const r=await this.getAllCachedPrefs();let n;try{n=await this.client.getPrefs(e)}catch(e){if(!(e instanceof SanitizedIOManagerApiError&&404===e.status))throw e;n=void 0}if(n){const e=r.find(e=>e.app===n?.app);if(e&&!objEqualFast(e.data,n.data)){const e={app:n.app,prefs:this.transformPrefs(n)};this.callbacks.execute(PREFS_CHANGED_EVENT_KEY,e)}}const i=n?this.transformPrefs(n):void 0;return t&&this.logger?.trace(`[${t}] request completed, prefs retrieved`),i}):ioError.raiseError("Cannot get preferences, because the feature is not enabled")}async getAllPrefs(e){return this.config?.features?.preferencesStore?this.sequelizer.enqueue(async()=>{e&&this.logger?.trace(`[${e}] handling "getAllPrefs" request`);const t=await this.getAllCachedPrefs(),r=await this.client.getAllPrefs();this.notifyPrefs(t,r);const n=r.map(this.transformPrefs);return e&&this.logger?.trace(`[${e}] request completed, all prefs retrieved`),n}):ioError.raiseError("Cannot get all preferences, because the feature is not enabled")}async savePrefs(e,t){return this.config?.features?.preferencesStore?this.sequelizer.enqueue(async()=>{t&&this.logger?.trace(`[${t}] handling "savePrefs" request`);const r=await this.client.setPrefs({app:e.app,data:e.data,merge:!e.overwrite});await this.mergeInPreferenceCache([r]);const n={app:r.app,prefs:this.transformPrefs(r)};this.callbacks.execute(PREFS_CHANGED_EVENT_KEY,n),t&&this.logger?.trace(`[${t}] request completed, preferences saved`)}):ioError.raiseError("Cannot save preferences, because the feature is not enabled")}async clearPrefs(e,t){return this.config?.features?.preferencesStore?this.sequelizer.enqueue(async()=>{t&&this.logger?.trace(`[${t}] handling "clearPrefs" request`);const r=await Promise.all(e.map(e=>this.client.setPrefs({app:e,data:{},merge:!1})));await this.mergeInPreferenceCache(r);for(const e of r){const t={app:e.app,prefs:this.transformPrefs(e)};this.callbacks.execute(PREFS_CHANGED_EVENT_KEY,t)}t&&this.logger?.trace(`[${t}] request completed, preferences cleared`)}):ioError.raiseError("Cannot clear preferences, because the feature is not enabled")}async clearAllPrefs(e){return this.config?.features?.preferencesStore?this.sequelizer.enqueue(async()=>{e&&this.logger?.trace(`[${e}] handling "clearAllPrefs" request`);let t=await this.client.getAllPrefs();t=await Promise.all(t.map(e=>this.client.setPrefs({app:e.app,data:{},merge:!1}))),await this.managerCache.set(PREFS_CACHE_KEY,t);for(const e of t){const t={app:e.app,prefs:this.transformPrefs(e)};this.callbacks.execute(PREFS_CHANGED_EVENT_KEY,t)}e&&this.logger?.trace(`[${e}] request completed, all preferences cleared`)}):ioError.raiseError("Cannot clear all preferences, because the feature is not enabled")}clearCache(){return this.managerCache?.clear()}onPrefsChanged(e){return this.config?.features?.preferencesStore?this.callbacks.add(PREFS_CHANGED_EVENT_KEY,e):ioError.raiseError("Cannot subscribe to prefs changes, because the feature is not enabled")}handleOnLayoutsChanged(e){const t=this.parseLayouts(e);this.notifyLayouts(this.lastLayouts,t),this.setLastLayouts(e,t)}setLastLayouts(e,t){this.lastLayouts=t,this.lastLayoutIdsByKey.clear();for(const t of e)this.lastLayoutIdsByKey.set(this.getLayoutKey(t),t.id)}getLayoutKey(e){return e.name+" | "+e.type}notifyLayouts(e,t){const r=[],n=[],i=[],o=new Set(t.map(e=>e.name)),s=new Map;for(const t of e)o.has(t.name)||n.push(t),s.set(this.getLayoutKey(t),t);for(const e of t){const t=s.get(this.getLayoutKey(e));t?objEqualFast(e,t)||i.push(e):r.push(e)}r.length&&this.callbacks.execute(LAYOUTS_ADDED_EVENT_KEY,r),n.length&&this.callbacks.execute(LAYOUTS_REMOVED_EVENT_KEY,n),i.length&&this.callbacks.execute(LAYOUTS_CHANGED_EVENT_KEY,i)}parseLayouts(e){const t=e.map(e=>"string"==typeof e.definition?JSON.parse(e.definition):e.definition);return this.sanitizeLayouts(t).valid}sanitizeLayouts(e){return e.reduce((e,t)=>{const r=glueLayoutDecoder.run(t);return r.ok?e.valid.push(t):this.logger?.warn(`A layout with name: ${t.name} was not imported, because of error: ${JSON.stringify(r.error)}`),e},{valid:[]})}sanitizeApps(e){return e.reduce((e,t)=>{const r=allApplicationDefinitionsDecoder.run(t);return r.ok?e.valid.push(t):this.logger?.warn(`An app with name: ${t.name} was not imported, because of error: ${JSON.stringify(r.error)}`),e},{valid:[]})}notifyPrefs(e,t){const r=[],n=new Map;for(const t of e)n.set(t.app,t);for(const e of t){const t=n.get(e.app);t&&!objEqualFast(e.data,t.data)&&r.push(e)}for(const e of r){const t={app:e.app,prefs:this.transformPrefs(e)};this.callbacks.execute(PREFS_CHANGED_EVENT_KEY,t)}}async mergeInPreferenceCache(e){const t=await this.getAllCachedPrefs();for(const r of e){const e=t.findIndex(e=>e.app===r.app);-1!==e?t[e]=r:t.push(r)}await this.managerCache.set(PREFS_CACHE_KEY,t)}async getAllCachedPrefs(){const e=(await this.managerCache.get(PREFS_CACHE_KEY))?.value??[];for(const t of e)"string"==typeof t?.data&&(t.data=JSON.parse(t.data));return e}async getAllCachedLayouts(){return(await this.managerCache.get(LAYOUTS_CACHE_KEY))?.value??[]}handleOnConnectedStateChanged(e){const t=this.convertStateToConnectionState(e);this.connectionStateStream.push(t),this.callbacks.execute(CONNECTED_STATE_CHANGED_EVENT_KEY,t)}handleOnAppsChanged(e){let t=e;t=this.sanitizeApps(t)?.valid,this.notifyApps(this.lastApps,t),this.lastApps=t}notifyApps(e,t){const r=[],n=[],i=[],o=new Set(t.map(e=>e.name)),s=new Map;for(const t of e)o.has(t.name)||n.push(t),s.set(t.name,t);for(const e of t){const t=s.get(e.name);t?objEqualFast(e,t)||i.push(e):r.push(e)}r.length&&this.callbacks.execute(APPS_ADDED_EVENT_KEY,r),n.length&&this.callbacks.execute(APPS_DELETED_EVENT_KEY,n),i.length&&this.callbacks.execute(APPS_CHANGED_EVENT_KEY,i)}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}handleUnload(){this.unregisterInteropMethods(),this.client&&(this.callbacks.clear(),this.client.unload())}transformPrefs({app:e,data:t,lastUpdate:r}){return{app:e,data:t,lastUpdate:r}}convertErrorToDisconnectionError(e){return e?{message:e.message,name:e.name,code:e.code,status:e.status,request:e.request,isSessionExpired:e.isSessionExpired}:e}convertStateToConnectionState(e){const{disconnectionError:t,...r}=e;return{...r,disconnectionError:this.convertErrorToDisconnectionError(t)}}async registerInteropMethods(){this.logger?.info("Registering io.Manager interop methods"),await this.glueController.clientGlue.interop.register(GET_CONNECTION_STATE_METHOD_NAME,this.getConnectionState.bind(this)),await this.glueController.clientGlue.interop.register(FETCH_DATA_METHOD_NAME,this.handleFetchDataRequest.bind(this)),this.connectionStateStream=await this.glueController.clientGlue.interop.createStream(CONNECTION_STATE_STREAM_NAME,this.getConnectionStateStreamOptions())}unregisterInteropMethods(){this.logger?.info("Unregistering io.Manager interop methods"),this.glueController.clientGlue.interop.unregister(GET_CONNECTION_STATE_METHOD_NAME),this.glueController.clientGlue.interop.unregister(FETCH_DATA_METHOD_NAME),this.connectionStateStream.close()}getConnectionState(){return this.convertStateToConnectionState(this.managerConnectionState)}async handleFetchDataRequest(e){this.client&&await this.client.refreshData({applications:{include:e.applications??!1},commands:{include:e.commands??!1},layouts:{include:e.layouts??!1},configs:{include:e.configs??!1}})}getConnectionStateStreamOptions(){return{subscriptionAddedHandler:e=>{const t=this.getConnectionState();e.push(t)}}}createManagerLogger(){const e=logger.get("io-manager-connection"),t=e=>{if(e instanceof SanitizedIOManagerApiError)return JSON.stringify(e,null,2);if(e instanceof IOManagerRequestValidationError)return`${e.toString()} ${e.getZodError().toString()}`;if(e instanceof Error)return extractErrorMsg$1(e);try{return JSON.stringify(e)}catch{return"[Unable to serialize]"}},r=(e,r)=>r.length?`${e} ${r.map(t).join(" ").trim()}`:e;return{trace(t,...n){e?.canPublish("trace")&&e?.trace(r(t,n))},debug(t,...n){e?.canPublish("debug")&&e?.debug(r(t,n))},info(t,...n){e?.canPublish("info")&&e?.info(r(t,n))},warn(t,...n){e?.canPublish("warn")&&e?.warn(r(t,n))},error(t,...n){e?.canPublish("error")&&e?.error(r(t,n))},isTraceEnabled:()=>Boolean(e?.canPublish("trace")),isDebugEnabled:()=>Boolean(e?.canPublish("debug")),isInfoEnabled:()=>Boolean(e?.canPublish("info")),isWarnEnabled:()=>Boolean(e?.canPublish("warn")),isErrorEnabled:()=>Boolean(e?.canPublish("error")),isLevelEnabled:t=>Boolean(e?.canPublish(t)),log:(t,n,...i)=>{e?.canPublish(t)&&e?.log(r(n,i),t)}}}}class Identity{uaParser;glueController;pluginsController;workspacesFrameUrl;constructor(e,t,r,n){this.uaParser=e,this.glueController=t,this.pluginsController=r,this.workspacesFrameUrl=n}get logger(){return logger.get("manager.identity")}async getMachineInfo(e){const t=this.uaParser.getResult();return{user:e,name:"",os:{name:t.os.name||"",version:t.os.version||"",arch:t.cpu.architecture||""},browser:{name:t.browser.name||"",version:t.browser.version||"",engine:t.engine.name||""},mobileDevice:"mobile"===t.device?.type?{vendor:t.device.vendor,model:t.device.model}:void 0,displays:await this.getDisplays()}}getGlueInfo(){return{version:"",build:"",region:"",env:"",core:{web:{version:this.glueController.clientGlue.version},platform:{version:this.glueController.platformVersion,plugins:this.pluginsController.registeredPlugins},plus:{version:version$1}},workspaces:this.glueController.isWorkspacesEnabled?{version:this.glueController.clientGlue.workspaces?.version,frameUrl:this.workspacesFrameUrl}:void 0}}async getDisplays(){try{const{state:e}=await getWindowManagementPermissionStatus(this.logger);if("granted"!==e)return[]}catch(e){return this.logger?.warn(extractErrorMsg$1(e)),[]}return(await window.getScreenDetails()).screens.map(e=>({bounds:{x:e.left,y:e.top,width:e.width,height:e.height},workingArea:{x:e.availLeft,y:e.availTop,width:e.availWidth,height:e.availHeight},dpi:e.devicePixelRatio,isPrimary:e.isPrimary}))}}const prefsOperationTypesDecoder=oneOf$1(constant$2("operationCheck"),constant$2("clear"),constant$2("clearAll"),constant$2("get"),constant$2("getAll"),constant$2("set"),constant$2("update"),constant$2("prefsHello"),constant$2("registerSubscriber")),appPreferencesDecoder=object$2({app:nonEmptyStringDecoder$2,data:object$2(),lastUpdate:optional$3(nonEmptyStringDecoder$2)}),basePrefsConfigDecoder=object$2({app:nonEmptyStringDecoder$2}),subscriberRegisterConfigDecoder=object$2({interopId:nonEmptyStringDecoder$2,appName:optional$3(nonEmptyStringDecoder$2)}),getPrefsResultDecoder=object$2({prefs:appPreferencesDecoder}),getAllPrefsResultDecoder=object$2({all:array$3(appPreferencesDecoder)}),changePrefsDataDecoder=object$2({app:nonEmptyStringDecoder$2,data:object$2()}),prefsHelloSuccessDecoder=object$2({platform:object$2({app:nonEmptyStringDecoder$2}),validNonExistentApps:optional$3(array$3(nonEmptyStringDecoder$2)),isAppValidationEnabled:optional$3(boolean$3())});class PrefsController{glueController;localStore;managerStore;restStore;operations={operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)},clear:{name:"clear",execute:this.clear.bind(this),dataDecoder:basePrefsConfigDecoder},clearAll:{name:"clearAll",execute:this.clearAll.bind(this)},get:{name:"get",execute:this.get.bind(this),dataDecoder:basePrefsConfigDecoder,resultDecoder:getPrefsResultDecoder},getAll:{name:"getAll",execute:this.getAll.bind(this),resultDecoder:getAllPrefsResultDecoder},set:{name:"set",execute:this.set.bind(this),dataDecoder:changePrefsDataDecoder},update:{name:"update",execute:this.update.bind(this),dataDecoder:changePrefsDataDecoder},prefsHello:{name:"prefsHello",execute:this.prefsHello.bind(this),resultDecoder:prefsHelloSuccessDecoder},registerSubscriber:{name:"registerSubscriber",dataDecoder:subscriberRegisterConfigDecoder,execute:this.registerSubscriber.bind(this)}};started=!1;unsubFuncs=[];_platformAppName=`Platform-${window.location.origin}`;config;store;isAppValidationEnabled;constructor(e,t,r,n){this.glueController=e,this.localStore=t,this.managerStore=r,this.restStore=n}get logger(){return logger.get("prefs.controller")}get systemValidNonExistentApps(){return[systemPrefsAppName]}get validNonExistentApps(){const e=Array.isArray(this.config?.validNonExistentApps)?this.config.validNonExistentApps:[];return this.systemValidNonExistentApps.concat(e)}handlePlatformShutdown(){this.started=!1,this.unsubFuncs.forEach(e=>e()),this.unsubFuncs=[],this.store.stop()}get platformAppName(){return this._platformAppName}get storeType(){return this.store.type}async start(e){this.logger?.trace("initializing prefs"),this.started=!0,this.config=e.applicationPreferences,this.isAppValidationEnabled="all"!==(this.config?.validNonExistentApps??"all"),this.store=this.getStore(e),this.setupStoreListeners(),await this.store.start(e),this.logger?.trace("initialization is completed")}ready(){return Promise.resolve()}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this prefs control message, because the controller has not been started");const t=e.data,r=e.commandId,n=prefsOperationTypesDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This prefs request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`Prefs request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`Prefs request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}async registerSubscriber({interopId:e,appName:t},r){if(this.trace(`[${r}] handling registerSubscriber command with interopId: ${e}`,r),!t)return void this.trace(`[${r}] no appName provided, skipping subscriber registration.`,r);const n=this.validateApp(t);this.store.processNewSubscriber(n),this.trace(`[${r}] registerSubscriber command was executed successfully`,r)}async get({app:e},t){this.trace(`[${t}] handling get command with app: ${e}`,t);const r={app:e,data:{}};return{prefs:await this.store.getPrefs(e,t)||r}}async update({app:e,data:t},r){this.trace(`[${r}] handling update command with app: ${e} and data: ${JSON.stringify(t)}`,r);const n=this.validateApp(e);await this.store.savePrefs({app:n,data:t,overwrite:!1},r),this.trace(`[${r}] update command was executed successfully`,r)}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}async clear({app:e},t){this.trace(`[${t}] handling clear command with app: ${e}`,t);const r=this.validateApp(e);await this.store.clearPrefs([r],t),this.trace(`[${t}] clear command was executed successfully`,t)}async clearAll(e,t){this.trace(`[${t}] handling clearAll command`,t),await this.store.clearAllPrefs(t),this.trace(`[${t}] clearAll command was executed successfully`,t)}async getAll(e,t){this.trace(`[${t}] handling getAll command`,t);const r=await this.store.getAllPrefs(t);return this.trace(`[${t}] getAll command was executed successfully`,t),{all:r}}async set({app:e,data:t},r){this.trace(`[${r}] handling set command with app: ${e} and data: ${JSON.stringify(t)}`,r);const n=this.validateApp(e);await this.store.savePrefs({app:n,data:t,overwrite:!0},r),this.trace(`[${r}] set command was executed successfully`,r)}async prefsHello(){return{platform:{app:this._platformAppName},validNonExistentApps:this.validNonExistentApps,isAppValidationEnabled:this.isAppValidationEnabled}}validateApp(e){if(!this.isAppValidationEnabled)return e;const t=this.glueController.getAllApplicationNames();return e===this._platformAppName||t.includes(e)||this.validNonExistentApps.includes(e)?e:ioError.raiseError(`The provided app name "${e}" is not valid.`)}trace(e,t){t&&this.logger?.trace(e)}setupStoreListeners(){const e=this.store.onPrefsChanged(e=>{this.emitStreamData("prefsChanged",{prefs:e.prefs})});this.unsubFuncs.push(e)}emitStreamData(e,t){this.logger?.trace(`sending notification of event: ${e} with data: ${JSON.stringify(t)}`),this.glueController.pushSystemMessage("prefs",e,t)}getStore(e){const t=e.applicationPreferences?.store?.type,r=!(!e?.manager?.url||!e?.manager?.features?.preferencesStore),n=!!e?.applicationPreferences?.store?.rest?.url;return!t&&r?this.managerStore:t||r?"local"===t?this.localStore:"rest"===t&&n?this.restStore:"rest"!==t||n?"manager"===t&&r?this.managerStore:"manager"!==t||r?ioError.raiseError("Cannot set prefs store."):ioError.raiseError("The prefs store is configured to be managed, but the manager is not configured."):ioError.raiseError("The prefs store is configured to be rest, but the rest url is not configured."):this.localStore}}class IdbBasedIOManagerCache{kvStoreName="data";dbVersion=1;dbNamePrefix="IOManagerCache";logger=logger.get("io-manager-cache");config;dbName;database;data={};constructor(e,t){if(!("indexedDB"in window))throw new Error("Cannot initialize the local storage, because IndexedDB is not supported");this.config=e,this.dbName=`${this.dbNamePrefix}-${t}-${e.url}`}async get(e){const t=this.data[e];return t?(this.logger?.trace(`Read cache data for key: ${e}`),t):void this.logger?.trace(`Read cache data for key: ${e} - key not found.`)}async set(e,t){if(!this.database)throw new Error("Database not initialized.");this.logger?.trace(`Write cache data for key: ${e}`);const r=this.data[e];r?r.value=t:this.data[e]={value:t},await this.database.put(this.kvStoreName,{value:t,key:e})}async remove(e){if(!this.database)throw new Error("Database not initialized.");this.logger?.trace(`Remove cache data for key: ${e}`),delete this.data[e],await this.database.delete(this.kvStoreName,e)}async initialize(){if(this.database=await openDB(this.dbName,this.dbVersion,{upgrade:this.setUpDB.bind(this)}),this.config.cache?.clearOld)if("databases"in indexedDB){const e=(await indexedDB.databases()).filter(e=>e.name?.startsWith(this.dbNamePrefix)&&e.name!==this.dbName);for(const t of e)if(t.name)try{this.logger?.info(`Deleting cache db "${t.name}"`),await deleteDB(t.name)}catch(e){this.logger?.warn(`Failed to delete db "${t.name}". Error: ${extractErrorMsg$1(e)}`)}}else this.logger?.warn("Could not delete extraneous cache databases. This engine does not support indexedDB.databases.");await this.readFromDB()}async dispose(){this.logger?.trace(`Closing idb connection: "${this.dbName}"`),this.database?.close(),delete this.database}async clear(){await this.dispose(),this.logger?.trace(`Deleting idb database: "${this.dbName}"`),await deleteDB(this.dbName),await this.initialize()}setUpDB(e){e.objectStoreNames.contains(this.kvStoreName)||e.createObjectStore(this.kvStoreName,{keyPath:"key"})}async readFromDB(){if(!this.database)throw new Error("Database not initialized.");this.logger?.trace(`Reading from db: "${this.dbName}"`);const e=await this.database.getAll(this.kvStoreName),t={};for(const r of e)t[r.key]=r;this.data=t}}class SessionStorageBasedIOManagerCache{storageKeyPrefix="IOManagerCache";storageKey;logger=logger.get("io-manager-cache");config;data={};constructor(e,t){if(!("sessionStorage"in window))throw new Error("Cannot initialize the local storage, because sessionStorage is not supported");this.config=e,this.storageKey=`${this.storageKeyPrefix}-${t}-${e.url}`}async get(e){const t=this.data[e];return t?(this.logger?.trace(`Read cache data for key: ${e}`),t):void this.logger?.trace(`Read cache data for key: ${e} - key not found.`)}async set(e,t){this.logger?.trace(`Write cache data for key: ${e}`);const r=this.data[e];r?r.value=t:this.data[e]={value:t},this.writeToSessionStorage()}async remove(e){this.logger?.trace(`Remove cache data for key: ${e}`),delete this.data[e],this.writeToSessionStorage()}async initialize(){if(this.config.cache?.clearOld){const e=Object.keys(sessionStorage).filter(e=>e.startsWith(this.storageKeyPrefix)&&e!==this.storageKey);for(const t of e)try{this.logger?.info(`Deleting cache item "${t}"`),sessionStorage.removeItem(t)}catch(e){this.logger?.warn(`Failed to delete cache with key "${t}". Error: ${extractErrorMsg$1(e)}`)}}await this.readFromSessionStorage()}async dispose(){}async clear(){this.logger?.trace(`Deleting sessionStorage item with key "${this.storageKey}"`),sessionStorage.removeItem(this.storageKey),await this.initialize(),this.writeToSessionStorage()}async readFromSessionStorage(){let e;this.logger?.trace(`Reading sessionStorage item with key "${this.storageKey}"`);try{e=sessionStorage.getItem(this.storageKey)}catch(e){return this.logger?.warn(`Failed to read sessionStorage item with key "${this.storageKey}". ${extractErrorMsg$1(e)}`),void(this.data={})}if(!e)return this.logger?.warn(`sessionStorage item with key "${this.storageKey}" does not exist.`),void(this.data={});try{this.data=JSON.parse(e)}catch(e){this.logger?.warn(`Failed to parse json from sessionStorage item with key "${this.storageKey}". ${extractErrorMsg$1(e)}`),this.data={}}}writeToSessionStorage(){let e;this.logger?.trace(`Writing cache to sessionStorage item with key "${this.storageKey}"`);try{e=JSON.stringify(this.data)}catch(e){return void this.logger?.warn(`Failed to serialize io-manager cache. ${extractErrorMsg$1(e)}`)}try{sessionStorage.setItem(this.storageKey,e)}catch(e){this.logger?.warn(`Failed to write to sessionStorage item with key "${this.storageKey}". ${extractErrorMsg$1(e)}`)}}}let urlAlphabet="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",nanoid=(e=21)=>{let t="",r=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+=urlAlphabet[63&r[e]];return t};const otelOperationTypesDecoder=oneOf$1(constant$2("operationCheck"));class OtelController{telemetry;getNewMetricsDependencyBuilder;glueController;getPlatformController;systemController;applicationsController;layoutsController;workspacesController;serviceId=nanoid();serviceName="io.Connect Browser";fallbackLayoutName="unknown";config;platformController;started=!1;operations={operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)}};constructor(e,t,r,n,i,o,s,a){this.telemetry=e,this.getNewMetricsDependencyBuilder=t,this.glueController=r,this.getPlatformController=n,this.systemController=i,this.applicationsController=o,this.layoutsController=s,this.workspacesController=a}get logger(){return logger.get("otel.controller")}get glue(){return this.glueController.clientGlue}get metricsDependencyContainer(){const e=this.getNewMetricsDependencyBuilder();e.withInstanceStartedHandler(this.instanceStartedHandler.bind(this)).withInstanceStoppedHandler(this.instanceStoppedHandler.bind(this)).withInstanceReadyHandler(this.instanceReadyHandler.bind(this)).withInstanceFocusedHandler(this.instanceFocusedHandler.bind(this)).withInstanceErrorHandler(this.instanceErrorHandler.bind(this)).withLayoutRestoredHandler(this.layoutRestoredHandler.bind(this)).withWorkspaceStoppedHandler(this.workspaceStoppedHandler.bind(this)).withWorkspaceStartedHandler(this.workspaceStartedHandler.bind(this)).withWorkspaceSavedHandler(this.workspaceSavedHandler.bind(this)).withPlatformStartedHandler(this.platformStartedHandler.bind(this)).withPlatformErrorHandler(this.platformErrorHandler.bind(this));return e.build()}get metricsSettings(){if(!this.config.otel?.metrics)return{enabled:!1};const{additionalResourceAttributes:e,getAdditionalAttributes:t,headers:r,metrics:n,publishInterval:i=3e4,url:o}=this.config.otel.metrics,s=t?.();this.warnIfPlatformVersionAttributeIsProvided(s),this.warnIfPlatformVersionAttributeIsProvided(e);const a=n?.map(e=>({...e,enabled:e.enabled??!0,name:e.name??e.type,description:e.description??"no description"}));return{additionalResourceAttributes:e,additionalAttributes:s,enabled:!0,headers:r,metrics:a,platformMetricsEnabled:!0,publishInterval:i,url:o}}get settings(){const e=this.config.otel?.getAdditionalAttributes?.(),t=this.config.otel?.additionalResourceAttributes;return this.warnIfPlatformVersionAttributeIsProvided(e),this.warnIfPlatformVersionAttributeIsProvided(t),{additionalAttributes:e,additionalResourceAttributes:t,enabled:!!this.config.otel?.metrics,headers:this.config.otel?.headers,metrics:this.metricsSettings,platformVersion:this.glueController.platformVersion,serviceId:this.serviceId,serviceName:this.serviceName,serviceVersion:this.glueController.platformVersion,userId:this.config.user?.id}}warnIfPlatformVersionAttributeIsProvided(e){e&&"platformVersion"in e&&this.logger?.warn("The provided additional attributes override the default platform version settings.")}async start(e){this.config=e,this.shouldStartController()&&(this.platformController=this.getPlatformController(),this.logger?.trace("Starting the Otel controller."))}async configurePostStart(){if(this.shouldStartController())try{await this.telemetry.start(this.settings,this.metricsDependencyContainer),this.started=!0}catch(e){const t=extractErrorMsg$1(e);this.logger?.error(`Failed to start Otel Controller. Reason: ${t}`)}}ready(){return Promise.resolve()}async handlePlatformShutdown(){if(this.started)try{await this.telemetry.stop(),this.started=!1,this.resetMetricHandlerSubscriptionCounters()}catch(e){const t=extractErrorMsg$1(e);this.logger?.error(`Failed to stop Otel Controller. Reason: ${t}`)}}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this otel control message, because the controller has not been started");const t=e.data,r=e.commandId,n=otelOperationTypesDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This otel request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`Otel request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`Otel request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}shouldStartController(){return!!this.config.otel?.metrics?.url}incrementMetricHandlerSubscriptionCounter(e){window.testingOtel&&++window.testingOtel.metricHandlers[e].numberOfSubscriptions}resetMetricHandlerSubscriptionCounters(){window.testingOtel&&Object.values(window.testingOtel.metricHandlers).forEach(e=>{e.numberOfSubscriptions=0})}instanceStartedHandler(e){this.incrementMetricHandlerSubscriptionCounter("instanceStarted");const t=t=>{const r={application:t.application.name};if(window.testingOtel)return window.testingOtel.metricHandlers.instanceStarted.callback(r);e(r)},r=this.glue.appManager.onInstanceStarted(t);return this.glue.appManager.instances().forEach(t),r}instanceStoppedHandler(e){return this.incrementMetricHandlerSubscriptionCounter("instanceStopped"),this.glue.appManager.onInstanceStopped(t=>{const r={application:t.application.name};if(window.testingOtel)return window.testingOtel.metricHandlers.instanceStopped.callback(r);e(r)})}instanceReadyHandler(e){return this.incrementMetricHandlerSubscriptionCounter("instanceReady"),this.applicationsController.onInstanceStarted(({api:t="unknown",applicationName:r,startup:n})=>{const i={api:t,application:r,startTime:n.start,endTime:n.end};if(window.testingOtel)return window.testingOtel.metricHandlers.instanceReady.callback(i);e(i)})}instanceFocusedHandler(e){this.incrementMetricHandlerSubscriptionCounter("instanceFocused");const t=this.glue.windows.onWindowGotFocus(t=>{const r=this.glue.appManager.instances().find(e=>e.id===t.id),n={application:r?.application?.name??t.name,focused:!0};if(window.testingOtel)return window.testingOtel.metricHandlers.instanceFocused.callback(n);e(n)}),r=this.glue.windows.onWindowLostFocus(t=>{const r=this.glue.appManager.instances().find(e=>e.id===t.id),n={application:r?.application?.name??t.name,focused:!1};if(window.testingOtel)return window.testingOtel.metricHandlers.instanceFocused.callback(n);e(n)});return()=>{t(),r()}}instanceErrorHandler(e){return this.incrementMetricHandlerSubscriptionCounter("instanceError"),this.systemController.onClientError(({callerId:t})=>{const r={application:this.glueController.getAppNameByInstanceId(t??"")??"unknown"};if(window.testingOtel)return window.testingOtel.metricHandlers.instanceError.callback(r);e(r)})}layoutRestoredHandler(e){return this.incrementMetricHandlerSubscriptionCounter("layoutRestored"),this.layoutsController.onLayoutRestored(({layoutName:t,startTime:r,endTime:n})=>{const i={layout:t,startTime:r,endTime:n};if(window.testingOtel)return window.testingOtel.metricHandlers.layoutRestored.callback(i);e(i)})}workspaceStoppedHandler(e){return this.incrementMetricHandlerSubscriptionCounter("workspaceStopped"),this.workspacesController.onWorkspaceClosed(({layoutName:t})=>{const r={layout:t??this.fallbackLayoutName};if(window.testingOtel)return window.testingOtel.metricHandlers.workspaceStopped.callback(r);e(r)})}workspaceStartedHandler(e){return this.incrementMetricHandlerSubscriptionCounter("workspaceStarted"),this.workspacesController.onWorkspaceStarted(({layoutName:t})=>{const r={layout:t??this.fallbackLayoutName};if(window.testingOtel)return window.testingOtel.metricHandlers.workspaceStarted.callback(r);e(r)})}workspaceSavedHandler(e){return this.incrementMetricHandlerSubscriptionCounter("workspaceSaved"),this.workspacesController.onWorkspaceSaved(({layoutName:t,oldLayoutName:r})=>{const n={layout:t,oldLayout:r??this.fallbackLayoutName};if(window.testingOtel)return window.testingOtel.metricHandlers.workspaceSaved.callback(n);e(n)})}platformStartedHandler(e){return this.incrementMetricHandlerSubscriptionCounter("platformStarted"),this.platformController.onPlatformStarted(({platformVersion:t,startup:r})=>{const n={startTime:r.start,endTime:r.end,api:t};if(window.testingOtel)return window.testingOtel.metricHandlers.platformStarted.callback(n);e(n)})}platformErrorHandler(e){return this.incrementMetricHandlerSubscriptionCounter("platformError"),this.systemController.onPlatformError(()=>{const t={};if(window.testingOtel)return window.testingOtel.metricHandlers.platformError.callback(t);e(t)})}}class Telemetry{getNewContainerBuilder;buildLogger;container=null;constructor(e,t){this.getNewContainerBuilder=e,this.buildLogger=t}get logger(){return logger.get("otel.telemetry")}async start(e,t){if(this.container)return ioError.raiseError("An Otel container has already been started");this.logger?.trace(`Starting an Otel container with settings: ${JSON.stringify(e)}`);const r=await this.buildContainer(e,t);await r.start(),this.container=r,this.logger?.trace("The Otel container has been started successfully")}async stop(){this.container&&(await this.container.stop(),this.container=null,this.logger?.trace("The Otel container has been stopped successfully"))}async buildContainer(e,t){const r=this.getNewContainerBuilder();if(this.logger&&r.withLogger(this.buildLogger(this.logger)),r.withSettings(e),e?.metrics?.enabled){let e;try{(await Promise.resolve().then(function(){return index$2})).init(),e=!0}catch{this.logger?.warn("@interopio/insights-base plugin failed to load, insights functionality will be disabled"),e=!1}try{e&&(await Promise.resolve().then(function(){return index$1})).init()}catch{this.logger?.warn("@interopio/insights-metrics plugin failed to load, insights metrics functionality will be disabled")}r.withMetrics().withDependencyContainer(t)}return r.build()}}class LoggerAdapter{logger;logLevelMap={error:30,warn:50,info:60,debug:70,trace:80};constructor(e){this.logger=e}get level(){const e=this.logger.consoleLevel();return this.logLevelMap[e]??60}error(e,...t){const r=this.tryStringify(e,t);this.logger.error(r)}warn(e,...t){const r=this.tryStringify(e,t);this.logger.warn(r)}info(e,...t){const r=this.tryStringify(e,t);this.logger.info(r)}debug(e,...t){const r=this.tryStringify(e,t);this.logger.debug(r)}verbose(e,...t){const r=this.tryStringify(e,t);this.logger.trace(r)}tryStringify(e,t){try{return JSON.stringify(t.length?{message:e,args:t}:{message:e})}catch(t){return e}}}const defaultWidgetConfig={channels:{selector:{enable:!0,type:"default"},displayMode:"all"},position:"bottom-center",displayInWorkspace:!1,restoreLastKnownPosition:!0};class UIController{sessionStorage;glueController;started=!1;config;operations={getResources:{name:"getResources",dataDecoder:getResourcesDataDecoder,resultDecoder:getResourcesResultDecoder,execute:this.handleGetResources.bind(this)},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)},requestAlert:{name:"requestAlert",dataDecoder:uiAlertRequestMessageDecoder,execute:this.handleAlertRequest.bind(this)},requestDialog:{name:"requestDialog",dataDecoder:uiDialogRequestMessageDecoder,resultDecoder:uiDialogClientResponseDecoder,execute:this.handleDialogRequest.bind(this)},alertInteropAction:{name:"alertInteropAction",dataDecoder:alertInteropActionDataDecoder,execute:this.handleAlertInteropAction.bind(this)},getModalsStatus:{name:"getModalsStatus",resultDecoder:modalsStatusResponseDecoder,execute:this.handleGetModalsStatus.bind(this)}};clientOperations={showAlert:{name:"showAlert",execute:noop$1},showDialog:{name:"showDialog",execute:noop$1},operationCheck:{name:"operationCheck",execute:noop$1},showResolver:{name:"showResolver",execute:noop$1}};constructor(e,t){this.sessionStorage=e,this.glueController=t}async start(e){this.started=!0,this.config=e}ready(){return Promise.resolve()}async openResolver({config:e,initialCaller:t,methodResponseTimeoutMs:r,commandId:n}){this.logger?.trace(`[${n}] Handling open resolver request with config: ${JSON.stringify(e)}`);const i=this.getIntentResolverTargetInstance(t.instanceId,n);return(await this.glueController.callInstance("ui",this.clientOperations.showResolver,{config:e},{instance:i},{methodResponseTimeoutMs:r})).result}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this UI control message, because the controller has not been started");const t=e.data,r=e.commandId,n=uiOperationTypesDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This UI request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`UI request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`UI request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}get logger(){return logger.get("ui.controller")}async handleGetResources({origin:e}){return{resources:{widget:this.getWidgetResources(e),modals:this.getModalsResources(e),intentResolver:this.getIntentResolverResources(e)}}}async handleGetModalsStatus(e,t){this.logger?.trace(`[${t}] Handling get status request`);const r={status:{platformConfigured:!!this.config.modals}};return this.logger?.trace(`[${t}] Get status request was handled successfully with response: ${JSON.stringify(r)}`),r}async handleAlertRequest(e,t){if(this.logger?.trace(`[${t}] Handling alert request with config: ${JSON.stringify(e)}`),!this.config.modals)return ioError.raiseError(`[${t}] Cannot handle alert request, because modals are not configured in the platform`);const r=this.getModalsTargetInstance(e.target.instance,t,e.target.container);this.logger?.trace(`[${t}] Target instance for the alert request is: ${r}`);const{isSupported:n}=await this.glueController.checkClientOperationSupport("ui",this.clientOperations.showAlert,{instance:r});if(!n)return ioError.raiseError(`[${t}] Cannot handle alert request, because the target instance does not support the operation`);this.logger?.trace(`[${t}] Calling the showAlert operation with the provided config`),await this.glueController.callInstance("ui",this.clientOperations.showAlert,e,{instance:r}),this.logger?.trace(`[${t}] Alert request was handled successfully`)}async handleDialogRequest(e,t){if(this.logger?.trace(`[${t}] Handling dialog request with config: ${JSON.stringify(e)}`),!this.config.modals)return ioError.raiseError(`[${t}] Cannot handle dialog request, because modals are not configured in the platform`);const r=this.getModalsTargetInstance(e.target.instance,t,e.target.container);this.logger?.trace(`[${t}] Target instance for the dialog request is: ${r}`);const{isSupported:n}=await this.glueController.checkClientOperationSupport("ui",this.clientOperations.showDialog,{instance:r});if(!n)return ioError.raiseError(`[${t}] Cannot handle dialog request, because the target instance does not support the operation`);this.logger?.trace(`[${t}] Calling the showDialog operation with the provided config`);const{timer:i}=e.config,o={methodResponseTimeoutMs:i?.duration?getSafeTimeoutDelay(i.duration+DEFAULT_METHOD_RESPONSE_TIMEOUT_MS$1):MAX_SET_TIMEOUT_DELAY},s=await this.glueController.callInstance("ui",this.clientOperations.showDialog,e,{instance:r},o);return this.logger?.trace(`[${t}] Dialog request was handled successfully.`),s}getWidgetResources(e){if(!this.config?.widget)return;return checkIsOriginBlocked(e,this.config.widget.blockList)?{blockedOrigin:!0}:{blockedOrigin:!1,config:this.config?.widget?.defaultConfig||defaultWidgetConfig,sources:this.config.widget.sources}}getModalsResources(e){if(!this.config?.modals)return;return checkIsOriginBlocked(e,this.config.modals.blockList)?{blockedOrigin:!0}:{blockedOrigin:!1,sources:this.config.modals.sources}}getIntentResolverResources(e){if(!this.config?.intentResolver)return;return checkIsOriginBlocked(e,this.config.intentResolver.blockList)?{blockedOrigin:!0}:{blockedOrigin:!1,sources:this.config.intentResolver.sources}}getModalsTargetInstance(e,t,r){const n=r?this.retrieveWindowContainerInstanceId(e,r):e;return this.glueController.getLocalServers().some(e=>e.instance===n)?n:ioError.raiseError(`[${t}] Cannot handle modals request, because the target instance does not exist - ${n}`)}retrieveWindowContainerInstanceId(e,t){if("Global"===t)return ioError.raiseError(`Cannot retrieve the instance id for the client with id: ${e}, because the container type - "Global" is not supported`);const r=this.sessionStorage.getWorkspaceClientById(e);return r?r.frameId:e}async handleAlertInteropAction(e,t){this.logger?.trace(`[${t}] Handling alert interop action with config: ${JSON.stringify(e)}`);const{method:r,arguments:n,target:i}=e.interopAction.settings,o=i?this.getInteropInstanceTarget(i,t):void 0;this.logger?.trace(`[${t}] Instance target for the alert interop action is: ${JSON.stringify(o)}`),await this.glueController.invokeMethod(r,n,o)}getInteropInstanceTarget(e,t){if("best"===e||"all"===e)return e;const r=this.glueController.getLocalServers().find(t=>t.instance===e);return r||ioError.raiseError(`[${t}] No interop instance was found for the provided target ${e}.`)}getIntentResolverTargetInstance(e,t){const r=this.sessionStorage.getWorkspaceClientById(e);this.logger?.trace(`[${t}] Initial caller id '${e}' ${r?"is":"isn't"} a workspace client.`);const n=r?r.frameId:e;return this.logger?.trace(`[${t}] Target instance id for the intent resolver is: ${n}`),n}}class LocalPrefsStore{idbController;registry=CallbackRegistryFactory$2();type="local";constructor(e){this.idbController=e}async start(){}stop(){}async getPrefs(e){return await this.idbController.getPrefs(e)}async savePrefs(e){const t=e.overwrite?"setPrefs":"updatePrefs",r=await this.idbController[t]({app:e.app,data:e.data,lastUpdate:getLastUpdateTimestamp()});this.registry.execute("prefsChanged",{app:e.app,prefs:r})}async clearPrefs(e){await Promise.all(e.map(async e=>{const t=await this.idbController.setPrefs({app:e,data:{},lastUpdate:getLastUpdateTimestamp()});this.registry.execute("prefsChanged",{app:e,prefs:t})}))}async clearAllPrefs(){(await this.idbController.clearAllPrefs(getLastUpdateTimestamp())).forEach(e=>{this.registry.execute("prefsChanged",{app:e.app,prefs:e})})}async getAllPrefs(){return await this.idbController.getAllPrefs()}onPrefsChanged(e){return this.registry.add("prefsChanged",e)}processNewSubscriber(){}}class ManagerPrefsStore{managerController;type="manager";constructor(e){this.managerController=e}async start(){}stop(){}async getPrefs(e,t){return await this.managerController.getPrefs(e,t)}async savePrefs(e,t){await this.managerController.savePrefs(e,t)}async clearPrefs(e,t){await this.managerController.clearPrefs(e,t)}async clearAllPrefs(e){await this.managerController.clearAllPrefs(e)}async getAllPrefs(e){return await this.managerController.getAllPrefs(e)}onPrefsChanged(e){return this.managerController.onPrefsChanged(e)}processNewSubscriber(){}}const defaultRestHeaders={"Content-Type":"application/json",Accept:"application/json"},defaultRestRequestTimeoutMS=3e4;class RestPrefsStore{sequelizer;scheduler;cache;sessionController;type="rest";registry=CallbackRegistryFactory$2();cacheConfig;url;requestTimeout;pollingInterval;userCustomHeaders={};getUserRequestInit=()=>({});fetched={};get logger(){return logger.get("applications.prefs.rest.store")}constructor(e,t,r,n){this.sequelizer=e,this.scheduler=t,this.cache=r,this.sessionController=n}async start(e){const t=e.applicationPreferences?.store?.rest;if(!t)return ioError.raiseError("Cannot setup prefs rest store, because of missing config");if(!t.pollingInterval&&t.cache?.enabled)return ioError.raiseError("Cannot setup prefs rest store, because polling interval is not set while cache is enabled");if(t.pollingInterval&&t.pollingInterval<5e3)return ioError.raiseError("Cannot setup prefs rest store, because polling interval is set to less than 5000ms");this.url=this.getBaseUrl(t.url),this.requestTimeout=t.requestTimeout??defaultRestRequestTimeoutMS,this.userCustomHeaders=t.customHeaders??{},this.getUserRequestInit=t.getRequestInit??(()=>({})),this.pollingInterval=t.pollingInterval??0,this.cacheConfig=t.cache??{},await this.cache.start(t);const r=this.sessionController.getAllPrefsRestSchedulerCache().map(e=>e.app);this.sessionController.clearAllPrefsRestSchedulerCache(),r.forEach(e=>this.addSchedulerEntry(e))}stop(){this.cache.stop()}async getPrefs(e,t){return this.sequelizer.enqueue(async()=>{const r=this.cacheConfig.enabled,n=r&&this.fetched[e]?await this.cache.getPrefs(e):void 0;let i;try{i=n??await this.getPrefsFromServer(e,t)}catch(t){const n=r&&await this.cache.getPrefs(e);return n?(this.logger?.warn(`Failed to fetch prefs for app ${e} from server, using cached prefs: ${t}`),n):ioError.raiseError(`Failed to fetch prefs for app ${e} from server and no cached prefs available: ${t}`)}return await this.comparePrefs(i),this.addSchedulerEntry(e),await this.cache.setPrefs(i),i})}async savePrefs(e,t){return this.sequelizer.enqueue(async()=>{const r=await this.getPrefsFromServer(e.app),n=e.overwrite?{}:r.data,i=e.overwrite?{app:e.app,data:e.data}:{app:e.app,data:{...n,...e.data}},o=this.getRequest("/","POST",i),s=await fetchTimeout(o,this.requestTimeout);if(!s.ok)return ioError.raiseError(`[${t}] The POST rest for prefs for app ${e.app} returned invalid status: ${s.status}`);const a=await this.getPrefsFromServer(e.app);await this.comparePrefs(a,r),this.addSchedulerEntry(e.app),await this.cache.setPrefs(a)})}async clearPrefs(e,t){return this.sequelizer.enqueue(async()=>{await Promise.all(e.map(async e=>{await this.clearPrefsFromServer(e,t),await this.comparePrefs({app:e,data:{}}),await this.cache.clearPrefs(e)}))})}async clearAllPrefs(e){return this.sequelizer.enqueue(async()=>{const t=(await this.getAllPrefsFromServer(e)).filter(e=>Object.keys(e.data).length);for(const r of t)try{await this.clearPrefsFromServer(r.app,e),await this.comparePrefs({app:r.app,data:{}})}catch(e){this.logger?.warn(`Failed to clear prefs for app ${r.app}: ${e}`)}await this.cache.clearAllPrefs()})}async getAllPrefs(e){return this.sequelizer.enqueue(async()=>{const t=await this.getAllPrefsFromServer(e),r=await this.cache.getAllPrefs();for(const e of r){const r=t.find(t=>t.app===e.app);r&&(await this.comparePrefs(r,e),await this.cache.setPrefs(r))}return t})}onPrefsChanged(e){return this.registry.add("prefsChanged",e)}processNewSubscriber(e){this.logger?.info(`Processing new subscriber for appName: ${e}`),this.addSchedulerEntry(e)}async getAllPrefsFromServer(e){const t=this.getRequest("/all","GET"),r=await fetchTimeout(t,this.requestTimeout);if(!r.ok)return ioError.raiseError(`[${e}] The GET all rest for all prefs returned invalid status: ${r.status}`);const n=await r.json(),i=array$3(appPreferencesDecoder).run(n);return i.ok?i.result:ioError.raiseError(`[${e}] The GET all rest for all prefs returned invalid data: ${i.error}`)}async getPrefsFromServer(e,t){const r=new URLSearchParams({app:e}).toString(),n=this.getRequest(`/?${r}`,"GET"),i=await fetchTimeout(n,this.requestTimeout);if(!i.ok)return ioError.raiseError(`[${t}] The GET rest for prefs for app ${e} returned invalid status: ${i.status}`);const o=await i.json(),s=appPreferencesDecoder.run(o);return s.ok?(this.fetched[o.app]=!0,s.result):ioError.raiseError(`[${t}] The GET rest for prefs for app ${e} returned invalid data: ${s.error}`)}async clearPrefsFromServer(e,t){const r={app:e,data:{}},n=this.getRequest("/","POST",r),i=await fetchTimeout(n,this.requestTimeout);if(!i.ok)return ioError.raiseError(`[${t}] The POST rest for prefs for app ${e} returned invalid status: ${i.status}`)}async comparePrefs(e,t){const r=t??await this.cache.getPrefs(e.app);r&&JSON.stringify(r.data)===JSON.stringify(e.data)||this.registry.execute("prefsChanged",{app:e.app,prefs:e})}getRequest(e,t,r){const n=new Headers;for(const e in defaultRestHeaders)n.append(e,defaultRestHeaders[e]);for(const e in this.userCustomHeaders)n.append(e,this.userCustomHeaders[e]);const i={method:t,headers:n,mode:"cors",cache:"default",body:r?JSON.stringify(r):void 0},o=`${this.url}${e}`,s=this.getUserRequestInit({url:o,requestInit:i});return new Request(o,{...i,...s})}getBaseUrl(e){return e.endsWith("/")?e.slice(0,-1):e}addSchedulerEntry(e){if(!this.pollingInterval)return void this.logger?.info(`Polling interval is not set, skipping scheduler entry addition for app: ${e}`);const t=new URLSearchParams({app:e}).toString(),r=`prefs:get:${e}`,n={key:r,getRequest:()=>this.getRequest(`/?${t}`,"GET"),timeout:this.requestTimeout,refreshIntervalMS:this.pollingInterval,onData:this.processSchedulerGetPrefsUpdate.bind(this),onError:t=>this.logger?.error(`Error during get prefs for ${e} request:`,t)};this.scheduler.checkEntryExists(r)||(this.sessionController.savePrefsRestSchedulerCache({app:e}),this.scheduler.register(n))}processSchedulerGetPrefsUpdate(e){return this.sequelizer.enqueue(async()=>{this.fetched[e.app]=!0;const t=appPreferencesDecoder.run(e);if(!t.ok)return this.logger?.warn(`The GET rest for prefs as part of polling for app ${e.app} returned invalid data: ${t.error}`);await this.comparePrefs(t.result),await this.cache.setPrefs(t.result)})}}class LocalLayoutsStore{idbController;sessionStore;localStore;registry=CallbackRegistryFactory$2();mode="idb";get logger(){return logger.get("layouts.local.store")}constructor(e,t,r){this.idbController=e,this.sessionStore=t,this.localStore=r}async start(e){if(this.mode=e.layouts.mode,!e.layouts.local.length)return;const t=e.layouts.local.filter(e=>"Global"===e.type),r=e.layouts.local.filter(e=>"Workspace"===e.type);await Promise.all([this.localMergeImport(t,"Global"),this.localMergeImport(r,"Workspace")])}stop(){"idb"===this.mode&&(this.idbController.clearLayouts("Global").catch(e=>this.logger?.warn(extractErrorMsg$1(e))),this.idbController.clearLayouts("Workspace").catch(e=>this.logger?.warn(extractErrorMsg$1(e))))}async saveLayouts(e,t,r,n){const i="merge"===r?this.localMergeImport.bind(this):this.localReplaceImport.bind(this);this.logger?.trace(`[${n}] importing the layouts in local ${r} mode`),await Promise.all([i(t,"Global"),i(e,"Workspace")]),this.logger?.trace(`[${n}] mass import completed, responding to caller`)}async deleteLayout(e,t){await this.localDelete(e.name,e.type),await this.announceEvents({removed:[e]}),this.logger?.trace(`[${t}] layout with name "${e.name}" and type: "${e.type}" has been removed`)}async renameLayout(e,t,r){let n;try{n=await this.localRename(e,t)}catch(t){const n=extractErrorMsg$1(t);return this.logger?.trace(`[${r}] Layout named ${e.name} has not been renamed. Reason: ${n}.`),{status:n}}return await this.announceEvents({renamed:[{...n,prevName:e.name}]}),this.logger?.trace(`[${r}] Layout named ${e.name} has been renamed to ${t}.`),{status:"Success"}}async getDefaultLayout(e){const t=this.localStore.getDefaultGlobalLayoutName(),r=await this.getAll("Global");return this.logger?.trace(this.createGetDefaultGlobalLogMessage(e,t)),r.find(e=>e.name===t)}async setDefaultLayout(e,t){this.localStore.saveDefaultGlobalLayout(e),this.logger?.trace(`[${t}] request completed for global layout with name ${e}, responding to the caller`)}async clearDefaultLayout(e){this.localStore.clearDefaultGlobalLayout(),this.logger?.trace(`[${e}] request completed, responding to the caller`)}async getAllLayouts(e){return"idb"===this.mode?await this.idbController.getAllLayouts(e):this.sessionStore.getLayoutSnapshot(e).layouts}onLayoutsAdded(e){return this.registry.add("layouts-added",e)}onLayoutsChanged(e){return this.registry.add("layouts-changed",e)}onLayoutsRemoved(e){return this.registry.add("layouts-removed",e)}onLayoutsRenamed(e){return this.registry.add("layouts-renamed",e)}async localMergeImport(e,t){const r=await this.getAll(t),n=[],i=[];for(const t of e){const e=r.findIndex(e=>e.name===t.name);e>-1&&!objEqual(t,r[e])?(this.logger?.trace(`change detected at layout ${t.name}`),i.push(t),r[e]=t):e<0&&(this.logger?.trace(`new layout: ${t.name} detected, adding and announcing`),n.push(t),r.push(t))}await this.localCleanSave(r,t),await this.announceEvents({added:n,changed:i})}async localReplaceImport(e,t){const r=await this.getAll(t),n=[],i=[],o=[];for(const t of e){const e=r.findIndex(e=>e.name===t.name);e<0?(this.logger?.trace(`new layout: ${t.name} detected, adding and announcing`),n.push(t)):(objEqual(t,r[e])||(this.logger?.trace(`change detected at layout ${t.name}`),i.push(t)),r.splice(e,1))}r.forEach(e=>{this.logger?.trace(`layout ${e.name} missing, removing and announcing`),o.push(e)}),await this.localCleanSave(e,t),await this.announceEvents({added:n,changed:i,removed:o})}async localCleanSave(e,t){if("session"!==this.mode){await this.idbController.clearLayouts(t);for(const t of e)await this.idbController.storeLayout(t)}else this.sessionStore.saveLayoutSnapshot({layouts:e},t)}async localDelete(e,t){if("idb"===this.mode)return void await this.idbController.deleteLayout(e,t);const r=this.sessionStore.getLayoutSnapshot(t).layouts,n=r.findIndex(t=>t.name===e);n>-1&&r.splice(n,1),this.sessionStore.saveLayoutSnapshot({layouts:r},t)}async localRename(e,t){const r={...e,name:t};if("idb"===this.mode)return await this.idbController.renameLayout(r,e.name),r;const n=this.sessionStore.getLayoutSnapshot(e.type).layouts,i=n.findIndex(({name:t})=>t===e.name),o=-1===i?n.length:i;return n.splice(o,1,r),this.sessionStore.saveLayoutSnapshot({layouts:n},e.type),r}async getAll(e){const t="Workspace"===e?"Workspace":"Global";return"idb"===this.mode?await this.idbController.getAllLayouts(t):this.sessionStore.getLayoutSnapshot(t).layouts}updateDefaultGlobalLayoutIfNeeded(e){const t=this.localStore.getDefaultGlobalLayoutName();if(!t)return;if("removed"===e.operation&&e.layouts.some(e=>"Global"===e.type&&e.name===t))return this.localStore.clearDefaultGlobalLayout();const r="renamed"===e.operation?e.layouts.find(e=>"Global"===e.type&&e.prevName===t):void 0;return r?this.localStore.saveDefaultGlobalLayout(r.name):void 0}async announceEvents(e){const t=[];e.added?.length&&t.push(this.throttleEvents(e.added,"layouts-added")),e.changed?.length&&t.push(this.throttleEvents(e.changed,"layouts-changed")),e.removed?.length&&(this.updateDefaultGlobalLayoutIfNeeded({operation:"removed",layouts:e.removed}),t.push(this.throttleEvents(e.removed,"layouts-removed"))),e.renamed?.length&&(this.updateDefaultGlobalLayoutIfNeeded({operation:"renamed",layouts:e.renamed}),t.push(this.throttleEvents(e.renamed,"layouts-renamed"))),await Promise.all(t),await this.waitEventFlush()}async throttleEvents(e,t){let r=0;for(const n of e)++r,r%10==0&&await this.waitEventFlush(),this.registry.execute(t,[n])}createGetDefaultGlobalLogMessage(e,t){return t?`[${e}] request completed, responding to the caller with layout with name ${t}`:`[${e}] request completed, no default global layout found, responding to the caller`}waitEventFlush(){return new Promise(e=>setTimeout(e,10))}}class ManagerLayoutsStore{manager;get logger(){return logger.get("layouts.manager.store")}constructor(e){this.manager=e}async start(){}stop(){}async saveLayouts(e,t,r,n){this.logger?.trace(`[${n}] importing the layouts to manager`),await this.manager.saveLayouts([...e,...t],r,n),this.logger?.trace(`[${n}] mass import to manager completed, responding to caller`)}async deleteLayout(e,t){await this.manager.deleteLayout(e.name,e.type,t),this.logger?.trace(`[${t}] layout with name "${e.name}" and type: "${e.type}" has been removed from manager`)}async renameLayout(e,t,r){return await this.manager.renameLayout(e.name,t,e.type,r),this.logger?.trace(`[${r}] Layout named ${e.name} has been renamed to ${t} in manager.`),{status:"Success"}}async getDefaultLayout(e){this.logger?.trace(`[${e}] getting default global layout from manager`);const t=await this.manager.getDefaultLayout(e);return this.logger?.trace(this.createGetDefaultGlobalLogMessage(e,t?.name)),t}async setDefaultLayout(e,t){this.logger?.trace(`[${t}] setting default global layout in manager`),await this.manager.setDefaultLayout(e,t),this.logger?.trace(`[${t}] request completed for global layout with name ${e}, responding to the caller`)}async clearDefaultLayout(e){this.logger?.trace(`[${e}] clearing default global layout in manager`),await this.manager.clearDefaultLayout(e),this.logger?.trace(`[${e}] request completed, responding to the caller`)}async getAllLayouts(e,t){return await this.manager.getAllLayouts(e,t)}onLayoutsAdded(e){return this.manager.onLayoutsAdded(e)}onLayoutsChanged(e){return this.manager.onLayoutsChanged(e)}onLayoutsRemoved(e){return this.manager.onLayoutsRemoved(e)}onLayoutsRenamed(e){return this.manager.onLayoutsRenamed(e)}createGetDefaultGlobalLogMessage(e,t){return t?`[${e}] request completed, responding to the caller with layout with name ${t}`:`[${e}] request completed, no default global layout found, responding to the caller`}}class RestLayoutsStore{sequelizer;scheduler;cache;registry=CallbackRegistryFactory$2();cacheConfig;config;get logger(){return logger.get("layouts.rest.store")}constructor(e,t,r){this.sequelizer=e,this.scheduler=t,this.cache=r}async start(e){const t=e.layouts?.rest;if(!t)return ioError.raiseError("Cannot setup layouts rest store, because of missing config");this.config=this.prepareConfig(t),this.logger?.info(`Starting layouts rest store with config: ${JSON.stringify({...this.config,customHeaders:"omitted"})}`),this.cacheConfig=t.cache??{},await this.cache.start(t),this.logger?.trace("Finished starting layouts rest store"),await this.dataWarmUp(),this.logger?.trace("Finished data warm up"),this.configureScheduler(),this.logger?.info("Layouts rest store started")}stop(){this.cache.stop()}async getAllLayouts(e,t){return this.sequelizer.enqueue(()=>this.getAllLayoutsNoSeq(e,t))}async saveLayouts(e,t,r,n){return this.sequelizer.enqueue(async()=>{const i=[...e,...t];"replace"===r&&await this.deleteAllLayoutsFromServer(n);const o=1===i.length;for(const e of i)try{await this.saveLayoutToServer(e,n)}catch(t){if(!o){this.logger?.warn(`Failed to save layout ${e.name} type:${e.type} with error: ${t}, continuing with the rest`);continue}return ioError.raiseError(`Failed to save layout ${e.name} type:${e.type} with error: ${t}`)}const s=await this.getAllLayoutsFromServer(n);await this.processNewLayoutsSnapshot(s)})}async deleteLayout(e,t){return this.sequelizer.enqueue(async()=>{this.logger?.trace(`[${t}] Deleting layout ${e.name} type:${e.type}`);const r=this.getRequest("/layouts","DELETE",{name:e.name,type:e.type}),n=await fetchTimeout(r,this.config.requestTimeout);if(!n.ok)return ioError.raiseError(`Failed to remove layout ${e.name} and type: ${e.type}: ${n.statusText}`);this.logger?.trace(`[${t}] Removed layout ${e.name} type:${e.type}`),await this.cache.deleteLayout(e),await this.announceEvents({removed:[e]})})}async renameLayout(e,t,r){return this.sequelizer.enqueue(async()=>{this.logger?.trace(`[${r}] Renaming layout ${e.name} type:${e.type} to ${t}`);const n=this.getRequest("/layouts","PUT",{layout:e,newName:t}),i=await fetchTimeout(n,this.config.requestTimeout);return i.ok?(await this.cache.updateLayout(e,t),this.registry.execute("layouts-renamed",[{...e,name:t,prevName:e.name}]),{status:"Success"}):{status:`Failed to rename layout ${e.name} type:${e.type}: ${i.statusText}`}})}async getDefaultLayout(e){return this.sequelizer.enqueue(async()=>{this.logger?.trace(`[${e}] Getting default layout`);const t=this.getRequest("/layouts/default","GET"),r=await fetchTimeout(t,this.config.requestTimeout);if(!r.ok)return ioError.raiseError(`[${e}] The rest for get default layout returned invalid status: ${r.status}`);let n;try{n=await r.json()}catch{return void this.logger?.trace(`[${e}] No default layout found`)}if(!n?.name)return void this.logger?.trace(`[${e}] No default layout found`);const i=n.name;return(await this.getAllLayoutsNoSeq("Global",e)).find(e=>e.name===i)})}async setDefaultLayout(e,t){this.sequelizer.enqueue(async()=>{this.logger?.trace(`[${t}] Setting default layout to ${e}`);const r=this.getRequest("/layouts/default","POST",{name:e}),n=await fetchTimeout(r,this.config.requestTimeout);if(!n.ok)return ioError.raiseError(`[${t}] The rest for set default layout returned invalid status: ${n.status}`);this.logger?.trace(`[${t}] Set default layout to ${e}`)})}async clearDefaultLayout(e){this.sequelizer.enqueue(async()=>{this.logger?.trace(`[${e}] Clearing default layout`);const t=this.getRequest("/layouts/default","POST",{}),r=await fetchTimeout(t,this.config.requestTimeout);if(!r.ok)return ioError.raiseError(`[${e}] The rest for clear default layout returned invalid status: ${r.status}`);this.logger?.trace(`[${e}] Default layout cleared`)})}onLayoutsAdded(e){return this.registry.add("layouts-added",e)}onLayoutsChanged(e){return this.registry.add("layouts-changed",e)}onLayoutsRemoved(e){return this.registry.add("layouts-removed",e)}onLayoutsRenamed(e){return this.registry.add("layouts-renamed",e)}async getAllLayoutsNoSeq(e,t){const r=this.cacheConfig.enabled?await this.cache.getAllLayouts("all"):void 0;if(r?.length)return r.filter(t=>t.type===e);const n=await this.getAllLayoutsFromServer(t);return(await this.processNewLayoutsSnapshot(n)).filter(t=>t.type===e)}async getAllLayoutsFromServer(e){this.logger?.trace(`[${e}] Fetching all layouts from server`);const t=this.getRequest("/layouts","GET"),r=await fetchTimeout(t,this.config.requestTimeout);if(!r.ok)return ioError.raiseError(`[${e}] The rest for get all layouts returned invalid status: ${r.status}`);const n=await r.json();if(!n?.layouts)return ioError.raiseError(`[${e}] The rest for get all layouts returned invalid response`);return this.sanitizeLayouts(n.layouts)}async deleteAllLayoutsFromServer(e){const t=(await this.getAllLayoutsFromServer(e)).map(e=>this.getLayoutId(e.name,e.type)),r=this.getRequest("/layouts","DELETE",{ids:t}),n=await fetchTimeout(r,this.config.requestTimeout);if(!n.ok)return ioError.raiseError(`[${e}] Failed to remove all layouts: ${n.statusText}`);this.logger?.trace(`[${e}] Removed all layouts`)}async saveLayoutToServer(e,t){const r=this.getRequest("/layouts","POST",{layout:e}),n=await fetchTimeout(r,this.config.requestTimeout),i=`[${t}] Failed to save layout ${e.name} type:${e.type}: ${n.statusText}`;if(!n.ok)throw new Error(i);this.logger?.trace(`[${t}] Saved layout ${e.name} type:${e.type}`)}getBaseUrl(e){return e.endsWith("/")?e.slice(0,-1):e}getRequest(e,t,r){const n=new Headers;for(const e in defaultRestHeaders$1)n.append(e,defaultRestHeaders$1[e]);for(const e in this.config.customHeaders)n.append(e,this.config.customHeaders[e]);const i={method:t,headers:n,mode:"cors",cache:"default",body:r?JSON.stringify(r):void 0},o=`${this.config.url}${e}`,s=this.config.getRequestInit?.({url:o,requestInit:i});return new Request(o,{...i,...s})}getLayoutId(e,t){return`${e.toLowerCase()} (${t})`}sanitizeLayouts(e){return e.reduce((e,t)=>{const r=glueLayoutDecoder.run(t);return r.ok&&e.push(t),r.ok||this.logger?.warn(`A layout with name: ${t.name} was not imported, because of error: ${JSON.stringify(r.error)}`),e},[])}async executeLayoutsChangeDetection(e,t){if(!e.length)return;const r=[],n=[],i=[],o=await this.cache.getAllLayouts(t);for(const t of e){const e=o.findIndex(e=>e.name===t.name);e<0?(this.logger?.trace(`new layout: ${t.name} detected, adding and announcing`),r.push(t)):(objEqual(t,o[e])||(this.logger?.trace(`change detected at layout ${t.name}`),n.push(t)),o.splice(e,1))}o.forEach(e=>{this.logger?.trace(`layout ${e.name} missing, removing and announcing`),i.push(e)}),await this.announceEvents({added:r,changed:n,removed:i})}async announceEvents(e){const t=[];e.added?.length&&t.push(this.throttleEvents(e.added,"layouts-added")),e.changed?.length&&t.push(this.throttleEvents(e.changed,"layouts-changed")),e.removed?.length&&t.push(this.throttleEvents(e.removed,"layouts-removed")),e.renamed?.length&&t.push(this.throttleEvents(e.renamed,"layouts-renamed")),await Promise.all(t),await this.waitEventFlush()}async throttleEvents(e,t){let r=0;for(const n of e)++r,r%10==0&&await this.waitEventFlush(),this.registry.execute(t,[n])}waitEventFlush(){return new Promise(e=>setTimeout(e,10))}processSchedulerGetAllLayoutsUpdate(e){return this.sequelizer.enqueue(async()=>{this.logger?.trace("Processing scheduler get all layouts update"),await this.processNewLayoutsSnapshot(e.layouts),this.logger?.trace("Finished processing scheduler get all layouts update")})}async processNewLayoutsSnapshot(e){const t=this.sanitizeLayouts(e),r=t.filter(e=>"Workspace"===e.type),n=t.filter(e=>"Global"===e.type);return await this.executeLayoutsChangeDetection(r,"Workspace"),await this.executeLayoutsChangeDetection(n,"Global"),await this.cache.saveLayouts(t,"replace"),t}configureScheduler(){if(!this.config.pollingInterval)return void this.logger?.info("Polling interval is not set, skipping scheduler setup");const e="layouts:get:all";if(this.scheduler.checkEntryExists(e))return;const t={key:e,getRequest:()=>this.getRequest("/layouts","GET"),timeout:this.config.requestTimeout,refreshIntervalMS:this.config.pollingInterval,onData:this.processSchedulerGetAllLayoutsUpdate.bind(this),onError:e=>this.logger?.error("Error during get all layouts from scheduler",e)};this.scheduler.register(t)}async dataWarmUp(){const e=this.getAllLayoutsFromServer("start-up");if(this.config.waitInitialResponse)try{const t=await e;await this.cache.saveLayouts(t,"replace")}catch(e){return this.handleDataWarmUpFail(e)}else e.then(e=>this.cache.saveLayouts(e,"replace")).catch(e=>{const t=extractErrorMsg$1(e);this.logger?.warn(`Layouts store initial data warm up failed: ${t}`)})}prepareConfig(e){const t={...e,url:this.getBaseUrl(e.url),requestTimeout:e.requestTimeout??defaultRestRequestTimeoutMS$1,customHeaders:e.customHeaders??{},getRequestInit:e.getRequestInit??(()=>({})),waitInitialResponse:e.waitInitialResponse??!0};return t.pollingInterval&&t.pollingInterval<5e3?ioError.raiseError("Polling interval must be at least 5000ms"):t.cache?.enabled&&!t.pollingInterval?ioError.raiseError("Polling interval is required when cache is enabled"):t}async handleDataWarmUpFail(e){const t=await this.cache.getAllLayouts("all"),r=extractErrorMsg$1(e);if(!this.cacheConfig.enabled||!t.length)return ioError.raiseError(`Layouts store initial data warm up failed: ${r}`);this.logger?.warn(`Layouts store initial data warm up failed, but cache is not empty, continuing with cached data. Response error: ${r}`)}}class RestScheduler{localStorageController;entries=new Map;currentAbortControllers=new Map;_handleConnectionChange;isAppOnline=navigator.onLine;isActive=!1;schedulerLockName;constructor(e){this.localStorageController=e}start(e){if(this.isActive)return;this.entries.size?(this.schedulerLockName=`io-connect-rest-scheduler-lock-${e?.id||"public"}`,this.isActive=!0,this.setupOnlineTracker(),this.tick()):this.logger?.info("No entries registered in the RestScheduler, skipping start.")}stop(){this.isActive=!1,this.currentAbortControllers.forEach(e=>e.abort()),this.currentAbortControllers.clear(),this.entries.clear(),this.localStorageController.clearRestSchedulerEntries(),window.removeEventListener("offline",this._handleConnectionChange),window.removeEventListener("online",this._handleConnectionChange)}checkEntryExists(e){return this.entries.has(e)}register(e){if(this.checkEntryExists(e.key))return ioError.raiseError(`Request with key "${e.key}" is already registered.`);this.entries.set(e.key,e);this.localStorageController.getRestSchedulerEntry(e.key)||this.setInitialLocalStorageEntry(e)}async tick(){if(this.isActive){if(await this.waitInterval(),!this.isAppOnline)return this.isActive=!1,void this.logger?.warn("App is offline, ticking stopped.");await navigator.locks.request(this.schedulerLockName,{ifAvailable:!0},async e=>{if(e)try{await this.executeTick()}catch(e){this.logger?.error("Error during rest scheduler tick:",e)}else this.logger?.trace("The scheduler lock is already held by another process, skipping this tick.")}),this.tick()}}async executeTick(){const e=Date.now(),t=this.localStorageController.getAllRestSchedulerEntries(),r=Array.from(this.entries).reduce((r,[n,i])=>{const o=t[n];return o||(this.setInitialLocalStorageEntry(i),r.push(n)),o&&e>=o.nextRefreshAt&&r.push(n),r},[]);if(!r.length)return;const n=this.splitKeysBasedOnConcurrency(r);for(const e of n)try{const t=Promise.all(e.map(async e=>{await this.refreshKey(e)}));await t}catch(e){const t="string"==typeof e?e:JSON.stringify(e.message);this.logger?.warn(t)}}async refreshKey(e){const t=this.entries.get(e);if(!t)return ioError.raiseError(`No request registered with key "${e}".`);if(t.continuationCheck&&!t.continuationCheck())return this.logger?.trace(`Cancelling request for key "${e}" as continuation check failed.`),this.entries.delete(e),void this.localStorageController.deleteRestSchedulerEntry(e);const r=t.getRequest(),n=new AbortController;let i,o;this.currentAbortControllers.set(e,n);try{i=await fetchTimeout(r,t.timeout,n),o=Date.now()}catch(t){return this.setEntryFailure(e,Date.now())}if(!i.ok)return this.setEntryFailure(e,o,i.status);let s=null;try{s=await i.json()}catch(e){}finally{this.setEntrySuccess(e,s,o)}}setupOnlineTracker(){this._handleConnectionChange=this.handleConnectionChange.bind(this),window.addEventListener("offline",this._handleConnectionChange),window.addEventListener("online",this._handleConnectionChange)}setEntryFailure(e,t,r){this.currentAbortControllers.delete(e);const n=this.localStorageController.getRestSchedulerEntry(e),i=this.entries.get(e);if(!i)return ioError.raiseError(`No entry found for key "${e}" in local storage.`);const o=Math.ceil(250*Math.random())+t+Math.min(i.refreshIntervalMS*Math.pow(2,n?.errorCount??0),36e5),s=n?{...n,nextRefreshAt:o,errorCount:n.errorCount+1}:{key:i.key,nextRefreshAt:o,lastRefreshedAt:0,errorCount:1};this.localStorageController.saveRestSchedulerEntry(s);const a=`Request failed with status ${r||"timeout"} for key "${e}" and url "${i.getRequest().url}".`;return i.onError?.(a),ioError.raiseError(a)}setEntrySuccess(e,t,r){this.currentAbortControllers.delete(e);const n=this.localStorageController.getRestSchedulerEntry(e),i=this.entries.get(e);if(!i)return ioError.raiseError(`No entry found for key "${e}" in local storage.`);const o=r+i.refreshIntervalMS+Math.ceil(250*Math.random()),s=n?{...n,errorCount:0,lastRefreshedAt:r,nextRefreshAt:o}:{key:i.key,nextRefreshAt:o,lastRefreshedAt:r,errorCount:0};this.localStorageController.saveRestSchedulerEntry(s);try{i.onData(t)}catch(e){this.logger?.warn(`[${i.key}] Error occurred while processing data: ${e}`)}}setInitialLocalStorageEntry(e){const t={key:e.key,nextRefreshAt:Date.now()+e.refreshIntervalMS+Math.ceil(250*Math.random()),lastRefreshedAt:0,errorCount:0};this.localStorageController.saveRestSchedulerEntry(t)}splitKeysBasedOnConcurrency(e){const t=[],r=e.length;for(let n=0;n<r;n+=maxConcurrentRequestsForScheduler)t.push(e.slice(n,n+maxConcurrentRequestsForScheduler));return t}handleConnectionChange(){const e=navigator.onLine;e&&!this.isActive&&(this.isActive=!0,this.tick()),this.isAppOnline=e}waitInterval(e){return new Promise(t=>setTimeout(t,e??globalTickIntervalMSForScheduler))}get logger(){return logger.get("system.rest.scheduler")}}class PrefsRestCache{idbCacheController;allKnownPrefs=[];cacheConfig={};constructor(e){this.idbCacheController=e}async start(e){this.allKnownPrefs=[],this.cacheConfig=e.cache??{}}async stop(){this.allKnownPrefs=[]}async getPrefs(e){return this.cacheConfig.enabled?(await this.idbCacheController.getPrefs(e))?.prefs:this.allKnownPrefs.find(t=>t.app===e)}async getAllPrefs(){if(!this.cacheConfig.enabled)return this.allKnownPrefs;return(await this.idbCacheController.getAllPrefs()).map(e=>e.prefs)}async setPrefs(e){this.allKnownPrefs=this.allKnownPrefs.filter(t=>t.app!==e.app),this.allKnownPrefs.push(e),this.cacheConfig.enabled&&await this.idbCacheController.setPrefs(e,Date.now())}async clearPrefs(e){this.allKnownPrefs=this.allKnownPrefs.filter(t=>t.app!==e),this.cacheConfig.enabled&&await this.idbCacheController.deleteManyPrefs([e])}async clearAllPrefs(){this.allKnownPrefs=[],this.cacheConfig.enabled&&await this.idbCacheController.clearPrefs()}}class IdbCacheController{_database;dbName;dbVersion=1;globalLayoutsObjectStoreName="globalLayouts";prefsObjectStoreName="prefs";workspaceLayoutsObjectStoreName="workspaceLayouts";appsDefObjectStoreName="applicationDefinitions";constructor(){this.dbName=defaultCacheDBName,"indexedDB"in window||ioError.raiseError("Cannot initialize the local storage, because IndexedDB is not supported")}get database(){return this._database?this._database:ioError.raiseError("There is no open database")}async start(e){this.dbName=`${defaultCacheDBName}-${e?.id??"public"}`;const t=await openDB(this.dbName,this.dbVersion,{upgrade:this.setUpDB.bind(this)});this._database=t}stop(){this._database&&(this.database.close(),delete this._database,this.dbName=defaultCacheDBName)}async clear(){this._database&&(await this.database.clear(this.globalLayoutsObjectStoreName),await this.database.clear(this.workspaceLayoutsObjectStoreName),await this.database.clear(this.prefsObjectStoreName),await this.database.clear(this.appsDefObjectStoreName))}async deleteOtherDBs(){const e=(await indexedDB.databases()).filter(e=>e.name&&e.name!==this.dbName&&e.name.startsWith(defaultCacheDBName)).map(e=>new Promise((t,r)=>{if(!e.name)return t();const n=indexedDB.deleteDatabase(e.name);n.onerror=t=>{console.error("Error deleting database:",t),r(new Error(`Error deleting database: ${e.name}`))},n.onsuccess=()=>{t()}}));await Promise.all(e)}async getAllLayouts(e){if("all"===e){return[...(await this.database.getAll(this.globalLayoutsObjectStoreName)).map(e=>e.layout),...(await this.database.getAll(this.workspaceLayoutsObjectStoreName)).map(e=>e.layout)]}return(await this.database.getAll(this.getLayoutsObjectStoreName(e))).map(e=>e.layout)}deleteLayout(e,t){const r=this.getLayoutsObjectStoreName(t);return this.database.delete(r,e)}storeLayout(e,t,r){const n=this.getLayoutsObjectStoreName(e.type);return this.database.put(n,{layout:{...e,name:r??e.name},lastUpdated:t},e.name)}clearLayouts(e){const t=this.getLayoutsObjectStoreName(e);return this.database.clear(t)}async getPrefs(e){return this.database.get(this.prefsObjectStoreName,e)}getAllPrefs(){return this.database.getAll(this.prefsObjectStoreName)}async setPrefs(e,t){await this.database.put(this.prefsObjectStoreName,{prefs:e,lastUpdated:t},e.app)}async deleteManyPrefs(e){for(const t of e)await this.database.delete(this.prefsObjectStoreName,t)}async clearPrefs(){await this.database.clear(this.prefsObjectStoreName)}async getAllApps(){return(await this.database.getAll(this.appsDefObjectStoreName)).map(e=>e.definition)}async setApps(e,t){const r=this.database.transaction(this.appsDefObjectStoreName,"readwrite");await Promise.all([r.store.clear(),...e.map(e=>r.store.put({definition:e,lastUpdated:t},e.name)),r.done])}setUpDB(e){e.objectStoreNames.contains(this.workspaceLayoutsObjectStoreName)||e.createObjectStore(this.workspaceLayoutsObjectStoreName),e.objectStoreNames.contains(this.globalLayoutsObjectStoreName)||e.createObjectStore(this.globalLayoutsObjectStoreName),e.objectStoreNames.contains(this.prefsObjectStoreName)||e.createObjectStore(this.prefsObjectStoreName),e.objectStoreNames.contains(this.appsDefObjectStoreName)||e.createObjectStore(this.appsDefObjectStoreName)}getLayoutsObjectStoreName(e){return"Global"!==e&&"Workspace"!==e?ioError.raiseError(`Invalid layout type: ${e}`):"Global"===e?this.globalLayoutsObjectStoreName:this.workspaceLayoutsObjectStoreName}}class LayoutsRestCache{idbCacheController;allKnownLayouts=[];cacheConfig={};constructor(e){this.idbCacheController=e}async start(e){this.allKnownLayouts=[],this.cacheConfig=e.cache??{}}async stop(){this.allKnownLayouts=[]}async getAllLayouts(e){return this.cacheConfig.enabled?await this.idbCacheController.getAllLayouts(e):this.allKnownLayouts.filter(t=>"all"===e||t.type===e)}saveLayouts(e,t){return"replace"===t?this.replaceLayouts(e):this.mergeLayouts(e)}async deleteLayout(e){this.allKnownLayouts=this.allKnownLayouts.filter(t=>t.name!==e.name&&t.type!==e.type),this.cacheConfig.enabled&&await this.idbCacheController.deleteLayout(e.name,e.type)}async updateLayout(e,t){this.allKnownLayouts=this.allKnownLayouts.filter(t=>t.name!==e.name&&t.type!==e.type),this.allKnownLayouts.push({...e,name:t??e.name}),this.cacheConfig.enabled&&await this.idbCacheController.storeLayout(e,Date.now(),t)}async replaceLayouts(e){if(this.allKnownLayouts=e,this.cacheConfig.enabled){await this.idbCacheController.clearLayouts("Global"),await this.idbCacheController.clearLayouts("Workspace");for(const t of e)await this.idbCacheController.storeLayout(t,Date.now())}}async mergeLayouts(e){for(const t of e)await this.updateLayout(t)}}class AppsRestCache{idbCacheController;sessionController;cacheConfig={};constructor(e,t){this.idbCacheController=e,this.sessionController=t}async start(e){this.cacheConfig=e?.cache??{}}async getAllRemoteApps(){return this.cacheConfig.enabled?this.idbCacheController.getAllApps():this.sessionController.getAllApps("remote")}async getAllMemoryApps(){return this.sessionController.getAllApps("inmemory")}async saveMemoryApps(e){this.sessionController.overwriteApps(e,"inmemory")}async saveRemoteApps(e){return this.cacheConfig.enabled?this.idbCacheController.setApps(e,Date.now()):this.sessionController.overwriteApps(e,"remote")}async removeMemoryApp(e){return this.sessionController.removeApp(e,"inmemory")}}class RemotePlatformConfigController{remoteManagerConfig;remoteConfigsCacheController;endpointPath="/systemConfig/get";browserPlatformConfigKey="browser-platform.json";constructor(e,t){this.remoteManagerConfig=e,this.remoteConfigsCacheController=t}async getPlatformConfig(){let e;this.isCacheEnabled&&await this.remoteConfigsCacheController.start();try{e=await this.fetchRemoteConfig()}catch(e){const t=`Received error while fetching platform configuration from io.Manager: ${extractErrorMsg$1(e)}`;return this.handleConfigError(t)}if(!e.ok){const t=`Failed to fetch the platform configuration version ${this.platformConfigVersion} from io.Manager to url ${this.endpointUrl}. Status: ${e.status} ${e.statusText}`;return this.handleConfigError(t)}const t=await e.json(),r=t?.[this.browserPlatformConfigKey]?.contents;if(!r){const e=`The fetched platform configuration from io.Manager did not provide valid io.Connect Browser Platform configuration for version ${this.platformConfigVersion}`;return this.handleConfigError(e)}this.isCacheEnabled&&await this.saveConfigToCache(r);return await this.applyConfigModifications(r)}get isCacheEnabled(){return this.remoteManagerConfig.enableCache??!0}get platformConfigVersion(){return this.remoteManagerConfig.platformVersion||version$1}get fetchTimeoutMs(){return this.remoteManagerConfig.fetchTimeoutMs||3e4}get endpointUrl(){let e=this.remoteManagerConfig.managerURL;for(;e.endsWith("/");)e=e.slice(0,-1);return`${e}${this.endpointPath}`}async fetchRemoteConfig(){const e=this.getRequest();return await fetchTimeout(e,this.fetchTimeoutMs)}async fallbackToCachedConfig(){const e=await this.remoteConfigsCacheController.getPlatformConfig(this.platformConfigVersion);if(!e)return ioError.raiseError(`No cached configuration found for Platform version ${this.platformConfigVersion}. Cannot proceed without a valid io.Connect Browser configuration.`);return await this.applyConfigModifications(e)}handleConfigError(e){return this.isCacheEnabled?(console.warn(`${e}. Attempting to retrieve cached configuration.`),this.fallbackToCachedConfig()):ioError.raiseError(`${e} and caching is disabled. Cannot proceed without valid configuration.`)}async applyConfigModifications(e){return this.remoteManagerConfig.modifyConfig?this.remoteManagerConfig.modifyConfig(e):e}saveConfigToCache(e){return this.remoteConfigsCacheController.savePlatformConfig(this.platformConfigVersion,e)}getRequest(){const e={identifier:{version:this.platformConfigVersion,group:"*",user:"*"}};return new Request(this.endpointUrl,{method:"POST",headers:{"Content-Type":"application/json",Accept:"*/*"},mode:"cors",cache:"default",body:JSON.stringify(e)})}}class RemoteConfigsCacheController{dbName="remote-configs-cache";dbVersion=1;_database;platformConfigObjectStoreName="platformConfig";constructor(){"indexedDB"in window||ioError.raiseError("Cannot initialize the remote configurations cache storage, because IndexedDB is not supported")}get database(){return this._database?this._database:ioError.raiseError("There is no open remote configurations cache database")}async start(){if(this._database)return;const e=await openDB(this.dbName,this.dbVersion,{upgrade:this.setUpDB.bind(this)});this._database=e}stop(){this.database.close(),delete this._database}async clear(){this._database&&await this.database.clear(this.platformConfigObjectStoreName)}async savePlatformConfig(e,t){await this.database.put(this.platformConfigObjectStoreName,t,e)}async getPlatformConfig(e){return this.database.get(this.platformConfigObjectStoreName,e)}async setUpDB(e){e.objectStoreNames.contains(this.platformConfigObjectStoreName)||e.createObjectStore(this.platformConfigObjectStoreName)}}class IoC{_config;_remoteConfigFromManager;_gatewayInstance;_platformInstance;_mainController;_glueController;_portsBridge;_windowsController;_applicationsController;_appDirectory;_remoteWatcher;_layoutsController;_workspacesController;_hibernationWatcher;_intentsController;_legacyResolverController;_channelsController;_notificationsController;_extensionController;_sessionController;_localStorageController;_stateChecker;_framesController;_systemController;_idbController;_serviceWorkerController;_preferredConnectionController;_transactionsController;_interceptionController;_pluginsController;_domainsController;_licenseController;_layoutsBuilder;_layoutsRestorer;_layoutsValidator;_layoutsResetter;_searchController;_appsSearchRepo;_layoutsSearchRepo;_workspacesSearchRepo;_themesController;_managerController;_managerIdentity;_prefsController;_otelController;_otelTelemetry;_uiController;_localPrefsStore;_managerPrefsStore;_restPrefsStore;_localLayoutsStore;_managerLayoutsStore;_restLayoutsStore;_restScheduler;_prefsRestCache;_layoutsRestCache;_appsRestCache;_idbCacheController;_remotePlatformConfigController;_remoteConfigsCacheController;get config(){return this._config}set config(e){this._config=e}get remoteConfigFromManager(){return this._remoteConfigFromManager}set remoteConfigFromManager(e){this._remoteConfigFromManager=e}get gateway(){return this._gatewayInstance||(this._gatewayInstance=new Gateway),this._gatewayInstance}get platform(){return this._platformInstance||(this._platformInstance=new Platform(this.controller,this.sessionController,this.localStorageController,this.config)),this._platformInstance}get domainsController(){return this._domainsController||(this._domainsController=new DomainsController(this.systemController,this.windowsController,this.applicationsController,this.layoutsController,this.workspacesController,this.intentsController,this.channelsController,this.notificationsController,this.extensionController,this.searchController,this.themesController,this.managerController,this.prefsController,this.otelController,this.uiController)),this._domainsController}get controller(){return this._mainController||(this._mainController=new PlatformController(this.domainsController,this.glueController,this.portsBridge,this.stateController,this.serviceWorkerController,this.preferredConnectionController,this.interceptionController,this.pluginsController,this.sessionController,this.licenseController,this.localStorageController,this.idbController,this.idbCacheController,this.restScheduler)),this._mainController}get glueController(){return this._glueController||(this._glueController=new GlueController(this.portsBridge,this.sessionController)),this._glueController}get restScheduler(){return this._restScheduler||(this._restScheduler=new RestScheduler(this.localStorageController)),this._restScheduler}get idbCacheController(){return this._idbCacheController||(this._idbCacheController=new IdbCacheController),this._idbCacheController}get prefsRestCache(){return this._prefsRestCache||(this._prefsRestCache=new PrefsRestCache(this.idbCacheController)),this._prefsRestCache}get layoutsRestCache(){return this._layoutsRestCache||(this._layoutsRestCache=new LayoutsRestCache(this.idbCacheController)),this._layoutsRestCache}get appsRestCache(){return this._appsRestCache||(this._appsRestCache=new AppsRestCache(this.idbCacheController,this.sessionController)),this._appsRestCache}get systemController(){return this._systemController||(this._systemController=new SystemController(this.sessionController,this.workspacesController,this.glueController,this.pluginsController)),this._systemController}get searchController(){return this._searchController||(this._searchController=new SearchController(this.glueController,this.appsSearchRepo,this.layoutsSearchRepo,this.workspacesSearchRepo)),this._searchController}get uiController(){return this._uiController||(this._uiController=new UIController(this.sessionController,this.glueController)),this._uiController}get themesController(){return this._themesController||(this._themesController=new ThemesController(this.glueController,this.localStorageController,this.prefsController)),this._themesController}get sessionController(){return this._sessionController||(this._sessionController=new SessionStorageController),this._sessionController}get localStorageController(){return this._localStorageController||(this._localStorageController=new LocalStoreController),this._localStorageController}get stateController(){return this._stateChecker||(this._stateChecker=new WindowsStateController(this.sessionController)),this._stateChecker}get windowsController(){return this._windowsController||(this._windowsController=new WindowsController(this.glueController,this.sessionController,this.stateController,this)),this._windowsController}get applicationsController(){return this._applicationsController||(this._applicationsController=new ApplicationsController(this.glueController,this.sessionController,this.stateController,this.appDirectory,this.managerController,this)),this._applicationsController}get appDirectory(){return this._appDirectory||(this._appDirectory=new AppDirectory(this.remoteWatcher,this.managerController,this.appsRestCache)),this._appDirectory}get remoteWatcher(){return this._remoteWatcher||(this._remoteWatcher=new RemoteWatcher(this.restScheduler)),this._remoteWatcher}get licenseController(){return this._licenseController||(this._licenseController=new LicenseController),this._licenseController}get localLayoutsStore(){return this._localLayoutsStore||(this._localLayoutsStore=new LocalLayoutsStore(this.idbController,this.sessionController,this.localStorageController)),this._localLayoutsStore}get managerLayoutsStore(){return this._managerLayoutsStore||(this._managerLayoutsStore=new ManagerLayoutsStore(this.managerController)),this._managerLayoutsStore}get restLayoutsStore(){return this._restLayoutsStore||(this._restLayoutsStore=new RestLayoutsStore(this.createSequelizer(),this.restScheduler,this.layoutsRestCache)),this._restLayoutsStore}get layoutsController(){return this._layoutsController||(this._layoutsController=new LayoutsController(this.glueController,this.layoutsBuilder,this.layoutsRestorer,this.localLayoutsStore,this.managerLayoutsStore,this.restLayoutsStore,this.sessionController)),this._layoutsController}get workspacesController(){return this._workspacesController||(this._workspacesController=new WorkspacesController(this.framesController,this.glueController,this.stateController,this.hibernationWatcher,this.createSequelizer(),this.sessionController,this)),this._workspacesController}get hibernationWatcher(){return this._hibernationWatcher||(this._hibernationWatcher=new WorkspaceHibernationWatcher(this.sessionController,this.createSequelizer())),this._hibernationWatcher}get intentsController(){return this._intentsController||(this._intentsController=new IntentsController(this.glueController,this.legacyResolverController,this.appDirectory,this.windowsController,this.prefsController,this.uiController)),this._intentsController}get legacyResolverController(){return this._legacyResolverController||(this._legacyResolverController=new LegacyResolverController(this.glueController,this.workspacesController,this.windowsController,this.prefsController)),this._legacyResolverController}get channelsController(){return this._channelsController||(this._channelsController=new ChannelsController(this.glueController,this.sessionController,this.workspacesController)),this._channelsController}get extensionController(){return this._extensionController||(this._extensionController=new ExtensionController(this.sessionController)),this._extensionController}get layoutsBuilder(){return this._layoutsBuilder||(this._layoutsBuilder=new Builder(this.glueController,this.sessionController,this.windowsController,this.workspacesController)),this._layoutsBuilder}get layoutsRestorer(){return this._layoutsRestorer||(this._layoutsRestorer=new Restorer(this.glueController,this.layoutsValidator,this.layoutsResetter,this.workspacesController,this.sessionController)),this._layoutsRestorer}get layoutsValidator(){return this._layoutsValidator||(this._layoutsValidator=new LayoutValidator(this.glueController,this.workspacesController)),this._layoutsValidator}get layoutsResetter(){return this._layoutsResetter||(this._layoutsResetter=new Resetter(this.glueController,this.workspacesController)),this._layoutsResetter}get notificationsController(){return this._notificationsController||(this._notificationsController=new NotificationsController(this.glueController,this.serviceWorkerController,this.sessionController,this.localStorageController,this.prefsController)),this._notificationsController}get framesController(){return this._framesController||(this._framesController=new FramesController(this.sessionController,this.glueController,this)),this._framesController}get idbController(){return this._idbController||(this._idbController=new IDBController),this._idbController}get portsBridge(){return this._portsBridge||(this._portsBridge=new PortsBridge(this.gateway,this.sessionController,this.stateController,this)),this._portsBridge}get serviceWorkerController(){return this._serviceWorkerController||(this._serviceWorkerController=new ServiceWorkerController(this.idbController)),this._serviceWorkerController}get transactionsController(){return this._transactionsController||(this._transactionsController=new TransactionsController),this._transactionsController}get interceptionController(){return this._interceptionController||(this._interceptionController=new InterceptionController),this._interceptionController}get pluginsController(){return this._pluginsController||(this._pluginsController=new PluginsController(this.interceptionController,this.glueController)),this._pluginsController}get appsSearchRepo(){return this._appsSearchRepo||(this._appsSearchRepo=new ApplicationsRepository(this.glueController)),this._appsSearchRepo}get managerController(){return this._managerController||(this._managerController=new ManagerController(this.managerIdentity,this.glueController,this.createSequelizer(),this.buildClient.bind(this),this.buildCache.bind(this))),this._managerController}get managerIdentity(){return this._managerIdentity||(this._managerIdentity=new Identity(new uaParserExports.UAParser,this.glueController,this.pluginsController,this.config?.workspaces?.src)),this._managerIdentity}get layoutsSearchRepo(){return this._layoutsSearchRepo||(this._layoutsSearchRepo=new LayoutsRepository(this.glueController)),this._layoutsSearchRepo}get workspacesSearchRepo(){return this._workspacesSearchRepo||(this._workspacesSearchRepo=new WorkspacesRepository(this.glueController)),this._workspacesSearchRepo}get preferredConnectionController(){return this._preferredConnectionController||(this._preferredConnectionController=new PreferredConnectionController(this.glueController,this.portsBridge,this.createSequelizer())),this._preferredConnectionController}get localPrefsStore(){return this._localPrefsStore||(this._localPrefsStore=new LocalPrefsStore(this.idbController)),this._localPrefsStore}get managerPrefsStore(){return this._managerPrefsStore||(this._managerPrefsStore=new ManagerPrefsStore(this.managerController)),this._managerPrefsStore}get restPrefsStore(){return this._restPrefsStore||(this._restPrefsStore=new RestPrefsStore(this.createSequelizer(),this.restScheduler,this.prefsRestCache,this.sessionController)),this._restPrefsStore}get prefsController(){return this._prefsController||(this._prefsController=new PrefsController(this.glueController,this.localPrefsStore,this.managerPrefsStore,this.restPrefsStore)),this._prefsController}get otelController(){return this._otelController||(this._otelController=new OtelController(this.otelTelemetry,this.getNewMetricsDependencyBuilder.bind(this),this.glueController,this.getPlatformController.bind(this),this.systemController,this.applicationsController,this.layoutsController,this.workspacesController)),this._otelController}get remotePlatformConfigController(){if(!this.remoteConfigFromManager)throw new Error("Cannot initialize RemotePlatformConfigController because RemoteConfigFromManager is not set");return this._remotePlatformConfigController||(this._remotePlatformConfigController=new RemotePlatformConfigController(this.remoteConfigFromManager,this.remoteConfigsCacheController)),this._remotePlatformConfigController}get remoteConfigsCacheController(){return this._remoteConfigsCacheController||(this._remoteConfigsCacheController=new RemoteConfigsCacheController),this._remoteConfigsCacheController}createMessageChannel(){return new MessageChannel}createSequelizer(e){return new AsyncSequelizer(e)}buildClient(e){return new CachedClientAPI(e)}buildCache(e,t){return e.cache?.enabled??1?new IdbBasedIOManagerCache(e,t):new SessionStorageBasedIOManagerCache(e,t)}getPlatformController(){return this.controller}getNewMetricsDependencyBuilder(){return new distExports$1.MetricsDependencyBuilder}getNewOtelContainerBuilder(){return new distExports$1.Builder}buildOtelLogger(e){return new LoggerAdapter(e)}get otelTelemetry(){return this._otelTelemetry||(this._otelTelemetry=new Telemetry(this.getNewOtelContainerBuilder.bind(this),this.buildOtelLogger.bind(this))),this._otelTelemetry}}let platformCache;const checkSingleton=()=>{const e=window.glue42core||window.iobrowser;if(e?.platformStarted)throw new Error("The Glue42 Core Platform has already been started for this application.")},initPlatformApi=async e=>{await e.platform.ready();return{io:e.platform.getClientGlue(),platform:e?.platform.getPlatformApi()}},setupPlatformConfig=async(e,t)=>{"manager"===t?.type?(e.remoteConfigFromManager=remoteConfigFromManagerDecoder.runWithException(t),e.config=await e.remotePlatformConfigController.getPlatformConfig()):e.config=t},ioConnectBrowserPlatformFactory=async e=>{const t=new IoC;await setupPlatformConfig(t,e);if(window.glue42gd||window.iodesktop)return fallbackToEnterprise(t.config);const r=!t.config?.connection?.alwaysPlatform&&await checkIsOpenerIOConnect(t.config?.connection),n=checkIfPlacedInWorkspace();if(t.config?.clientOnly||r||n){return{io:t.config?.browserFactory?await(t.config?.browserFactory(t.config?.browser)):await iOConnectBrowserFactory(t.config?.browser)}}try{checkSingleton()}catch(e){return void 0===platformCache?Promise.reject(new Error(e)):platformCache}const i=initPlatformApi(t);return t.config?.browser?.memoizeAPI&&(platformCache=i),i};"undefined"!=typeof window&&(window.IOBrowserPlatform=ioConnectBrowserPlatformFactory);const legacyGlobal=window.glue42gd||window.glue42core,ioGlobal=window.iodesktop||window.iobrowser;legacyGlobal||ioGlobal||(window.iobrowser={webStarted:!1});var dist$2={};const VERSION$4="1.9.1",re=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function _makeCompatibilityCheck(e){const t=new Set([e]),r=new Set,n=e.match(re);if(!n)return()=>!1;const i=+n[1],o=+n[2],s=+n[3];if(null!=n[4])return function(t){return t===e};function a(e){return r.add(e),!1}function c(e){return t.add(e),!0}return function(e){if(t.has(e))return!0;if(r.has(e))return!1;const n=e.match(re);if(!n)return a(e);const l=+n[1],u=+n[2],d=+n[3];return null!=n[4]||i!==l?a(e):0===i?o===u&&s<=d?c(e):a(e):o<=u?c(e):a(e)}}const isCompatible=_makeCompatibilityCheck(VERSION$4),major=VERSION$4.split(".")[0],GLOBAL_OPENTELEMETRY_API_KEY=Symbol.for(`opentelemetry.js.api.${major}`),_global="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof global?global:{};function registerGlobal(e,t,r,n=!1){var i;const o=_global[GLOBAL_OPENTELEMETRY_API_KEY]=null!==(i=_global[GLOBAL_OPENTELEMETRY_API_KEY])&&void 0!==i?i:{version:VERSION$4};if(!n&&o[e]){const t=new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${e}`);return r.error(t.stack||t.message),!1}if(o.version!==VERSION$4){const t=new Error(`@opentelemetry/api: Registration of version v${o.version} for ${e} does not match previously registered API v${VERSION$4}`);return r.error(t.stack||t.message),!1}return o[e]=t,r.debug(`@opentelemetry/api: Registered a global for ${e} v${VERSION$4}.`),!0}function getGlobal(e){var t,r;const n=null===(t=_global[GLOBAL_OPENTELEMETRY_API_KEY])||void 0===t?void 0:t.version;if(n&&isCompatible(n))return null===(r=_global[GLOBAL_OPENTELEMETRY_API_KEY])||void 0===r?void 0:r[e]}function unregisterGlobal(e,t){t.debug(`@opentelemetry/api: Unregistering a global for ${e} v${VERSION$4}.`);const r=_global[GLOBAL_OPENTELEMETRY_API_KEY];r&&delete r[e]}class DiagComponentLogger{constructor(e){this._namespace=e.namespace||"DiagComponentLogger"}debug(...e){return logProxy("debug",this._namespace,e)}error(...e){return logProxy("error",this._namespace,e)}info(...e){return logProxy("info",this._namespace,e)}warn(...e){return logProxy("warn",this._namespace,e)}verbose(...e){return logProxy("verbose",this._namespace,e)}}function logProxy(e,t,r){const n=getGlobal("diag");if(n)return n[e](t,...r)}var DiagLogLevel;function createLogLevelDiagLogger(e,t){function r(r,n){const i=t[r];return"function"==typeof i&&e>=n?i.bind(t):function(){}}return e<DiagLogLevel.NONE?e=DiagLogLevel.NONE:e>DiagLogLevel.ALL&&(e=DiagLogLevel.ALL),t=t||{},{error:r("error",DiagLogLevel.ERROR),warn:r("warn",DiagLogLevel.WARN),info:r("info",DiagLogLevel.INFO),debug:r("debug",DiagLogLevel.DEBUG),verbose:r("verbose",DiagLogLevel.VERBOSE)}}!function(e){e[e.NONE=0]="NONE",e[e.ERROR=30]="ERROR",e[e.WARN=50]="WARN",e[e.INFO=60]="INFO",e[e.DEBUG=70]="DEBUG",e[e.VERBOSE=80]="VERBOSE",e[e.ALL=9999]="ALL"}(DiagLogLevel||(DiagLogLevel={}));const API_NAME$4="diag";class DiagAPI{static instance(){return this._instance||(this._instance=new DiagAPI),this._instance}constructor(){function e(e){return function(...t){const r=getGlobal("diag");if(r)return r[e](...t)}}const t=this;t.setLogger=(e,r={logLevel:DiagLogLevel.INFO})=>{var n,i,o;if(e===t){const e=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return t.error(null!==(n=e.stack)&&void 0!==n?n:e.message),!1}"number"==typeof r&&(r={logLevel:r});const s=getGlobal("diag"),a=createLogLevelDiagLogger(null!==(i=r.logLevel)&&void 0!==i?i:DiagLogLevel.INFO,e);if(s&&!r.suppressOverrideMessage){const e=null!==(o=(new Error).stack)&&void 0!==o?o:"<failed to generate stacktrace>";s.warn(`Current logger will be overwritten from ${e}`),a.warn(`Current logger will overwrite one already registered from ${e}`)}return registerGlobal("diag",a,t,!0)},t.disable=()=>{unregisterGlobal(API_NAME$4,t)},t.createComponentLogger=e=>new DiagComponentLogger(e),t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}}class BaggageImpl{constructor(e){this._entries=e?new Map(e):new Map}getEntry(e){const t=this._entries.get(e);if(t)return Object.assign({},t)}getAllEntries(){return Array.from(this._entries.entries())}setEntry(e,t){const r=new BaggageImpl(this._entries);return r._entries.set(e,t),r}removeEntry(e){const t=new BaggageImpl(this._entries);return t._entries.delete(e),t}removeEntries(...e){const t=new BaggageImpl(this._entries);for(const r of e)t._entries.delete(r);return t}clear(){return new BaggageImpl}}const baggageEntryMetadataSymbol=Symbol("BaggageEntryMetadata"),diag$1=DiagAPI.instance();function createBaggage(e={}){return new BaggageImpl(new Map(Object.entries(e)))}function baggageEntryMetadataFromString(e){return"string"!=typeof e&&(diag$1.error("Cannot create baggage metadata from unknown type: "+typeof e),e=""),{__TYPE__:baggageEntryMetadataSymbol,toString:()=>e}}function createContextKey(e){return Symbol.for(e)}class BaseContext{constructor(e){const t=this;t._currentContext=e?new Map(e):new Map,t.getValue=e=>t._currentContext.get(e),t.setValue=(e,r)=>{const n=new BaseContext(t._currentContext);return n._currentContext.set(e,r),n},t.deleteValue=e=>{const r=new BaseContext(t._currentContext);return r._currentContext.delete(e),r}}}const ROOT_CONTEXT=new BaseContext,consoleMap=[{n:"error",c:"error"},{n:"warn",c:"warn"},{n:"info",c:"info"},{n:"debug",c:"debug"},{n:"verbose",c:"trace"}],_originalConsoleMethods={};if("undefined"!=typeof console){const e=["error","warn","info","debug","trace","log"];for(const t of e)"function"==typeof console[t]&&(_originalConsoleMethods[t]=console[t])}class DiagConsoleLogger{constructor(){function e(e){return function(...t){let r=_originalConsoleMethods[e];if("function"!=typeof r&&(r=_originalConsoleMethods.log),"function"!=typeof r&&console&&(r=console[e],"function"!=typeof r&&(r=console.log)),"function"==typeof r)return r.apply(console,t)}}for(let t=0;t<consoleMap.length;t++)this[consoleMap[t].n]=e(consoleMap[t].c)}}class NoopMeter{constructor(){}createGauge(e,t){return NOOP_GAUGE_METRIC}createHistogram(e,t){return NOOP_HISTOGRAM_METRIC}createCounter(e,t){return NOOP_COUNTER_METRIC}createUpDownCounter(e,t){return NOOP_UP_DOWN_COUNTER_METRIC}createObservableGauge(e,t){return NOOP_OBSERVABLE_GAUGE_METRIC}createObservableCounter(e,t){return NOOP_OBSERVABLE_COUNTER_METRIC}createObservableUpDownCounter(e,t){return NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC}addBatchObservableCallback(e,t){}removeBatchObservableCallback(e){}}class NoopMetric{}class NoopCounterMetric extends NoopMetric{add(e,t){}}class NoopUpDownCounterMetric extends NoopMetric{add(e,t){}}class NoopGaugeMetric extends NoopMetric{record(e,t){}}class NoopHistogramMetric extends NoopMetric{record(e,t){}}class NoopObservableMetric{addCallback(e){}removeCallback(e){}}class NoopObservableCounterMetric extends NoopObservableMetric{}class NoopObservableGaugeMetric extends NoopObservableMetric{}class NoopObservableUpDownCounterMetric extends NoopObservableMetric{}const NOOP_METER=new NoopMeter,NOOP_COUNTER_METRIC=new NoopCounterMetric,NOOP_GAUGE_METRIC=new NoopGaugeMetric,NOOP_HISTOGRAM_METRIC=new NoopHistogramMetric,NOOP_UP_DOWN_COUNTER_METRIC=new NoopUpDownCounterMetric,NOOP_OBSERVABLE_COUNTER_METRIC=new NoopObservableCounterMetric,NOOP_OBSERVABLE_GAUGE_METRIC=new NoopObservableGaugeMetric,NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC=new NoopObservableUpDownCounterMetric;function createNoopMeter(){return NOOP_METER}var ValueType;!function(e){e[e.INT=0]="INT",e[e.DOUBLE=1]="DOUBLE"}(ValueType||(ValueType={}));const defaultTextMapGetter={get(e,t){if(null!=e)return e[t]},keys:e=>null==e?[]:Object.keys(e)},defaultTextMapSetter={set(e,t,r){null!=e&&(e[t]=r)}};class NoopContextManager{active(){return ROOT_CONTEXT}with(e,t,r,...n){return t.call(r,...n)}bind(e,t){return t}enable(){return this}disable(){return this}}const API_NAME$3="context",NOOP_CONTEXT_MANAGER=new NoopContextManager;class ContextAPI{constructor(){}static getInstance(){return this._instance||(this._instance=new ContextAPI),this._instance}setGlobalContextManager(e){return registerGlobal(API_NAME$3,e,DiagAPI.instance())}active(){return this._getContextManager().active()}with(e,t,r,...n){return this._getContextManager().with(e,t,r,...n)}bind(e,t){return this._getContextManager().bind(e,t)}_getContextManager(){return getGlobal(API_NAME$3)||NOOP_CONTEXT_MANAGER}disable(){this._getContextManager().disable(),unregisterGlobal(API_NAME$3,DiagAPI.instance())}}var TraceFlags;!function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"}(TraceFlags||(TraceFlags={}));const INVALID_SPANID="0000000000000000",INVALID_TRACEID="00000000000000000000000000000000",INVALID_SPAN_CONTEXT={traceId:INVALID_TRACEID,spanId:INVALID_SPANID,traceFlags:TraceFlags.NONE};class NonRecordingSpan{constructor(e=INVALID_SPAN_CONTEXT){this._spanContext=e}spanContext(){return this._spanContext}setAttribute(e,t){return this}setAttributes(e){return this}addEvent(e,t){return this}addLink(e){return this}addLinks(e){return this}setStatus(e){return this}updateName(e){return this}end(e){}isRecording(){return!1}recordException(e,t){}}const SPAN_KEY=createContextKey("OpenTelemetry Context Key SPAN");function getSpan(e){return e.getValue(SPAN_KEY)||void 0}function getActiveSpan(){return getSpan(ContextAPI.getInstance().active())}function setSpan(e,t){return e.setValue(SPAN_KEY,t)}function deleteSpan(e){return e.deleteValue(SPAN_KEY)}function setSpanContext(e,t){return setSpan(e,new NonRecordingSpan(t))}function getSpanContext(e){var t;return null===(t=getSpan(e))||void 0===t?void 0:t.spanContext()}const isHex=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1]);function isValidHex(e,t){if("string"!=typeof e||e.length!==t)return!1;let r=0;for(let t=0;t<e.length;t+=4)r+=(0|isHex[e.charCodeAt(t)])+(0|isHex[e.charCodeAt(t+1)])+(0|isHex[e.charCodeAt(t+2)])+(0|isHex[e.charCodeAt(t+3)]);return r===t}function isValidTraceId(e){return isValidHex(e,32)&&e!==INVALID_TRACEID}function isValidSpanId(e){return isValidHex(e,16)&&e!==INVALID_SPANID}function isSpanContextValid(e){return isValidTraceId(e.traceId)&&isValidSpanId(e.spanId)}function wrapSpanContext(e){return new NonRecordingSpan(e)}const contextApi=ContextAPI.getInstance();class NoopTracer{startSpan(e,t,r=contextApi.active()){if(Boolean(null==t?void 0:t.root))return new NonRecordingSpan;const n=r&&getSpanContext(r);return isSpanContext(n)&&isSpanContextValid(n)?new NonRecordingSpan(n):new NonRecordingSpan}startActiveSpan(e,t,r,n){let i,o,s;if(arguments.length<2)return;2===arguments.length?s=t:3===arguments.length?(i=t,s=r):(i=t,o=r,s=n);const a=null!=o?o:contextApi.active(),c=this.startSpan(e,i,a),l=setSpan(a,c);return contextApi.with(l,s,void 0,c)}}function isSpanContext(e){return null!==e&&"object"==typeof e&&"spanId"in e&&"string"==typeof e.spanId&&"traceId"in e&&"string"==typeof e.traceId&&"traceFlags"in e&&"number"==typeof e.traceFlags}const NOOP_TRACER=new NoopTracer;class ProxyTracer{constructor(e,t,r,n){this._provider=e,this.name=t,this.version=r,this.options=n}startSpan(e,t,r){return this._getTracer().startSpan(e,t,r)}startActiveSpan(e,t,r,n){const i=this._getTracer();return Reflect.apply(i.startActiveSpan,i,arguments)}_getTracer(){if(this._delegate)return this._delegate;const e=this._provider.getDelegateTracer(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):NOOP_TRACER}}class NoopTracerProvider{getTracer(e,t,r){return new NoopTracer}}const NOOP_TRACER_PROVIDER=new NoopTracerProvider;class ProxyTracerProvider{getTracer(e,t,r){var n;return null!==(n=this.getDelegateTracer(e,t,r))&&void 0!==n?n:new ProxyTracer(this,e,t,r)}getDelegate(){var e;return null!==(e=this._delegate)&&void 0!==e?e:NOOP_TRACER_PROVIDER}setDelegate(e){this._delegate=e}getDelegateTracer(e,t,r){var n;return null===(n=this._delegate)||void 0===n?void 0:n.getTracer(e,t,r)}}var SamplingDecision$1,SpanKind,SpanStatusCode;!function(e){e[e.NOT_RECORD=0]="NOT_RECORD",e[e.RECORD=1]="RECORD",e[e.RECORD_AND_SAMPLED=2]="RECORD_AND_SAMPLED"}(SamplingDecision$1||(SamplingDecision$1={})),function(e){e[e.INTERNAL=0]="INTERNAL",e[e.SERVER=1]="SERVER",e[e.CLIENT=2]="CLIENT",e[e.PRODUCER=3]="PRODUCER",e[e.CONSUMER=4]="CONSUMER"}(SpanKind||(SpanKind={})),function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"}(SpanStatusCode||(SpanStatusCode={}));const VALID_KEY_CHAR_RANGE$1="[_0-9a-z-*/]",VALID_KEY$1=`[a-z]${VALID_KEY_CHAR_RANGE$1}{0,255}`,VALID_VENDOR_KEY$1=`[a-z0-9]${VALID_KEY_CHAR_RANGE$1}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE$1}{0,13}`,VALID_KEY_REGEX$1=new RegExp(`^(?:${VALID_KEY$1}|${VALID_VENDOR_KEY$1})$`),VALID_VALUE_BASE_REGEX$1=/^[ -~]{0,255}[!-~]$/,INVALID_VALUE_COMMA_EQUAL_REGEX$1=/,|=/;function validateKey$1(e){return VALID_KEY_REGEX$1.test(e)}function validateValue$1(e){return VALID_VALUE_BASE_REGEX$1.test(e)&&!INVALID_VALUE_COMMA_EQUAL_REGEX$1.test(e)}const MAX_TRACE_STATE_ITEMS$1=32,MAX_TRACE_STATE_LEN$1=512,LIST_MEMBERS_SEPARATOR$1=",",LIST_MEMBER_KEY_VALUE_SPLITTER$1="=";class TraceStateImpl{constructor(e){this._internalState=new Map,e&&this._parse(e)}set(e,t){const r=this._clone();return r._internalState.has(e)&&r._internalState.delete(e),r._internalState.set(e,t),r}unset(e){const t=this._clone();return t._internalState.delete(e),t}get(e){return this._internalState.get(e)}serialize(){return Array.from(this._internalState.keys()).reduceRight((e,t)=>(e.push(t+LIST_MEMBER_KEY_VALUE_SPLITTER$1+this.get(t)),e),[]).join(LIST_MEMBERS_SEPARATOR$1)}_parse(e){e.length>MAX_TRACE_STATE_LEN$1||(this._internalState=e.split(LIST_MEMBERS_SEPARATOR$1).reduceRight((e,t)=>{const r=t.trim(),n=r.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER$1);if(-1!==n){const i=r.slice(0,n),o=r.slice(n+1,t.length);validateKey$1(i)&&validateValue$1(o)&&e.set(i,o)}return e},new Map),this._internalState.size>MAX_TRACE_STATE_ITEMS$1&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,MAX_TRACE_STATE_ITEMS$1))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){const e=new TraceStateImpl;return e._internalState=new Map(this._internalState),e}}function createTraceState(e){return new TraceStateImpl(e)}const context=ContextAPI.getInstance(),diag=DiagAPI.instance();class NoopMeterProvider{getMeter(e,t,r){return NOOP_METER}}const NOOP_METER_PROVIDER=new NoopMeterProvider,API_NAME$2="metrics";class MetricsAPI{constructor(){}static getInstance(){return this._instance||(this._instance=new MetricsAPI),this._instance}setGlobalMeterProvider(e){return registerGlobal(API_NAME$2,e,DiagAPI.instance())}getMeterProvider(){return getGlobal(API_NAME$2)||NOOP_METER_PROVIDER}getMeter(e,t,r){return this.getMeterProvider().getMeter(e,t,r)}disable(){unregisterGlobal(API_NAME$2,DiagAPI.instance())}}const metrics=MetricsAPI.getInstance();class NoopTextMapPropagator{inject(e,t){}extract(e,t){return e}fields(){return[]}}const BAGGAGE_KEY=createContextKey("OpenTelemetry Baggage Key");function getBaggage(e){return e.getValue(BAGGAGE_KEY)||void 0}function getActiveBaggage(){return getBaggage(ContextAPI.getInstance().active())}function setBaggage(e,t){return e.setValue(BAGGAGE_KEY,t)}function deleteBaggage(e){return e.deleteValue(BAGGAGE_KEY)}const API_NAME$1="propagation",NOOP_TEXT_MAP_PROPAGATOR=new NoopTextMapPropagator;class PropagationAPI{constructor(){this.createBaggage=createBaggage,this.getBaggage=getBaggage,this.getActiveBaggage=getActiveBaggage,this.setBaggage=setBaggage,this.deleteBaggage=deleteBaggage}static getInstance(){return this._instance||(this._instance=new PropagationAPI),this._instance}setGlobalPropagator(e){return registerGlobal(API_NAME$1,e,DiagAPI.instance())}inject(e,t,r=defaultTextMapSetter){return this._getGlobalPropagator().inject(e,t,r)}extract(e,t,r=defaultTextMapGetter){return this._getGlobalPropagator().extract(e,t,r)}fields(){return this._getGlobalPropagator().fields()}disable(){unregisterGlobal(API_NAME$1,DiagAPI.instance())}_getGlobalPropagator(){return getGlobal(API_NAME$1)||NOOP_TEXT_MAP_PROPAGATOR}}const propagation=PropagationAPI.getInstance(),API_NAME="trace";class TraceAPI{constructor(){this._proxyTracerProvider=new ProxyTracerProvider,this.wrapSpanContext=wrapSpanContext,this.isSpanContextValid=isSpanContextValid,this.deleteSpan=deleteSpan,this.getSpan=getSpan,this.getActiveSpan=getActiveSpan,this.getSpanContext=getSpanContext,this.setSpan=setSpan,this.setSpanContext=setSpanContext}static getInstance(){return this._instance||(this._instance=new TraceAPI),this._instance}setGlobalTracerProvider(e){const t=registerGlobal(API_NAME,this._proxyTracerProvider,DiagAPI.instance());return t&&this._proxyTracerProvider.setDelegate(e),t}getTracerProvider(){return getGlobal(API_NAME)||this._proxyTracerProvider}getTracer(e,t){return this.getTracerProvider().getTracer(e,t)}disable(){unregisterGlobal(API_NAME,DiagAPI.instance()),this._proxyTracerProvider=new ProxyTracerProvider}}const trace=TraceAPI.getInstance();var index$3={context:context,diag:diag,metrics:metrics,propagation:propagation,trace:trace},esm$6=Object.freeze({__proto__:null,DiagConsoleLogger:DiagConsoleLogger,get DiagLogLevel(){return DiagLogLevel},INVALID_SPANID:INVALID_SPANID,INVALID_SPAN_CONTEXT:INVALID_SPAN_CONTEXT,INVALID_TRACEID:INVALID_TRACEID,ProxyTracer:ProxyTracer,ProxyTracerProvider:ProxyTracerProvider,ROOT_CONTEXT:ROOT_CONTEXT,get SamplingDecision(){return SamplingDecision$1},get SpanKind(){return SpanKind},get SpanStatusCode(){return SpanStatusCode},get TraceFlags(){return TraceFlags},get ValueType(){return ValueType},baggageEntryMetadataFromString:baggageEntryMetadataFromString,context:context,createContextKey:createContextKey,createNoopMeter:createNoopMeter,createTraceState:createTraceState,default:index$3,defaultTextMapGetter:defaultTextMapGetter,defaultTextMapSetter:defaultTextMapSetter,diag:diag,isSpanContextValid:isSpanContextValid,isValidSpanId:isValidSpanId,isValidTraceId:isValidTraceId,metrics:metrics,propagation:propagation,trace:trace}),require$$0$2=getAugmentedNamespace(esm$6);const VERSION$3="2.2.0",TMP_PROCESS_RUNTIME_NAME="process.runtime.name",TMP_TELEMETRY_SDK_NAME="telemetry.sdk.name",TMP_TELEMETRY_SDK_LANGUAGE="telemetry.sdk.language",TMP_TELEMETRY_SDK_VERSION="telemetry.sdk.version",SEMRESATTRS_PROCESS_RUNTIME_NAME=TMP_PROCESS_RUNTIME_NAME,SEMRESATTRS_TELEMETRY_SDK_NAME=TMP_TELEMETRY_SDK_NAME,SEMRESATTRS_TELEMETRY_SDK_LANGUAGE=TMP_TELEMETRY_SDK_LANGUAGE,SEMRESATTRS_TELEMETRY_SDK_VERSION=TMP_TELEMETRY_SDK_VERSION,TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS="webjs",TELEMETRYSDKLANGUAGEVALUES_WEBJS=TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS,ATTR_EXCEPTION_MESSAGE="exception.message",ATTR_EXCEPTION_STACKTRACE="exception.stacktrace",ATTR_EXCEPTION_TYPE="exception.type",ATTR_SERVICE_NAME="service.name",ATTR_TELEMETRY_SDK_LANGUAGE="telemetry.sdk.language",TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS="webjs",ATTR_TELEMETRY_SDK_NAME="telemetry.sdk.name",ATTR_TELEMETRY_SDK_VERSION="telemetry.sdk.version",ATTR_PROCESS_RUNTIME_NAME$1="process.runtime.name",SDK_INFO$2={[ATTR_TELEMETRY_SDK_NAME]:"opentelemetry",[ATTR_PROCESS_RUNTIME_NAME$1]:"browser",[ATTR_TELEMETRY_SDK_LANGUAGE]:TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS,[ATTR_TELEMETRY_SDK_VERSION]:VERSION$3};function defaultServiceName$1(){return"unknown_service"}const isPromiseLike$1=e=>null!==e&&"object"==typeof e&&"function"==typeof e.then;let ResourceImpl$1=class e{_rawAttributes;_asyncAttributesPending=!1;_schemaUrl;_memoizedAttributes;static FromAttributeList(t,r){const n=new e({},r);return n._rawAttributes=guardedRawAttributes$1(t),n._asyncAttributesPending=t.filter(([e,t])=>isPromiseLike$1(t)).length>0,n}constructor(e,t){const r=e.attributes??{};this._rawAttributes=Object.entries(r).map(([e,t])=>(isPromiseLike$1(t)&&(this._asyncAttributesPending=!0),[e,t])),this._rawAttributes=guardedRawAttributes$1(this._rawAttributes),this._schemaUrl=validateSchemaUrl$1(t?.schemaUrl)}get asyncAttributesPending(){return this._asyncAttributesPending}async waitForAsyncAttributes(){if(this.asyncAttributesPending){for(let e=0;e<this._rawAttributes.length;e++){const[t,r]=this._rawAttributes[e];this._rawAttributes[e]=[t,isPromiseLike$1(r)?await r:r]}this._asyncAttributesPending=!1}}get attributes(){if(this.asyncAttributesPending&&diag.error("Accessing resource attributes before async attributes settled"),this._memoizedAttributes)return this._memoizedAttributes;const e={};for(const[t,r]of this._rawAttributes)isPromiseLike$1(r)?diag.debug(`Unsettled resource attribute ${t} skipped`):null!=r&&(e[t]??=r);return this._asyncAttributesPending||(this._memoizedAttributes=e),e}getRawAttributes(){return this._rawAttributes}get schemaUrl(){return this._schemaUrl}merge(t){if(null==t)return this;const r=mergeSchemaUrl$1(this,t),n=r?{schemaUrl:r}:void 0;return e.FromAttributeList([...t.getRawAttributes(),...this.getRawAttributes()],n)}};function resourceFromAttributes$1(e,t){return ResourceImpl$1.FromAttributeList(Object.entries(e),t)}function resourceFromDetectedResource(e,t){return new ResourceImpl$1(e,t)}function emptyResource(){return resourceFromAttributes$1({})}function defaultResource$1(){return resourceFromAttributes$1({[ATTR_SERVICE_NAME]:defaultServiceName$1(),[ATTR_TELEMETRY_SDK_LANGUAGE]:SDK_INFO$2[ATTR_TELEMETRY_SDK_LANGUAGE],[ATTR_TELEMETRY_SDK_NAME]:SDK_INFO$2[ATTR_TELEMETRY_SDK_NAME],[ATTR_TELEMETRY_SDK_VERSION]:SDK_INFO$2[ATTR_TELEMETRY_SDK_VERSION]})}function guardedRawAttributes$1(e){return e.map(([e,t])=>isPromiseLike$1(t)?[e,t.catch(t=>{diag.debug("promise rejection for resource attribute: %s - %s",e,t)})]:[e,t])}function validateSchemaUrl$1(e){if("string"==typeof e||void 0===e)return e;diag.warn("Schema URL must be string or undefined, got %s. Schema URL will be ignored.",e)}function mergeSchemaUrl$1(e,t){const r=e?.schemaUrl,n=t?.schemaUrl;return void 0===r||""===r?n:void 0===n||""===n||r===n?r:void diag.warn('Schema URL merge conflict: old resource has "%s", updating resource has "%s". Resulting resource will have undefined Schema URL.',r,n)}const detectResources=(e={})=>{const t=(e.detectors||[]).map(t=>{try{const r=resourceFromDetectedResource(t.detect(e));return diag.debug(`${t.constructor.name} found resource.`,r),r}catch(e){return diag.debug(`${t.constructor.name} failed: ${e.message}`),emptyResource()}});return t.reduce((e,t)=>e.merge(t),emptyResource())};class EnvDetector{_MAX_LENGTH=255;_COMMA_SEPARATOR=",";_LABEL_KEY_VALUE_SPLITTER="=";_ERROR_MESSAGE_INVALID_CHARS="should be a ASCII string with a length greater than 0 and not exceed "+this._MAX_LENGTH+" characters.";_ERROR_MESSAGE_INVALID_VALUE="should be a ASCII string with a length not exceed "+this._MAX_LENGTH+" characters.";detect(e){return{attributes:{}}}_parseResourceAttributes(e){if(!e)return{};const t={},r=e.split(this._COMMA_SEPARATOR,-1);for(const e of r){const r=e.split(this._LABEL_KEY_VALUE_SPLITTER,-1);if(2!==r.length)continue;let[n,i]=r;if(n=n.trim(),i=i.trim().split(/^"|"$/).join(""),!this._isValidAndNotEmpty(n))throw new Error(`Attribute key ${this._ERROR_MESSAGE_INVALID_CHARS}`);if(!this._isValid(i))throw new Error(`Attribute value ${this._ERROR_MESSAGE_INVALID_VALUE}`);t[n]=decodeURIComponent(i)}return t}_isValid(e){return e.length<=this._MAX_LENGTH&&this._isBaggageOctetString(e)}_isBaggageOctetString(e){for(let t=0;t<e.length;t++){const r=e.charCodeAt(t);if(r<33||44===r||59===r||92===r||r>126)return!1}return!0}_isValidAndNotEmpty(e){return e.length>0&&this._isValid(e)}}const envDetector=new EnvDetector;class NoopDetector{detect(){return{attributes:{}}}}const noopDetector=new NoopDetector,hostDetector=noopDetector,osDetector=noopDetector,processDetector=noopDetector,serviceInstanceIdDetector=noopDetector;var esm$5=Object.freeze({__proto__:null,defaultResource:defaultResource$1,defaultServiceName:defaultServiceName$1,detectResources:detectResources,emptyResource:emptyResource,envDetector:envDetector,hostDetector:hostDetector,osDetector:osDetector,processDetector:processDetector,resourceFromAttributes:resourceFromAttributes$1,serviceInstanceIdDetector:serviceInstanceIdDetector}),require$$2$1=getAugmentedNamespace(esm$5);Object.defineProperty(dist$2,"__esModule",{value:!0});var init_1$1=dist$2.init=void 0;const otel_1$v=requireDist$1(),api_1$2=require$$0$2,resources_1=require$$2$1;function init$1(){(0,otel_1$v.registerInsightsPlugin)("base",()=>({resourceFromAttributes:e=>(0,resources_1.resourceFromAttributes)(e),diag:api_1$2.diag}))}init_1$1=dist$2.init=init$1;var index$2=Object.freeze({__proto__:null,default:dist$2,get init(){return init_1$1}}),dist$1={},customHistogram={},base$1={},base={},validator={};Object.defineProperty(validator,"__esModule",{value:!0}),validator.Validator=void 0;class Validator{static isNullOrUndefined(e){return null==e}static throwIfNullOrUndefined(e,t,r){if(this.isNullOrUndefined(e))throw new Error(r||`${t} must be defined`)}}validator.Validator=Validator,Object.defineProperty(base,"__esModule",{value:!0}),base.MetricBaseValidator=void 0;const validator_1$l=validator;class MetricBaseValidator{validate(e){validator_1$l.Validator.throwIfNullOrUndefined(e,"base"),validator_1$l.Validator.throwIfNullOrUndefined(e.logger,"logger"),this.validateSettings(e.settings)}validateSettings(e){validator_1$l.Validator.throwIfNullOrUndefined(e,"settings"),validator_1$l.Validator.throwIfNullOrUndefined(e.enabled,"enabled"),validator_1$l.Validator.throwIfNullOrUndefined(e.name,"name"),validator_1$l.Validator.throwIfNullOrUndefined(e.type,"type"),validator_1$l.Validator.throwIfNullOrUndefined(e.description,"description"),validator_1$l.Validator.throwIfNullOrUndefined(e.platformVersion,"platformVersion")}}base.MetricBaseValidator=MetricBaseValidator;var utils$1={},lodash_clonedeep={exports:{}};lodash_clonedeep.exports,function(e,t){var r="__lodash_hash_undefined__",n=9007199254740991,i="[object Arguments]",o="[object Boolean]",s="[object Date]",a="[object Function]",c="[object GeneratorFunction]",l="[object Map]",u="[object Number]",d="[object Object]",h="[object Promise]",p="[object RegExp]",g="[object Set]",m="[object String]",f="[object Symbol]",y="[object WeakMap]",$="[object ArrayBuffer]",b="[object DataView]",w="[object Float32Array]",v="[object Float64Array]",S="[object Int8Array]",E="[object Int16Array]",C="[object Int32Array]",_="[object Uint8Array]",I="[object Uint8ClampedArray]",T="[object Uint16Array]",A="[object Uint32Array]",D=/\w*$/,x=/^\[object .+?Constructor\]$/,R=/^(?:0|[1-9]\d*)$/,O={};O[i]=O["[object Array]"]=O[$]=O[b]=O[o]=O[s]=O[w]=O[v]=O[S]=O[E]=O[C]=O[l]=O[u]=O[d]=O[p]=O[g]=O[m]=O[f]=O[_]=O[I]=O[T]=O[A]=!0,O["[object Error]"]=O[a]=O[y]=!1;var P="object"==typeof commonjsGlobal$1&&commonjsGlobal$1&&commonjsGlobal$1.Object===Object&&commonjsGlobal$1,N="object"==typeof self&&self&&self.Object===Object&&self,k=P||N||Function("return this")(),M=t&&!t.nodeType&&t,L=M&&e&&!e.nodeType&&e,F=L&&L.exports===M;function j(e,t){return e.set(t[0],t[1]),e}function U(e,t){return e.add(t),e}function B(e,t,r,n){for(var i=-1,o=e?e.length:0;++i<o;)r=t(r,e[i],i,e);return r}function q(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(e){}return t}function H(e){var t=-1,r=Array(e.size);return e.forEach(function(e,n){r[++t]=[n,e]}),r}function W(e,t){return function(r){return e(t(r))}}function G(e){var t=-1,r=Array(e.size);return e.forEach(function(e){r[++t]=e}),r}var J,K=Array.prototype,V=Function.prototype,z=Object.prototype,X=k["__core-js_shared__"],Y=(J=/[^.]+$/.exec(X&&X.keys&&X.keys.IE_PROTO||""))?"Symbol(src)_1."+J:"",Z=V.toString,Q=z.hasOwnProperty,ee=z.toString,te=RegExp("^"+Z.call(Q).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),re=F?k.Buffer:void 0,ne=k.Symbol,ie=k.Uint8Array,oe=W(Object.getPrototypeOf,Object),se=Object.create,ae=z.propertyIsEnumerable,ce=K.splice,le=Object.getOwnPropertySymbols,ue=re?re.isBuffer:void 0,de=W(Object.keys,Object),he=Le(k,"DataView"),pe=Le(k,"Map"),ge=Le(k,"Promise"),me=Le(k,"Set"),fe=Le(k,"WeakMap"),ye=Le(Object,"create"),$e=qe(he),be=qe(pe),we=qe(ge),ve=qe(me),Se=qe(fe),Ee=ne?ne.prototype:void 0,Ce=Ee?Ee.valueOf:void 0;function _e(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function Ie(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function Te(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function Ae(e){this.__data__=new Ie(e)}function De(e,t){var r=We(e)||function(e){return function(e){return function(e){return!!e&&"object"==typeof e}(e)&&Ge(e)}(e)&&Q.call(e,"callee")&&(!ae.call(e,"callee")||ee.call(e)==i)}(e)?function(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}(e.length,String):[],n=r.length,o=!!n;for(var s in e)!Q.call(e,s)||o&&("length"==s||Ue(s,n))||r.push(s);return r}function xe(e,t,r){var n=e[t];Q.call(e,t)&&He(n,r)&&(void 0!==r||t in e)||(e[t]=r)}function Re(e,t){for(var r=e.length;r--;)if(He(e[r][0],t))return r;return-1}function Oe(e,t,r,n,h,y,x){var R;if(n&&(R=y?n(e,h,y,x):n(e)),void 0!==R)return R;if(!Ve(e))return e;var P=We(e);if(P){if(R=function(e){var t=e.length,r=e.constructor(t);t&&"string"==typeof e[0]&&Q.call(e,"index")&&(r.index=e.index,r.input=e.input);return r}(e),!t)return function(e,t){var r=-1,n=e.length;t||(t=Array(n));for(;++r<n;)t[r]=e[r];return t}(e,R)}else{var N=je(e),k=N==a||N==c;if(Je(e))return function(e,t){if(t)return e.slice();var r=new e.constructor(e.length);return e.copy(r),r}(e,t);if(N==d||N==i||k&&!y){if(q(e))return y?e:{};if(R=function(e){return"function"!=typeof e.constructor||Be(e)?{}:(t=oe(e),Ve(t)?se(t):{});var t}(k?{}:e),!t)return function(e,t){return ke(e,Fe(e),t)}(e,function(e,t){return e&&ke(t,ze(t),e)}(R,e))}else{if(!O[N])return y?e:{};R=function(e,t,r,n){var i=e.constructor;switch(t){case $:return Ne(e);case o:case s:return new i(+e);case b:return function(e,t){var r=t?Ne(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.byteLength)}(e,n);case w:case v:case S:case E:case C:case _:case I:case T:case A:return function(e,t){var r=t?Ne(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}(e,n);case l:return function(e,t,r){var n=t?r(H(e),!0):H(e);return B(n,j,new e.constructor)}(e,n,r);case u:case m:return new i(e);case p:return function(e){var t=new e.constructor(e.source,D.exec(e));return t.lastIndex=e.lastIndex,t}(e);case g:return function(e,t,r){var n=t?r(G(e),!0):G(e);return B(n,U,new e.constructor)}(e,n,r);case f:return a=e,Ce?Object(Ce.call(a)):{}}var a}(e,N,Oe,t)}}x||(x=new Ae);var M=x.get(e);if(M)return M;if(x.set(e,R),!P)var L=r?function(e){return function(e,t,r){var n=t(e);return We(e)?n:function(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e}(n,r(e))}(e,ze,Fe)}(e):ze(e);return function(e,t){for(var r=-1,n=e?e.length:0;++r<n&&!1!==t(e[r],r,e););}(L||e,function(i,o){L&&(i=e[o=i]),xe(R,o,Oe(i,t,r,n,o,e,x))}),R}function Pe(e){return!(!Ve(e)||(t=e,Y&&Y in t))&&(Ke(e)||q(e)?te:x).test(qe(e));var t}function Ne(e){var t=new e.constructor(e.byteLength);return new ie(t).set(new ie(e)),t}function ke(e,t,r,n){r||(r={});for(var i=-1,o=t.length;++i<o;){var s=t[i];xe(r,s,e[s])}return r}function Me(e,t){var r=e.__data__;return function(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}(t)?r["string"==typeof t?"string":"hash"]:r.map}function Le(e,t){var r=function(e,t){return null==e?void 0:e[t]}(e,t);return Pe(r)?r:void 0}_e.prototype.clear=function(){this.__data__=ye?ye(null):{}},_e.prototype.delete=function(e){return this.has(e)&&delete this.__data__[e]},_e.prototype.get=function(e){var t=this.__data__;if(ye){var n=t[e];return n===r?void 0:n}return Q.call(t,e)?t[e]:void 0},_e.prototype.has=function(e){var t=this.__data__;return ye?void 0!==t[e]:Q.call(t,e)},_e.prototype.set=function(e,t){return this.__data__[e]=ye&&void 0===t?r:t,this},Ie.prototype.clear=function(){this.__data__=[]},Ie.prototype.delete=function(e){var t=this.__data__,r=Re(t,e);return!(r<0)&&(r==t.length-1?t.pop():ce.call(t,r,1),!0)},Ie.prototype.get=function(e){var t=this.__data__,r=Re(t,e);return r<0?void 0:t[r][1]},Ie.prototype.has=function(e){return Re(this.__data__,e)>-1},Ie.prototype.set=function(e,t){var r=this.__data__,n=Re(r,e);return n<0?r.push([e,t]):r[n][1]=t,this},Te.prototype.clear=function(){this.__data__={hash:new _e,map:new(pe||Ie),string:new _e}},Te.prototype.delete=function(e){return Me(this,e).delete(e)},Te.prototype.get=function(e){return Me(this,e).get(e)},Te.prototype.has=function(e){return Me(this,e).has(e)},Te.prototype.set=function(e,t){return Me(this,e).set(e,t),this},Ae.prototype.clear=function(){this.__data__=new Ie},Ae.prototype.delete=function(e){return this.__data__.delete(e)},Ae.prototype.get=function(e){return this.__data__.get(e)},Ae.prototype.has=function(e){return this.__data__.has(e)},Ae.prototype.set=function(e,t){var r=this.__data__;if(r instanceof Ie){var n=r.__data__;if(!pe||n.length<199)return n.push([e,t]),this;r=this.__data__=new Te(n)}return r.set(e,t),this};var Fe=le?W(le,Object):function(){return[]},je=function(e){return ee.call(e)};function Ue(e,t){return!!(t=null==t?n:t)&&("number"==typeof e||R.test(e))&&e>-1&&e%1==0&&e<t}function Be(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||z)}function qe(e){if(null!=e){try{return Z.call(e)}catch(e){}try{return e+""}catch(e){}}return""}function He(e,t){return e===t||e!=e&&t!=t}(he&&je(new he(new ArrayBuffer(1)))!=b||pe&&je(new pe)!=l||ge&&je(ge.resolve())!=h||me&&je(new me)!=g||fe&&je(new fe)!=y)&&(je=function(e){var t=ee.call(e),r=t==d?e.constructor:void 0,n=r?qe(r):void 0;if(n)switch(n){case $e:return b;case be:return l;case we:return h;case ve:return g;case Se:return y}return t});var We=Array.isArray;function Ge(e){return null!=e&&function(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=n}(e.length)&&!Ke(e)}var Je=ue||function(){return!1};function Ke(e){var t=Ve(e)?ee.call(e):"";return t==a||t==c}function Ve(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function ze(e){return Ge(e)?De(e):function(e){if(!Be(e))return de(e);var t=[];for(var r in Object(e))Q.call(e,r)&&"constructor"!=r&&t.push(r);return t}(e)}e.exports=function(e){return Oe(e,!0,!0)}}(lodash_clonedeep,lodash_clonedeep.exports);var lodash_clonedeepExports=lodash_clonedeep.exports,__importDefault$2=commonjsGlobal$1&&commonjsGlobal$1.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(utils$1,"__esModule",{value:!0}),utils$1.reduceModality=void 0;const lodash_clonedeep_1$2=__importDefault$2(lodash_clonedeepExports);function reduceModality(e,t){var r;if(!e||!t)return e;if(!Object.keys(t))return e;e=(0,lodash_clonedeep_1$2.default)(e);for(const n in t)if(n in e){const i=null===(r=t[n])||void 0===r?void 0:r.reduceModality;if(void 0===i||i<0)continue;0===i?delete e[n]:i>0&&(e[n]=simpleHash(e[n]+"",i))}return e}function simpleHash(e,t){let r=2166136261;for(let t=0;t<e.length;t++)r^=e.charCodeAt(t),r=Math.imul(r,16777619);let n=(r>>>0).toString(16);return n.length<t?n.padEnd(t,n).slice(0,t):n.slice(0,t)}utils$1.reduceModality=reduceModality;var __awaiter$9=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(base$1,"__esModule",{value:!0}),base$1.MetricBase=void 0;const base_1$j=base,otel_1$u=requireDist$1(),utils_1$3=utils$1;class MetricBase{constructor(e,t,r,n,i){var o,s;this.settings=e,this.meter=t,this.logger=r,this.generalSettings=n,this.started=!1;(new base_1$j.MetricBaseValidator).validate(this),this.filters=null!==(o=null==n?void 0:n.filters)&&void 0!==o?o:[],this.defaultFilters=(null===(s=null==n?void 0:n.useDefaultFilters)||void 0===s||s)&&null!=i?i:[]}getFilter(e){var t,r,n,i,o,s,a,c,l,u,d,h,p;const g=(null!==(r=null===(t=this.filters)||void 0===t?void 0:t.filter(e=>e.overrideDefaultFilters))&&void 0!==r?r:[]).concat((null!==(n=this.defaultFilters)&&void 0!==n?n:[]).map(e=>{var t;return Object.assign(Object.assign({},e),{type:this.settings.type,name:null!==(t=this.settings.name)&&void 0!==t?t:this.settings.type})})).concat(null!==(o=null===(i=this.filters)||void 0===i?void 0:i.filter(e=>!e.overrideDefaultFilters))&&void 0!==o?o:[]).find(t=>{var r,n,i;if(!this.matchStringOrRegex(this.settings.type,t.type))return!1;if(!this.matchStringOrRegex(null!==(r=this.settings.name)&&void 0!==r?r:this.settings.type,t.name))return!1;for(const r of Object.keys(null!==(n=null==t?void 0:t.attributes)&&void 0!==n?n:{}))if(e[r]!==(null!==(i=null==t?void 0:t.attributes)&&void 0!==i?i:{})[r])return!1;return!0});null==g||g.enabled,null==g||g.enabled;let m=null===(s=null==g?void 0:g.enabled)||void 0===s||s;if(!1!==(null==g?void 0:g.enabled)){const e=null!==(u=null!==(a=null==g?void 0:g.sample)&&void 0!==a?a:null===(l=null===(c=this.settings)||void 0===c?void 0:c.publishingSettings)||void 0===l?void 0:l.sample)&&void 0!==u?u:null===(h=null===(d=this.generalSettings)||void 0===d?void 0:d.defaultPublishingSettings)||void 0===h?void 0:h.sample;void 0!==e&&(m=!0===e||!1!==e&&Math.random()<e)}return Object.assign(Object.assign({},g),{enabled:m,type:this.settings.type,name:null!==(p=this.settings.name)&&void 0!==p?p:this.settings.type})}start(){return __awaiter$9(this,void 0,void 0,function*(){try{yield this.createMetric(),yield this.subscribe(),this.started=!0}catch(e){this.settings.type}return Promise.resolve()})}stop(){return __awaiter$9(this,void 0,void 0,function*(){try{yield this.unsubscribe(),yield this.destroyMetric(),this.started=!1}catch(e){this.settings.type}return Promise.resolve()})}createMetric(){const e=this.settings.name||this.settings.type+"-"+this.createUniqueName(10),t=this.settings.description,r=this.settings.unit,n={explicitBucketBoundaries:this.settings.buckets};return this.metricAny=this.createMetricCore(e,{description:t,unit:r,advice:n}),Promise.resolve()}createRecordingMetric(e,t,r){var n;return"histogram"===(null!==(n=this.settings.baseMetricType)&&void 0!==n?n:r)?this.meter.createHistogram(e,t):this.meter.createGauge(e,t)}subscribe(){return Promise.resolve()}unsubscribe(){return Promise.resolve()}destroyMetric(){return Promise.resolve()}getData(){return Object.assign({platformVersion:this.settings.platformVersion,user:this.settings.user},otel_1$u.Container.errorless(this.settings.additionalAttributes))}prePublish(e){var t,r;if(!e)return e;const n=Object.assign(Object.assign({},null===(t=this.generalSettings.defaultPublishingSettings)||void 0===t?void 0:t.attributeSettings),null===(r=this.settings.publishingSettings)||void 0===r?void 0:r.attributeSettings);return(0,utils_1$3.reduceModality)(e,n)}getApplicationData(e){return Object.assign(Object.assign({},this.getData()),{application:e})}getLayoutData(e){return Object.assign(Object.assign({},this.getData()),{layout:e})}createUniqueName(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";let r="";const n=new Uint8Array(e);return crypto.getRandomValues(n),n.forEach(e=>{r+=t[e%52]}),r}matchStringOrRegex(e,t){if(!t)return!0;if("string"==typeof t&&"#"===t[0]){if(null==e||!new RegExp(t.substring(1),"i").test(e+""))return!1}else if(e!==t)return!1;return!0}}base$1.MetricBase=MetricBase,Object.defineProperty(customHistogram,"__esModule",{value:!0}),customHistogram.CustomHistogramMetric=void 0;const base_1$i=base$1;class CustomHistogramMetric extends base_1$i.MetricBase{constructor(e,t,r,n,i){super(e,t,r,n,i),this.meter=t}createMetricCore(e,t){return this.metric=this.meter.createHistogram(e,t)}record(e,t){var r,n;const i=Object.assign(Object.assign({},this.getData()),t);!1!==(null===(r=this.getFilter(i))||void 0===r?void 0:r.enabled)&&(null===(n=this.metric)||void 0===n||n.record(e,this.prePublish(i)))}}customHistogram.CustomHistogramMetric=CustomHistogramMetric;var customUpDownCounter={};Object.defineProperty(customUpDownCounter,"__esModule",{value:!0}),customUpDownCounter.CustomUpDownCounterMetric=void 0;const base_1$h=base$1;class CustomUpDownCounterMetric extends base_1$h.MetricBase{constructor(e,t,r,n,i){super(e,t,r,n,i),this.meter=t}createMetricCore(e,t){return this.metric=this.meter.createUpDownCounter(e,t)}add(e,t){var r,n;const i=Object.assign(Object.assign({},this.getData()),t);!1!==(null===(r=this.getFilter(i))||void 0===r?void 0:r.enabled)&&(null===(n=this.metric)||void 0===n||n.add(e,this.prePublish(i)))}}customUpDownCounter.CustomUpDownCounterMetric=CustomUpDownCounterMetric;var builder$1={},_default={};Object.defineProperty(_default,"__esModule",{value:!0}),_default.DefaultMetricsSettings=void 0;class DefaultMetricsSettings{constructor(){this.unknown="unknown"}get enabled(){return!0}get platformMetricsEnabled(){return!0}get userId(){return this.unknown}get platformVersion(){return this.unknown}get additionalAttributes(){return{}}get metrics(){return[this.getAppCount(),this.getAppCPU(),this.getAppCrash(),this.getAppDuration(),this.getAppDurationSoft(),this.getAppError(),this.getAppMemory(),this.getAppStarted(),this.getAppStartup(),this.getAppStopped(),this.getLayoutStartup(),this.getPlatformError(),this.getPlatformStartup(),this.getSystemCPU(),this.getSystemMemory(),this.getWorkspaceCount(),this.getWorkspaceSelected(),this.getWorkspaceStarted(),this.getWorkspaceStopped(),this.getWorkspaceStartupLegacy(),this.getWorkspaceStartup(),this.getWorkspaceStartupFrame(),this.getWorkspaceStartupFrameInit(),this.getWorkspaceStartupFramePageLoad(),this.getWorkspaceStartupFrameWorkspaceRender(),this.getWorkspaceStartupComponent(),this.getWorkspaceStartupApps()]}getWorkspaceStartupLegacy(){return Object.assign(Object.assign({},this.getSettings("workspace_startup","Time to load the workspace layout","workspace_startup_legacy","ms",[100,1e3,1e4,3e4,6e4])),{enabled:!1})}getWorkspaceStartup(){return this.getSettings("workspace_startup","Time to load the workspace layout","workspace_startup","ms")}getWorkspaceStartupFrame(){return this.getSettings("workspace_startup_frame","Time to load the workspace frame","workspace_startup_frame","ms")}getWorkspaceStartupFrameInit(){return this.getSettings("workspace_startup_frame_init","Time to initialize the workspace frame","workspace_startup_frame_init","ms")}getWorkspaceStartupFramePageLoad(){return this.getSettings("workspace_startup_frame_page_load","Time to load the page for the workspace frame","workspace_startup_frame_page_load","ms")}getWorkspaceStartupFrameWorkspaceRender(){return this.getSettings("workspace_startup_frame_workspace_render","Time to render the workspace frame","workspace_startup_frame_workspace_render","ms")}getWorkspaceStartupComponent(){return this.getSettings("workspace_startup_component","Time to load the workspace layout component","workspace_startup_component","ms")}getWorkspaceStartupApps(){return this.getSettings("workspace_startup_apps","Time to load the workspace applications","workspace_startup_apps","ms")}getAppStarted(){return this.getSettings("app_started","Number of times an application has been started during each platform session","app_started")}getAppStopped(){return this.getSettings("app_stopped","Number of times an application has been stopped during each platform session","app_stopped")}getAppCount(){return this.getSettings("app_count","Number of application instances running in the platform during each platform session","app_count")}getAppStartup(){return this.getSettings("app_startup","Time to load an application","app_startup","ms",[100,1e3,1e4,3e4,6e4])}getAppDuration(){return this.getSettings("app_duration","How long an application has been focused during each platform session","app_duration","ms",[1e3,1e4,3e4,6e4,6e5])}getAppDurationSoft(){return Object.assign(Object.assign({},this.getSettings("app_duration_soft","How long an application has been focused during each platform session (without the currently focused application)","app_duration_soft","ms",[1e3,1e4,3e4,6e4,6e5])),{enabled:!1})}getAppMemory(){return this.getSettings("app_memory","Current app memory usage","app_memory","kb")}getAppCPU(){return this.getSettings("app_cpu","Percentage of CPU used for the last interval.","app_cpu","%")}getAppError(){return this.getSettings("app_error","Number of times app error was received during each platform session","app_error")}getAppCrash(){return this.getSettings("app_crash","Number of times an application crashed during each platform session","app_crash")}getLayoutStartup(){return this.getSettings("layout_startup","Time to load a layout","layout_startup","ms",[100,1e3,1e4,3e4,6e4])}getWorkspaceStarted(){return this.getSettings("workspace_started","Number of times a workspace has been stopped during each platform session","workspace_started")}getWorkspaceStopped(){return this.getSettings("workspace_stopped","Number of times a workspace has been stopped during each platform session","workspace_stopped")}getWorkspaceSelected(){return this.getSettings("workspace_selected","TBD","workspace_selected")}getWorkspaceCount(){return this.getSettings("workspace_count","Number of workspace running in the platform during each platform session","workspace_count")}getPlatformStartup(){return this.getSettings("platform_startup","Time to load the platform","platform_startup","ms")}getPlatformError(){return this.getSettings("platform_error","Number of times platform error was received during each platform session","platform_error")}getSystemMemory(){return this.getSettings("system_memory","Free system memory, used system memory and used platform memory","system_memory","gb")}getSystemCPU(){return this.getSettings("system_cpu","Current and average system CPU and average platform CPU","system_cpu","%")}getSettings(e,t,r,n,i){return{enabled:!0,name:e,description:t,user:this.unknown,platformVersion:this.unknown,type:r,unit:n,buckets:i}}}_default.DefaultMetricsSettings=DefaultMetricsSettings,DefaultMetricsSettings.instance=new DefaultMetricsSettings;var constants$1={};Object.defineProperty(constants$1,"__esModule",{value:!0}),constants$1.Defaults=void 0,constants$1.Defaults={TRACE_VERSION:"00",DEFAULT_USER:"unknown-user",DEFAULT_SERVICE_NAME:"unknown-service-name",DEFAULT_SERVICE_ID:"unknown-service-id",DEFAULT_SERVICE_VERSION:"unknown-service-version",DEFAULT_PLATFORM_VERSION:"unknown-platform-version",DEFAULT_METRIC_DESCRIPTION:"unknown-metric",stopPropagationIfSpanIsDisabled:!1,countMetric:!1,durationMetric:!1,resultMetric:!1,countMetricOnDisabledSpans:!1,durationMetricOnDisabledSpans:!1,resultMetricOnDisabledSpans:!1,maxAttributeDepth:5,otelSpanOptions:{},disablePropagation:!1,addContextToTrace:!0,level:"INFO",forceChildTracing:!1,canBeRoot:!0,currentTracingStateGetterContextName:"interopio.insights.currentTracingStateGetter",minDurationMs:0,log:!1,logOnDisabledSpans:!1},Object.defineProperty(builder$1,"__esModule",{value:!0}),builder$1.MetricsSettingsBuilder=void 0;const default_1$1=_default,constants_1$2=constants$1,otel_1$t=requireDist$1();class MetricsSettingsBuilder{constructor(){this.metrics=new Map,this.defaultSettings=new default_1$1.DefaultMetricsSettings,this.withSettings({enabled:!1,platformVersion:constants_1$2.Defaults.DEFAULT_PLATFORM_VERSION,serviceId:constants_1$2.Defaults.DEFAULT_SERVICE_ID,serviceName:constants_1$2.Defaults.DEFAULT_SERVICE_NAME,userId:constants_1$2.Defaults.DEFAULT_USER,serviceVersion:constants_1$2.Defaults.DEFAULT_SERVICE_VERSION,metrics:this.defaultSettings})}build(){var e,t,r,n,i,o,s,a,c,l,u,d,h,p,g,m,f,y,$,b,w,v,S,E;if(this.platformMetricsEnabled){if(null===(t=this.settings)||void 0===t?void 0:t.useLegacyWorkspaceStartupMetric){this.metrics.set("workspace_startup",this.defaultSettings.getWorkspaceStartupLegacy());const e=null===(n=null===(r=this.settings)||void 0===r?void 0:r.metrics)||void 0===n?void 0:n.find(e=>{var t;return"workspace_startup"===(null!==(t=e.name)&&void 0!==t?t:e.type)});e&&this.withCustomMetric(e)}}else for(const t of this.defaultSettings.metrics)this.metrics.delete(null!==(e=t.name)&&void 0!==e?e:t.type);this.metrics.forEach(e=>{var t;this.metrics.set(null!==(t=e.name)&&void 0!==t?t:e.type,this.convert(e))});const C=null!==(o=null===(i=this.meter)||void 0===i?void 0:i.headers)&&void 0!==o?o:Object.assign(Object.assign({},otel_1$t.Container.errorless(null===(s=this.otelSettings)||void 0===s?void 0:s.headers)),otel_1$t.Container.errorless(null===(a=this.settings)||void 0===a?void 0:a.headers)),_=Object.assign(Object.assign({},this.settings),{enabled:this.enabled,platformMetricsEnabled:this.platformMetricsEnabled,url:null!==(u=null!==(c=this.meter.url)&&void 0!==c?c:null===(l=this.settings)||void 0===l?void 0:l.url)&&void 0!==u?u:"http://localhost:4318/v1/metrics",publishInterval:null!==(p=null!==(d=this.meter.publishInterval)&&void 0!==d?d:null===(h=this.settings)||void 0===h?void 0:h.publishInterval)&&void 0!==p?p:3e4,compression:null!==(g=this.meter.compression)&&void 0!==g?g:null===(m=this.settings)||void 0===m?void 0:m.compression,headers:C,hostname:null!==(f=this.meter.hostname)&&void 0!==f?f:null===(y=this.settings)||void 0===y?void 0:y.hostname,keepAlive:null!==($=this.meter.keepAlive)&&void 0!==$?$:null===(b=this.settings)||void 0===b?void 0:b.keepAlive,concurrencyLimit:null!==(w=this.meter.concurrencyLimit)&&void 0!==w?w:null===(v=this.settings)||void 0===v?void 0:v.concurrencyLimit,timeoutMillis:null!==(S=this.meter.timeoutMillis)&&void 0!==S?S:null===(E=this.settings)||void 0===E?void 0:E.timeoutMillis,metrics:[...this.metrics.values()],additionalAttributes:()=>{var e,t;return Object.assign(Object.assign({},otel_1$t.Container.errorless(null===(e=this.otelSettings)||void 0===e?void 0:e.additionalAttributes)),otel_1$t.Container.errorless(null===(t=this.settings)||void 0===t?void 0:t.additionalAttributes))}});return _}withSettings(e){var t,r,n,i,o,s,a,c,l,u,d,h;const p=this.otelSettings;this.otelSettings=e;const g=this.settings;return this.settings=null==e?void 0:e.metrics,this.withEnabled(null!==(r=null===(t=this.settings)||void 0===t?void 0:t.enabled)&&void 0!==r?r:null==g?void 0:g.enabled).withPlatformMetricsEnabled(null!==(i=null===(n=this.settings)||void 0===n?void 0:n.platformMetricsEnabled)&&void 0!==i?i:null==g?void 0:g.platformMetricsEnabled).withUser(null!==(s=null===(o=this.otelSettings)||void 0===o?void 0:o.userId)&&void 0!==s?s:null==p?void 0:p.userId).withPlatformVersion(null!==(c=null===(a=this.otelSettings)||void 0===a?void 0:a.platformVersion)&&void 0!==c?c:null==p?void 0:p.platformVersion).withAdditionalAttributes(null===(l=this.settings)||void 0===l?void 0:l.additionalAttributes).withCustomMetrics(null===(u=this.settings)||void 0===u?void 0:u.metrics).withMeter(null!==(h=null===(d=this.settings)||void 0===d?void 0:d.meter)&&void 0!==h?h:this.meter)}withEnabled(e){return this.enabled=null!=e?e:this.enabled,this}withUser(e){return this.userId=null!=e?e:this.userId,this.metrics.forEach(e=>{var t;e.user=this.userId,this.metrics.set(null!==(t=e.name)&&void 0!==t?t:e.type,e)}),this}withAdditionalAttributes(e){return this.additionalAttributes=null!=e?e:this.additionalAttributes,this.metrics.forEach(e=>{var t;e.additionalAttributes=this.additionalAttributes,this.metrics.set(null!==(t=e.name)&&void 0!==t?t:e.type,e)}),this}withPlatformVersion(e){return this.platformVersion=null!=e?e:this.platformVersion,this.metrics.forEach(e=>{var t;e.platformVersion=this.platformVersion,this.metrics.set(null!==(t=e.name)&&void 0!==t?t:e.type,e)}),this}withPlatformMetricsEnabled(e){return this.platformMetricsEnabled=null!=e?e:this.platformMetricsEnabled,this}withMeter(e){var t,r,n,i,o,s,a,c,l,u;const d=this.meter;return this.meter=Object.assign(Object.assign(Object.assign({},d),null!=e?e:{}),{url:null!==(t=null==e?void 0:e.url)&&void 0!==t?t:null==d?void 0:d.url,publishInterval:null!==(r=null==e?void 0:e.publishInterval)&&void 0!==r?r:null==d?void 0:d.publishInterval,compression:null!==(o=null!==(n=null==e?void 0:e.compression)&&void 0!==n?n:null===(i=this.settings)||void 0===i?void 0:i.compression)&&void 0!==o?o:null==d?void 0:d.compression,headers:null!==(s=null==e?void 0:e.headers)&&void 0!==s?s:null==d?void 0:d.headers,hostname:null!==(a=null==e?void 0:e.hostname)&&void 0!==a?a:null==d?void 0:d.hostname,keepAlive:null!==(c=null==e?void 0:e.keepAlive)&&void 0!==c?c:null==d?void 0:d.keepAlive,concurrencyLimit:null!==(l=null==e?void 0:e.concurrencyLimit)&&void 0!==l?l:null==d?void 0:d.concurrencyLimit,timeoutMillis:null!==(u=null==e?void 0:e.timeoutMillis)&&void 0!==u?u:null==d?void 0:d.timeoutMillis}),this}withCustomMetrics(e){return(null!=e?e:[]).forEach(e=>this.withCustomMetric(e)),this}withCustomMetric(e){var t,r,n,i;if(!e.name)throw new Error("settings.name is not defined");if(this.metrics.has(null!==(t=e.name)&&void 0!==t?t:e.type)){const t=this.metrics.get(null!==(n=e.name)&&void 0!==n?n:e.type),r=this.mergeSettings(e,t);this.metrics.set(null!==(i=r.name)&&void 0!==i?i:r.type,r)}else{const t=this.convert(e);this.metrics.set(null!==(r=e.name)&&void 0!==r?r:e.type,t)}return this}convert(e){var t,r,n,i;return Object.assign(Object.assign(Object.assign({},this.settings),e),{type:e.type,user:this.userId,enabled:null===(t=e.enabled)||void 0===t||t,name:null!==(r=e.name)&&void 0!==r?r:e.type,description:null!==(n=e.description)&&void 0!==n?n:null!==(i=e.name)&&void 0!==i?i:e.type,platformVersion:this.platformVersion,unit:e.unit,buckets:e.buckets,additionalAttributes:e.additionalAttributes})}mergeSettings(e,t){var r,n,i,o,s;return Object.assign(Object.assign(Object.assign({},t),this.settings),{type:e.type,user:this.userId,enabled:null!==(r=e.enabled)&&void 0!==r?r:t.enabled,name:null!==(n=e.name)&&void 0!==n?n:t.name,description:null!==(i=e.description)&&void 0!==i?i:t.description,platformVersion:this.platformVersion,unit:t.unit,buckets:null!==(o=e.buckets)&&void 0!==o?o:t.buckets,additionalAttributes:null!==(s=e.additionalAttributes)&&void 0!==s?s:t.additionalAttributes})}}builder$1.MetricsSettingsBuilder=MetricsSettingsBuilder;var lazyProvider={};Object.defineProperty(lazyProvider,"__esModule",{value:!0}),lazyProvider.LazyMetricsMeterProvider=void 0;class LazyMetricsMeterProvider{get metricReaders(){return this._metricReaders||this.buildMeterProvider(),this._metricReaders}constructor(e,t){this.meterProviderCreateFunc=e,this.serviceName=t}getMeter(){return this.getMeterProvider().getMeter(this.serviceName)}forceFlush(){return this.getMeterProvider().forceFlush()}getMeterProvider(){return this.meterProvider||this.buildMeterProvider(),this.meterProvider}buildMeterProvider(){const e=this.meterProviderCreateFunc();this.meterProvider=e.meterProvider,this._metricReaders=e.metricReaders}}lazyProvider.LazyMetricsMeterProvider=LazyMetricsMeterProvider;var builder={},factoryBuilder={};Object.defineProperty(factoryBuilder,"__esModule",{value:!0}),factoryBuilder.MetricsFactoryBuilderValidator=void 0;const validator_1$k=validator;class MetricsFactoryBuilderValidator{validate(e){validator_1$k.Validator.throwIfNullOrUndefined(e,"builder"),validator_1$k.Validator.throwIfNullOrUndefined(e.logger,"logger")}validateDependencies(e){validator_1$k.Validator.throwIfNullOrUndefined(e,"dependencyContainer"),validator_1$k.Validator.throwIfNullOrUndefined(e.instanceFocusedHandler,"instanceFocusedHandler"),validator_1$k.Validator.throwIfNullOrUndefined(e.instanceReadyHandler,"instanceReadyHandler"),validator_1$k.Validator.throwIfNullOrUndefined(e.instanceStartedHandler,"instanceStartedHandler"),validator_1$k.Validator.throwIfNullOrUndefined(e.instanceStoppedHandler,"instanceStoppedHandler"),validator_1$k.Validator.throwIfNullOrUndefined(e.layoutRestoredHandler,"layoutRestoredHandler"),validator_1$k.Validator.throwIfNullOrUndefined(e.performanceProvider,"performanceProvider"),validator_1$k.Validator.throwIfNullOrUndefined(e.platformStartedHandler,"platformStartedHandler")}}factoryBuilder.MetricsFactoryBuilderValidator=MetricsFactoryBuilderValidator;var factory$1={},factory={};Object.defineProperty(factory,"__esModule",{value:!0}),factory.MetricsFactoryValidator=void 0;const validator_1$j=validator;class MetricsFactoryValidator{validate(e){validator_1$j.Validator.throwIfNullOrUndefined(e,"factory"),validator_1$j.Validator.throwIfNullOrUndefined(e.metricsFactories,"metricsFactories"),validator_1$j.Validator.throwIfNullOrUndefined(e.logger,"logger")}}factory.MetricsFactoryValidator=MetricsFactoryValidator;var customCounter={};Object.defineProperty(customCounter,"__esModule",{value:!0}),customCounter.CustomCounterMetric=void 0;const base_1$g=base$1;class CustomCounterMetric extends base_1$g.MetricBase{constructor(e,t,r,n,i){super(e,t,r,n,i),this.meter=t}createMetricCore(e,t){return this.metric=this.meter.createCounter(e,t)}add(e,t){var r,n;const i=Object.assign(Object.assign({},this.getData()),t);!1!==(null===(r=this.getFilter(i))||void 0===r?void 0:r.enabled)&&(null===(n=this.metric)||void 0===n||n.add(e,this.prePublish(i)))}}customCounter.CustomCounterMetric=CustomCounterMetric;var customObservableGauge={},observable={},__awaiter$8=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(observable,"__esModule",{value:!0}),observable.ObservableMetricBase=void 0;const base_1$f=base$1,otel_1$s=requireDist$1();class ObservableResultWrapper{constructor(e,t,r,n){this.metric=e,this.innerResult=t,this.data=r,this.getFilter=n}observe(e,t){var r,n;const i=this.metric.prePublish(Object.assign(Object.assign({},this.data),t));!1!==(null===(n=null===(r=this.getFilter)||void 0===r?void 0:r.call(this,i))||void 0===n?void 0:n.enabled)&&this.innerResult.observe(e,i)}}class ObservableMetricBase extends base_1$f.MetricBase{constructor(e,t,r,n,i,o,s,a){super(e,t,r,n,i),this.observeCallback=o,this.subscribeCallback=s,this.unsubcribeCallback=a}createMetric(){const e=Object.create(null,{createMetric:{get:()=>super.createMetric}});return __awaiter$8(this,void 0,void 0,function*(){yield e.createMetric.call(this),this.metric=this.metricAny})}subscribeCore(){return otel_1$s.Container.errorlessAsync(()=>{var e,t;return null!==(t=null===(e=this.subscribeCallback)||void 0===e?void 0:e.call(this))&&void 0!==t?t:Promise.resolve()})}unsubscribeCore(){return otel_1$s.Container.errorlessAsync(()=>{var e,t;return null!==(t=null===(e=this.unsubcribeCallback)||void 0===e?void 0:e.call(this))&&void 0!==t?t:Promise.resolve()})}observeCore(e){const t=new ObservableResultWrapper(this,e,this.getData(),this.getFilter.bind(this));return otel_1$s.Container.errorlessAsync(()=>{var e,r;return null!==(r=null===(e=this.observeCallback)||void 0===e?void 0:e.call(this,t))&&void 0!==r?r:Promise.resolve()})}subscribe(){return __awaiter$8(this,void 0,void 0,function*(){this.observableCallback=this.observe.bind(this),this.metric.addCallback(this.observableCallback),yield this.subscribeCore()})}destroyMetric(){return this.metric.removeCallback(this.observableCallback),Promise.resolve()}unsubscribe(){return this.unsubscribeCore()}observe(e){return __awaiter$8(this,void 0,void 0,function*(){try{yield this.observeCore(e)}catch(e){this.settings.name,this.settings.type}})}}observable.ObservableMetricBase=ObservableMetricBase,Object.defineProperty(customObservableGauge,"__esModule",{value:!0}),customObservableGauge.CustomObservableGaugeMetric=void 0;const observable_1$5=observable;class CustomObservableGaugeMetric extends observable_1$5.ObservableMetricBase{createMetricCore(e,t){var r;return null===(r=this.meter)||void 0===r?void 0:r.createObservableGauge(e,t)}}customObservableGauge.CustomObservableGaugeMetric=CustomObservableGaugeMetric;var customObservableCounter={};Object.defineProperty(customObservableCounter,"__esModule",{value:!0}),customObservableCounter.CustomObservableCounterMetric=void 0;const observable_1$4=observable;class CustomObservableCounterMetric extends observable_1$4.ObservableMetricBase{createMetricCore(e,t){var r;return null===(r=this.meter)||void 0===r?void 0:r.createObservableCounter(e,t)}}customObservableCounter.CustomObservableCounterMetric=CustomObservableCounterMetric;var customObservableUpDownCounter={};Object.defineProperty(customObservableUpDownCounter,"__esModule",{value:!0}),customObservableUpDownCounter.CustomObservableUpDownCounterMetric=void 0;const observable_1$3=observable;class CustomObservableUpDownCounterMetric extends observable_1$3.ObservableMetricBase{createMetricCore(e,t){var r;return null===(r=this.meter)||void 0===r?void 0:r.createObservableUpDownCounter(e,t)}}customObservableUpDownCounter.CustomObservableUpDownCounterMetric=CustomObservableUpDownCounterMetric;var customGauge={};Object.defineProperty(customGauge,"__esModule",{value:!0}),customGauge.CustomGaugeMetric=void 0;const base_1$e=base$1;class CustomGaugeMetric extends base_1$e.MetricBase{constructor(e,t,r,n,i){super(e,t,r,n,i),this.meter=t}createMetricCore(e,t){return this.metric=this.meter.createGauge(e,t)}record(e,t){var r,n;const i=Object.assign(Object.assign({},this.getData()),t);!1!==(null===(r=this.getFilter(i))||void 0===r?void 0:r.enabled)&&(null===(n=this.metric)||void 0===n||n.record(e,this.prePublish(i)))}}customGauge.CustomGaugeMetric=CustomGaugeMetric;var __importDefault$1=commonjsGlobal$1&&commonjsGlobal$1.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(factory$1,"__esModule",{value:!0}),factory$1.MetricsFactory=void 0;const factory_1$1=factory,otel_1$r=requireDist$1(),customCounter_1=customCounter,customHistogram_1=customHistogram,customUpDownCounter_1=customUpDownCounter,customObservableGauge_1=customObservableGauge,customObservableCounter_1=customObservableCounter,customObservableUpDownCounter_1=customObservableUpDownCounter,customGauge_1=customGauge,otel_2=requireDist$1(),default_1=_default,lodash_clonedeep_1$1=__importDefault$1(lodash_clonedeepExports);class MetricsFactory{constructor(e,t,r){this.logger=e,this.metricsFactories=t,this.meter=r;(new factory_1$1.MetricsFactoryValidator).validate(this)}create(e,t,r,n,i){var o;const s=e.type;e.name=null!==(o=e.name)&&void 0!==o?o:s,~s.indexOf("observable")&&!r&&otel_2.Container.errorless(()=>{throw new Error(`Metric type ${s} requires observeCallback argument to be provided.`)});if(this.metricsFactories.has(s)){const r=(new default_1.DefaultMetricsSettings).metrics.find(e=>e.name===s),n=this.metricsFactories.get(s),i=(0,lodash_clonedeep_1$1.default)(e);for(const e of Object.keys(i))void 0===i[e]&&delete i[e];return n(Object.assign(Object.assign({},r),i),t)}if("custom_observable_gauge"===s)return new customObservableGauge_1.CustomObservableGaugeMetric(e,this.meter,this.logger,t,[],r,n,i);if("custom_observable_counter"===s)return new customObservableCounter_1.CustomObservableCounterMetric(e,this.meter,this.logger,t,[],r,n,i);if("custom_observable_up_down_counter"===s)return new customObservableUpDownCounter_1.CustomObservableUpDownCounterMetric(e,this.meter,this.logger,t,[],r,n,i);if("custom_counter"===s)return new customCounter_1.CustomCounterMetric(e,this.meter,this.logger,t);if("custom_gauge"===s)return new customGauge_1.CustomGaugeMetric(e,this.meter,this.logger,t);if("custom_up_down_counter"===s)return new customUpDownCounter_1.CustomUpDownCounterMetric(e,this.meter,this.logger,t);if("custom_histogram"===s)return new customHistogram_1.CustomHistogramMetric(e,this.meter,this.logger,t);return this.createNullMetric(e,"not supported")}createNullMetric(e,t){this.logger.debug(`cannot create ${e.name} metric, reason: ${t}`);return new otel_1$r.NullMetric(e,this.logger)}}factory$1.MetricsFactory=MetricsFactory;var count$3={},count$2={};Object.defineProperty(count$2,"__esModule",{value:!0}),count$2.ApplicationCountMetricValidator=void 0;const validator_1$i=validator;class ApplicationCountMetricValidator{validate(e){validator_1$i.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$i.Validator.throwIfNullOrUndefined(e.instanceStartedHandler,"instanceStartedHandler"),validator_1$i.Validator.throwIfNullOrUndefined(e.instanceStoppedHandler,"instanceStoppedHandler")}validateInstanceStarted(e){validator_1$i.Validator.throwIfNullOrUndefined(e,"args"),validator_1$i.Validator.throwIfNullOrUndefined(e.application,"application")}validateInstanceStopped(e){validator_1$i.Validator.throwIfNullOrUndefined(e,"args"),validator_1$i.Validator.throwIfNullOrUndefined(e.application,"application")}}count$2.ApplicationCountMetricValidator=ApplicationCountMetricValidator,Object.defineProperty(count$3,"__esModule",{value:!0}),count$3.ApplicationCountMetric=void 0;const base_1$d=base$1,count_1$2=count$2,otel_1$q=requireDist$1();class ApplicationCountMetric extends base_1$d.MetricBase{constructor(e,t,r,n,i,o,s){super(e,t,r,n,s),this.meter=t,this.instanceStartedHandler=i,this.instanceStoppedHandler=o,this.validator=new count_1$2.ApplicationCountMetricValidator,this.validator.validate(this)}createMetricCore(e,t){return this.appCountMetric=this.meter.createUpDownCounter(e,t)}subscribe(){return this.instanceStartedUn=otel_1$q.Container.errorless(()=>this.instanceStartedHandler(this.handleInstanceStarted.bind(this))),this.instanceStoppedUn=otel_1$q.Container.errorless(()=>this.instanceStoppedHandler(this.handleInstanceStopped.bind(this))),Promise.resolve()}unsubscribe(){return otel_1$q.Container.errorless(()=>this.instanceStartedUn),otel_1$q.Container.errorless(()=>this.instanceStoppedUn),Promise.resolve()}destroyMetric(){return Promise.resolve()}handleInstanceStarted(e){var t;try{this.validator.validateInstanceStarted(e);const r=this.getApplicationData(e.application);if(!1===(null===(t=this.getFilter(r))||void 0===t?void 0:t.enabled))return;this.appCountMetric.add(1,this.prePublish(r))}catch(e){this.settings.type}}handleInstanceStopped(e){var t;try{this.validator.validateInstanceStopped(e);const r=this.getApplicationData(e.application);if(!1===(null===(t=this.getFilter(r))||void 0===t?void 0:t.enabled))return;this.appCountMetric.add(-1,this.prePublish(r))}catch(e){this.settings.type}}}count$3.ApplicationCountMetric=ApplicationCountMetric;var cpu$1={},zeroOutClosedAppObservableGaugeMetricBase={},__awaiter$7=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(zeroOutClosedAppObservableGaugeMetricBase,"__esModule",{value:!0}),zeroOutClosedAppObservableGaugeMetricBase.ZeroOutClosedAppObservableGaugeMetricBase=void 0;const observable_1$2=observable;class ZeroOutClosedAppObservableGaugeMetricBase extends observable_1$2.ObservableMetricBase{observeCore(e){var t;return __awaiter$7(this,void 0,void 0,function*(){const r=yield this.observeCoreCore(e);if(this.reported)for(const n of this.reported.filter(e=>!r.some(t=>e.instance===t.instance))){const r=Object.assign({applicationInstance:n.instance},this.getApplicationData(n.app));!1!==(null===(t=this.getFilter(r))||void 0===t?void 0:t.enabled)&&e.observe(0,this.prePublish(r))}this.reported=r})}createMetricCore(e,t){return this.meter.createObservableGauge(e,t)}}zeroOutClosedAppObservableGaugeMetricBase.ZeroOutClosedAppObservableGaugeMetricBase=ZeroOutClosedAppObservableGaugeMetricBase;var perf={};Object.defineProperty(perf,"__esModule",{value:!0}),perf.PerformanceProviderValidator=void 0;const validator_1$h=validator;class PerformanceProviderValidator{validate(e){validator_1$h.Validator.throwIfNullOrUndefined(e,"performanceProvider")}validateAppsCPU(e){validator_1$h.Validator.throwIfNullOrUndefined(e,"data"),e.forEach(e=>{validator_1$h.Validator.throwIfNullOrUndefined(e,"item"),validator_1$h.Validator.throwIfNullOrUndefined(e.app,"app"),validator_1$h.Validator.throwIfNullOrUndefined(e.instance,"instance"),validator_1$h.Validator.throwIfNullOrUndefined(e.cpu,"cpu")})}validateAppsMemory(e){validator_1$h.Validator.throwIfNullOrUndefined(e,"data"),e.forEach(e=>{validator_1$h.Validator.throwIfNullOrUndefined(e,"item"),validator_1$h.Validator.throwIfNullOrUndefined(e.app,"app"),validator_1$h.Validator.throwIfNullOrUndefined(e.instance,"instance"),validator_1$h.Validator.throwIfNullOrUndefined(e.memory,"memory")})}validateSystemCPU(e){validator_1$h.Validator.throwIfNullOrUndefined(e,"data"),validator_1$h.Validator.throwIfNullOrUndefined(e.current,"current"),validator_1$h.Validator.throwIfNullOrUndefined(e.average,"average"),validator_1$h.Validator.throwIfNullOrUndefined(e.platform,"platform")}validateSystemMemory(e){validator_1$h.Validator.throwIfNullOrUndefined(e,"data"),validator_1$h.Validator.throwIfNullOrUndefined(e.platformTotal,"platformTotal"),validator_1$h.Validator.throwIfNullOrUndefined(e.systemFree,"systemFree"),validator_1$h.Validator.throwIfNullOrUndefined(e.systemTotal,"systemTotal")}}perf.PerformanceProviderValidator=PerformanceProviderValidator;var __awaiter$6=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(cpu$1,"__esModule",{value:!0}),cpu$1.ApplicationCPUMetric=void 0;const zeroOutClosedAppObservableGaugeMetricBase_1$1=zeroOutClosedAppObservableGaugeMetricBase,otel_1$p=requireDist$1(),perf_1$3=perf,validator_1$g=validator;class ApplicationCPUMetric extends zeroOutClosedAppObservableGaugeMetricBase_1$1.ZeroOutClosedAppObservableGaugeMetricBase{constructor(e,t,r,n,i,o){super(e,t,r,n,o),this.perfProvider=i}subscribeCore(){return Promise.resolve()}observeCoreCore(e){return __awaiter$6(this,void 0,void 0,function*(){const t=new perf_1$3.PerformanceProviderValidator;t.validate(this.perfProvider);const r=yield otel_1$p.Container.errorlessAsync(()=>this.perfProvider.getAppsCPU());return validator_1$g.Validator.isNullOrUndefined(r)?[]:(t.validateAppsCPU(r),r.forEach(t=>{var r;const n=Object.assign({applicationInstance:t.instance},this.getApplicationData(t.app));!1!==(null===(r=this.getFilter(n))||void 0===r?void 0:r.enabled)&&e.observe(t.cpu,this.prePublish(n))}),r)})}unsubscribeCore(){return Promise.resolve()}}cpu$1.ApplicationCPUMetric=ApplicationCPUMetric;var crash$1={},crash={};Object.defineProperty(crash,"__esModule",{value:!0}),crash.PlatformCrashMetricValidator=void 0;const validator_1$f=validator;class PlatformCrashMetricValidator{validate(e){validator_1$f.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$f.Validator.throwIfNullOrUndefined(e.instanceCrashHandler,"applicationCrashHandler")}validateApplicationCrash(e){validator_1$f.Validator.throwIfNullOrUndefined(e,"args"),validator_1$f.Validator.throwIfNullOrUndefined(e.application,"application")}}crash.PlatformCrashMetricValidator=PlatformCrashMetricValidator,Object.defineProperty(crash$1,"__esModule",{value:!0}),crash$1.ApplicationCrashMetric=void 0;const base_1$c=base$1,crash_1$1=crash,otel_1$o=requireDist$1();class ApplicationCrashMetric extends base_1$c.MetricBase{constructor(e,t,r,n,i,o){super(e,t,r,n,o),this.meter=t,this.instanceCrashHandler=i,this.validator=new crash_1$1.PlatformCrashMetricValidator,this.validator.validate(this)}createMetricCore(e,t){return this.applicationCrashMetric=this.meter.createCounter(e,t)}subscribe(){return this.applicationCrashUn=otel_1$o.Container.errorless(()=>this.instanceCrashHandler(this.handleInstanceCrash.bind(this))),Promise.resolve()}destroyMetric(){return Promise.resolve()}unsubscribe(){return otel_1$o.Container.errorless(()=>{var e;return null===(e=this.applicationCrashUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}handleInstanceCrash(e){var t;try{this.validator.validateApplicationCrash(e);const r=Object.assign({reason:e.reason},this.getApplicationData(e.application));if(!1===(null===(t=this.getFilter(r))||void 0===t?void 0:t.enabled))return;this.applicationCrashMetric.add(1,this.prePublish(r))}catch(e){this.settings.type}}}crash$1.ApplicationCrashMetric=ApplicationCrashMetric;var duration$1={},duration={};Object.defineProperty(duration,"__esModule",{value:!0}),duration.ApplicationDurationMetricValidator=void 0;const validator_1$e=validator;class ApplicationDurationMetricValidator{validate(e){validator_1$e.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$e.Validator.throwIfNullOrUndefined(e.instanceFocusHandler,"instanceFocusHandler")}validateFocusChanged(e){validator_1$e.Validator.throwIfNullOrUndefined(e,"args"),validator_1$e.Validator.throwIfNullOrUndefined(e.application,"application"),validator_1$e.Validator.throwIfNullOrUndefined(e.focused,"focused")}}duration.ApplicationDurationMetricValidator=ApplicationDurationMetricValidator,Object.defineProperty(duration$1,"__esModule",{value:!0}),duration$1.ApplicationDurationMetric=void 0;const validator_1$d=validator,duration_1$2=duration,observable_1$1=observable,otel_1$n=requireDist$1();class ApplicationDurationMetric extends observable_1$1.ObservableMetricBase{constructor(e,t,r,n,i,o){super(e,t,r,n,o),this.instanceFocusHandler=i,this.focusedTimes=new Map,this.validator=new duration_1$2.ApplicationDurationMetricValidator,this.validator.validate(this)}createMetricCore(e,t){return this.appDurationMetric=this.createRecordingMetric(e,t,"gauge"),this.meter.createObservableGauge(this.createUniqueName(10))}sendMetric(e,t){e.forEach(e=>{this.appDurationMetric.record(e,this.prePublish(t))})}observeCore(){return this.focusedTimes.forEach((e,t)=>{var r;const n=this.getApplicationData(t);!1!==(null===(r=this.getFilter(n))||void 0===r?void 0:r.enabled)&&(this.sendMetric(e,this.prePublish(n)),e.splice(0))}),Promise.resolve()}subscribeCore(){return this.unInstanceFocusHandler=otel_1$n.Container.errorless(()=>this.instanceFocusHandler(this.handleFocusChanged.bind(this))),Promise.resolve()}unsubscribeCore(){return otel_1$n.Container.errorless(()=>{var e;return null===(e=this.unInstanceFocusHandler)||void 0===e?void 0:e.call(this)}),Promise.resolve()}handleFocusChanged(e){try{return this.validator.validateFocusChanged(e),this.handleFocusChangedCore(e)}catch(e){this.settings.type}}handleFocusChangedCore(e){const t=e.focused,r=e.application;if(t)this.handleGotFocus(r);else try{this.handleLostFocus(r)}finally{this.currentFocusedApp=void 0}}handleGotFocus(e){const t=(new Date).getTime();this.currentFocusedApp={name:e,gotFocusTime:t},this.focusedTimes.has(this.currentFocusedApp.name)||this.focusedTimes.set(this.currentFocusedApp.name,[])}handleLostFocus(e){if(validator_1$d.Validator.isNullOrUndefined(this.currentFocusedApp))throw new Error(`cannot handle focus lost for application ${e} since there is no previous got focus event`);const t=this.currentFocusedApp.name,r=this.currentFocusedApp.gotFocusTime;if(e!==t)throw new Error(`cannot handle focus lost for application ${e} since the previous got focus event had come from application ${t}`);if(!this.focusedTimes.has(e))throw new Error(`there is no got focus event for ${e}`);this.addFocusLostEventCore(t,r)}addFocusLostEventCore(e,t){const r=(new Date).getTime()-t;this.focusedTimes.get(e).push(r)}}duration$1.ApplicationDurationMetric=ApplicationDurationMetric;var durationSoft={},__awaiter$5=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(durationSoft,"__esModule",{value:!0}),durationSoft.ApplicationDurationSoftMetric=void 0;const duration_1$1=duration$1;class ApplicationDurationSoftMetric extends duration_1$1.ApplicationDurationMetric{observeCore(){const e=Object.create(null,{observeCore:{get:()=>super.observeCore}});return __awaiter$5(this,void 0,void 0,function*(){const t=void 0!==this.currentFocusedApp,r=t?this.currentFocusedApp.name:void 0;return t&&this.handleFocusChanged({application:r,focused:!1}),yield e.observeCore.call(this),t&&this.handleFocusChanged({application:r,focused:!0}),Promise.resolve()})}}durationSoft.ApplicationDurationSoftMetric=ApplicationDurationSoftMetric;var error$3={},error$2={};Object.defineProperty(error$2,"__esModule",{value:!0}),error$2.ApplicationErrorMetricValidator=void 0;const validator_1$c=validator;class ApplicationErrorMetricValidator{validate(e){validator_1$c.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$c.Validator.throwIfNullOrUndefined(e.instanceErrorHandler,"appErrorHandler")}validateApplicationError(e){validator_1$c.Validator.throwIfNullOrUndefined(e,"args"),validator_1$c.Validator.throwIfNullOrUndefined(e.application,"application")}}error$2.ApplicationErrorMetricValidator=ApplicationErrorMetricValidator,Object.defineProperty(error$3,"__esModule",{value:!0}),error$3.ApplicationErrorMetric=void 0;const base_1$b=base$1,error_1$2=error$2,otel_1$m=requireDist$1();class ApplicationErrorMetric extends base_1$b.MetricBase{constructor(e,t,r,n,i,o){super(e,t,r,n,o),this.meter=t,this.instanceErrorHandler=i,this.validator=new error_1$2.ApplicationErrorMetricValidator,this.validator.validate(this)}createMetricCore(e,t){return this.appErrorMetric=this.meter.createCounter(e,t)}subscribe(){return this.appErrorUn=otel_1$m.Container.errorless(()=>this.instanceErrorHandler(this.instanceApplicationError.bind(this))),Promise.resolve()}destroyMetric(){return Promise.resolve()}unsubscribe(){return otel_1$m.Container.errorless(()=>{var e;return null===(e=this.appErrorUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}instanceApplicationError(e){var t;try{this.validator.validateApplicationError(e);const r=this.getApplicationData(e.application);if(!1===(null===(t=this.getFilter(r))||void 0===t?void 0:t.enabled))return;this.appErrorMetric.add(1,this.prePublish(r))}catch(e){this.settings.type}}}error$3.ApplicationErrorMetric=ApplicationErrorMetric;var memory$1={},__awaiter$4=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(memory$1,"__esModule",{value:!0}),memory$1.ApplicationMemoryMetric=void 0;const perf_1$2=perf,validator_1$b=validator,zeroOutClosedAppObservableGaugeMetricBase_1=zeroOutClosedAppObservableGaugeMetricBase,otel_1$l=requireDist$1();class ApplicationMemoryMetric extends zeroOutClosedAppObservableGaugeMetricBase_1.ZeroOutClosedAppObservableGaugeMetricBase{constructor(e,t,r,n,i,o){super(e,t,r,n,o),this.perfProvider=i,this.validator=new perf_1$2.PerformanceProviderValidator,this.validator.validate(this.perfProvider)}subscribeCore(){return Promise.resolve()}observeCoreCore(e){return __awaiter$4(this,void 0,void 0,function*(){const t=yield otel_1$l.Container.errorlessAsync(()=>this.perfProvider.getAppsMemory());return validator_1$b.Validator.isNullOrUndefined(t)?[]:(this.validator.validateAppsMemory(t),t.forEach(t=>{var r,n;const i=Object.assign({applicationInstance:t.instance},this.getApplicationData(t.app));!1!==(null===(r=this.getFilter(i))||void 0===r?void 0:r.enabled)&&e.observe(null!==(n=t.memory)&&void 0!==n?n:0,this.prePublish(i))}),t)})}unsubscribeCore(){return Promise.resolve()}}memory$1.ApplicationMemoryMetric=ApplicationMemoryMetric;var started$2={},started$1={};Object.defineProperty(started$1,"__esModule",{value:!0}),started$1.ApplicationStartedMetricValidator=void 0;const validator_1$a=validator;class ApplicationStartedMetricValidator{validate(e){validator_1$a.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$a.Validator.throwIfNullOrUndefined(e.instanceStartedHandler,"instanceStartedHandler")}validateInstanceStarted(e){validator_1$a.Validator.throwIfNullOrUndefined(e,"args"),validator_1$a.Validator.throwIfNullOrUndefined(e.application,"application")}}started$1.ApplicationStartedMetricValidator=ApplicationStartedMetricValidator,Object.defineProperty(started$2,"__esModule",{value:!0}),started$2.ApplicationStartedMetric=void 0;const base_1$a=base$1,started_1$1=started$1,otel_1$k=requireDist$1();class ApplicationStartedMetric extends base_1$a.MetricBase{constructor(e,t,r,n,i,o){super(e,t,r,n,o),this.meter=t,this.instanceStartedHandler=i,this.validator=new started_1$1.ApplicationStartedMetricValidator,this.validator.validate(this)}createMetricCore(e,t){return this.appStartedMetric=this.meter.createCounter(e,t)}subscribe(){return this.instanceStartedUn=otel_1$k.Container.errorless(()=>this.instanceStartedHandler(this.handleInstanceStarted.bind(this))),Promise.resolve()}destroyMetric(){return Promise.resolve()}unsubscribe(){return otel_1$k.Container.errorless(()=>{var e;return null===(e=this.instanceStartedUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}handleInstanceStarted(e){var t;try{this.validator.validateInstanceStarted(e);const r=this.getApplicationData(e.application);if(!1===(null===(t=this.getFilter(r))||void 0===t?void 0:t.enabled))return;this.appStartedMetric.add(1,this.prePublish(r))}catch(e){this.settings.type}}}started$2.ApplicationStartedMetric=ApplicationStartedMetric;var startup$3={},startupHistogram$1={};Object.defineProperty(startupHistogram$1,"__esModule",{value:!0}),startupHistogram$1.ApplicationStartupHistogramMetricValidator=void 0;const validator_1$9=validator;class ApplicationStartupHistogramMetricValidator{validate(e){validator_1$9.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$9.Validator.throwIfNullOrUndefined(e.instanceReadyHandler,"instanceReadyHandler")}validateInstanceReady(e){validator_1$9.Validator.throwIfNullOrUndefined(e,"args"),validator_1$9.Validator.throwIfNullOrUndefined(e.application,"application"),validator_1$9.Validator.throwIfNullOrUndefined(e.startTime,"startTime"),validator_1$9.Validator.throwIfNullOrUndefined(e.endTime,"endTime")}}startupHistogram$1.ApplicationStartupHistogramMetricValidator=ApplicationStartupHistogramMetricValidator,Object.defineProperty(startup$3,"__esModule",{value:!0}),startup$3.ApplicationStartupMetric=void 0;const startupHistogram_1$1=startupHistogram$1,base_1$9=base$1,otel_1$j=requireDist$1();class ApplicationStartupMetric extends base_1$9.MetricBase{constructor(e,t,r,n,i,o){super(e,t,r,n,o),this.meter=t,this.instanceReadyHandler=i,this.validator=new startupHistogram_1$1.ApplicationStartupHistogramMetricValidator,this.validator.validate(this)}createMetricCore(e,t){return this.appStartupMetric=this.createRecordingMetric(e,t,"gauge")}subscribe(){return this.instanceReadyUn=otel_1$j.Container.errorless(()=>this.instanceReadyHandler(this.handleInstanceReady.bind(this))),Promise.resolve()}unsubscribe(){return otel_1$j.Container.errorless(()=>{var e;return null===(e=this.instanceReadyUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}destroyMetric(){return Promise.resolve()}handleInstanceReady(e){var t;try{this.validator.validateInstanceReady(e);const r=e.endTime.getTime()-e.startTime.getTime(),n=Object.assign({api:e.api},this.getApplicationData(e.application));if(!1===(null===(t=this.getFilter(n))||void 0===t?void 0:t.enabled))return;this.appStartupMetric.record(r,this.prePublish(n))}catch(e){this.settings.type}}}startup$3.ApplicationStartupMetric=ApplicationStartupMetric;var stopped$2={},stopped$1={};Object.defineProperty(stopped$1,"__esModule",{value:!0}),stopped$1.ApplicationStoppedMetricValidator=void 0;const validator_1$8=validator;class ApplicationStoppedMetricValidator{validate(e){validator_1$8.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$8.Validator.throwIfNullOrUndefined(e.instanceStoppedHandler,"instanceStoppedHandler")}validateInstanceStopped(e){validator_1$8.Validator.throwIfNullOrUndefined(e,"args"),validator_1$8.Validator.throwIfNullOrUndefined(e.application,"application")}}stopped$1.ApplicationStoppedMetricValidator=ApplicationStoppedMetricValidator,Object.defineProperty(stopped$2,"__esModule",{value:!0}),stopped$2.ApplicationStoppedMetric=void 0;const base_1$8=base$1,stopped_1$1=stopped$1,otel_1$i=requireDist$1();class ApplicationStoppedMetric extends base_1$8.MetricBase{constructor(e,t,r,n,i,o){super(e,t,r,n,o),this.meter=t,this.instanceStoppedHandler=i,this.validator=new stopped_1$1.ApplicationStoppedMetricValidator,this.validator.validate(this)}createMetricCore(e,t){return this.appStoppedMetric=this.meter.createCounter(e,t)}subscribe(){return this.instanceStoppedUn=otel_1$i.Container.errorless(()=>this.instanceStoppedHandler(this.handleInstanceStopped.bind(this))),Promise.resolve()}unsubscribe(){return otel_1$i.Container.errorless(()=>{var e;return null===(e=this.instanceStoppedUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}destroyMetric(){return Promise.resolve()}handleInstanceStopped(e){var t;try{this.validator.validateInstanceStopped(e);const r=this.getApplicationData(e.application);if(!1===(null===(t=this.getFilter(r))||void 0===t?void 0:t.enabled))return;this.appStoppedMetric.add(1,this.prePublish(r))}catch(e){this.settings.type}}}stopped$2.ApplicationStoppedMetric=ApplicationStoppedMetric;var startup$2={},startupHistogram={};Object.defineProperty(startupHistogram,"__esModule",{value:!0}),startupHistogram.LayoutStartupMetricHistogramValidator=void 0;const validator_1$7=validator;class LayoutStartupMetricHistogramValidator{validate(e){validator_1$7.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$7.Validator.throwIfNullOrUndefined(e.layoutRestoredHandler,"layoutRestoredHandler")}validateLayoutRestored(e){validator_1$7.Validator.throwIfNullOrUndefined(e,"args"),validator_1$7.Validator.throwIfNullOrUndefined(e.layout,"layout"),validator_1$7.Validator.throwIfNullOrUndefined(e.startTime,"startTime"),validator_1$7.Validator.throwIfNullOrUndefined(e.endTime,"endTime")}}startupHistogram.LayoutStartupMetricHistogramValidator=LayoutStartupMetricHistogramValidator,Object.defineProperty(startup$2,"__esModule",{value:!0}),startup$2.LayoutStartupMetric=void 0;const startupHistogram_1=startupHistogram,base_1$7=base$1,otel_1$h=requireDist$1();class LayoutStartupMetric extends base_1$7.MetricBase{constructor(e,t,r,n,i,o){super(e,t,r,n,o),this.meter=t,this.layoutRestoredHandler=i,this.validator=new startupHistogram_1.LayoutStartupMetricHistogramValidator,this.validator.validate(this)}createMetricCore(e,t){return this.layoutStartupMetric=this.createRecordingMetric(e,t,"gauge")}subscribe(){return this.layoutRestoredUn=otel_1$h.Container.errorless(()=>this.layoutRestoredHandler(this.handleLayoutRestored.bind(this))),Promise.resolve()}unsubscribe(){return otel_1$h.Container.errorless(()=>{var e;return null===(e=this.layoutRestoredUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}handleLayoutRestored(e){var t;try{this.validator.validateLayoutRestored(e);const r=e.endTime.getTime()-e.startTime.getTime(),n=this.getLayoutData(e.layout);if(!1===(null===(t=this.getFilter(n))||void 0===t?void 0:t.enabled))return;this.layoutStartupMetric.record(r,this.prePublish(n))}catch(e){this.settings.type}}}startup$2.LayoutStartupMetric=LayoutStartupMetric;var error$1={},error={};Object.defineProperty(error,"__esModule",{value:!0}),error.PlatformErrorMetricValidator=void 0;const validator_1$6=validator;class PlatformErrorMetricValidator{validate(e){validator_1$6.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$6.Validator.throwIfNullOrUndefined(e.platformErrorHandler,"platformErrorHandler")}validatePlatformError(e){validator_1$6.Validator.throwIfNullOrUndefined(e,"args")}}error.PlatformErrorMetricValidator=PlatformErrorMetricValidator,Object.defineProperty(error$1,"__esModule",{value:!0}),error$1.PlatformErrorMetric=void 0;const base_1$6=base$1,error_1$1=error,otel_1$g=requireDist$1();class PlatformErrorMetric extends base_1$6.MetricBase{constructor(e,t,r,n,i,o){super(e,t,r,n,o),this.meter=t,this.platformErrorHandler=i,this.validator=new error_1$1.PlatformErrorMetricValidator,this.validator.validate(this)}createMetricCore(e,t){return this.platformErrorMetric=this.meter.createCounter(e,t)}subscribe(){return this.platformErrorUn=otel_1$g.Container.errorless(()=>this.platformErrorHandler(this.handlePlatformError.bind(this))),Promise.resolve()}unsubscribe(){var e;return null===(e=this.platformErrorUn)||void 0===e||e.call(this),Promise.resolve()}handlePlatformError(e){var t;try{this.validator.validatePlatformError(e);const r=this.getData();if(!1===(null===(t=this.getFilter(r))||void 0===t?void 0:t.enabled))return;this.platformErrorMetric.add(1,this.prePublish(r))}catch(e){this.settings.type}}}error$1.PlatformErrorMetric=PlatformErrorMetric;var startup$1={},startup={};Object.defineProperty(startup,"__esModule",{value:!0}),startup.PlatformStartupMetricValidator=void 0;const validator_1$5=validator;class PlatformStartupMetricValidator{validate(e){validator_1$5.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$5.Validator.throwIfNullOrUndefined(e.platformStartedHandler,"platformStartedHandler")}validatePlatformStarted(e){validator_1$5.Validator.throwIfNullOrUndefined(e,"args"),validator_1$5.Validator.throwIfNullOrUndefined(e.startTime,"startTime"),validator_1$5.Validator.throwIfNullOrUndefined(e.endTime,"endTime"),validator_1$5.Validator.throwIfNullOrUndefined(e.api,"api")}}startup.PlatformStartupMetricValidator=PlatformStartupMetricValidator,Object.defineProperty(startup$1,"__esModule",{value:!0}),startup$1.PlatformStartupMetric=void 0;const startup_1$2=startup,otel_1$f=requireDist$1(),base_1$5=base$1;class PlatformStartupMetric extends base_1$5.MetricBase{constructor(e,t,r,n,i,o){super(e,t,r,n,o),this.platformStartedHandler=i,this.validator=new startup_1$2.PlatformStartupMetricValidator,this.validator.validate(this)}createMetricCore(e,t){return this.platformStartupMetric=this.createRecordingMetric(e,t,"gauge")}subscribe(){return this.platformStartedUn=otel_1$f.Container.errorless(()=>this.platformStartedHandler(this.handlePlatformStarted.bind(this))),Promise.resolve()}unsubscribe(){return otel_1$f.Container.errorless(()=>{var e;return null===(e=this.platformStartedUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}handlePlatformStarted(e){var t,r;try{this.validator.validatePlatformStarted(e),this.startupTime=e.endTime.getTime()-e.startTime.getTime()-(null!==(t=e.idleTimeMs)&&void 0!==t?t:0),this.apiVersion=e.api;const n=Object.assign({api:this.apiVersion},this.getData());if(!1===(null===(r=this.getFilter(n))||void 0===r?void 0:r.enabled))return;this.platformStartupMetric.record(this.startupTime,this.prePublish(n))}catch(e){this.settings.type}}}startup$1.PlatformStartupMetric=PlatformStartupMetric;var cpu={},observableGauge={};Object.defineProperty(observableGauge,"__esModule",{value:!0}),observableGauge.ObservableGaugeMetricBase=void 0;const observable_1=observable;class ObservableGaugeMetricBase extends observable_1.ObservableMetricBase{createMetricCore(e,t){return this.meter.createObservableGauge(e,t)}}observableGauge.ObservableGaugeMetricBase=ObservableGaugeMetricBase;var __awaiter$3=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(cpu,"__esModule",{value:!0}),cpu.SystemCPUMetric=void 0;const observableGauge_1$1=observableGauge,perf_1$1=perf,validator_1$4=validator,otel_1$e=requireDist$1();class SystemCPUMetric extends observableGauge_1$1.ObservableGaugeMetricBase{constructor(e,t,r,n,i,o){super(e,t,r,n,o),this.perfProvider=i,this.validator=new perf_1$1.PerformanceProviderValidator,this.validator.validate(this.perfProvider)}observeCore(e){return __awaiter$3(this,void 0,void 0,function*(){const t=yield otel_1$e.Container.errorlessAsync(()=>this.perfProvider.getSystemCPU());validator_1$4.Validator.isNullOrUndefined(t)||(this.validator.validateSystemCPU(t),this.sendMetrics(t,e))})}sendMetrics(e,t){var r;let n=this.getData();!1!==(null===(r=this.getFilter(n))||void 0===r?void 0:r.enabled)&&(n=this.prePublish(n),this.settings.name,t.observe(e.current,Object.assign({type:"current_system_cpu"},n)),t.observe(e.average,Object.assign({type:"average_system_cpu"},n)),t.observe(e.platform,Object.assign({type:"average_platform_cpu"},n)))}}cpu.SystemCPUMetric=SystemCPUMetric;var memory={},__awaiter$2=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(memory,"__esModule",{value:!0}),memory.SystemMemoryMetric=void 0;const observableGauge_1=observableGauge,perf_1=perf,validator_1$3=validator,otel_1$d=requireDist$1();class SystemMemoryMetric extends observableGauge_1.ObservableGaugeMetricBase{constructor(e,t,r,n,i,o){super(e,t,r,n,o),this.perfProvider=i,this.validator=new perf_1.PerformanceProviderValidator,this.validator.validate(this.perfProvider)}observeCore(e){return __awaiter$2(this,void 0,void 0,function*(){const t=yield otel_1$d.Container.errorlessAsync(()=>this.perfProvider.getSystemMemory());validator_1$3.Validator.isNullOrUndefined(t)||(this.validator.validateSystemMemory(t),this.sendMetrics(t,e))})}sendMetrics(e,t){var r;let n=this.getData();if(!1===(null===(r=this.getFilter(n))||void 0===r?void 0:r.enabled))return;n=this.prePublish(n),this.settings.name,t.observe(e.platformTotal,Object.assign({type:"used_platform_memory"},n));const i=e.systemTotal-e.systemFree;t.observe(i,Object.assign({type:"used_system_memory"},n)),t.observe(e.systemFree,Object.assign({type:"free_system_memory"},n))}}memory.SystemMemoryMetric=SystemMemoryMetric;var count$1={},count={};Object.defineProperty(count,"__esModule",{value:!0}),count.WorkspaceCountMetricValidator=void 0;const validator_1$2=validator;class WorkspaceCountMetricValidator{validate(e){validator_1$2.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$2.Validator.throwIfNullOrUndefined(e.workspaceStartedHandler,"workspaceStartedHandler"),validator_1$2.Validator.throwIfNullOrUndefined(e.workspaceStoppedHandler,"workspaceStoppedHandler")}validateWorkspaceSaved(e){validator_1$2.Validator.throwIfNullOrUndefined(e,"args"),validator_1$2.Validator.throwIfNullOrUndefined(e.layout,"layout")}validateWorkspaceStarted(e){validator_1$2.Validator.throwIfNullOrUndefined(e,"args"),validator_1$2.Validator.throwIfNullOrUndefined(e.layout,"layout")}validateWorkspaceStopped(e){validator_1$2.Validator.throwIfNullOrUndefined(e,"args"),validator_1$2.Validator.throwIfNullOrUndefined(e.layout,"layout")}}count.WorkspaceCountMetricValidator=WorkspaceCountMetricValidator,Object.defineProperty(count$1,"__esModule",{value:!0}),count$1.WorkspaceCountMetric=void 0;const base_1$4=base$1,count_1$1=count,otel_1$c=requireDist$1();class WorkspaceCountMetric extends base_1$4.MetricBase{constructor(e,t,r,n,i,o,s,a,c){super(e,t,r,n,c),this.meter=t,this.workspaceSavedHandler=i,this.workspaceStartedHandler=o,this.workspaceRestoredHandler=s,this.workspaceStoppedHandler=a,this.validator=new count_1$1.WorkspaceCountMetricValidator,this.validator.validate(this)}createMetricCore(e,t){return this.workspaceCountMetric=this.meter.createUpDownCounter(e,t)}subscribe(){return this.workspaceStartedUn=otel_1$c.Container.errorless(()=>this.workspaceStartedHandler(this.handleWorkspaceStarted.bind(this))),this.workspaceRestoredUn=otel_1$c.Container.errorless(()=>this.workspaceRestoredHandler(this.handleWorkspaceStarted.bind(this))),this.workspaceStoppedUn=otel_1$c.Container.errorless(()=>this.workspaceStoppedHandler(this.handleWorkspaceStopped.bind(this))),this.workspaceSavedUn=otel_1$c.Container.errorless(()=>this.workspaceSavedHandler(this.handleWorkspaceSaved.bind(this))),Promise.resolve()}unsubscribe(){return otel_1$c.Container.errorless(()=>{var e;return null===(e=this.workspaceStartedUn)||void 0===e?void 0:e.call(this)}),otel_1$c.Container.errorless(()=>{var e;return null===(e=this.workspaceRestoredUn)||void 0===e?void 0:e.call(this)}),otel_1$c.Container.errorless(()=>{var e;return null===(e=this.workspaceStoppedUn)||void 0===e?void 0:e.call(this)}),otel_1$c.Container.errorless(()=>{var e;return null===(e=this.workspaceSavedUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}handleWorkspaceSaved(e){var t;try{this.validator.validateWorkspaceSaved(e);const r=this.getLayoutData(e.layout);if(!1===(null===(t=this.getFilter(r))||void 0===t?void 0:t.enabled))return;if(e.oldLayout){const t=this.getLayoutData(e.oldLayout);this.workspaceCountMetric.add(-1,t)}this.workspaceCountMetric.add(1,this.prePublish(r))}catch(e){this.settings.type}}handleWorkspaceStarted(e){var t;try{this.validator.validateWorkspaceStarted(e);const r=this.getLayoutData(e.layout);if(!1===(null===(t=this.getFilter(r))||void 0===t?void 0:t.enabled))return;this.workspaceCountMetric.add(1,this.prePublish(r))}catch(e){this.settings.type}}handleWorkspaceStopped(e){var t;try{this.validator.validateWorkspaceStopped(e);const r=this.getLayoutData(e.layout);if(!1===(null===(t=this.getFilter(r))||void 0===t?void 0:t.enabled))return;this.workspaceCountMetric.add(-1,this.prePublish(r))}catch(e){this.settings.type}}}count$1.WorkspaceCountMetric=WorkspaceCountMetric;var started={},startedOrStoppedMetric={};Object.defineProperty(startedOrStoppedMetric,"__esModule",{value:!0}),startedOrStoppedMetric.WorkspaceStartedOrStoppedMetricValidator=void 0;const validator_1$1=validator;class WorkspaceStartedOrStoppedMetricValidator{validate(e){validator_1$1.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$1.Validator.throwIfNullOrUndefined(e.workspaceActionHandler,"workspaceActionHandler")}validateWorkspaceStarted(e){validator_1$1.Validator.throwIfNullOrUndefined(e,"args")}validateWorkspaceStopped(e){validator_1$1.Validator.throwIfNullOrUndefined(e,"args"),validator_1$1.Validator.throwIfNullOrUndefined(e.layout,"layout")}}startedOrStoppedMetric.WorkspaceStartedOrStoppedMetricValidator=WorkspaceStartedOrStoppedMetricValidator,Object.defineProperty(started,"__esModule",{value:!0}),started.WorkspaceStartedMetric=void 0;const base_1$3=base$1,startedOrStoppedMetric_1$1=startedOrStoppedMetric,otel_1$b=requireDist$1();class WorkspaceStartedMetric extends base_1$3.MetricBase{constructor(e,t,r,n,i,o,s){super(e,t,r,n,s),this.meter=t,this.workspaceActionHandler=i,this.workspaceRestoredHandler=o,this.validator=new startedOrStoppedMetric_1$1.WorkspaceStartedOrStoppedMetricValidator,this.validator.validate(this)}createMetricCore(e,t){return this.workspaceStartedMetric=this.meter.createCounter(e,t)}subscribe(){return this.workspaceStartedUn=otel_1$b.Container.errorless(()=>this.workspaceActionHandler(this.handleWorkspaceStarted.bind(this))),this.workspaceRestoredUn=otel_1$b.Container.errorless(()=>this.workspaceRestoredHandler(this.handleWorkspaceStarted.bind(this))),Promise.resolve()}unsubscribe(){return otel_1$b.Container.errorless(()=>{var e;return null===(e=this.workspaceStartedUn)||void 0===e?void 0:e.call(this)}),otel_1$b.Container.errorless(()=>{var e;return null===(e=this.workspaceRestoredUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}handleWorkspaceStarted(e){var t;try{this.validator.validateWorkspaceStarted(e);const r=this.getLayoutData(e.layout);if(!1===(null===(t=this.getFilter(r))||void 0===t?void 0:t.enabled))return;this.workspaceStartedMetric.add(1,this.prePublish(r))}catch(e){this.settings.type}}}started.WorkspaceStartedMetric=WorkspaceStartedMetric;var startupLegacy={};Object.defineProperty(startupLegacy,"__esModule",{value:!0}),startupLegacy.WorkspaceStartupHistogramMetric=void 0;const startup_1$1=startup$2;class WorkspaceStartupHistogramMetric extends startup_1$1.LayoutStartupMetric{constructor(e,t,r,n,i,o,s){super(e,t,r,n,e=>{const t=this.workspaceLoadedHandler(e),r=this.workspaceRestoredHandler(e);return()=>{t(),r()}},s),this.workspaceLoadedHandler=i,this.workspaceRestoredHandler=o}}startupLegacy.WorkspaceStartupHistogramMetric=WorkspaceStartupHistogramMetric;var stopped={};Object.defineProperty(stopped,"__esModule",{value:!0}),stopped.WorkspaceStoppedMetric=void 0;const base_1$2=base$1,startedOrStoppedMetric_1=startedOrStoppedMetric,otel_1$a=requireDist$1();class WorkspaceStoppedMetric extends base_1$2.MetricBase{constructor(e,t,r,n,i,o){super(e,t,r,n,o),this.meter=t,this.workspaceActionHandler=i,this.validator=new startedOrStoppedMetric_1.WorkspaceStartedOrStoppedMetricValidator,this.validator.validate(this)}createMetricCore(e,t){return this.workspaceStoppedMetric=this.meter.createCounter(e,t)}subscribe(){return this.workspaceStoppedUn=otel_1$a.Container.errorless(()=>this.workspaceActionHandler(this.handleWorkspaceStopped.bind(this))),Promise.resolve()}unsubscribe(){return otel_1$a.Container.errorless(()=>{var e;return null===(e=this.workspaceStoppedUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}handleWorkspaceStopped(e){var t;try{this.validator.validateWorkspaceStopped(e);const r=this.getLayoutData(e.layout);if(!1===(null===(t=this.getFilter(r))||void 0===t?void 0:t.enabled))return;this.workspaceStoppedMetric.add(1,this.prePublish(r))}catch(e){this.settings.type}}}stopped.WorkspaceStoppedMetric=WorkspaceStoppedMetric;var selected={};Object.defineProperty(selected,"__esModule",{value:!0}),selected.WorkspaceSelectedMetric=void 0;const base_1$1=base$1,otel_1$9=requireDist$1();class WorkspaceSelectedMetric extends base_1$1.MetricBase{constructor(e,t,r,n,i,o){super(e,t,r,n,o),this.meter=t,this.workspaceActionHandler=i}createMetricCore(e,t){return this.workspaceSelectedMetric=this.meter.createCounter(e,t)}subscribe(){return this.workspaceSelectedUn=otel_1$9.Container.errorless(()=>this.workspaceActionHandler(this.handleSelectedStopped.bind(this))),Promise.resolve()}unsubscribe(){return otel_1$9.Container.errorless(()=>{var e;return null===(e=this.workspaceSelectedUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}handleSelectedStopped(e){var t;try{const r=this.getLayoutData(e.layout);if(!1===(null===(t=this.getFilter(r))||void 0===t?void 0:t.enabled))return;this.workspaceSelectedMetric.add(1,this.prePublish(r))}catch(e){this.settings.type}}}selected.WorkspaceSelectedMetric=WorkspaceSelectedMetric;var timedGauge={};Object.defineProperty(timedGauge,"__esModule",{value:!0}),timedGauge.WorkspaceTimedGaugeMetric=void 0;const base_1=base$1,otel_1$8=requireDist$1();class WorkspaceTimedGaugeMetric extends base_1.MetricBase{constructor(e,t,r,n,i,o,s){super(e,r,n,t,o),this.subscriber=i,this.getAttributes=s,s||(this.getAttributes=e=>{const t=Object.assign({},e);return delete t.startTime,delete t.endTime,t})}createMetricCore(e,t){return this.metric=this.createRecordingMetric(e,t,"gauge")}subscribe(){return this.unsubscribeCallback=otel_1$8.Container.errorless(()=>this.subscriber(this.handler.bind(this))),Promise.resolve()}unsubscribe(){return otel_1$8.Container.errorless(()=>{var e;return null===(e=this.unsubscribeCallback)||void 0===e?void 0:e.call(this)}),Promise.resolve()}handler(e){var t,r;try{const n=this.getLayoutData(e.layout),i=Object.assign(Object.assign({},n),null===(t=this.getAttributes)||void 0===t?void 0:t.call(this,e));if(!1===(null===(r=this.getFilter(i))||void 0===r?void 0:r.enabled))return;const o=e.endTime.getTime()-e.startTime.getTime();this.metric.record(o,this.prePublish(i))}catch(e){this.settings.type}}}timedGauge.WorkspaceTimedGaugeMetric=WorkspaceTimedGaugeMetric,Object.defineProperty(builder,"__esModule",{value:!0}),builder.MetricsFactoryBuilder=void 0;const factoryBuilder_1=factoryBuilder,factory_1=factory$1,count_1=count$3,cpu_1=cpu$1,crash_1=crash$1,duration_1=duration$1,durationSoft_1=durationSoft,error_1=error$3,memory_1=memory$1,started_1=started$2,startup_1=startup$3,stopped_1=stopped$2,startup_2=startup$2,error_2=error$1,startup_3=startup$1,cpu_2=cpu,memory_2=memory,count_2=count$1,started_2=started,startupLegacy_1=startupLegacy,stopped_2=stopped,selected_1=selected,timedGauge_1=timedGauge;class MetricsFactoryBuilder{constructor(e,t,r){this.lazyMeterProvider=e,this.dependencyContainer=t,this.logger=r,this.metricsFactories=new Map,this.metricsFactories=new Map}get meter(){return this.lazyMeterProvider.getMeter()}build(){(new factoryBuilder_1.MetricsFactoryBuilderValidator).validate(this);return new factory_1.MetricsFactory(this.logger,this.metricsFactories,this.meter)}withDefaults(){return this.withAppStarted().withAppStopped().withAppStartup().withAppCount().withAppDuration().withAppDurationSoft().withAppMemory().withAppCPU().withSystemMemory().withSystemCPU().withAppError().withAppCrash().withLayoutStartup().withWorkspaceStartupLegacy().withWorkspaceStarted().withWorkspaceStopped().withWorkspaceSelected().withWorkspaceCount().withWorkspaceMetric("workspace_startup",e=>e.workspaceStartupHandler,[{attributes:{complexLoad:!0},enabled:!1}]).withWorkspaceMetric("workspace_startup_frame",e=>e.workspaceFrameCreatedHandler,[{attributes:{complexLoad:!0},enabled:!1}]).withWorkspaceMetric("workspace_startup_frame_init",e=>e.workspaceFrameInitHandler,[{attributes:{complexLoad:!0},enabled:!1}]).withWorkspaceMetric("workspace_startup_frame_page_load",e=>e.workspaceFramePageLoadHandler,[{attributes:{complexLoad:!0},enabled:!1}]).withWorkspaceMetric("workspace_startup_frame_workspace_render",e=>e.workspaceFrameWorkspaceRenderHandler,[{attributes:{complexLoad:!0},enabled:!1}]).withWorkspaceMetric("workspace_startup_component",e=>e.workspaceComponentCreatedHandler,[{attributes:{complexLoad:!0},enabled:!1}]).withWorkspaceMetric("workspace_startup_apps",e=>e.workspaceAppsStartedHandler,[{attributes:{complexLoad:!0},enabled:!1}]).withPlatformStartup().withPlatformError()}withWorkspaceMetric(e,t,r,n){return this.metricsFactories.set(e,((e,i)=>new timedGauge_1.WorkspaceTimedGaugeMetric(e,i,this.meter,this.logger,t(this.dependencyContainer),r,n)).bind(this)),this}withAppStarted(){return this.metricsFactories.set("app_started",((e,t)=>new started_1.ApplicationStartedMetric(e,this.meter,this.logger,t,this.dependencyContainer.instanceStartedHandler)).bind(this)),this}withAppStopped(){return this.metricsFactories.set("app_stopped",((e,t)=>new stopped_1.ApplicationStoppedMetric(e,this.meter,this.logger,t,this.dependencyContainer.instanceStoppedHandler)).bind(this)),this}withAppStartup(){return this.metricsFactories.set("app_startup",((e,t)=>new startup_1.ApplicationStartupMetric(e,this.meter,this.logger,t,this.dependencyContainer.instanceReadyHandler)).bind(this)),this}withAppCount(){return this.metricsFactories.set("app_count",((e,t)=>new count_1.ApplicationCountMetric(e,this.meter,this.logger,t,this.dependencyContainer.instanceStartedHandler,this.dependencyContainer.instanceStoppedHandler)).bind(this)),this}withAppDuration(){return this.metricsFactories.set("app_duration",((e,t)=>new duration_1.ApplicationDurationMetric(e,this.meter,this.logger,t,this.dependencyContainer.instanceFocusedHandler)).bind(this)),this}withAppDurationSoft(){return this.metricsFactories.set("app_duration_soft",((e,t)=>new durationSoft_1.ApplicationDurationSoftMetric(e,this.meter,this.logger,t,this.dependencyContainer.instanceFocusedHandler)).bind(this)),this}withAppMemory(){return this.metricsFactories.set("app_memory",((e,t)=>new memory_1.ApplicationMemoryMetric(e,this.meter,this.logger,t,this.dependencyContainer.performanceProvider)).bind(this)),this}withAppCPU(){return this.metricsFactories.set("app_cpu",((e,t)=>new cpu_1.ApplicationCPUMetric(e,this.meter,this.logger,t,this.dependencyContainer.performanceProvider)).bind(this)),this}withAppError(){return this.metricsFactories.set("app_error",((e,t)=>new error_1.ApplicationErrorMetric(e,this.meter,this.logger,t,this.dependencyContainer.instanceErrorHandler)).bind(this)),this}withAppCrash(){return this.metricsFactories.set("app_crash",((e,t)=>new crash_1.ApplicationCrashMetric(e,this.meter,this.logger,t,this.dependencyContainer.instanceCrashHandler)).bind(this)),this}withSystemMemory(){return this.metricsFactories.set("system_memory",((e,t)=>new memory_2.SystemMemoryMetric(e,this.meter,this.logger,t,this.dependencyContainer.performanceProvider)).bind(this)),this}withSystemCPU(){return this.metricsFactories.set("system_cpu",((e,t)=>new cpu_2.SystemCPUMetric(e,this.meter,this.logger,t,this.dependencyContainer.performanceProvider)).bind(this)),this}withLayoutStartup(){return this.metricsFactories.set("layout_startup",((e,t)=>new startup_2.LayoutStartupMetric(e,this.meter,this.logger,t,this.dependencyContainer.layoutRestoredHandler)).bind(this)),this}withWorkspaceStartupLegacy(){return this.metricsFactories.set("workspace_startup_legacy",((e,t)=>new startupLegacy_1.WorkspaceStartupHistogramMetric(e,this.meter,this.logger,t,this.dependencyContainer.workspaceLoadedHandler,this.dependencyContainer.workspaceRestoredHandler)).bind(this)),this}withWorkspaceStarted(){return this.metricsFactories.set("workspace_started",((e,t)=>new started_2.WorkspaceStartedMetric(e,this.meter,this.logger,t,this.dependencyContainer.workspaceStartedHandler,this.dependencyContainer.workspaceRestoredHandler)).bind(this)),this}withWorkspaceStopped(){return this.metricsFactories.set("workspace_stopped",((e,t)=>new stopped_2.WorkspaceStoppedMetric(e,this.meter,this.logger,t,this.dependencyContainer.workspaceStoppedHandler)).bind(this)),this}withWorkspaceSelected(){return this.metricsFactories.set("workspace_selected",((e,t)=>new selected_1.WorkspaceSelectedMetric(e,this.meter,this.logger,t,this.dependencyContainer.workspaceSelectedHandler)).bind(this)),this}withWorkspaceCount(){return this.metricsFactories.set("workspace_count",((e,t)=>new count_2.WorkspaceCountMetric(e,this.meter,this.logger,t,this.dependencyContainer.workspaceSavedHandler,this.dependencyContainer.workspaceStartedHandler,this.dependencyContainer.workspaceRestoredHandler,this.dependencyContainer.workspaceStoppedHandler)).bind(this)),this}withPlatformStartup(){return this.metricsFactories.set("platform_startup",((e,t)=>new startup_3.PlatformStartupMetric(e,this.meter,this.logger,t,this.dependencyContainer.platformStartedHandler)).bind(this)),this}withPlatformError(){return this.metricsFactories.set("platform_error",((e,t)=>new error_2.PlatformErrorMetric(e,this.meter,this.logger,t,this.dependencyContainer.platformErrorHandler)).bind(this)),this}}builder.MetricsFactoryBuilder=MetricsFactoryBuilder;var providerFactory={},AggregationTemporality$2,InstrumentType$2,DataPointType$2;function hashAttributes(e){let t=Object.keys(e);return 0===t.length?"":(t=t.sort(),JSON.stringify(t.map(t=>[t,e[t]])))}function instrumentationScopeId(e){return`${e.name}:${e.version??""}:${e.schemaUrl??""}`}!function(e){e[e.DELTA=0]="DELTA",e[e.CUMULATIVE=1]="CUMULATIVE"}(AggregationTemporality$2||(AggregationTemporality$2={})),function(e){e.COUNTER="COUNTER",e.GAUGE="GAUGE",e.HISTOGRAM="HISTOGRAM",e.UP_DOWN_COUNTER="UP_DOWN_COUNTER",e.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",e.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",e.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"}(InstrumentType$2||(InstrumentType$2={})),function(e){e[e.HISTOGRAM=0]="HISTOGRAM",e[e.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",e[e.GAUGE=2]="GAUGE",e[e.SUM=3]="SUM"}(DataPointType$2||(DataPointType$2={}));let TimeoutError$1=class e extends Error{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype)}};function callWithTimeout$1(e,t){let r;const n=new Promise(function(e,n){r=setTimeout(function(){n(new TimeoutError$1("Operation timed out."))},t)});return Promise.race([e,n]).then(e=>(clearTimeout(r),e),e=>{throw clearTimeout(r),e})}function setEquals(e,t){if(e.size!==t.size)return!1;for(const r of e)if(!t.has(r))return!1;return!0}function binarySearchUB(e,t){let r=0,n=e.length-1,i=e.length;for(;n>=r;){const o=r+Math.trunc((n-r)/2);e[o]<t?r=o+1:(i=o,n=o-1)}return i}function equalsCaseInsensitive(e,t){return e.toLowerCase()===t.toLowerCase()}var AggregatorKind;!function(e){e[e.DROP=0]="DROP",e[e.SUM=1]="SUM",e[e.LAST_VALUE=2]="LAST_VALUE",e[e.HISTOGRAM=3]="HISTOGRAM",e[e.EXPONENTIAL_HISTOGRAM=4]="EXPONENTIAL_HISTOGRAM"}(AggregatorKind||(AggregatorKind={}));class DropAggregator{kind=AggregatorKind.DROP;createAccumulation(){}merge(e,t){}diff(e,t){}toMetricData(e,t,r,n){}}function createNewEmptyCheckpoint(e){const t=e.map(()=>0);return t.push(0),{buckets:{boundaries:e,counts:t},sum:0,count:0,hasMinMax:!1,min:1/0,max:-1/0}}class HistogramAccumulation{startTime;_boundaries;_recordMinMax;_current;constructor(e,t,r=!0,n=createNewEmptyCheckpoint(t)){this.startTime=e,this._boundaries=t,this._recordMinMax=r,this._current=n}record(e){if(Number.isNaN(e))return;this._current.count+=1,this._current.sum+=e,this._recordMinMax&&(this._current.min=Math.min(e,this._current.min),this._current.max=Math.max(e,this._current.max),this._current.hasMinMax=!0);const t=binarySearchUB(this._boundaries,e);this._current.buckets.counts[t]+=1}setStartTime(e){this.startTime=e}toPointValue(){return this._current}}class HistogramAggregator{kind=AggregatorKind.HISTOGRAM;_boundaries;_recordMinMax;constructor(e,t){this._boundaries=e,this._recordMinMax=t}createAccumulation(e){return new HistogramAccumulation(e,this._boundaries,this._recordMinMax)}merge(e,t){const r=e.toPointValue(),n=t.toPointValue(),i=r.buckets.counts,o=n.buckets.counts,s=new Array(i.length);for(let e=0;e<i.length;e++)s[e]=i[e]+o[e];let a=1/0,c=-1/0;return this._recordMinMax&&(r.hasMinMax&&n.hasMinMax?(a=Math.min(r.min,n.min),c=Math.max(r.max,n.max)):r.hasMinMax?(a=r.min,c=r.max):n.hasMinMax&&(a=n.min,c=n.max)),new HistogramAccumulation(e.startTime,r.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:r.buckets.boundaries,counts:s},count:r.count+n.count,sum:r.sum+n.sum,hasMinMax:this._recordMinMax&&(r.hasMinMax||n.hasMinMax),min:a,max:c})}diff(e,t){const r=e.toPointValue(),n=t.toPointValue(),i=r.buckets.counts,o=n.buckets.counts,s=new Array(i.length);for(let e=0;e<i.length;e++)s[e]=o[e]-i[e];return new HistogramAccumulation(t.startTime,r.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:r.buckets.boundaries,counts:s},count:n.count-r.count,sum:n.sum-r.sum,hasMinMax:!1,min:1/0,max:-1/0})}toMetricData(e,t,r,n){return{descriptor:e,aggregationTemporality:t,dataPointType:DataPointType$2.HISTOGRAM,dataPoints:r.map(([t,r])=>{const i=r.toPointValue(),o=e.type===InstrumentType$2.GAUGE||e.type===InstrumentType$2.UP_DOWN_COUNTER||e.type===InstrumentType$2.OBSERVABLE_GAUGE||e.type===InstrumentType$2.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:t,startTime:r.startTime,endTime:n,value:{min:i.hasMinMax?i.min:void 0,max:i.hasMinMax?i.max:void 0,sum:o?void 0:i.sum,buckets:i.buckets,count:i.count}}})}}}class Buckets{backing;indexBase;indexStart;indexEnd;constructor(e=new BucketsBacking,t=0,r=0,n=0){this.backing=e,this.indexBase=t,this.indexStart=r,this.indexEnd=n}get offset(){return this.indexStart}get length(){return 0===this.backing.length||this.indexEnd===this.indexStart&&0===this.at(0)?0:this.indexEnd-this.indexStart+1}counts(){return Array.from({length:this.length},(e,t)=>this.at(t))}at(e){const t=this.indexBase-this.indexStart;return e<t&&(e+=this.backing.length),e-=t,this.backing.countAt(e)}incrementBucket(e,t){this.backing.increment(e,t)}decrementBucket(e,t){this.backing.decrement(e,t)}trim(){for(let e=0;e<this.length;e++){if(0!==this.at(e)){this.indexStart+=e;break}if(e===this.length-1)return void(this.indexStart=this.indexEnd=this.indexBase=0)}for(let e=this.length-1;e>=0;e--)if(0!==this.at(e)){this.indexEnd-=this.length-e-1;break}this._rotate()}downscale(e){this._rotate();const t=1+this.indexEnd-this.indexStart,r=1<<e;let n=0,i=0;for(let e=this.indexStart;e<=this.indexEnd;){let o=e%r;o<0&&(o+=r);for(let s=o;s<r&&n<t;s++)this._relocateBucket(i,n),n++,e++;i++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart}clone(){return new Buckets(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)}_rotate(){const e=this.indexBase-this.indexStart;0!==e&&(e>0?(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,e),this.backing.reverse(e,this.backing.length)):(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,this.backing.length+e)),this.indexBase=this.indexStart)}_relocateBucket(e,t){e!==t&&this.incrementBucket(e,this.backing.emptyBucket(t))}}class BucketsBacking{_counts;constructor(e=[0]){this._counts=e}get length(){return this._counts.length}countAt(e){return this._counts[e]}growTo(e,t,r){const n=new Array(e).fill(0);n.splice(r,this._counts.length-t,...this._counts.slice(t)),n.splice(0,t,...this._counts.slice(0,t)),this._counts=n}reverse(e,t){const r=Math.floor((e+t)/2)-e;for(let n=0;n<r;n++){const r=this._counts[e+n];this._counts[e+n]=this._counts[t-n-1],this._counts[t-n-1]=r}}emptyBucket(e){const t=this._counts[e];return this._counts[e]=0,t}increment(e,t){this._counts[e]+=t}decrement(e,t){this._counts[e]>=t?this._counts[e]-=t:this._counts[e]=0}clone(){return new BucketsBacking([...this._counts])}}const SIGNIFICAND_WIDTH=52,EXPONENT_MASK=2146435072,SIGNIFICAND_MASK=1048575,EXPONENT_BIAS=1023,MIN_NORMAL_EXPONENT=1-EXPONENT_BIAS,MAX_NORMAL_EXPONENT=EXPONENT_BIAS,MIN_VALUE=Math.pow(2,-1022);function getNormalBase2(e){const t=new DataView(new ArrayBuffer(8));t.setFloat64(0,e);return((t.getUint32(0)&EXPONENT_MASK)>>20)-EXPONENT_BIAS}function getSignificand(e){const t=new DataView(new ArrayBuffer(8));t.setFloat64(0,e);const r=t.getUint32(0),n=t.getUint32(4);return(r&SIGNIFICAND_MASK)*Math.pow(2,32)+n}function ldexp(e,t){return 0===e||e===Number.POSITIVE_INFINITY||e===Number.NEGATIVE_INFINITY||Number.isNaN(e)?e:e*Math.pow(2,t)}function nextGreaterSquare(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,++e}class MappingError extends Error{}class ExponentMapping{_shift;constructor(e){this._shift=-e}mapToIndex(e){if(e<MIN_VALUE)return this._minNormalLowerBoundaryIndex();return getNormalBase2(e)+this._rightShift(getSignificand(e)-1,SIGNIFICAND_WIDTH)>>this._shift}lowerBoundary(e){const t=this._minNormalLowerBoundaryIndex();if(e<t)throw new MappingError(`underflow: ${e} is < minimum lower boundary: ${t}`);const r=this._maxNormalLowerBoundaryIndex();if(e>r)throw new MappingError(`overflow: ${e} is > maximum lower boundary: ${r}`);return ldexp(1,e<<this._shift)}get scale(){return 0===this._shift?0:-this._shift}_minNormalLowerBoundaryIndex(){let e=MIN_NORMAL_EXPONENT>>this._shift;return this._shift<2&&e--,e}_maxNormalLowerBoundaryIndex(){return MAX_NORMAL_EXPONENT>>this._shift}_rightShift(e,t){return Math.floor(e*Math.pow(2,-t))}}class LogarithmMapping{_scale;_scaleFactor;_inverseFactor;constructor(e){this._scale=e,this._scaleFactor=ldexp(Math.LOG2E,e),this._inverseFactor=ldexp(Math.LN2,-e)}mapToIndex(e){if(e<=MIN_VALUE)return this._minNormalLowerBoundaryIndex()-1;if(0===getSignificand(e)){return(getNormalBase2(e)<<this._scale)-1}const t=Math.floor(Math.log(e)*this._scaleFactor),r=this._maxNormalLowerBoundaryIndex();return t>=r?r:t}lowerBoundary(e){const t=this._maxNormalLowerBoundaryIndex();if(e>=t){if(e===t)return 2*Math.exp((e-(1<<this._scale))/this._scaleFactor);throw new MappingError(`overflow: ${e} is > maximum lower boundary: ${t}`)}const r=this._minNormalLowerBoundaryIndex();if(e<=r){if(e===r)return MIN_VALUE;if(e===r-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new MappingError(`overflow: ${e} is < minimum lower boundary: ${r}`)}return Math.exp(e*this._inverseFactor)}get scale(){return this._scale}_minNormalLowerBoundaryIndex(){return MIN_NORMAL_EXPONENT<<this._scale}_maxNormalLowerBoundaryIndex(){return(MAX_NORMAL_EXPONENT+1<<this._scale)-1}}const MIN_SCALE=-10,MAX_SCALE$1=20,PREBUILT_MAPPINGS=Array.from({length:31},(e,t)=>t>10?new LogarithmMapping(t-10):new ExponentMapping(t-10));function getMapping(e){if(e>MAX_SCALE$1||e<MIN_SCALE)throw new MappingError(`expected scale >= ${MIN_SCALE} && <= ${MAX_SCALE$1}, got: ${e}`);return PREBUILT_MAPPINGS[e+10]}class HighLow{static combine(e,t){return new HighLow(Math.min(e.low,t.low),Math.max(e.high,t.high))}low;high;constructor(e,t){this.low=e,this.high=t}}const MAX_SCALE=20,DEFAULT_MAX_SIZE=160,MIN_MAX_SIZE=2;class ExponentialHistogramAccumulation{startTime;_maxSize;_recordMinMax;_sum;_count;_zeroCount;_min;_max;_positive;_negative;_mapping;constructor(e,t=DEFAULT_MAX_SIZE,r=!0,n=0,i=0,o=0,s=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY,c=new Buckets,l=new Buckets,u=getMapping(MAX_SCALE)){this.startTime=e,this._maxSize=t,this._recordMinMax=r,this._sum=n,this._count=i,this._zeroCount=o,this._min=s,this._max=a,this._positive=c,this._negative=l,this._mapping=u,this._maxSize<MIN_MAX_SIZE&&(diag.warn(`Exponential Histogram Max Size set to ${this._maxSize}, changing to the minimum size of: ${MIN_MAX_SIZE}`),this._maxSize=MIN_MAX_SIZE)}record(e){this.updateByIncrement(e,1)}setStartTime(e){this.startTime=e}toPointValue(){return{hasMinMax:this._recordMinMax,min:this.min,max:this.max,sum:this.sum,positive:{offset:this.positive.offset,bucketCounts:this.positive.counts()},negative:{offset:this.negative.offset,bucketCounts:this.negative.counts()},count:this.count,scale:this.scale,zeroCount:this.zeroCount}}get sum(){return this._sum}get min(){return this._min}get max(){return this._max}get count(){return this._count}get zeroCount(){return this._zeroCount}get scale(){return this._count===this._zeroCount?0:this._mapping.scale}get positive(){return this._positive}get negative(){return this._negative}updateByIncrement(e,t){Number.isNaN(e)||(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=t,0!==e?(this._sum+=e*t,e>0?this._updateBuckets(this._positive,e,t):this._updateBuckets(this._negative,-e,t)):this._zeroCount+=t)}merge(e){0===this._count?(this._min=e.min,this._max=e.max):0!==e.count&&(e.min<this.min&&(this._min=e.min),e.max>this.max&&(this._max=e.max)),this.startTime=e.startTime,this._sum+=e.sum,this._count+=e.count,this._zeroCount+=e.zeroCount;const t=this._minScale(e);this._downscale(this.scale-t),this._mergeBuckets(this.positive,e,e.positive,t),this._mergeBuckets(this.negative,e,e.negative,t)}diff(e){this._min=1/0,this._max=-1/0,this._sum-=e.sum,this._count-=e.count,this._zeroCount-=e.zeroCount;const t=this._minScale(e);this._downscale(this.scale-t),this._diffBuckets(this.positive,e,e.positive,t),this._diffBuckets(this.negative,e,e.negative,t)}clone(){return new ExponentialHistogramAccumulation(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)}_updateBuckets(e,t,r){let n=this._mapping.mapToIndex(t),i=!1,o=0,s=0;if(0===e.length?(e.indexStart=n,e.indexEnd=e.indexStart,e.indexBase=e.indexStart):n<e.indexStart&&e.indexEnd-n>=this._maxSize?(i=!0,s=n,o=e.indexEnd):n>e.indexEnd&&n-e.indexStart>=this._maxSize&&(i=!0,s=e.indexStart,o=n),i){const e=this._changeScale(o,s);this._downscale(e),n=this._mapping.mapToIndex(t)}this._incrementIndexBy(e,n,r)}_incrementIndexBy(e,t,r){if(0===r)return;if(0===e.length&&(e.indexStart=e.indexEnd=e.indexBase=t),t<e.indexStart){const r=e.indexEnd-t;r>=e.backing.length&&this._grow(e,r+1),e.indexStart=t}else if(t>e.indexEnd){const r=t-e.indexStart;r>=e.backing.length&&this._grow(e,r+1),e.indexEnd=t}let n=t-e.indexBase;n<0&&(n+=e.backing.length),e.incrementBucket(n,r)}_grow(e,t){const r=e.backing.length,n=e.indexBase-e.indexStart,i=r-n;let o=nextGreaterSquare(t);o>this._maxSize&&(o=this._maxSize);const s=o-n;e.backing.growTo(o,i,s)}_changeScale(e,t){let r=0;for(;e-t>=this._maxSize;)e>>=1,t>>=1,r++;return r}_downscale(e){if(0===e)return;if(e<0)throw new Error(`impossible change of scale: ${this.scale}`);const t=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=getMapping(t)}_minScale(e){const t=Math.min(this.scale,e.scale),r=HighLow.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),n=HighLow.combine(this._highLowAtScale(this.negative,this.scale,t),this._highLowAtScale(e.negative,e.scale,t));return Math.min(t-this._changeScale(r.high,r.low),t-this._changeScale(n.high,n.low))}_highLowAtScale(e,t,r){if(0===e.length)return new HighLow(0,-1);const n=t-r;return new HighLow(e.indexStart>>n,e.indexEnd>>n)}_mergeBuckets(e,t,r,n){const i=r.offset,o=t.scale-n;for(let t=0;t<r.length;t++)this._incrementIndexBy(e,i+t>>o,r.at(t))}_diffBuckets(e,t,r,n){const i=r.offset,o=t.scale-n;for(let t=0;t<r.length;t++){let n=(i+t>>o)-e.indexBase;n<0&&(n+=e.backing.length),e.decrementBucket(n,r.at(t))}e.trim()}}class ExponentialHistogramAggregator{kind=AggregatorKind.EXPONENTIAL_HISTOGRAM;_maxSize;_recordMinMax;constructor(e,t){this._maxSize=e,this._recordMinMax=t}createAccumulation(e){return new ExponentialHistogramAccumulation(e,this._maxSize,this._recordMinMax)}merge(e,t){const r=t.clone();return r.merge(e),r}diff(e,t){const r=t.clone();return r.diff(e),r}toMetricData(e,t,r,n){return{descriptor:e,aggregationTemporality:t,dataPointType:DataPointType$2.EXPONENTIAL_HISTOGRAM,dataPoints:r.map(([t,r])=>{const i=r.toPointValue(),o=e.type===InstrumentType$2.GAUGE||e.type===InstrumentType$2.UP_DOWN_COUNTER||e.type===InstrumentType$2.OBSERVABLE_GAUGE||e.type===InstrumentType$2.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:t,startTime:r.startTime,endTime:n,value:{min:i.hasMinMax?i.min:void 0,max:i.hasMinMax?i.max:void 0,sum:o?void 0:i.sum,positive:{offset:i.positive.offset,bucketCounts:i.positive.bucketCounts},negative:{offset:i.negative.offset,bucketCounts:i.negative.bucketCounts},count:i.count,scale:i.scale,zeroCount:i.zeroCount}}})}}}const SUPPRESS_TRACING_KEY$2=createContextKey("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function suppressTracing$2(e){return e.setValue(SUPPRESS_TRACING_KEY$2,!0)}function loggingErrorHandler$2(){return e=>{diag.error(stringifyException$2(e))}}function stringifyException$2(e){return"string"==typeof e?e:JSON.stringify(flattenException$2(e))}function flattenException$2(e){const t={};let r=e;for(;null!==r;)Object.getOwnPropertyNames(r).forEach(e=>{if(t[e])return;const n=r[e];n&&(t[e]=String(n))}),r=Object.getPrototypeOf(r);return t}let delegateHandler$2=loggingErrorHandler$2();function globalErrorHandler$2(e){try{delegateHandler$2(e)}catch{}}const VERSION$2="2.7.0",ATTR_PROCESS_RUNTIME_NAME="process.runtime.name",SDK_INFO$1={[ATTR_TELEMETRY_SDK_NAME]:"opentelemetry",[ATTR_PROCESS_RUNTIME_NAME]:"browser",[ATTR_TELEMETRY_SDK_LANGUAGE]:TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS,[ATTR_TELEMETRY_SDK_VERSION]:VERSION$2},NANOSECOND_DIGITS_IN_MILLIS$2=6,MILLISECONDS_TO_NANOSECONDS$2=Math.pow(10,NANOSECOND_DIGITS_IN_MILLIS$2);function millisToHrTime$2(e){const t=e/1e3;return[Math.trunc(t),Math.round(e%1e3*MILLISECONDS_TO_NANOSECONDS$2)]}function hrTimeToMicroseconds$2(e){return 1e6*e[0]+e[1]/1e3}var ExportResultCode$2;function _export$2(e,t){return new Promise(r=>{context.with(suppressTracing$2(context.active()),()=>{e.export(t,r)})})}!function(e){e[e.SUCCESS=0]="SUCCESS",e[e.FAILED=1]="FAILED"}(ExportResultCode$2||(ExportResultCode$2={}));const internal$2={_export:_export$2};class LastValueAccumulation{startTime;_current;sampleTime;constructor(e,t=0,r=[0,0]){this.startTime=e,this._current=t,this.sampleTime=r}record(e){this._current=e,this.sampleTime=millisToHrTime$2(Date.now())}setStartTime(e){this.startTime=e}toPointValue(){return this._current}}class LastValueAggregator{kind=AggregatorKind.LAST_VALUE;createAccumulation(e){return new LastValueAccumulation(e)}merge(e,t){const r=hrTimeToMicroseconds$2(t.sampleTime)>=hrTimeToMicroseconds$2(e.sampleTime)?t:e;return new LastValueAccumulation(e.startTime,r.toPointValue(),r.sampleTime)}diff(e,t){const r=hrTimeToMicroseconds$2(t.sampleTime)>=hrTimeToMicroseconds$2(e.sampleTime)?t:e;return new LastValueAccumulation(t.startTime,r.toPointValue(),r.sampleTime)}toMetricData(e,t,r,n){return{descriptor:e,aggregationTemporality:t,dataPointType:DataPointType$2.GAUGE,dataPoints:r.map(([e,t])=>({attributes:e,startTime:t.startTime,endTime:n,value:t.toPointValue()}))}}}class SumAccumulation{startTime;monotonic;_current;reset;constructor(e,t,r=0,n=!1){this.startTime=e,this.monotonic=t,this._current=r,this.reset=n}record(e){this.monotonic&&e<0||(this._current+=e)}setStartTime(e){this.startTime=e}toPointValue(){return this._current}}class SumAggregator{kind=AggregatorKind.SUM;monotonic;constructor(e){this.monotonic=e}createAccumulation(e){return new SumAccumulation(e,this.monotonic)}merge(e,t){const r=e.toPointValue(),n=t.toPointValue();return t.reset?new SumAccumulation(t.startTime,this.monotonic,n,t.reset):new SumAccumulation(e.startTime,this.monotonic,r+n)}diff(e,t){const r=e.toPointValue(),n=t.toPointValue();return this.monotonic&&r>n?new SumAccumulation(t.startTime,this.monotonic,n,!0):new SumAccumulation(t.startTime,this.monotonic,n-r)}toMetricData(e,t,r,n){return{descriptor:e,aggregationTemporality:t,dataPointType:DataPointType$2.SUM,dataPoints:r.map(([e,t])=>({attributes:e,startTime:t.startTime,endTime:n,value:t.toPointValue()})),isMonotonic:this.monotonic}}}class DropAggregation{static DEFAULT_INSTANCE=new DropAggregator;createAggregator(e){return DropAggregation.DEFAULT_INSTANCE}}class SumAggregation{static MONOTONIC_INSTANCE=new SumAggregator(!0);static NON_MONOTONIC_INSTANCE=new SumAggregator(!1);createAggregator(e){switch(e.type){case InstrumentType$2.COUNTER:case InstrumentType$2.OBSERVABLE_COUNTER:case InstrumentType$2.HISTOGRAM:return SumAggregation.MONOTONIC_INSTANCE;default:return SumAggregation.NON_MONOTONIC_INSTANCE}}}class LastValueAggregation{static DEFAULT_INSTANCE=new LastValueAggregator;createAggregator(e){return LastValueAggregation.DEFAULT_INSTANCE}}class HistogramAggregation{static DEFAULT_INSTANCE=new HistogramAggregator([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0);createAggregator(e){return HistogramAggregation.DEFAULT_INSTANCE}}class ExplicitBucketHistogramAggregation{_boundaries;_recordMinMax;constructor(e,t=!0){if(null==e)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");e=(e=e.concat()).sort((e,t)=>e-t);const r=e.lastIndexOf(-1/0);let n=e.indexOf(1/0);-1===n&&(n=void 0),this._boundaries=e.slice(r+1,n),this._recordMinMax=t}createAggregator(e){return new HistogramAggregator(this._boundaries,this._recordMinMax)}}class ExponentialHistogramAggregation{_maxSize;_recordMinMax;constructor(e=160,t=!0){this._maxSize=e,this._recordMinMax=t}createAggregator(e){return new ExponentialHistogramAggregator(this._maxSize,this._recordMinMax)}}class DefaultAggregation{_resolve(e){switch(e.type){case InstrumentType$2.COUNTER:case InstrumentType$2.UP_DOWN_COUNTER:case InstrumentType$2.OBSERVABLE_COUNTER:case InstrumentType$2.OBSERVABLE_UP_DOWN_COUNTER:return SUM_AGGREGATION;case InstrumentType$2.GAUGE:case InstrumentType$2.OBSERVABLE_GAUGE:return LAST_VALUE_AGGREGATION;case InstrumentType$2.HISTOGRAM:return e.advice.explicitBucketBoundaries?new ExplicitBucketHistogramAggregation(e.advice.explicitBucketBoundaries):HISTOGRAM_AGGREGATION}return diag.warn(`Unable to recognize instrument type: ${e.type}`),DROP_AGGREGATION}createAggregator(e){return this._resolve(e).createAggregator(e)}}const DROP_AGGREGATION=new DropAggregation,SUM_AGGREGATION=new SumAggregation,LAST_VALUE_AGGREGATION=new LastValueAggregation,HISTOGRAM_AGGREGATION=new HistogramAggregation,DEFAULT_AGGREGATION$1=new DefaultAggregation;var AggregationType$1;function toAggregation(e){switch(e.type){case AggregationType$1.DEFAULT:return DEFAULT_AGGREGATION$1;case AggregationType$1.DROP:return DROP_AGGREGATION;case AggregationType$1.SUM:return SUM_AGGREGATION;case AggregationType$1.LAST_VALUE:return LAST_VALUE_AGGREGATION;case AggregationType$1.EXPONENTIAL_HISTOGRAM:{const t=e;return new ExponentialHistogramAggregation(t.options?.maxSize,t.options?.recordMinMax)}case AggregationType$1.EXPLICIT_BUCKET_HISTOGRAM:{const t=e;return null==t.options?HISTOGRAM_AGGREGATION:new ExplicitBucketHistogramAggregation(t.options?.boundaries,t.options?.recordMinMax)}default:throw new Error("Unsupported Aggregation")}}!function(e){e[e.DEFAULT=0]="DEFAULT",e[e.DROP=1]="DROP",e[e.SUM=2]="SUM",e[e.LAST_VALUE=3]="LAST_VALUE",e[e.EXPLICIT_BUCKET_HISTOGRAM=4]="EXPLICIT_BUCKET_HISTOGRAM",e[e.EXPONENTIAL_HISTOGRAM=5]="EXPONENTIAL_HISTOGRAM"}(AggregationType$1||(AggregationType$1={}));const DEFAULT_AGGREGATION_SELECTOR=e=>({type:AggregationType$1.DEFAULT}),DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR=e=>AggregationTemporality$2.CUMULATIVE;class MetricReader{_shutdown=!1;_metricProducers;_sdkMetricProducer;_aggregationTemporalitySelector;_aggregationSelector;_cardinalitySelector;constructor(e){this._aggregationSelector=e?.aggregationSelector??DEFAULT_AGGREGATION_SELECTOR,this._aggregationTemporalitySelector=e?.aggregationTemporalitySelector??DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR,this._metricProducers=e?.metricProducers??[],this._cardinalitySelector=e?.cardinalitySelector}setMetricProducer(e){if(this._sdkMetricProducer)throw new Error("MetricReader can not be bound to a MeterProvider again.");this._sdkMetricProducer=e,this.onInitialized()}selectAggregation(e){return this._aggregationSelector(e)}selectAggregationTemporality(e){return this._aggregationTemporalitySelector(e)}selectCardinalityLimit(e){return this._cardinalitySelector?this._cardinalitySelector(e):2e3}onInitialized(){}async collect(e){if(void 0===this._sdkMetricProducer)throw new Error("MetricReader is not bound to a MetricProducer");if(this._shutdown)throw new Error("MetricReader is shutdown");const[t,...r]=await Promise.all([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis}),...this._metricProducers.map(t=>t.collect({timeoutMillis:e?.timeoutMillis}))]),n=t.errors.concat(r.flatMap(e=>e.errors));return{resourceMetrics:{resource:t.resourceMetrics.resource,scopeMetrics:t.resourceMetrics.scopeMetrics.concat(r.flatMap(e=>e.resourceMetrics.scopeMetrics))},errors:n}}async shutdown(e){this._shutdown?diag.error("Cannot call shutdown twice."):(null==e?.timeoutMillis?await this.onShutdown():await callWithTimeout$1(this.onShutdown(),e.timeoutMillis),this._shutdown=!0)}async forceFlush(e){this._shutdown?diag.warn("Cannot forceFlush on already shutdown MetricReader."):null!=e?.timeoutMillis?await callWithTimeout$1(this.onForceFlush(),e.timeoutMillis):await this.onForceFlush()}}class PeriodicExportingMetricReader extends MetricReader{_interval;_exporter;_exportInterval;_exportTimeout;constructor(e){const{exporter:t,exportIntervalMillis:r=6e4,metricProducers:n,cardinalityLimits:i}=e;let{exportTimeoutMillis:o=3e4}=e;if(super({aggregationSelector:t.selectAggregation?.bind(t),aggregationTemporalitySelector:t.selectAggregationTemporality?.bind(t),metricProducers:n,cardinalitySelector:e=>{const t={default:2e3,...i};switch(e){case InstrumentType$2.COUNTER:return t.counter??t.default;case InstrumentType$2.GAUGE:return t.gauge??t.default;case InstrumentType$2.HISTOGRAM:return t.histogram??t.default;case InstrumentType$2.OBSERVABLE_COUNTER:return t.observableCounter??t.default;case InstrumentType$2.OBSERVABLE_UP_DOWN_COUNTER:return t.observableUpDownCounter??t.default;case InstrumentType$2.OBSERVABLE_GAUGE:return t.observableGauge??t.default;case InstrumentType$2.UP_DOWN_COUNTER:return t.upDownCounter??t.default;default:return t.default}}}),r<=0)throw Error("exportIntervalMillis must be greater than 0");if(o<=0)throw Error("exportTimeoutMillis must be greater than 0");if(r<o){if("exportIntervalMillis"in e&&"exportTimeoutMillis"in e)throw Error("exportIntervalMillis must be greater than or equal to exportTimeoutMillis");diag.info(`Timeout of ${o} exceeds the interval of ${r}. Clamping timeout to interval duration.`),o=r}this._exportInterval=r,this._exportTimeout=o,this._exporter=t}async _runOnce(){try{await callWithTimeout$1(this._doRun(),this._exportTimeout)}catch(e){if(e instanceof TimeoutError$1)return void diag.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout);globalErrorHandler$2(e)}}async _doRun(){const{resourceMetrics:e,errors:t}=await this.collect({timeoutMillis:this._exportTimeout});if(t.length>0&&diag.error("PeriodicExportingMetricReader: metrics collection errors",...t),e.resource.asyncAttributesPending)try{await(e.resource.waitForAsyncAttributes?.())}catch(e){diag.debug("Error while resolving async portion of resource: ",e),globalErrorHandler$2(e)}if(0===e.scopeMetrics.length)return;const r=await internal$2._export(this._exporter,e);if(r.code!==ExportResultCode$2.SUCCESS)throw new Error(`PeriodicExportingMetricReader: metrics export failed (error ${r.error})`)}onInitialized(){this._interval=setInterval(()=>{this._runOnce()},this._exportInterval),"number"!=typeof this._interval&&this._interval.unref()}async onForceFlush(){await this._runOnce(),await this._exporter.forceFlush()}async onShutdown(){this._interval&&clearInterval(this._interval),await this.onForceFlush(),await this._exporter.shutdown()}}class InMemoryMetricExporter{_shutdown=!1;_aggregationTemporality;_metrics=[];constructor(e){this._aggregationTemporality=e}export(e,t){this._shutdown?setTimeout(()=>t({code:ExportResultCode$2.FAILED}),0):(this._metrics.push(e),setTimeout(()=>t({code:ExportResultCode$2.SUCCESS}),0))}getMetrics(){return this._metrics}forceFlush(){return Promise.resolve()}reset(){this._metrics=[]}selectAggregationTemporality(e){return this._aggregationTemporality}shutdown(){return this._shutdown=!0,Promise.resolve()}}class ConsoleMetricExporter{_shutdown=!1;_temporalitySelector;constructor(e){this._temporalitySelector=e?.temporalitySelector??DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR}export(e,t){if(!this._shutdown)return ConsoleMetricExporter._sendMetrics(e,t);t({code:ExportResultCode$2.FAILED})}forceFlush(){return Promise.resolve()}selectAggregationTemporality(e){return this._temporalitySelector(e)}shutdown(){return this._shutdown=!0,Promise.resolve()}static _sendMetrics(e,t){for(const t of e.scopeMetrics)for(const e of t.metrics)console.dir({descriptor:e.descriptor,dataPointType:e.dataPointType,dataPoints:e.dataPoints},{depth:null});t({code:ExportResultCode$2.SUCCESS})}}let serviceName;function defaultServiceName(){if(void 0===serviceName)try{const e=globalThis.process.argv0;serviceName=e?`unknown_service:${e}`:"unknown_service"}catch{serviceName="unknown_service"}return serviceName}const isPromiseLike=e=>null!==e&&"object"==typeof e&&"function"==typeof e.then;class ResourceImpl{_rawAttributes;_asyncAttributesPending=!1;_schemaUrl;_memoizedAttributes;static FromAttributeList(e,t){const r=new ResourceImpl({},t);return r._rawAttributes=guardedRawAttributes(e),r._asyncAttributesPending=e.filter(([e,t])=>isPromiseLike(t)).length>0,r}constructor(e,t){const r=e.attributes??{};this._rawAttributes=Object.entries(r).map(([e,t])=>(isPromiseLike(t)&&(this._asyncAttributesPending=!0),[e,t])),this._rawAttributes=guardedRawAttributes(this._rawAttributes),this._schemaUrl=validateSchemaUrl(t?.schemaUrl)}get asyncAttributesPending(){return this._asyncAttributesPending}async waitForAsyncAttributes(){if(this.asyncAttributesPending){for(let e=0;e<this._rawAttributes.length;e++){const[t,r]=this._rawAttributes[e];this._rawAttributes[e]=[t,isPromiseLike(r)?await r:r]}this._asyncAttributesPending=!1}}get attributes(){if(this.asyncAttributesPending&&diag.error("Accessing resource attributes before async attributes settled"),this._memoizedAttributes)return this._memoizedAttributes;const e={};for(const[t,r]of this._rawAttributes)isPromiseLike(r)?diag.debug(`Unsettled resource attribute ${t} skipped`):null!=r&&(e[t]??=r);return this._asyncAttributesPending||(this._memoizedAttributes=e),e}getRawAttributes(){return this._rawAttributes}get schemaUrl(){return this._schemaUrl}merge(e){if(null==e)return this;const t=mergeSchemaUrl(this,e),r=t?{schemaUrl:t}:void 0;return ResourceImpl.FromAttributeList([...e.getRawAttributes(),...this.getRawAttributes()],r)}}function resourceFromAttributes(e,t){return ResourceImpl.FromAttributeList(Object.entries(e),t)}function defaultResource(){return resourceFromAttributes({[ATTR_SERVICE_NAME]:defaultServiceName(),[ATTR_TELEMETRY_SDK_LANGUAGE]:SDK_INFO$1[ATTR_TELEMETRY_SDK_LANGUAGE],[ATTR_TELEMETRY_SDK_NAME]:SDK_INFO$1[ATTR_TELEMETRY_SDK_NAME],[ATTR_TELEMETRY_SDK_VERSION]:SDK_INFO$1[ATTR_TELEMETRY_SDK_VERSION]})}function guardedRawAttributes(e){return e.map(([e,t])=>isPromiseLike(t)?[e,t.catch(t=>{diag.debug("promise rejection for resource attribute: %s - %s",e,t)})]:[e,t])}function validateSchemaUrl(e){if("string"==typeof e||void 0===e)return e;diag.warn("Schema URL must be string or undefined, got %s. Schema URL will be ignored.",e)}function mergeSchemaUrl(e,t){const r=e?.schemaUrl,n=t?.schemaUrl;return void 0===r||""===r?n:void 0===n||""===n||r===n?r:void diag.warn('Schema URL merge conflict: old resource has "%s", updating resource has "%s". Resulting resource will have undefined Schema URL.',r,n)}class ViewRegistry{_registeredViews=[];addView(e){this._registeredViews.push(e)}findViews(e,t){return this._registeredViews.filter(r=>this._matchInstrument(r.instrumentSelector,e)&&this._matchMeter(r.meterSelector,t))}_matchInstrument(e,t){return(void 0===e.getType()||t.type===e.getType())&&e.getNameFilter().match(t.name)&&e.getUnitFilter().match(t.unit)}_matchMeter(e,t){return e.getNameFilter().match(t.name)&&(void 0===t.version||e.getVersionFilter().match(t.version))&&(void 0===t.schemaUrl||e.getSchemaUrlFilter().match(t.schemaUrl))}}function createInstrumentDescriptor(e,t,r){return isValidName(e)||diag.warn(`Invalid metric name: "${e}". The metric name should be a ASCII string with a length no greater than 255 characters.`),{name:e,type:t,description:r?.description??"",unit:r?.unit??"",valueType:r?.valueType??ValueType.DOUBLE,advice:r?.advice??{}}}function createInstrumentDescriptorWithView(e,t){return{name:e.name??t.name,description:e.description??t.description,type:t.type,unit:t.unit,valueType:t.valueType,advice:t.advice}}function isDescriptorCompatibleWith(e,t){return equalsCaseInsensitive(e.name,t.name)&&e.unit===t.unit&&e.type===t.type&&e.valueType===t.valueType}const NAME_REGEXP=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function isValidName(e){return NAME_REGEXP.test(e)}class SyncInstrument{_writableMetricStorage;_descriptor;constructor(e,t){this._writableMetricStorage=e,this._descriptor=t}_record(e,t={},r=context.active()){"number"==typeof e?(this._descriptor.valueType!==ValueType.INT||Number.isInteger(e)||(diag.warn(`INT value type cannot accept a floating-point value for ${this._descriptor.name}, ignoring the fractional digits.`),e=Math.trunc(e),Number.isInteger(e)))&&this._writableMetricStorage.record(e,t,r,millisToHrTime$2(Date.now())):diag.warn(`non-number value provided to metric ${this._descriptor.name}: ${e}`)}}class UpDownCounterInstrument extends SyncInstrument{add(e,t,r){this._record(e,t,r)}}class CounterInstrument extends SyncInstrument{add(e,t,r){e<0?diag.warn(`negative value provided to counter ${this._descriptor.name}: ${e}`):this._record(e,t,r)}}class GaugeInstrument extends SyncInstrument{record(e,t,r){this._record(e,t,r)}}class HistogramInstrument extends SyncInstrument{record(e,t,r){e<0?diag.warn(`negative value provided to histogram ${this._descriptor.name}: ${e}`):this._record(e,t,r)}}class ObservableInstrument{_metricStorages;_descriptor;_observableRegistry;constructor(e,t,r){this._descriptor=e,this._metricStorages=t,this._observableRegistry=r}addCallback(e){this._observableRegistry.addCallback(e,this)}removeCallback(e){this._observableRegistry.removeCallback(e,this)}}class ObservableCounterInstrument extends ObservableInstrument{}class ObservableGaugeInstrument extends ObservableInstrument{}class ObservableUpDownCounterInstrument extends ObservableInstrument{}function isObservableInstrument(e){return e instanceof ObservableInstrument}class Meter{_meterSharedState;constructor(e){this._meterSharedState=e}createGauge(e,t){const r=createInstrumentDescriptor(e,InstrumentType$2.GAUGE,t),n=this._meterSharedState.registerMetricStorage(r);return new GaugeInstrument(n,r)}createHistogram(e,t){const r=createInstrumentDescriptor(e,InstrumentType$2.HISTOGRAM,t),n=this._meterSharedState.registerMetricStorage(r);return new HistogramInstrument(n,r)}createCounter(e,t){const r=createInstrumentDescriptor(e,InstrumentType$2.COUNTER,t),n=this._meterSharedState.registerMetricStorage(r);return new CounterInstrument(n,r)}createUpDownCounter(e,t){const r=createInstrumentDescriptor(e,InstrumentType$2.UP_DOWN_COUNTER,t),n=this._meterSharedState.registerMetricStorage(r);return new UpDownCounterInstrument(n,r)}createObservableGauge(e,t){const r=createInstrumentDescriptor(e,InstrumentType$2.OBSERVABLE_GAUGE,t),n=this._meterSharedState.registerAsyncMetricStorage(r);return new ObservableGaugeInstrument(r,n,this._meterSharedState.observableRegistry)}createObservableCounter(e,t){const r=createInstrumentDescriptor(e,InstrumentType$2.OBSERVABLE_COUNTER,t),n=this._meterSharedState.registerAsyncMetricStorage(r);return new ObservableCounterInstrument(r,n,this._meterSharedState.observableRegistry)}createObservableUpDownCounter(e,t){const r=createInstrumentDescriptor(e,InstrumentType$2.OBSERVABLE_UP_DOWN_COUNTER,t),n=this._meterSharedState.registerAsyncMetricStorage(r);return new ObservableUpDownCounterInstrument(r,n,this._meterSharedState.observableRegistry)}addBatchObservableCallback(e,t){this._meterSharedState.observableRegistry.addBatchCallback(e,t)}removeBatchObservableCallback(e,t){this._meterSharedState.observableRegistry.removeBatchCallback(e,t)}}class MetricStorage{_instrumentDescriptor;constructor(e){this._instrumentDescriptor=e}getInstrumentDescriptor(){return this._instrumentDescriptor}updateDescription(e){this._instrumentDescriptor=createInstrumentDescriptor(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})}}class HashMap{_valueMap=new Map;_keyMap=new Map;_hash;constructor(e){this._hash=e}get(e,t){return t??=this._hash(e),this._valueMap.get(t)}getOrDefault(e,t){const r=this._hash(e);if(this._valueMap.has(r))return this._valueMap.get(r);const n=t();return this._keyMap.has(r)||this._keyMap.set(r,e),this._valueMap.set(r,n),n}set(e,t,r){r??=this._hash(e),this._keyMap.has(r)||this._keyMap.set(r,e),this._valueMap.set(r,t)}has(e,t){return t??=this._hash(e),this._valueMap.has(t)}*keys(){const e=this._keyMap.entries();let t=e.next();for(;!0!==t.done;)yield[t.value[1],t.value[0]],t=e.next()}*entries(){const e=this._valueMap.entries();let t=e.next();for(;!0!==t.done;)yield[this._keyMap.get(t.value[0]),t.value[1],t.value[0]],t=e.next()}get size(){return this._valueMap.size}}class AttributeHashMap extends HashMap{constructor(){super(hashAttributes)}}class DeltaMetricProcessor{_activeCollectionStorage=new AttributeHashMap;_cumulativeMemoStorage=new AttributeHashMap;_cardinalityLimit;_overflowAttributes={"otel.metric.overflow":!0};_overflowHashCode;_aggregator;constructor(e,t){this._aggregator=e,this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=hashAttributes(this._overflowAttributes)}record(e,t,r,n){let i=this._activeCollectionStorage.get(t);if(!i){if(this._activeCollectionStorage.size>=this._cardinalityLimit){const t=this._activeCollectionStorage.getOrDefault(this._overflowAttributes,()=>this._aggregator.createAccumulation(n));return void t?.record(e)}i=this._aggregator.createAccumulation(n),this._activeCollectionStorage.set(t,i)}i?.record(e)}batchCumulate(e,t){Array.from(e.entries()).forEach(([e,r,n])=>{const i=this._aggregator.createAccumulation(t);i?.record(r);let o=i;if(this._cumulativeMemoStorage.has(e,n)){const t=this._cumulativeMemoStorage.get(e,n);o=this._aggregator.diff(t,i)}else if(this._cumulativeMemoStorage.size>=this._cardinalityLimit&&(e=this._overflowAttributes,n=this._overflowHashCode,this._cumulativeMemoStorage.has(e,n))){const t=this._cumulativeMemoStorage.get(e,n);o=this._aggregator.diff(t,i)}if(this._activeCollectionStorage.has(e,n)){const t=this._activeCollectionStorage.get(e,n);o=this._aggregator.merge(t,o)}this._cumulativeMemoStorage.set(e,i,n),this._activeCollectionStorage.set(e,o,n)})}collect(){const e=this._activeCollectionStorage;return this._activeCollectionStorage=new AttributeHashMap,e}}class TemporalMetricProcessor{_aggregator;_unreportedAccumulations=new Map;_reportHistory=new Map;constructor(e,t){this._aggregator=e,t.forEach(e=>{this._unreportedAccumulations.set(e,[])})}buildMetrics(e,t,r,n){this._stashAccumulations(r);const i=this._getMergedUnreportedAccumulations(e);let o,s=i;if(this._reportHistory.has(e)){const t=this._reportHistory.get(e),r=t.collectionTime;o=t.aggregationTemporality,s=o===AggregationTemporality$2.CUMULATIVE?TemporalMetricProcessor.merge(t.accumulations,i,this._aggregator):TemporalMetricProcessor.calibrateStartTime(t.accumulations,i,r)}else o=e.selectAggregationTemporality(t.type);this._reportHistory.set(e,{accumulations:s,collectionTime:n,aggregationTemporality:o});const a=AttributesMapToAccumulationRecords(s);if(0!==a.length)return this._aggregator.toMetricData(t,o,a,n)}_stashAccumulations(e){const t=this._unreportedAccumulations.keys();for(const r of t){let t=this._unreportedAccumulations.get(r);void 0===t&&(t=[],this._unreportedAccumulations.set(r,t)),t.push(e)}}_getMergedUnreportedAccumulations(e){let t=new AttributeHashMap;const r=this._unreportedAccumulations.get(e);if(this._unreportedAccumulations.set(e,[]),void 0===r)return t;for(const e of r)t=TemporalMetricProcessor.merge(t,e,this._aggregator);return t}static merge(e,t,r){const n=e,i=t.entries();let o=i.next();for(;!0!==o.done;){const[t,s,a]=o.value;if(e.has(t,a)){const i=e.get(t,a),o=r.merge(i,s);n.set(t,o,a)}else n.set(t,s,a);o=i.next()}return n}static calibrateStartTime(e,t,r){for(const[n,i]of e.keys()){const e=t.get(n,i);e?.setStartTime(r)}return t}}function AttributesMapToAccumulationRecords(e){return Array.from(e.entries())}class AsyncMetricStorage extends MetricStorage{_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;_attributesProcessor;constructor(e,t,r,n,i){super(e),this._aggregationCardinalityLimit=i,this._deltaMetricStorage=new DeltaMetricProcessor(t,this._aggregationCardinalityLimit),this._temporalMetricStorage=new TemporalMetricProcessor(t,n),this._attributesProcessor=r}record(e,t){const r=new AttributeHashMap;Array.from(e.entries()).forEach(([e,t])=>{r.set(this._attributesProcessor.process(e),t)}),this._deltaMetricStorage.batchCumulate(r,t)}collect(e,t){const r=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(e,this._instrumentDescriptor,r,t)}}function getIncompatibilityDetails(e,t){let r="";return e.unit!==t.unit&&(r+=`\t- Unit '${e.unit}' does not match '${t.unit}'\n`),e.type!==t.type&&(r+=`\t- Type '${e.type}' does not match '${t.type}'\n`),e.valueType!==t.valueType&&(r+=`\t- Value Type '${e.valueType}' does not match '${t.valueType}'\n`),e.description!==t.description&&(r+=`\t- Description '${e.description}' does not match '${t.description}'\n`),r}function getValueTypeConflictResolutionRecipe(e,t){return`\t- use valueType '${e.valueType}' on instrument creation or use an instrument name other than '${t.name}'`}function getUnitConflictResolutionRecipe(e,t){return`\t- use unit '${e.unit}' on instrument creation or use an instrument name other than '${t.name}'`}function getTypeConflictResolutionRecipe(e,t){const r={name:t.name,type:t.type,unit:t.unit},n=JSON.stringify(r);return`\t- create a new view with a name other than '${e.name}' and InstrumentSelector '${n}'`}function getDescriptionResolutionRecipe(e,t){const r={name:t.name,type:t.type,unit:t.unit},n=JSON.stringify(r);return`\t- create a new view with a name other than '${e.name}' and InstrumentSelector '${n}'\n \t- OR - create a new view with the name ${e.name} and description '${e.description}' and InstrumentSelector ${n}\n \t- OR - create a new view with the name ${t.name} and description '${e.description}' and InstrumentSelector ${n}`}function getConflictResolutionRecipe(e,t){return e.valueType!==t.valueType?getValueTypeConflictResolutionRecipe(e,t):e.unit!==t.unit?getUnitConflictResolutionRecipe(e,t):e.type!==t.type?getTypeConflictResolutionRecipe(e,t):e.description!==t.description?getDescriptionResolutionRecipe(e,t):""}class MetricStorageRegistry{_sharedRegistry=new Map;_perCollectorRegistry=new Map;static create(){return new MetricStorageRegistry}getStorages(e){let t=[];for(const e of this._sharedRegistry.values())t=t.concat(e);const r=this._perCollectorRegistry.get(e);if(null!=r)for(const e of r.values())t=t.concat(e);return t}register(e){this._registerStorage(e,this._sharedRegistry)}registerForCollector(e,t){let r=this._perCollectorRegistry.get(e);null==r&&(r=new Map,this._perCollectorRegistry.set(e,r)),this._registerStorage(t,r)}findOrUpdateCompatibleStorage(e){const t=this._sharedRegistry.get(e.name);return void 0===t?null:this._findOrUpdateCompatibleStorage(e,t)}findOrUpdateCompatibleCollectorStorage(e,t){const r=this._perCollectorRegistry.get(e);if(void 0===r)return null;const n=r.get(t.name);return void 0===n?null:this._findOrUpdateCompatibleStorage(t,n)}_registerStorage(e,t){const r=e.getInstrumentDescriptor(),n=t.get(r.name);void 0!==n?n.push(e):t.set(r.name,[e])}_findOrUpdateCompatibleStorage(e,t){let r=null;for(const n of t){const t=n.getInstrumentDescriptor();isDescriptorCompatibleWith(t,e)?(t.description!==e.description&&(e.description.length>t.description.length&&n.updateDescription(e.description),diag.warn("A view or instrument with the name ",e.name," has already been registered, but has a different description and is incompatible with another registered view.\n","Details:\n",getIncompatibilityDetails(t,e),"The longer description will be used.\nTo resolve the conflict:",getConflictResolutionRecipe(t,e))),r=n):diag.warn("A view or instrument with the name ",e.name," has already been registered and is incompatible with another registered view.\n","Details:\n",getIncompatibilityDetails(t,e),"To resolve the conflict:\n",getConflictResolutionRecipe(t,e))}return r}}class MultiMetricStorage{_backingStorages;constructor(e){this._backingStorages=e}record(e,t,r,n){this._backingStorages.forEach(i=>{i.record(e,t,r,n)})}}class ObservableResultImpl{_buffer=new AttributeHashMap;_instrumentName;_valueType;constructor(e,t){this._instrumentName=e,this._valueType=t}observe(e,t={}){"number"==typeof e?(this._valueType!==ValueType.INT||Number.isInteger(e)||(diag.warn(`INT value type cannot accept a floating-point value for ${this._instrumentName}, ignoring the fractional digits.`),e=Math.trunc(e),Number.isInteger(e)))&&this._buffer.set(t,e):diag.warn(`non-number value provided to metric ${this._instrumentName}: ${e}`)}}class BatchObservableResultImpl{_buffer=new Map;observe(e,t,r={}){if(!isObservableInstrument(e))return;let n=this._buffer.get(e);null==n&&(n=new AttributeHashMap,this._buffer.set(e,n)),"number"==typeof t?(e._descriptor.valueType!==ValueType.INT||Number.isInteger(t)||(diag.warn(`INT value type cannot accept a floating-point value for ${e._descriptor.name}, ignoring the fractional digits.`),t=Math.trunc(t),Number.isInteger(t)))&&n.set(r,t):diag.warn(`non-number value provided to metric ${e._descriptor.name}: ${t}`)}}class ObservableRegistry{_callbacks=[];_batchCallbacks=[];addCallback(e,t){this._findCallback(e,t)>=0||this._callbacks.push({callback:e,instrument:t})}removeCallback(e,t){const r=this._findCallback(e,t);r<0||this._callbacks.splice(r,1)}addBatchCallback(e,t){const r=new Set(t.filter(isObservableInstrument));if(0===r.size)return void diag.error("BatchObservableCallback is not associated with valid instruments",t);this._findBatchCallback(e,r)>=0||this._batchCallbacks.push({callback:e,instruments:r})}removeBatchCallback(e,t){const r=new Set(t.filter(isObservableInstrument)),n=this._findBatchCallback(e,r);n<0||this._batchCallbacks.splice(n,1)}async observe(e,t){const r=this._observeCallbacks(e,t),n=this._observeBatchCallbacks(e,t);return(await Promise.allSettled([...r,...n])).filter(e=>"rejected"===e.status).map(e=>e.reason)}_observeCallbacks(e,t){return this._callbacks.map(async({callback:r,instrument:n})=>{const i=new ObservableResultImpl(n._descriptor.name,n._descriptor.valueType);let o=Promise.resolve(r(i));null!=t&&(o=callWithTimeout$1(o,t)),await o,n._metricStorages.forEach(t=>{t.record(i._buffer,e)})})}_observeBatchCallbacks(e,t){return this._batchCallbacks.map(async({callback:r,instruments:n})=>{const i=new BatchObservableResultImpl;let o=Promise.resolve(r(i));null!=t&&(o=callWithTimeout$1(o,t)),await o,n.forEach(t=>{const r=i._buffer.get(t);null!=r&&t._metricStorages.forEach(t=>{t.record(r,e)})})})}_findCallback(e,t){return this._callbacks.findIndex(r=>r.callback===e&&r.instrument===t)}_findBatchCallback(e,t){return this._batchCallbacks.findIndex(r=>r.callback===e&&setEquals(r.instruments,t))}}class SyncMetricStorage extends MetricStorage{_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;_attributesProcessor;constructor(e,t,r,n,i){super(e),this._aggregationCardinalityLimit=i,this._deltaMetricStorage=new DeltaMetricProcessor(t,this._aggregationCardinalityLimit),this._temporalMetricStorage=new TemporalMetricProcessor(t,n),this._attributesProcessor=r}record(e,t,r,n){t=this._attributesProcessor.process(t,r),this._deltaMetricStorage.record(e,t,r,n)}collect(e,t){const r=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(e,this._instrumentDescriptor,r,t)}}class NoopAttributesProcessor{process(e,t){return e}}class MultiAttributesProcessor{_processors;constructor(e){this._processors=e}process(e,t){let r=e;for(const e of this._processors)r=e.process(r,t);return r}}class AllowListProcessor{_allowedAttributeNames;constructor(e){this._allowedAttributeNames=e}process(e,t){const r={};return Object.keys(e).forEach(t=>{this._allowedAttributeNames.includes(t)&&(r[t]=e[t])}),r}}class DenyListProcessor{_deniedAttributeNames;constructor(e){this._deniedAttributeNames=e}process(e,t){const r={};return Object.keys(e).forEach(t=>{this._deniedAttributeNames.includes(t)||(r[t]=e[t])}),r}}function createNoopAttributesProcessor(){return NOOP}function createMultiAttributesProcessor(e){return new MultiAttributesProcessor(e)}function createAllowListAttributesProcessor(e){return new AllowListProcessor(e)}function createDenyListAttributesProcessor(e){return new DenyListProcessor(e)}const NOOP=new NoopAttributesProcessor;class MeterSharedState{metricStorageRegistry=new MetricStorageRegistry;observableRegistry=new ObservableRegistry;meter;_meterProviderSharedState;_instrumentationScope;constructor(e,t){this.meter=new Meter(this),this._meterProviderSharedState=e,this._instrumentationScope=t}registerMetricStorage(e){const t=this._registerMetricStorage(e,SyncMetricStorage);return 1===t.length?t[0]:new MultiMetricStorage(t)}registerAsyncMetricStorage(e){return this._registerMetricStorage(e,AsyncMetricStorage)}async collect(e,t,r){const n=await this.observableRegistry.observe(t,r?.timeoutMillis),i=this.metricStorageRegistry.getStorages(e);if(0===i.length)return null;const o=[];return i.forEach(r=>{const n=r.collect(e,t);null!=n&&o.push(n)}),0===o.length?{errors:n}:{scopeMetrics:{scope:this._instrumentationScope,metrics:o},errors:n}}_registerMetricStorage(e,t){let r=this._meterProviderSharedState.viewRegistry.findViews(e,this._instrumentationScope).map(r=>{const n=createInstrumentDescriptorWithView(r,e),i=this.metricStorageRegistry.findOrUpdateCompatibleStorage(n);if(null!=i)return i;const o=r.aggregation.createAggregator(n),s=new t(n,o,r.attributesProcessor,this._meterProviderSharedState.metricCollectors,r.aggregationCardinalityLimit);return this.metricStorageRegistry.register(s),s});if(0===r.length){const n=this._meterProviderSharedState.selectAggregations(e.type).map(([r,n])=>{const i=this.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(r,e);if(null!=i)return i;const o=n.createAggregator(e),s=r.selectCardinalityLimit(e.type),a=new t(e,o,createNoopAttributesProcessor(),[r],s);return this.metricStorageRegistry.registerForCollector(r,a),a});r=r.concat(n)}return r}}class MeterProviderSharedState{viewRegistry=new ViewRegistry;metricCollectors=[];meterSharedStates=new Map;resource;constructor(e){this.resource=e}getMeterSharedState(e){const t=instrumentationScopeId(e);let r=this.meterSharedStates.get(t);return null==r&&(r=new MeterSharedState(this,e),this.meterSharedStates.set(t,r)),r}selectAggregations(e){const t=[];for(const r of this.metricCollectors)t.push([r,toAggregation(r.selectAggregation(e))]);return t}}class MetricCollector{_sharedState;_metricReader;constructor(e,t){this._sharedState=e,this._metricReader=t}async collect(e){const t=millisToHrTime$2(Date.now()),r=[],n=[],i=Array.from(this._sharedState.meterSharedStates.values()).map(async i=>{const o=await i.collect(this,t,e);null!=o?.scopeMetrics&&r.push(o.scopeMetrics),null!=o?.errors&&n.push(...o.errors)});return await Promise.all(i),{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:r},errors:n}}async forceFlush(e){await this._metricReader.forceFlush(e)}async shutdown(e){await this._metricReader.shutdown(e)}selectAggregationTemporality(e){return this._metricReader.selectAggregationTemporality(e)}selectAggregation(e){return this._metricReader.selectAggregation(e)}selectCardinalityLimit(e){return this._metricReader.selectCardinalityLimit?.(e)??2e3}}const ESCAPE=/[\^$\\.+?()[\]{}|]/g;class PatternPredicate{_matchAll;_regexp;constructor(e){"*"===e?(this._matchAll=!0,this._regexp=/.*/):(this._matchAll=!1,this._regexp=new RegExp(PatternPredicate.escapePattern(e)))}match(e){return!!this._matchAll||this._regexp.test(e)}static escapePattern(e){return`^${e.replace(ESCAPE,"\\$&").replace("*",".*")}$`}static hasWildcard(e){return e.includes("*")}}class ExactPredicate{_matchAll;_pattern;constructor(e){this._matchAll=void 0===e,this._pattern=e}match(e){return!!this._matchAll||e===this._pattern}}class InstrumentSelector{_nameFilter;_type;_unitFilter;constructor(e){this._nameFilter=new PatternPredicate(e?.name??"*"),this._type=e?.type,this._unitFilter=new ExactPredicate(e?.unit)}getType(){return this._type}getNameFilter(){return this._nameFilter}getUnitFilter(){return this._unitFilter}}class MeterSelector{_nameFilter;_versionFilter;_schemaUrlFilter;constructor(e){this._nameFilter=new ExactPredicate(e?.name),this._versionFilter=new ExactPredicate(e?.version),this._schemaUrlFilter=new ExactPredicate(e?.schemaUrl)}getNameFilter(){return this._nameFilter}getVersionFilter(){return this._versionFilter}getSchemaUrlFilter(){return this._schemaUrlFilter}}function isSelectorNotProvided(e){return null==e.instrumentName&&null==e.instrumentType&&null==e.instrumentUnit&&null==e.meterName&&null==e.meterVersion&&null==e.meterSchemaUrl}function validateViewOptions(e){if(isSelectorNotProvided(e))throw new Error("Cannot create view with no selector arguments supplied");if(null!=e.name&&(null==e?.instrumentName||PatternPredicate.hasWildcard(e.instrumentName)))throw new Error("Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter.")}class View{name;description;aggregation;attributesProcessor;instrumentSelector;meterSelector;aggregationCardinalityLimit;constructor(e){validateViewOptions(e),null!=e.attributesProcessors?this.attributesProcessor=createMultiAttributesProcessor(e.attributesProcessors):this.attributesProcessor=createNoopAttributesProcessor(),this.name=e.name,this.description=e.description,this.aggregation=toAggregation(e.aggregation??{type:AggregationType$1.DEFAULT}),this.instrumentSelector=new InstrumentSelector({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new MeterSelector({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}}class MeterProvider{_sharedState;_shutdown=!1;constructor(e){if(this._sharedState=new MeterProviderSharedState(e?.resource??defaultResource()),null!=e?.views&&e.views.length>0)for(const t of e.views)this._sharedState.viewRegistry.addView(new View(t));if(null!=e?.readers&&e.readers.length>0)for(const t of e.readers){const e=new MetricCollector(this._sharedState,t);t.setMetricProducer(e),this._sharedState.metricCollectors.push(e)}}getMeter(e,t="",r={}){return this._shutdown?(diag.warn("A shutdown MeterProvider cannot provide a Meter"),createNoopMeter()):this._sharedState.getMeterSharedState({name:e,version:t,schemaUrl:r.schemaUrl}).meter}async shutdown(e){this._shutdown?diag.warn("shutdown may only be called once per MeterProvider"):(this._shutdown=!0,await Promise.all(this._sharedState.metricCollectors.map(t=>t.shutdown(e))))}async forceFlush(e){this._shutdown?diag.warn("invalid attempt to force flush after MeterProvider shutdown"):await Promise.all(this._sharedState.metricCollectors.map(t=>t.forceFlush(e)))}}var esm$4=Object.freeze({__proto__:null,get AggregationTemporality(){return AggregationTemporality$2},get AggregationType(){return AggregationType$1},ConsoleMetricExporter:ConsoleMetricExporter,get DataPointType(){return DataPointType$2},InMemoryMetricExporter:InMemoryMetricExporter,get InstrumentType(){return InstrumentType$2},MeterProvider:MeterProvider,MetricReader:MetricReader,PeriodicExportingMetricReader:PeriodicExportingMetricReader,TimeoutError:TimeoutError$1,createAllowListAttributesProcessor:createAllowListAttributesProcessor,createDenyListAttributesProcessor:createDenyListAttributesProcessor}),require$$0$1=getAugmentedNamespace(esm$4);const SUPPRESS_TRACING_KEY$1=createContextKey("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function suppressTracing$1(e){return e.setValue(SUPPRESS_TRACING_KEY$1,!0)}function unsuppressTracing(e){return e.deleteValue(SUPPRESS_TRACING_KEY$1)}function isTracingSuppressed$1(e){return!0===e.getValue(SUPPRESS_TRACING_KEY$1)}const BAGGAGE_KEY_PAIR_SEPARATOR="=",BAGGAGE_PROPERTIES_SEPARATOR=";",BAGGAGE_ITEMS_SEPARATOR=",",BAGGAGE_HEADER="baggage",BAGGAGE_MAX_NAME_VALUE_PAIRS=180,BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=4096,BAGGAGE_MAX_TOTAL_LENGTH=8192;function serializeKeyPairs(e){return e.reduce((e,t)=>{const r=`${e}${""!==e?BAGGAGE_ITEMS_SEPARATOR:""}${t}`;return r.length>BAGGAGE_MAX_TOTAL_LENGTH?e:r},"")}function getKeyPairs(e){return e.getAllEntries().map(([e,t])=>{let r=`${encodeURIComponent(e)}=${encodeURIComponent(t.value)}`;return void 0!==t.metadata&&(r+=BAGGAGE_PROPERTIES_SEPARATOR+t.metadata.toString()),r})}function parsePairKeyValue(e){const t=e.split(BAGGAGE_PROPERTIES_SEPARATOR);if(t.length<=0)return;const r=t.shift();if(!r)return;const n=r.indexOf(BAGGAGE_KEY_PAIR_SEPARATOR);if(n<=0)return;const i=decodeURIComponent(r.substring(0,n).trim()),o=decodeURIComponent(r.substring(n+1).trim());let s;return t.length>0&&(s=baggageEntryMetadataFromString(t.join(BAGGAGE_PROPERTIES_SEPARATOR))),{key:i,value:o,metadata:s}}function parseKeyPairsIntoRecord(e){return"string"!=typeof e||0===e.length?{}:e.split(BAGGAGE_ITEMS_SEPARATOR).map(e=>parsePairKeyValue(e)).filter(e=>void 0!==e&&e.value.length>0).reduce((e,t)=>(e[t.key]=t.value,e),{})}class W3CBaggagePropagator{inject(e,t,r){const n=propagation.getBaggage(e);if(!n||isTracingSuppressed$1(e))return;const i=serializeKeyPairs(getKeyPairs(n).filter(e=>e.length<=BAGGAGE_MAX_PER_NAME_VALUE_PAIRS).slice(0,BAGGAGE_MAX_NAME_VALUE_PAIRS));i.length>0&&r.set(t,BAGGAGE_HEADER,i)}extract(e,t,r){const n=r.get(t,BAGGAGE_HEADER),i=Array.isArray(n)?n.join(BAGGAGE_ITEMS_SEPARATOR):n;if(!i)return e;const o={};if(0===i.length)return e;return i.split(BAGGAGE_ITEMS_SEPARATOR).forEach(e=>{const t=parsePairKeyValue(e);if(t){const e={value:t.value};t.metadata&&(e.metadata=t.metadata),o[t.key]=e}}),0===Object.entries(o).length?e:propagation.setBaggage(e,propagation.createBaggage(o))}fields(){return[BAGGAGE_HEADER]}}class AnchoredClock{_monotonicClock;_epochMillis;_performanceMillis;constructor(e,t){this._monotonicClock=t,this._epochMillis=e.now(),this._performanceMillis=t.now()}now(){const e=this._monotonicClock.now()-this._performanceMillis;return this._epochMillis+e}}function sanitizeAttributes$1(e){const t={};if("object"!=typeof e||null==e)return t;for(const[r,n]of Object.entries(e))isAttributeKey$1(r)?isAttributeValue$1(n)?Array.isArray(n)?t[r]=n.slice():t[r]=n:diag.warn(`Invalid attribute value set for key: ${r}`):diag.warn(`Invalid attribute key: ${r}`);return t}function isAttributeKey$1(e){return"string"==typeof e&&e.length>0}function isAttributeValue$1(e){return null==e||(Array.isArray(e)?isHomogeneousAttributeValueArray$1(e):isValidPrimitiveAttributeValue(e))}function isHomogeneousAttributeValueArray$1(e){let t;for(const r of e)if(null!=r){if(!t){if(isValidPrimitiveAttributeValue(r)){t=typeof r;continue}return!1}if(typeof r!==t)return!1}return!0}function isValidPrimitiveAttributeValue(e){switch(typeof e){case"number":case"boolean":case"string":return!0}return!1}function loggingErrorHandler$1(){return e=>{diag.error(stringifyException$1(e))}}function stringifyException$1(e){return"string"==typeof e?e:JSON.stringify(flattenException$1(e))}function flattenException$1(e){const t={};let r=e;for(;null!==r;)Object.getOwnPropertyNames(r).forEach(e=>{if(t[e])return;const n=r[e];n&&(t[e]=String(n))}),r=Object.getPrototypeOf(r);return t}let delegateHandler$1=loggingErrorHandler$1();function setGlobalErrorHandler(e){delegateHandler$1=e}function globalErrorHandler$1(e){try{delegateHandler$1(e)}catch{}}function getStringFromEnv(e){}function getBooleanFromEnv(e){}function getNumberFromEnv$1(e){}function getStringListFromEnv(e){}const _globalThis="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof global?global:{},otperformance$1=performance,VERSION$1="2.0.0",SDK_INFO={[SEMRESATTRS_TELEMETRY_SDK_NAME]:"opentelemetry",[SEMRESATTRS_PROCESS_RUNTIME_NAME]:"browser",[SEMRESATTRS_TELEMETRY_SDK_LANGUAGE]:TELEMETRYSDKLANGUAGEVALUES_WEBJS,[SEMRESATTRS_TELEMETRY_SDK_VERSION]:VERSION$1};function unrefTimer(e){}const NANOSECOND_DIGITS$1=9,NANOSECOND_DIGITS_IN_MILLIS$1=6,MILLISECONDS_TO_NANOSECONDS$1=Math.pow(10,NANOSECOND_DIGITS_IN_MILLIS$1),SECOND_TO_NANOSECONDS$1=Math.pow(10,NANOSECOND_DIGITS$1);function millisToHrTime$1(e){const t=e/1e3;return[Math.trunc(t),Math.round(e%1e3*MILLISECONDS_TO_NANOSECONDS$1)]}function getTimeOrigin$1(){let e=otperformance$1.timeOrigin;if("number"!=typeof e){const t=otperformance$1;e=t.timing&&t.timing.fetchStart}return e}function hrTime$1(e){return addHrTimes$1(millisToHrTime$1(getTimeOrigin$1()),millisToHrTime$1("number"==typeof e?e:otperformance$1.now()))}function timeInputToHrTime(e){if(isTimeInputHrTime$1(e))return e;if("number"==typeof e)return e<getTimeOrigin$1()?hrTime$1(e):millisToHrTime$1(e);if(e instanceof Date)return millisToHrTime$1(e.getTime());throw TypeError("Invalid input type")}function hrTimeDuration$1(e,t){let r=t[0]-e[0],n=t[1]-e[1];return n<0&&(r-=1,n+=SECOND_TO_NANOSECONDS$1),[r,n]}function hrTimeToTimeStamp(e){const t=NANOSECOND_DIGITS$1,r=`${"0".repeat(t)}${e[1]}Z`,n=r.substring(r.length-t-1);return new Date(1e3*e[0]).toISOString().replace("000Z",n)}function hrTimeToNanoseconds(e){return e[0]*SECOND_TO_NANOSECONDS$1+e[1]}function hrTimeToMilliseconds(e){return 1e3*e[0]+e[1]/1e6}function hrTimeToMicroseconds$1(e){return 1e6*e[0]+e[1]/1e3}function isTimeInputHrTime$1(e){return Array.isArray(e)&&2===e.length&&"number"==typeof e[0]&&"number"==typeof e[1]}function isTimeInput$1(e){return isTimeInputHrTime$1(e)||"number"==typeof e||e instanceof Date}function addHrTimes$1(e,t){const r=[e[0]+t[0],e[1]+t[1]];return r[1]>=SECOND_TO_NANOSECONDS$1&&(r[1]-=SECOND_TO_NANOSECONDS$1,r[0]+=1),r}var ExportResultCode$1;!function(e){e[e.SUCCESS=0]="SUCCESS",e[e.FAILED=1]="FAILED"}(ExportResultCode$1||(ExportResultCode$1={}));class CompositePropagator{_propagators;_fields;constructor(e={}){this._propagators=e.propagators??[],this._fields=Array.from(new Set(this._propagators.map(e=>"function"==typeof e.fields?e.fields():[]).reduce((e,t)=>e.concat(t),[])))}inject(e,t,r){for(const n of this._propagators)try{n.inject(e,t,r)}catch(e){diag.warn(`Failed to inject with ${n.constructor.name}. Err: ${e.message}`)}}extract(e,t,r){return this._propagators.reduce((e,n)=>{try{return n.extract(e,t,r)}catch(e){diag.warn(`Failed to extract with ${n.constructor.name}. Err: ${e.message}`)}return e},e)}fields(){return this._fields.slice()}}const VALID_KEY_CHAR_RANGE="[_0-9a-z-*/]",VALID_KEY=`[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`,VALID_VENDOR_KEY=`[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`,VALID_KEY_REGEX=new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`),VALID_VALUE_BASE_REGEX=/^[ -~]{0,255}[!-~]$/,INVALID_VALUE_COMMA_EQUAL_REGEX=/,|=/;function validateKey(e){return VALID_KEY_REGEX.test(e)}function validateValue(e){return VALID_VALUE_BASE_REGEX.test(e)&&!INVALID_VALUE_COMMA_EQUAL_REGEX.test(e)}const MAX_TRACE_STATE_ITEMS=32,MAX_TRACE_STATE_LEN=512,LIST_MEMBERS_SEPARATOR=",",LIST_MEMBER_KEY_VALUE_SPLITTER="=";class TraceState{_internalState=new Map;constructor(e){e&&this._parse(e)}set(e,t){const r=this._clone();return r._internalState.has(e)&&r._internalState.delete(e),r._internalState.set(e,t),r}unset(e){const t=this._clone();return t._internalState.delete(e),t}get(e){return this._internalState.get(e)}serialize(){return this._keys().reduce((e,t)=>(e.push(t+LIST_MEMBER_KEY_VALUE_SPLITTER+this.get(t)),e),[]).join(LIST_MEMBERS_SEPARATOR)}_parse(e){e.length>MAX_TRACE_STATE_LEN||(this._internalState=e.split(LIST_MEMBERS_SEPARATOR).reverse().reduce((e,t)=>{const r=t.trim(),n=r.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER);if(-1!==n){const i=r.slice(0,n),o=r.slice(n+1,t.length);validateKey(i)&&validateValue(o)&&e.set(i,o)}return e},new Map),this._internalState.size>MAX_TRACE_STATE_ITEMS&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,MAX_TRACE_STATE_ITEMS))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){const e=new TraceState;return e._internalState=new Map(this._internalState),e}}const TRACE_PARENT_HEADER="traceparent",TRACE_STATE_HEADER="tracestate",VERSION="00",VERSION_PART="(?!ff)[\\da-f]{2}",TRACE_ID_PART="(?![0]{32})[\\da-f]{32}",PARENT_ID_PART="(?![0]{16})[\\da-f]{16}",FLAGS_PART="[\\da-f]{2}",TRACE_PARENT_REGEX=new RegExp(`^\\s?(${VERSION_PART})-(${TRACE_ID_PART})-(${PARENT_ID_PART})-(${FLAGS_PART})(-.*)?\\s?$`);function parseTraceParent(e){const t=TRACE_PARENT_REGEX.exec(e);return t?"00"===t[1]&&t[5]?null:{traceId:t[2],spanId:t[3],traceFlags:parseInt(t[4],16)}:null}class W3CTraceContextPropagator{inject(e,t,r){const n=trace.getSpanContext(e);if(!n||isTracingSuppressed$1(e)||!isSpanContextValid(n))return;const i=`${VERSION}-${n.traceId}-${n.spanId}-0${Number(n.traceFlags||TraceFlags.NONE).toString(16)}`;r.set(t,TRACE_PARENT_HEADER,i),n.traceState&&r.set(t,TRACE_STATE_HEADER,n.traceState.serialize())}extract(e,t,r){const n=r.get(t,TRACE_PARENT_HEADER);if(!n)return e;const i=Array.isArray(n)?n[0]:n;if("string"!=typeof i)return e;const o=parseTraceParent(i);if(!o)return e;o.isRemote=!0;const s=r.get(t,TRACE_STATE_HEADER);if(s){const e=Array.isArray(s)?s.join(","):s;o.traceState=new TraceState("string"==typeof e?e:void 0)}return trace.setSpanContext(e,o)}fields(){return[TRACE_PARENT_HEADER,TRACE_STATE_HEADER]}}const RPC_METADATA_KEY=createContextKey("OpenTelemetry SDK Context Key RPC_METADATA");var RPCType;function setRPCMetadata(e,t){return e.setValue(RPC_METADATA_KEY,t)}function deleteRPCMetadata(e){return e.deleteValue(RPC_METADATA_KEY)}function getRPCMetadata(e){return e.getValue(RPC_METADATA_KEY)}!function(e){e.HTTP="http"}(RPCType||(RPCType={}));const objectTag$1="[object Object]",nullTag$1="[object Null]",undefinedTag$1="[object Undefined]",funcProto$1=Function.prototype,funcToString$1=funcProto$1.toString,objectCtorString$1=funcToString$1.call(Object),getPrototypeOf$1=Object.getPrototypeOf,objectProto$1=Object.prototype,hasOwnProperty$1=objectProto$1.hasOwnProperty,symToStringTag$1=Symbol?Symbol.toStringTag:void 0,nativeObjectToString$1=objectProto$1.toString;function isPlainObject$1(e){if(!isObjectLike$1(e)||baseGetTag$1(e)!==objectTag$1)return!1;const t=getPrototypeOf$1(e);if(null===t)return!0;const r=hasOwnProperty$1.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&funcToString$1.call(r)===objectCtorString$1}function isObjectLike$1(e){return null!=e&&"object"==typeof e}function baseGetTag$1(e){return null==e?void 0===e?undefinedTag$1:nullTag$1:symToStringTag$1&&symToStringTag$1 in Object(e)?getRawTag$1(e):objectToString$1(e)}function getRawTag$1(e){const t=hasOwnProperty$1.call(e,symToStringTag$1),r=e[symToStringTag$1];let n=!1;try{e[symToStringTag$1]=void 0,n=!0}catch(e){}const i=nativeObjectToString$1.call(e);return n&&(t?e[symToStringTag$1]=r:delete e[symToStringTag$1]),i}function objectToString$1(e){return nativeObjectToString$1.call(e)}const MAX_LEVEL$1=20;function merge$1(...e){let t=e.shift();const r=new WeakMap;for(;e.length>0;)t=mergeTwoObjects$1(t,e.shift(),0,r);return t}function takeValue$1(e){return isArray$1(e)?e.slice():e}function mergeTwoObjects$1(e,t,r=0,n){let i;if(!(r>MAX_LEVEL$1)){if(r++,isPrimitive$1(e)||isPrimitive$1(t)||isFunction$1(t))i=takeValue$1(t);else if(isArray$1(e)){if(i=e.slice(),isArray$1(t))for(let e=0,r=t.length;e<r;e++)i.push(takeValue$1(t[e]));else if(isObject$1(t)){const e=Object.keys(t);for(let r=0,n=e.length;r<n;r++){const n=e[r];i[n]=takeValue$1(t[n])}}}else if(isObject$1(e))if(isObject$1(t)){if(!shouldMerge$1(e,t))return t;i=Object.assign({},e);const o=Object.keys(t);for(let s=0,a=o.length;s<a;s++){const a=o[s],c=t[a];if(isPrimitive$1(c))void 0===c?delete i[a]:i[a]=c;else{const o=i[a],s=c;if(wasObjectReferenced$1(e,a,n)||wasObjectReferenced$1(t,a,n))delete i[a];else{if(isObject$1(o)&&isObject$1(s)){const r=n.get(o)||[],i=n.get(s)||[];r.push({obj:e,key:a}),i.push({obj:t,key:a}),n.set(o,r),n.set(s,i)}i[a]=mergeTwoObjects$1(i[a],c,r,n)}}}}else i=t;return i}}function wasObjectReferenced$1(e,t,r){const n=r.get(e[t])||[];for(let r=0,i=n.length;r<i;r++){const i=n[r];if(i.key===t&&i.obj===e)return!0}return!1}function isArray$1(e){return Array.isArray(e)}function isFunction$1(e){return"function"==typeof e}function isObject$1(e){return!isPrimitive$1(e)&&!isArray$1(e)&&!isFunction$1(e)&&"object"==typeof e}function isPrimitive$1(e){return"string"==typeof e||"number"==typeof e||"boolean"==typeof e||void 0===e||e instanceof Date||e instanceof RegExp||null===e}function shouldMerge$1(e,t){return!(!isPlainObject$1(e)||!isPlainObject$1(t))}class TimeoutError extends Error{constructor(e){super(e),Object.setPrototypeOf(this,TimeoutError.prototype)}}function callWithTimeout(e,t){let r;const n=new Promise(function(e,n){r=setTimeout(function(){n(new TimeoutError("Operation timed out."))},t)});return Promise.race([e,n]).then(e=>(clearTimeout(r),e),e=>{throw clearTimeout(r),e})}function urlMatches(e,t){return"string"==typeof t?e===t:!!e.match(t)}function isUrlIgnored(e,t){if(!t)return!1;for(const r of t)if(urlMatches(e,r))return!0;return!1}let Deferred$1=class{_promise;_resolve;_reject;constructor(){this._promise=new Promise((e,t)=>{this._resolve=e,this._reject=t})}get promise(){return this._promise}resolve(e){this._resolve(e)}reject(e){this._reject(e)}},BindOnceFuture$1=class{_callback;_that;_isCalled=!1;_deferred=new Deferred$1;constructor(e,t){this._callback=e,this._that=t}get isCalled(){return this._isCalled}get promise(){return this._deferred.promise}call(...e){if(!this._isCalled){this._isCalled=!0;try{Promise.resolve(this._callback.call(this._that,...e)).then(e=>this._deferred.resolve(e),e=>this._deferred.reject(e))}catch(e){this._deferred.reject(e)}}return this._deferred.promise}};const logLevelMap={ALL:DiagLogLevel.ALL,VERBOSE:DiagLogLevel.VERBOSE,DEBUG:DiagLogLevel.DEBUG,INFO:DiagLogLevel.INFO,WARN:DiagLogLevel.WARN,ERROR:DiagLogLevel.ERROR,NONE:DiagLogLevel.NONE};function diagLogLevelFromString(e){if(null==e)return;const t=logLevelMap[e.toUpperCase()];return null==t?(diag.warn(`Unknown log level "${e}", expected one of ${Object.keys(logLevelMap)}, using default`),DiagLogLevel.INFO):t}function _export$1(e,t){return new Promise(r=>{context.with(suppressTracing$1(context.active()),()=>{e.export(t,e=>{r(e)})})})}const internal$1={_export:_export$1};var esm$3=Object.freeze({__proto__:null,AnchoredClock:AnchoredClock,BindOnceFuture:BindOnceFuture$1,CompositePropagator:CompositePropagator,get ExportResultCode(){return ExportResultCode$1},get RPCType(){return RPCType},SDK_INFO:SDK_INFO,TRACE_PARENT_HEADER:TRACE_PARENT_HEADER,TRACE_STATE_HEADER:TRACE_STATE_HEADER,TimeoutError:TimeoutError,TraceState:TraceState,W3CBaggagePropagator:W3CBaggagePropagator,W3CTraceContextPropagator:W3CTraceContextPropagator,_globalThis:_globalThis,addHrTimes:addHrTimes$1,callWithTimeout:callWithTimeout,deleteRPCMetadata:deleteRPCMetadata,diagLogLevelFromString:diagLogLevelFromString,getBooleanFromEnv:getBooleanFromEnv,getNumberFromEnv:getNumberFromEnv$1,getRPCMetadata:getRPCMetadata,getStringFromEnv:getStringFromEnv,getStringListFromEnv:getStringListFromEnv,getTimeOrigin:getTimeOrigin$1,globalErrorHandler:globalErrorHandler$1,hrTime:hrTime$1,hrTimeDuration:hrTimeDuration$1,hrTimeToMicroseconds:hrTimeToMicroseconds$1,hrTimeToMilliseconds:hrTimeToMilliseconds,hrTimeToNanoseconds:hrTimeToNanoseconds,hrTimeToTimeStamp:hrTimeToTimeStamp,internal:internal$1,isAttributeValue:isAttributeValue$1,isTimeInput:isTimeInput$1,isTimeInputHrTime:isTimeInputHrTime$1,isTracingSuppressed:isTracingSuppressed$1,isUrlIgnored:isUrlIgnored,loggingErrorHandler:loggingErrorHandler$1,merge:merge$1,millisToHrTime:millisToHrTime$1,otperformance:otperformance$1,parseKeyPairsIntoRecord:parseKeyPairsIntoRecord,parseTraceParent:parseTraceParent,sanitizeAttributes:sanitizeAttributes$1,setGlobalErrorHandler:setGlobalErrorHandler,setRPCMetadata:setRPCMetadata,suppressTracing:suppressTracing$1,timeInputToHrTime:timeInputToHrTime,unrefTimer:unrefTimer,unsuppressTracing:unsuppressTracing,urlMatches:urlMatches}),AggregationTemporality$1,InstrumentType$1,DataPointType$1,AggregationType,AggregationTemporalityPreference;!function(e){e[e.DELTA=0]="DELTA",e[e.CUMULATIVE=1]="CUMULATIVE"}(AggregationTemporality$1||(AggregationTemporality$1={})),function(e){e.COUNTER="COUNTER",e.GAUGE="GAUGE",e.HISTOGRAM="HISTOGRAM",e.UP_DOWN_COUNTER="UP_DOWN_COUNTER",e.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",e.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",e.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"}(InstrumentType$1||(InstrumentType$1={})),function(e){e[e.HISTOGRAM=0]="HISTOGRAM",e[e.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",e[e.GAUGE=2]="GAUGE",e[e.SUM=3]="SUM"}(DataPointType$1||(DataPointType$1={})),function(e){e[e.DEFAULT=0]="DEFAULT",e[e.DROP=1]="DROP",e[e.SUM=2]="SUM",e[e.LAST_VALUE=3]="LAST_VALUE",e[e.EXPLICIT_BUCKET_HISTOGRAM=4]="EXPLICIT_BUCKET_HISTOGRAM",e[e.EXPONENTIAL_HISTOGRAM=5]="EXPONENTIAL_HISTOGRAM"}(AggregationType||(AggregationType={})),function(e){e[e.DELTA=0]="DELTA",e[e.CUMULATIVE=1]="CUMULATIVE",e[e.LOWMEMORY=2]="LOWMEMORY"}(AggregationTemporalityPreference||(AggregationTemporalityPreference={}));class OTLPExporterBase{_delegate;constructor(e){this._delegate=e}export(e,t){this._delegate.export(e,t)}forceFlush(){return this._delegate.forceFlush()}shutdown(){return this._delegate.shutdown()}}class OTLPExporterError extends Error{code;name="OTLPExporterError";data;constructor(e,t,r){super(e),this.data=r,this.code=t}}function validateTimeoutMillis(e){if(Number.isFinite(e)&&e>0)return e;throw new Error(`Configuration: timeoutMillis is invalid, expected number greater than 0 (actual: '${e}')`)}function wrapStaticHeadersInFunction(e){if(null!=e)return()=>e}function mergeOtlpSharedConfigurationWithDefaults(e,t,r){return{timeoutMillis:validateTimeoutMillis(e.timeoutMillis??t.timeoutMillis??r.timeoutMillis),concurrencyLimit:e.concurrencyLimit??t.concurrencyLimit??r.concurrencyLimit,compression:e.compression??t.compression??r.compression}}function getSharedConfigurationDefaults(){return{timeoutMillis:1e4,concurrencyLimit:30,compression:"none"}}class BoundedQueueExportPromiseHandler{_concurrencyLimit;_sendingPromises=[];constructor(e){this._concurrencyLimit=e}pushPromise(e){if(this.hasReachedLimit())throw new Error("Concurrency Limit reached");this._sendingPromises.push(e);const t=()=>{const t=this._sendingPromises.indexOf(e);this._sendingPromises.splice(t,1)};e.then(t,t)}hasReachedLimit(){return this._sendingPromises.length>=this._concurrencyLimit}async awaitAll(){await Promise.all(this._sendingPromises)}}function createBoundedQueueExportPromiseHandler(e){return new BoundedQueueExportPromiseHandler(e.concurrencyLimit)}function isPartialSuccessResponse(e){return Object.prototype.hasOwnProperty.call(e,"partialSuccess")}function createLoggingPartialSuccessResponseHandler(){return{handleResponse(e){null!=e&&isPartialSuccessResponse(e)&&null!=e.partialSuccess&&0!==Object.keys(e.partialSuccess).length&&diag.warn("Received Partial Success response:",JSON.stringify(e.partialSuccess))}}}class OTLPExportDelegate{_transport;_serializer;_responseHandler;_promiseQueue;_timeout;_diagLogger;constructor(e,t,r,n,i){this._transport=e,this._serializer=t,this._responseHandler=r,this._promiseQueue=n,this._timeout=i,this._diagLogger=diag.createComponentLogger({namespace:"OTLPExportDelegate"})}export(e,t){if(this._diagLogger.debug("items to be sent",e),this._promiseQueue.hasReachedLimit())return void t({code:ExportResultCode$1.FAILED,error:new Error("Concurrent export limit reached")});const r=this._serializer.serializeRequest(e);null!=r?this._promiseQueue.pushPromise(this._transport.send(r,this._timeout).then(e=>{if("success"!==e.status)"failure"===e.status&&e.error?t({code:ExportResultCode$1.FAILED,error:e.error}):"retryable"===e.status?t({code:ExportResultCode$1.FAILED,error:new OTLPExporterError("Export failed with retryable status")}):t({code:ExportResultCode$1.FAILED,error:new OTLPExporterError("Export failed with unknown error")});else{if(null!=e.data)try{this._responseHandler.handleResponse(this._serializer.deserializeResponse(e.data))}catch(t){this._diagLogger.warn("Export succeeded but could not deserialize response - is the response specification compliant?",t,e.data)}t({code:ExportResultCode$1.SUCCESS})}},e=>t({code:ExportResultCode$1.FAILED,error:e}))):t({code:ExportResultCode$1.FAILED,error:new Error("Nothing to send")})}forceFlush(){return this._promiseQueue.awaitAll()}async shutdown(){this._diagLogger.debug("shutdown started"),await this.forceFlush(),this._transport.shutdown()}}function createOtlpExportDelegate(e,t){return new OTLPExportDelegate(e.transport,e.serializer,createLoggingPartialSuccessResponseHandler(),e.promiseHandler,t.timeout)}function createOtlpNetworkExportDelegate(e,t,r){return createOtlpExportDelegate({transport:r,serializer:t,promiseHandler:createBoundedQueueExportPromiseHandler(e)},{timeout:e.timeoutMillis})}const CumulativeTemporalitySelector=()=>AggregationTemporality$1.CUMULATIVE,DeltaTemporalitySelector=e=>{switch(e){case InstrumentType$1.COUNTER:case InstrumentType$1.OBSERVABLE_COUNTER:case InstrumentType$1.GAUGE:case InstrumentType$1.HISTOGRAM:case InstrumentType$1.OBSERVABLE_GAUGE:return AggregationTemporality$1.DELTA;case InstrumentType$1.UP_DOWN_COUNTER:case InstrumentType$1.OBSERVABLE_UP_DOWN_COUNTER:return AggregationTemporality$1.CUMULATIVE}},LowMemoryTemporalitySelector=e=>{switch(e){case InstrumentType$1.COUNTER:case InstrumentType$1.HISTOGRAM:return AggregationTemporality$1.DELTA;case InstrumentType$1.GAUGE:case InstrumentType$1.UP_DOWN_COUNTER:case InstrumentType$1.OBSERVABLE_UP_DOWN_COUNTER:case InstrumentType$1.OBSERVABLE_COUNTER:case InstrumentType$1.OBSERVABLE_GAUGE:return AggregationTemporality$1.CUMULATIVE}};function chooseTemporalitySelectorFromEnvironment(){const e="cumulative".toLowerCase();return"cumulative"===e?CumulativeTemporalitySelector:"delta"===e?DeltaTemporalitySelector:"lowmemory"===e?LowMemoryTemporalitySelector:(diag.warn(`OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE is set to '${e}', but only 'cumulative' and 'delta' are allowed. Using default ('cumulative') instead.`),CumulativeTemporalitySelector)}function chooseTemporalitySelector(e){return null!=e?e===AggregationTemporalityPreference.DELTA?DeltaTemporalitySelector:e===AggregationTemporalityPreference.LOWMEMORY?LowMemoryTemporalitySelector:CumulativeTemporalitySelector:chooseTemporalitySelectorFromEnvironment()}const DEFAULT_AGGREGATION=Object.freeze({type:AggregationType.DEFAULT});function chooseAggregationSelector(e){return e?.aggregationPreference??(()=>DEFAULT_AGGREGATION)}class OTLPMetricExporterBase extends OTLPExporterBase{_aggregationTemporalitySelector;_aggregationSelector;constructor(e,t){super(e),this._aggregationSelector=chooseAggregationSelector(t),this._aggregationTemporalitySelector=chooseTemporalitySelector(t?.temporalityPreference)}selectAggregation(e){return this._aggregationSelector(e)}selectAggregationTemporality(e){return this._aggregationTemporalitySelector(e)}}function intValue(e){return e>=48&&e<=57?e-48:e>=97&&e<=102?e-87:e-55}function hexToBinary(e){const t=new Uint8Array(e.length/2);let r=0;for(let n=0;n<e.length;n+=2){const i=intValue(e.charCodeAt(n)),o=intValue(e.charCodeAt(n+1));t[r++]=i<<4|o}return t}function hrTimeToNanos(e){const t=BigInt(1e9);return BigInt(e[0])*t+BigInt(e[1])}function toLongBits(e){return{low:Number(BigInt.asUintN(32,e)),high:Number(BigInt.asUintN(32,e>>BigInt(32)))}}function encodeAsLongBits(e){return toLongBits(hrTimeToNanos(e))}function encodeAsString(e){return hrTimeToNanos(e).toString()}const encodeTimestamp="undefined"!=typeof BigInt?encodeAsString:hrTimeToNanoseconds;function identity(e){return e}function optionalHexToBinary(e){if(void 0!==e)return hexToBinary(e)}const DEFAULT_ENCODER={encodeHrTime:encodeAsLongBits,encodeSpanContext:hexToBinary,encodeOptionalSpanContext:optionalHexToBinary};function getOtlpEncoder(e){if(void 0===e)return DEFAULT_ENCODER;const t=e.useLongBits??!0,r=e.useHex??!1;return{encodeHrTime:t?encodeAsLongBits:encodeTimestamp,encodeSpanContext:r?identity:hexToBinary,encodeOptionalSpanContext:r?identity:optionalHexToBinary}}function createResource(e){return{attributes:toAttributes(e.attributes),droppedAttributesCount:0}}function createInstrumentationScope(e){return{name:e.name,version:e.version}}function toAttributes(e){return Object.keys(e).map(t=>toKeyValue(t,e[t]))}function toKeyValue(e,t){return{key:e,value:toAnyValue(t)}}function toAnyValue(e){const t=typeof e;return"string"===t?{stringValue:e}:"number"===t?Number.isInteger(e)?{intValue:e}:{doubleValue:e}:"boolean"===t?{boolValue:e}:e instanceof Uint8Array?{bytesValue:e}:Array.isArray(e)?{arrayValue:{values:e.map(toAnyValue)}}:"object"===t&&null!=e?{kvlistValue:{values:Object.entries(e).map(([e,t])=>toKeyValue(e,t))}}:{}}var AggregationTemporality,InstrumentType,DataPointType;function toResourceMetrics(e,t){const r=getOtlpEncoder(t);return{resource:createResource(e.resource),schemaUrl:void 0,scopeMetrics:toScopeMetrics(e.scopeMetrics,r)}}function toScopeMetrics(e,t){return Array.from(e.map(e=>({scope:createInstrumentationScope(e.scope),metrics:e.metrics.map(e=>toMetric(e,t)),schemaUrl:e.scope.schemaUrl})))}function toMetric(e,t){const r={name:e.descriptor.name,description:e.descriptor.description,unit:e.descriptor.unit},n=toAggregationTemporality(e.aggregationTemporality);switch(e.dataPointType){case DataPointType.SUM:r.sum={aggregationTemporality:n,isMonotonic:e.isMonotonic,dataPoints:toSingularDataPoints(e,t)};break;case DataPointType.GAUGE:r.gauge={dataPoints:toSingularDataPoints(e,t)};break;case DataPointType.HISTOGRAM:r.histogram={aggregationTemporality:n,dataPoints:toHistogramDataPoints(e,t)};break;case DataPointType.EXPONENTIAL_HISTOGRAM:r.exponentialHistogram={aggregationTemporality:n,dataPoints:toExponentialHistogramDataPoints(e,t)}}return r}function toSingularDataPoint(e,t,r){const n={attributes:toAttributes(e.attributes),startTimeUnixNano:r.encodeHrTime(e.startTime),timeUnixNano:r.encodeHrTime(e.endTime)};switch(t){case ValueType.INT:n.asInt=e.value;break;case ValueType.DOUBLE:n.asDouble=e.value}return n}function toSingularDataPoints(e,t){return e.dataPoints.map(r=>toSingularDataPoint(r,e.descriptor.valueType,t))}function toHistogramDataPoints(e,t){return e.dataPoints.map(e=>{const r=e.value;return{attributes:toAttributes(e.attributes),bucketCounts:r.buckets.counts,explicitBounds:r.buckets.boundaries,count:r.count,sum:r.sum,min:r.min,max:r.max,startTimeUnixNano:t.encodeHrTime(e.startTime),timeUnixNano:t.encodeHrTime(e.endTime)}})}function toExponentialHistogramDataPoints(e,t){return e.dataPoints.map(e=>{const r=e.value;return{attributes:toAttributes(e.attributes),count:r.count,min:r.min,max:r.max,sum:r.sum,positive:{offset:r.positive.offset,bucketCounts:r.positive.bucketCounts},negative:{offset:r.negative.offset,bucketCounts:r.negative.bucketCounts},scale:r.scale,zeroCount:r.zeroCount,startTimeUnixNano:t.encodeHrTime(e.startTime),timeUnixNano:t.encodeHrTime(e.endTime)}})}function toAggregationTemporality(e){switch(e){case AggregationTemporality.DELTA:return 1;case AggregationTemporality.CUMULATIVE:return 2}}function createExportMetricsServiceRequest(e,t){return{resourceMetrics:e.map(e=>toResourceMetrics(e,t))}}function sdkSpanToOtlpSpan(e,t){const r=e.spanContext(),n=e.status,i=e.parentSpanContext?.spanId?t.encodeSpanContext(e.parentSpanContext?.spanId):void 0;return{traceId:t.encodeSpanContext(r.traceId),spanId:t.encodeSpanContext(r.spanId),parentSpanId:i,traceState:r.traceState?.serialize(),name:e.name,kind:null==e.kind?0:e.kind+1,startTimeUnixNano:t.encodeHrTime(e.startTime),endTimeUnixNano:t.encodeHrTime(e.endTime),attributes:toAttributes(e.attributes),droppedAttributesCount:e.droppedAttributesCount,events:e.events.map(e=>toOtlpSpanEvent(e,t)),droppedEventsCount:e.droppedEventsCount,status:{code:n.code,message:n.message},links:e.links.map(e=>toOtlpLink(e,t)),droppedLinksCount:e.droppedLinksCount}}function toOtlpLink(e,t){return{attributes:e.attributes?toAttributes(e.attributes):[],spanId:t.encodeSpanContext(e.context.spanId),traceId:t.encodeSpanContext(e.context.traceId),traceState:e.context.traceState?.serialize(),droppedAttributesCount:e.droppedAttributesCount||0}}function toOtlpSpanEvent(e,t){return{attributes:e.attributes?toAttributes(e.attributes):[],name:e.name,timeUnixNano:t.encodeHrTime(e.time),droppedAttributesCount:e.droppedAttributesCount||0}}function createExportTraceServiceRequest(e,t){return{resourceSpans:spanRecordsToResourceSpans(e,getOtlpEncoder(t))}}function createResourceMap(e){const t=new Map;for(const r of e){let e=t.get(r.resource);e||(e=new Map,t.set(r.resource,e));const n=`${r.instrumentationScope.name}@${r.instrumentationScope.version||""}:${r.instrumentationScope.schemaUrl||""}`;let i=e.get(n);i||(i=[],e.set(n,i)),i.push(r)}return t}function spanRecordsToResourceSpans(e,t){const r=[],n=createResourceMap(e).entries();let i=n.next();for(;!i.done;){const[e,o]=i.value,s=[],a=o.values();let c=a.next();for(;!c.done;){const e=c.value;if(e.length>0){const r=e.map(e=>sdkSpanToOtlpSpan(e,t));s.push({scope:createInstrumentationScope(e[0].instrumentationScope),spans:r,schemaUrl:e[0].instrumentationScope.schemaUrl})}c=a.next()}const l={resource:createResource(e),scopeSpans:s,schemaUrl:void 0};r.push(l),i=n.next()}return r}!function(e){e[e.DELTA=0]="DELTA",e[e.CUMULATIVE=1]="CUMULATIVE"}(AggregationTemporality||(AggregationTemporality={})),function(e){e.COUNTER="COUNTER",e.GAUGE="GAUGE",e.HISTOGRAM="HISTOGRAM",e.UP_DOWN_COUNTER="UP_DOWN_COUNTER",e.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",e.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",e.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"}(InstrumentType||(InstrumentType={})),function(e){e[e.HISTOGRAM=0]="HISTOGRAM",e[e.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",e[e.GAUGE=2]="GAUGE",e[e.SUM=3]="SUM"}(DataPointType||(DataPointType={}));const JsonMetricsSerializer={serializeRequest:e=>{const t=createExportMetricsServiceRequest([e],{useLongBits:!1});return(new TextEncoder).encode(JSON.stringify(t))},deserializeResponse:e=>{const t=new TextDecoder;return JSON.parse(t.decode(e))}},JsonTraceSerializer={serializeRequest:e=>{const t=createExportTraceServiceRequest(e,{useHex:!0,useLongBits:!1});return(new TextEncoder).encode(JSON.stringify(t))},deserializeResponse:e=>{const t=new TextDecoder;return JSON.parse(t.decode(e))}},MAX_ATTEMPTS=5,INITIAL_BACKOFF=1e3,MAX_BACKOFF=5e3,BACKOFF_MULTIPLIER=1.5,JITTER=.2;function getJitter(){return Math.random()*(2*JITTER)-JITTER}class RetryingTransport{_transport;constructor(e){this._transport=e}retry(e,t,r){return new Promise((n,i)=>{setTimeout(()=>{this._transport.send(e,t).then(n,i)},r)})}async send(e,t){const r=Date.now()+t;let n=await this._transport.send(e,t),i=MAX_ATTEMPTS,o=INITIAL_BACKOFF;for(;"retryable"===n.status&&i>0;){i--;const t=Math.max(Math.min(o,MAX_BACKOFF)+getJitter(),0);o*=BACKOFF_MULTIPLIER;const s=n.retryInMillis??t,a=r-Date.now();if(s>a)return n;n=await this.retry(e,a,s)}return n}shutdown(){return this._transport.shutdown()}}function createRetryingTransport(e){return new RetryingTransport(e.transport)}function isExportRetryable(e){return[429,502,503,504].includes(e)}function parseRetryAfterToMills(e){if(null==e)return;const t=Number.parseInt(e,10);if(Number.isInteger(t))return t>0?1e3*t:-1;const r=new Date(e).getTime()-Date.now();return r>=0?r:0}class XhrTransport{_parameters;constructor(e){this._parameters=e}send(e,t){return new Promise(r=>{const n=new XMLHttpRequest;n.timeout=t,n.open("POST",this._parameters.url);const i=this._parameters.headers();Object.entries(i).forEach(([e,t])=>{n.setRequestHeader(e,t)}),n.ontimeout=e=>{r({status:"failure",error:new Error("XHR request timed out")})},n.onreadystatechange=()=>{n.status>=200&&n.status<=299?(diag.debug("XHR success"),r({status:"success"})):n.status&&isExportRetryable(n.status)?r({status:"retryable",retryInMillis:parseRetryAfterToMills(n.getResponseHeader("Retry-After"))}):0!==n.status&&r({status:"failure",error:new Error("XHR request failed with non-retryable status")})},n.onabort=()=>{r({status:"failure",error:new Error("XHR request aborted")})},n.onerror=()=>{r({status:"failure",error:new Error("XHR request errored")})},n.send(e)})}shutdown(){}}function createXhrTransport(e){return new XhrTransport(e)}class SendBeaconTransport{_params;constructor(e){this._params=e}send(e){return new Promise(t=>{navigator.sendBeacon(this._params.url,new Blob([e],{type:this._params.blobType}))?(diag.debug("SendBeacon success"),t({status:"success"})):t({status:"failure",error:new Error("SendBeacon failed")})})}shutdown(){}}function createSendBeaconTransport(e){return new SendBeaconTransport(e)}function createOtlpXhrExportDelegate(e,t){return createOtlpNetworkExportDelegate(e,t,createRetryingTransport({transport:createXhrTransport(e)}))}function createOtlpSendBeaconExportDelegate(e,t){return createOtlpNetworkExportDelegate(e,t,createRetryingTransport({transport:createSendBeaconTransport({url:e.url,blobType:e.headers()["Content-Type"]})}))}function validateAndNormalizeHeaders(e){return()=>{const t={};return Object.entries(e?.()??{}).forEach(([e,r])=>{void 0!==r?t[e]=String(r):diag.warn(`Header "${e}" has invalid value (${r}) and will be ignored`)}),t}}function mergeHeaders(e,t,r){const n={...r()},i={};return()=>(null!=t&&Object.assign(i,t()),null!=e&&Object.assign(i,e()),Object.assign(i,n))}function validateUserProvidedUrl(e){if(null!=e)try{return new URL(e),e}catch(t){throw new Error(`Configuration: Could not parse user-provided export URL: '${e}'`)}}function mergeOtlpHttpConfigurationWithDefaults(e,t,r){return{...mergeOtlpSharedConfigurationWithDefaults(e,t,r),headers:mergeHeaders(validateAndNormalizeHeaders(e.headers),t.headers,r.headers),url:validateUserProvidedUrl(e.url)??t.url??r.url,agentOptions:e.agentOptions??t.agentOptions??r.agentOptions}}function getHttpConfigurationDefaults(e,t){return{...getSharedConfigurationDefaults(),headers:()=>e,url:"http://localhost:4318/"+t,agentOptions:{keepAlive:!0}}}function convertLegacyBrowserHttpOptions(e,t,r){return mergeOtlpHttpConfigurationWithDefaults({url:e.url,timeoutMillis:e.timeoutMillis,headers:wrapStaticHeadersInFunction(e.headers),concurrencyLimit:e.concurrencyLimit},{},getHttpConfigurationDefaults(r,t))}function createLegacyOtlpBrowserExportDelegate(e,t,r,n){const i=!!e.headers||"function"!=typeof navigator.sendBeacon,o=convertLegacyBrowserHttpOptions(e,r,n);return i?createOtlpXhrExportDelegate(o,t):createOtlpSendBeaconExportDelegate(o,t)}class OTLPMetricExporter extends OTLPMetricExporterBase{constructor(e){super(createLegacyOtlpBrowserExportDelegate(e??{},JsonMetricsSerializer,"v1/metrics",{"Content-Type":"application/json"}),e)}}var esm$2=Object.freeze({__proto__:null,get AggregationTemporalityPreference(){return AggregationTemporalityPreference},CumulativeTemporalitySelector:CumulativeTemporalitySelector,DeltaTemporalitySelector:DeltaTemporalitySelector,LowMemoryTemporalitySelector:LowMemoryTemporalitySelector,OTLPMetricExporter:OTLPMetricExporter,OTLPMetricExporterBase:OTLPMetricExporterBase}),require$$2=getAugmentedNamespace(esm$2);Object.defineProperty(providerFactory,"__esModule",{value:!0}),providerFactory.MetricsMeterProviderFactory=void 0;const sdk_metrics_1=require$$0$1,otel_1$7=requireDist$1(),exporter_metrics_otlp_http_1=require$$2,utils_1$2=utils$1;class MetricsMeterProviderFactory{create(e,t,r){var n;const i=Object.assign(Object.assign({url:e.url,concurrencyLimit:e.concurrencyLimit,timeoutMillis:e.timeoutMillis,compression:e.compression,keepAlive:e.keepAlive},e.exporterSettings),{headers:Object.assign(Object.assign(Object.assign({},otel_1$7.Container.errorless(t.headers)),otel_1$7.Container.errorless(null===(n=e.exporterSettings)||void 0===n?void 0:n.headers)),otel_1$7.Container.errorless(e.headers))}),o=Object.assign(Object.assign({},e.readerSettings),{exportIntervalMillis:e.publishInterval});let s=[];e.metricReaders&&(s=otel_1$7.Container.errorless(()=>e.metricReaders(o,i,e,t)));let a=[];e.metricExporters&&(a=otel_1$7.Container.errorless(()=>{var r;return null===(r=e.metricExporters)||void 0===r?void 0:r.call(e,i,e,t)})),!e.url||(null==a?void 0:a.length)||(null==s?void 0:s.length)||(a=[new exporter_metrics_otlp_http_1.OTLPMetricExporter(i)]);for(const e of a)s.push(new sdk_metrics_1.PeriodicExportingMetricReader(Object.assign(Object.assign({},o),{exporter:e})));return{meterProvider:this.createMeterProvider(e,t,s,r),metricReaders:s}}createMeterProvider(e,t,r,n){var i,o,s;const a=(0,otel_1$7.loadInsightsPlugin)("base",n);a||n.error("Unable to create meter provider without loaded @interopio/insights-base package");const c=null!==(i=otel_1$7.Container.errorless(e.additionalResourceAttributes))&&void 0!==i?i:{},l=(0,utils_1$2.reduceModality)(c,null===(o=e.defaultPublishingSettings)||void 0===o?void 0:o.attributeSettings),u=Object.assign({resource:null==a?void 0:a.resourceFromAttributes(l),readers:r},e.meterProviderSettings),d=null!==(s=otel_1$7.Container.errorless(()=>{var r;return null===(r=e.meterProvider)||void 0===r?void 0:r.call(e,u,e,t)}))&&void 0!==s?s:new sdk_metrics_1.MeterProvider(u);return d}}providerFactory.MetricsMeterProviderFactory=MetricsMeterProviderFactory;var manager$2={},manager$1={};Object.defineProperty(manager$1,"__esModule",{value:!0}),manager$1.MetricsManagerValidator=void 0;const validator_1=validator;class MetricsManagerValidator{validate(e){validator_1.Validator.throwIfNullOrUndefined(e,"manager"),validator_1.Validator.throwIfNullOrUndefined(e.settings,"settings"),validator_1.Validator.throwIfNullOrUndefined(e.metricsFactory,"metricsFactory"),validator_1.Validator.throwIfNullOrUndefined(e.meterProvider,"meterProvider"),validator_1.Validator.throwIfNullOrUndefined(e.logger,"logger")}}manager$1.MetricsManagerValidator=MetricsManagerValidator;var __awaiter$1=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(manager$2,"__esModule",{value:!0}),manager$2.MetricsManager=void 0;const manager_1$1=manager$1,constants_1$1=constants$1,otel_1$6=requireDist$1();class MetricsManager{constructor(e,t,r,n,i){this.otelSettings=e,this.settings=t,this.metricsFactory=r,this.meterProvider=n,this.logger=i,this.metrics=new Map,this.started=!1,!1!==(null==e?void 0:e.logSettingsOnStartup)&&(null==i||i.info(`Starting MetricsManager with settings ${(0,otel_1$6.safeStringify)(t)}`));(new manager_1$1.MetricsManagerValidator).validate(this)}get(e){return this.getOrCreateMetric(e)}getFromSettings(e){return this.getOrCreateMetricFromSettings(e)}getObservable(e,t,r,n){return this.getOrCreateMetric(e,t,r,n)}getObservableFromSettings(e,t,r,n){return this.getOrCreateMetricFromSettings(e,t,r,n)}start(){var e;return __awaiter$1(this,void 0,void 0,function*(){try{this.createEnabledMetrics(null!==(e=this.settings.metrics)&&void 0!==e?e:[]);for(const e of this.metrics){const t=e[1];yield this.startMetric(t)}this.started=!0,this.logger.debug("metrics manager has been started")}catch(e){const t="error while starting metrics manager";this.logger.warn(t,e)}})}stop(){return __awaiter$1(this,void 0,void 0,function*(){try{for(const e of this.metrics){const t=e[1];yield this.stopMetric(t)}yield this.meterProvider.forceFlush(),this.started=!1,this.logger.debug("metrics manager has been stopped")}catch(e){const t="error while stopping metrics manager";this.logger.warn(t,e)}})}waitForFinalExport(e){return __awaiter$1(this,void 0,void 0,function*(){const t=new Date;yield Promise.all(this.meterProvider.metricReaders.map(t=>t.collect({timeoutMillis:e})));const r=e?e-((new Date).getTime()-t.getTime()):void 0;return Promise.race([new Promise(e=>r&&setTimeout(e,r)),this.meterProvider.forceFlush()])})}createEnabledMetrics(e){const t=e.filter(e=>{var t;return!this.metrics.has(null!==(t=e.name)&&void 0!==t?t:e.type)}),r=t.filter(e=>e.enabled);r.forEach(e=>this.createMetric(e))}getOrCreateMetric(e,t,r,n){var i;if(this.metrics.has(e))return this.metrics.get(e);{let o;const s=null===(i=this.settings.metrics)||void 0===i?void 0:i.find(t=>t.name===e);return s&&(o=this.createMetric(s,t,r,n)),o}}getOrCreateMetricFromSettings(e,t,r,n){var i;if(!e.name)throw new Error("settings.name not defined");return this.metrics.has(e.name)?this.metrics.get(e.name):this.createMetric(Object.assign(Object.assign({},e),{enabled:null===(i=e.enabled)||void 0===i||i}),t,r,n)}createMetric(e,t,r,n){var i;try{const o=e.additionalAttributes;e=Object.assign(Object.assign({},e),{description:e.description||constants_1$1.Defaults.DEFAULT_METRIC_DESCRIPTION,platformVersion:e.platformVersion||this.otelSettings.platformVersion||"unknown",user:e.user||this.otelSettings.userId||constants_1$1.Defaults.DEFAULT_USER,additionalAttributes:()=>Object.assign(Object.assign(Object.assign({},otel_1$6.Container.errorless(this.otelSettings.additionalAttributes)),otel_1$6.Container.errorless(this.settings.additionalAttributes)),otel_1$6.Container.errorless(o))});const s=this.metricsFactory.create(e,this.settings,t,r,n);return s&&this.metrics.set(null!==(i=e.name)&&void 0!==i?i:e.type,s),s}catch(t){const r=`error while creating metric from type: ${e.type}`;return void this.logger.warn(r,t)}}startMetric(e){return __awaiter$1(this,void 0,void 0,function*(){try{yield e.start()}catch(t){const r=`error while starting metric from type: ${e.settings.type}`;this.logger.warn(r,t)}})}stopMetric(e){return __awaiter$1(this,void 0,void 0,function*(){try{yield e.stop()}catch(t){const r=`error while stopping metric from type: ${e.settings.type}`;this.logger.warn(r,t)}})}}manager$2.MetricsManager=MetricsManager,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CustomUpDownCounterMetric=e.CustomHistogramMetric=e.init=void 0;const t=requireDist$1(),r=customHistogram;Object.defineProperty(e,"CustomHistogramMetric",{enumerable:!0,get:function(){return r.CustomHistogramMetric}});const n=customUpDownCounter;Object.defineProperty(e,"CustomUpDownCounterMetric",{enumerable:!0,get:function(){return n.CustomUpDownCounterMetric}});const i=builder$1,o=lazyProvider,s=builder,a=providerFactory,c=manager$2;e.init=function(){(0,t.registerInsightsPlugin)("metrics",()=>({newMetricsManager:(e,t,r,n)=>{var l,u;const d=function(e){const t=(new i.MetricsSettingsBuilder).withSettings(e).build();return t}(e),h=null!==(u=null===(l=e.metrics)||void 0===l?void 0:l.dependencyContainerOverride)&&void 0!==u?u:t,p=null!=r?r:function(e,t,r){return()=>(new a.MetricsMeterProviderFactory).create(e,t,r)}(d,e,n),g=new o.LazyMetricsMeterProvider(p,e.serviceName||"io.Insights"),m=function(e,t,r,n){let i=new s.MetricsFactoryBuilder(t,r,n);(null==e?void 0:e.platformMetricsEnabled)&&(i=i.withDefaults());const o=i.build();return o}(e.metrics,g,h,n);return new c.MetricsManager(e,d,m,g,n)}}))}}(dist$1);var index$1=_mergeNamespaces({__proto__:null},[dist$1]),dist={},manager={},utils={};const SUPPRESS_TRACING_KEY=createContextKey("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function suppressTracing(e){return e.setValue(SUPPRESS_TRACING_KEY,!0)}function isTracingSuppressed(e){return!0===e.getValue(SUPPRESS_TRACING_KEY)}function sanitizeAttributes(e){const t={};if("object"!=typeof e||null==e)return t;for(const r in e){if(!Object.prototype.hasOwnProperty.call(e,r))continue;if(!isAttributeKey(r)){diag.warn(`Invalid attribute key: ${r}`);continue}const n=e[r];isAttributeValue(n)?Array.isArray(n)?t[r]=n.slice():t[r]=n:diag.warn(`Invalid attribute value set for key: ${r}`)}return t}function isAttributeKey(e){return"string"==typeof e&&""!==e}function isAttributeValue(e){return null==e||(Array.isArray(e)?isHomogeneousAttributeValueArray(e):isValidPrimitiveAttributeValueType(typeof e))}function isHomogeneousAttributeValueArray(e){let t;for(const r of e){if(null==r)continue;const e=typeof r;if(e!==t){if(!t){if(isValidPrimitiveAttributeValueType(e)){t=e;continue}return!1}return!1}}return!0}function isValidPrimitiveAttributeValueType(e){switch(e){case"number":case"boolean":case"string":return!0}return!1}function loggingErrorHandler(){return e=>{diag.error(stringifyException(e))}}function stringifyException(e){return"string"==typeof e?e:JSON.stringify(flattenException(e))}function flattenException(e){const t={};let r=e;for(;null!==r;)Object.getOwnPropertyNames(r).forEach(e=>{if(t[e])return;const n=r[e];n&&(t[e]=String(n))}),r=Object.getPrototypeOf(r);return t}let delegateHandler=loggingErrorHandler();function globalErrorHandler(e){try{delegateHandler(e)}catch{}}function getNumberFromEnv(e){}const otperformance=performance,NANOSECOND_DIGITS=9,NANOSECOND_DIGITS_IN_MILLIS=6,MILLISECONDS_TO_NANOSECONDS=Math.pow(10,NANOSECOND_DIGITS_IN_MILLIS),SECOND_TO_NANOSECONDS=Math.pow(10,NANOSECOND_DIGITS);function millisToHrTime(e){const t=e/1e3;return[Math.trunc(t),Math.round(e%1e3*MILLISECONDS_TO_NANOSECONDS)]}function getTimeOrigin(){let e=otperformance.timeOrigin;if("number"!=typeof e){const t=otperformance;e=t.timing&&t.timing.fetchStart}return e}function hrTime(e){return addHrTimes(millisToHrTime(getTimeOrigin()),millisToHrTime("number"==typeof e?e:otperformance.now()))}function hrTimeDuration(e,t){let r=t[0]-e[0],n=t[1]-e[1];return n<0&&(r-=1,n+=SECOND_TO_NANOSECONDS),[r,n]}function hrTimeToMicroseconds(e){return 1e6*e[0]+e[1]/1e3}function isTimeInputHrTime(e){return Array.isArray(e)&&2===e.length&&"number"==typeof e[0]&&"number"==typeof e[1]}function isTimeInput(e){return isTimeInputHrTime(e)||"number"==typeof e||e instanceof Date}function addHrTimes(e,t){const r=[e[0]+t[0],e[1]+t[1]];return r[1]>=SECOND_TO_NANOSECONDS&&(r[1]-=SECOND_TO_NANOSECONDS,r[0]+=1),r}var ExportResultCode;!function(e){e[e.SUCCESS=0]="SUCCESS",e[e.FAILED=1]="FAILED"}(ExportResultCode||(ExportResultCode={}));const objectTag="[object Object]",nullTag="[object Null]",undefinedTag="[object Undefined]",funcProto=Function.prototype,funcToString=funcProto.toString,objectCtorString=funcToString.call(Object),getPrototypeOf=Object.getPrototypeOf,objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty,symToStringTag=Symbol?Symbol.toStringTag:void 0,nativeObjectToString=objectProto.toString;function isPlainObject(e){if(!isObjectLike(e)||baseGetTag(e)!==objectTag)return!1;const t=getPrototypeOf(e);if(null===t)return!0;const r=hasOwnProperty.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&funcToString.call(r)===objectCtorString}function isObjectLike(e){return null!=e&&"object"==typeof e}function baseGetTag(e){return null==e?void 0===e?undefinedTag:nullTag:symToStringTag&&symToStringTag in Object(e)?getRawTag(e):objectToString(e)}function getRawTag(e){const t=hasOwnProperty.call(e,symToStringTag),r=e[symToStringTag];let n=!1;try{e[symToStringTag]=void 0,n=!0}catch{}const i=nativeObjectToString.call(e);return n&&(t?e[symToStringTag]=r:delete e[symToStringTag]),i}function objectToString(e){return nativeObjectToString.call(e)}const MAX_LEVEL=20;function merge(...e){let t=e.shift();const r=new WeakMap;for(;e.length>0;)t=mergeTwoObjects(t,e.shift(),0,r);return t}function takeValue(e){return isArray(e)?e.slice():e}function mergeTwoObjects(e,t,r=0,n){let i;if(!(r>MAX_LEVEL)){if(r++,isPrimitive(e)||isPrimitive(t)||isFunction(t))i=takeValue(t);else if(isArray(e)){if(i=e.slice(),isArray(t))for(let e=0,r=t.length;e<r;e++)i.push(takeValue(t[e]));else if(isObject(t)){const e=Object.keys(t);for(let r=0,n=e.length;r<n;r++){const n=e[r];i[n]=takeValue(t[n])}}}else if(isObject(e))if(isObject(t)){if(!shouldMerge(e,t))return t;i=Object.assign({},e);const o=Object.keys(t);for(let s=0,a=o.length;s<a;s++){const a=o[s],c=t[a];if(isPrimitive(c))void 0===c?delete i[a]:i[a]=c;else{const o=i[a],s=c;if(wasObjectReferenced(e,a,n)||wasObjectReferenced(t,a,n))delete i[a];else{if(isObject(o)&&isObject(s)){const r=n.get(o)||[],i=n.get(s)||[];r.push({obj:e,key:a}),i.push({obj:t,key:a}),n.set(o,r),n.set(s,i)}i[a]=mergeTwoObjects(i[a],c,r,n)}}}}else i=t;return i}}function wasObjectReferenced(e,t,r){const n=r.get(e[t])||[];for(let r=0,i=n.length;r<i;r++){const i=n[r];if(i.key===t&&i.obj===e)return!0}return!1}function isArray(e){return Array.isArray(e)}function isFunction(e){return"function"==typeof e}function isObject(e){return!isPrimitive(e)&&!isArray(e)&&!isFunction(e)&&"object"==typeof e}function isPrimitive(e){return"string"==typeof e||"number"==typeof e||"boolean"==typeof e||void 0===e||e instanceof Date||e instanceof RegExp||null===e}function shouldMerge(e,t){return!(!isPlainObject(e)||!isPlainObject(t))}class Deferred{_promise;_resolve;_reject;constructor(){this._promise=new Promise((e,t)=>{this._resolve=e,this._reject=t})}get promise(){return this._promise}resolve(e){this._resolve(e)}reject(e){this._reject(e)}}class BindOnceFuture{_callback;_that;_isCalled=!1;_deferred=new Deferred;constructor(e,t){this._callback=e,this._that=t}get isCalled(){return this._isCalled}get promise(){return this._deferred.promise}call(...e){if(!this._isCalled){this._isCalled=!0;try{Promise.resolve(this._callback.call(this._that,...e)).then(e=>this._deferred.resolve(e),e=>this._deferred.reject(e))}catch(e){this._deferred.reject(e)}}return this._deferred.promise}}function _export(e,t){return new Promise(r=>{context.with(suppressTracing(context.active()),()=>{e.export(t,e=>{r(e)})})})}const internal={_export:_export},ExceptionEventName="exception";class SpanImpl{_spanContext;kind;parentSpanContext;attributes={};links=[];events=[];startTime;resource;instrumentationScope;_droppedAttributesCount=0;_droppedEventsCount=0;_droppedLinksCount=0;name;status={code:SpanStatusCode.UNSET};endTime=[0,0];_ended=!1;_duration=[-1,-1];_spanProcessor;_spanLimits;_attributeValueLengthLimit;_performanceStartTime;_performanceOffset;_startTimeProvided;constructor(e){const t=Date.now();this._spanContext=e.spanContext,this._performanceStartTime=otperformance.now(),this._performanceOffset=t-(this._performanceStartTime+getTimeOrigin()),this._startTimeProvided=null!=e.startTime,this._spanLimits=e.spanLimits,this._attributeValueLengthLimit=this._spanLimits.attributeValueLengthLimit||0,this._spanProcessor=e.spanProcessor,this.name=e.name,this.parentSpanContext=e.parentSpanContext,this.kind=e.kind,this.links=e.links||[],this.startTime=this._getTime(e.startTime??t),this.resource=e.resource,this.instrumentationScope=e.scope,null!=e.attributes&&this.setAttributes(e.attributes),this._spanProcessor.onStart(this,e.context)}spanContext(){return this._spanContext}setAttribute(e,t){if(null==t||this._isSpanEnded())return this;if(0===e.length)return diag.warn(`Invalid attribute key: ${e}`),this;if(!isAttributeValue(t))return diag.warn(`Invalid attribute value set for key: ${e}`),this;const{attributeCountLimit:r}=this._spanLimits;return void 0!==r&&Object.keys(this.attributes).length>=r&&!Object.prototype.hasOwnProperty.call(this.attributes,e)?(this._droppedAttributesCount++,this):(this.attributes[e]=this._truncateToSize(t),this)}setAttributes(e){for(const[t,r]of Object.entries(e))this.setAttribute(t,r);return this}addEvent(e,t,r){if(this._isSpanEnded())return this;const{eventCountLimit:n}=this._spanLimits;if(0===n)return diag.warn("No events allowed."),this._droppedEventsCount++,this;void 0!==n&&this.events.length>=n&&(0===this._droppedEventsCount&&diag.debug("Dropping extra events."),this.events.shift(),this._droppedEventsCount++),isTimeInput(t)&&(isTimeInput(r)||(r=t),t=void 0);const i=sanitizeAttributes(t);return this.events.push({name:e,attributes:i,time:this._getTime(r),droppedAttributesCount:0}),this}addLink(e){return this.links.push(e),this}addLinks(e){return this.links.push(...e),this}setStatus(e){return this._isSpanEnded()||(this.status={...e},null!=this.status.message&&"string"!=typeof e.message&&(diag.warn(`Dropping invalid status.message of type '${typeof e.message}', expected 'string'`),delete this.status.message)),this}updateName(e){return this._isSpanEnded()||(this.name=e),this}end(e){this._isSpanEnded()?diag.error(`${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`):(this._ended=!0,this.endTime=this._getTime(e),this._duration=hrTimeDuration(this.startTime,this.endTime),this._duration[0]<0&&(diag.warn("Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.",this.startTime,this.endTime),this.endTime=this.startTime.slice(),this._duration=[0,0]),this._droppedEventsCount>0&&diag.warn(`Dropped ${this._droppedEventsCount} events because eventCountLimit reached`),this._spanProcessor.onEnd(this))}_getTime(e){if("number"==typeof e&&e<=otperformance.now())return hrTime(e+this._performanceOffset);if("number"==typeof e)return millisToHrTime(e);if(e instanceof Date)return millisToHrTime(e.getTime());if(isTimeInputHrTime(e))return e;if(this._startTimeProvided)return millisToHrTime(Date.now());const t=otperformance.now()-this._performanceStartTime;return addHrTimes(this.startTime,millisToHrTime(t))}isRecording(){return!1===this._ended}recordException(e,t){const r={};"string"==typeof e?r[ATTR_EXCEPTION_MESSAGE]=e:e&&(e.code?r[ATTR_EXCEPTION_TYPE]=e.code.toString():e.name&&(r[ATTR_EXCEPTION_TYPE]=e.name),e.message&&(r[ATTR_EXCEPTION_MESSAGE]=e.message),e.stack&&(r[ATTR_EXCEPTION_STACKTRACE]=e.stack)),r[ATTR_EXCEPTION_TYPE]||r[ATTR_EXCEPTION_MESSAGE]?this.addEvent(ExceptionEventName,r,t):diag.warn(`Failed to record an exception ${e}`)}get duration(){return this._duration}get ended(){return this._ended}get droppedAttributesCount(){return this._droppedAttributesCount}get droppedEventsCount(){return this._droppedEventsCount}get droppedLinksCount(){return this._droppedLinksCount}_isSpanEnded(){if(this._ended){const e=new Error(`Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`);diag.warn(`Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`,e)}return this._ended}_truncateToLimitUtil(e,t){return e.length<=t?e:e.substring(0,t)}_truncateToSize(e){const t=this._attributeValueLengthLimit;return t<=0?(diag.warn(`Attribute value limit must be positive, got ${t}`),e):"string"==typeof e?this._truncateToLimitUtil(e,t):Array.isArray(e)?e.map(e=>"string"==typeof e?this._truncateToLimitUtil(e,t):e):e}}var SamplingDecision,TracesSamplerValues;!function(e){e[e.NOT_RECORD=0]="NOT_RECORD",e[e.RECORD=1]="RECORD",e[e.RECORD_AND_SAMPLED=2]="RECORD_AND_SAMPLED"}(SamplingDecision||(SamplingDecision={}));class AlwaysOffSampler{shouldSample(){return{decision:SamplingDecision.NOT_RECORD}}toString(){return"AlwaysOffSampler"}}class AlwaysOnSampler{shouldSample(){return{decision:SamplingDecision.RECORD_AND_SAMPLED}}toString(){return"AlwaysOnSampler"}}class ParentBasedSampler{_root;_remoteParentSampled;_remoteParentNotSampled;_localParentSampled;_localParentNotSampled;constructor(e){this._root=e.root,this._root||(globalErrorHandler(new Error("ParentBasedSampler must have a root sampler configured")),this._root=new AlwaysOnSampler),this._remoteParentSampled=e.remoteParentSampled??new AlwaysOnSampler,this._remoteParentNotSampled=e.remoteParentNotSampled??new AlwaysOffSampler,this._localParentSampled=e.localParentSampled??new AlwaysOnSampler,this._localParentNotSampled=e.localParentNotSampled??new AlwaysOffSampler}shouldSample(e,t,r,n,i,o){const s=trace.getSpanContext(e);return s&&isSpanContextValid(s)?s.isRemote?s.traceFlags&TraceFlags.SAMPLED?this._remoteParentSampled.shouldSample(e,t,r,n,i,o):this._remoteParentNotSampled.shouldSample(e,t,r,n,i,o):s.traceFlags&TraceFlags.SAMPLED?this._localParentSampled.shouldSample(e,t,r,n,i,o):this._localParentNotSampled.shouldSample(e,t,r,n,i,o):this._root.shouldSample(e,t,r,n,i,o)}toString(){return`ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`}}class TraceIdRatioBasedSampler{_ratio;_upperBound;constructor(e=0){this._ratio=e,this._ratio=this._normalize(e),this._upperBound=Math.floor(4294967295*this._ratio)}shouldSample(e,t){return{decision:isValidTraceId(t)&&this._accumulate(t)<this._upperBound?SamplingDecision.RECORD_AND_SAMPLED:SamplingDecision.NOT_RECORD}}toString(){return`TraceIdRatioBased{${this._ratio}}`}_normalize(e){return"number"!=typeof e||isNaN(e)?0:e>=1?1:e<=0?0:e}_accumulate(e){let t=0;for(let r=0;r<e.length/8;r++){const n=8*r;t=(t^parseInt(e.slice(n,n+8),16))>>>0}return t}}!function(e){e.AlwaysOff="always_off",e.AlwaysOn="always_on",e.ParentBasedAlwaysOff="parentbased_always_off",e.ParentBasedAlwaysOn="parentbased_always_on",e.ParentBasedTraceIdRatio="parentbased_traceidratio",e.TraceIdRatio="traceidratio"}(TracesSamplerValues||(TracesSamplerValues={}));const DEFAULT_RATIO=1;function loadDefaultConfig(){return{sampler:buildSamplerFromEnv(),forceFlushTimeoutMillis:3e4,generalLimits:{attributeValueLengthLimit:1/0,attributeCountLimit:128},spanLimits:{attributeValueLengthLimit:1/0,attributeCountLimit:128,linkCountLimit:128,eventCountLimit:128,attributePerEventCountLimit:128,attributePerLinkCountLimit:128}}}function buildSamplerFromEnv(){const e=TracesSamplerValues.ParentBasedAlwaysOn;switch(e){case TracesSamplerValues.AlwaysOn:return new AlwaysOnSampler;case TracesSamplerValues.AlwaysOff:return new AlwaysOffSampler;case TracesSamplerValues.ParentBasedAlwaysOn:return new ParentBasedSampler({root:new AlwaysOnSampler});case TracesSamplerValues.ParentBasedAlwaysOff:return new ParentBasedSampler({root:new AlwaysOffSampler});case TracesSamplerValues.TraceIdRatio:return new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv());case TracesSamplerValues.ParentBasedTraceIdRatio:return new ParentBasedSampler({root:new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv())});default:return diag.error(`OTEL_TRACES_SAMPLER value "${e}" invalid, defaulting to "${TracesSamplerValues.ParentBasedAlwaysOn}".`),new ParentBasedSampler({root:new AlwaysOnSampler})}}function getSamplerProbabilityFromEnv(){return diag.error(`OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${DEFAULT_RATIO}.`),DEFAULT_RATIO}const DEFAULT_ATTRIBUTE_COUNT_LIMIT=128,DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT=1/0;function mergeConfig(e){const t={sampler:buildSamplerFromEnv()},r=loadDefaultConfig(),n=Object.assign({},r,t,e);return n.generalLimits=Object.assign({},r.generalLimits,e.generalLimits||{}),n.spanLimits=Object.assign({},r.spanLimits,e.spanLimits||{}),n}function reconfigureLimits(e){const t=Object.assign({},e.spanLimits);return t.attributeCountLimit=e.spanLimits?.attributeCountLimit??e.generalLimits?.attributeCountLimit??getNumberFromEnv()??getNumberFromEnv()??DEFAULT_ATTRIBUTE_COUNT_LIMIT,t.attributeValueLengthLimit=e.spanLimits?.attributeValueLengthLimit??e.generalLimits?.attributeValueLengthLimit??getNumberFromEnv()??getNumberFromEnv()??DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,Object.assign({},e,{spanLimits:t})}class BatchSpanProcessorBase{_exporter;_maxExportBatchSize;_maxQueueSize;_scheduledDelayMillis;_exportTimeoutMillis;_isExporting=!1;_finishedSpans=[];_timer;_shutdownOnce;_droppedSpansCount=0;constructor(e,t){this._exporter=e,this._maxExportBatchSize="number"==typeof t?.maxExportBatchSize?t.maxExportBatchSize:512,this._maxQueueSize="number"==typeof t?.maxQueueSize?t.maxQueueSize:2048,this._scheduledDelayMillis="number"==typeof t?.scheduledDelayMillis?t.scheduledDelayMillis:5e3,this._exportTimeoutMillis="number"==typeof t?.exportTimeoutMillis?t.exportTimeoutMillis:3e4,this._shutdownOnce=new BindOnceFuture(this._shutdown,this),this._maxExportBatchSize>this._maxQueueSize&&(diag.warn("BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize"),this._maxExportBatchSize=this._maxQueueSize)}forceFlush(){return this._shutdownOnce.isCalled?this._shutdownOnce.promise:this._flushAll()}onStart(e,t){}onEnd(e){this._shutdownOnce.isCalled||0!==(e.spanContext().traceFlags&TraceFlags.SAMPLED)&&this._addToBuffer(e)}shutdown(){return this._shutdownOnce.call()}_shutdown(){return Promise.resolve().then(()=>this.onShutdown()).then(()=>this._flushAll()).then(()=>this._exporter.shutdown())}_addToBuffer(e){if(this._finishedSpans.length>=this._maxQueueSize)return 0===this._droppedSpansCount&&diag.debug("maxQueueSize reached, dropping spans"),void this._droppedSpansCount++;this._droppedSpansCount>0&&(diag.warn(`Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`),this._droppedSpansCount=0),this._finishedSpans.push(e),this._maybeStartTimer()}_flushAll(){return new Promise((e,t)=>{const r=[];for(let e=0,t=Math.ceil(this._finishedSpans.length/this._maxExportBatchSize);e<t;e++)r.push(this._flushOneBatch());Promise.all(r).then(()=>{e()}).catch(t)})}_flushOneBatch(){return this._clearTimer(),0===this._finishedSpans.length?Promise.resolve():new Promise((e,t)=>{const r=setTimeout(()=>{t(new Error("Timeout"))},this._exportTimeoutMillis);context.with(suppressTracing(context.active()),()=>{let n;this._finishedSpans.length<=this._maxExportBatchSize?(n=this._finishedSpans,this._finishedSpans=[]):n=this._finishedSpans.splice(0,this._maxExportBatchSize);const i=()=>this._exporter.export(n,n=>{clearTimeout(r),n.code===ExportResultCode.SUCCESS?e():t(n.error??new Error("BatchSpanProcessor: span export failed"))});let o=null;for(let e=0,t=n.length;e<t;e++){const t=n[e];t.resource.asyncAttributesPending&&t.resource.waitForAsyncAttributes&&(o??=[],o.push(t.resource.waitForAsyncAttributes()))}null===o?i():Promise.all(o).then(i,e=>{globalErrorHandler(e),t(e)})})})}_maybeStartTimer(){if(this._isExporting)return;const e=()=>{this._isExporting=!0,this._flushOneBatch().finally(()=>{this._isExporting=!1,this._finishedSpans.length>0&&(this._clearTimer(),this._maybeStartTimer())}).catch(e=>{this._isExporting=!1,globalErrorHandler(e)})};if(this._finishedSpans.length>=this._maxExportBatchSize)return e();void 0===this._timer&&(this._timer=setTimeout(()=>e(),this._scheduledDelayMillis),"number"!=typeof this._timer&&this._timer.unref())}_clearTimer(){void 0!==this._timer&&(clearTimeout(this._timer),this._timer=void 0)}}class BatchSpanProcessor extends BatchSpanProcessorBase{_visibilityChangeListener;_pageHideListener;constructor(e,t){super(e,t),this.onInit(t)}onInit(e){!0!==e?.disableAutoFlushOnDocumentHide&&"undefined"!=typeof document&&(this._visibilityChangeListener=()=>{"hidden"===document.visibilityState&&this.forceFlush().catch(e=>{globalErrorHandler(e)})},this._pageHideListener=()=>{this.forceFlush().catch(e=>{globalErrorHandler(e)})},document.addEventListener("visibilitychange",this._visibilityChangeListener),document.addEventListener("pagehide",this._pageHideListener))}onShutdown(){"undefined"!=typeof document&&(this._visibilityChangeListener&&document.removeEventListener("visibilitychange",this._visibilityChangeListener),this._pageHideListener&&document.removeEventListener("pagehide",this._pageHideListener))}}const SPAN_ID_BYTES=8,TRACE_ID_BYTES=16;class RandomIdGenerator{generateTraceId=getIdGenerator(TRACE_ID_BYTES);generateSpanId=getIdGenerator(SPAN_ID_BYTES)}const SHARED_CHAR_CODES_ARRAY=Array(32);function getIdGenerator(e){return function(){for(let t=0;t<2*e;t++)SHARED_CHAR_CODES_ARRAY[t]=Math.floor(16*Math.random())+48,SHARED_CHAR_CODES_ARRAY[t]>=58&&(SHARED_CHAR_CODES_ARRAY[t]+=39);return String.fromCharCode.apply(null,SHARED_CHAR_CODES_ARRAY.slice(0,2*e))}}class Tracer{_sampler;_generalLimits;_spanLimits;_idGenerator;instrumentationScope;_resource;_spanProcessor;constructor(e,t,r,n){const i=mergeConfig(t);this._sampler=i.sampler,this._generalLimits=i.generalLimits,this._spanLimits=i.spanLimits,this._idGenerator=t.idGenerator||new RandomIdGenerator,this._resource=r,this._spanProcessor=n,this.instrumentationScope=e}startSpan(e,t={},r=context.active()){t.root&&(r=trace.deleteSpan(r));const n=trace.getSpan(r);if(isTracingSuppressed(r)){diag.debug("Instrumentation suppressed, returning Noop Span");return trace.wrapSpanContext(INVALID_SPAN_CONTEXT)}const i=n?.spanContext(),o=this._idGenerator.generateSpanId();let s,a,c;i&&trace.isSpanContextValid(i)?(a=i.traceId,c=i.traceState,s=i):a=this._idGenerator.generateTraceId();const l=t.kind??SpanKind.INTERNAL,u=(t.links??[]).map(e=>({context:e.context,attributes:sanitizeAttributes(e.attributes)})),d=sanitizeAttributes(t.attributes),h=this._sampler.shouldSample(r,a,e,l,d,u);c=h.traceState??c;const p={traceId:a,spanId:o,traceFlags:h.decision===SamplingDecision$1.RECORD_AND_SAMPLED?TraceFlags.SAMPLED:TraceFlags.NONE,traceState:c};if(h.decision===SamplingDecision$1.NOT_RECORD){diag.debug("Recording is off, propagating context in a non-recording span");return trace.wrapSpanContext(p)}const g=sanitizeAttributes(Object.assign(d,h.attributes));return new SpanImpl({resource:this._resource,scope:this.instrumentationScope,context:r,spanContext:p,name:e,kind:l,links:u,parentSpanContext:s,attributes:g,startTime:t.startTime,spanProcessor:this._spanProcessor,spanLimits:this._spanLimits})}startActiveSpan(e,t,r,n){let i,o,s;if(arguments.length<2)return;2===arguments.length?s=t:3===arguments.length?(i=t,s=r):(i=t,o=r,s=n);const a=o??context.active(),c=this.startSpan(e,i,a),l=trace.setSpan(a,c);return context.with(l,s,void 0,c)}getGeneralLimits(){return this._generalLimits}getSpanLimits(){return this._spanLimits}}class MultiSpanProcessor{_spanProcessors;constructor(e){this._spanProcessors=e}forceFlush(){const e=[];for(const t of this._spanProcessors)e.push(t.forceFlush());return new Promise(t=>{Promise.all(e).then(()=>{t()}).catch(e=>{globalErrorHandler(e||new Error("MultiSpanProcessor: forceFlush failed")),t()})})}onStart(e,t){for(const r of this._spanProcessors)r.onStart(e,t)}onEnd(e){for(const t of this._spanProcessors)t.onEnd(e)}shutdown(){const e=[];for(const t of this._spanProcessors)e.push(t.shutdown());return new Promise((t,r)=>{Promise.all(e).then(()=>{t()},r)})}}var ForceFlushState;!function(e){e[e.resolved=0]="resolved",e[e.timeout=1]="timeout",e[e.error=2]="error",e[e.unresolved=3]="unresolved"}(ForceFlushState||(ForceFlushState={}));class BasicTracerProvider{_config;_tracers=new Map;_resource;_activeSpanProcessor;constructor(e={}){const t=merge({},loadDefaultConfig(),reconfigureLimits(e));this._resource=t.resource??defaultResource$1(),this._config=Object.assign({},t,{resource:this._resource});const r=[];e.spanProcessors?.length&&r.push(...e.spanProcessors),this._activeSpanProcessor=new MultiSpanProcessor(r)}getTracer(e,t,r){const n=`${e}@${t||""}:${r?.schemaUrl||""}`;return this._tracers.has(n)||this._tracers.set(n,new Tracer({name:e,version:t,schemaUrl:r?.schemaUrl},this._config,this._resource,this._activeSpanProcessor)),this._tracers.get(n)}forceFlush(){const e=this._config.forceFlushTimeoutMillis,t=this._activeSpanProcessor._spanProcessors.map(t=>new Promise(r=>{let n;const i=setTimeout(()=>{r(new Error(`Span processor did not completed within timeout period of ${e} ms`)),n=ForceFlushState.timeout},e);t.forceFlush().then(()=>{clearTimeout(i),n!==ForceFlushState.timeout&&(n=ForceFlushState.resolved,r(n))}).catch(e=>{clearTimeout(i),n=ForceFlushState.error,r(e)})}));return new Promise((e,r)=>{Promise.all(t).then(t=>{const n=t.filter(e=>e!==ForceFlushState.resolved);n.length>0?r(n):e()}).catch(e=>r([e]))})}shutdown(){return this._activeSpanProcessor.shutdown()}}class ConsoleSpanExporter{export(e,t){return this._sendSpans(e,t)}shutdown(){return this._sendSpans([]),this.forceFlush()}forceFlush(){return Promise.resolve()}_exportInfo(e){return{resource:{attributes:e.resource.attributes},instrumentationScope:e.instrumentationScope,traceId:e.spanContext().traceId,parentSpanContext:e.parentSpanContext,traceState:e.spanContext().traceState?.serialize(),name:e.name,id:e.spanContext().spanId,kind:e.kind,timestamp:hrTimeToMicroseconds(e.startTime),duration:hrTimeToMicroseconds(e.duration),attributes:e.attributes,status:e.status,events:e.events,links:e.links}}_sendSpans(e,t){for(const t of e)console.dir(this._exportInfo(t),{depth:3});if(t)return t({code:ExportResultCode.SUCCESS})}}class InMemorySpanExporter{_finishedSpans=[];_stopped=!1;export(e,t){if(this._stopped)return t({code:ExportResultCode.FAILED,error:new Error("Exporter has been stopped")});this._finishedSpans.push(...e),setTimeout(()=>t({code:ExportResultCode.SUCCESS}),0)}shutdown(){return this._stopped=!0,this._finishedSpans=[],this.forceFlush()}forceFlush(){return Promise.resolve()}reset(){this._finishedSpans=[]}getFinishedSpans(){return this._finishedSpans}}class SimpleSpanProcessor{_exporter;_shutdownOnce;_pendingExports;constructor(e){this._exporter=e,this._shutdownOnce=new BindOnceFuture(this._shutdown,this),this._pendingExports=new Set}async forceFlush(){await Promise.all(Array.from(this._pendingExports)),this._exporter.forceFlush&&await this._exporter.forceFlush()}onStart(e,t){}onEnd(e){if(this._shutdownOnce.isCalled)return;if(0===(e.spanContext().traceFlags&TraceFlags.SAMPLED))return;const t=this._doExport(e).catch(e=>globalErrorHandler(e));this._pendingExports.add(t),t.finally(()=>this._pendingExports.delete(t))}async _doExport(e){e.resource.asyncAttributesPending&&await(e.resource.waitForAsyncAttributes?.());const t=await internal._export(this._exporter,[e]);if(t.code!==ExportResultCode.SUCCESS)throw t.error??new Error(`SimpleSpanProcessor: span export failed (status ${t})`)}shutdown(){return this._shutdownOnce.call()}_shutdown(){return this._exporter.shutdown()}}class NoopSpanProcessor{onStart(e,t){}onEnd(e){}shutdown(){return Promise.resolve()}forceFlush(){return Promise.resolve()}}var esm$1=Object.freeze({__proto__:null,AlwaysOffSampler:AlwaysOffSampler,AlwaysOnSampler:AlwaysOnSampler,BasicTracerProvider:BasicTracerProvider,BatchSpanProcessor:BatchSpanProcessor,ConsoleSpanExporter:ConsoleSpanExporter,InMemorySpanExporter:InMemorySpanExporter,NoopSpanProcessor:NoopSpanProcessor,ParentBasedSampler:ParentBasedSampler,RandomIdGenerator:RandomIdGenerator,get SamplingDecision(){return SamplingDecision},SimpleSpanProcessor:SimpleSpanProcessor,TraceIdRatioBasedSampler:TraceIdRatioBasedSampler}),require$$0=getAugmentedNamespace(esm$1),durationFilterProcessor={};Object.defineProperty(durationFilterProcessor,"__esModule",{value:!0}),durationFilterProcessor.DurationFilterProcessor=void 0;class DurationFilterProcessor{constructor(e){this._innerProcessor=e}onStart(e,t){this._innerProcessor.onStart(e,t)}onEnd(e){const t=e.attributes.insightsMinDurationMs&&parseInt(e.attributes.insightsMinDurationMs+"",10);if(t){1e9*e.endTime[0]+e.endTime[1]-(1e9*e.startTime[0]+e.startTime[1])>=1e6*t&&this._innerProcessor.onEnd(e)}else this._innerProcessor.onEnd(e)}shutdown(){return this._innerProcessor.shutdown()}forceFlush(){return this._innerProcessor.forceFlush()}}durationFilterProcessor.DurationFilterProcessor=DurationFilterProcessor;var parentOperationSpanProcessor={};Object.defineProperty(parentOperationSpanProcessor,"__esModule",{value:!0}),parentOperationSpanProcessor.ParentOperationSpanProcessor=void 0;const api_1$1=require$$0$2;class ParentOperationSpanProcessor{constructor(e,t){this._innerProcessor=e,this.nameLimit=t}onStart(e,t){var r,n;if(this.nameLimit)try{const i=ParentOperationSpanProcessor._spanToName,o=ParentOperationSpanProcessor._spanNames,s=e.spanContext().spanId;if(!i.has(s)&&(i.set(s,e.name),this.nameLimit>0))for(o.push(e.name);o.length>this.nameLimit;)i.delete(o[0]),o.shift();const a=api_1$1.trace.getSpan(null!=t?t:api_1$1.context.active());a&&e.setAttribute("insights.parent.operation",null!==(r=a.name)&&void 0!==r?r:i.get(null===(n=a.spanContext())||void 0===n?void 0:n.spanId))}catch(e){}this._innerProcessor.onStart(e,t)}onEnd(e){this._innerProcessor.onEnd(e)}forceFlush(){return this._innerProcessor.forceFlush()}shutdown(){return this._innerProcessor.shutdown()}}parentOperationSpanProcessor.ParentOperationSpanProcessor=ParentOperationSpanProcessor,ParentOperationSpanProcessor._spanNames=[],ParentOperationSpanProcessor._spanToName=new Map;var ioInsightsSampler$1={};Object.defineProperty(ioInsightsSampler$1,"__esModule",{value:!0}),ioInsightsSampler$1.ioInsightsSampler=void 0;const otel_1$5=requireDist$1(),cyrb53=(e,t=0)=>{let r=3735928559^t,n=1103547991^t;for(let t,i=0;i<e.length;i++)t=e.charCodeAt(i),r=Math.imul(r^t,2654435761),n=Math.imul(n^t,1597334677);return r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),4294967296*(2097151&n)+(r>>>0)};class ioInsightsSampler{constructor(e,t,r,n){this.settings=e,this.defaults=t,this.filteringContextGetter=r,this.logger=n}shouldSample(e,t,r,n,i,o){var s,a,c,l,u,d,h,p,g,m,f,y;const $=otel_1$5.Container.errorless(()=>{var e;return null===(e=this.filteringContextGetter)||void 0===e?void 0:e.call(null)})||{};for(const e of this.settings||[]){let n=!0;if(n&&e.name&&(this.matchObjects("name",{name:e.name},{name:r})||(n=!1)),n&&e.attributes&&(this.matchObjects("attributes",e.attributes,i)||(n=!1)),n&&e.context&&(this.matchObjects("context",e.context,$,!0)||(n=!1)),n)return(null===(l=this.logger)||void 0===l?void 0:l.level)&&(null===(u=this.logger)||void 0===u?void 0:u.level)>=80&&(null===(d=this.logger)||void 0===d||d.verbose("sampling rule matched: "+JSON.stringify(e))),this.maybeSample(t,e.sample);(null===(s=this.logger)||void 0===s?void 0:s.level)&&(null===(a=this.logger)||void 0===a?void 0:a.level)>=80&&(null===(c=this.logger)||void 0===c||c.verbose("sampling rule didn't match: "+JSON.stringify(e)))}return(null===(h=this.logger)||void 0===h?void 0:h.level)&&(null===(p=this.logger)||void 0===p?void 0:p.level)>=80&&(null===(g=this.logger)||void 0===g||g.verbose("no sampling rule matched, will fall back to defaults "+JSON.stringify(this.defaults||{}))),this.defaults?this.maybeSample(t,this.defaults.sample||!0):((null===(m=this.logger)||void 0===m?void 0:m.level)&&(null===(f=this.logger)||void 0===f?void 0:f.level)>=80&&(null===(y=this.logger)||void 0===y||y.verbose("no sampling rule matched, no defaults - will sample")),{decision:2})}toString(){try{return"ioInsightsSampler: "+JSON.stringify({settings:this.settings,defaults:this.defaults})}catch(e){return"ioInsightsSampler: (error) "+e.message}}matchObjects(e,t,r,n){var i,o,s,a,c,l;for(const[u,d]of Object.entries(t)){const t=n?(0,otel_1$5.deep_value)(r,u):r[u];if("string"==typeof d&&"#"===d[0]&&(null==t||!new RegExp(d.substring(1),"i").test(t+"")))return(null===(i=this.logger)||void 0===i?void 0:i.level)&&(null===(o=this.logger)||void 0===o?void 0:o.level)>=80&&(null===(s=this.logger)||void 0===s||s.verbose(`matching ${e}: regex ${d} doesn't match ${t}`)),!1;if(d!==t)return(null===(a=this.logger)||void 0===a?void 0:a.level)&&(null===(c=this.logger)||void 0===c?void 0:c.level)>=80&&(null===(l=this.logger)||void 0===l||l.verbose(`matching ${e}: ${d} doesn't match ${t}`)),!1}return!0}maybeSample(e,t){var r,n,i;let o;if(!0===t||"number"==typeof t&&t>=1)o={decision:2};else if(!1===t||"number"==typeof t&&t<=0)o={decision:0};else{const r=cyrb53(e);o={decision:r/1e3-Math.floor(r/1e3)<=t?2:0}}return(null===(r=this.logger)||void 0===r?void 0:r.level)&&(null===(n=this.logger)||void 0===n?void 0:n.level)>=80&&(null===(i=this.logger)||void 0===i||i.verbose(`sampling decision with value ${t}: ${JSON.stringify(o)}`)),o}}ioInsightsSampler$1.ioInsightsSampler=ioInsightsSampler;class OTLPTraceExporter extends OTLPExporterBase{constructor(e={}){super(createLegacyOtlpBrowserExportDelegate(e,JsonTraceSerializer,"v1/traces",{"Content-Type":"application/json"}))}}var esm=Object.freeze({__proto__:null,OTLPTraceExporter:OTLPTraceExporter}),require$$6=getAugmentedNamespace(esm),require$$7=getAugmentedNamespace(esm$3);!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.saveDataInAttribute=e.isFunctionType=e.setTracerProvider=e.isFilterMatch=e.findMatchingFilters=e.isSpanEnabled=void 0;const t=require$$0,r=require$$0$2,n=require$$0$2,i=durationFilterProcessor,o=parentOperationSpanProcessor,s=ioInsightsSampler$1,a=requireDist$1(),c=require$$6,l=require$$7;e.isSpanEnabled=(e,t,r)=>{var n,i;let o;return o=e?void 0===e.enabled||e.enabled:null===(i=null!==(n=null==t?void 0:t.enabled)&&void 0!==n?n:null==r?void 0:r.enabled)||void 0===i||i,o};e.findMatchingFilters=(t,r,n)=>{let i=!1;const o={},s={source:"",context:{},enabled:!1,stopPropagationIfSpanIsDisabled:!1,level:"INFO",addContextToTrace:!1,autoSetSuccessStatus:!1,sample:0,disablePropagation:!1,disableNesting:!1,countMetric:!1,countMetricOnDisabledSpans:!1,resultMetric:!1,resultMetricOnDisabledSpans:!1,durationMetric:!1,durationMetricOnDisabledSpans:!1,canBeRoot:!1,maxAttributeDepth:0,forceChildTracing:!1,otelSpanOptions:{},minDurationMs:0,log:!1,logOnDisabledSpans:!1,overrideDefaultFilters:!1};for(const a of t)if((0,e.isFilterMatch)(a,r,n)){i=!0;for(const e of Object.keys(s))void 0===o[e]&&(o[e]=a[e])}return i?o:void 0};e.isFilterMatch=(e,t,r)=>{let n=!0;if(e.source&&e.source.startsWith("#")){if(!new RegExp(e.source.substring(1),"i").test(r))return 0}else if(e.source&&r!==e.source&&!r.startsWith(e.source+".")&&r+"."!==e.source)return 0;if(!e.context)return 1;for(const r of Object.keys(e.context)){const i=e.context[r],o=(0,a.deep_value)(t,r);if("string"!=typeof i||"#"!==i[0]){i!==o&&(n=!1);break}if(null==o||!new RegExp(i.substring(1),"i").test(o+"")){n=!1;break}}return n?2:0};e.setTracerProvider=(e,u)=>{var d,h,p,g,m,f;if(!e)throw new Error("Required arguments not provided");const y=(0,a.loadInsightsPlugin)("base",u);if(!y)return;const $=e.traces,b=null==$?void 0:$.processorSettings,w=Object.assign(Object.assign({url:$.url,concurrencyLimit:$.concurrencyLimit,timeoutMillis:$.timeoutMillis,compression:$.compression,keepAlive:$.keepAlive},$.exporterSettings),{headers:Object.assign(Object.assign(Object.assign({},a.Container.errorless(e.headers)),a.Container.errorless(null===(d=$.exporterSettings)||void 0===d?void 0:d.headers)),a.Container.errorless($.headers))}),v=a.Container.errorless(()=>{var t;return null===(t=$.spanProcessors)||void 0===t?void 0:t.call($,b,w,$,e)})||[];let S=a.Container.errorless(()=>{var t;return null===(t=$.spanExporters)||void 0===t?void 0:t.call($,"string"==typeof w?{url:w}:w,$,e)})||[];if(!(null==$?void 0:$.url)||(null==S?void 0:S.length)||(null==v?void 0:v.length)||(S=[new c.OTLPTraceExporter(w)]),(null==$?void 0:$.console)&&S.push(new t.ConsoleSpanExporter),S)for(const e of S)v.push(new t.BatchSpanProcessor(e,b));const E=[];if(v)for(const e of v)E.push(new o.ParentOperationSpanProcessor(new i.DurationFilterProcessor(e),null==$?void 0:$.parentNameLimit));const C=new t.ParentBasedSampler({root:new s.ioInsightsSampler((null==$?void 0:$.sampling)||[],null==$?void 0:$.defaults,()=>Object.assign(Object.assign({},a.Container.errorless(null==$?void 0:$.additionalResourceAttributes)),a.Container.errorless(null==$?void 0:$.additionalAttributes)),u)}),_=a.Container.errorless(()=>{var t;return null===(t=$.sampler)||void 0===t?void 0:t.call($,C,$,e)}),I=Object.assign({sampler:null!=_?_:C,resource:y.resourceFromAttributes(null!==(h=a.Container.errorless(null==$?void 0:$.additionalResourceAttributes))&&void 0!==h?h:{}),spanProcessors:E},null==$?void 0:$.tracerProviderSettings),T=null!==(p=a.Container.errorless(()=>{var t;return null===(t=$.tracerProvider)||void 0===t?void 0:t.call($,I,$,e)}))&&void 0!==p?p:new t.BasicTracerProvider(I);r.trace.disable(),r.trace.setGlobalTracerProvider(T);const A=a.Container.errorless(()=>{var t;return null===(t=$.providerRegistrationSettings)||void 0===t?void 0:t.call($,$,e)}),D=null!==(g=a.Container.errorless(()=>{var t;return"function"==typeof $.contextManager?null===(t=$.contextManager)||void 0===t?void 0:t.call($,$,e):$.contextManager}))&&void 0!==g?g:null==A?void 0:A.contextManager,x=null!==(f=null!==(m=a.Container.errorless(()=>{var t;return null===(t=$.propagator)||void 0===t?void 0:t.call($,$,e)}))&&void 0!==m?m:null==A?void 0:A.propagator)&&void 0!==f?f:new l.W3CTraceContextPropagator;return D&&(D.enable(),n.context.setGlobalContextManager(D)),r.propagation.setGlobalPropagator(x),"function"==typeof T.register&&T.register(A||{}),{tracerProvider:T,spanProcessors:E}};e.isFunctionType=e=>"function"==typeof e;e.saveDataInAttribute=(e,t,r)=>{var n;if(null!=e){"object"!=typeof e&&(e={unknownAttribute:e});for(const[i,o]of Object.entries(e)){const e=(0,a.getOTELData)(i,o,0,r);for(const[r,i]of e)"function"==typeof(null===(n=t.otelSpan)||void 0===n?void 0:n.setAttribute)?t.otelSpan.setAttribute(r,i):"object"==typeof t.attributes&&(t.attributes[r]=i)}}}}(utils);var tracingState={};Object.defineProperty(tracingState,"__esModule",{value:!0}),tracingState.TracingState=void 0;const utils_1$1=utils,otel_1$4=requireDist$1();class TracingState{constructor(e,t,r,n,i,o,s,a,c){this.source=e,this.level=t,this.span=r,this.logger=n,this.version=i,this.disablePropagation=o,this.forceChildTracing=s,this.maxAttributeDepth=a,this.context=c,this.currentSpanStatus={code:otel_1$4.SpanStatusCode.UNSET},this._startTime=new Date,this.hasEnded=!1,this.spanContextField=r.spanContext()}get startTime(){return this._startTime}get endTime(){return this._endTime}end(){return this.endSpan()}endSpan(e,t){var r;return this.hasEnded?t||null===(r=this.logger)||void 0===r||r.debug(`Span ended more than once: ${this.source}`):(this.hasEnded=!0,this._endTime=null!=e?e:new Date,this.span.end(e)),Promise.resolve()}get enabled(){return!0}get id(){return this.spanContextField.spanId}get traceId(){return this.spanContextField.traceId}set status(e){this.currentSpanStatus=Object.assign({},e),this.span.setStatus.call(this.span,e)}get status(){return this.currentSpanStatus}addEvent(e,t,r){return this.span.addEvent.call(this.span,e,t,r),this}recordException(e,t){this.span.recordException.call(this.span,e,t)}isRecording(){return this.span.isRecording.call(this.span)}updateName(e){return this.span.updateName.call(this.span,e),this}spanContext(){return this.span.spanContext.call(this.span)}addData(e,t){var r;"function"==typeof t&&(t=t()),"string"==typeof e&&(e=SpanVerbosity[e]),e>=SpanVerbosity[this.level]&&(0,utils_1$1.saveDataInAttribute)(t,{otelSpan:this.span},null!==(r=this.maxAttributeDepth)&&void 0!==r?r:5)}getPropagationInfo(){const e={traceparent:`${this.version}-${this.spanContextField.traceId}-${this.spanContextField.spanId}-0${this.spanContextField.traceFlags}`,tracestate:this.spanContextField.traceState&&String(this.spanContextField.traceState)};return this.forceChildTracing&&(e.forceTracing=!0),e}injectPropagationInfo(e){if(this.disablePropagation)return;const t=this.getPropagationInfo();t&&(e.__interopIOTracePropagationInfo=t)}}var SpanVerbosity;tracingState.TracingState=TracingState,function(e){e[e.OFF=0]="OFF",e[e.LOWEST=1]="LOWEST",e[e.DIAGNOSTIC=2]="DIAGNOSTIC",e[e.DEBUG=3]="DEBUG",e[e.INFO=4]="INFO",e[e.WARN=5]="WARN",e[e.HIGHEST=6]="HIGHEST"}(SpanVerbosity||(SpanVerbosity={}));var clickstream={};Object.defineProperty(clickstream,"__esModule",{value:!0}),clickstream.instrumentRequests=clickstream.setupClickstreamTrace=void 0;const otel_1$3=requireDist$1(),listenerMap=new WeakMap,eventRoot=new WeakMap;let clickstreamPropagationInfo=null,clickstreamTracingState=null,clickstreamTracePrefix,structure;function setupClickstreamTrace(e){var t,r,n,i,o,s,a,c,l,u,d,h,p,g,m,f,y,$;if("undefined"==typeof window)return;const b=e.applicationName;if(!e.traces||!1===e.traces.clickstream||"object"==typeof e.traces.clickstream&&!(null===(t=e.traces.clickstream)||void 0===t?void 0:t.enabled))return;structure=null!==(s="string"==typeof(null===(r=e.traces)||void 0===r?void 0:r.clickstream)?null===(n=e.traces)||void 0===n?void 0:n.clickstream:"object"==typeof(null===(i=e.traces)||void 0===i?void 0:i.clickstream)?null===(o=e.traces)||void 0===o?void 0:o.clickstream.structure:null)&&void 0!==s?s:"sibling";const w=null===(u="string"==typeof(null===(a=e.traces)||void 0===a?void 0:a.clickstream)?null:"object"==typeof(null===(c=e.traces)||void 0===c?void 0:c.clickstream)?null===(l=e.traces)||void 0===l?void 0:l.clickstream.descriptiveName:null)||void 0===u||u,v=null!==(g="string"==typeof(null===(d=e.traces)||void 0===d?void 0:d.clickstream)?null:"object"==typeof(null===(h=e.traces)||void 0===h?void 0:h.clickstream)?null===(p=e.traces)||void 0===p?void 0:p.clickstream.events:null)&&void 0!==g?g:["click"],S=null===($="string"==typeof(null===(m=e.traces)||void 0===m?void 0:m.clickstream)?null:"object"==typeof(null===(f=e.traces)||void 0===f?void 0:f.clickstream)?null===(y=e.traces)||void 0===y?void 0:y.clickstream.nestEventListeners:null)||void 0===$||$;clickstreamTracePrefix=w?"interopio.api.clickstream."+b+".":"interopio.api.clickstream.";const E=EventTarget.prototype.addEventListener,C=EventTarget.prototype.removeEventListener;for(const e of v)document.addEventListener(e,e=>{maybeStartClickstream(),getOrCreateEventRoot(e)},{capture:!0});return S&&(EventTarget.prototype.addEventListener=function(e,t,r){return t&&v.find(t=>t===e)?E.call(this,e,wrapListener(this,t,clickstreamTracePrefix),r):E.call(this,e,t,r)},EventTarget.prototype.removeEventListener=function(e,t,r){var n;if(!t||!v.find(t=>t===e))return C.call(this,e,t,r);const i=listenerMap.get(this),o=null!==(n=null==i?void 0:i.get(t))&&void 0!==n?n:t;return C.call(this,e,o,r)}),setClickstreamMarker}function getOrCreateEventRoot(e){var t;let r=eventRoot.get(e);if(r)return r;const n=e.target||{},i=getElementSelector(n),o=null===(t=null==n?void 0:n.getBoundingClientRect)||void 0===t?void 0:t.call(n),s=Object.assign(Object.assign({},i),{elementId:n.id,elementHref:n.href,elementSrc:n.src,eventType:e.type,elementBounds:{x:null==o?void 0:o.x,y:null==o?void 0:o.y,top:null==o?void 0:o.top,bottom:null==o?void 0:o.bottom,left:null==o?void 0:o.left,right:null==o?void 0:o.right,height:null==o?void 0:o.height,width:null==o?void 0:o.width}});let a;return otel_1$3.Traces.withSpan(clickstreamTracePrefix+e.type,s,clickstreamPropagationInfo,t=>("nested"===structure&&(clickstreamPropagationInfo=t.getPropagationInfo()),eventRoot.set(e,t),a=t,new Promise(r=>{setTimeout(()=>{t.end(),eventRoot.delete(e),r()},0)}))),a}function maybeStartClickstream(){clickstreamPropagationInfo||otel_1$3.Traces.withSpan(clickstreamTracePrefix+"start",{},null,{disableNesting:!0},e=>{clickstreamTracingState=e,clickstreamPropagationInfo=e.getPropagationInfo()})}function setClickstreamMarker(e,t){var r;if(maybeStartClickstream(),e){let r=null;return otel_1$3.Traces.withSpan(clickstreamTracePrefix+e,{},clickstreamPropagationInfo,e=>{if(clickstreamTracingState=e,t)for(const[r,n]of Object.entries(t))e.addData(r,n);r=e.getPropagationInfo(),"nested"===structure&&(clickstreamPropagationInfo=e.getPropagationInfo())}),Promise.resolve(r)}if(t)for(const[e,r]of Object.entries(t))null==clickstreamTracingState||clickstreamTracingState.addData(e,r);return Promise.resolve(null!==(r=null==clickstreamTracingState?void 0:clickstreamTracingState.getPropagationInfo())&&void 0!==r?r:null)}function getElementSelector(e){const t=e.tagName.toLowerCase(),r=e.id?`#${e.id}`:"",n=Array.from(e.classList).map(e=>`.${e}`).join("");return{elementTagName:t,elementIdSelector:r,elementClassSelector:n,elementSelectorString:t+r+n}}function wrapListener(e,t,r,n){let i=listenerMap.get(e);i||(i=new WeakMap,listenerMap.set(e,i));const o=i.get(t);if(o)return o;const s=function(e,...n){maybeStartClickstream();let i=getOrCreateEventRoot(e);return(()=>{var o;return(0,otel_1$3.withSpan)(r+e.type+".listener",{eventName:e.type},null!==(o=null==i?void 0:i.getPropagationInfo())&&void 0!==o?o:clickstreamPropagationInfo,"function"==typeof t?()=>null==t?void 0:t.call(this,e,...n):()=>{var r;return null===(r=t.handleEvent)||void 0===r?void 0:r.call(t,e,...n)})})()};return i.set(t,s),s}function instrumentRequests(e){try{patchFetch(e)}catch(e){}try{patchXHR()}catch(e){}}clickstream.setupClickstreamTrace=setupClickstreamTrace,clickstream.instrumentRequests=instrumentRequests;const origFetch=globalThis.fetch;function patchFetch(e){"function"==typeof origFetch&&(globalThis.fetch=function(t,r){var n,i,o;let s;const a="string"==typeof t?t:t.url?t.url:t.toString();return a===(null===(n=e.traces)||void 0===n?void 0:n.url)||a===(null===(i=e.metrics)||void 0===i?void 0:i.url)||a===(null===(o=e.logs)||void 0===o?void 0:o.url)?origFetch.call(globalThis,t,r):(otel_1$3.Traces.withSpan("interopio.api.instrumentation.fetch",{url:"string"==typeof t?t:"object"==typeof t&&t.url||String(t),method:r&&r.method||"object"==typeof t&&t.method||"GET"},e=>(s=origFetch.call(globalThis,t,r),s.then(t=>{e.addData("INFO",{statusCode:t.status,responseContentType:t.headers.get("content-type"),responseContentLength:t.headers.get("content-length")})}),s)),s)})}function patchXHR(){const e=globalThis.XMLHttpRequest&&globalThis.XMLHttpRequest.prototype,t=null==e?void 0:e.open,r=null==e?void 0:e.send;function n(e){try{return e.status}catch(e){return null}}function i(e,t){try{return e.getResponseHeader(t)}catch(e){return}}e&&t&&r&&(e.open=function(e,r,n,i,o){let s,a;n=null==n||n;const c=new Promise((e,t)=>{s=e,a=t});otel_1$3.Traces.withSpan("interopio.api.instrumentation.xhr",{method:e||"GET",url:String(r)},l=>(Object.defineProperty(this,"__netRecord",{value:{resolve:s,reject:a,ts:l},configurable:!0}),t.call(this,e,r,null==n||n,i,o),c))},e.send=function(e){const{resolve:t,reject:o,ts:s}=this.__netRecord;if(s){const e=(e,r)=>{if(this.__netRecord){if(this.__netRecord.finalized)return;this.__netRecord.finalized=!0}s.addData("INFO",{statusCode:n(this),responseContentType:i(this,"content-type"),responseContentLength:i(this,"content-length"),resultKind:e}),r&&s.recordException(r),"error"===e?o(r):t(null)};this.addEventListener("loadend",()=>e("success"),{once:!0}),this.addEventListener("error",()=>e("error",new Error("XHR network error")),{once:!0}),this.addEventListener("abort",()=>e("abort",new Error("XHR aborted")),{once:!0}),this.addEventListener("timeout",()=>e("timeout",new Error("XHR timeout")),{once:!0})}return r.call(this,e)})}var startupTrace={};Object.defineProperty(startupTrace,"__esModule",{value:!0}),startupTrace.onDomReady=startupTrace.setStartupTraceLogic=void 0;const otel_1$2=requireDist$1();function setStartupTraceLogic(e){var t,r,n,i;let o=!1;const s=null!==(t=e.startupParentSpanTimeoutMs)&&void 0!==t?t:3e3;let a=e.rootPropagationInfo;if("undefined"!=typeof window&&(a=null!=a?a:null===(r=window.glue42gd)||void 0===r?void 0:r.propagationInfo),a){(0,otel_1$2.isNode)()||onDomReady(()=>{otel_1$2.Traces.withSpan("interopio.api.appStartup.domReady",()=>{})}),e.defaults=null!==(n=e.defaults)&&void 0!==n?n:{};const t=null===(i=e.defaults)||void 0===i?void 0:i.getPropagationInfo;e.defaults.getPropagationInfo=(e,r)=>{const n=null==t?void 0:t(e,r);return n||(o?null:a||null)}}return"number"==typeof s&&s>0&&setTimeout(()=>{o||onDomReady(()=>{otel_1$2.Traces.withSpan("interopio.api.appStartup.finished",e=>{e.addData("INFO",{startupFinishedType:"timeout"})}),o=!0})},s),()=>{otel_1$2.Traces.withSpan("interopio.api.appStartup.explicitFinish",()=>{}),o||(otel_1$2.Traces.withSpan("interopio.api.appStartup.finished",e=>{e.addData("INFO",{startupFinishedType:"explicit"})}),o=!0)}}function onDomReady(e){(0,otel_1$2.isNode)()||"undefined"==typeof window||"undefined"==typeof document?e():"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e):e()}startupTrace.setStartupTraceLogic=setStartupTraceLogic,startupTrace.onDomReady=onDomReady;var constants={};Object.defineProperty(constants,"__esModule",{value:!0}),constants.Defaults=void 0,constants.Defaults={TRACE_VERSION:"00",DEFAULT_USER:"unknown-user",DEFAULT_SERVICE_NAME:"unknown-service-name",DEFAULT_SERVICE_ID:"unknown-service-id",DEFAULT_SERVICE_VERSION:"unknown-service-version",DEFAULT_PLATFORM_VERSION:"unknown-platform-version",DEFAULT_METRIC_DESCRIPTION:"unknown-metric",stopPropagationIfSpanIsDisabled:!1,countMetric:!1,durationMetric:!1,resultMetric:!1,countMetricOnDisabledSpans:!1,durationMetricOnDisabledSpans:!1,resultMetricOnDisabledSpans:!1,maxAttributeDepth:5,otelSpanOptions:{},disablePropagation:!1,addContextToTrace:!0,level:"INFO",forceChildTracing:!1,canBeRoot:!0,currentTracingStateGetterContextName:"interopio.insights.currentTracingStateGetter",minDurationMs:0,log:!1,logOnDisabledSpans:!1};var __awaiter=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})},__importDefault=commonjsGlobal$1&&commonjsGlobal$1.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(manager,"__esModule",{value:!0}),manager.TracesManager=void 0;const api_1=require$$0$2,utils_1=utils,tracingState_1=tracingState,clickstream_1=clickstream,startupTrace_1=startupTrace,constants_1=constants,otel_1$1=requireDist$1(),lodash_clonedeep_1=__importDefault(lodash_clonedeepExports);class TracesManager{constructor(e,t,r,n,i,o){var s,a,c,l,u;this.otelSettings=e,this.logger=t,this.traceLogger=r,this.store=i,this.read=o,this.started=!1,this._currentTracingState=null,this.traceLogger=null!==(s=this.traceLogger)&&void 0!==s?s:this.logger,this.settings=e.traces||{enabled:!1},this.settings.hybridContextMode=null!==(a=this.settings.hybridContextMode)&&void 0!==a&&a,!1!==e.logSettingsOnStartup&&(null==t||t.info(`Starting TracesManager with settings ${(0,otel_1$1.safeStringify)(this.settings)}`)),this.filters=this.settings.filters||[];const d=(0,utils_1.setTracerProvider)(e,this.logger);this.spanProcessors=null==d?void 0:d.spanProcessors,this.tracerProvider=null==d?void 0:d.tracerProvider;const h=this.settings.autoInstrumentations&&(0,otel_1$1.loadInsightsPlugin)("autoInstrumentations",this.logger);this.settings.autoInstrumentations&&h&&this.registerAutoInstrumentations(h),null!==this.settings.countMetric&&(this.traceMetric=null==n?void 0:n.getFromSettings({enabled:!0,description:"Counts number of hits for io.Insights spans",name:null!==(c=this.settings.countMetric)&&void 0!==c?c:"insights_trace_count",type:"custom_counter"})),null!==this.settings.resultMetric&&(this.traceMetricResult=null==n?void 0:n.getFromSettings({enabled:!0,description:"Counts results of io.Insights spans",name:null!==(l=this.settings.resultMetric)&&void 0!==l?l:"insights_trace_result",type:"custom_counter"})),null!==this.settings.durationMetric&&(this.traceMetricDuration=null==n?void 0:n.getFromSettings({enabled:!0,description:"Counts durations of io.Insights spans",name:null!==(u=this.settings.durationMetric)&&void 0!==u?u:"insights_trace_duration",type:"custom_histogram"})),(0,otel_1$1.isNode)()||!1===this.settings.instrumentDocumentLoad||(this.startupTraceFinishedFunc=(0,startupTrace_1.setStartupTraceLogic)(this.settings)),(0,otel_1$1.isNode)()||!1===this.settings.clickstream||(this.clickstreamMarkerFunc=protectMarkerFunc((0,clickstream_1.setupClickstreamTrace)(e))),(0,otel_1$1.isNode)()||!1===this.settings.instrumentRequests||(0,clickstream_1.instrumentRequests)(this.otelSettings),!(0,otel_1$1.isNode)()&&this.settings.instrumentAppLoad}registerAutoInstrumentations(e){var t,r;const n=this.settings.autoInstrumentations,i="object"==typeof n.documentLoad?n.documentLoad:void 0,o="object"==typeof n.userInteraction?n.userInteraction:void 0,s="object"==typeof n.fetch?n.fetch:void 0,a="object"==typeof n.xhr?n.xhr:void 0;null==e||e.registerInstrumentations({instrumentations:[n.documentLoad&&e.newDocumentLoadInstrumentation(i),n.userInteraction&&e.newUserInteractionInstrumentation(Object.assign(Object.assign({eventNames:["submit","click","keypress"]},o),{shouldPreventSpanCreation:(e,t,r)=>{var n;return r.setAttribute("target.id",t.id),null===(n=null==o?void 0:o.shouldPreventSpanCreation)||void 0===n?void 0:n.call(o,e,t,r)}})),n.fetch&&e.newFetchInstrumentation(s),n.xhr&&e.newXMLHttpRequestInstrumentation(Object.assign(Object.assign({},a),{ignoreUrls:!1!==n.ignoreObservabilityUrls?[...(null==a?void 0:a.ignoreUrls)||[],this.settings.url,null===(t=this.otelSettings.metrics)||void 0===t?void 0:t.url,null===(r=this.otelSettings.logs)||void 0===r?void 0:r.url].filter(e=>e):null==a?void 0:a.ignoreUrls}))].filter(e=>e)})}setFilterConfig(e){this.filters=null!=e?e:[]}get userJourneyMarker(){var e;return null!==(e=this.userJourneyMarkerFunc)&&void 0!==e?e:()=>{}}setUserJourneyMarker(e){this.userJourneyMarkerFunc=protectMarkerFunc(e)}get clickstreamMarker(){var e;return null!==(e=this.clickstreamMarkerFunc)&&void 0!==e?e:()=>{}}get startupTraceFinished(){var e;return null!==(e=this.startupTraceFinishedFunc)&&void 0!==e?e:()=>{}}waitForFinalExport(e){return Promise.race([new Promise(t=>e&&setTimeout(t,e)),Promise.allSettled((this.spanProcessors||[]).map(e=>e.forceFlush()))])}get currentTracingState(){return this.resolveCurrentTracingState()}set currentTracingState(e){this._currentTracingState=e}resolveCurrentTracingState(){if(this.settings.useOTELContextManager){const e=api_1.context.active(),t=null==e?void 0:e.getValue(Symbol.for("interopio.insights.currentTracingStateGetter"));return"function"==typeof t?t():this.settings.hybridContextMode?this._currentTracingState:null}return this._currentTracingState}withSequenceSpan(e,t,r,n){return __awaiter(this,void 0,void 0,function*(){return this.withSequenceSpanEx(e,e+".start",t,r,n)})}withSequenceSpanEx(e,t,r,n,i){return __awaiter(this,void 0,void 0,function*(){if("function"==typeof r&&(i=r,r=null),"function"==typeof n&&(i=n,n=null),!i)throw new Error("Callback must be a function, received "+typeof i);const o="string"==typeof t?t:e;let s=null;return this.read&&this.store&&(s=yield this.read(o)),s||(yield this.withSpan(o,r,null,n,e=>__awaiter(this,void 0,void 0,function*(){var t;s=e.getPropagationInfo(),s&&(yield null===(t=this.store)||void 0===t?void 0:t.call(this,o,s))}))),this.withSpan(e,r,s,n,e=>__awaiter(this,void 0,void 0,function*(){var t;const r=e.getPropagationInfo();return r&&"object"==typeof n&&"nested"===(null==n?void 0:n.structure)&&(yield null===(t=this.store)||void 0===t?void 0:t.call(this,o,r)),i(e)}))})}withSpan(e,t,r,n,i){var o,s,a,c,l,u,d,h,p,g,m,f,y,$,b,w,v;let S={};(0,utils_1.isFunctionType)(t)||(S=Object.assign({},t));const E=Object.assign(Object.assign({},otel_1$1.Container.errorless(this.settings.additionalAttributes)),S),C=Object.assign(Object.assign({},otel_1$1.Container.errorless(this.settings.additionalResourceAttributes)),E),_="t42.applogger.log"===(null===(s=null===(o=null==C?void 0:C.method)||void 0===o?void 0:o.toLowerCase)||void 0===s?void 0:s.call(o)),I="function"==typeof n?void 0:n,T=(!1!==this.settings.useDefaultFilters&&null!==(a=null==I?void 0:I.defaultFilters)&&void 0!==a?a:[]).map(t=>Object.assign(Object.assign({},t),{source:e})),A=this.filters.filter(e=>e.overrideDefaultFilters).concat(T,null!==(c=!1!==this.settings.useDefaultFilters?this.settings.defaultFilters:[])&&void 0!==c?c:[],this.filters.filter(e=>!e.overrideDefaultFilters)),D=(0,utils_1.findMatchingFilters)(A,C,e);let x=api_1.context.active(),R=null;!0!==(null==D?void 0:D.disableNesting)&&!0!==(null==I?void 0:I.disableNesting)&&(R||r&&"function"!=typeof r&&(R=otel_1$1.Traces.extractPropagationInfo(r)),R||"function"!=typeof(null==I?void 0:I.getPropagationInfo)||(R=null==I?void 0:I.getPropagationInfo(e,C)),R||(!otel_1$1.Traces.currentTracingState||!0===this.settings.useOTELContextManager&&!0!==this.settings.hybridContextMode?(this.settings.useOTELContextManager||!0===this.settings.hybridContextMode)&&(R=(null===(u=this.resolveCurrentTracingState())||void 0===u?void 0:u.getPropagationInfo())||null):(R=otel_1$1.Traces.currentTracingState.getPropagationInfo(),R||!0!==this.settings.hybridContextMode||(R=(null===(l=this.resolveCurrentTracingState())||void 0===l?void 0:l.getPropagationInfo())||null))),R||"function"!=typeof(null===(h=null===(d=this.settings)||void 0===d?void 0:d.defaults)||void 0===h?void 0:h.getPropagationInfo)||(R=null===(g=null===(p=this.settings)||void 0===p?void 0:p.defaults)||void 0===g?void 0:g.getPropagationInfo(e,C))),x=R?api_1.propagation.extract(api_1.context.active(),R):api_1.ROOT_CONTEXT;const O=this.resolveProperty("canBeRoot",D,I),P=this.started&&((null==R?void 0:R.forceTracing)||(0,utils_1.isSpanEnabled)(D,I,this.settings.defaults))&&(O||!!R),N=P&&(null!==(m=null==R?void 0:R.forceTracing)&&void 0!==m?m:this.resolveProperty("forceChildTracing",D,I)),k=this.resolveProperty("level",D,I),M=this.resolveProperty(P?"countMetric":"countMetricOnDisabledSpans",D,I),L=this.resolveProperty("maxAttributeDepth",D,I);M&&(null===(y=null===(f=this.traceMetric)||void 0===f?void 0:f.add)||void 0===y||y.call(f,1,Object.assign({source:e},(0,otel_1$1.flattenOtelAtributes)(E,L))));const F=this.resolveProperty(P?"resultMetric":"resultMetricOnDisabledSpans",D,I),j=this.resolveProperty(P?"durationMetric":"durationMetricOnDisabledSpans",D,I),U=!_&&this.resolveProperty(P?"log":"logOnDisabledSpans",D,I),B=this.resolveProperty("minDurationMs",D,I);let q;if("function"==typeof t)q=i=t;else if("function"==typeof r)q=i=r;else if("function"==typeof n)q=i=n;else{if("function"!=typeof i)throw new Error("Callback must be a function, received "+typeof i);q=i}const H=this.resolveProperty("disablePropagation",D,I),W=this.resolveProperty("addContextToTrace",D,I),G=(0,lodash_clonedeep_1.default)(null!==($=this.resolveProperty("otelSpanOptions",D,I))&&void 0!==$?$:{});if(G.attributes=null!==(b=G.attributes)&&void 0!==b?b:{},this.saveDataInAttributes({attributes:null!==(w=G.attributes)&&void 0!==w?w:{}},B,L,W,E),P){const t=api_1.trace.getTracer(e);let r=null;return x=x.setValue(Symbol.for(constants_1.Defaults.currentTracingStateGetterContextName),()=>r),t.startActiveSpan(e,G,x,t=>(r=new tracingState_1.TracingState(e,k,t,this.logger,constants_1.Defaults.TRACE_VERSION,H,N,L,x),this.saveDataInAttributes({otelSpan:t},B,L,W,E),this.handleCallbackAndResult(r,q,D,I,F,j,U,E,L)))}{let t=null;if(!this.resolveProperty("stopPropagationIfSpanIsDisabled",D,I))if(r){let e={};(0,utils_1.isFunctionType)(r)||(e=Object.assign({},r)),t=otel_1$1.Traces.extractPropagationInfo(e)}else otel_1$1.Traces.currentTracingState&&!0!==this.settings.useOTELContextManager?t=otel_1$1.Traces.currentTracingState.getPropagationInfo():this.settings.useOTELContextManager&&(R=(null===(v=this.resolveCurrentTracingState())||void 0===v?void 0:v.getPropagationInfo())||null);const n=new otel_1$1.NullTracingState(e,t,H);return x=x.setValue(Symbol.for(constants_1.Defaults.currentTracingStateGetterContextName),()=>n),api_1.context.with(x,()=>this.handleCallbackAndResult(n,q,D,I,F,j,U,E,L))}}saveDataInAttributes(e,t,r,n,i){t&&(0,utils_1.saveDataInAttribute)({insightsMinDurationMs:t},e,r),this.otelSettings.platformVersion&&(0,utils_1.saveDataInAttribute)({platformVersion:this.otelSettings.platformVersion},e,r),this.otelSettings.additionalAttributes&&(0,utils_1.saveDataInAttribute)(otel_1$1.Container.errorlessDefined(this.otelSettings.additionalAttributes,{}),e,r),this.settings.additionalAttributes&&(0,utils_1.saveDataInAttribute)(otel_1$1.Container.errorlessDefined(this.settings.additionalAttributes,{}),e,r),n&&(0,utils_1.saveDataInAttribute)(i,e,r)}handleCallbackAndResult(e,t,r,n,i,o,s,a,c){var l,u,d,h,p,g;const m=new Date;let f,y=null===(p=null!==(u=null!==(l=null==r?void 0:r.autoSetSuccessStatus)&&void 0!==l?l:null==n?void 0:n.autoSetSuccessStatus)&&void 0!==u?u:null===(h=null===(d=this.settings)||void 0===d?void 0:d.defaults)||void 0===h?void 0:h.autoSetSuccessStatus)||void 0===p||p;const $=null!==(g=otel_1$1.Traces.currentTracingState)&&void 0!==g?g:null;try{otel_1$1.Traces.currentTracingState=e;const r=t(e);return f=r&&"function"==typeof r.then&&"function"==typeof r.catch&&"function"==typeof r.finally,f?(y=!1,r.then(b.bind(this)).catch(w.bind(this)).finally(v.bind(this))):b.apply(this,[r])}catch(e){w.call(this,e)}finally{otel_1$1.Traces.currentTracingState=!0===this.settings.hybridContextMode?$:null,f||v.apply(this)}function b(t){var r;return y&&(null===(r=e.status)||void 0===r?void 0:r.code)===otel_1$1.SpanStatusCode.UNSET&&(e.status={code:otel_1$1.SpanStatusCode.OK}),t}function w(t){throw e.status={message:"string"==typeof t?t:null==t?void 0:t.message,code:otel_1$1.SpanStatusCode.ERROR},e.recordException(t),t}function v(){var t,r,n,l,u,d,h,p,g,f,y,$,b,w,v,S,E,C;if(i&&(null===(r=null===(t=this.traceMetricResult)||void 0===t?void 0:t.add)||void 0===r||r.call(t,1,Object.assign(Object.assign({source:e.source},(0,otel_1$1.flattenOtelAtributes)(a,c)),{code:e.status.code}))),o&&(null===(l=null===(n=this.traceMetricDuration)||void 0===n?void 0:n.record)||void 0===l||l.call(n,(new Date).getTime()-m.getTime(),Object.assign({source:e.source},(0,otel_1$1.flattenOtelAtributes)(a,c)))),e.endSpan(void 0,!0),s){let t="none";switch(e.level){case"OFF":t="none";break;case"LOWEST":case"DIAGNOSTIC":t="verbose";break;case"DEBUG":t="debug";break;case"INFO":t="info";break;case"WARN":t="warn";break;case"HIGHEST":t="error"}if("none"!==t){const r=null!==(h=null===(d=null===(u=null==e?void 0:e.span)||void 0===u?void 0:u.parentSpanContext)||void 0===d?void 0:d.spanId)&&void 0!==h?h:"0000000000000000",n=`${e.traceId}-${e.id}-${r}`,i=1e3*(null===(g=null===(p=e.span)||void 0===p?void 0:p.endTime)||void 0===g?void 0:g[0])+(null===(y=null===(f=e.span)||void 0===f?void 0:f.endTime)||void 0===y?void 0:y[1])/1e6-1e3*(null===(b=null===($=e.span)||void 0===$?void 0:$.startTime)||void 0===b?void 0:b[0])-(null===(v=null===(w=e.span)||void 0===w?void 0:w.startTime)||void 0===v?void 0:v[1])/1e6;this.traceLogger[t](`span ${n} ${e.source} ${null!==(E=null===(S=e.status)||void 0===S?void 0:S.code)&&void 0!==E?E:"unknown"} ${Math.floor(i)} ${JSON.stringify(null===(C=null==e?void 0:e.span)||void 0===C?void 0:C.attributes)}`)}}}}start(){return __awaiter(this,void 0,void 0,function*(){this.started=!0})}stop(){return __awaiter(this,void 0,void 0,function*(){this.started=!1})}resolveProperty(e,t,r,n){var i,o,s,a,c,l;return null!==(l=null!==(c=null!==(o=null!==(i=null==t?void 0:t[e])&&void 0!==i?i:null==r?void 0:r[e])&&void 0!==o?o:null===(a=null===(s=this.settings)||void 0===s?void 0:s.defaults)||void 0===a?void 0:a[e])&&void 0!==c?c:constants_1.Defaults[e])&&void 0!==l?l:n}}function protectMarkerFunc(e){return(t,r)=>{const n=["OFF","LOWEST","DIAGNOSTIC","DEBUG","INFO","WARN","HIGHEST"];if(void 0!==r&&("object"!=typeof r||Object.keys(r).some(e=>!n.find(t=>e===t.toUpperCase()))||Object.values(r).some(e=>"object"!=typeof e)))throw new Error('Data parameter must map from log level ("OFF", "LOWEST", "DIAGNOSTIC", "DEBUG", "INFO", "WARN", "HIGHEST") to object containing attributes to add to span.');return null==e?void 0:e(t,r)}}manager.TracesManager=TracesManager,Object.defineProperty(dist,"__esModule",{value:!0});var init_1=dist.init=void 0;const manager_1=manager,otel_1=requireDist$1();function init(){(0,otel_1.registerInsightsPlugin)("traces",()=>({newTracesManager:(e,t,r,n,i,o)=>new manager_1.TracesManager(t,e,r,n,i,o)}))}init_1=dist.init=init;var index=Object.freeze({__proto__:null,default:dist,get init(){return init_1}});export{ioConnectBrowserPlatformFactory as default};
60
60
  //# sourceMappingURL=browser.platform.es.js.map