@interopio/desktop 6.8.2 → 6.8.3

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.
@@ -1,2 +1,2 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):((e="undefined"!=typeof globalThis?globalThis:e||self).desktop=e.desktop||{},e.desktop.browser=e.desktop.browser||{},e.desktop.browser.min=t())}(this,(function(){"use strict";var e={STRING:1,NUMBER:2,TIMESTAMP:3,OBJECT:4};function t(t){return t.type===e.TIMESTAMP?"timestamp":t.type===e.NUMBER?"number":t.type===e.STRING?"string":t.type===e.OBJECT?"object":"unknown"}function i(e){return e.constructor===Date?"timestamp":"number"==typeof e?"number":"string"==typeof e?"string":"object"==typeof e?"object":"string"}function n(e){const n={},o=t(e);if("object"===o){const t=Object.keys(e.value).reduce(((t,n)=>{const r=i(e.value[n]);if("object"===r){const i=s(e.value[n]);t[n]={type:"object",description:"",context:{},composite:i}}else t[n]={type:r,description:"",context:{}};return t}),{});n.composite=t}return n.name=r(e.path.join("/")+"/"+e.name),n.type=o,n.description=e.description,n.context={},n}function s(e){return Object.keys(e).reduce(((t,n)=>{const r=i(e[n]);return t[n]="object"===r?{type:"object",description:"",context:{},composite:s(e[n])}:{type:r,description:"",context:{}},t}),{})}function r(e){return void 0!==e&&e.length>0&&"/"!==e[0]?"/"+e:e}function o(e){return"timestamp"===t(e)?Date.now():a(e.value)}function a(e){return"object"!=typeof e?e:Object.keys(e).reduce(((t,i)=>{const n=e[i];return"object"==typeof n&&n.constructor!==Date?t[i]=a(n):n.constructor===Date?t[i]=new Date(n).getTime():n.constructor===Boolean?t[i]=n.toString():t[i]=n,t}),{})}function c(e){return e.reduce(((e,t)=>e.concat(Array.isArray(t)?c(t):t)),[])}function d(e){const t=c(e.root.getAggregateState()),i=t.sort(((e,t)=>e.state?t.state?t.state-e.state:-1:1))[0];const n=function(e){let t="";return e.forEach(((e,i,n)=>{const s=e.path.join(".");i===n.length-1?t+=s+"."+e.name+": "+e.description:t+=s+"."+e.name+": "+e.description+","})),t.length>100?t.slice(0,100)+"...":t}(t);return{description:n,value:i.state}}var h=(e,t,i)=>{if(null===e||"object"!=typeof e)throw new Error("Missing definition");if(null===t||"object"!=typeof t)throw new Error("Missing parent");if(null===i||"object"!=typeof i)throw new Error("Missing transport")};class u{definition;system;transport;value;type;path=[];name;description;get repo(){return this.system?.repo}get id(){return`${this.system.path}/${name}`}constructor(e,t,i,n,s){this.definition=e,this.system=t,this.transport=i,this.value=n,this.type=s,h(e,t,i),this.path=t.path.slice(0),this.path.push(t.name),this.name=e.name,this.description=e.description,i.createMetric(this)}update(e){return this.value=e,this.transport.updateMetric(this)}}class l extends u{constructor(t,i,n,s){super(t,i,n,s,e.NUMBER)}incrementBy(e){this.update(this.value+e)}increment(){this.incrementBy(1)}decrement(){this.incrementBy(-1)}decrementBy(e){this.incrementBy(-1*e)}}class p extends u{constructor(t,i,n,s){super(t,i,n,s,e.OBJECT)}update(e){return this.mergeValues(e),this.transport.updateMetric(this)}mergeValues(e){return Object.keys(this.value).forEach((t=>{void 0!==e[t]&&(this.value[t]=e[t])}))}}class g extends u{constructor(t,i,n,s){super(t,i,n,s,e.STRING)}}class m extends u{constructor(t,i,n,s){super(t,i,n,s,e.TIMESTAMP)}now(){this.update(new Date)}}function f(t,i,n,s,r){if(!i)throw new Error("Repository is required");if(!n)throw new Error("Transport is required");const o=n,a=t,c=r||"",d=i,h=s,u=function e(t){if(!t||!t.parent)return[];const i=e(t.parent);return i.push(t.name),i}(s);let y={};const w=(b="/",((v=u)&&v.length>0?v.join(b):"")+t);var v,b;const _=i.root,I=[],C=[];function A(e,t,i,n){let s={name:""};s="string"==typeof e?{name:e}:e;const r=C.filter((e=>e.name===s.name));if(r.length>0){const e=r[0];if(e.type!==t)throw new Error(`A metric named ${s.name} is already defined with different type.`);return void 0!==i&&e.update(i).catch((()=>{})),e}const o=n(s);return C.push(o),o}const S={get name(){return a},get description(){return c},get repo(){return d},get parent(){return h},path:u,id:w,root:_,get subSystems(){return I},get metrics(){return C},subSystem:function(e,t){if(!e||0===e.length)throw new Error("name is required");const i=I.filter((t=>t.name===e));if(i.length>0)return i[0];const n=f(e,d,o,S,t);return I.push(n),n},getState:()=>y,setState:function(e,t){y={state:e,description:t},o.updateSystem(S,y)},stringMetric:function(t,i){return A(t,e.STRING,i,(e=>new g(e,S,o,i)))},timestampMetric:function(t,i){return A(t,e.TIMESTAMP,i,(e=>new m(e,S,o,i)))},objectMetric:function(t,i){return A(t,e.OBJECT,i,(e=>new p(e,S,o,i)))},numberMetric:function(t,i){return A(t,e.NUMBER,i,(e=>new l(e,S,o,i)))},getAggregateState:function(){const e=[];return Object.keys(y).length>0&&e.push({name:a,path:u,state:y.state,description:y.description}),I.forEach((t=>{const i=t.getAggregateState();i.length>0&&e.push(...i)})),e}};return o.createSystem(S),S}class y{root;constructor(e,t){t.init(this),this.root=f("",this,t),this.addSystemMetrics(this.root,e.clickStream||void 0===e.clickStream)}addSystemMetrics(e,t){if("undefined"!=typeof navigator&&e.stringMetric("UserAgent",navigator.userAgent),t&&"undefined"!=typeof document){const t=e.subSystem("ClickStream"),i=e=>{if(!e.target)return;const i=e.target,n=i?i.getAttribute("class")??"":"";t.objectMetric("LastBrowserEvent",{type:"click",timestamp:new Date,target:{className:n,id:i.id,type:"<"+i.tagName.toLowerCase()+">",href:i.href||""}})};t.objectMetric("Page",{title:document.title,page:window.location.href}),document.addEventListener?document.addEventListener("click",i):document.attachEvent("onclick",i)}e.stringMetric("StartTime",(new Date).toString());const i=e.stringMetric("StartURL",""),n=e.stringMetric("AppName","");if("undefined"!=typeof window){if(void 0!==window.location){const e=window.location.href;i.update(e)}void 0!==window.glue42gd&&n.update(window.glue42gd.appName)}}}class w{init(e){}createSystem(e){return Promise.resolve()}updateSystem(e,t){return Promise.resolve()}createMetric(e){return Promise.resolve()}updateMetric(e){return Promise.resolve()}}class v{api;lastCount=0;initialPublishTimeout=1e4;publishInterval=6e4;system;constructor(e,t,i){this.api=e,this.initialPublishTimeout=t??this.initialPublishTimeout,this.publishInterval=i??this.publishInterval,this.scheduleCollection(),this.system=this.api.subSystem("performance","Performance data published by the web application")}scheduleCollection(){setTimeout((()=>{this.collect(),setInterval((()=>{this.collect()}),this.publishInterval)}),this.initialPublishTimeout)}collect(){try{this.collectMemory(),this.collectEntries()}catch{}}collectMemory(){const e=window.performance.memory;this.system.stringMetric("memory",JSON.stringify({totalJSHeapSize:e.totalJSHeapSize,usedJSHeapSize:e.usedJSHeapSize}))}collectEntries(){const e=window.performance.getEntries();if(e.length<=this.lastCount)return;this.lastCount=e.length;const t=e.map((e=>e.toJSON()));this.system.stringMetric("entries",JSON.stringify(t))}}var b=e=>{let t;t=e.connection&&"object"==typeof e.connection?function(e,t){if(!e||"object"!=typeof e)throw new Error("Connection is required parameter");let i,s;const a=e=>{c(e.root)},c=e=>{h(e),e.metrics.forEach((e=>{u(e)})),e.subSystems.forEach((e=>{c(e)}))},h=async e=>{if(void 0===e.parent)return;await i;const t={type:"define",metrics:[{name:r(e.path.join("/")+"/"+e.name+"/State"),type:"object",composite:{Description:{type:"string",description:""},Value:{type:"number",description:""}},description:"System state",context:{}}]};s.send(t)},u=async e=>{const t=p(e);await i;const r={type:"define",metrics:[n(t)]};s.send(r),void 0!==t.value&&l(t)},l=e=>{if(g()){const t=o(e),i={type:"publish",values:[{name:r(e.path.join("/")+"/"+e.name),value:t,timestamp:Date.now()}]};return s.sendFireAndForget(i)}return Promise.resolve()},p=e=>{const t={...e};return"object"==typeof e.value&&null!==e.value&&(t.value={...e.value}),t},g=()=>{try{return(t.canUpdateMetric??(()=>!0))()}catch{return!0}};return{init:n=>{let r;i=new Promise((e=>{r=e})),s=e.domain("metrics"),s.onJoined((e=>{!e&&r&&(r(),r=void 0);const t={type:"define",metrics:[{name:"/State",type:"object",composite:{Description:{type:"string",description:""},Value:{type:"number",description:""}},description:"System state",context:{}}]};s.send(t),e&&a(n)})),s.join({system:t.system,service:t.service,instance:t.instance})},createSystem:h,updateSystem:async(t,n)=>{await i;const o={type:"publish",values:[{name:r(t.path.join("/")+"/"+t.name+"/State"),value:{Description:n.description,Value:n.state},timestamp:Date.now()}]};s.send(o);const a=d(t),c={type:"publish",peer_id:e.peerId,values:[{name:"/State",value:{Description:a.description,Value:a.value},timestamp:Date.now()}]};s.send(c)},createMetric:u,updateMetric:async e=>{const t=p(e);await i,l(t)}}}(e.connection,e):new w;let i=new y(e,t).root;e.disableAutoAppSystem||(i=i.subSystem("App"));const s=function(e){const t=e.subSystem("reporting"),i={name:"features"};let n;const s=(e,s,r)=>{if(void 0===e||""===e)throw new Error("name is mandatory");if(void 0===s||""===s)throw new Error("action is mandatory");if(void 0===r||""===r)throw new Error("payload is mandatory");n?n.update({name:e,action:s,payload:r}):n=t.objectMetric(i,{name:e,action:s,payload:r})};return e.featureMetric=s,e}(i);return function(e,t){if("undefined"==typeof window)return;const i=window?.glue42gd?.metrics?.pagePerformanceMetrics;i&&(t=i);t?.enabled&&new v(e,t.initialPublishTimeout,t.publishInterval)}(s,e.pagePerformanceMetrics),s};var _="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function I(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function C(e){if(e&&e.errorHandling&&"function"!=typeof e.errorHandling&&"log"!==e.errorHandling&&"silent"!==e.errorHandling&&"throw"!==e.errorHandling)throw new Error('Invalid options passed to createRegistry. Prop errorHandling should be ["log" | "silent" | "throw" | (err) => void], but '+typeof e.errorHandling+" was passed");var t=e&&"function"==typeof e.errorHandling&&e.errorHandling,i={};function n(i,n){var s=i instanceof Error?i:new Error(i);if(t)t(s);else{var r='[ERROR] callback-registry: User callback for key "'+n+'" failed: '+s.stack;if(e)switch(e.errorHandling){case"log":return console.error(r);case"silent":return;case"throw":throw new Error(r)}console.error(r)}}return{add:function(e,t,s){var r=i[e];return r||(r=[],i[e]=r),r.push(t),s&&setTimeout((function(){s.forEach((function(s){var r;if(null===(r=i[e])||void 0===r?void 0:r.includes(t))try{Array.isArray(s)?t.apply(void 0,s):t.apply(void 0,[s])}catch(t){n(t,e)}}))}),0),function(){var n=i[e];n&&(0===(n=n.reduce((function(e,i,n){return i===t&&e.length===n||e.push(i),e}),[])).length?delete i[e]:i[e]=n)}},execute:function(e){for(var t=[],s=1;s<arguments.length;s++)t[s-1]=arguments[s];var r=i[e];if(!r||0===r.length)return[];var o=[];return r.forEach((function(i){try{var s=i.apply(void 0,t);o.push(s)}catch(t){o.push(void 0),n(t,e)}})),o},clear:function(){i={}},clearKey:function(e){i[e]&&delete i[e]}}}C.default=C;var A=I(C);class S{gw;registry=A();client;constructor(e,t){this.gw=e.facade,this.gw.connect(((e,t)=>{this.messageHandler(t)})).then((e=>{this.client=e}))}get isObjectBasedTransport(){return!0}sendObject(e){return this.client?(this.client.send(e),Promise.resolve(void 0)):Promise.reject("not connected")}send(e){return Promise.reject("not supported")}onMessage(e){return this.registry.add("onMessage",e)}onConnectedChanged(e){return e(!0),()=>{}}close(){return Promise.resolve()}open(){return Promise.resolve()}name(){return"in-memory"}reconnect(){return Promise.resolve()}messageHandler(e){this.registry.execute("onMessage",e)}}class x{logger;worker;registry=A();constructor(e,t){this.logger=t,this.worker=new SharedWorker(e),this.worker.port.onmessage=e=>{this.messageHandler(e.data)}}get isObjectBasedTransport(){return!0}sendObject(e){return this.worker.port.postMessage(e),Promise.resolve()}send(e){return Promise.reject("not supported")}onMessage(e){return this.registry.add("onMessage",e)}onConnectedChanged(e){return e(!0),()=>{}}close(){return Promise.resolve()}open(){return Promise.resolve()}name(){return"shared-worker"}reconnect(){return Promise.resolve()}messageHandler(e){this.registry.execute("onMessage",e)}}let k=class e{static isNode(){if(void 0!==e._isNode)return e._isNode;if("undefined"!=typeof window)return e._isNode=!1,!1;try{e._isNode="[object process]"===Object.prototype.toString.call(global.process)}catch(t){e._isNode=!1}return e._isNode}static _isNode};class T{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)}}))}}const E={};function P(e){const t=E[e];if(t)return t;const i=[];function n(){return(new Date).getTime()}const s=n();let r,o;function a(e,t){const s=t??n();let r=0;i.length>0&&(r=s-i[i.length-1].time),i.push({name:e,time:s,diff:r})}a("start",s);const c={get startTime(){return s},get endTime(){return r},get period(){return o},stop:function(){return r=n(),a("end",r),o=r-s,o},mark:a,marks:i};return E[e]=c,c}const M=k.isNode()?null:window.WebSocket;class R{ws;logger;settings;startupTimer=P("connection");_running=!0;_registry=A();wsRequests=[];constructor(e,t){if(this.settings=e,this.logger=t,!this.settings.ws)throw new Error("ws is missing")}onMessage(e){return this._registry.add("onMessage",e)}send(e,t){return new Promise(((t,i)=>{this.waitForSocketConnection((()=>{try{this.ws?.send(e),t()}catch(e){i(e)}}),i)}))}open(){return this.logger.info("opening ws..."),this._running=!0,new Promise(((e,t)=>{this.waitForSocketConnection(e,t)}))}close(){return this._running=!1,this.ws&&this.ws.close(),Promise.resolve()}onConnectedChanged(e){return this._registry.add("onConnectedChanged",e)}name(){return this.settings.ws}reconnect(){this.ws?.close();const e=new T;return this.waitForSocketConnection((()=>{e.resolve()})),e.promise}waitForSocketConnection(e,t){t=t??(()=>{}),this._running?1!==this.ws?.readyState?(this.wsRequests.push({callback:e,failed:t}),this.wsRequests.length>1||this.openSocket()):e():t(`wait for socket on ${this.settings.ws} failed - socket closed by user`)}async openSocket(e,t){if(this.logger.info(`opening ws to ${this.settings.ws}, retryInterval: ${e}, retriesLeft: ${t}...`),this.startupTimer.mark("opening-socket"),void 0===e&&(e=this.settings.reconnectInterval),void 0===t&&(t=this.settings.reconnectAttempts),void 0!==t){if(0===t)return void this.notifyForSocketState(`wait for socket on ${this.settings.ws} failed - no more retries left`);this.logger.debug(`will retry ${t} more times (every ${e} ms)`)}try{await this.initiateSocket(),this.startupTimer.mark("socket-initiated"),this.notifyForSocketState()}catch{setTimeout((()=>{const i=void 0===t?void 0:t-1;this.openSocket(e,i)}),e)}}initiateSocket(){const e=new T;return this.logger.debug(`initiating ws to ${this.settings.ws}...`),this.ws=new M(this.settings.ws??""),this.ws.onerror=t=>{let i="";try{i=JSON.stringify(t)}catch(e){const n=new WeakSet,s=(e,t)=>{if("object"==typeof t&&null!==t){if(n.has(t))return;n.add(t)}return t};i=JSON.stringify(t,s)}this.logger.info(`ws error - reason: ${i}`),e.reject("error"),this.notifyStatusChanged(!1,i)},this.ws.onclose=t=>{this.logger.info(`ws closed - code: ${t?.code} reason: ${t?.reason}`),e.reject("closed"),this.notifyStatusChanged(!1)},this.ws.onopen=()=>{this.startupTimer.mark("ws-opened"),this.logger.info(`ws opened ${this.settings.identity?.application}`),e.resolve(),this.notifyStatusChanged(!0)},this.ws.onmessage=e=>{this._registry.execute("onMessage",e.data)},e.promise}notifyForSocketState(e){this.wsRequests.forEach((t=>{e?t.failed&&t.failed(e):t.callback()})),this.wsRequests=[]}notifyStatusChanged(e,t){this._registry.execute("onConnectedChanged",e,t)}}class N{specs;specsNames=[];messages={};isDone;subs={};subsRefCount={};connection;constructor(e){this.specs={};for(const t of e)this.specs[t.name]=t,this.specsNames.push(t.name)}init(e){this.connection=e;for(const t of this.specsNames)for(const i of this.specs[t].types){let t=this.subsRefCount[i];if(t||(t=0),t+=1,this.subsRefCount[i]=t,t>1)continue;const n=e.on(i,(e=>this.processMessage(i,e)));this.subs[i]=n}}processMessage(e,t){if(!this.isDone&&t)for(const i of this.specsNames)if(-1!==this.specs[i].types.indexOf(e)){const e=this.messages[i]||[];this.messages[i]=e,e.push(t)}}drain(e,t){t&&(this.messages[e]||[]).forEach(t),delete this.messages[e];for(const t of this.specs[e].types)this.subsRefCount[t]-=1,this.subsRefCount[t]<=0&&(this.connection?.off(this.subs[t]),delete this.subs[t],delete this.subsRefCount[t]);delete this.specs[e],this.specs.length||(this.isDone=!0)}}let j=(e=21)=>{let t="",i=e;for(;i--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return t};const W=(e,t,i)=>new Promise(((n,s)=>{const r=setTimeout((()=>{s(i||`Promise timeout hit: ${t}`)}),t);new Promise(e).then((e=>{clearTimeout(r),n(e)})).catch((e=>{clearTimeout(r),s(e)}))}));class O{settings;logger;identity;isPreferredActivated;_communicationId;publicWindowId;selfAssignedWindowId;iAmConnected=!1;parentReady=!1;rejected=!1;parentPingResolve;parentPingInterval;connectionResolve;extConnectionResolve;extConnectionReject;connectionReject;port;myClientId;children=[];extContentAvailable=!1;extContentConnecting=!1;extContentConnected=!1;parentWindowId;parentInExtMode=!1;webNamespace="g42_core_web";parent;parentType;parentPingTimeout=5e3;connectionRequestTimeout=7e3;defaultTargetString="*";registry=A();messages={connectionAccepted:{name:"connectionAccepted",handle:this.handleConnectionAccepted.bind(this)},connectionRejected:{name:"connectionRejected",handle:this.handleConnectionRejected.bind(this)},connectionRequest:{name:"connectionRequest",handle:this.handleConnectionRequest.bind(this)},parentReady:{name:"parentReady",handle:()=>{}},parentPing:{name:"parentPing",handle:this.handleParentPing.bind(this)},platformPing:{name:"platformPing",handle:this.handlePlatformPing.bind(this)},platformReady:{name:"platformReady",handle:this.handlePlatformReady.bind(this)},clientUnload:{name:"clientUnload",handle:this.handleClientUnload.bind(this)},manualUnload:{name:"manualUnload",handle:this.handleManualUnload.bind(this)},extConnectionResponse:{name:"extConnectionResponse",handle:this.handleExtConnectionResponse.bind(this)},extSetupRequest:{name:"extSetupRequest",handle:this.handleExtSetupRequest.bind(this)},gatewayDisconnect:{name:"gatewayDisconnect",handle:this.handleGatewayDisconnect.bind(this)},gatewayInternalConnect:{name:"gatewayInternalConnect",handle:this.handleGatewayInternalConnect.bind(this)}};constructor(e,t,i){this.settings=e,this.logger=t,this.identity=i,this.extContentAvailable=!!window.glue42ext,this.setUpMessageListener(),this.setUpUnload(),this.setupPlatformUnloadListener(),this.parentType=window.name.includes("#wsp")?"workspace":void 0}manualSetReadyState(){this.iAmConnected=!0,this.parentReady=!0}get transportWindowId(){return this.publicWindowId}get communicationId(){return this._communicationId}async sendObject(e){if(this.extContentConnected)return window.postMessage({glue42ExtOut:e},this.defaultTargetString);if(!this.port)throw new Error("Cannot send message, because the port was not opened yet");this.port.postMessage(e)}get isObjectBasedTransport(){return!0}onMessage(e){return this.registry.add("onMessage",e)}send(){return Promise.reject("not supported")}onConnectedChanged(e){return this.registry.add("onConnectedChanged",e)}async open(){this.logger.debug("opening a connection to the web platform gateway."),await this.connect(),this.notifyStatusChanged(!0)}close(){const e={glue42core:{type:this.messages.gatewayDisconnect.name,data:{clientId:this.myClientId,ownWindowId:this.identity?.windowId}}};return this.port?.postMessage(e),this.parentReady=!1,this.notifyStatusChanged(!1,"manual reconnection"),Promise.resolve()}name(){return"web-platform"}async reconnect(){return await this.close(),Promise.resolve()}initiateInternalConnection(){return new Promise(((e,t)=>{this.logger.debug("opening an internal web platform connection"),this.port=this.settings.port,this.iAmConnected?this.logger.warn("cannot open a new connection, because this client is currently connected"):(this.port.onmessage=i=>{if(this.iAmConnected&&!i.data?.glue42core)return void this.registry.execute("onMessage",i.data);const n=i.data?.glue42core;n&&(n.type===this.messages.gatewayInternalConnect.name&&n.success&&(this.publicWindowId=this.settings.windowId,this.identity&&this.publicWindowId&&(this.identity.windowId=this.publicWindowId,this.identity.instance=this.publicWindowId),e()),n.type===this.messages.gatewayInternalConnect.name&&n.error&&t(n.error))},this.port.postMessage({glue42core:{type:this.messages.gatewayInternalConnect.name}}))}))}initiateRemoteConnection(e){return W(((t,i)=>{this.connectionResolve=t,this.connectionReject=i,this.myClientId=this.myClientId??j(10);const n=this.getMyWindowId()||j(10),s={glue42core:{type:this.messages.connectionRequest.name,clientId:this.myClientId,clientType:"child",bridgeInstanceId:n,selfAssignedWindowId:this.selfAssignedWindowId}};if(this.logger.debug("sending connection request"),this.extContentConnecting)return s.glue42core.clientType="child",s.glue42core.bridgeInstanceId=this.myClientId,s.glue42core.parentWindowId=this.parentWindowId,window.postMessage(s,this.defaultTargetString);if(!e)throw new Error("Cannot send a connection request, because no glue target was specified!");e.postMessage(s,this.defaultTargetString)}),this.connectionRequestTimeout,"The connection to the target glue window timed out")}async isParentCheckSuccess(e){try{return await e,{success:!0}}catch(e){return{success:!1}}}setUpMessageListener(){this.settings.port?this.logger.debug("skipping generic message listener, because this is an internal client"):window.addEventListener("message",(e=>{const t=e.data?.glue42core;if(!t||this.rejected)return;const i=this.settings.allowedOrigins||[];if(i.length&&!i.includes(e.origin))return void this.logger.warn(`received a message from an origin which is not in the allowed list: ${e.origin}`);if(!this.checkMessageTypeValid(t.type))return void this.logger.error(`cannot handle the incoming glue42 core message, because the type is invalid: ${t.type}`);const n=t.type;this.logger.debug(`received valid glue42core message of type: ${n}`),this.messages[n].handle(e)}))}setUpUnload(){this.settings.port?this.logger.debug("skipping unload event listener, because this is an internal client"):window.addEventListener("beforeunload",(()=>{if(this.extContentConnected)return;const e={glue42core:{type:this.messages.clientUnload.name,data:{clientId:this.myClientId,ownWindowId:this.identity?.windowId}}};this.parent&&this.parent.postMessage(e,this.defaultTargetString),this.port?.postMessage(e)}))}handlePlatformReady(e){this.logger.debug("the web platform gave the ready signal"),this.parentReady=!0,this.parentPingResolve&&(this.parentPingResolve(),delete this.parentPingResolve),this.parentPingInterval&&(clearInterval(this.parentPingInterval),delete this.parentPingInterval),this.parent=e.source,this.parentType=window.name.includes("#wsp")?"workspace":"window"}handleConnectionAccepted(e){const t=e.data?.glue42core;return this.myClientId===t.clientId?this.handleAcceptanceOfMyRequest(t):this.handleAcceptanceOfGrandChildRequest(t,e)}handleAcceptanceOfMyRequest(e){if(this.logger.debug("handling a connection accepted signal targeted at me."),this.isPreferredActivated=e.isPreferredActivated,this.extContentConnecting)return this.processExtContentConnection(e);if(e.port){if(this.publicWindowId=this.getMyWindowId(),this.identity&&(this.identity.windowId=this.publicWindowId,this.identity.instance=this.identity.instance?this.identity.instance:this.publicWindowId||j(10)),this.identity&&e.appName&&(this.identity.application=e.appName,this.identity.applicationName=e.appName),this._communicationId=e.communicationId,this.port=e.port,this.port.onmessage=e=>this.registry.execute("onMessage",e.data),this.connectionResolve)return this.logger.debug("my connection is set up, calling the connection resolve."),this.connectionResolve(),void delete this.connectionResolve;this.logger.error("unable to call the connection resolve, because no connection promise was found")}else this.logger.error("cannot set up my connection, because I was not provided with a port")}processExtContentConnection(e){if(this.logger.debug("handling a connection accepted signal targeted at me for extension content connection."),this.extContentConnecting=!1,this.extContentConnected=!0,this.publicWindowId=this.parentWindowId||this.myClientId,this.extContentConnecting&&this.identity&&(this.identity.windowId=this.publicWindowId),this.identity&&e.appName&&(this.identity.application=e.appName,this.identity.applicationName=e.appName),window.addEventListener("message",(e=>{const t=e.data?.glue42ExtInc;if(!t)return;const i=this.settings.allowedOrigins||[];!i.length||i.includes(e.origin)?this.registry.execute("onMessage",t):this.logger.warn(`received a message from an origin which is not in the allowed list: ${e.origin}`)})),this.connectionResolve)return this.logger.debug("my connection is set up, calling the connection resolve."),this.connectionResolve(),void delete this.connectionResolve}handleAcceptanceOfGrandChildRequest(e,t){if(this.extContentConnecting||this.extContentConnected)return void this.logger.debug("cannot process acceptance of a grandchild, because I am connected to a content script");this.logger.debug(`handling a connection accepted signal targeted at a grandchild: ${e.clientId}`);const i=this.children.find((t=>t.grandChildId===e.clientId));i?(i.connected=!0,this.logger.debug(`the grandchild connection for ${e.clientId} is set up, forwarding the success message and the gateway port`),e.parentWindowId=this.publicWindowId,i.source.postMessage(t.data,i.origin,[e.port])):this.logger.error(`cannot handle connection accepted for grandchild: ${e.clientId}, because there is no grandchild with this id`)}handleConnectionRejected(){this.logger.debug("handling a connection rejection. Most likely the reason is that this window was not created by a glue API call"),this.connectionReject&&(this.connectionReject("The platform connection was rejected. Most likely because this window was not created by a glue API call"),delete this.connectionReject)}handleConnectionRequest(e){if(this.extContentConnecting)return void this.logger.debug("This connection request event is targeted at the extension content");const t=e.source,i=e.data.glue42core;return i.clientType&&"grandChild"===i.clientType?i.clientId?this.parent?(this.logger.debug(`handling a connection request for a grandchild: ${i.clientId}`),this.children.push({grandChildId:i.clientId,source:t,connected:!1,origin:e.origin}),this.logger.debug(`grandchild: ${i.clientId} is prepared, forwarding connection request to the platform`),void this.parent.postMessage(e.data,this.defaultTargetString)):this.rejectConnectionRequest(t,e.origin,"Cannot forward the connection request, because no direct connection to the platform was found"):this.rejectConnectionRequest(t,e.origin,"rejecting a connection request, because the source did not provide a valid id"):this.rejectConnectionRequest(t,e.origin,"rejecting a connection request, because the source was not opened by a glue API call")}handleParentPing(e){if(!this.parentReady)return void this.logger.debug("my parent is not ready, I am ignoring the parent ping");if(!this.iAmConnected)return void this.logger.debug("i am not fully connected yet, I am ignoring the parent ping");const t={glue42core:{type:this.messages.parentReady.name}};this.extContentConnected&&(t.glue42core.extMode={windowId:this.myClientId});const i=e.source;this.logger.debug("responding to a parent ping with a ready message"),i.postMessage(t,e.origin)}setupPlatformUnloadListener(){this.onMessage((e=>{"platformUnload"===e.type&&(this.logger.debug("detected a web platform unload"),this.parentReady=!1,this.notifyStatusChanged(!1,"Gateway unloaded"))}))}handleManualUnload(){const e={glue42core:{type:this.messages.clientUnload.name,data:{clientId:this.myClientId,ownWindowId:this.identity?.windowId}}};if(this.extContentConnected)return window.postMessage({glue42ExtOut:e},this.defaultTargetString);this.port?.postMessage(e)}handleClientUnload(e){const t=e.data.glue42core,i=t?.data.clientId;if(!i)return void this.logger.warn("cannot process grand child unload, because the provided id was not valid");this.children.find((e=>e.grandChildId===i))?(this.logger.debug(`handling grandchild unload for id: ${i}`),this.children=this.children.filter((e=>e.grandChildId!==i))):this.logger.warn("cannot process grand child unload, because this client is unaware of this grandchild")}handlePlatformPing(){}notifyStatusChanged(e,t){this.iAmConnected=e,this.registry.execute("onConnectedChanged",e,t)}checkMessageTypeValid(e){return"string"==typeof e&&!!this.messages[e]}rejectConnectionRequest(e,t,i){this.rejected=!0,this.logger.error(i);const n={glue42core:{type:this.messages.connectionRejected.name}};e.postMessage(n,t)}requestConnectionPermissionFromExt(){return this.waitForContentScript().then((()=>W(((e,t)=>{this.extConnectionResolve=e,this.extConnectionReject=t;this.logger.debug("permission request to the extension content script was sent"),window.postMessage({glue42core:{type:"extSetupRequest"}},this.defaultTargetString)}),this.parentPingTimeout,"Cannot initialize glue, because this app was not opened or created by a Glue Client and the request for extension connection timed out")))}handleExtConnectionResponse(e){const t=e.data?.glue42core;if(!t.approved)return this.extConnectionReject?this.extConnectionReject("Cannot initialize glue, because this app was not opened or created by a Glue Client and the request for extension connection was rejected"):void 0;this.extConnectionResolve&&(this.extConnectionResolve(),delete this.extConnectionResolve),this.extContentConnecting=!0,this.parentType="extension",this.logger.debug("The extension connection was approved, proceeding.")}handleExtSetupRequest(){}handleGatewayDisconnect(){}handleGatewayInternalConnect(){}waitForContentScript(){return!!window.glue42ext?.content?Promise.resolve():W((e=>{window.addEventListener("Glue42EXTReady",(()=>{e()}))}),this.connectionRequestTimeout,"The content script was available, but was never heard to be ready")}async connect(){if(this.settings.port)return await this.initiateInternalConnection(),void this.logger.debug("internal web platform connection completed");this.logger.debug("opening a client web platform connection"),await this.findParent(),await this.initiateRemoteConnection(this.parent),this.logger.debug("the client is connected")}async findParent(){const e="Cannot initiate glue, because this window was not opened or created by a glue client",t=this.getPossibleParentsInWindow(window),i=this.getPossibleParentsOutsideWindow(window.top?.opener,window.top),n=new Set([...t,...i]);if(!n.size&&!this.extContentAvailable)throw new Error(e);if(!n.size&&this.extContentAvailable)return void await this.requestConnectionPermissionFromExt();if((await this.isParentCheckSuccess(this.confirmParent(Array.from(n)))).success)this.logger.debug("The default parent was found!");else{if(!this.extContentAvailable)throw new Error(e);await this.requestConnectionPermissionFromExt()}}getPossibleParentsInWindow(e){return e&&e!==e.top?[e.parent,...this.getPossibleParentsInWindow(e.parent)]:[]}getPossibleParentsOutsideWindow(e,t){return e&&t&&e!==t?[e,...this.getPossibleParentsInWindow(e),...this.getPossibleParentsOutsideWindow(e.opener,e)]:[]}confirmParent(e){const t=W((t=>{this.parentPingResolve=t;const i={glue42core:{type:this.messages.platformPing.name}};this.parentPingInterval=setInterval((()=>{e.forEach((e=>{e.postMessage(i,this.defaultTargetString)}))}),1e3)}),this.parentPingTimeout,"Cannot initiate glue, because this window was not opened or created by a glue client");return t.catch((()=>{this.parentPingInterval&&(clearInterval(this.parentPingInterval),delete this.parentPingInterval)})),t}getMyWindowId(){return"workspace"===this.parentType?window.name.substring(0,window.name.indexOf("#wsp")):window===window.top?window.name?.includes("g42")?window.name:(this.selfAssignedWindowId=this.selfAssignedWindowId||`g42-${j(10)}`,this.selfAssignedWindowId):void 0}}class F{minSequenceInterval;queue=[];isExecutingQueue=!1;constructor(e=0){this.minSequenceInterval=e}enqueue(e){return new Promise(((t,i)=>{this.queue.push({action:e,resolve:t,reject:i}),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)))}}function D(e,t,i,n,s){null==e&&(e="global"),n=n??["success"],s=s??["error"];let r,o="global"===e,a=!1,c=!1;const d=A();t.disconnected((function(){c=!1,i.debug("connection is down"),o=!1,a=!0,d.execute("onLeft",{disconnected:!0})})),t.loggedIn((function(){c=!0,a&&(i.debug("connection is now up - trying to reconnect..."),u(r))})),t.on("success",(e=>g(e))),t.on("error",(e=>p(e))),t.on("result",(e=>g(e))),n&&n.forEach((e=>{t.on(e,(e=>g(e)))})),s&&s.forEach((e=>{t.on(e,(e=>p(e)))}));const h={};function u(t){return r=t,new Promise(((n,s)=>{if(o)return void n({});let r;if("global"===e)r=c?Promise.resolve({}):Promise.reject("not connected to gateway");else{i.debug(`joining domain ${e}`);r=y({type:"join",destination:e,domain:"global",options:t})}r.then((()=>{!function(){i.debug("did join "+e),o=!0;const t=a;a=!1,d.execute("onJoined",t)}(),n({})})).catch((t=>{i.debug("error joining "+e+" domain: "+JSON.stringify(t)),s(t)}))}))}function l(e){return o&&e(!1),d.add("onJoined",e)}function p(t){if(e!==t.domain)return;const i=t.request_id;if(!i)return;const n=h[i];n&&n.error(t)}function g(t){if(t.domain!==e)return;const i=t.request_id;if(!i)return;const n=h[i];n&&n.success(t)}function m(){return j(10)}let f=[];function y(n,s,r){if(n.type&&-1===["hello","join"].indexOf(n.type)&&!o){console.warn(`trying to send a message (${n.domain} ${n.type}) but not connected, will queue`);const e=new T;if(f.push({msg:n,tag:s,options:r,pw:e}),1===f.length){const e=l((()=>{i.info(`joined - will now send queued messages (${f.length} -> [${f.map((e=>e.msg.type))}])`),f.forEach((e=>{y(e.msg,e.tag,e.options).then((t=>e.pw.resolve(t))).catch((t=>e.pw.reject(t)))})),f=[],e()}))}return e.promise}r=r??{},n.request_id=n.request_id??m(),n.domain=n.domain??e,r.skipPeerId||(n.peer_id=t.peerId);const a=n.request_id;return new Promise(((e,o)=>{h[a]={success:t=>{delete h[a],t._tag=s,e(t)},error:e=>{i.warn(`Gateway error - ${JSON.stringify(e)}`),delete h[a],e._tag=s,o(e)}},t.send(n,r).catch((e=>{h[a].error({err:e})}))}))}return{join:u,leave:function(){return"global"===e?Promise.resolve():(i.debug("stopping session "+e+"..."),a=!1,y({type:"leave",destination:e,domain:"global"}).then((()=>{o=!1,d.execute("onLeft")})).catch((()=>{o=!1,d.execute("onLeft")})))},onJoined:l,onLeft:function(e){return o||e(),d.add("onLeft",e)},send:y,sendFireAndForget:function(i){return i.request_id=i.request_id?i.request_id:m(),i.domain=i.domain??e,i.peer_id=t.peerId,t.send(i)},on:(n,s)=>{t.on(n,(t=>{if(t.domain===e)try{s(t)}catch(e){i.error(`Callback failed: ${e} \n ${e.stack} \n msg was: ${JSON.stringify(t)}`,e)}}))},loggedIn:e=>t.loggedIn(e),connected:e=>t.connected(e),disconnected:e=>t.disconnected(e),get peerId(){return t.peerId},get domain(){return e}}}class L{settings;logger;protocolVersion=3;peerId;token;info;resolvedIdentity;availableDomains;gatewayToken;replayer;messageHandlers={};ids=1;registry=A();_connected=!1;isTrace=!1;transport;_defaultTransport;_defaultAuth;_targetTransport;_targetAuth;_swapTransport=!1;_switchInProgress=!1;_transportSubscriptions=[];datePrefix="#T42_DATE#";datePrefixLen=this.datePrefix.length;dateMinLen=this.datePrefixLen+1;datePrefixFirstChar=this.datePrefix[0];_sequelizer=new F;_isLoggedIn=!1;shouldTryLogin=!0;pingTimer;sessions=[];globalDomain;initialLogin=!0;initialLoginAttempts=3;loginConfig;constructor(e,t){if(this.settings=e,this.logger=t,(e=e||{}).reconnectAttempts=e.reconnectAttempts??10,e.reconnectInterval=e.reconnectInterval??1e3,e.inproc)this.transport=new S(e.inproc,t.subLogger("inMemory"));else if(e.sharedWorker)this.transport=new x(e.sharedWorker,t.subLogger("shared-worker"));else if(e.webPlatform)this.transport=new O(e.webPlatform,t.subLogger("web-platform"),e.identity);else{if(void 0===e.ws)throw new Error("No connection information specified");this.transport=new R(e,t.subLogger("ws"))}this.isTrace=t.canPublish("trace"),t.debug(`starting with ${this.transport.name()} transport`);const i=this.transport.onConnectedChanged(this.handleConnectionChanged.bind(this)),n=this.transport.onMessage(this.handleTransportMessage.bind(this));this._transportSubscriptions.push(i),this._transportSubscriptions.push(n),this._defaultTransport=this.transport,this.ping()}async switchTransport(e){return this._sequelizer.enqueue((async()=>{if(!e||"object"!=typeof e)throw new Error("Cannot switch transports, because the settings are missing or invalid.");if(void 0===e.type)throw new Error("Cannot switch the transport, because the type is not defined");this.logger.trace(`Starting transport switch with settings: ${JSON.stringify(e)}`);const t="secondary"===e.type?this.getNewSecondaryTransport(e):this._defaultTransport;this._targetTransport=t,this._targetAuth="secondary"===e.type?this.getNewSecondaryAuth(e):this._defaultAuth;const i=this.verifyConnection();this._swapTransport=!0,this._switchInProgress=!0,this.logger.trace("The new transport has been set, closing the current transport"),await this.transport.close();try{await i;const e=this.transport===t;return this.logger.info(`The reconnection after the switch was completed. Was the switch a success: ${e}`),this._switchInProgress=!1,{success:e}}catch(e){return this.logger.info("The reconnection after the switch timed out, reverting back to the default transport."),this.switchTransport({type:"default"}),this._switchInProgress=!1,{success:!1}}}))}onLibReAnnounced(e){return this.registry.add("libReAnnounced",e)}setLibReAnnounced(e){this.registry.execute("libReAnnounced",e)}send(e,t){if(this.transport.sendObject&&this.transport.isObjectBasedTransport){const i=this.createObjectMessage(e);return this.isTrace&&this.logger.trace(`>> ${JSON.stringify(i)}`),this.transport.sendObject(i,t)}{const i=this.createStringMessage(e);return this.isTrace&&this.logger.trace(`>> ${i}`),this.transport.send(i,t)}}on(e,t){e=e.toLowerCase(),void 0===this.messageHandlers[e]&&(this.messageHandlers[e]={});const i=this.ids++;return this.messageHandlers[e][i]=t,{type:e,id:i}}off(e){delete this.messageHandlers[e.type.toLowerCase()][e.id]}get isConnected(){return this._isLoggedIn}connected(e){return this.loggedIn((()=>{const t=this.transport.name();e(t)}))}disconnected(e){return this.registry.add("disconnected",e)}async login(e,t){if(this._defaultAuth||(this._defaultAuth=e),this._swapTransport){this.logger.trace("Detected a transport swap, swapping transports");e=this.transportSwap()??e}this.logger.trace(`Starting login for transport: ${this.transport.name()} and auth ${JSON.stringify(e)}`);try{await this.transport.open(),this.logger.trace(`Transport: ${this.transport.name()} opened, logging in`),P("connection").mark("transport-opened");const i=await this.loginCore(e,t);return this.logger.trace(`Logged in with identity: ${JSON.stringify(i)}`),P("connection").mark("protocol-logged-in"),i}catch(e){throw this._switchInProgress&&(this.logger.trace("An error while logging in after a transport swap, preparing a default swap."),this.prepareDefaultSwap()),new Error(e)}}async logout(){await this.logoutCore(),await this.transport.close()}loggedIn(e){return this._isLoggedIn&&e(),this.registry.add("onLoggedIn",e)}domain(e,t,i){let n=this.sessions.find((t=>t.domain===e));return n||(n=D(e,this,this.logger.subLogger(`domain=${e}`),t,i),this.sessions.push(n)),n}authToken(){return this.globalDomain?this.globalDomain.send({domain:"global",type:"create-token"}).then((e=>e.token)):Promise.reject(new Error("no global domain session"))}reconnect(){return this.transport.reconnect()}setLoggedIn(e){this._isLoggedIn=e,this._isLoggedIn&&this.registry.execute("onLoggedIn")}distributeMessage(e,t){const i=this.messageHandlers[t.toLowerCase()];void 0!==i&&Object.keys(i).forEach((t=>{const n=i[t];if(void 0!==n)try{n(e)}catch(e){try{this.logger.error(`Message handler failed with ${e.stack}`,e)}catch(t){console.log("Message handler failed",e)}}}))}handleConnectionChanged(e){this._connected!==e&&(this._connected=e,e?(this.settings?.replaySpecs?.length&&(this.replayer=new N(this.settings.replaySpecs),this.replayer.init(this)),this.registry.execute("connected")):(this.handleDisconnected(),this.registry.execute("disconnected")))}handleDisconnected(){this.setLoggedIn(!1);if(this.shouldTryLogin&&this.initialLogin){if(this.initialLoginAttempts<=0)return;this.initialLoginAttempts--}if(this.logger.debug("disconnected - will try new login?"+this.shouldTryLogin),this.shouldTryLogin){if(!this.loginConfig)throw new Error("no login info");this.login(this.loginConfig,!0).catch((()=>{setTimeout(this.handleDisconnected.bind(this),this.settings.reconnectInterval||1e3)}))}}handleTransportMessage(e){let t;t="string"==typeof e?this.processStringMessage(e):this.processObjectMessage(e),this.isTrace&&this.logger.trace(`<< ${JSON.stringify(t)}`),this.distributeMessage(t.msg,t.msgType)}verifyConnection(){return W((e=>{let t;const i=((e,t)=>{let i=e;return()=>{i--,0===i&&t()}})(2,(()=>{t&&t(),e()}));t=this.onLibReAnnounced((e=>"interop"===e.name||"contexts"===e.name?i():void 0))}),1e4,"Transport switch timed out waiting for all libraries to be re-announced")}getNewSecondaryTransport(e){if(!e.transportConfig?.url)throw new Error("Missing secondary transport URL.");return new R(Object.assign({},this.settings,{ws:e.transportConfig.url,reconnectAttempts:1}),this.logger.subLogger("ws-secondary"))}getNewSecondaryAuth(e){if(!e.transportConfig?.auth)throw new Error("Missing secondary transport auth information.");return e.transportConfig.auth}transportSwap(){if(this._swapTransport=!1,!this._targetTransport||!this._targetAuth)return void this.logger.warn(`Error while switching transports - either the target transport or auth is not defined: transport defined -> ${!!this._defaultTransport}, auth defined -> ${!!this._targetAuth}. Staying on the current one.`);this._transportSubscriptions.forEach((e=>e())),this._transportSubscriptions=[],this.transport=this._targetTransport;const e=this.transport.onConnectedChanged(this.handleConnectionChanged.bind(this)),t=this.transport.onMessage(this.handleTransportMessage.bind(this));return this._transportSubscriptions.push(e),this._transportSubscriptions.push(t),this._targetAuth}prepareDefaultSwap(){this._transportSubscriptions.forEach((e=>e())),this._transportSubscriptions=[],this.transport.close().catch((e=>this.logger.warn(`Error closing the ${this.transport.name()} transport after a failed connection attempt: ${JSON.stringify(e)}`))),this._targetTransport=this._defaultTransport,this._targetAuth=this._defaultAuth,this._swapTransport=!0}processStringMessage(e){const t=JSON.parse(e,((e,t)=>{if("string"!=typeof t)return t;if(t.length<this.dateMinLen)return t;if(!t.startsWith(this.datePrefixFirstChar))return t;if(t.substring(0,this.datePrefixLen)!==this.datePrefix)return t;try{const e=parseInt(t.substring(this.datePrefixLen,t.length),10);return isNaN(e)?t:new Date(e)}catch(e){return t}}));return{msg:t,msgType:t.type}}createStringMessage(e){const t=Date.prototype.toJSON;try{const t=this.datePrefix;Date.prototype.toJSON=function(){return t+this.getTime()};return JSON.stringify(e)}finally{Date.prototype.toJSON=t}}processObjectMessage(e){if(!e.type)throw new Error("Object should have type property");return{msg:e,msgType:e.type}}createObjectMessage(e){return e}async loginCore(e,t){this.logger.info("logging in..."),this.loginConfig=e,this.loginConfig||(this.loginConfig={username:"",password:""}),this.shouldTryLogin=!0;const i=await this.setupAuthConfig(e,t),n={type:"hello",identity:this.settings.identity,authentication:i};e.sessionId&&(n.request_id=e.sessionId),this.globalDomain=D("global",this,this.logger.subLogger("global-domain"),["welcome","token","authentication-request"]);const s={skipPeerId:!0};this.initialLogin&&(s.retryInterval=this.settings.reconnectInterval,s.maxRetries=this.settings.reconnectAttempts);try{const t=await this.tryAuthenticate(this.globalDomain,n,s,e);return this.initialLogin=!1,this.logger.info("login successful with peerId "+t.peer_id),this.peerId=t.peer_id,this.resolvedIdentity=t.resolved_identity,this.availableDomains=t.available_domains,t.options&&(this.token=t.options.access_token,this.info=t.options.info),this.setLoggedIn(!0),t.resolved_identity}catch(e){throw this.logger.error("error sending hello message - "+(e.message||e.msg||e.reason||e),e),e}finally{e?.flowCallback&&e.sessionId&&e.flowCallback(e.sessionId,null)}}async tryAuthenticate(e,t,i,n){let s;for(;;){const r=await e.send(t,void 0,i);if("authentication-request"!==r.type){if("welcome"===r.type){s=r;break}throw"error"===r.type?new Error("Authentication failed: "+r.reason):new Error("Unexpected message type during authentication: "+r.type)}{const e=Buffer.from(r.authentication.token,"base64");n.flowCallback&&n.sessionId&&(t.authentication.token=(await n.flowCallback(n.sessionId,e)).data.toString("base64")),t.request_id=n.sessionId}}return s}async setupAuthConfig(e,t){const i={};if(this.gatewayToken=e.gatewayToken,e.gatewayToken){if(t)try{e.gatewayToken=await this.getNewGWToken()}catch(e){this.logger.warn(`failed to get GW token when reconnecting ${e?.message||e}`)}i.method="gateway-token",i.token=e.gatewayToken,this.gatewayToken=e.gatewayToken}else if("sspi"===e.flowName){if(i.provider="win",i.method="access-token",!e.flowCallback||!e.sessionId)throw new Error("Invalid SSPI config");i.token=(await e.flowCallback(e.sessionId,null)).data.toString("base64")}else if(e.token)i.method="access-token",i.token=e.token;else if(e.username)i.method="secret",i.login=e.username,i.secret=e.password;else{if(!e.provider)throw new Error("invalid auth message"+JSON.stringify(e));i.provider=e.provider,i.providerContext=e.providerContext}return i}async logoutCore(){this.logger.debug("logging out..."),this.shouldTryLogin=!1,this.pingTimer&&clearTimeout(this.pingTimer);const e=this.sessions.map((e=>{e.leave()}));await Promise.all(e)}getNewGWToken(){if("undefined"!=typeof window){const e=window.glue42gd;if(e)return e.getGWToken()}return Promise.reject(new Error("not running in GD"))}ping(){this.shouldTryLogin&&(this._isLoggedIn&&this.send({type:"ping"}),this.pingTimer=setTimeout((()=>{this.ping()}),3e4))}}const $=["trace","debug","info","warn","error","off"];let G=class e{name;parent;static Interop;static InteropMethodName="T42.AppLogger.Log";static Instance;path;subLoggers=[];_consoleLevel;_publishLevel;loggerFullName;includeTimeAndLevel;logFn=console;customLogFn=!1;constructor(e,t,i){this.name=e,this.parent=t,this.name=e,this.path=t?`${t.path}.${e}`:e,this.loggerFullName=`[${this.path}]`,this.includeTimeAndLevel=!i,i&&(this.logFn=i,this.customLogFn=!0)}subLogger(t){const i=this.subLoggers.filter((e=>e.name===t))[0];if(void 0!==i)return i;Object.keys(this).forEach((e=>{if(e===t)throw new Error("This sub logger name is not allowed.")}));const n=new e(t,this,this.customLogFn?this.logFn:void 0);return this.subLoggers.push(n),n}publishLevel(e){return e&&(this._publishLevel=e),this._publishLevel||this.parent?.publishLevel()}consoleLevel(e){return e&&(this._consoleLevel=e),this._consoleLevel||this.parent?.consoleLevel()}log(e,t,i){this.publishMessage(t||"info",e,i)}trace(e){this.log(e,"trace")}debug(e){this.log(e,"debug")}info(e){this.log(e,"info")}warn(e){this.log(e,"warn")}error(e,t){this.log(e,"error")}canPublish(e,t){return $.indexOf(e)>=$.indexOf(t||this.consoleLevel()||"trace")}publishMessage(t,i,n){const s=this.loggerFullName;if("error"===t&&!n){const e=new Error;e.stack&&(i=i+"\n"+e.stack.split("\n").slice(3).join("\n"))}if(this.canPublish(t,this.publishLevel())){const n=e.Interop;if(n)try{n.methods({name:e.InteropMethodName}).length>0&&n.invoke(e.InteropMethodName,{msg:`${i}`,logger:s,level:t})}catch{}}if(this.canPublish(t)){let e="";if(this.includeTimeAndLevel){const i=new Date;e=`[${`${i.getHours()}:${i.getMinutes()}:${i.getSeconds()}:${i.getMilliseconds()}`}] [${t}] `}const r=`${e}${s}: ${i}`;switch(t){case"trace":this.logFn.debug(r);break;case"debug":this.logFn.debug?this.logFn.debug(r):this.logFn.log(r);break;case"info":this.logFn.info(r);break;case"warn":this.logFn.warn(r);break;case"error":this.logFn.error(r,n)}}}};const B="create-context",H="created",U="destroyed",q="context-created",J="context-added",V="subscribe-context",z="subscribed-context",K="unsubscribe-context",Q="destroy-context",Z="context-destroyed",X="update-context",Y="context-updated",ee="joined",te={get name(){return"context"},get types(){return[B,H,U,q,J,V,z,K,Q,Z,X,Y,ee]}};var ie="6.4.2";class ne{name;contextId;context;isAnnounced;joinedActivity;updateCallbacks={};activityId;sentExplicitSubscription;hasReceivedSnapshot;constructor(e,t,i,n){this.contextId=e,this.name=t,this.isAnnounced=i,this.activityId=n,this.context={}}hasCallbacks(){return Object.keys(this.updateCallbacks).length>0}getState(){return this.isAnnounced&&this.hasCallbacks()?3:this.isAnnounced?2:this.hasCallbacks()?1:0}}var se={exports:{}};!function(e,t){var i="__lodash_hash_undefined__",n=9007199254740991,s="[object Arguments]",r="[object Boolean]",o="[object Date]",a="[object Function]",c="[object GeneratorFunction]",d="[object Map]",h="[object Number]",u="[object Object]",l="[object Promise]",p="[object RegExp]",g="[object Set]",m="[object String]",f="[object Symbol]",y="[object WeakMap]",w="[object ArrayBuffer]",v="[object DataView]",b="[object Float32Array]",I="[object Float64Array]",C="[object Int8Array]",A="[object Int16Array]",S="[object Int32Array]",x="[object Uint8Array]",k="[object Uint8ClampedArray]",T="[object Uint16Array]",E="[object Uint32Array]",P=/\w*$/,M=/^\[object .+?Constructor\]$/,R=/^(?:0|[1-9]\d*)$/,N={};N[s]=N["[object Array]"]=N[w]=N[v]=N[r]=N[o]=N[b]=N[I]=N[C]=N[A]=N[S]=N[d]=N[h]=N[u]=N[p]=N[g]=N[m]=N[f]=N[x]=N[k]=N[T]=N[E]=!0,N["[object Error]"]=N[a]=N[y]=!1;var j="object"==typeof _&&_&&_.Object===Object&&_,W="object"==typeof self&&self&&self.Object===Object&&self,O=j||W||Function("return this")(),F=t&&!t.nodeType&&t,D=F&&e&&!e.nodeType&&e,L=D&&D.exports===F;function $(e,t){return e.set(t[0],t[1]),e}function G(e,t){return e.add(t),e}function B(e,t,i,n){var s=-1,r=e?e.length:0;for(n&&r&&(i=e[++s]);++s<r;)i=t(i,e[s],s,e);return i}function H(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(e){}return t}function U(e){var t=-1,i=Array(e.size);return e.forEach((function(e,n){i[++t]=[n,e]})),i}function q(e,t){return function(i){return e(t(i))}}function J(e){var t=-1,i=Array(e.size);return e.forEach((function(e){i[++t]=e})),i}var V,z=Array.prototype,K=Function.prototype,Q=Object.prototype,Z=O["__core-js_shared__"],X=(V=/[^.]+$/.exec(Z&&Z.keys&&Z.keys.IE_PROTO||""))?"Symbol(src)_1."+V:"",Y=K.toString,ee=Q.hasOwnProperty,te=Q.toString,ie=RegExp("^"+Y.call(ee).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),ne=L?O.Buffer:void 0,se=O.Symbol,re=O.Uint8Array,oe=q(Object.getPrototypeOf,Object),ae=Object.create,ce=Q.propertyIsEnumerable,de=z.splice,he=Object.getOwnPropertySymbols,ue=ne?ne.isBuffer:void 0,le=q(Object.keys,Object),pe=De(O,"DataView"),ge=De(O,"Map"),me=De(O,"Promise"),fe=De(O,"Set"),ye=De(O,"WeakMap"),we=De(Object,"create"),ve=He(pe),be=He(ge),_e=He(me),Ie=He(fe),Ce=He(ye),Ae=se?se.prototype:void 0,Se=Ae?Ae.valueOf:void 0;function xe(e){var t=-1,i=e?e.length:0;for(this.clear();++t<i;){var n=e[t];this.set(n[0],n[1])}}function ke(e){var t=-1,i=e?e.length:0;for(this.clear();++t<i;){var n=e[t];this.set(n[0],n[1])}}function Te(e){var t=-1,i=e?e.length:0;for(this.clear();++t<i;){var n=e[t];this.set(n[0],n[1])}}function Ee(e){this.__data__=new ke(e)}function Pe(e,t){var i=qe(e)||function(e){return function(e){return function(e){return!!e&&"object"==typeof e}(e)&&Je(e)}(e)&&ee.call(e,"callee")&&(!ce.call(e,"callee")||te.call(e)==s)}(e)?function(e,t){for(var i=-1,n=Array(e);++i<e;)n[i]=t(i);return n}(e.length,String):[],n=i.length,r=!!n;for(var o in e)!t&&!ee.call(e,o)||r&&("length"==o||Ge(o,n))||i.push(o);return i}function Me(e,t,i){var n=e[t];ee.call(e,t)&&Ue(n,i)&&(void 0!==i||t in e)||(e[t]=i)}function Re(e,t){for(var i=e.length;i--;)if(Ue(e[i][0],t))return i;return-1}function Ne(e,t,i,n,l,y,_){var M;if(n&&(M=y?n(e,l,y,_):n(e)),void 0!==M)return M;if(!Ke(e))return e;var R=qe(e);if(R){if(M=function(e){var t=e.length,i=e.constructor(t);t&&"string"==typeof e[0]&&ee.call(e,"index")&&(i.index=e.index,i.input=e.input);return i}(e),!t)return function(e,t){var i=-1,n=e.length;t||(t=Array(n));for(;++i<n;)t[i]=e[i];return t}(e,M)}else{var j=$e(e),W=j==a||j==c;if(Ve(e))return function(e,t){if(t)return e.slice();var i=new e.constructor(e.length);return e.copy(i),i}(e,t);if(j==u||j==s||W&&!y){if(H(e))return y?e:{};if(M=function(e){return"function"!=typeof e.constructor||Be(e)?{}:(t=oe(e),Ke(t)?ae(t):{});var t}(W?{}:e),!t)return function(e,t){return Oe(e,Le(e),t)}(e,function(e,t){return e&&Oe(t,Qe(t),e)}(M,e))}else{if(!N[j])return y?e:{};M=function(e,t,i,n){var s=e.constructor;switch(t){case w:return We(e);case r:case o:return new s(+e);case v:return function(e,t){var i=t?We(e.buffer):e.buffer;return new e.constructor(i,e.byteOffset,e.byteLength)}(e,n);case b:case I:case C:case A:case S:case x:case k:case T:case E:return function(e,t){var i=t?We(e.buffer):e.buffer;return new e.constructor(i,e.byteOffset,e.length)}(e,n);case d:return function(e,t,i){var n=t?i(U(e),!0):U(e);return B(n,$,new e.constructor)}(e,n,i);case h:case m:return new s(e);case p:return function(e){var t=new e.constructor(e.source,P.exec(e));return t.lastIndex=e.lastIndex,t}(e);case g:return function(e,t,i){var n=t?i(J(e),!0):J(e);return B(n,G,new e.constructor)}(e,n,i);case f:return a=e,Se?Object(Se.call(a)):{}}var a}(e,j,Ne,t)}}_||(_=new Ee);var O=_.get(e);if(O)return O;if(_.set(e,M),!R)var F=i?function(e){return function(e,t,i){var n=t(e);return qe(e)?n:function(e,t){for(var i=-1,n=t.length,s=e.length;++i<n;)e[s+i]=t[i];return e}(n,i(e))}(e,Qe,Le)}(e):Qe(e);return function(e,t){for(var i=-1,n=e?e.length:0;++i<n&&!1!==t(e[i],i,e););}(F||e,(function(s,r){F&&(s=e[r=s]),Me(M,r,Ne(s,t,i,n,r,e,_))})),M}function je(e){return!(!Ke(e)||(t=e,X&&X in t))&&(ze(e)||H(e)?ie:M).test(He(e));var t}function We(e){var t=new e.constructor(e.byteLength);return new re(t).set(new re(e)),t}function Oe(e,t,i,n){i||(i={});for(var s=-1,r=t.length;++s<r;){var o=t[s],a=n?n(i[o],e[o],o,i,e):void 0;Me(i,o,void 0===a?e[o]:a)}return i}function Fe(e,t){var i,n,s=e.__data__;return("string"==(n=typeof(i=t))||"number"==n||"symbol"==n||"boolean"==n?"__proto__"!==i:null===i)?s["string"==typeof t?"string":"hash"]:s.map}function De(e,t){var i=function(e,t){return null==e?void 0:e[t]}(e,t);return je(i)?i:void 0}xe.prototype.clear=function(){this.__data__=we?we(null):{}},xe.prototype.delete=function(e){return this.has(e)&&delete this.__data__[e]},xe.prototype.get=function(e){var t=this.__data__;if(we){var n=t[e];return n===i?void 0:n}return ee.call(t,e)?t[e]:void 0},xe.prototype.has=function(e){var t=this.__data__;return we?void 0!==t[e]:ee.call(t,e)},xe.prototype.set=function(e,t){return this.__data__[e]=we&&void 0===t?i:t,this},ke.prototype.clear=function(){this.__data__=[]},ke.prototype.delete=function(e){var t=this.__data__,i=Re(t,e);return!(i<0)&&(i==t.length-1?t.pop():de.call(t,i,1),!0)},ke.prototype.get=function(e){var t=this.__data__,i=Re(t,e);return i<0?void 0:t[i][1]},ke.prototype.has=function(e){return Re(this.__data__,e)>-1},ke.prototype.set=function(e,t){var i=this.__data__,n=Re(i,e);return n<0?i.push([e,t]):i[n][1]=t,this},Te.prototype.clear=function(){this.__data__={hash:new xe,map:new(ge||ke),string:new xe}},Te.prototype.delete=function(e){return Fe(this,e).delete(e)},Te.prototype.get=function(e){return Fe(this,e).get(e)},Te.prototype.has=function(e){return Fe(this,e).has(e)},Te.prototype.set=function(e,t){return Fe(this,e).set(e,t),this},Ee.prototype.clear=function(){this.__data__=new ke},Ee.prototype.delete=function(e){return this.__data__.delete(e)},Ee.prototype.get=function(e){return this.__data__.get(e)},Ee.prototype.has=function(e){return this.__data__.has(e)},Ee.prototype.set=function(e,t){var i=this.__data__;if(i instanceof ke){var n=i.__data__;if(!ge||n.length<199)return n.push([e,t]),this;i=this.__data__=new Te(n)}return i.set(e,t),this};var Le=he?q(he,Object):function(){return[]},$e=function(e){return te.call(e)};function Ge(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||Q)}function He(e){if(null!=e){try{return Y.call(e)}catch(e){}try{return e+""}catch(e){}}return""}function Ue(e,t){return e===t||e!=e&&t!=t}(pe&&$e(new pe(new ArrayBuffer(1)))!=v||ge&&$e(new ge)!=d||me&&$e(me.resolve())!=l||fe&&$e(new fe)!=g||ye&&$e(new ye)!=y)&&($e=function(e){var t=te.call(e),i=t==u?e.constructor:void 0,n=i?He(i):void 0;if(n)switch(n){case ve:return v;case be:return d;case _e:return l;case Ie:return g;case Ce:return y}return t});var qe=Array.isArray;function Je(e){return null!=e&&function(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=n}(e.length)&&!ze(e)}var Ve=ue||function(){return!1};function ze(e){var t=Ke(e)?te.call(e):"";return t==a||t==c}function Ke(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function Qe(e){return Je(e)?Pe(e):function(e){if(!Be(e))return le(e);var t=[];for(var i in Object(e))ee.call(e,i)&&"constructor"!=i&&t.push(i);return t}(e)}e.exports=function(e){return Ne(e,!0,!0)}}(se,se.exports);var re=I(se.exports);function oe(e,t,i){try{if(i?.canPublish("trace")&&i?.trace(`applying context delta ${JSON.stringify(t)} on context ${JSON.stringify(e)}`),!t)return e;if(t.reset)return e={...t.reset};if(e=ae(e,void 0),t.commands){for(const i of t.commands)"remove"===i.type?le(e,i.path):"set"===i.type&&he(e,i.value,i.path);return e}const n=t.added,s=t.updated,r=t.removed;return n&&Object.keys(n).forEach((t=>{e[t]=n[t]})),s&&Object.keys(s).forEach((t=>{ce(t,e,s)})),r&&r.forEach((t=>{delete e[t]})),e}catch(n){return i?.error(`error applying context delta ${JSON.stringify(t)} on context ${JSON.stringify(e)}`,n),e}}function ae(e,t){return re(e)}const ce=(e,t,i)=>{const n=i[e];if(void 0===n)return t;const s=t[e];return s&&n?"string"==typeof s||"number"==typeof s||"boolean"==typeof s||"string"==typeof n||"number"==typeof n||"boolean"==typeof n||Array.isArray(s)||Array.isArray(n)?(t[e]=n,t):(t[e]=Object.assign({},s,n),t):(t[e]=n,t)};function de(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 i in e)if(e.hasOwnProperty(i)){if(!t.hasOwnProperty(i))return!1;if(e[i]!==t[i]){if("object"!=typeof e[i])return!1;if(!de(e[i],t[i]))return!1}}for(const i in t)if(t.hasOwnProperty(i)&&!e.hasOwnProperty(i))return!1;return!0}function he(e,t,i){const n=i.split(".");let s;for(s=0;s<n.length-1;s++)e[n[s]]||(e[n[s]]={}),"object"!=typeof e[n[s]]&&(e[n[s]]={}),e=e[n[s]];e[n[s]]=t}function ue(e,t){return Object.keys(t).every((i=>"object"==typeof t[i]?ue(e?.[i]||{},t[i]||{}):t[i]===e?.[i]))}function le(e,t){const i=t.split(".");let n;for(n=0;n<i.length-1;n++){if(!e[i[n]])return;e=e[i[n]]}delete e[i[n]]}class pe{initTime;initStartTime;initEndTime;_bridge;constructor(e){this._bridge=new class{_logger;_connection;_trackAllContexts;_reAnnounceKnownContexts;_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._gw3Session=this._connection.domain("global",[q,z,Z,Y]),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"}))):this._connection.setLibReAnnounced({name:"contexts"})})),this.subscribeToContextCreatedMessages(),this.subscribeToContextUpdatedMessages(),this.subscribeToContextDestroyedMessages(),this._connection.replayer?.drain(te.name,(e=>{const t=e.type;t&&(t===q||t===J||t===H?this.handleContextCreatedMessage(e):t===z||t===Y||t===ee?this.handleContextUpdatedMessage(e):t!==Z&&t!==U||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){return e in this._creationPromises||(this._creationPromises[e]=this._gw3Session.send({type:B,domain:"global",name:e,data:t,lifetime:"retained"}).then((i=>{this._contextNameToId[e]=i.context_id,this._contextIdToName[i.context_id]=e;const n=this._contextNameToData[e]||new ne(i.context_id,e,!0,void 0);return n.isAnnounced=!0,n.name=e,n.contextId=i.context_id,n.context=i.data||ae(t),n.hasReceivedSnapshot=!0,this._contextNameToData[e]=n,delete this._creationPromises[e],i.context_id}))),this._creationPromises[e]}all(){return Object.keys(this._contextNameToData).filter((e=>this._contextNameToData[e].isAnnounced))}async update(e,t){t&&(t=ae(t)),e in this._creationPromises&&await this._creationPromises[e];const i=this._contextNameToData[e];if(!i||!i.isAnnounced)return this.createContext(e,t);let n=i.context;i.hasCallbacks()||(n=await this.get(i.name));const s=this.setPathSupported?this.calculateContextDeltaV2(n,t):this.calculateContextDeltaV1(n,t);return Object.keys(s.added).length||Object.keys(s.updated).length||s.removed.length||s.commands?.length?this._gw3Session.send({type:X,domain:"global",context_id:i.contextId,delta:s},{},{skipPeerId:!1}).then((e=>{this.handleUpdated(i,s,{updaterId:e.peer_id})})):Promise.resolve()}async set(e,t){t&&(t=ae(t)),e in this._creationPromises&&await this._creationPromises[e];const i=this._contextNameToData[e];return i&&i.isAnnounced?this._gw3Session.send({type:X,domain:"global",context_id:i.contextId,delta:{reset:t}},{},{skipPeerId:!1}).then((e=>{this.handleUpdated(i,{reset:t,added:{},removed:[],updated:{}},{updaterId:e.peer_id})})):this.createContext(e,t)}setPath(e,t,i){return this.setPathSupported?this.setPaths(e,[{path:t,value:i}]):Promise.reject("glue.contexts.setPath operation is not supported, use Glue42 3.10 or later")}async setPaths(e,t){if(!this.setPathSupported)return Promise.reject("glue.contexts.setPaths operation is not supported, use Glue42 3.10 or later");t&&(t=ae(t)),e in this._creationPromises&&await this._creationPromises[e];const i=this._contextNameToData[e];if(!i||!i.isAnnounced){const i={};for(const e of t)he(i,e.value,e.path);return this.createContext(e,i)}const n=[];for(const e of t)null===e.value?n.push({type:"remove",path:e.path}):n.push({type:"set",path:e.path,value:e.value});return this._gw3Session.send({type:X,domain:"global",context_id:i.contextId,delta:{commands:n}},{},{skipPeerId:!1}).then((e=>{this.handleUpdated(i,{added:{},removed:[],updated:{},commands:n},{updaterId:e.peer_id})}))}async get(e){e in this._creationPromises&&await this._creationPromises[e];const t=this._contextNameToData[e];if(!t||!t.isAnnounced)return Promise.resolve({});if(t&&(!t.hasCallbacks()||!t.hasReceivedSnapshot))return new Promise((t=>{this.subscribe(e,((e,i,n,s)=>{this.unsubscribe(s),t(e)}))}));const i=t?.context??{};return Promise.resolve(ae(i))}async subscribe(e,t,i){e in this._creationPromises&&await this._creationPromises[e];const n=void 0===i?this._nextCallbackSubscriptionNumber:i;void 0===i&&(this._nextCallbackSubscriptionNumber+=1),this._contextsSubscriptionsCache.every((e=>e.subKey!==this._nextCallbackSubscriptionNumber))&&this._contextsSubscriptionsCache.push({contextName:e,subKey:n,callback:t});let s=this._contextNameToData[e];if(!s||!s.isAnnounced)return s=s||new ne(void 0,e,!1,void 0),this._contextNameToData[e]=s,s.updateCallbacks[n]=t,Promise.resolve(n);const r=s.hasCallbacks();if(s.updateCallbacks[n]=t,r){if(s.hasReceivedSnapshot){const e=ae(s.context);t(e,e,[],n)}return Promise.resolve(n)}if(s.joinedActivity){if(s.hasReceivedSnapshot){const e=ae(s.context);t(e,e,[],n)}return Promise.resolve(n)}if(s.context&&s.sentExplicitSubscription){if(s.hasReceivedSnapshot){const e=ae(s.context);t(e,e,[],n)}return Promise.resolve(n)}return this.sendSubscribe(s).then((()=>n))}unsubscribe(e){this._contextsSubscriptionsCache=this._contextsSubscriptionsCache.filter((t=>t.subKey!==e));for(const t of Object.keys(this._contextNameToData)){const i=this._contextNameToData[t];if(!i)return;const n=i.hasCallbacks();delete i.updateCallbacks[e],i.isAnnounced&&n&&!i.hasCallbacks()&&i.sentExplicitSubscription&&this.sendUnsubscribe(i).catch((()=>{})),i.isAnnounced||i.hasCallbacks()||delete this._contextNameToData[t]}}async destroy(e){e in this._creationPromises&&await this._creationPromises[e];const t=this._contextNameToData[e];return t?this._gw3Session.send({type:Q,domain:"global",context_id:t.contextId}).then((e=>{})):Promise.reject(`context with ${e} does not exist`)}handleUpdated(e,t,i){const n=e.context;e.context=oe(e.context,t,this._logger),e.hasReceivedSnapshot=!0,this._contextNameToData[e.name]!==e||de(n,e.context)||this.invokeUpdateCallbacks(e,t,i)}subscribeToContextCreatedMessages(){const e=[J,q,H];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===H?(this._contextNameToId[e.activity_id]=e.context_id,this._contextIdToName[e.context_id]=e.activity_id):t===J&&(this._contextNameToId[e.name]=e.context_id,this._contextIdToName[e.context_id]=e.name);const i=this._contextIdToName[e.context_id];if(!i)throw new Error("Received created event for context with unknown name: "+e.context_id);if(!this._contextNameToId[i])throw new Error("Received created event for context with unknown id: "+e.context_id);let n=this._contextNameToData[i];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)}else this._contextNameToData[i]=n=new ne(e.context_id,i,!0,e.activity_id),this._trackAllContexts&&this.subscribe(i,(()=>{})).then((e=>this._systemContextsSubKey=e))}subscribeToContextUpdatedMessages(){const e=[Y,z,ee];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,i=e.context_id;let n=this._contextNameToData[this._contextIdToName[i]];const s=!n||!n.isAnnounced;if(t===ee)n||(n=this._contextNameToData[e.activity_id]||new ne(i,e.activity_id,!0,e.activity_id)),this._contextNameToData[e.activity_id]=n,this._contextIdToName[i]=e.activity_id,this._contextNameToId[e.activity_id]=i,n.contextId=i,n.isAnnounced=!0,n.activityId=e.activity_id,n.joinedActivity=!0;else if(!n||!n.isAnnounced)return void(t===z?(n=n||new ne(i,e.name,!0,void 0),n.sentExplicitSubscription=!0,this._contextNameToData[e.name]=n,this._contextIdToName[i]=e.name,this._contextNameToId[e.name]=i):this._logger.error(`Received 'update' for unknown context: ${i}`));const r=n.context;if(n.hasReceivedSnapshot=!0,t===z)n.context=e.data||{};else if(t===ee)n.context=e.context_snapshot||{};else{if(t!==Y)throw new Error("Unrecognized context update message "+t);n.context=oe(n.context,e.delta,this._logger)}!s&&de(n.context,r)&&t!==z||this.invokeUpdateCallbacks(n,e.delta,{updaterId:e.updater_id})}invokeUpdateCallbacks(e,t,i){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),he(t.updated,null,e.path)):"set"===e.type&&he(t.updated,e.value,e.path)}for(const n in e.updateCallbacks)if(e.updateCallbacks.hasOwnProperty(n))try{(0,e.updateCallbacks[n])(ae(e.context),ae(Object.assign({},t.added||{},t.updated||{},t.reset||{})),t.removed,parseInt(n,10),i)}catch(e){this._logger.debug("callback error: "+JSON.stringify(e))}}subscribeToContextDestroyedMessages(){const e=[Z,U];for(const t of e){const e=this._connection.on(t,this.handleContextDestroyedMessage.bind(this));this._gw3Subscriptions.push(e)}}handleContextDestroyedMessage(e){let t,i;if(e.type===U){if(i=e.activity_id,t=this._contextNameToId[i],!t)return void this._logger.error(`Received 'destroyed' for unknown activity: ${e.activity_id}`)}else if(t=e.context_id,i=this._contextIdToName[t],!i)return void this._logger.error(`Received 'destroyed' for unknown context: ${e.context_id}`);delete this._contextIdToName[t],delete this._contextNameToId[i];const n=this._contextNameToData[i];delete this._contextNameToData[i],n&&n.isAnnounced||this._logger.error(`Received 'destroyed' for unknown context: ${t}`)}sendSubscribe(e){return e.sentExplicitSubscription=!0,this._gw3Session.send({type:V,domain:"global",context_id:e.contextId}).then((e=>{}))}sendUnsubscribe(e){return e.sentExplicitSubscription=!1,this._gw3Session.send({type:K,domain:"global",context_id:e.contextId}).then((e=>{}))}calculateContextDeltaV1(e,t){const i={added:{},updated:{},removed:[],reset:void 0};if(e)for(const n of Object.keys(e))-1===Object.keys(t).indexOf(n)||null===t[n]||de(e[n],t[n])||(i.updated[n]=t[n]);for(const n of Object.keys(t))e&&-1!==Object.keys(e).indexOf(n)?null===t[n]&&i.removed.push(n):null!==t[n]&&(i.added[n]=t[n]);return i}calculateContextDeltaV2(e,t){const i={added:{},updated:{},removed:[],reset:void 0,commands:[]};for(const n of Object.keys(t))null!==t[n]?de(e?e[n]:null,t[n])||i.commands?.push({type:"set",path:n,value:t[n]}):i.commands?.push({type:"remove",path:n});return i}resetState(){for(const e of this._gw3Subscriptions)this._connection.off(e);this._systemContextsSubKey&&(this.unsubscribe(this._systemContextsSubKey),delete this._systemContextsSubKey),this._gw3Subscriptions=[],this._contextNameToId={},this._contextIdToName={},delete this._protocolVersion,this._contextsTempCache=Object.keys(this._contextNameToData).reduce(((e,t)=>(e[t]=this._contextNameToData[t].context,e)),{}),this._contextNameToData={}}async reInitiateState(){this.subscribeToContextCreatedMessages(),this.subscribeToContextUpdatedMessages(),this.subscribeToContextDestroyedMessages(),this._connection.replayer?.drain(te.name,(e=>{const t=e.type;t&&(t===q||t===J||t===H?this.handleContextCreatedMessage(e):t===z||t===Y||t===ee?this.handleContextUpdatedMessage(e):t!==Z&&t!==U||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)))}}(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,i){this.checkName(e),this.checkPath(t);return""===t?(this.checkData(i),this.set(e,i)):this._bridge.setPath(e,t,i)}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:i}of t){this.checkPath(e);""===e&&this.checkData(i)}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,i,n,s,r)=>t(e,i,n,(()=>this._bridge.unsubscribe(s)),r))).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 ge(e,t,i){return"function"!=typeof t&&"function"!=typeof i?e:("function"!=typeof t?t=()=>{}:"function"!=typeof i&&(i=()=>{}),e.then(t,i))}function me(e=0,t,i){let n;const s=()=>{n&&clearTimeout(n)};return t.then((()=>{s()})).catch((()=>{s()})),new Promise(((t,s)=>{n=setTimeout((()=>s(i)),e)}))}var fe;!function(e){e[e.Success=0]="Success",e[e.Error=1]="Error"}(fe||(fe={}));class ye{protocol;repo;instance;configuration;constructor(e,t,i,n){this.protocol=e,this.repo=t,this.instance=i,this.configuration=n}subscribe(e,t,i,n,s){const r=(e,i,n,r)=>{t.methodResponseTimeout=t.methodResponseTimeout??t.waitTimeoutMs,this.protocol.client.subscribe(i,t,e,n,r,s)};return ge(new Promise(((i,n)=>{const s=e=>{i(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 d=0,h=this.getServerMethodsByFilterAndTarget(a,c);if(h.length>0)r(h,h[0].methods[0],s,o);else{const i=()=>{if(c&&t.waitTimeoutMs)if(d+=500,h=this.getServerMethodsByFilterAndTarget(a,c),h.length>0){const e=h[0].methods[0];r(h,e,s,o)}else if(d>=t.waitTimeoutMs){r(h,"string"==typeof e?{name:e}:e,s,o)}else setTimeout(i,500)};setTimeout(i,500)}})),i,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,i)=>{e(t,i)}))}serverMethodAdded(e){return this.repo.onServerMethodAdded(((t,i)=>{e({server:t,method:i})}))}serverMethodRemoved(e){return this.repo.onServerMethodRemoved(((t,i)=>{e({server:t,method:i})}))}async invoke(e,t,i,n,s,r){return ge((async()=>{let s;if(s="string"==typeof e?{name:e}:{...e},!s.name)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(t||(t={}),i||(i="best"),"string"==typeof i&&"all"!==i&&"best"!==i&&"skipMine"!==i)return Promise.reject(new Error(`"${i}" is not a valid target. Valid targets are "all" and "best".`));if(n||(n={}),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)),void 0!==n.waitTimeoutMs&&"number"!=typeof n.waitTimeoutMs)return Promise.reject(new Error(`"${n.waitTimeoutMs}" is not a valid number for "waitTimeoutMs" `));if("object"!=typeof t)return Promise.reject(new Error(`The method arguments must be an object. method: ${s.name}`));let r=this.getServerMethodsByFilterAndTarget(s,i);if(0===r.length)try{r=await this.tryToAwaitForMethods(s,i,n)}catch(n){const r={method:{...s,getServers:()=>[],supportsStreaming:!1,objectTypes:s.objectTypes??[],flags:s.flags?.metadata??{}},called_with:t,message:`Can not find a method matching ${JSON.stringify(e)} with server filter ${JSON.stringify(i)}`,executed_by:void 0,returned:void 0,status:void 0};return Promise.reject(r)}const o=n.methodResponseTimeoutMs,a=n,c=r.map((e=>{const i=j(10),n=e.methods[0],s=e.server,r=this.protocol.client.invoke(i,n,t,s,a);return Promise.race([r,me(o,r,{invocationId:i,message:`Invocation timeout (${o} ms) reached for method name: ${n?.name}, target instance: ${JSON.stringify(s.instance)}, options: ${JSON.stringify(a)}`,status:fe.Error})])})),d=await Promise.all(c),h=this.getInvocationResultObj(d,s,t);return d.every((e=>e.status===fe.Error))?Promise.reject(h):h})(),s,r)}getInvocationResultObj(e,t,i){const n=e.filter((e=>e.status===fe.Success)).reduce(((e,n)=>e=[...e,{executed_by:n.instance,returned:n.result,called_with:i,method:t,message:n.message,status:n.status}]),[]),s=e.filter((e=>e.status===fe.Error)).reduce(((e,n)=>e=[...e,{executed_by:n.instance,called_with:i,name:t.name,message:n.message}]),[]),r=e[0];return{method:t,called_with:i,returned:r.result,executed_by:r.instance,all_return_values:n,all_errors:s,message:r.message,status:r.status}}tryToAwaitForMethods(e,t,i){return new Promise(((n,s)=>{if(0===i.waitTimeoutMs)return void s();let r=0;const o=setInterval((()=>{r+=500;const a=this.getServerMethodsByFilterAndTarget(e,t);if(a.length>0)clearInterval(o),n(a);else if(r>=(i.waitTimeoutMs||1e4))return clearInterval(o),void s()}),500)}))}filterByTarget(e,t){if("string"!=typeof e){let i;i=Array.isArray(e)?e:[e];return i.reduce(((e,i)=>{const n=t.filter((e=>this.instanceMatch(i,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((i=>{let n;const s=e[i],r=t[i];switch(i){case"objectTypes":n=(s||[]).every((e=>(r||[]).includes(e)));break;case"flags":n=ue(r||{},s||{});break;default:n=String(s).toLowerCase()===String(r).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 i={};return 1===t.length?i=t[0].methods:t.forEach((e=>{Object.keys(e.methods).forEach((t=>{const n=e.methods[t];i[n.identifier]=n}))})),Object.keys(i).map((e=>i[e]))}getServers(e){const t=this.repo.getServers();return void 0===e?t.map((e=>({server:e,methods:[]}))):t.reduce(((t,i)=>{const n=Object.values(i.methods).filter((t=>this.methodMatch(e,t)));return n.length>0&&t.push({server:i,methods:n}),t}),[])}getServerMethodsByFilterAndTarget(e,t){const i=this.getServers(e);return this.filterByTarget(t,i)}}class we{protocol;repoMethod;subscription;constructor(e,t,i){this.protocol=e,this.repoMethod=t,this.subscription=i}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)}}class ve{protocol;repoMethod;requestContext;arguments;instance;constructor(e,t,i){this.protocol=e,this.repoMethod=t,this.requestContext=i,this.arguments=i.arguments,this.instance=i.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)}}class be{key;protocol;repoMethod;constructor(e,t,i){this.key=e,this.protocol=t,this.repoMethod=i}subscriptions(){return this.protocol.server.getSubscriptionList(this.repoMethod,this.key).map((e=>new we(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 _e{_protocol;_repoMethod;_server;name;constructor(e,t,i){this._protocol=e,this._repoMethod=t,this._server=i,this.name=this._repoMethod.definition.name}branches(e){const t=this._protocol.server.getBranchList(this._repoMethod);return e?t.indexOf(e)>-1?new be(e,this._protocol,this._repoMethod):void 0:t.map((e=>new be(e,this._protocol,this._repoMethod)))}branch(e){return this.branches(e)}subscriptions(){return this._protocol.server.getSubscriptionList(this._repoMethod).map((e=>new we(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}}close(){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.");this._protocol.server.pushData(this._repoMethod,e,t)}updateRepoMethod(e){this._repoMethod=e}}class Ie{protocol;serverRepository;streaming;invocations=0;currentlyUnregistering={};constructor(e,t){this.protocol=e,this.serverRepository=t,this.streaming=new 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 i=new ve(this.protocol,t,e);t.streamCallbacks.subscriptionRequestHandler(i)}handleSubAdded(e,t){if(!t||!t.streamCallbacks||"function"!=typeof t.streamCallbacks.subscriptionAddedHandler)return;const i=new we(this.protocol,t,e);t.streamCallbacks.subscriptionAddedHandler(i)}handleSubRemoved(e,t){if(!t||!t.streamCallbacks||"function"!=typeof t.streamCallbacks.subscriptionRemovedHandler)return;const i=new we(this.protocol,t,e);t.streamCallbacks.subscriptionRemovedHandler(i)}}(e,this),this.protocol.server.onInvoked(this.onMethodInvoked.bind(this))}createStream(e,t,i,n,s){return ge(new Promise(((i,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 r;if(r="string"==typeof e?{name:""+e}:{...e},!r.name)return n(`The “name” property is required for the “streamDefinition” object and must be unique. Stream definition: ${JSON.stringify(r)}`);if(this.serverRepository.getList().some((e=>e.definition.name===r.name)))return n(`A stream with the name "${r.name}" already exists! Please, provide a unique name for the stream.`);r.supportsStreaming=!0,t||(t={}),"function"!=typeof t.subscriptionRequestHandler&&(t.subscriptionRequestHandler=e=>{e.accept()});const o=this.serverRepository.add({definition:r,streamCallbacks:t,protocolState:{}});this.protocol.server.createStream(o).then((()=>{let e;s?(e=s,s.updateRepoMethod(o)):e=new _e(this.protocol,o,this),o.stream=e,i(e)})).catch((e=>{o.repoId&&this.serverRepository.remove(o.repoId),n(e)}))})),i,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("function"!=typeof t)return Promise.reject(`The second parameter must be a callback function. Method: ${"string"==typeof e?e:e.name}`);const i=async(e,i)=>{try{const n=t(e.args,e.instance);if(n&&"function"==typeof n.then){i(void 0,await n)}else i(void 0,n)}catch(e){i(e??"",e??"")}};return i.userCallback=t,this.registerCore(e,i)}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("function"!=typeof t)return Promise.reject(`The second parameter must be a callback function. Method: ${"string"==typeof e?e:e.name}`);const i=async(e,i)=>{try{let n=!1;const s=e=>{n||i(void 0,e),n=!0},r=e=>{n||(e||(e=""),i(e,e)),n=!0},o=t(e.args,e.instance,s,r);o&&"function"==typeof o.then&&o.then(s).catch(r)}catch(e){i(e,void 0)}};return i.userCallbackAsync=t,this.registerCore(e,i)}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("function"==typeof e)return void await this.unregisterWithPredicate(e,t);let i;if(i="string"==typeof e?{name:e}:e,void 0===i.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===i.name&&(e.definition.supportsStreaming||!1)===t));if(!n)return Promise.reject(`Method with a name "${i.name}" does not exist or is not registered by your application!`);await this.removeMethodsOrStreams([n])}async unregisterWithPredicate(e,t){const i=this.serverRepository.getList().filter((t=>e(t.definition))).filter((e=>(e.definition.supportsStreaming||!1)===t));if(!i||0===i.length)return Promise.reject(`Could not find a ${t?"stream":"method"} matching the specified condition!`);await this.removeMethodsOrStreams(i)}removeMethodsOrStreams(e){const t=[];return e.forEach((e=>{const i=this.protocol.server.unregister(e).then((()=>{e.repoId&&this.serverRepository.remove(e.repoId)}));t.push(i),this.addAsCurrentlyUnregistering(e.definition.name,i)})),Promise.all(t)}async addAsCurrentlyUnregistering(e,t){const i=new Promise((e=>setTimeout(e,5e3)));this.currentlyUnregistering[e]=Promise.race([t,i]).then((()=>{delete this.currentlyUnregistering[e]}))}async registerCore(e,t){let i;if(i="string"==typeof e?{name:""+e}:{...e},!i.name)return Promise.reject(`Please, provide a (unique) string value for the “name” property in the “methodDefinition” object: ${JSON.stringify(e)}`);const n=this.currentlyUnregistering[i.name];void 0!==n&&await n;if(this.serverRepository.getList().some((e=>e.definition.name===i.name)))return Promise.reject(`A method with the name "${i.name}" already exists! Please, provide a unique name for the method.`);if(i.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 “${i.name}” to be a stream, please use the “glue.interop.createStream()” method.`);const s=this.serverRepository.add({definition:i,theFunction:t,protocolState:{}});return this.protocol.server.register(s).catch((e=>{throw s?.repoId&&this.serverRepository.remove(s.repoId),e}))}onMethodInvoked(e,t,i){e&&e.theFunction&&e.theFunction(i,((i,n)=>{if(null!=i)if(i.message&&"string"==typeof i.message)i=i.message;else if("string"!=typeof i)try{i=JSON.stringify(i)}catch(e){i=`un-stringifyable error in onMethodInvoked! Top level prop names: ${Object.keys(i)}`}n?("object"!=typeof n||Array.isArray(n))&&(n={_value:n}):n={},this.protocol.server.methodInvocationResult(e,t,i,n)}))}}class Ce{wrapped={};constructor(e,t,i){this.wrapped.getMethods=function(){return e.methodsForInstance(this)},this.wrapped.getStreams=function(){return e.methodsForInstance(this).filter((e=>e.supportsStreaming))},t&&this.refreshWrappedObject(t),i&&(i.loggedIn((()=>{this.refresh(i)})),this.refresh(i))}unwrap(){return this.wrapped}refresh(e){if(!e)return;const t=e?.resolvedIdentity,i=Object.assign({},t??{},{peerId:e?.peerId});this.refreshWrappedObject(i)}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??j(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 Ae=e=>({...e,flags:e.flags.metadata||{}});class Se{logger;API;servers={};myServer;methodsCount={};callbacks=A();constructor(e,t){this.logger=e,this.API=t;const i=this.API.instance.peerId;this.myServer={id:i,methods:{},instance:this.API.instance,wrapper:this.API.unwrappedInstance},this.servers[i]=this.myServer}addServer(e,t){this.logger.debug(`adding server ${t}`);const i=this.servers[t];if(i)return i.id;const n=new Ce(this.API,e),s={id:t,methods:{},instance:n.unwrap(),wrapper:n};return this.servers[t]=s,this.callbacks.execute("onServerAdded",s.instance),t}removeServerById(e,t){const i=this.servers[e];i?(this.logger.debug(`removing server ${e}`),Object.keys(i.methods).forEach((t=>{this.removeServerMethod(e,t)})),delete this.servers[e],this.callbacks.execute("onServerRemoved",i.instance,t)):this.logger.warn(`not aware of server ${e}, my state ${JSON.stringify(Object.keys(this.servers))}`)}addServerMethod(e,t){const i=this.servers[e];if(!i)throw new Error("server does not exists");if(i.methods[t.id])return;const n=this.createMethodIdentifier(t),s=this,r={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:()=>s.getServersByMethod(n)};r.object_types=r.objectTypes,r.display_name=r.displayName,r.version=r.version,i.methods[t.id]=r;const o=Ae(r);return this.methodsCount[n]||(this.methodsCount[n]=0,this.callbacks.execute("onMethodAdded",o)),this.methodsCount[n]=this.methodsCount[n]+1,this.callbacks.execute("onServerMethodAdded",i.instance,o),r}removeServerMethod(e,t){const i=this.servers[e];if(!i)throw new Error("server does not exists");const n=i.methods[t];delete i.methods[t];const s=Ae(n);this.methodsCount[n.identifier]=this.methodsCount[n.identifier]-1,0===this.methodsCount[n.identifier]&&this.callbacks.execute("onMethodRemoved",s),this.callbacks.execute("onServerMethodRemoved",i.instance,s)}getMethods(){return this.extractMethodsFromServers(Object.values(this.servers)).map(Ae)}getServers(){return Object.values(this.servers).map(this.hideServerMethodSystemFlags)}onServerAdded(e){const t=this.callbacks.add("onServerAdded",e),i=this.getServers().map((e=>e.instance));return this.returnUnsubWithDelayedReplay(t,i,e)}onMethodAdded(e){const t=this.callbacks.add("onMethodAdded",e),i=this.getMethods();return this.returnUnsubWithDelayedReplay(t,i,e)}onServerMethodAdded(e){const t=this.callbacks.add("onServerMethodAdded",e);let i=!1;const n=this.getServers();return setTimeout((()=>{n.forEach((t=>{const n=t.methods;Object.keys(n).forEach((s=>{i||e(t.instance,n[s])}))}))}),0),()=>{i=!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??"",i=e.result_signature??"";return(e.name+t+i).toLowerCase()}getServersByMethod(e){const t=[];return Object.values(this.servers).forEach((i=>{Object.values(i.methods).forEach((n=>{n.identifier===e&&t.push(i.instance)}))})),t}returnUnsubWithDelayedReplay(e,t,i){let n=!1;return setTimeout((()=>{t.forEach((e=>{n||i(e)}))}),0),()=>{n=!0,e()}}hideServerMethodSystemFlags(e){const t={};return Object.entries(e.methods).forEach((([e,i])=>{t[e]=Ae(i)})),{...e,methods:t}}extractMethodsFromServers(e){return Object.values(e).reduce(((e,t)=>[...e,...Object.values(t.methods)]),[])}}class xe{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 ke="onSubscriptionRequest",Te="onSubscriptionAdded",Ee="onSubscriptionRemoved";class Pe{session;repository;serverRepository;ERR_URI_SUBSCRIPTION_FAILED="com.tick42.agm.errors.subscription.failure";callbacks=A();nextStreamId=0;constructor(e,t,i){this.session=e,this.repository=t,this.serverRepository=i,e.on("add-interest",(e=>{this.handleAddInterest(e)})),e.on("remove-interest",(e=>{this.handleRemoveInterest(e)}))}acceptRequestOnBranch(e,t,i){if("string"!=typeof i&&(i=""),"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,i),s=e.msg.subscription_id,r={id:s,arguments:e.arguments,instance:e.instance,branchKey:i,streamId:n,subscribeMsg:e.msg};t.protocolState.subscriptionsMap[s]=r,this.session.sendFireAndForget({type:"accepted",subscription_id:s,stream_id:n}),this.callbacks.execute(Te,r,t)}rejectRequest(e,t,i){"string"!=typeof i&&(i=""),this.sendSubscriptionFailed("Subscription rejected by user. "+i,e.msg.subscription_id)}pushData(e,t,i){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 i?i=[i]:(!Array.isArray(i)||i.length<=0)&&(i=[]);e.protocolState.branchKeyToStreamIdMap.filter((e=>!i||0===i.length||i.indexOf(e.key)>=0)).map((e=>e.streamId)).forEach((e=>{const i={type:"publish",stream_id:e,data:t};this.session.sendFireAndForget(i)}))}pushDataToSingle(e,t,i){if("object"!=typeof i)throw new Error("Invalid arguments. Data must be an object.");const n={type:"post",subscription_id:t.id,data:i};this.session.sendFireAndForget(n)}closeSingleSubscription(e,t){e.protocolState.subscriptionsMap&&delete e.protocolState.subscriptionsMap[t.id];const i={type:"drop-subscription",subscription_id:t.id,reason:"Server dropping a single subscription"};this.session.sendFireAndForget(i),t.instance,this.callbacks.execute(Ee,t,e)}closeMultipleSubscriptions(e,t){if("object"!=typeof e||"object"!=typeof e.protocolState.subscriptionsMap)return;if(!e.protocolState.subscriptionsMap)return;const i=e.protocolState.subscriptionsMap;let n=Object.keys(i).map((e=>i[e]));"string"==typeof t&&(n=n.filter((e=>e.branchKey===t))),n.forEach((e=>{delete i[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)}))}getSubscriptionList(e,t){if("object"!=typeof e)return[];let i=[];if(!e.protocolState.subscriptionsMap)return[];const n=e.protocolState.subscriptionsMap,s=Object.keys(n).map((e=>n[e]));return i="string"!=typeof t?s:s.filter((e=>e.branchKey===t)),i}getBranchList(e){if("object"!=typeof e)return[];if(!e.protocolState.subscriptionsMap)return[];const t=e.protocolState.subscriptionsMap,i=Object.keys(t).map((e=>t[e])),n=[];return i.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(Te,e)}onSubRequest(e){this.onSubscriptionLifetimeEvent(ke,e)}onSubRemoved(e){this.onSubscriptionLifetimeEvent(Ee,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 i=t.protocolState.subscriptionsMap[e.subscription_id];delete t.protocolState.subscriptionsMap[e.subscription_id],this.callbacks.execute(Ee,i,t)}onSubscriptionLifetimeEvent(e,t){this.callbacks.add(e,t)}getNextStreamId(){return this.nextStreamId+++""}handleAddInterest(e){const t=this.repository.getServerById(e.caller_id),i=t?.instance??{},n={msg:e,arguments:e.arguments_kv||{},instance:i},s=this.serverRepository.getById(e.method_id);if(void 0!==s)s.protocolState.subscriptionsMap&&s.protocolState.subscriptionsMap[e.subscription_id]?this.sendSubscriptionFailed("A subscription with id "+e.subscription_id+" already exists.",e.subscription_id):this.callbacks.execute(ke,n,s);else{const t="No method with id "+e.method_id+" on this server.";this.sendSubscriptionFailed(t,e.subscription_id)}}sendSubscriptionFailed(e,t){const i={type:"error",reason_uri:this.ERR_URI_SUBSCRIPTION_FAILED,reason:e,request_id:t};this.session.sendFireAndForget(i)}getStreamId(e,t){if("string"!=typeof t&&(t=""),!e.protocolState.branchKeyToStreamIdMap)throw new Error(`streaming ${e.definition.name} method without protocol state`);const i=e.protocolState.branchKeyToStreamIdMap.filter((e=>e.key===t))[0];let n=i?i.streamId:void 0;return"string"==typeof n&&""!==n||(n=this.getNextStreamId(),e.protocolState.branchKeyToStreamIdMap.push({key:t,streamId:n})),n}}class Me{session;clientRepository;serverRepository;logger;callbacks=A();streaming;constructor(e,t,i,n){this.session=e,this.clientRepository=t,this.serverRepository=i,this.logger=n,this.streaming=new Pe(e,t,i),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 i=e.definition,n=Object.assign({},{metadata:i.flags??{}},{streaming:t||!1}),s={type:"register",methods:[{id:e.repoId,name:i.name,display_name:i.displayName,description:i.description,version:i.version,flags:n,object_types:i.objectTypes||i.object_types,input_signature:i.accepts,result_signature:i.returns,restrictions:void 0}]};return this.session.send(s,{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,i,n){let s;s=i||""===i?{type:"error",request_id:t,reason_uri:"agm.errors.client_error",reason:i,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(s)}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,i){this.streaming.pushData(e,t,i)}pushDataToSingle(e,t,i){this.streaming.pushDataToSingle(e,t,i)}closeSingleSubscription(e,t){this.streaming.closeSingleSubscription(e,t)}acceptRequestOnBranch(e,t,i){this.streaming.acceptRequestOnBranch(e,t,i)}rejectRequest(e,t,i){this.streaming.rejectRequest(e,t,i)}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,i=e.caller_id,n=e.method_id,s=e.arguments_kv,r=this.serverRepository.getList().filter((e=>e.repoId===n))[0];if(void 0===r)return;const o=this.clientRepository.getServerById(i)?.instance,a={args:s,instance:o};this.callbacks.execute("onInvoked",r,t,a)}}class Re{repository;subscriptionData;get requestArguments(){return this.subscriptionData.params.arguments||{}}get servers(){return this.subscriptionData.trackedServers.reduce(((e,t)=>{if(t.subscriptionId){const i=this.repository.getServerById(t.serverId)?.instance;i&&e.push(i)}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 Ne{config;cache=[];timeoutIds=[];constructor(e){this.config=e}add(e){const t=j(10);this.cache.push({id:t,element:e});const i=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(i)}flush(){const e=this.cache.map((e=>e.element));return this.timeoutIds.forEach((e=>clearInterval(e))),this.cache=[],this.timeoutIds=[],e}}const je="awaitingAccept",We="subscribed",Oe="Subscription failed.",Fe="ClientInitiated";class De{session;repository;logger;subscriptionsList={};timedCache=new Ne({ELEMENT_TTL_MS:1e4});subscriptionIdToLocalKeyMap={};nextSubLocalKey=0;constructor(e,t,i){this.session=e,this.repository=t,this.logger=i,e.on("subscribed",this.handleSubscribed),e.on("event",this.handleEventData),e.on("subscription-cancelled",this.handleSubscriptionCancelled)}subscribe(e,t,i,n,s,r){if(0===i.length)return void s({method:e,called_with:t.arguments,message:Oe+" No available servers matched the target params."});const o=this.getNextSubscriptionLocalKey(),a=this.registerSubscription(o,e,t,n,s,t.methodResponseTimeout||1e4,r);"object"==typeof a?i.forEach((i=>{const n=i.server.id,s=i.methods.find((t=>t.name===e.name));if(!s)return void this.logger.error(`can not find method ${e.name} for target ${i.server.id}`);a.trackedServers.push({serverId:n,subscriptionId:void 0});const r={type:"subscribe",server_id:n,method_id:s.gatewayId,arguments_kv:t.arguments};this.session.send(r,{serverId:n,subLocalKey:o}).then((e=>this.handleSubscribed(e))).catch((e=>this.handleErrorSubscribing(e)))})):s({method:e,called_with:t.arguments,message:Oe+" 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,i,n,s,r,o){const a={localKey:e,status:je,method:t,params:i,success:n,error:s,trackedServers:[],handlers:{onData:o?.handlers.onData||[],onClosed:o?.handlers.onClosed||[],onConnected:o?.handlers.onConnected||[]},queued:{data:[],closers:[]},timeoutId:void 0,close:()=>this.closeSubscription(e),subscription:o?.subscription};return o||(i.onData&&a.handlers.onData.push(i.onData),i.onClosed&&a.handlers.onClosed.push(i.onClosed),i.onConnected&&a.handlers.onConnected.push(i.onConnected)),this.subscriptionsList[e]=a,a.timeoutId=setTimeout((()=>{if(void 0===this.subscriptionsList[e])return;const n=this.subscriptionsList[e];n.status===je?(s({method:t,called_with:i.arguments,message:Oe+" Subscription attempt timed out after "+r+" ms."}),delete this.subscriptionsList[e]):n.status===We&&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]))}),r),a}handleErrorSubscribing=e=>{const t=e._tag,i=t.subLocalKey,n=this.subscriptionsList[i];if("object"==typeof n&&(n.trackedServers=n.trackedServers.filter((e=>e.serverId!==t.serverId)),n.trackedServers.length<=0)){if(clearTimeout(n.timeoutId),n.status===je){const t="string"==typeof e.reason&&""!==e.reason?' Publisher said "'+e.reason+'".':" No reason given.",i="object"==typeof n.params.arguments?JSON.stringify(n.params.arguments):"{}";n.error({message:"Subscription rejected."+t+" Called with:"+i,called_with:n.params.arguments,method:n.method})}else n.status===We&&this.callOnClosedHandlers(n);delete this.subscriptionsList[i]}};handleSubscribed=e=>{const t=e._tag.subLocalKey,i=this.subscriptionsList[t];if("object"!=typeof i)return;const n=e._tag.serverId,s=i.trackedServers.filter((e=>e.serverId===n))[0];if("object"!=typeof s)return;s.subscriptionId=e.subscription_id,this.subscriptionIdToLocalKeyMap[e.subscription_id]=t;const r=i.status===je;if(i.status=We,r){let e=!1,t=i.subscription;t?(t.setNewSubscription(i),i.success(t),e=!0):(t=new Re(this.repository,i),i.subscription=t,i.success(t));for(const n of i.handlers.onConnected)try{n(t.serverInstance,e)}catch(e){}}};handleEventData=e=>{const t=this.subscriptionIdToLocalKeyMap[e.subscription_id];if(void 0===t)return;const i=this.subscriptionsList[t];if("object"!=typeof i)return;const n=i.trackedServers.filter((t=>t.subscriptionId===e.subscription_id));if(1!==n.length)return;const s=e.oob,r=n[0].serverId,o=this.repository.getServerById(r),a=()=>({data:e.data,server:o?.instance??{},requestArguments:i.params.arguments,message:void 0,private:s}),c=i.handlers.onData,d=i.queued.data;c.length>0?c.forEach((e=>{"function"==typeof e&&e(a())})):d.push(a())};handleSubscriptionCancelled=e=>{const t=this.subscriptionIdToLocalKeyMap[e.subscription_id];if(void 0===t)return;const i=this.subscriptionsList[t];if("object"!=typeof i)return;const n=i.trackedServers.length-1;i.trackedServers=i.trackedServers.filter((t=>t.subscriptionId!==e.subscription_id||(i.queued.closers.push(t.serverId),!1))),i.trackedServers.length===n&&(i.trackedServers.length<=0&&(this.timedCache.add(i),clearTimeout(i.timeoutId),this.callOnClosedHandlers(i),delete this.subscriptionsList[t]),delete this.subscriptionIdToLocalKeyMap[e.subscription_id])};callOnClosedHandlers(e,t){const i=e.queued.closers.length,n=i>0?e.queued.closers[i-1]:null;let s;void 0!==n&&"string"==typeof n&&(s=this.repository.getServerById(n)?.instance??{}),e.handlers.onClosed.forEach((i=>{"function"==typeof i&&i({message:t||"ServerInitiated",requestArguments:e.params.arguments||{},server:s,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:Fe}),delete this.subscriptionIdToLocalKeyMap[e.subscriptionId])})),t.trackedServers=[],this.callOnClosedHandlers(t,Fe),delete this.subscriptionsList[e])}}class Le{session;repository;logger;streaming;constructor(e,t,i){this.session=e,this.repository=t,this.logger=i,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 De(e,t,i)}subscribe(e,t,i,n,s,r){this.streaming.subscribe(e,t,i,n,s,r)}invoke(e,t,i,n){const s=n.id,r={type:"call",server_id:s,method_id:t.gatewayId,arguments_kv:i};return this.session.send(r,{invocationId:e,serverId:s}).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,i=e.identity,n=!e.meta||e.meta.local,s=Number(i.process),r={machine:i.machine,pid:isNaN(s)?i.process:s,instance:i.instance,application:i.application,applicationName:i.applicationName,environment:i.environment,region:i.region,user:i.user,windowId:i.windowId,peerId:t,api:i.api,isLocal:n};this.repository.addServer(r,t)}handlePeerRemoved(e){const t=e.removed_id,i=e.reason;this.repository.removeServerById(t,i)}handleMethodsAddedMessage(e){const t=e.server_id;e.methods.forEach((e=>{this.repository.addServerMethod(t,e)}))}handleMethodsRemovedMessage(e){const t=e.server_id,i=e.methods,n=this.repository.getServerById(t);if(n){Object.keys(n.methods).forEach((e=>{const s=n.methods[e];i.indexOf(s.gatewayId)>-1&&this.repository.removeServerMethod(t,e)}))}}handleResultMessage(e){const t=e._tag.invocationId,i=e.result,n=e._tag.serverId,s=this.repository.getServerById(n);return{invocationId:t,result:i,instance:s?.instance,status:fe.Success,message:""}}handleInvocationError(e){if(this.logger.debug(`handle invocation error ${JSON.stringify(e)}`),"_tag"in e){const t=e._tag.invocationId,i=e._tag.serverId,n=this.repository.getServerById(i),s=e.reason;return{invocationId:t,result:e.context,instance:n?.instance,status:fe.Error,message:s}}return{invocationId:"",message:e.message,status:fe.Error,error:e}}}function $e(e,t,i,n,s,r){const o=s.logger.subLogger("gw3-protocol");let a;const c=new Promise((e=>{a=e})),d=t.domain("agm",["subscribed"]),h=new Me(d,i,n,o.subLogger("server")),u=new Le(d,i,o.subLogger("client"));return d.onJoined((s=>{i.addServer(e,t.peerId),s?async function(){o.info("reconnected - will replay registered methods and subscriptions"),u.drainSubscriptionsCache().forEach((e=>{const t=e.method,i=Object.assign({},e.params);o.info(`trying to soft-re-subscribe to method ${t.name}, with params: ${JSON.stringify(i)}`),r.client.subscribe(t,i,void 0,void 0,e).then((()=>o.info(`soft-subscribing to method ${t.name} DONE`))).catch((e=>o.warn(`subscribing to method ${t.name} failed: ${JSON.stringify(e)}}`)))}));const e=[],t=u.drainSubscriptions();for(const i of t){const t=i.method,n=Object.assign({},i.params);o.info(`trying to re-subscribe to method ${t.name}, with params: ${JSON.stringify(n)}`),e.push(r.client.subscribe(t,n,void 0,void 0,i).then((()=>o.info(`subscribing to method ${t.name} DONE`))))}const i=n.getList();n.reset();for(const t of i){const i=t.definition;t.stream?e.push(r.server.createStream(i,t.streamCallbacks,void 0,void 0,t.stream).then((()=>o.info(`subscribing to method ${i.name} DONE`))).catch((()=>o.warn(`subscribing to method ${i.name} FAILED`)))):t?.theFunction?.userCallback?e.push(r.register(i,t.theFunction.userCallback).then((()=>o.info(`registering method ${i.name} DONE`))).catch((()=>o.warn(`registering method ${i.name} FAILED`)))):t?.theFunction?.userCallbackAsync&&e.push(r.registerAsync(i,t.theFunction.userCallbackAsync).then((()=>o.info(`registering method ${i.name} DONE`))).catch((()=>o.warn(`registering method ${i.name} FAILED`))))}await Promise.all(e),o.info("Interop is re-announced")}().then((()=>t.setLibReAnnounced({name:"interop"}))).catch((e=>o.warn(`Error while re-announcing interop: ${JSON.stringify(e)}`))):a&&(a({client:u,server:h}),a=void 0)})),d.onLeft((()=>{i.reset()})),d.join(),c}class Ge{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 i;if("number"!=typeof e.methodResponseTimeout&&(e.methodResponseTimeout=3e4),"number"!=typeof e.waitTimeoutMs&&(e.waitTimeoutMs=3e4),this.unwrappedInstance=new Ce(this,void 0,t),this.instance=this.unwrappedInstance.unwrap(),this.clientRepository=new Se(e.logger.subLogger("cRep"),this),this.serverRepository=new xe,3!==t.protocolVersion)throw new Error(`protocol ${t.protocolVersion} not supported`);i=$e(this.instance,t,this.clientRepository,this.serverRepository,e,this),this.readyPromise=i.then((t=>(this.protocol=t,this.client=new ye(this.protocol,this.clientRepository,this.instance,e),this.server=new Ie(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,i,n){return this.client.subscribe(e,t,i,n)}createStream(e,t,i,n){return this.server.createStream(e,t,i,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,i,n,s,r){return this.client.invoke(e,t,i,n,s,r)}waitForMethod(e){const t=new T,i=this.client.methodAdded((n=>{n.name===e&&(i(),t.resolve(n))}));return t.promise}}const Be=["subscribed","success"];class He{connection;logger;peerId;session;subscriptions;readyPromise;constructor(e,t){this.connection=e,this.logger=t,this.peerId=e.peerId,this.subscriptions=[],this.session=e.domain("bus",Be),this.readyPromise=this.session.join(),this.readyPromise.then((()=>{this.watchOnEvent()}))}ready(){return this.readyPromise}publish=(e,t,i)=>{const{routingKey:n,target:s}=i||{},r=this.removeEmptyValues({type:"publish",topic:e,data:t,peer_id:this.peerId,routing_key:n,target_identity:s});this.session.send(r)};subscribe=(e,t,i)=>new Promise(((n,s)=>{const{routingKey:r,target:o}=i||{},a=this.removeEmptyValues({type:"subscribe",topic:e,peer_id:this.peerId,routing_key:r,source:o});this.session.send(a).then((i=>{const{subscription_id:s}=i;this.subscriptions.push({subscription_id:s,topic:e,callback:t,source:o}),n({unsubscribe:()=>(this.session.send({type:"unsubscribe",subscription_id:s,peer_id:this.peerId}),this.subscriptions=this.subscriptions.filter((e=>e.subscription_id!==s)),Promise.resolve())})})).catch((e=>s(e)))}));watchOnEvent=()=>{this.session.on("event",(e=>{const{data:t,subscription_id:i}=e,n=e["publisher-identity"],s=this.subscriptions.find((e=>e.subscription_id===i));s&&(s.source?this.keysMatch(s.source,n)&&s.callback(t,s.topic,n):s.callback(t,s.topic,n))}))};removeEmptyValues(e){const t={};return Object.keys(e).forEach((i=>{void 0!==e[i]&&null!==e[i]&&(t[i]=e[i])})),t}keysMatch(e,t){const i=Object.keys(e);let n=!0;return i.forEach((i=>{e[i]!==t[i]&&(n=!1)})),n}}const Ue=(e,t)=>{const i="object"==typeof window?window.iodesktop??window.glue42gd:void 0,n="object"==typeof window?window.gdPreloadPromise??Promise.resolve():Promise.resolve(),s=P("glue"),r=function(e,t,i){let n;if(k.isNode()){const e=process.env._GD_STARTING_CONTEXT_;if(e)try{n=JSON.parse(e)}catch{}}function s(){if(e.application)return e.application;if(i)return i.applicationName;if("undefined"!=typeof window&&void 0!==window.glue42electron)return window.glue42electron.application;const t=j(10);return k.isNode()?n?n.applicationConfig.name:"NodeJS"+t:"undefined"!=typeof window&&"undefined"!=typeof document?document.title+` (${t})`:t}const r=function(){const r=e.gateway,o=r?.protocolVersion??3,a=r?.reconnectInterval,c=r?.reconnectAttempts;let d=r?.ws;const h=r?.sharedWorker,u=r?.inproc,l=r?.webPlatform??void 0;let p,g,m,f,y;i&&(d=i.gwURL),k.isNode()&&n&&n.gwURL&&(d=n.gwURL),d||h||u||(d="ws://localhost:8385");const w=s();let v=w;void 0!==i?(g=i.windowId,m=i.pid,i.env&&(f=i.env.env,y=i.env.region),v=i.application??"glue-app",p=i.appInstanceId):k.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,v=window?.glue42electron.application??"glue-app",p=window?.glue42electron.instanceId);const b=e.gateway?.replaySpecs??[];b.push(te);let _={application:v,applicationName:w,windowId:g,instance:p,process:m,region:y,environment:f,api:t.version||ie};return e.identity&&(_=Object.assign(_,e.identity)),{identity:_,reconnectInterval:a,ws:d,sharedWorker:h,webPlatform:l,inproc:u,protocolVersion:o,reconnectAttempts:c,replaySpecs:b}}();let o=s();if("undefined"!=typeof window){const e=window,t=e.htmlContainer?`${e.htmlContainer.containerName}.${e.htmlContainer.application}`:e?.glue42gd?.application;t&&(o=t)}return{bus:e.bus??!1,application:o,auth:"string"==typeof e.auth?{token:e.auth}:e.auth?e.auth:k.isNode()&&n&&n.gwToken?{gatewayToken:n.gwToken}:e.gateway?.webPlatform||e.gateway?.inproc||e.gateway?.sharedWorker?{username:"glue42",password:"glue42"}:void 0,logger:function(){let t=e.logger;const n="warn";let s;return t||(t=n),i&&(s=i.consoleLogLevel),"string"==typeof t?{console:s??t,publish:n}:{console:s??t.console??n,publish:t.publish??n}}(),connection:r,metrics:e.metrics??!0,contexts:void 0===e.contexts||"boolean"==typeof e.contexts&&e.contexts?{reAnnounceKnownContexts:!0}:"object"==typeof e.contexts&&Object.assign({},{reAnnounceKnownContexts:!0},e.contexts),version:t.version||ie,libs:t.libs??[],customLogger:e.customLogger}}(e=e||{},t=t||{},i);let o,a,c,d,h,u,l;const p={};function g(e,t,i){l=c.canPublish("trace"),l&&c.trace(`registering ${e} module`);const n=()=>{t.initTime=i.stop(),t.initEndTime=i.endTime,t.marks=i.marks,l&&c.trace(`${e} is ready - ${i.endTime-i.startTime}`)};t.initStartTime=i.startTime,t.ready?t.ready().then((()=>{n()})):n(),Array.isArray(e)||(e=[e]),e.forEach((e=>{p[e]=t,Ue[e]=t}))}function m(){const e=P("metrics"),t=r.metrics,n=i?.getMetricsPublishingEnabled,s=r.connection.identity,a=n||(()=>!0),h=("boolean"!=typeof t&&t.disableAutoAppSystem)??!1;return d=b({connection:t?o:void 0,logger:c.subLogger("metrics"),canUpdateMetric:a,system:"Glue42",service:s?.service??i?.applicationName??r.application,instance:s?.instance??s?.windowId??j(10),disableAutoAppSystem:h,pagePerformanceMetrics:"boolean"!=typeof t?t?.pagePerformanceMetrics:void 0}),g("metrics",d,e),Promise.resolve()}function f(){const e=P("interop"),t={connection:o,logger:c.subLogger("interop")};return a=new Ge(t),G.Interop=a,g(["interop","agm"],a,e),Promise.resolve()}function y(){const e=r.activities&&3===o.protocolVersion;if(r.contexts||e){const e=P("contexts");return h=new pe({connection:o,logger:c.subLogger("contexts"),trackAllContexts:"object"==typeof r.contexts&&r.contexts.trackAllContexts,reAnnounceKnownContexts:"object"==typeof r.contexts&&r.contexts.reAnnounceKnownContexts}),g("contexts",h,e),h}{const e=o.replayer;e&&e.drain(te.name)}}async function w(){if(!r.bus)return Promise.resolve();const e=P("bus");return u=new He(o,c.subLogger("bus")),g("bus",u,e),Promise.resolve()}function v(e){try{return e.forEach((e=>{!function(e,t){const i=P(e),n=t(p);n&&g(e,n,i)}(e.name,e.create)})),Promise.resolve()}catch(e){return Promise.reject(e)}}return n.then((function(){const e=P("logger");return c=new G(`${r.connection.identity?.application}`,void 0,r.customLogger),c.consoleLevel(r.logger.console),c.publishLevel(r.logger.publish),c.canPublish("debug")&&c.debug("initializing glue..."),g("logger",c,e),Promise.resolve(void 0)})).then((function(){const e=P("connection");o=new L(r.connection,c.subLogger("connection"));let t=Promise.resolve(r.auth);return r.connection&&!r.auth&&(i?t=i.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 i;if(e.mark("auth-promise-resolved"),"[object Object]"!==Object.prototype.toString.call(t))throw new Error("Invalid auth object - "+JSON.stringify(t));return i=t,o.login(i)})).then((()=>(g("connection",o,e),r))).catch((e=>{throw o&&o.logout(),e}))})).then((()=>Promise.all([m(),f(),y(),w()]))).then((()=>a.readyPromise)).then((()=>async function(){const t="T42.ACS.RegisterInstance";if(k.isNode()&&void 0===process.env._GD_STARTING_CONTEXT_&&void 0!==e?.application&&a.methods({name:t}).length>0)try{await a.invoke(t,{appName:e?.application,pid:process.pid})}catch(e){const t=e;c.error(`Cannot register as an instance: ${JSON.stringify(t.message)}`)}}())).then((()=>v(r.libs||[]))).then((function(){const e=Object.keys(p).map((e=>{const t=p[e];return t.ready?t.ready():Promise.resolve()}));return Promise.all(e)})).then((function(){const n={coreVersion:ie,version:r.version};s.stop();const l={feedback:e=>{a&&a.invoke("T42.ACS.Feedback",e,"best")},info:n,logger:c,interop:a,agm:a,connection:o,metrics:d,contexts:h,bus:u,version:r.version,userConfig:e,done:()=>(c?.info("done called by user..."),o.logout())};if(l.performance={get glueVer(){return r.version},get glueConfig(){return JSON.stringify(e)},get browser(){return window.performance.timing.toJSON()},get memory(){return window.performance.memory},get initTimes(){const e=E;return Object.keys(e).map((t=>{const i=e[t];return{name:t,duration:i.endTime-i.startTime,marks:i.marks,startTime:i.startTime,endTime:i.endTime}}))}},Object.keys(p).forEach((e=>{const t=p[e];l[e]=t})),l.config={},Object.keys(r).forEach((e=>{l.config[e]=r[e]})),t&&t.extOptions&&Object.keys(t.extOptions).forEach((e=>{l.config[e]=t?.extOptions[e]})),t?.enrichGlue&&t.enrichGlue(l),i&&i.updatePerfData&&i.updatePerfData(l.performance),l.agm){const e=(e,t,i)=>function(){return l.logger.warn(`glue.js - 'glue.agm.${t}' method is deprecated, use 'glue.interop.${i}' instead.`),e.apply(l.agm,arguments)},t=l.agm;t.method_added=e(l.agm.methodAdded,"method_added","methodAdded"),t.method_removed=e(l.agm.methodRemoved,"method_removed","methodRemoved"),t.server_added=e(l.agm.serverAdded,"server_added","serverAdded"),t.server_method_aded=e(l.agm.serverMethodAdded,"server_method_aded","serverMethodAdded"),t.server_method_removed=e(l.agm.serverMethodRemoved,"server_method_removed","serverMethodRemoved")}return l})).catch((e=>Promise.reject({err:e,libs:p})))};"undefined"!=typeof window&&(window.IOConnectCore=Ue),Ue.version=ie,Ue.default=Ue;class qe{constructor(e){this._id=e}get id(){return this._id}_update(e){if(e._id!==this._id)throw Error("Can not update from entity with different id.");this._updateCore(e)}_updateCore(e){}_beforeDelete(e){}}function Je(e){return"number"==typeof e}function Ve(e){return"string"==typeof e}function ze(e){return"object"==typeof e&&null!==e}function Ke(e){return Array.isArray?Array.isArray(e):"[object Array]"===toString.call(e)}function Qe(e){return void 0===e}function Ze(e){return null==e}function Xe(e){return"string"!=typeof e||!e||0===e.length||/^\s*$/.test(e)}function Ye(e){return!0===e||!1===e||"[object Boolean]"===toString.call(e)}function et(e){return!!(e&&e.constructor&&e.call&&e.apply)}function tt(e,t){void 0!==e&&t(e)}class it extends qe{constructor(e,t,i,n){super(e),this._name=e,this._description=n,this._ownerWindow=t,this._helperWindows=i||[]}get name(){return this._name}get description(){return this._description}get helperWindows(){return this._helperWindows.map((e=>this.covertToWindowDef(e)))}get ownerWindow(){return this.covertToWindowDef(this._ownerWindow)}initiate(e,t,i){return this._manager.initiate(this._name,e,t,i)}_updateCore(e){super._updateCore(e),tt(e._description,(e=>this._description=e)),tt(e._ownerWindow,(e=>this._ownerWindow=e)),tt(e._helperWindows,(e=>this._helperWindows=e))}covertToWindowDef(e){var t,i;return{type:null===(t=null==e?void 0:e.id)||void 0===t?void 0:t.type,name:null===(i=null==e?void 0:e.id)||void 0===i?void 0:i.name}}}class nt extends qe{constructor(e,t){super(e),this._name=e,this._appByWindowTypeGetter=t}get name(){return this._name}get config(){return this._appByWindowTypeGetter(this._name)}get windows(){return this._manager.getWindows({type:this._name})}create(e,t){const i=Object.assign({type:this.name,name:this.name,isIndependent:!1},t);return this._manager.createWindow(e,i)}}class st{constructor(e,t){this.entity=e,this.context=t}}class rt{constructor(e){this.type=e}}class ot extends rt{constructor(e,t){super(ct.StatusChange),this.newStatus=e,this.oldStatus=t}}class at extends rt{constructor(e,t,i){super(ct.ActivityContextChange),this.context="string"==typeof e?JSON.parse(e):e,this.updated=t,this.removed=i}}class ct{}ct.Added="added",ct.Removed="removed",ct.Updated="updated",ct.Closed="closed",ct.StatusChange="statusChange",ct.ActivityContextChange="activityContextUpdate",ct.ActivityWindowEvent="activityWindowEvent",ct.ActivityWindowJoinedActivity="joined",ct.ActivityWindowLeftActivity="left";class dt{}dt.Created="created",dt.Started="started",dt.Destroyed="destroyed";class ht{constructor(e){this._activity=e}register(e,t){this._ensureHasAgm(),ht.AGM.register(e,t)}servers(){return this._ensureHasAgm(),Ze(this._activity)?[]:this._activity.windows.map((e=>e.instance))}methods(){if(this._ensureHasAgm(),Ze(this._activity))return[];const e=this._activity.windows,t=[],i=[];return e.forEach((e=>{this.methodsForWindow(e).forEach((e=>{-1===t.indexOf(e.name)&&(t.push(e.name),i.push(e))}))})),i}methodsForWindow(e){return this._ensureHasAgm(),e.instance?ht.AGM.methodsForInstance(e.instance):[]}invoke(e,t,i,n,s,r){this._ensureHasAgm();const o=this.servers();if(Ze(i)&&(i="activity.all"),Ve(i))if("activity.all"===i);else{if("activity.best"!==i){if("all"===i||"best"===i)return function(e,t,i){if("function"!=typeof t&&"function"!=typeof i)return e;"function"!=typeof t?t=()=>{}:"function"!=typeof i&&(i=()=>{}),e.then(t,i)}(ht.AGM.invoke(e,t,i,n),s,r);throw new Error("Invalid invoke target "+i)}{const t=o.filter((t=>ht.AGM.methodsForInstance(t).filter((t=>t.name===e)).length>0));t.length>0&&t[0]}}else if(Ke(i)){if(i.length>=0){const e=i[0];if(this._isInstance(e))i.map((e=>e));else{if(!this._isActivityWindow(e))throw new Error("Unknown target object");i.map((e=>e.instance))}}}else if(this._isInstance(i));else{if(!this._isActivityWindow(i))throw new Error("Unknown target object");i.instance}throw new Error("Not implemented")}unregister(e){return this._ensureHasAgm(),ht.AGM.unregister(e)}createStream(e,t,i){this._ensureHasAgm(),ht.AGM.createStream(e,{subscriptionAddedHandler:t,subscriptionRemovedHandler:i,subscriptionRequestHandler:void 0})}subscribe(e,t,i){return this._ensureHasAgm(),ht.AGM.subscribe(e,t)}_ensureHasAgm(){if(Ze(ht.AGM))throw new Error("Agm should be configured to be used in activity")}_isInstance(e){return void 0!==e.application}_isActivityWindow(e){return void 0!==e.instance}}class ut{constructor(e,t,i){this._manager=e,this._ownerActivityId=t,this._state=i}get ownerId(){return this._state.ownerId}get windowIds(){return this._state.windowIds}get frameColor(){return this._state.frameColor}get context(){return this._state.context}get tag(){return this._state.tag}detach(e){e=e||{};const t={};return Object.keys(this._state).forEach((e=>{t[e]=this._state[e]})),t.context=e.context||t.context,t.frameColor=e.frameColor||t.frameColor,this._manager.detachActivities(this._ownerActivityId,t)}}const lt=e=>{setTimeout(e,0)};function pt(e,t){if(!et(t))return e;e.then((e=>{lt((()=>{t(null,e)}))}),(e=>{lt((()=>{t(e,null)}))}))}class gt extends qe{constructor(e,t,i,n,s){super(e),this._id=e,this._actType=t,this._status=i,this._context=n,this._ownerId=s,this._agm=new ht(this)}get type(){if(this._manager)return this._manager.getActivityType(this._actType)}get context(){return this._context}get status(){return this._status}get owner(){return this._ownerId?this._manager.getWindows({id:this._ownerId})[0]:null}get windows(){return this._manager.getWindows({activityId:this._id})}get agm(){return this._agm}addWindow(e,t){return this._manager.addWindowToActivity(this,e,t)}createWindow(e,t){return this._manager.createWindow(this,e,t)}createStackedWindows(e,t,i){return this._manager.createStackedWindows(this,e,t,i)}leave(e,t){return this._manager.leaveWindowFromActivity(this,e,t)}getWindowsByType(e){const t={activityId:this._id,type:e};return this._manager.getWindows(t)}setContext(e,t){return this._manager.setActivityContext(this,e,t)}updateContext(e,t){return this._manager.updateActivityContext(this,e,t)}onStatusChange(e){return this._manager.subscribeActivityEvents(((t,i,n)=>{t.id===this.id&&e(t,i,n)}))}onWindowEvent(e){return this._manager.subscribeWindowEvents(((t,i,n)=>{t.id===this.id&&e(t,i,n)}))}onContextChanged(e){this._manager.subscribeActivityContextChanged(((t,i,n,s)=>{t.id===this.id&&e(i,n,s,t)}));try{e(this.context,this.context,[],this)}catch(e){return}}stop(){this._manager.stopActivity(this)}clone(e){return this._manager.clone(this,e)}attach(e,t){let i;return i="string"==typeof e?e:e.id,this._manager.attachActivities(i,this.id,t)}onActivityAttached(e){this._manager.subscribeActivitiesAttached(((t,i,n)=>{t===this._id&&e(n)}))}onDetached(e){this._manager.subscribeActivitiesDetached(((t,i,n)=>{i.id===this._id&&e(t,n)}))}_updateCore(e){super._updateCore(e),tt(e._actType,(e=>this._actType=e)),tt(e._context,(e=>this._context=e)),tt(e._ownerId,(e=>this._ownerId=e)),!e._status||this._status&&this._status.state===e._status.state||(this._status=e._status)}_updateDescriptors(e){this._attached=e.map((e=>new ut(this._manager,this._id,e)))}get attached(){return this._attached}setFrameColor(e,t){return pt(new Promise(((t,i)=>{let n=this.windows.length;0===n&&t(this),this.windows.forEach((i=>{i.underlyingWindow.setFrameColor(e,(()=>{n--,n<=0&&t(this)}))})),setTimeout((()=>{n>0&&i(this.id+" - timed out waiting for setFrameColor with"+e)}),5e3)})),t)}getFrameColor(){return this.windows&&0!==this.windows.length?this.windows[0].underlyingWindow.frameColor:""}}class mt{}mt.Trace="trace",mt.Debug="debug",mt.Info="info",mt.Warn="warn",mt.Error="error";class ft{static GetNamed(e){return new ft(e)}static Get(e){return new ft(ft.GetTypeName(e))}constructor(e){this._name=e,Ze(ft.GlueLogger)||(this._glueLogger=ft.GlueLogger.subLogger(e))}trace(e){Ze(this._glueLogger)?ft.Level===mt.Trace&&console.info(this._getMessage(e,mt.Trace)):this._glueLogger.trace(e)}debug(e){Ze(this._glueLogger)?ft.Level!==mt.Debug&&ft.Level!==mt.Trace||console.info(this._getMessage(e,mt.Debug)):this._glueLogger.debug(e)}info(e){Ze(this._glueLogger)?ft.Level!==mt.Debug&&ft.Level!==mt.Trace&&ft.Level!==mt.Info||console.info(this._getMessage(e,mt.Info)):this._glueLogger.info(e)}warn(e){Ze(this._glueLogger)?ft.Level!==mt.Debug&&ft.Level!==mt.Trace&&ft.Level!==mt.Info&&ft.Level!==mt.Warn||console.info(this._getMessage(e,mt.Info)):this._glueLogger.warn(e)}error(e){Ze(this._glueLogger)?(console.error(this._getMessage(e,mt.Error)),console.trace()):this._glueLogger.error(e)}_getMessage(e,t){return"["+t+"] "+this._name+" - "+e}static GetTypeName(e){const t=/function (.{1,})\(/.exec(e.constructor.toString());return t&&t.length>1?t[1]:""}}ft.Level=mt.Info;class yt extends qe{constructor(e,t,i,n,s,r,o,a){super(e),this._logger=ft.Get("window"),this._type=i,this._activityId=n,this._name=t,this._instance=s,this._isIndependent=r,this._windowGetter=o,this._hcWindowId=a}getBounds(){return this._manager.getWindowBounds(this.id)}get name(){return this._name}get isIndependent(){return this._isIndependent}get type(){if(this._manager)return this._manager.getWindowType(this._type)}get activity(){if(!Qe(this._activityId))return this._manager.getActivityById(this._activityId)}get isOwner(){const e=this.activity;return!Qe(e)&&e.owner.id===this.id}setVisible(e,t){return this._manager.setWindowVisibility(this.id,e)}activate(e){return this._manager.activateWindow(this.id,e)}setBounds(e,t){return this._manager.setWindowBounds(this.id,e,t)}close(){return this._manager.closeWindow(this.id)}get instance(){return this._instance}get underlyingWindow(){const e=this._windowGetter();return e||{id:this._hcWindowId}}onActivityJoined(e){this._subscribeForActivityWindowEvent(ct.ActivityWindowJoinedActivity,e)}onActivityRemoved(e){this._subscribeForActivityWindowEvent(ct.ActivityWindowLeftActivity,e)}_updateCore(e){tt(e._activityId,(e=>this._activityId=e)),tt(e._isIndependent,(e=>this._isIndependent=e)),tt(e._hcWindowId,(e=>this._hcWindowId=e)),tt(e._type,(e=>this._type=e)),tt(e._name,(e=>this._name=e)),Ze(e._instance)||(this._instance=e._instance)}_subscribeForActivityWindowEvent(e,t){this._manager.subscribeWindowEvents(((i,n,s)=>{n.id===this.id&&s===e&&t(i)}))}_beforeDelete(e){this._hcWindowId=e._hcWindowId}}class wt{constructor(e,t,i){this.state=e,this.message=t,this.time=i}getState(){return this.state}getMessage(){return this.message}getTime(){return this.time}}const vt="error",bt="add-types",_t="created",It="destroyed",Ct="initiated",At="joined",St="activity-joined",xt="left",kt="owner-changed",Tt="add-peer-factories",Et="peer-factories-added",Pt="peer-factories-removed",Mt="peer-created";class Rt{static activityTypeGwMessageEntityToActivityType(e,t){const i=e=>new nt(e,void 0);return new it(e.name,e.owner_type&&i(e.owner_type),e.helper_types&&e.helper_types.map(i),t)}static peerFactoryGwMessageEntityToWindowType(e){return new nt(e.peer_type,(e=>{}))}static activityGwMessageToActivity(e,t){const i=void 0!==e.owner?e.owner.peer_id:e.owner_id;return new gt(e.activity_id,e.activity_type,t,e.context_snapshot,i)}static activityToActivityStatusChangeEvent(e){return new st(e,new ot(e.status,void 0))}constructor(e){if(this._activityChangeCallbacks=[],this._activityTypeStatusChangeCallbacks=[],this._activityWindowChangeCallbacks=[],this._windowTypeStatusChangeCallbacks=[],this._peerIdAndFactoryIdToPeerType={},this._peerFactoriesRegisteredByUs={},this._gw3Subscriptions=[],this._contextSubscriptions={},this._activityTypesInitiatedFromMe={},this._config=e,this._connection=e.connection,this._logger=e.logger,this._contexts=e.contexts,this._windows=e.windows,this._sessionJoinedPromise=new Promise((e=>{this._sessionJoinedPromiseResolve=e})),this._activityJoinedPromise=new Promise((e=>{this._activityJoinedPromiseResolve=e})),this._config.activityId||this._activityJoinedPromiseResolve({}),this._gw3Session=this._connection.domain("activity",["joined","initiated","peer-created","token"]),"undefined"!=typeof window){const e=window.glue42gd;e&&e.activityInfo&&("function"==typeof e.addRefreshHandler&&e.addRefreshHandler(((t,i)=>{this._gw3Session.send({type:"reload"}).then((n=>{if(n.token){try{e.setGWToken(n.token)}catch(e){return void i(e.message||e)}t()}else i("Expected gateway token for refreshing.")}),i)})),e&&"function"==typeof e.addWillNavigateHandler&&e.addWillNavigateHandler(((t,i)=>{this._gw3Session.send({type:"reload"}).then((n=>{if(n.token){try{e.setGWToken(n.token)}catch(e){return void i(e.message||e)}t()}else i("Expected gateway token for refreshing.")}),i)})))}}get bridgeType(){return"GW3"}init(){this.forwardActivityTypeMessagesToStatusEventHandlers(),this.subscribe(_t,this.handleActivityCreatedMessage),this.subscribe(It,this.handleActivityDestroyedMessage),this.forwardActivityMessagesToStatusEventHandlers(),this.forwardActivityCreatedAndJoinedActivityToActivityWindowEventHandlers(),this.forwardPeerFactoryMessagesToStatusEventHandlers(),this.forwardPeerFactoryMessagesToPeerFactoryRequests(),this.subscribe(Et,this.handlePeerFactoriesAdded),this.subscribe(Pt,this.handlePeerFactoriesRemoved),this.forwardActivityWindowMessagesToEventHandlers(),this.subscribe("dispose-peer",(()=>{if("dispose"!==this._config.disposeRequestHandling){if("exit"===this._config.disposeRequestHandling){if(this._windows&&void 0!==this._windows.my())return void this._windows.my().close();if("undefined"!=typeof window&&"function"==typeof window.close)return void window.close();if("undefined"!=typeof process&&"function"==typeof process.exit)return void process.exit()}}else this.dispose()})),this._gw3Session.onJoined((()=>{"trackMyOnly"===this._config.mode||"trackMyTypeAndInitiatedFromMe"===this._config.mode?this._sessionJoinedPromiseResolve(this):this._gw3Session.send({type:"subscribe",activity_types:"trackAll"===this._config.mode?[]:"trackTypes"===this._config.mode?this._config.typesToTrack:[]}).then((()=>{this._sessionJoinedPromiseResolve(this)}))})),this._gw3Session.join()}dispose(){this._gw3Subscriptions.forEach((e=>e&&this._connection.off(e))),this._gw3Subscriptions.length=0}ready(){return Promise.all([this._sessionJoinedPromise,this._activityJoinedPromise])}initReady(){return this._sessionJoinedPromise}onActivityTypeStatusChange(e){this._activityTypeStatusChangeCallbacks.push(e)}registerActivityType(e,t,i,n,s){const r={};r.name=e;const o=e=>({type:e.type,name:e.name,configuration:e});return r.owner_type=o(t),r.helper_types=i.map(o),this._gw3Session.send({type:bt,types:[r]}).then((()=>{const e=Rt.activityTypeGwMessageEntityToActivityType(r,s);return this.invokeCallbacks(this._activityTypeStatusChangeCallbacks,new st(e,new rt(ct.Added)),bt),e}))}unregisterActivityType(e){return this._gw3Session.send({type:"remove-types",types:[e]}).then((()=>{const t=new it(e,void 0,void 0,void 0);this.invokeCallbacks(this._activityTypeStatusChangeCallbacks,new st(t,new rt(ct.Removed)),bt)}))}onWindowTypeStatusChange(e){this._windowTypeStatusChangeCallbacks.push(e)}registerWindowFactory(e,t,i){if(this._peerFactoriesRegisteredByUs[e])return Promise.reject(new Error(`Factory for windowType ${e} already registered.`));this._peerFactoriesRegisteredByUs[e]=t;const n={id:e,peer_type:e,configuration:i};return this._gw3Session.send({type:Tt,factories:[n]}).then((()=>{this.invokeCallbacks(this._windowTypeStatusChangeCallbacks,new st(Rt.peerFactoryGwMessageEntityToWindowType(n),new rt(ct.Added)),Tt)})).catch((()=>{delete this._peerFactoriesRegisteredByUs[e]}))}unregisterWindowFactory(e){return this._peerFactoriesRegisteredByUs[e]?(delete this._peerFactoriesRegisteredByUs[e],this._gw3Session.send({type:"remove-peer-factories",factory_ids:[e]}).then((()=>{this.invokeCallbacks(this._windowTypeStatusChangeCallbacks,new st(new nt(e,void 0),new rt(ct.Removed)),Tt)}))):Promise.reject(new Error(`Factory for windowType ${e} not registered.`))}onActivityStatusChange(e){this._activityChangeCallbacks.push(e)}initiateActivity(e,t,i){const n={type:"create",activity_type:e,initial_context:t};return this.isOverrideTypeDefinition(i)?n.types_override={owner_type:{type:i.owner.type,name:i.owner.name,configuration:i.owner},helper_types:i.helpers&&i.helpers.map((e=>({type:e.type,name:e.name,configuration:e})))}:n.configuration=i&&i.map((e=>({type:e.type,name:e.name,configuration:e}))),this.sendCreateAndMapResultingMessagesToPromise(n,Ct,((e,t)=>e.request_id===t),_t,((e,t,i)=>e.activity_id===i.activity_id),It,((e,t,i)=>e.activity_id===i.activity_id),(e=>e.activity_id),null).then((t=>"trackMyTypeAndInitiatedFromMe"!==this._config.mode||this._activityTypesInitiatedFromMe[e]?t:(this._activityTypesInitiatedFromMe[e]=!0,this._gw3Session.send({type:"subscribe",activity_types:[e]}).then((()=>t)))))}stopActivity(e){return this._gw3Session.send({type:"destroy",activity_id:e.id,reason_uri:"com.tick42.glue.activity.constants.destroyReason.general",reason:"Destroying activity"}).then((e=>!0))}updateActivityContext(e,t,i,n){if(i)return this._contexts.set(e.id,t);n=n||[];for(const e of n)t[e]=null;return this._contexts.update(e.id,t)}announceWindow(e,t){throw new Error("Invalid operation 'announceWindow' for GW3 protocol")}registerWindow(e,t,i){let n=void 0!==this._connection.gatewayToken;const s=this._connection.peerId;if("undefined"!=typeof window){const e=window.glue42gd;e&&(n=void 0!==e.activityInfo)}return n&&this._gw3Session.send({type:"ready"}),this.invokeCallbacks(this._activityWindowChangeCallbacks,new st(new yt(s,t,e,void 0,this.getAgmInstance(s),i,this.generateWindowGetter(s),void 0),new rt(ct.Added)),"register window"),Promise.resolve(s)}onActivityWindowChange(e){this._activityWindowChangeCallbacks.push(e)}createWindow(e,t){t.layout||(t.left||t.width||t.height||t.top)&&(t.layout={mode:"pixels",cellSize:1});const i=i=>{if(e)return this.joinActivity(e,i,t.name).then((()=>i))};return this.sendCreateAndMapResultingMessagesToPromise({type:"create-peer",peer_type:t.type,peer_name:t.name||t.type,configuration:t,activity_id:e},void 0,void 0,Mt,((e,t)=>e.request_id===t),void 0,void 0,(e=>e.created_id),i).then(i)}closeWindow(e){return this._gw3Session.send({type:"destroy-peer",destroy_peer_id:e}).then((e=>{}))}getAnnouncementInfo(){let e=this._config.activityId||this._config.announcementInfo&&this._config.announcementInfo.activityId,t=this._config.announcementInfo&&this._config.announcementInfo.activityWindowType,i=this._config.announcementInfo&&this._config.announcementInfo.activityWindowIndependent,n=this._config.announcementInfo&&this._config.announcementInfo.activityWindowName;if("undefined"!=typeof window&&void 0!==window.location&&window.location.search&&"function"==typeof URLSearchParams){const s=new URLSearchParams(location.search.slice(1));t=t||s.get("t42PeerType"),t=t||s.get("t42ActivityWindowType"),void 0===i&&(i=s.get("t42ActivityWindowIndependent")),n=n||s.get("t42ActivityWindowName"),e=e||s.get("t42ActivityId")}return t=t||"unknown",i=i||!1,n=n||this._connection.peerId,{activityWindowId:void 0,activityId:e,activityWindowType:t,activityWindowIndependent:i,activityWindowName:n}}joinActivity(e,t,i){const n=i&&{name:i}||{};return this._gw3Session.send({type:"join-activity",target_id:t,activity_id:e,...n}).then((()=>{this.invokeCallbacks(this._activityWindowChangeCallbacks,new st(new yt(t,void 0,void 0,e,this.getAgmInstance(t),void 0,this.generateWindowGetter(t),void 0),new rt(ct.ActivityWindowJoinedActivity)),"activity joined - ActivityWindow"),this.invokeCallbacks(this._activityChangeCallbacks,new st(new gt(e,void 0,new wt("created",void 0,void 0),void 0,void 0),new rt(ct.Updated)),"activity joined - Activity")}))}leaveActivity(e,t){return this._gw3Session.send({type:"leave-activity",target_id:t,activity_id:e}).then((()=>{this.invokeCallbacks(this._activityWindowChangeCallbacks,new st(new yt(t,void 0,void 0,null,this.getAgmInstance(t),void 0,this.generateWindowGetter(t),void 0),new rt(ct.ActivityWindowLeftActivity)),"activity left - ActivityWindow"),this.invokeCallbacks(this._activityChangeCallbacks,new st(new gt(e,void 0,new wt("created",void 0,void 0),void 0,void 0),new rt(ct.Updated)),"activity left - Activity")}))}getActivityTypes(){return Promise.resolve([])}getWindowTypes(){return Promise.resolve([])}getActivities(){return Promise.resolve([])}getActivityWindows(){return Promise.resolve([])}createStackedWindows(e,t,i){}getWindowBounds(e){}setWindowBounds(e,t){}activateWindow(e,t){}setWindowVisibility(e,t){}cloneActivity(e,t){}attachActivities(e,t,i){return this._gw3Session.send({type:"merge",into:t,merge:e})}detachActivities(e,t){return this._gw3Session.send({type:"split",from:e}).then((()=>""))}onActivitiesAttached(e){}onActivitiesDetached(e){}onActivityAttachedDescriptorsRefreshed(e){}getAttachedDescriptors(){return Promise.resolve([])}getRandomRequestId(){return this._connection.peerId+":"+Math.floor(1e9*Math.random())}forwardAddedAndRemovedMessagesToEventHandler(e,t,i,n){const s=e=>t=>new st(t,new rt(e?ct.Added:ct.Removed));return[e&&this.forwardMessageToEventHandler(e,(e=>i(e,!0)),s(!0),n),t&&this.forwardMessageToEventHandler(t,(e=>i(e,!1)),s(!1),n)].filter((e=>e))}forwardMessageToEventHandler(e,t,i,n){return this.subscribe(e,(e=>{t(e).forEach((t=>n.forEach((n=>n(i(t,e))))))}))}sendCreateAndMapResultingMessagesToPromise(e,t,i,n,s,r,o,a,c){const d=this.getRandomRequestId();let h,u;const l=new Promise(((e,t)=>{h=e,u=t}));let p,g,m,f,y=null;const w=()=>{this.dropSubscription(p),c||this.dropSubscription(g),this.dropSubscription(m),this.dropSubscription(f)};p=t&&this.subscribe(t,(e=>{i(e,d)&&(y=e,this.dropSubscription(p))}));let v=!1;g=this.subscribe(n,(e=>{s(e,d,y)&&(v?c&&c(a(e)):(v=!0,h(a(e))))})),m=r&&this.subscribe(r,(e=>{o(e,d,y)&&u(e)})),f=r&&this.subscribe(vt,(e=>{e.request_id===d&&u(e)})),e.request_id=d;const b=this._gw3Session.send(e).then((()=>l));return b.then(w,w),b}peerFactoryIdAndOwnerIdToWindowType(e,t){const i=this._peerIdAndFactoryIdToPeerType[t+":"+e];return i?new nt(i,void 0):null}subscribe(e,t){const i=this._connection.on(e,(e=>t.bind(this)(e)));return this._gw3Subscriptions.push(i),i}dropSubscription(e){e&&(this._connection.off(e),delete this._gw3Subscriptions[this._gw3Subscriptions.indexOf(e)])}invokeCallbacks(e,t,i){e.forEach((e=>{try{e(t)}catch(e){this._logger.error(`Error in ${i||t.context.type} callback: `+JSON.stringify(e))}}))}handleActivityCreatedMessage(e){e.context_id?this._contextSubscriptions[e.activity_id]||this.subscribeToContext(e):this._logger.error("Activity created with unknown context_id: "+e.activity_id)}async subscribeToContext(e){const t=e.activity_id;this._contextSubscriptions[t]=await this._contexts.subscribe(t,((e,i,n)=>{const s=new st(new gt(t,void 0,void 0,e,void 0),new at(e,i,n));this.invokeCallbacks(this._activityChangeCallbacks,s,"context updated")}))}handleActivityDestroyedMessage(e){const t=this._contextSubscriptions[e.activity_id];"function"==typeof t&&t(),delete this._contextSubscriptions[e.activity_id]}handlePeerFactoriesAdded(e){e.factories.forEach((t=>{this._peerIdAndFactoryIdToPeerType[e.owner_id+":"+t.id]=t.peer_type}))}handlePeerFactoriesRemoved(e){e.factory_ids.forEach((t=>{delete this._peerIdAndFactoryIdToPeerType[e.owner_id+":"+t]}))}forwardActivityTypeMessagesToStatusEventHandlers(){this.forwardAddedAndRemovedMessagesToEventHandler("types-added","types-removed",((e,t)=>t?e.types.map((e=>Rt.activityTypeGwMessageEntityToActivityType(e,void 0))):e.types.map((e=>new it(e.name,void 0,void 0,void 0)))),this._activityTypeStatusChangeCallbacks)}forwardActivityCreatedAndJoinedActivityToActivityWindowEventHandlers(){for(const e of[_t,At,kt])this.forwardMessageToEventHandler(e,(e=>[e.owner||{...e,type:e.peer_type,name:e.peer_name,peer_id:e.owner_id}].concat(e.participants||[]).map((t=>new yt(t.peer_id,t.name,t.type,e.activity_id,this.getAgmInstance(t.peer_id),void 0,this.generateWindowGetter(t.peer_id),void 0)))),((e,t)=>new st(e,new rt(ct.ActivityWindowJoinedActivity))),this._activityWindowChangeCallbacks)}forwardActivityMessagesToStatusEventHandlers(){for(const e of[_t,At])this.forwardMessageToEventHandler(e,(e=>[Rt.activityGwMessageToActivity(e,new wt("started","",new Date))]),((e,t)=>Rt.activityToActivityStatusChangeEvent(e)),this._activityChangeCallbacks);this.forwardMessageToEventHandler(It,(e=>[Rt.activityGwMessageToActivity(e,new wt("destroyed",e.reason,new Date))]),((e,t)=>Rt.activityToActivityStatusChangeEvent(e)),this._activityChangeCallbacks),this.forwardMessageToEventHandler(Ct,(e=>[Rt.activityGwMessageToActivity(e,new wt("created","",new Date))]),((e,t)=>Rt.activityToActivityStatusChangeEvent(e)),this._activityChangeCallbacks),this.forwardMessageToEventHandler(kt,(e=>[Rt.activityGwMessageToActivity(e,new wt("created","",new Date))]),((e,t)=>Rt.activityToActivityStatusChangeEvent(e)),this._activityChangeCallbacks)}forwardPeerFactoryMessagesToStatusEventHandlers(){this.forwardAddedAndRemovedMessagesToEventHandler(Et,Pt,((e,t)=>t?e.factories.map(Rt.peerFactoryGwMessageEntityToWindowType):e.factory_ids.map((t=>this.peerFactoryIdAndOwnerIdToWindowType(t,e.owner_id))).filter((e=>null!=e))),this._windowTypeStatusChangeCallbacks)}forwardPeerFactoryMessagesToPeerFactoryRequests(){this.subscribe("peer-requested",(e=>{const t=this._peerFactoriesRegisteredByUs[e.peer_factory];if(t)try{const i=e.configuration||{};i.gateway_token=i.gateway_token||e.gateway_token,i.peer_factory=i.peer_factory||e.peer_factory;const n=t({activityId:e.activity&&e.activity.id,activityType:e.activity&&e.activity.type,type:e.configuration&&e.configuration.type,gwToken:i.gateway_token,configuration:i});n&&n.then&&n.catch&&n.catch((t=>this._gw3Session.send({type:vt,request_id:e.request_id,reason:t&&(t.message||JSON.stringify(t))})))}catch(t){this._gw3Session.send({type:vt,request_id:e.request_id,reason:t&&(t.message||JSON.stringify(t))})}else this._gw3Session.send({type:vt,request_id:e.request_id,reason:`Unknown peer factory ${e.peer_factory}`})}))}forwardActivityWindowMessagesToEventHandlers(){for(const e of[St,At])this.subscribe(e,(t=>{const i=e===St?t.joined_id:t.peer_id,n=e===St?t.joined_type:t.peer_type,s=e===St?t.joined_name:t.peer_name,r=new yt(i,s,n,t.activity_id,this.getAgmInstance(i),void 0,this.generateWindowGetter(i),void 0);this._contextSubscriptions[t.activity_id]?e===At&&this._activityJoinedPromiseResolve({}):this.subscribeToContext(t).then((()=>{e===At&&this._activityJoinedPromiseResolve({})})),this.invokeCallbacks(this._activityWindowChangeCallbacks,new st(r,new rt(ct.ActivityWindowJoinedActivity)),e)}));this.subscribe(xt,(e=>{const t=new yt(e.left_id,void 0,void 0,null,this.getAgmInstance(e.left_id),void 0,this.generateWindowGetter(e.left_id),void 0);this.invokeCallbacks(this._activityWindowChangeCallbacks,new st(t,new rt(ct.ActivityWindowLeftActivity)),xt)})),this.forwardAddedAndRemovedMessagesToEventHandler(Mt,void 0,(e=>[new yt(e.created_id,void 0,void 0,void 0,void 0,void 0,this.generateWindowGetter(e.created_id),void 0)]),this._activityWindowChangeCallbacks)}getAgmInstance(e){return this._config.agm.servers().find((t=>t.peerId===e||t.windowId===e))}generateWindowGetter(e){return()=>{const t=this.getAgmInstance(e);if(!t)return;const i=t.windowId;return this._config.windows.list().filter((e=>e.id===i))[0]}}isOverrideTypeDefinition(e){return void 0!==e&&!!e.owner}}class Nt{constructor(e,t){this._myAttached=[],this._myDetached=[],this._myAttachedTo=[],this._myDetachedFrom=[],this._myActivityFrameColorChanged=[],this._myActivityJoinedCallbacks=[],this._myActivityRemovedCallbacks=[],this._myContextUpdateCallbacks=[],this._logger=ft.Get(this),this._m=e,e.ready().then((e=>{e.subscribeActivityContextChanged(this._subscribeMyContextChanged.bind(this)),e.subscribeWindowEvents(this._subscribeMyWindowEvent.bind(this)),e.subscribeActivitiesAttached(this._subscribeActivitiesAttached.bind(this)),e.subscribeActivitiesDetached(this._subscribeActivitiesDetached.bind(this)),t&&t.onWindowFrameColorChanged(this._subscribeWindowFrameColorChanged.bind(this))}))}get window(){if(Ze(this._w)){const e=this._m.announcedWindows;e.length>0&&(this._w=e[0])}return this._w}get activity(){const e=this.window;if(!Ze(e))return e.activity}createWindow(e){return this._m.createWindow(this.activity,e)}createStackedWindows(e,t){return this._m.createStackedWindows(this.activity,e,t)}get context(){const e=this.activity;return Qe(e)?{}:e.context}updateContext(e,t){const i=this.activity;return Qe(i)?new Promise(((e,t)=>{t("Not in activity")})):i.updateContext(e,t)}setContext(e,t){const i=this.activity;return Qe(i)?new Promise(((e,t)=>{t("Not in activity")})):i.setContext(e,t)}onActivityJoined(e){this._myActivityJoinedCallbacks.push(e);const t=this.window;Ze(t)||Ze(t.activity)||e(t.activity)}onActivityLeft(e){this._myActivityRemovedCallbacks.push(e)}onContextChanged(e){this._myContextUpdateCallbacks.push(e);const t=this.window;if(Ze(t))return;const i=t.activity;Ze(i)||e(i.context,i.context,[],i)}clone(e,t){const i=this.activity;return this._m.clone(i,e,t)}attach(e,t){let i;return i="string"==typeof e?e:e.id,this._m.attachActivities(i,this.activity.id,t)}onActivityAttached(e){this._myAttached.push(e)}onActivityDetached(e){this._myDetached.push(e)}onAttachedToActivity(e){this._myAttachedTo.push(e)}onDetachedFromActivity(e){this._myDetachedFrom.push(e)}get attached(){return this.activity?this.activity.attached:[]}setFrameColor(e,t){return this.activity?this.activity.setFrameColor(e,t):Promise.resolve(null)}getFrameColor(){return this.activity?this.activity.getFrameColor():""}onFrameColorChanged(e){this._myActivityFrameColorChanged.push(e)}_subscribeMyContextChanged(e,t,i,n){const s=this.window;if(Ze(s))return;const r=s.activity;Ze(r)||e.id===r.id&&this._notifyMyContextChanged(e,t,i,n)}_subscribeMyWindowEvent(e,t,i){Ze(this.window)||this.window.id===t.id&&(i===ct.ActivityWindowJoinedActivity?(this._notifyMyWindowEvent(e,this._myActivityJoinedCallbacks),this._notifyMyContextChanged(e,e.context,null,null)):i===ct.ActivityWindowLeftActivity&&this._notifyMyWindowEvent(e,this._myActivityRemovedCallbacks))}_notifyMyWindowEvent(e,t){t.forEach((t=>{try{t(e,event)}catch(e){this._logger.warn("error in user callback "+e)}}))}_notifyMyContextChanged(e,t,i,n){i=i||{},n=n||[],this._myContextUpdateCallbacks.forEach((s=>{try{s(t,i,n,e)}catch(e){this._logger.warn("error in user callback "+e)}}))}_notifyAttached(e){this._myAttached.forEach((t=>{try{t(e)}catch(e){this._logger.warn("error in user callback "+e)}}))}_notifyDetached(e){this._myDetached.forEach((t=>{try{t(e)}catch(e){this._logger.warn("error in user callback "+e)}}))}_notifyAttachedTo(e){this._myAttachedTo.forEach((t=>{try{t(this.activity,e)}catch(e){this._logger.warn("error in user callback "+e)}}))}_notifyDetachedFrom(e,t,i){this._myDetachedFrom.forEach((n=>{try{n(e,t,i)}catch(e){this._logger.warn("error in user callback "+e)}}))}_subscribeActivitiesAttached(e,t){const i=this.window;if(Ze(i))return;const n=i.activity;Ze(n)||e.id===n.id&&(t.windowIds.indexOf(i.id)>=0?this._notifyAttachedTo(t):this._notifyAttached(t))}_subscribeActivitiesDetached(e,t,i){const n=this.window;if(Ze(n))return;const s=n.activity;Ze(s)||(t.id===s.id&&this._notifyDetached(i),e.id===s.id&&this._notifyDetachedFrom(e,t,i))}_subscribeWindowFrameColorChanged(e){const t=this.activity;t&&t.owner&&t.owner.underlyingWindow.id===e.id&&this._myActivityFrameColorChanged.forEach((t=>{t(e.frameColor)}))}}class jt{constructor(e,t){if(this._logger=ft.Get("ReadyMarker ["+e+"]"),this._logger.debug("Initializing ready marker for '"+e+"' with "+t+" signals to wait"),t<=0)throw new Error("Invalid signal number. Should be > 0");this._signals=t,this._callbacks=[],this._name=e}setCallback(e){this.isSet()?e(void 0):this.isError()?e(this._error):this._callbacks.push(e)}signal(e){if(this._logger.debug("Signaled - "+e+" - signals left "+(this._signals-1)),this._signals--,this._signals<0)throw new Error("Error in ready marker '"+this._name+" - signals are "+this._signals);this.isSet()&&this._callbacks.forEach((e=>{e(void 0)}))}error(e){this._error=e,this._callbacks.forEach((t=>{t(e)}))}isSet(){return!this.isError()&&0===this._signals}isError(){return!Qe(this._error)}getError(){return this._error}}class Wt{constructor(e){this._items={},this._listeners=[],this._processNew=e}addOne(e){this.add([e])}add(e){e.forEach((e=>{this.process(new st(e,new rt(ct.Added)))}))}process(e){const t=e.context,i=t.type,n=e.entity;if(i===ct.StatusChange&&!t.oldStatus){const e=this._items[n.id];e&&(t.oldStatus=e.status)}i===ct.StatusChange&&t.oldStatus&&t.newStatus&&t.oldStatus.state===t.newStatus.state&&(t.type=ct.Updated),"undefined"==typeof htmlContainer&&(i===ct.ActivityWindowJoinedActivity&&this._items[n.id]&&this._items[n.id].activity&&(t.type=ct.Updated),i===ct.ActivityWindowLeftActivity&&this._items[n.id]&&!this._items[n.id].activity&&(t.type=ct.Updated));const s=this._updateInternalCollections(n,i,t);return this._notifyListeners(s,t),s}get(){const e=[];for(const t in this._items)if(this._items.hasOwnProperty(t)){const i=this._items[t];e.push(i)}return e}getByName(e){for(const t in this._items)if(t===e)return this._items[t]}getOrWait(e){return new Promise((t=>{const i=n=>{n.id===e&&(t(n),this.unsubscribe(i))};this.subscribe(i);const n=this.getByName(e);if(n)return this.unsubscribe(i),void t(n)}))}subscribe(e){return this._listeners.push(e),Object.keys(this._items).forEach((t=>{const i=this._items[t];e(i,new rt(ct.Added.toString()))})),()=>{this.unsubscribe(e)}}unsubscribe(e){const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}_notifyListeners(e,t){this._listeners.forEach((i=>{try{i(e,t)}catch(e){return}}))}_updateInternalCollections(e,t,i){const n=e,s=t===ct.StatusChange&&n.status&&n.status.state===dt.Destroyed||t===ct.StatusChange&&i&&i.newStatus&&i.newStatus.state===dt.Destroyed,r=t===ct.Closed;if(t===ct.Removed&&void 0===n.isIndependent||r||s){const t=this._items[e.id];return delete this._items[e.id],this._processNew(e),t&&e._beforeDelete(t),e}{const t=e.id;this._items.hasOwnProperty(t)?this._items[e.id]._update(e):(this._processNew(e),this._items[e.id]=e)}return this._items[e.id]}}class Ot{get usingHc(){return"HC"===this._bridge.bridgeType}get announcedWindows(){return this._announcedWindows}set announcedWindows(e){throw new Error("not allowed")}constructor(e,t,i){this._logger=ft.Get("activityManager"),this._announcedWindows=[],this._attachedCallbacks=[],this._detachedCallbacks=[],this._frameColorChangesCallbacks=[],this._windowHandlers=[],this._bridge=e,this._activityTypes=new Wt((e=>this._grabEntity(e))),this._windowTypes=new Wt((e=>this._grabEntity(e))),this._activities=new Wt((e=>this._grabEntity(e))),this._windows=new Wt((e=>this._grabEntity(e))),this._dataReadyMarker=new jt("Activity Manager Data",4),this._descriptorsMarker=new jt("Attached Activities Descriptors",1),t?(this._readyMarker=new jt("Activity Manager Announce",1),this._dataReadyMarker.setCallback((e=>{e&&this._readyMarker.error(e),this._descriptorsMarker.setCallback((e=>{e&&this._readyMarker.error(e),this._logger.debug("Auto announcing window"),this.announceWindow().then((e=>{this._announcedWindows.push(e),this._readyMarker.signal("Successfully announced window with id '"+e.id+"'")})).catch((e=>{this._logger.debug("Will not announce window - "+e),this._readyMarker.signal()}))})),this.refreshDescriptors()}))):this._readyMarker=this._dataReadyMarker,this._bridge.onActivitiesAttached((e=>{this._handleActivitiesAttached(e)})),this._bridge.onActivitiesDetached((e=>{this._handleActivitiesDetached(e)})),this._bridge.onActivityAttachedDescriptorsRefreshed((e=>{this._handleActivityDescriptorsRefreshed(e)})),i&&i.onWindowFrameColorChanged(this._handleWindowFrameColorChanged.bind(this)),this._bridge.init(),this._subscribeForData(),this._bridge.initReady().then((e=>{this._getInitialData()})).catch((e=>{console.log(e)}))}ready(e){const t=new Promise(((e,t)=>{this._readyMarker.setCallback((i=>{i?t(this._readyMarker.getError()):e(this)}))}));return pt(Promise.all([this._bridge.ready(),t]).then((()=>this)),e)}getActivityTypes(){return this._activityTypes.get()}getActivityType(e){return this._activityTypes.getByName(e)}registerActivityType(e,t,i,n,s,r){return pt(new Promise(((r,o)=>{if(Ze(e))return void o("activityTypeName argument can not be undefined");if(!Ve(e))return void o("activityTypeName should be string");if(!Ze(this.getActivityType(e)))return void o("Activity type '"+e+"' already exists");let a;if(Qe(t))return void o("Owner window type can not be undefined");a=Ve(t)?{type:t,name:"",isIndependent:!1,arguments:{}}:t;const c=[];if(!Qe(i)&&Ke(i))for(const e in i){const t=i[e];if(Ve(t)){const e={type:t,name:"",isIndependent:!1,arguments:{},relativeTo:"",relativeDirection:"",windowStyleAttributes:{}};c.push(e)}else c.push(t)}this._bridge.registerActivityType(e,a,c,n,s).then((e=>{this._grabEntity(e),r(e)})).catch((e=>{o(e)}))})),r)}unregisterActivityType(e,t){return pt(new Promise(((t,i)=>{const n=this.getActivityType(e);Qe(n)?i("Activity type '"+e+"' does not exists"):this._bridge.unregisterActivityType(e).then((()=>t(n)),i)})),t)}initiate(e,t,i,n){return pt(new Promise(((i,s)=>{Qe(this.getActivityType(e))?s("Activity type '"+e+"' does not exists"):this._bridge.initiateActivity(e,t,n).then((e=>{this._activities.getOrWait(e).then((e=>{i(e)})).catch((e=>s(e)))})).catch((e=>{s(e)}))})),i)}subscribeActivityTypeEvents(e){this._activityTypes.subscribe(((t,i)=>{e(t,i.type)}))}getWindowTypes(){return this._windowTypes.get()}getWindowType(e){return this._windowTypes.getByName(e)}registerWindowFactory(e,t,i){return pt(new Promise(((i,n)=>{if(Ze(e))n("no windowType specified");else{if(ze(e))e=e.getName();else if(!Ve(e))return void n("windowType should be string or object that has getName method");this._bridge.registerWindowFactory(e,t).then((e=>{i(e)})).catch((e=>{n(e)}))}})),i)}unregisterWindowFactory(e,t){return pt(new Promise(((t,i)=>{Ze(e)?i("no windowType specified"):Ve(e)?this._bridge.unregisterWindowFactory(e).then((e=>{t(e)})).catch((e=>{i(e)})):i("windowType should be a string")})),t)}getActivities(e){let t=this._activities.get();if(t=t.filter((e=>e._ownerId)),!e)return t;let i=e;if(Ve(e))i=[e];else if(e instanceof it)i=[e.name];else if(!(e instanceof Array))throw new Error("Invalid input argument 'activityType' = "+e);return t.filter((e=>{const t=e.type;return function(e,t){for(let i=0;i<e.length;i++)if(t(e[i],i))return!0;return!1}(i,(e=>t.id===e.id))}))}getActivityById(e){return this._activities.getByName(e)}announceWindow(e,t){return new Promise(((i,n)=>{const s=this._bridge.getAnnouncementInfo();if(Qe(e)&&(e=s.activityWindowId),Qe(t)&&(t=s.activityWindowType),Ze(t))throw new Error("Can not announce - unknown windowType");const r=s&&s.activityId;if(Ze(e))this._logger.debug("Registering window with type:'"+t+"', name:'"+s.activityWindowName+"', ind.:'"+s.activityWindowIndependent+"'"),this._bridge.registerWindow(t,s.activityWindowName,s.activityWindowIndependent).then(this._windows.getOrWait.bind(this._windows)).then((e=>r?this._activities.getOrWait(r).then((t=>e)):e)).then((e=>{i(e)})).catch((e=>{this._logger.error(e)}));else{this._logger.debug("Announcing window with id '"+e+"' and type '"+t+"'");const s=this._windows.getByName(e);if(!Ze(s))return this._logger.debug("Window with id '"+e+"' already announced - reusing the window"),void i(s);const r=(t,s,o)=>{if(e===s.id&&o===ct.ActivityWindowJoinedActivity){Qe(s.activity)&&n("UNDEFINED ACTIVITY"),this._logger.trace("Got joined event for id '"+e+"'"),i(s),this.unsubscribeWindowEvents(r)}};this.subscribeWindowEvents(r),this._logger.trace("Waiting for joined event for id '"+e+"'"),this._bridge.announceWindow(t,e)}}))}subscribeWindowTypeEvents(e){this._windowTypes.subscribe(((t,i)=>{e(t,i.type)}))}subscribeActivityEvents(e){return this._activities.subscribe(((t,i)=>{if(i.type===ct.StatusChange){const n=i;e(t,n.newStatus,n.oldStatus)}if(i.type===ct.Removed||i.type===ct.StatusChange&&i.newStatus.getState()===dt.Destroyed)for(const e of this._windows.get())e.activity&&e.activity.id===t.id&&this._windows.process(new st(e,new rt(ct.ActivityWindowLeftActivity)))}))}subscribeWindowEvents(e){const t=(t,i)=>{let n=i.type;n===ct.Added&&(n="opened"),e(t.activity,t,n)};return this._windowHandlers.push([e,t]),this._windows.subscribe(t)}unsubscribeWindowEvents(e){const t=this._windowHandlers.find((t=>t[0]===e));t&&(this._windowHandlers.splice(this._windowHandlers.indexOf(t),1),this._windows.unsubscribe(t[1]))}createWindow(e,t,i){return pt(new Promise(((i,n)=>{let s,r;if(Ze(t)&&n("windowType is undefined"),Ve(t))s={type:t,name:"",isIndependent:!1,arguments:{}};else if(t instanceof nt)s={type:t.type||t.id,name:t.name||t.type||t.id,isIndependent:!1};else{const e=["url"],i={};Object.keys(t).forEach((n=>{-1===e.indexOf(n)&&(i[n]=t[n])})),s=i}if(!Ze(s.relativeTo))if(r=s.relativeTo,"string"==typeof r){const e=this.getWindows({type:r});!Ze(e)&&e.length>0&&(s.relativeTo=e[0].id)}else if(Ze(r.type))Ze(r.windowId)||(s.relativeTo=r.windowId);else{const e=this.getWindows({type:r.type});!Ze(e)&&e.length>0&&(s.relativeTo=e[0].id)}this._bridge.createWindow(e&&e.id,s).then((t=>{this._logger.debug("Window created, waiting for window entity with id "+t);const n=(s,r)=>{s.id!==t||e&&!s.activity||(this._logger.debug("Got entity window with id "+t),i(s),this._windows.unsubscribe(n))};this._windows.subscribe(n)})).catch((e=>{n(e)}))})),i)}createStackedWindows(e,t,i,n){return pt(new Promise(((n,s)=>{Ze(e)&&s("activity is undefined"),Ze(t)&&s("relativeWindowTypes is undefined"),Array.isArray(t)||s("relativeWindowTypes has to be an array"),Ze(i)&&(i=2e4);const r=[];t.forEach((e=>{let t,n;if(t=Ve(e)?{type:e,name:"",isIndependent:!1,arguments:{}}:e,t.stackedWindow=!0,t.timeout=i,!Ze(t.relativeTo))if(n=t.relativeTo,Ze(n.type)){if(!Ze(n.windowId)){const e=this.getWindows({id:n.windowId});!Ze(e)&&e.length>0&&(t.relativeTo=e[0].type.name)}}else t.relativeTo=n.type;r.push(t)}));const o=[];r.forEach((t=>o.push(this.createWindow(e,t)))),Promise.all(o).then(n).catch(s)})),n)}addWindowToActivity(e,t,i){const n=this._bridge.joinActivity(e.id,t.id).then((()=>t));return pt(n,i),n}leaveWindowFromActivity(e,t,i){const n=this._bridge.leaveActivity(e.id,t.id).then((()=>t));return pt(n,i),n}setActivityContext(e,t,i){return pt(new Promise(((i,n)=>{Ze(e)&&n("activity can not be null"),this._bridge.updateActivityContext(e,t,!0).then((t=>{i(e)})).catch((e=>{n(e)}))})),i)}updateActivityContext(e,t,i){return pt(new Promise(((i,n)=>{Ze(e)&&n("activity can not be null");const s=[];for(const e in t)t.hasOwnProperty(e)&&null===t[e]&&s.push(e);for(const e of s)delete t[e];this._bridge.updateActivityContext(e,t,!1,s).then((t=>{i(e)})).catch((e=>{n(e)}))})),i)}subscribeActivityContextChanged(e){this._activities.subscribe(((t,i)=>{if(i.type===ct.ActivityContextChange){const n=i;e(t,n.context,n.updated,n.removed)}}))}stopActivity(e,t){return pt(this._bridge.stopActivity(e),t)}getWindows(e){if(Qe(e))return this._windows.get();if(!Qe(e.id))return[this._windows.getByName(e.id)];return this._windows.get().filter((t=>{if(!Qe(e.type)&&t.type.id!==e.type)return!1;if(!Qe(e.name)&&t.name!==e.name)return!1;if(!Qe(e.activityId)){if(Ze(t.activity))return!1;if(t.activity.id!==e.activityId)return!1}return!0}))}getWindowBounds(e){return this._bridge.getWindowBounds(e)}setWindowBounds(e,t,i){return pt(new Promise(((i,n)=>{this._bridge.setWindowBounds(e,t).then((()=>i())).catch((e=>n(e)))})),i)}closeWindow(e){return this._bridge.closeWindow(e)}activateWindow(e,t){return this._bridge.activateWindow(e,t)}setWindowVisibility(e,t){return this._bridge.setWindowVisibility(e,t)}clone(e,t,i){return pt(new Promise(((i,n)=>{e||n("activity can not be null"),this._bridge.cloneActivity(e.id,t).then((e=>{this._activities.getOrWait(e).then((e=>{i(e)})).catch((e=>n(e)))})).catch((e=>n(e)))})),i)}attachActivities(e,t,i,n){i=i||{};return pt(new Promise(((n,s)=>{if(!this._activities.getByName(e))return void s("can not find activity with id "+e);if(this._activities.getByName(t))return this._bridge.attachActivities(e,t,i).then((e=>{const t=e.to,i=e.descriptor,s=e.descriptors;this._activities.getOrWait(t).then((e=>{e._updateDescriptors(s);const t=e.attached.filter((e=>e.ownerId===i.ownerId))[0];n(t)}))})).catch((e=>{s(e)}));s("can not find activity with id "+t)})),n)}detachActivities(e,t,i){return pt(new Promise(((i,n)=>this._bridge.detachActivities(e,t).then((()=>{this._activities.getOrWait(undefined).then((e=>{e._updateDescriptors(undefined),this._activities.getOrWait(undefined).then((e=>{i(e)}))})).catch((e=>n(e)))})).catch((e=>{n(e)})))),i)}subscribeActivitiesAttached(e){this._attachedCallbacks.push(e)}subscribeActivitiesDetached(e){this._detachedCallbacks.push(e)}subscribeActivityFrameColorChanged(e){this._frameColorChangesCallbacks.push(e)}_grabEntity(e){e._manager=this}_getInitialData(){this._logger.debug("Request initial data..."),this._bridge.getActivityTypes().then((e=>{this._activityTypes.add(e),this._dataReadyMarker.signal("Got act types")})).catch((e=>{this._logger.error(e),this._dataReadyMarker.error("Can not initialize ActivityManager - error getting activity types -"+e)})),this._bridge.getWindowTypes().then((e=>{this._windowTypes.add(e),this._dataReadyMarker.signal("Got window types")})).catch((e=>{this._logger.error(e),this._dataReadyMarker.error("Can not initialize ActivityManager - error getting window types "+e)})),this._bridge.getActivities().then((e=>{this._activities.add(e),this._dataReadyMarker.signal("Got activities")})).catch((e=>{this._logger.error(e),this._dataReadyMarker.error("Can not initialize ActivityManager - error getting activity instances -"+e)})),this._bridge.getActivityWindows().then((e=>{this._windows.add(e),this._dataReadyMarker.signal("Got windows")})).catch((e=>{this._logger.error(e),this._dataReadyMarker.error("Can not initialize ActivityManager - error getting activity windows -"+e)}))}_subscribeForData(){this._logger.debug("Subscribe for data..."),this._bridge.onActivityTypeStatusChange((e=>{this._activityTypes.process(e)})),this._bridge.onWindowTypeStatusChange((e=>{this._windowTypes.process(e)})),this._bridge.onActivityWindowChange((e=>{this._windows.process(e)})),this._bridge.onActivityStatusChange((e=>{this._activities.process(e)}))}_handleActivitiesAttached(e){const t=e.to,i=e.descriptor,n=e.descriptors;this._activities.getOrWait(t).then((e=>{e._updateDescriptors(n);const t=e.attached.filter((e=>e.ownerId===i.ownerId))[0];this._attachedCallbacks.forEach((i=>{try{i(e,t)}catch(e){return}}))}))}_handleActivitiesDetached(e){const t=e.oldActivityId,i=e.newActivityId,n=e.descriptors,s=e.descriptor;this._activities.getOrWait(t).then((e=>{e._updateDescriptors(n),this._activities.getOrWait(i).then((t=>{this._detachedCallbacks.forEach((i=>{try{i(t,e,s)}catch(e){return}}))}))}))}_handleActivityDescriptorsRefreshed(e){const t=e.id,i=e.descriptors,n=this._activities.getByName(t);n&&n._updateDescriptors(i)}refreshDescriptors(){this._bridge.getAttachedDescriptors().then((e=>{e&&Object.keys(e).forEach((t=>{const i=t,n=e[t],s=this._activities.getByName(i);s&&s._updateDescriptors(n)})),this._descriptorsMarker.signal("Successfully got descriptors")})).catch((e=>{this._descriptorsMarker.error("failed to get descriptors - "+e)}))}_handleWindowFrameColorChanged(e){if(!e.activityId)return;const t=this._activities.getByName(e.activityId);t&&t.owner&&t.owner.underlyingWindow.id===e.id&&this._frameColorChangesCallbacks.forEach((i=>{try{i(t,e.frameColor)}catch(e){return}}))}}class Ft{constructor(e,t){this._m=e,this._my=t,this.activityTypes={get:this._getActivityTypesWrapper.bind(this),register:this._m.registerActivityType.bind(this._m),unregister:this._m.unregisterActivityType.bind(this._m),subscribe:this._m.subscribeActivityTypeEvents.bind(this._m),unsubscribe:void 0,initiate:this._m.initiate.bind(this._m)},this.windowTypes={get:this._getWindowTypesWrapper.bind(this),registerFactory:this._m.registerWindowFactory.bind(this._m),unregisterFactory:this._m.unregisterWindowFactory.bind(this._m),subscribe:this._m.subscribeWindowTypeEvents.bind(this._m),unsubscribe:void 0},this.windows={get:this._m.getWindows.bind(this._m),subscribe:this._m.subscribeWindowEvents.bind(this._m),announce:this._m.announceWindow.bind(this._m),unsubscribe:void 0,create:this._m.createWindow.bind(this._m)},this.instances={get:this._m.getActivities.bind(this._m),subscribe:this._m.subscribeActivityEvents.bind(this._m),unsubscribe:void 0}}onAttached(e){this._m.subscribeActivitiesAttached(e)}onDetached(e){this._m.subscribeActivitiesDetached(e)}onActivityFrameColorChanged(e){this._m.subscribeActivityFrameColorChanged(e)}_getActivityTypesWrapper(e){return Qe(e)?this._m.getActivityTypes():this._m.getActivityType(e)}_getWindowTypesWrapper(e){return Qe(e)?this._m.getWindowTypes():this._m.getWindowType(e)}}class Dt{constructor(e,t){this._mgr=e,this._my=t,this.all=new Ft(e,t)}ready(e){return pt(new Promise(((e,t)=>{this._mgr.ready().then((()=>{e(this)})).catch((e=>{t(e)}))})),e)}get my(){return this._my}get aware(){return void 0!==this._my.window}get inActivity(){return this.aware&&void 0!==this._my.activity}get agm(){if(this.aware)return this.inActivity?this._my.activity.agm:new ht(null)}getAvailableFrameColors(){return[]}}class Lt{static checkIsUsingGW3Implementation(e){return 3===e.protocolVersion}get api(){return this._api}set api(e){this._api=e}constructor(e){if(!e)throw new Error("config can not be null");let t;if(Qe(e.logLevel)||(ft.Level=e.logLevel),Ze(e.logger)||(ft.GlueLogger=e.logger),this._isUsingHCImplementation=2===e.gdMajorVersion,this._isUsingGW3Implementation=Lt.checkIsUsingGW3Implementation(e.connection),this._isUsingHCImplementation)throw new Error("GD2 not supported");if(!this._isUsingGW3Implementation)throw new Error("Unable to instantiate activity bridge implementation");if(t=new Rt(e),!t)throw new Error("A bridge to native activity is needed to create activity lib.");ht.AGM=e.agm;const i=new Ot(t,!e.disableAutoAnnounce,e.windows),n=new Nt(i,e.windows);this._api=new Dt(i,n),this._readyPromise=i.ready().then((e=>this))}get isUsingHCImplementation(){return this._isUsingHCImplementation}get isUsingGW3Implementation(){return this._isUsingGW3Implementation}ready(e){return pt(this._readyPromise,e)}}const $t="T42.ACS.GetFunctionalEntitlement",Gt="T42.ACS.CanI",Bt="T42.ACS.OnEvent",Ht="T42.ACS.GetApplications";function Ut(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function qt(e){if(e&&e.errorHandling&&"function"!=typeof e.errorHandling&&"log"!==e.errorHandling&&"silent"!==e.errorHandling&&"throw"!==e.errorHandling)throw new Error('Invalid options passed to createRegistry. Prop errorHandling should be ["log" | "silent" | "throw" | (err) => void], but '+typeof e.errorHandling+" was passed");var t=e&&"function"==typeof e.errorHandling&&e.errorHandling,i={};function n(i,n){var s=i instanceof Error?i:new Error(i);if(t)t(s);else{var r='[ERROR] callback-registry: User callback for key "'+n+'" failed: '+s.stack;if(e)switch(e.errorHandling){case"log":return console.error(r);case"silent":return;case"throw":throw new Error(r)}console.error(r)}}return{add:function(e,t,s){var r=i[e];return r||(r=[],i[e]=r),r.push(t),s&&setTimeout((function(){s.forEach((function(s){var r;if(null===(r=i[e])||void 0===r?void 0:r.includes(t))try{Array.isArray(s)?t.apply(void 0,s):t.apply(void 0,[s])}catch(t){n(t,e)}}))}),0),function(){var n=i[e];n&&(0===(n=n.reduce((function(e,i,n){return i===t&&e.length===n||e.push(i),e}),[])).length?delete i[e]:i[e]=n)}},execute:function(e){for(var t=[],s=1;s<arguments.length;s++)t[s-1]=arguments[s];var r=i[e];if(!r||0===r.length)return[];var o=[];return r.forEach((function(i){try{var s=i.apply(void 0,t);o.push(s)}catch(t){o.push(void 0),n(t,e)}})),o},clear:function(){i={}},clearKey:function(e){i[e]&&delete i[e]}}}qt.default=qt;var Jt=Ut(qt);function Vt(e){return e?Object.keys(e).map((t=>e[t])):[]}function zt(e){let t;try{t=JSON.parse(JSON.stringify(e||{}))}catch(e){t={}}return t}function Kt(e,t){if(t.throwErrors&&"function"!=typeof e)throw new Error("Please provide the callback as a function!")}class Qt{constructor(e,t,i,n){this._appManager=e,this._name=t,this._agm=i,this._configuration=n,this._registry=Jt(),e.onInstanceStarted((e=>{e.application&&e.application.name!==this._name||this._registry.execute("instanceStarted",e)})),e.onInstanceStopped((e=>{e.application&&e.application.name!==this._name||this._registry.execute("instanceStopped",e)})),e.onAppRemoved((e=>{e.name===this._name&&this._registry.execute("appRemoved",e)})),e.onAppChanged((e=>{e.name===this._name&&this._registry.execute("appChanged",e)})),e.onAppAvailable((e=>{e.name===this._name&&(this._props.IsReady=!0,this._registry.execute("appAvailable",e))})),e.onAppUnavailable((e=>{e.name===this._name&&(this._props.IsReady=!1,this._registry.execute("appUnavailable",e))}))}get name(){return this._name}get title(){return this._props.Title}get version(){return this._props.Version}get autoStart(){return this._props.AutoStart}get isShell(){return this._props.IsShell}get caption(){return this._props.Caption}get hidden(){return this._props.IsHidden}get container(){return this._props.ApplicationName}get activityType(){return this._props.ActivityType}get activityWindowType(){return this._props.ActivityWindowType}get windowSettings(){return this._props.Arguments?zt(this._props.Arguments):{}}get allowMultiple(){return this._props.AllowMultiple}get available(){return this._props.IsReady||!0}get icon(){return this._props.Icon}get iconURL(){return this._props.IconUrl}get sortOrder(){return this._props.SortOrder}get userProperties(){return this._props.UserProperties?zt(this._props.UserProperties):{}}get keywords(){return this._props.Keywords?this._props.Keywords:[]}get isActivity(){return void 0!==this._props.ActivityType&&""!==this._props.ActivityType}get configuration(){return{autoStart:this._props.AutoStart,caption:this._props.Caption,hidden:this._props.IsHidden,container:this._props.ApplicationName,activityType:this._props.ActivityType,allowMultiple:this._props.AllowMultiple}}get instances(){return this._appManager.instances().filter((e=>e.application.name===this._name))}get type(){return this._props.Type}get mode(){if(!this._props)return"unknown";if(this._props.Mode&&"string"==typeof this._props.Mode)return this._props.Mode.toLowerCase();if(this.isActivity)return"unknown";if(this._props.Arguments&&this._props.Arguments.mode&&"string"==typeof this._props.Arguments.mode)return this._props.Arguments.mode.toLowerCase();let e=this._props.WindowStyleAttributes;if(e){e=e.split(" ").join("");const t='mode:"',i=e.indexOf(t);if(-1!==i){const n=i+t.length,s=e.indexOf('"',n),r=e.substr(n,s-n);if(r&&"string"==typeof r)return r.toLowerCase()}}return"flat"}async getConfiguration(){return(await this._agm.invoke(Ht,{v2:{apps:[this._name]}})).returned.applications[0]}updateFromProps(e){this._props||(this._props={Name:e.Name}),Object.keys(e).forEach((t=>{this._props[t]=e[t]}))}start(e,t){return new Promise((async(i,n)=>{var s,r,o,a,c;if(Ze(e))e={};else if((null===(s=this._configuration())||void 0===s?void 0:s.throwErrors)&&"object"!=typeof e||Array.isArray(e))return n(new Error('Invalid "context" parameter - must be an object.'));if(Ze(t))t={};else if((null===(r=this._configuration())||void 0===r?void 0:r.throwErrors)&&"object"!=typeof t)return n(new Error('Invalid "options" parameter - must be an object.'));const d=this._name;let h=null===(a=null!==(o=t.awaitInterop)&&void 0!==o?o:t.waitForAGMReady)||void 0===a||a,u=6e4;"number"==typeof t.timeout&&(u=1e3*t.timeout);const l=e=>{let t;const s=setTimeout((()=>{t&&t(),n(`timed out while waiting for instance id ${e} for app ${this.name}`)}),u),r=n=>{n.id===e&&(t&&(t(),t=void 0),clearTimeout(s),i(n))};t=h?this._appManager.onInstanceAgmServerReady(r):this._appManager.onInstanceStarted(r)};try{const n=(await this._agm.invoke("T42.ACS.StartApplication",{Name:d,Context:e,Options:t},"best",{methodResponseTimeoutMs:u})).returned;if(void 0!==n.timeout&&void 0===t.timeout&&(u=1e3*n.timeout),void 0!==n.waitForInterop&&void 0===t.waitForAGMReady&&void 0===t.awaitInterop&&(h=n.waitForInterop),n&&n.Id)if("startOnly"===this._appManager.mode){const e=this._appManager.handleInstanceStarted({ActivityId:void 0,IsActivityOwner:void 0,Context:void 0,Title:void 0,AgmServers:void 0,Id:n.Id,Name:n.Name});i(e)}else l(n.Id);else i(void 0)}catch(e){n(null!==(c=e.message)&&void 0!==c?c:e)}}))}onInstanceStarted(e){return Kt(e,this._configuration()),this._registry.add("instanceStarted",e)}onInstanceStopped(e){return Kt(e,this._configuration()),this._registry.add("instanceStopped",e)}onAvailable(e){return Kt(e,this._configuration()),this._props.IsReady&&setTimeout((()=>{this._registry.execute("appAvailable",this)}),0),this._registry.add("appAvailable",e)}onUnavailable(e){return Kt(e,this._configuration()),!1===this._props.IsReady&&setTimeout((()=>{this._registry.execute("appUnavailable",this)}),0),this._registry.add("appUnavailable",e)}onChanged(e){Kt(e,this._configuration()),this._registry.add("appChanged",e)}onRemoved(e){Kt(e,this._configuration()),this._registry.add("appRemoved",e)}}class Zt{constructor(e,t,i,n,s,r,o,a){this._id=e,this._appName=t,this._appManager=i,this._agm=n,this._activities=s,this._windows=r,this._configuration=a,this._registry=Jt(),o||(this._unsubscribeInstanceStopped=this._appManager.onInstanceStopped((e=>{e.id===this._id&&this._registry.execute("stopped",e)})),this._unsubscribeInstanceAgmServerReady=this._appManager.onInstanceAgmServerReady((e=>{e.id===this._id&&this._registry.execute("agmReady",e)})))}get id(){return this._id}get application(){return this._appManager.application(this._appName)}get activity(){if(!this._activities)throw new Error("This method requires glue.activities library to be enabled.");return this._activities.all.instances.get().filter((e=>e.id===this._activityId))[0]}get isActivityOwner(){return this._isActivityOwner}get activityInstances(){return this._appManager.instances().filter((e=>"activity"!==e.application.type&&e.activityId&&e.activityId===this._activityId))}get activityOwnerInstance(){if(this._activityId)return this.activityInstances.filter((e=>null==e?void 0:e.isActivityOwner))[0]}get window(){if(!this._windows)throw new Error("This method requires glue.windows library to be enabled.");let e=this._windows.list().filter((e=>e.id===this._id))[0];return!e&&this._activities&&this.activity&&this.activityOwnerInstance&&(e=this.activityOwnerInstance.window),e}get context(){var e,t,i;return null!==(i=null!==(e=this._startUpContext)&&void 0!==e?e:null===(t=this.window)||void 0===t?void 0:t.context)&&void 0!==i?i:{}}get title(){return this._title}get isActivityInstance(){return this._isActivityInstance}get activityId(){return this._activityId}get inActivity(){return this._inActivity}get isSingleWindowApp(){return!this._inActivity}get agm(){return this._agmInstance}get interopInstance(){return this._agmInstance}onInteropReady(e){return Kt(e,this._configuration()),this._agmInstance&&setTimeout((()=>{this._registry.execute("agmReady",this)}),0),this._registry.add("agmReady",e)}onAgmReady(e){return this.onInteropReady(e)}onStopped(e){return Kt(e,this._configuration()),this._registry.add("stopped",e)}getWindow(){return new Promise(((e,t)=>{const i=this.window;if(i)return void e(i);const n=(i,n)=>{i&&t(i),n&&e(n),setTimeout((()=>{clearTimeout(s),r()}),0)},s=setTimeout((()=>{n(new Error(`can not find a window with id ${this._id}`))}),3e4),r=this._windows.onWindowAdded((e=>{e.id===this._id&&n(void 0,e)}))}))}updateFromProps(e){this._startUpContext=e.Context,this._title=e.Title,this._isActivityInstance=!1,e.ActivityId&&""!==e.ActivityId&&(this._activityId=e.ActivityId,this._isActivityInstance=!0),this._isActivityOwner=e.IsActivityOwner,!this._activityId&&this._startUpContext&&this._startUpContext.activityId&&(this._activityId=this._startUpContext.activityId),this._inActivity=Boolean(this._activityId),this.updateAgmInstanceFromProps(e)}updateAgmInstanceFromProps(e){if(!e.AgmServers)return;const t=e.AgmServers;t&&t.length>0&&!Ze(t[0])&&(this._agmInstance=t[0])}stop(){return new Promise(((e,t)=>{let i=this._id;this.isActivityOwner&&(i=this.activityId);const n=this._appManager.onInstanceStopped((t=>{t.id===i&&(n(),e())}));this._agm.invoke("T42.ACS.StopApplication",{Name:this._appName,Id:this._id}).then((()=>{"startOnly"===this._appManager.mode&&(this._appManager.handleInstanceStopped({Name:this._appName,Id:this.id}),e())})).catch((e=>t(e)))}))}activate(){return this._agm.invoke("T42.ACS.ActivateApplication",{Name:this._appName,Id:this._id})}done(){this._registry.clear(),this._unsubscribeInstanceAgmServerReady(),this._unsubscribeInstanceStopped()}getContext(){return Promise.resolve(this.context)}async startedBy(){return(await this._agm.invoke("T42.ACS.Execute",{command:"getStartedBy",Name:this._appName,Id:this._id})).returned}}class Xt{constructor(e,t,i,n,s,r,o){this.mode=e,this._agm=t,this._activities=i,this._windows=n,this._logger=s,this._gdMajorVersion=r,this._configuration=o,this._apps={},this._instances=[],this._registry=Jt(),this.getConfigurations=async e=>{const t={v2:{apps:void 0}};Array.isArray(e)&&(t.v2={apps:e});return(await this._agm.invoke(Ht,t)).returned.applications},this.application=e=>{var t;if((null===(t=this._configuration())||void 0===t?void 0:t.throwErrors)&&"string"!=typeof e)throw new Error('"name" must be string');return this._apps[e]},this.applications=()=>Object.keys(this._apps).map((e=>this._apps[e])),this.instances=()=>this._instances.map((e=>e)),this.getMyInstance=()=>{const e="undefined"!=typeof window&&window.glue42gd;if(!e){const e=this._agm.instance.instance;return this._instances.find((t=>t.id===e))}if(this._gdMajorVersion>=3){const t=e.appInstanceId;return this._instances.find((e=>e.id===t))}},this.getMyApplication=()=>{var e;if(this._agm.instance)return null!==(e=this.application(this._agm.instance.applicationName))&&void 0!==e?e:this.application(this._agm.instance.application)},this.handleSnapshotAppsAdded=e=>{const t=this.applications();t.length>0&&t.forEach((t=>{const i=t.name;e.find((e=>e.Name===t.name))||this.handleAppRemoved({Name:i})})),e.forEach((e=>{t.find((t=>t.name===e.Name))||this.handleAppAdded(e)}))},this.handleSnapshotInstanceStarted=e=>{const t=this.instances();t.length>0&&t.forEach((t=>{const i=t.id;e.find((e=>e.Id===i))||this.handleInstanceStopped({Name:t.application.name,Id:i})})),e.forEach((e=>{t.find((t=>t.id===e.Id))||this.handleInstanceStarted(e)}))},this.handleAppAdded=e=>{const t=this._getAppId(e);this._logger.trace(`adding app ${t}`),this._apps[t]=new Qt(this,t,this._agm,this._configuration);const i=this._updateAppFromProps(e);this._registry.execute("appAdded",i),this._registry.execute("appAvailable",i)},this.handleAppUpdated=e=>{const t=this._updateAppFromProps(e);this._registry.execute("appChanged",t)},this.handleAppRemoved=e=>{const t=this._getAppId(e);this._logger.trace(`removing app ${t}`);const i=this.application(t);this._instances=this._instances.filter((e=>e.application.name!==i.name)),delete this._apps[t],this._registry.execute("appRemoved",i)},this.handleAppReady=e=>{const t=this._getAppId(e),i=this._getAppOrThrow(t);i.updateFromProps(e),i.available?this._registry.execute("appAvailable",i):this._registry.execute("appUnavailable",i)},this.handleInstanceStarted=e=>{this._logger.trace(`started app ${e.Name} ${e.Id}`);const t=this._getInstanceId(e),i=this._getInstanceAppName(e),n=new Zt(t,i,this,this._agm,this._activities,this._windows,!1,this._configuration);return this._updateInstanceFromProps(n,e),this._instances.push(n),this._registry.execute("instanceStarted",n),n},this.handleInstanceStopped=e=>{this._logger.trace(`failed to start app ${e.Name} ${e.Id}`);const t=this._getInstanceId(e),i=this._getInstanceAppName(e),n=this._getInstanceOrThrow(t,i);this._instances=this._instances.filter((e=>!this._matchInstance(e,t,i))),this._registry.execute("instanceStopped",n),n.done()},this.handleInstanceAgmServerReady=e=>{const t=this._getInstanceId(e),i=this._getInstanceAppName(e),n=this._getInstanceOrThrow(t,i);n.updateAgmInstanceFromProps(e),this._registry.execute("instanceAgmServerReady",n)},this.handleInstanceStartFailed=e=>{const t=this._getInstanceId(e),i=this._getInstanceAppName(e),n=new Zt(t,i,void 0,void 0,void 0,void 0,!0,this._configuration);this._updateInstanceFromProps(n,e),this._registry.execute("instanceStartFailed",n)},this.handleInstanceUpdated=e=>{const t=this._getInstanceId(e),i=this._getInstanceAppName(e),n=this._getInstanceOrThrow(t,i);this._updateInstanceFromProps(n,e)},this.onInstanceStarted=e=>(Kt(e,this._configuration()),this._registry.add("instanceStarted",e,this._instances)),this.onInstanceStartFailed=e=>(Kt(e,this._configuration()),this._registry.add("instanceStartFailed",e)),this.onInstanceStopped=e=>(Kt(e,this._configuration()),this._registry.add("instanceStopped",e)),this.onInstanceUpdated=e=>(Kt(e,this._configuration()),this._registry.add("instanceChanged",e)),this.onInstanceAgmServerReady=e=>(Kt(e,this._configuration()),this._registry.add("instanceAgmServerReady",e)),this.onAppAdded=e=>(Kt(e,this._configuration()),this._registry.add("appAdded",e,Object.values(this._apps))),this.onAppRemoved=e=>(Kt(e,this._configuration()),this._registry.add("appRemoved",e)),this.onAppAvailable=e=>(Kt(e,this._configuration()),this._registry.add("appAvailable",e)),this.onAppUnavailable=e=>(Kt(e,this._configuration()),this._registry.add("appUnavailable",e)),this.onAppChanged=e=>(Kt(e,this._configuration()),this._registry.add("appChanged",e))}_getAppOrThrow(e){const t=this.application(e);if(!t)throw Error(`app with id ${e} not found`);return t}_getAppId(e){return e.Name}_matchInstance(e,t,i){return e.id===t&&e.application.name===i}_getInstanceByIdAndName(e,t){return this._instances.filter((i=>this._matchInstance(i,e,t)))[0]}_getInstanceOrThrow(e,t){const i=this._getInstanceByIdAndName(e,t);if(!i)throw Error(`instance with id ${e} not found`);return i}_getInstanceId(e){return e.Id}_getInstanceAppName(e){return e.Name}_updateAppFromProps(e){const t=this._getAppId(e);this._logger.trace(`updating app with + ${t}, ${JSON.stringify(e)}`);const i=this._getAppOrThrow(t);return i.updateFromProps(e),i}_updateInstanceFromProps(e,t){this._logger.trace("updating instance with "+this._getInstanceId(t)+" for app "+this._getInstanceAppName(t)),e.updateFromProps(t)}}function Yt(e,t,i){const n=e=>!!(e&&e.constructor&&e.call&&e.apply);return n(t)||n(i)?(n(t)?n(i)||(i=()=>{}):t=()=>{},e.then(t,i)):e}class ei{constructor(e){this._agm=e,this._registry=Jt(),this._isMethodRegistered=!1,this.handleBranchModified=e=>{this._registry.execute("branchChanged",e)},this.handleBranchesModified=e=>{this._registry.execute("branchesChanged",e)},this.getRegion=(e,t)=>Yt(this._agmInvoke("T42.ACS.GetConfigurationRegion",(e=>e.returned.Region)),e,t),this.getBranches=(e,t)=>Yt(this._agmInvoke("T42.ACS.GetBranches",(e=>{const t=e.returned.Branches;return Object.keys(t).map((e=>t[e]))})),e,t),this.getCurrentBranch=(e,t)=>Yt(this._agmInvoke("T42.ACS.GetCurrentBranch",(e=>e.returned.Branch),void 0),e,t),this.setRegion=(e,t,i)=>Yt(this._agmInvoke("T42.ACS.SetConfigurationRegion",(e=>e.returned.ResultMessage),{Region:e}),t,i),this.setCurrentBranch=(e,t,i)=>Yt(this._agmInvoke("T42.ACS.SetCurrentBranch",(e=>e.returned.ResultMessage),{Branch:e}),t,i),this.currentUser=(e,t)=>Yt(this._agmInvoke("T42.ACS.GetUser"),e,t),this.getFunctionalEntitlement=(e,t,i)=>Yt(this._agmInvoke($t,(e=>e.returned.Entitlement),{Function:e}),t,i),this.getFunctionalEntitlementBranch=(e,t,i,n)=>Yt(this._agmInvoke($t,(e=>e.returned.Entitlement),{Function:e,Branch:t}),i,n),this.canI=(e,t,i)=>Yt(this._agmInvoke(Gt,(e=>e.returned.Result),{Function:e}),t,i),this.canIBranch=(e,t,i,n)=>Yt(this._agmInvoke(Gt,(e=>e.returned.Result),{Function:e,Branch:t}),i,n),this.onBranchesChanged=e=>this._registry.add("branchesChanged",e),this.onBranchChanged=e=>this._registry.add("branchChanged",e),this.exit=e=>this._agmInvoke("T42.ACS.Shutdown",null,e),this.onShuttingDown=e=>(this.registerMethod(),this._registry.add("onShuttingDown",e)),this.restart=e=>this._agmInvoke("T42.ACS.Restart",null,e),this._agmInvoke=(e,t,i)=>(i=i||{},new Promise(((n,s)=>{this._agm.invoke(e,i).then((e=>{t||(t=e=>e.returned),n(t(e))})).catch((e=>s(e)))})))}registerMethod(){this._isMethodRegistered||(this._agm.register("T42.ACS.OnGDShutdown",(async e=>{try{const t=await Promise.all(this._registry.execute("onShuttingDown",e));return{prevent:t.some((e=>e.prevent))}}catch(e){}})),this._isMethodRegistered=!0)}}const ti="T42.ACS.InMemoryStoreCommand";class ii{constructor(e){this.interop=e}import(e,t){if(!e||!Array.isArray(e))return Promise.reject("invalid apps argument - should be an array of application definitions");if(t&&"replace"!==t&&"merge"!==t)return Promise.reject("invalid mode argument - should be 'replace' or 'merge'");const i={command:"import",args:{apps:e,mode:t=null!=t?t:"replace"}};return this.interop.invoke(ti,i).then((e=>e.returned))}export(){return this.interop.invoke(ti,{command:"export"}).then((e=>e.returned.apps))}remove(e){if(!e||"string"!=typeof e)return Promise.reject("invalid app name, should be a string value");const t={command:"remove",args:{apps:[e]}};return this.interop.invoke(ti,t).then((e=>e.returned))}clear(){return this.interop.invoke(ti,{command:"clear"}).then((e=>e.returned))}createAppDef(e,t){return t||(t="https://google.com"),{name:e,type:"window",title:e,details:{url:t}}}}var ni=e=>{if(!e)throw Error("config not set");if(!e.agm)throw Error("config.agm is missing");const t="startOnly",i="skipIcons",n=e.mode||t;if(n!==t&&n!==i&&"full"!==n)throw new Error(`Invalid mode for appManager lib - ${n} is not supported`);const s=e.activities,r=e.agm,o=e.logger,a=e.windows;let c={};const d=new Xt(n,r,s,a,o.subLogger("applications"),e.gdMajorVersion,(()=>c)),h=new ei(r);let u;if(n===t)u=function(e,t){return new Promise(((i,n)=>{e.invoke(Ht,{skipIcon:!0}).then((e=>{var n;const s=e.returned,r=null!==(n=e.returned.configuration)&&void 0!==n?n:{};s||i(r);const o=s.applications;o||i(r),Vt(o).map((e=>t.handleAppAdded(e))),i(r)})).catch((e=>n(`Error getting application snapshot: ${e.message}`)))}))}(r,d);else{const e=function(e,t,i,n){let s,r=!1;return{start:()=>{let o,a;const c=new Promise(((e,t)=>{o=e,a=t}));return e.subscribe(Bt,{arguments:{skipIcon:n},waitTimeoutMs:1e4}).then((n=>{s=n,s.onData((n=>{var s;const a=n.data,c=null!==(s=a.configuration)&&void 0!==s?s:{},d=Vt(a.OnApplicationAdded);n.data.isSnapshot?t.handleSnapshotAppsAdded(d):d.forEach((e=>t.handleAppAdded(e))),Vt(a.OnApplicationChanged).forEach((e=>t.handleAppUpdated(e))),Vt(a.OnApplicationRemoved).forEach((e=>t.handleAppRemoved(e))),Vt(a.OnApplicationReady).forEach((e=>t.handleAppReady(e)));const h=Vt(a.OnApplicationStarted);if(n.data.isSnapshot?t.handleSnapshotInstanceStarted(h):h.forEach((e=>t.handleInstanceStarted(e))),Vt(a.OnApplicationStartFailed).forEach((e=>t.handleInstanceStartFailed(e))),Vt(a.OnApplicationStopped).forEach((e=>t.handleInstanceStopped(e))),Vt(a.OnApplicationUpdated).forEach((e=>t.handleInstanceUpdated(e))),Vt(a.OnApplicationAgmServerReady).forEach((e=>t.handleInstanceAgmServerReady(e))),Vt(a.OnBranchChanged).forEach((e=>i.handleBranchModified(e))),Vt(a.OnBranchesModified).forEach((e=>i.handleBranchesModified(e))),!r){r=!0;const i=d.some((t=>t.Name===e.instance.application)),n=h.some((t=>t.Id===e.instance.instance));if(i)if(n)o(c);else{const i=t.onInstanceStarted((t=>{t.id===e.instance.instance&&(i(),o(c))}))}else o(c)}})),s.onFailed((e=>a(e)))})).catch((e=>{var t;return a(`Error subscribing for ${Bt} stream. Err: ${null!==(t=e.message)&&void 0!==t?t:JSON.stringify(e)}`)})),c},stop:()=>{s&&s.close()}}}(r,d,h,n===i);u=e.start()}return{ready:()=>u.then((e=>{c=e})),applications:d.applications,application:d.application,getConfigurations:d.getConfigurations,onAppAdded:d.onAppAdded,onAppRemoved:d.onAppRemoved,onAppChanged:d.onAppChanged,onAppAvailable:d.onAppAvailable,onAppUnavailable:d.onAppUnavailable,instances:d.instances,get myInstance(){return d.getMyInstance()},get myApplication(){return d.getMyApplication()},onInstanceStarted:d.onInstanceStarted,onInstanceStopped:d.onInstanceStopped,onInstanceUpdated:d.onInstanceUpdated,onInstanceStartFailed:d.onInstanceStartFailed,getRegion:h.getRegion,getBranches:h.getBranches,getCurrentBranch:h.getCurrentBranch,getFunctionalEntitlement:h.getFunctionalEntitlement,getFunctionalEntitlementBranch:h.getFunctionalEntitlementBranch,setCurrentBranch:h.setCurrentBranch,setRegion:h.setRegion,currentUser:h.currentUser,canI:h.canI,canIBranch:h.canIBranch,onBranchesChanged:h.onBranchesChanged,exit:h.exit,restart:h.restart,onShuttingDown:h.onShuttingDown,inMemory:new ii(r)}};class si{static getGDMajorVersion(){if("undefined"==typeof window)return-1;if(!window.glueDesktop)return-1;if(!window.glueDesktop.version)return-1;const e=Number(window.glueDesktop.version.substr(0,1));return isNaN(e)?-1:e}static callbackifyPromise(e,t,i){const n=e=>{let t=e;if(e instanceof Error&&(t=e.message),"function"!=typeof i)return Promise.reject(t);i(t)};try{return e().then((e=>("function"==typeof t&&t(e),e))).catch((e=>n(e)))}catch(e){return n(e)}}static getMonitor(e,t){return t.map((t=>{const{left:i,top:n,workingAreaWidth:s,workingAreaHeight:r}=t;return{monitor:t,totalOverlap:this.calculateTotalOverlap({left:i,top:n,width:s,height:r},e)}})).sort(((e,t)=>t.totalOverlap-e.totalOverlap))[0].monitor}static getDisplayCenterOfScreen(e,t,i){const n=e.width/t.scaleFactor,s=e.height/t.scaleFactor,r=t.workArea.left/i.scaleFactor,o=t.workArea.top/i.scaleFactor,a=t.workArea.width/t.scaleFactor,c=t.workArea.height/t.scaleFactor,d=Math.max((a-n)/2,0),h=Math.max((c-s)/2,0),u=Math.floor(r+d),l=Math.floor(o+h);return{left:u*i.scaleFactor,top:l*i.scaleFactor,width:e.width,height:e.height}}static isNode(){if(void 0!==si._isNode)return si._isNode;if("undefined"!=typeof window)return si._isNode=!1,!1;try{si._isNode="[object process]"===Object.prototype.toString.call(global.process)}catch(e){si._isNode=!1}return si._isNode}static generateId(){return((e=21)=>{let t="",i=e;for(;i--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return t})(10)}static calculateTotalOverlap(e,t){const i=e.left,n=e.top,s=i+e.width,r=n+e.height,o=t.left,a=t.top,c=o+t.width,d=a+t.height;return Math.max(0,Math.min(s,c)-Math.max(i,o))*Math.max(0,Math.min(r,d)-Math.max(n,a))}}const ri="T42.JumpList.Action";var oi=new class{constructor(){this._groupActionCallbacks=new Map,this._registered=!1}init(e,t,i){this._executor=e,this._agm=t,this._logger=i,this.registerCallbackMethod()}setEnabled(e,t){const i={enabled:t};return this._executor.updateJumpList(e,i)}createCategory(e,t,i){this.validateActions(t,i);const n={category:{title:t,operation:"create",actions:this.toUpdateActions(e,"create",t,i)}};return this._executor.updateJumpList(e,n)}removeCategory(e,t){const i={category:{title:t,operation:"remove",actions:[]}};return this.manageActionCallback(e,i.category.operation,t),this._executor.updateJumpList(e,i)}createActions(e,t,i){this.validateActions(t,i);const n={category:{title:t,operation:"update",actions:this.toUpdateActions(e,"create",t,i)}};return this._executor.updateJumpList(e,n)}removeActions(e,t,i){const n={category:{title:t,operation:"update",actions:this.toUpdateActions(e,"remove",t,i)}};return this._executor.updateJumpList(e,n)}async getActions(e,t){const i=[],n=(await this.getJumpListSettings(e)).categories.find((e=>e.title===t));return n&&n.actions.forEach((e=>{const t=this.getActionCallback(e.callbackId);t&&(e.callback=t.callback),i.push({icon:e.icon,callback:e.callback,singleInstanceTitle:e.singleInstanceTitle,multiInstanceTitle:e.multiInstanceTitle})})),Promise.resolve(i)}getJumpListSettings(e){return this._executor.getJumpList(e)}toUpdateActions(e,t,i,n){return n.map((n=>{const s={icon:n.icon,callback:n.callback,callbackId:si.generateId(),singleInstanceTitle:n.singleInstanceTitle,multiInstanceTitle:n.multiInstanceTitle,operation:t};return this.manageActionCallback(e,t,i,s),s}))}manageActionCallback(e,t,i,n){var s;const r=`${i}-${e}`;if("create"===t){this._groupActionCallbacks.has(r)||this._groupActionCallbacks.set(r,[]);this._groupActionCallbacks.get(r).push({callbackId:n.callbackId,callback:n.callback})}else if("remove"===t)if(n){let e=null!==(s=this._groupActionCallbacks.get(r))&&void 0!==s?s:[];e=e.filter((e=>e.callbackId!==n.callbackId)),0===e.length?this._groupActionCallbacks.delete(r):this._groupActionCallbacks.set(r,e)}else this._groupActionCallbacks.delete(r)}registerCallbackMethod(){if(!this._registered){this._registered=!0;try{this._agm.register(ri,((e,t)=>{const i=this.getActionCallback(e.callbackId);if(i)try{i.callback()}catch(e){this._logger.error("Unable to execute user callback for jump list action!",e)}}))}catch(e){return this._logger.error(`Unable to register method ${ri} for invoking jump list action callbacks!`,e),Promise.reject(e)}}}getActionCallback(e){let t;return[...this._groupActionCallbacks.values()].forEach((i=>{const n=i.find((t=>t.callbackId===e));n&&(t=n)})),t}validateActions(e,t){if(!(t&&t.length>0))throw new Error(`Category '${e}' doesn't contain any actions!`);t.forEach((t=>{if(!t.singleInstanceTitle)throw new Error(`Category '${e}' contains an action with undefined singleInstanceTitle!`);if(!t.multiInstanceTitle)throw new Error(`Category '${e}' contains an action with undefined multiInstanceTitle!`);if(!t.callback)throw new Error(`Category '${e}' contains an action with undefined callback function!`)}))}};var ai=new class{constructor(){this.waitForTimeoutInMilliseconds=6e4,this._windows={},this._pendingWindows={},this._pendingWindowsStates={},this._registry=Jt()}init(e){this._logger=e}get(e){return this._windows[e]||this._pendingWindows[e]}getIfReady(e){return this._windows[e]}get list(){return this._windows}add(e){if(!!this._pendingWindows[e.API.id])return void this._logger.error(`trying to add window with id ${e.API.id} from windowStore, which already exists`);const t="remote"===e.API.windowType;this._pendingWindows[e.API.id]=e,this._pendingWindowsStates[e.API.id]={ready:!1,urlChanged:t},this._registry.execute("on-added",e)}remove(e){delete this._windows[e.API.id],delete this._pendingWindows[e.API.id],delete this._pendingWindowsStates[e.API.id],this._registry.execute("on-removed",e)}setReadyState(e){const t=this._pendingWindowsStates[e];void 0!==t&&(t.ready=!0,t.urlChanged&&this.markReadyToShow(e))}setUrlChangedState(e){const t=this._pendingWindowsStates[e];void 0!==t&&(t.urlChanged=!0,t.ready&&this.markReadyToShow(e))}setCompositionChangedState(e,t){void 0!==this._pendingWindowsStates[e]&&!1===t&&this.markReadyToShow(e)}waitFor(e){return new Promise(((t,i)=>{let n,s;const r=setTimeout((()=>{n(),s(),i(`Window with id "${e}" was not ready within ${this.waitForTimeoutInMilliseconds} milliseconds.`)}),this.waitForTimeoutInMilliseconds),o=this._windows[e];if(o)clearTimeout(r),t(o);else{const o=()=>{clearTimeout(r),n(),s()};n=this.onReadyWindow((i=>{i.API.id===e&&(o(),t(i))})),s=this.onRemoved((t=>{t.API.id===e&&(o(),i(`Window with id "${e}" was removed before it became ready.`))}))}}))}onReadyWindow(e){return this._registry.add("on-ready",e)}onAdded(e){return this._registry.add("on-added",e)}onRemoved(e){return this._registry.add("on-removed",e)}markReadyToShow(e){this._pendingWindows[e]&&(this._windows[e]=this._pendingWindows[e],delete this._pendingWindows[e],delete this._pendingWindowsStates[e]),this._registry.execute("on-ready",this._windows[e])}};class ci{constructor(e,t){this.windowId=e,this._categoryTitle=t.title}list(){return oi.getActions(this.windowId,this._categoryTitle)}create(e){return oi.createActions(this.windowId,this._categoryTitle,e)}remove(e){return oi.removeActions(this.windowId,this._categoryTitle,e)}}class di{constructor(e){this.windowId=e}list(){return this.getCategories()}create(e,t){return oi.createCategory(this.windowId,e,t)}remove(e){return oi.removeCategory(this.windowId,e)}async find(e){return(await this.getCategories()).find((t=>t.title===e))}async getCategories(){const e=[];return(await oi.getJumpListSettings(this.windowId)).categories.forEach((t=>{e.push({title:t.title,actions:new ci(this.windowId,t)})})),e}}class hi{constructor(e){this.windowId=e,this._categories=new di(e)}get categories(){return this._categories}async isEnabled(){return(await oi.getJumpListSettings(this.windowId)).enabled}setEnabled(e){return oi.setEnabled(this.windowId,e)}}var ui=(e,t,i,n,s,r,o,a)=>{var c,d,h,u;const l=Jt(),p=()=>{const e=o();if(!e)throw new Error("To use this method you need to enable channels API - set the channels property to true when initializing the Glue42 library");return e},g=e,m=t.name,f=t.mode;let y=t.bounds,w=t.url,v=t.title,b=null!==(c=t.context)&&void 0!==c?c:{},_=t.frameColor,I=t.focus,C=null!==(d=t.neighbours)&&void 0!==d?d:{},A=t.groupId,S=t.isGroupHeaderVisible,x=t.isTabHeaderVisible,k=t.isGroupHibernated,T=t.isGroupVisible,E=null!==(h=t.isTabSelected)&&void 0!==h&&h,P=t.settings;const M=t.applicationName;let R,N=t.isVisible,j=t.isSticky,W=t.isCollapsed,O=t.state,F=t.tabGroupId,D=t.tabIndex,L=t.frameId,$=t.isLocked,G=t.allowWorkspaceDrop,B=t.isPinned,H=null!==(u=t.frameButtons)&&void 0!==u?u:[],U=t.zoomFactor,q=t.placementSettings;const J=new hi(e);function V(e,t,n){return si.callbackifyPromise((()=>{if(Ze(e))throw new Error("The properties of `bounds` cannot be null or undefined.");return i.moveResize(ee,e)}),t,n)}function z(e,t,n){return si.callbackifyPromise((()=>i.setVisible(ee,e)),t,n)}function K(e){return Q("group-changed",e)}function Q(e,t,i){if(!et(t))throw new Error("callback must be a function");return l.add(e,t,i)}function Z(e){const t=C[e];if(void 0!==t)return t.reduce(((e,t)=>{const i=ai.get(t);return i&&e.push(i.API),e}),[])}function X(){var t;if(M)return M;if(b._APPLICATION_NAME)return b._APPLICATION_NAME;if(b&&b._t42&&b._t42.application)return b._t42.application;const i=Y();if(i&&i.applicationName)return i.applicationName;const n=s();if(n){const i=n.instances().find((t=>e===t.id));if(i)return null===(t=i.application)||void 0===t?void 0:t.name}}function Y(){if("undefined"!=typeof window&&window.glue42gd&&window.glue42gd.getWindowInfo){const t=window.glue42gd.getWindowInfo(e);return t||void 0}}const ee={get id(){return g},get name(){return m},get application(){const e=s(),t=X();if(t&&e)return e.application(t)},get hostInstance(){return i.hostInstance},get interopInstance(){const e=a.servers().find((e=>e.windowId===this.id));if(e)return e;{const e=X();if(e)return{application:e}}},get agmInstance(){return ee.interopInstance},get url(){return w},get title(){return v},get windowStyleAttributes(){return P},get settings(){return P},get tabGroupId(){return"tab"===f.toLowerCase()?F:void 0},get tabIndex(){return"tab"===f.toLowerCase()?D:void 0},get frameId(){return L},get frameButtons(){return H.sort(((e,t)=>e.order-t.order))},get mode(){return f},get state(){return O},get isCollapsed(){return W},get isVisible(){return N},get isLocked(){return $},get context(){return b},get bounds(){return y},get minHeight(){return P.minHeight},get maxHeight(){return P.maxHeight},get minWidth(){return P.minWidth},get maxWidth(){return P.maxWidth},get isFocused(){return I},get frameColor(){return _},get opened(){return void 0!==ee.id},get group(){return R},get groupId(){return A},get isSticky(){return j},get topNeighbours(){return Z("top")},get leftNeighbours(){return Z("left")},get rightNeighbours(){return Z("right")},get bottomNeighbours(){return Z("bottom")},get isGroupHeaderVisible(){return S},get activityId(){if(b._t42)return b._t42.activityId;const e=Y();return e?e.activityId:void 0},get activityWindowId(){if(b._t42)return b._t42.activityWindowId;const e=Y();return e?e.activityWindowId:void 0},get windowType(){return t.windowType||"electron"},get zoomFactor(){return U},get screen(){if("undefined"!=typeof window&&window.glue42gd)return si.getMonitor(ee.bounds,window.glue42gd.monitors)},get placementSettings(){return Object.assign({},q)},get jumpList(){return J},get allowWorkspaceDrop(){return G},get isPinned(){return B},maximize:function(e,t){return si.callbackifyPromise((()=>"maximized"===O?Promise.resolve(ee):i.maximize(ee)),e,t)},restore:function(e,t){return si.callbackifyPromise((()=>"normal"===O?Promise.resolve(ee):i.restore(ee)),e,t)},minimize:function(e,t){return si.callbackifyPromise((()=>"minimized"===O?Promise.resolve(ee):i.minimize(ee)),e,t)},maximizeRestore:function(e,t){return si.callbackifyPromise((()=>i.maximizeRestore(ee)),e,t)},collapse:function(e,t){return si.callbackifyPromise((()=>W?Promise.resolve(ee):i.collapse(ee)),e,t)},expand:function(e,t){return si.callbackifyPromise((()=>W?i.expand(ee):Promise.resolve(ee)),e,t)},toggleCollapse:function(e,t){return si.callbackifyPromise((()=>i.toggleCollapse(ee)),e,t)},focus:function(e,t){return si.callbackifyPromise((()=>I?Promise.resolve(ee):i.focus(ee)),e,t)},activate:function(e,t){return si.callbackifyPromise((()=>I?Promise.resolve(ee):i.activate(ee)),e,t)},moveResize:V,setTitle:function(e,t,n){return si.callbackifyPromise((()=>{if(Ze(e))throw new Error("`newTitle` must not be null or undefined.");return e===v?Promise.resolve(ee):i.setTitle(ee,e)}),t,n)},setStyle:function(e,t,n){return si.callbackifyPromise((()=>{if(!e||0===Object.keys(e).length||Object.keys(e).every((e=>!e)))throw new Error("Invalid style arguments: "+JSON.stringify(e));if(e&&void 0!==e.focus){if("boolean"!=typeof e.focus)throw new Error("Focus must be a boolean value. Currently, only `focus: true` is supported.");!1===e.focus&&console.warn("`focus: false` is not supported!")}if(e&&void 0!==e.hidden&&"boolean"!=typeof e.hidden)throw new Error("The `hidden` property must hold a boolean value.");for(const t of["minHeight","maxHeight","minWidth","maxWidth"]){const i=e,n=i[t];if(t in e){if(Ze(n)){delete i[t];continue}if(!Je(i[t]))throw new Error(`"${t}" must be a number`)}}return i.setStyle(ee,e)}),t,n)},setOnTop:function(e,t,n){return si.callbackifyPromise((()=>{if("string"==typeof e){if("always"!==e)throw new Error("`onTop` must hold a `always` value.")}else if("boolean"!=typeof e)throw new Error("`onTop` must hold a boolean or `always` value.");return i.setOnTop(ee,e)}),t,n)},resetButtons:function(e,t,n){return si.callbackifyPromise((()=>i.resetButtons(ee,e)),t,n)},getButtons:function(){return i.getButtons(ee)},setSizeConstraints:function(e,t,n){return si.callbackifyPromise((()=>{if(!e||Object.keys(e).every((e=>void 0===e)))throw new Error("The properties of `constraints` cannot be null or undefined.");return i.setSizeConstraints(ee,e)}),t,n)},getSizeConstraints:function(){return i.getSizeConstraints(ee)},navigate:function(e,t,n){if("function"==typeof t)return si.callbackifyPromise((()=>{if(Xe(e))throw new Error("The new URL must be a non-empty string.");return i.navigate(ee,e)}),t,n);if(Xe(e))throw new Error("The new URL must be a non-empty string.");return i.navigate(ee,e,t)},addFrameButton:function(e,t,n){return si.callbackifyPromise((()=>{if(void 0===e||0===Object.keys(e).length)throw new Error("Button info is not available.");if(Xe(e.buttonId))throw new Error("`buttonId` must not be null or undefined.");if(Xe(e.imageBase64))throw new Error("`imageBase64` must not be null or undefined.");return i.addFrameButton(ee,e)}),t,n)},removeFrameButton:function(e,t,n){return si.callbackifyPromise((()=>{if(Xe(e))throw new Error("`buttonId` must not be null or undefined.");return i.removeFrameButton(ee,e)}),t,n)},setVisible:z,show:()=>z(!0),hide:()=>z(!1),center:async function(e){return e&&function(e){if("object"!=typeof e)throw Error("display argument must be a valid display object");if(!e.workArea||!e.scaleFactor)throw Error("display argument is not a valid display object")}(e),i.center(ee,e)},close:function(t,n){return void 0===t||"function"==typeof t?si.callbackifyPromise((()=>{if(!e)throw new Error("The window is already closed.");return i.close(ee)}),t,n):i.close(ee,t)},snap:function(e,t,n,s){return si.callbackifyPromise((()=>{if(Ze(e))throw new Error(`A target window is not specified - ${"string"==typeof e?e:JSON.stringify(e)}`);if("string"==typeof e){const t=ai.get(e);if(!t)throw new Error(`Invalid "target" parameter or no such window. Invoked with: ${e}`);e=t.API}return"string"==typeof t&&(t={direction:t,autoAlign:!0}),i.snap(ee,e,t)}),n,s)},showLoader:function(e){return i.showLoader(ee,e)},hideLoader:function(){return i.hideLoader(ee)},updateContext:function(e,t,n){return si.callbackifyPromise((()=>{if(Ze(e))throw new Error('"context" must not be null or undefined.');return i.updateContext(ee,e,!1)}),t,n)},lock:function(e,t){return si.callbackifyPromise((()=>i.lock(ee)),e,t)},unlock:function(e,t){return si.callbackifyPromise((()=>i.unlock(ee)),e,t)},getIcon:function(e,t){return si.callbackifyPromise((()=>i.getIcon(ee)),e,t)},setIcon:function(e,t,n){return si.callbackifyPromise((()=>{if(Xe(e))throw new Error('"base64Image" must be a non-empty string.');return i.setIcon(ee,e)}),t,n)},setFrameColor:function(e,t,n){return si.callbackifyPromise((()=>{if(Xe(e))throw new Error('"frameColor" must be a non-empty string');return i.setFrameColor(ee,e)}),t,n)},setTabTooltip:async function(e){if(Xe(e))throw new Error(`"${e}" must not be null or undefined`);return i.setTabTooltip(ee,e)},getTabTooltip:async function(){return i.getTabTooltip(ee)},attachTab:function(e,t,n,s){return si.callbackifyPromise((()=>{var n;const s='Invalid "tab" parameter - must be an object with an "id" property or a string. Invoked for source window with ID:';if(Ze(e)){const t=`${s} ${"string"==typeof e?e:JSON.stringify(e)}`;throw new Error(t)}let r;if("string"==typeof e){if(r=null===(n=ai.get(e))||void 0===n?void 0:n.API,Ze(r)){const e=`${s} ${"string"==typeof r?r:JSON.stringify(r)}`;throw new Error(e)}}else{if(Ze(e.id))throw new Error(s);r=e}const o={};return Ze(t)||("number"==typeof t?o.index=t:(o.selected=t.selected,o.index=t.index)),i.attachTab(ee,r,o)}),n,s)},detachTab:function(e={},t,n){return si.callbackifyPromise((()=>{const t={};return void 0!==e.relativeTo?("string"==typeof e.relativeTo?t.relativeTo=e.relativeTo:Ze(e.relativeTo.id)||(t.relativeTo=e.relativeTo.id),Ze(e.relativeDirection)||(t.relativeDirection=e.relativeDirection),Ze(e.width)||(t.width=e.width),Ze(e.height)||(t.height=e.height)):Ze(e.bounds)||(t.bounds=e.bounds),Ze(e.hideTabHeader)||(t.hideTabHeader=e.hideTabHeader),i.detachTab(ee,t)}),t,n)},setTabHeaderVisible:function(e,t,n){return si.callbackifyPromise((()=>{if("boolean"!=typeof e)throw new Error('"toBeTabHeaderVisible" must hold a boolean value.');return i.setTabHeaderVisible(ee,e)}),t,n)},showPopup:function(e){return i.showPopup(ee,e)},createFlydown:function(e){return i.createFlydown(ee.id,e)},setModalState:function(e){return i.setModalState(ee.id,e||!1)},setZoomFactor:function(e,t,n){return si.callbackifyPromise((()=>{if(isNaN(e))throw new Error("zoomFactor is not a number");return i.setZoomFactor(ee,e)}),t,n)},zoomIn:function(e,t){return si.callbackifyPromise((()=>i.zoomIn(ee)),e,t)},zoomOut:function(e,t){return si.callbackifyPromise((()=>i.zoomOut(ee)),e,t)},showDevTools:function(){return i.showDevTools(ee)},capture:function(e){return i.capture(ee,e)},flash:function(e,t){const n={shouldFlash:!0,mode:"auto"};return"boolean"==typeof e&&(n.shouldFlash=e),void 0!==t&&(n.mode=t),i.flash(ee,n)},flashTab:function(e){const t={shouldFlash:!0};return"boolean"==typeof e&&(t.shouldFlash=e),i.flashTab(ee,t)},setSticky:function(e,t,n){return si.callbackifyPromise((()=>{if("boolean"!=typeof e)throw new Error("`isSticky` must hold a boolean value.");return i.setSticky(ee,e)}),t,n)},setAllowWorkspaceDrop:function(e){if("boolean"!=typeof e)throw new Error("`allowWorkspaceDrop` must hold a boolean value.");return i.setAllowWorkspaceDrop(ee,e)},pin:function(){return i.pin(ee)},unpin:function(){return i.unpin(ee)},print:function(e){return i.print(ee,e)},printToPDF:function(e){return i.printToPDF(ee,e)},place:function(e){return i.place(ee,e)},ungroup:function(t){return new Promise(((n,s)=>{const r=K(((t,i,s)=>{e===t.id&&(r(),n(ee))}));i.ungroup(ee,t).catch((e=>{r(),s(e)}))}))},refresh:function(e){return i.refresh(ee,e)},goBack:function(){return i.goBack(ee)},goForward:function(){return i.goForward(ee)},download:function(e,t){return i.download(ee,e,t)},configure:function(e){return i.configureWindow(ee,e)},getConfiguration:function(){return i.getWindowConfiguration(ee)},getDockingPlacement:function(){return i.getDockingPlacement(ee)},dock:function(e){return i.dock(ee,e)},clone:async function(e){return i.clone(ee,e)},executeCode:async function(e){if(!e)throw new Error("Code argument is missing");if("string"!=typeof e)throw new Error("Code argument must be a valid string");return(await i.executeCode(ee,e)).result},getChannel:async()=>{var e;return null===(e=(await p().getWindowsWithChannels({windowIds:[g]}))[0])||void 0===e?void 0:e.channel},startDrag:function(e){return i.startDrag(ee,e)},showDialog:function(e){if((null==e?void 0:e.timerDuration)&&isNaN(null==e?void 0:e.timerDuration))throw new Error("timerDuration must be a number");if((null==e?void 0:e.showTimer)&&"boolean"!=typeof(null==e?void 0:e.showTimer))throw new Error("showTimer must be a boolean");return i.showDialog(ee,e)},onClose:function(t){if(!et(t))throw new Error("callback should be a function");return void 0===e&&t(ee),l.add("onClose",t)},onUrlChanged:function(e){return Q("onUrlChanged",e)},onTitleChanged:function(e){if(!et(e))throw new Error("callback should be a function");return e(ee.title,ee),Q("onTitleChanged",e)},onFrameButtonAdded:function(e){return Q("onFrameButtonAdded",e)},onFrameButtonRemoved:function(e){return Q("onFrameButtonRemoved",e)},onFrameButtonClicked:function(e){return Q("onFrameButtonClicked",e)},onCollapsed:function(e){if(!et(e))throw new Error("callback should be a function");return W&&e(ee),l.add("collapsed",e)},onExpanded:function(e){if(!et(e))throw new Error("callback should be a function");return W||e(ee),l.add("expanded",e)},onMinimized:function(e){return"minimized"===O?Q("minimized",e,[ee]):Q("minimized",e)},onMaximized:function(e){return"maximized"===O?Q("maximized",e,[ee]):Q("maximized",e)},onNormal:function(e){return"normal"===O?Q("normal",e,[ee]):Q("normal",e)},onAttached:function(e){return Q("attached",e)},onDetached:function(e){return Q("detached",e)},onVisibilityChanged:function(e){return Q("visibility-changed",e)},onContextUpdated:function(e){return Q("context-updated",e)},onLockingChanged:function(e){return Q("lock-changed",e)},onBoundsChanged:function(e){return Q("bounds-changed",e)},onFrameColorChanged:function(e){return Q("frame-color-changed",e)},onFocusChanged:function(e){return Q("focus-changed",e)},onStickyChanged:function(e){return Q("sticky-changed",e)},onGroupChanged:K,onWindowAttached:function(e){return Q("window-attached",e)},onWindowDetached:function(e){return Q("window-detached",e)},onTabSelectionChanged:function(e){return Q("tab-selection-changed",e)},onTabHeaderVisibilityChanged:function(e){return Q("tab-header-visibility-changed",e)},onClosing:function(e){if(!et(e))throw new Error("callback must be a function");return i.onClosing(((t,i,n)=>{const s=e(n);(null==s?void 0:s.then)?s.then(t).catch(i):t()}),ee)},onRefreshing:function(e){if(!et(e))throw new Error("callback must be a function");return i.onRefreshing(((t,i,n)=>{const s=e(n);(null==s?void 0:s.then)?s.then(t).catch(i):t()}),ee)},onZoomFactorChanged:function(e){return Q("zoom-factor-changed",e)},onPlacementSettingsChanged:function(e){return Q("placementSettingsChanged",e)},onNeighboursChanged:function(e){return Q("neighbours-changed",e)},onDockingChanged:function(e){return Q("docking-changed",e)},onNavigating:function(e){if(!et(e))throw new Error("callback must be a function");return i.onNavigating(((t,i,n,s)=>{const r=e(s);(null==r?void 0:r.then)?r.then(t).catch(i):t()}),ee)},onChannelRestrictionsChanged:function(e){if(!et(e))throw new Error("callback must be a function");return Q("channel-restrictions-changed",e)},get tabs(){return function(){const e=ai.list;return"tab"!==f.toLowerCase()?[]:Object.keys(e).reduce(((t,i)=>{const n=e[i];return n&&n.API.tabGroupId&&void 0!==n.API.tabGroupId&&void 0!==ee.tabGroupId&&n.API.tabGroupId===ee.tabGroupId&&t.push(n.API),t}),[]).sort(((e,t)=>{if(e.tabIndex!==t.tabIndex){if(-1===e.tabIndex)return Number.MAX_SAFE_INTEGER;if(-1===t.tabIndex)return Number.MIN_SAFE_INTEGER}return e.tabIndex-t.tabIndex}))}()},get isTabHeaderVisible(){return x},get isTabSelected(){return E},getURL:()=>Promise.resolve(w),getTitle:()=>Promise.resolve(v),getBounds:()=>Promise.resolve(y),getContext:()=>Promise.resolve(b),setContext(e){if(Ze(e))throw new Error('"context" must not be null or undefined, set to empty object if you want to clear it out.');return i.updateContext(ee,e,!0)},getDisplay:()=>r().getByWindowId(e),resizeTo:(e,t)=>V({width:e,height:t}),moveTo:(e,t)=>V({top:e,left:t}),async getParentWindow(){var e;const t=P.parentInstanceId;if(t)return null===(e=ai.list[t])||void 0===e?void 0:e.API},getChildWindows:async()=>Object.keys(ai.list).map((e=>ai.list[e].API)).filter((t=>t.settings.parentInstanceId===e)),joinChannel:t=>p().join(t,e),leaveChannel:()=>p().leave(e)};return{API:ee,Events:{handleUpdate:function(e){w=e.url,v=e.title,b=e.context||{},y=e.bounds,_=e.frameColor,I=e.focus,C=e.neighbours||{},A=e.groupId,S=e.isGroupHeaderVisible,x=e.isTabHeaderVisible,k=e.isGroupHibernated,T=e.isGroupVisible,E=e.isTabSelected,P=e.settings,N=e.isVisible,j=e.isSticky,W=e.isCollapsed,O=e.state,F=e.tabGroupId,L=e.frameId,$=e.isLocked,G=e.allowWorkspaceDrop,B=e.isPinned,U=e.zoomFactor,q=e.placementSettings},handleWindowClose:function(){void 0!==e&&(l.execute("onClose",ee),e=void 0)},handleWindowChangeState:async function(e){"collapsed"===e?W=!0:"expanded"===e?W=!1:O=e,await i.finished,l.execute(e,ee)},handleTitleChanged:function(e){v=e,i.finished.finally((()=>{l.execute("onTitleChanged",e,ee)}))},handleVisibilityChanged:function(e){e!==N&&(N=e,l.execute("visibility-changed",ee))},handleUrlChanged:function(e){w=e,l.execute("onUrlChanged",e,ee)},handleWindowSettingsChanged:function(e){P=e,l.execute("settings-changed",ee)},handleContextUpdated:function(e){b=e,l.execute("context-updated",b,ee)},handleFrameIsLockedChanged:function(e){$=e,l.execute("lock-changed",ee)},handleBoundsChanged:function(e){y.top===e.top&&y.left===e.left&&y.width===e.width&&y.height===e.height||(y=e,l.execute("bounds-changed",ee))},handleFocusChanged:function(e){I=e,l.execute("focus-changed",ee)},handleFrameButtonAdded:function(e){const t=["buttonId","imageBase64","order","tooltip"].reduce(((t,i)=>(t[i]=e[i],t)),{});-1===H.map((e=>e.buttonId)).indexOf(e.buttonId)&&H.push(t),l.execute("onFrameButtonAdded",t,ee)},handleFrameButtonRemoved:function(e){let t;H=H.reduce(((i,n)=>(n.buttonId===e?t=n:i.push(n),i)),[]),void 0!==t&&l.execute("onFrameButtonRemoved",t,ee)},handleFrameButtonClicked:function(e){const t=H.filter((t=>t.buttonId===e.buttonId));t.length>0&&l.execute("onFrameButtonClicked",t[0],ee)},handleFrameColorChanged:function(e){_=e,l.execute("frame-color-changed",ee)},handleFrameAttached:function(e,t,i){F=e,L=t,x=i,l.execute("frame-attached",ee)},handleFrameSelectionChanged:async function(t,n){let s;t===e?(E=!0,s=ee):(E=!1,s=ai.get(t)?ai.get(t).API:void 0);const r=ai.get(n)?ai.get(n).API:void 0;await i.finished,l.execute("tab-selection-changed",s,r,ee)},handleCompositionChanged:function(e){C=e.neighbors||{},D=e.index,l.execute("neighbours-changed",C,ee)},handleAllowWorkspaceDropChanged:function(e){G=e,l.execute("allow-workspace-drop-changed",ee)},handleIsPinnedChanged:function(e){B=e,l.execute("is-pinned-changed",ee)},handleGroupHeaderVisibilityChanged:function(e){S=e},handleTabHeaderVisibilityChanged:function(e){x!==e&&(x=e,l.execute("tab-header-visibility-changed",ee))},handleGroupChanged:function(e,t){R=e,A=null==e?void 0:e.id,Ze(e)||Ze(t)||l.execute("group-changed",ee,e,t)},handleAttached:async function(e,t,n,s,r){F=e,x=n,L=t,void 0!==s&&($=s),await i.finished,r.forEach((e=>{e.Events.handleWindowAttached(ee)})),l.execute("attached",ee)},handleDetached:async function(e,t){F=void 0,E=!1,void 0!==e&&($=e),await i.finished,t.forEach((e=>{e.Events.handleWindowDetached(ee)})),l.execute("detached",ee)},handleWindowAttached:function(e){l.execute("window-attached",e)},handleWindowDetached:function(e){l.execute("window-detached",e)},handleZoomFactorChanged:function(e){U=e,l.execute("zoom-factor-changed",ee)},handleIsStickyChanged:function(e){j=e,l.execute("sticky-changed",e,ee)},handlePlacementSettingsChanged:function(e){let t;const i=e;if(i.display){const e=r();if(e){const n=i.display-1;t=new Promise(((t,i)=>{e.all().then((e=>{const i=e.find((e=>e.index===n));t(i)})).catch(i)}))}else t=Promise.resolve(void 0)}else t=Promise.resolve(void 0);t.then((e=>{i.display=e,q=i,l.execute("placementSettingsChanged",ee)}))},handleDockingChanged:function(e){l.execute("docking-changed",ee,{docked:e.docked,position:e.position,claimScreenArea:e.claimScreenArea})},handleChannelRestrictionsChanged:function(e){l.execute("channel-restrictions-changed",e)}},GroupCreationArgs:{get isGroupHibernated(){return k},get isGroupVisible(){return T}}}};function li(e,t){const i=ai.list;return Object.keys(i).reduce(((n,s)=>{const r=i[s];return r.API.tabGroupId===t&&r.API.id!==e&&n.push(r),n}),[])}function pi(e){return!(e&&!Object.keys(e).every((t=>void 0===e[t])))}var gi=new class{constructor(){this.GroupMethodName="T42.Group.Execute",this.WndMethodName="T42.Wnd.Execute",this._registry=Jt(),this._finished=Promise.resolve(),this.unsubCallbacks={}}get hostInstance(){return this.agmTarget}get finished(){return this._finished}get configuration(){return this._configuration}init(e,t){this.agm=e,this.agmTarget=t,this._registry.add("event",(e=>{if("Closed"===e.type){Object.keys(this.unsubCallbacks).forEach((t=>{t.startsWith(e.windowId)&&delete this.unsubCallbacks[t]}))}}))}setConfiguration(e){this._configuration=e}handleEvent(e){this._registry.execute("event",e)}async open(e){let t;this._finished=new Promise((e=>{t=e}));try{const t=await this.agm.invoke("T42.Wnd.Create",e,this.agmTarget);if(void 0===t.returned)throw new Error("failed to execute T42.Wnd.Create - unknown reason");const i=t.returned.id,n=await ai.waitFor(i);return this.configuration&&!this.configuration.windowAvailableOnURLChanged||setTimeout((()=>{"electron"===n.API.windowType&&n.Events.handleUrlChanged(n.API.url)}),0),n.API}finally{t()}}async close(e,t){const i=await this.execute("close",{windowId:e.id,options:t},"Closed");return t?i.closed:e}async navigate(e,t,i){return await this.execute("navigate",{windowId:e.id,options:{url:t,urlLoadOptions:i}},"UrlChanged"),e}async setStyle(e,t){var i;const n=[],s=e=>n.push(e);if(Ze(t.focus)||e.isFocused||s(e.focus()),!Ze(t.hidden)){const i=!t.hidden;s(e.setVisible(i))}if(Ze(t.onTop)||s(e.setOnTop(t.onTop)),!Xe(t.tabTooltip)||!Xe(t.tabToolTip)){const n=null!==(i=t.tabTooltip)&&void 0!==i?i:t.tabToolTip;s(e.setTabTooltip(n))}Xe(t.tabTitle)||s(this.execute("setTabTitle",{windowId:e.id,options:{tabTitle:t.tabTitle}}));const r={minHeight:t.minHeight,minWidth:t.minWidth,maxHeight:t.maxHeight,maxWidth:t.maxWidth};!pi(r)&&s(e.setSizeConstraints(r));const o={allowClose:t.allowClose,allowCollapse:t.allowCollapse,allowLockUnlock:t.allowLockUnlock,allowMaximize:t.allowMaximize,allowMinimize:t.allowMinimize};return!pi(o)&&s(e.resetButtons(o)),await Promise.all(n),e}async setSizeConstraints(e,t){return await this.execute("setSizeConstraints",{windowId:e.id,options:t}),e}async getSizeConstraints(e){return await this.execute("getSizeConstraints",{windowId:e.id})}async setTabTooltip(e,t){return await this.execute("setTabTooltip",{windowId:e.id,options:{tabTooltip:t}}),e}async getTabTooltip(e){return(await this.execute("getTabTooltip",{windowId:e.id})).tabTooltip}async resetButtons(e,t){return await this.execute("resetButtons",{windowId:e.id,options:t}),e}async getButtons(e){return await this.execute("getButtons",{windowId:e.id})}async setOnTop(e,t){return await this.execute("setOnTop",{windowId:e.id,options:{onTop:t}}),e}async setTitle(e,t){const i={windowId:e.id,options:{title:t}};return await this.execute("setTitle",i,"TitleChanged"),e}async setSticky(e,t){const i={windowId:e.id,options:{isSticky:t}};return await this.execute("setSticky",i),e}async setAllowWorkspaceDrop(e,t){const i={windowId:e.id,options:{allowWorkspaceDrop:t}};return await this.execute("setAllowWorkspaceDrop",i),e}async pin(e){const t={windowId:e.id};return await this.execute("pinTab",t),e}async unpin(e){const t={windowId:e.id};return await this.execute("unpinTab",t),e}async moveResize(e,t){return"undefined"!=typeof window&&window.glueDesktop.versionNum<31200?new Promise((async(i,n)=>{const s=this.areBoundsEqual(t,e);let r=!1;const o=()=>{r||(r=!0,c&&(c(),c=void 0),i(e),a&&(clearTimeout(a),a=void 0))};let a,c;s||(c=e.onBoundsChanged((e=>{this.areBoundsEqual(t,e)&&o()})));try{await this.execute("moveResize",{windowId:e.id,options:{bounds:t}})}catch(e){return void n(e)}s?o():a=setTimeout((()=>{o()}),1e3)})):(await this.execute("moveResize",{windowId:e.id,options:{bounds:t}}),e)}async addFrameButton(e,t){return await this.execute("addButton",{windowId:e.id,options:t},"ButtonAdded"),e}async removeFrameButton(e,t){return await this.execute("removeButton",{windowId:e.id,options:t},"ButtonRemoved"),e}async activate(e){let t,i;try{const n=new Promise(((n,s)=>{t=e.onFocusChanged((()=>{n()})),i=e.onClose((()=>{s(new Error("Window was closed"))}))}));return await Promise.all([this.execute("activate",{windowId:e.id},"FocusChanged"),n]),e}finally{t&&t(),i&&i()}}async focus(e){let t,i;try{const n=new Promise(((n,s)=>{t=e.onFocusChanged((()=>{n()})),i=e.onClose((()=>{s(new Error("Window was closed"))}))}));return await Promise.all([this.execute("focus",{windowId:e.id},"FocusChanged"),n]),e}finally{t&&t(),i&&i()}}async maximizeRestore(e){return await this.execute("maximizeRestore",{windowId:e.id},"StateChanged"),e}async maximize(e){return await this.execute("maximize",{windowId:e.id},"StateChanged"),e}async restore(e){return await this.execute("restore",{windowId:e.id},"StateChanged"),e}async minimize(e){return await this.execute("minimize",{windowId:e.id},"StateChanged"),e}async collapse(e){return await this.execute("collapse",{windowId:e.id},"StateChanged"),e}async expand(e){return await this.execute("expand",{windowId:e.id},"StateChanged"),e}async toggleCollapse(e){return await this.execute("toggleCollapse",{windowId:e.id},"StateChanged"),e}async snap(e,t,i){const n={targetWindowId:t.id};return n.snappingEdge=i.direction,n.autoAlign=i.autoAlign,await this.execute("snap",{windowId:e.id,options:n},"CompositionChanged",`CompositionChanged-${t.id}`),e}async attachTab(e,t,i){return await this.execute("attachTab",{windowId:e.id,options:{index:i,sourceWindowId:t.id,targetWindowId:e.id}},`WindowFrameAdded-${t.id}`,`WindowFrameRemoved-${t.id}`),e}async detachTab(e,t){const i=["WindowFrameRemoved","WindowFrameAdded"];return Ze(null==t?void 0:t.relativeTo)?i.push("BoundsChanged"):(i.push("CompositionChanged"),i.push(`CompositionChanged-${t.relativeTo}`)),await this.execute("detachTab",{windowId:e.id,options:t},...i),e}async setVisible(e,t=!0){let i;return i=t?"show":"hide",await this.execute(i,{windowId:e.id},"VisibilityChanged"),e}async center(e,t){return await this.execute("center",{windowId:e.id,options:t}),e}async showLoader(e,t){return await this.execute("showLoadingAnimation",{windowId:e.id,options:t}),e}async hideLoader(e){return await this.execute("hideLoadingAnimation",{windowId:e.id}),e}async updateContext(e,t,i){let n;try{const s=this.swapUndefinedToNull(t),r=new Promise(((t,i)=>{n=e.onContextUpdated((()=>{t()}))}));return await Promise.all([this.execute("updateContext",{windowId:e.id,context:s,replace:i}),r]),e}finally{n&&n()}}async lock(e){return await this.execute("lockUnlock",{windowId:e.id,options:{lock:!0}},"FrameIsLockedChanged"),e}async unlock(e){return await this.execute("lockUnlock",{windowId:e.id,options:{lock:!1}},"FrameIsLockedChanged"),e}async getIcon(e){return(await this.execute("getIcon",{windowId:e.id,options:{}})).icon}async setIcon(e,t){return await this.execute("setIcon",{windowId:e.id,options:{dataURL:t}}),e}async setFrameColor(e,t){return await this.execute("setFrameColor",{windowId:e.id,options:{frameColor:t}},"FrameColorChanged"),e}async setTabHeaderVisible(e,t){return await this.execute("setTabHeaderVisible",{windowId:e.id,options:{toShow:t}},"TabHeaderVisibilityChanged"),e}async showGroupPopup(e,t){const i=this.showPopupCore(e,t);await this.executeGroup("showGroupPopup",{groupId:e,options:i})}async showPopup(e,t){const i=this.showPopupCore(e.id,t);return await this.execute("showPopupWindow",{windowId:e.id,options:i}),e}async createFlydown(e,t){if(!t)throw new Error("The options object is not valid!");const i={...t};i.horizontalOffset||(i.horizontalOffset=0),i.verticalOffset||(i.verticalOffset=0);const n=this.reformatFlydownOptions(e,i);return this.execute("setFlydownArea",{windowId:e,options:n}).then((()=>{const e=n.zones.map((e=>e.id));return n.zones.forEach((e=>{let i="function"==typeof e.flydownSize?e.flydownSize:()=>e.flydownSize;t.size instanceof Function&&e.flydownSize&&(i=async(i,n)=>{let s;return t.size instanceof Function&&(s=await t.size(i,n)),e.flydownSize instanceof Function&&e.flydownSize!==t.size?await e.flydownSize(i,n)||s:s||e.flydownSize}),this._registry.clearKey(`${n.targetId}_${e.id}`),this._registry.add(`${n.targetId}_${e.id}`,i)})),{destroy:()=>this.clearFlydownArea(n.targetId,e),options:i}}))}async setModalState(e,t){return this.execute("setModalState",{windowId:e,options:{isModal:t}})}async autoArrange(e){return this.execute("autoArrange",{options:{displayId:e}})}async handleFlydownBoundsRequested(e,t){const i={zoneId:t.flydownId,flydownWindowBounds:t.flydownWindowBounds,flydownWindowId:t.flydownWindowId},n=await Promise.all(this._registry.execute(`${e}_${t.flydownId}`,i,(()=>t.cancel=!0)));if(1===n.length){const e={height:0,width:0,top:0,left:0},i="object"!=typeof n[0]||Array.isArray(n[0])?e:n[0];return{...t,flydownWindowBounds:i}}}async handleOnEventRequested(e,t){var i;const n=null!==(i=this.unsubCallbacks[e])&&void 0!==i?i:[];let s=!1;const r=[];return await Promise.all(n.map((e=>new Promise(((i,n)=>{e((()=>{i()}),(()=>{n()}),(e=>{s=!0,r.push(e)}),t)}))))),{prevented:s,preventArgs:r}}async zoomIn(e){return await this.execute("zoomIn",{windowId:e.id}),e}async zoomOut(e){return await this.execute("zoomOut",{windowId:e.id}),e}async setZoomFactor(e,t){return await this.execute("setZoomFactor",{windowId:e.id,options:{zoomFactor:t}}),e}async showDevTools(e){return await this.execute("showDevTools",{windowId:e.id}),e}async capture(e,t){return(await this.execute("captureScreenshot",{windowId:e.id,options:{...t}})).data}async captureGroup(e,t){return(await this.execute("captureGroupScreenshot",{windowId:e[0],options:{groupWindowIds:e,...t}})).data}async flash(e,t){return await this.execute("flash",{windowId:e.id,options:{...t}}),e}async flashTab(e,t){return await this.execute("flashTab",{windowId:e.id,options:{...t}}),e}async configure(e,t){return this.execute("configure",{windowId:e,options:{...t}})}async print(e,t){return await this.execute("print",{windowId:e.id,options:{...t}}),e}async printToPDF(e,t){return(await this.execute("printToPDF",{windowId:e.id,options:{...t}})).filePath}async place(e,t){const i={...t};return t.display&&"current"!==t.display||(i.display=await e.getDisplay()),i.display&&"string"!=typeof i.display&&"number"!=typeof i.display&&(i.display=i.display.index+1),this.execute("place",{windowId:e.id,options:{...i}})}async refresh(e,t){return await this.execute("refresh",{windowId:e.id,options:{ignoreCache:t}}),e}async download(e,t,i={}){i.enableDownloadBar=!i.silent;const n=await this.execute("downloadURL",{windowId:e.id,options:{url:t,options:i}});return{url:t,path:n.fullPath,size:n.fileSize}}async configureWindow(e,t){return await this.execute("configureWindow",{windowId:e.id,options:t}),e}async getWindowConfiguration(e){return await this.execute("getWindowConfiguration",{windowId:e.id})}async startDrag(e,t){return await this.execute("startDrag",{windowId:e.id,options:t}),e}showDialog(e,t){return new Promise(((i,n)=>{const s=si.generateId(),r=this._registry.add("event",(t=>{if("DialogResult"===t.type&&t.windowId===e.id&&t.data.token===s){r();const e=t.data;"status"in e&&("failed"===e.status?n(e.message):"successful"===e.status&&i(e.result))}}));this.execute("showDialog",{windowId:e.id,options:Object.assign({},{...t},{token:s})})}))}async execute(e,t,...i){return this.executeCore(this.WndMethodName,e,t,...i)}async executeGroup(e,t,...i){return this.executeCore(this.GroupMethodName,e,t,...i)}async ungroup(e,t){const i={windowId:e.id,options:t};return await this.execute("ungroup",i),e}async updateJumpList(e,t){const i={windowId:e,options:t};await this.execute("updateJumplist",i)}async getJumpList(e){const t={windowId:e};return await this.execute("getJumplist",t)}onClosing(e,t){const i="undefined"!=typeof window&&window.glue42gd;return i&&"electron"===t.windowType?i.addCloseHandler(e,t.id):this.nonWindowHandlers(e,t.id,"OnClosing")}onGroupClosing(e,t){return this.nonWindowHandlersCore(t.id,"OnClosing",!0,e)}onRefreshing(e,t){const i="undefined"!=typeof window&&window.glue42gd;return i&&"electron"===t.windowType?i.addRefreshHandler(e,t.id):this.nonWindowHandlers(e,t.id,"OnRefreshing")}onNavigating(e,t){const i="undefined"!=typeof window&&window.glue42gd;return i&&"electron"===t.windowType?i.addWillNavigateHandler(e,t.id):this.nonWindowHandlers(e,t.id,"OnNavigating")}async clone(e,t){const i={windowId:e.id,options:t},n=await this.execute("clone",i);return(await ai.waitFor(n.id)).API}async executeCode(e,t){const i={windowId:e.id,options:{code:t}};return this.execute("executeCode",i)}async goBack(e){await this.execute("goBack",{windowId:e.id})}async goForward(e){await this.execute("goForward",{windowId:e.id})}async getDockingPlacement(e){return this.execute("getDockingPlacement",{windowId:e.id})}dock(e,t){return this.execute("dock",{windowId:e.id,options:t})}clearCallbacks(e){Object.keys(this.unsubCallbacks).forEach((t=>{t.startsWith(e)&&delete this.unsubCallbacks[t]}))}nonWindowHandlers(e,t,i){return this.nonWindowHandlersCore(t,i,!1,e)}nonWindowHandlersCore(e,t,i,n){const s=`${e}-${t}`,r=()=>{var r;if(this.unsubCallbacks[s]){const e=this.unsubCallbacks[s];this.unsubCallbacks[s]=e.filter((e=>e!==n)),0===this.unsubCallbacks[s].length&&delete this.unsubCallbacks[s]}if(0===(null!==(r=this.unsubCallbacks[s])&&void 0!==r?r:[]).length){const n={unsubscribe:!0};i?this.executeGroup(t,{groupId:e,options:n}):this.execute(t,{windowId:e,options:n})}};return this.unsubCallbacks[s]?(this.unsubCallbacks[s].push(n),r):(this.unsubCallbacks[s]=[n],i?this.executeGroup(t,{groupId:e}):this.execute(t,{windowId:e}),r)}reformatFlydownOptions(e,t){const i=(e,i)=>{if(t[i]&&(void 0===e[i]||null===e[i])){const n=t[i];e[i]=n}},n=t.zones.map((e=>(i(e,"windowId"),i(e,"targetLocation"),!t.size||void 0!==e.flydownSize&&null!==e.flydownSize||(e.flydownSize=t.size),e.flydownBounds=e.flydownSize,e.flydownId=e.windowId,e.targetLocation||(e.targetLocation="bottom"),e)));return{...t,zones:n,targetId:e,flydownBounds:t.size,flydownActiveArea:t.activeArea}}clearFlydownArea(e,t){return this.execute("clearFlydownWindowArea",{windowId:e,options:{}}).then((()=>{t.forEach((t=>{this._registry.clearKey(`${e}_${t}`)}))}))}executeWithoutToken(e,...t){const i=[],n=null==t?void 0:t.filter((e=>!Ze(e))).map((t=>new Promise((n=>{const[s,r=e.windowId]=t.split("-");i.push(this._registry.add("event",(e=>{e.type===s&&e.windowId===r&&n()})))})))),s=new Promise(((t,i)=>{this.agm.invoke("T42.Wnd.Execute",e,this.agmTarget).then((e=>{e.returned&&e.returned.errorMsg?i(e):t(e.returned)})).catch((e=>i(e)))}));return Promise.all([s,...n]).then((e=>e[0])).finally((()=>{i.forEach((e=>e()))}))}async executeCore(e,t,i,...n){const s={...i,command:t};let r;this._finished=new Promise((e=>{r=e}));try{return"undefined"!=typeof window&&window.glueDesktop.versionNum<31200?await this.executeWithoutToken(s,...n):await this.executeWithToken(e,s)}finally{r()}}async executeWithToken(e,t){let i;try{const n=si.generateId(),s=new Promise((e=>{i=this._registry.add("event",(t=>{t.token===n&&e()}))})),r=new Promise(((i,s)=>{t.token=n,this.agm.invoke(e,t,this.agmTarget).then((e=>{e.returned&&e.returned.errorMsg?s(e):i(e.returned)})).catch((e=>{s(e)}))}));return(await Promise.all([r,s]))[0]}finally{i&&i()}}areBoundsEqual(e,t){const i=t.bounds,n=t.settings;let s=e.height,r=e.width;e.height<n.minHeight&&(s=n.minHeight),e.height>n.maxHeight&&(s=n.maxHeight),e.width<n.minWidth&&(r=n.minWidth),e.width>n.maxWidth&&(r=n.maxWidth);const o=!s||i.height===s,a=!r||i.width===r,c=!e.left||i.left===e.left,d=!e.top||i.top===e.top;return o&&a&&c&&d}swapUndefinedToNull(e){try{const t={};for(const i of Object.keys(e)){let n=e[i];void 0===n&&(n=null),t[i]=n}return t}catch{return e}}showPopupCore(e,t){if(!t)throw new Error("The options object is not valid!");const i={...t};i.targetLocation||(i.targetLocation="bottom");return{...i,popupBounds:i.size,targetId:e,popupId:i.windowId}}};class mi{constructor(e,t,i,n,s,r,o){this._registry=Jt(),this._waitTimeout=1e4,this._agm=e,this._logger=t.subLogger("gd-env"),this._windowId=r,this._groupId=o,this._appManagerGetter=i,this._displayAPIGetter=n,this._channelsAPIGetter=s}init(){return new Promise(((e,t)=>{this._agm.register("T42.Wnd.OnEventWithResponse",((e,t)=>this.respondToEvent(e))),new Promise(((i,n)=>{this._agm.subscribe("T42.Wnd.OnEvent",{waitTimeoutMs:this._waitTimeout,target:"best",arguments:{withConfig:!0},onData:t=>{if("Configuration"===t.data.type)return this._configuration=t.data,void gi.setConfiguration(this._configuration);this.updateWindow(t.data,e),gi.handleEvent(t.data)},onConnected:e=>{this._agmInstance=e,gi.init(this._agm,this._agmInstance)}}).catch((e=>{var i;const n=`${null===(i=null==e?void 0:e.method)||void 0===i?void 0:i.name} - ${JSON.stringify(null==e?void 0:e.called_with)} - ${null==e?void 0:e.message}`;t(new Error(n))}))}))}))}get executor(){return gi}open(e,t,i){i=i||{};const n={...i};return void 0!==n.relativeTo&&"string"!=typeof n.relativeTo&&(n.relativeTo=n.relativeTo.id||""),n.name=e,n.url=t,n.windowState=i.windowState||i.state,delete n.state,this.executor.open(n)}createFlydown(e,t){return this.executor.createFlydown(e,t)}async showPopup(e,t){const i=ai.get(e);await this.executor.showPopup(i.API,t)}tabAttached(e){return this._registry.add("tab-attached",e)}tabDetached(e){return this._registry.add("tab-detached",e)}onWindowFrameColorChanged(e){return this._registry.add("frame-color-changed",e)}onEvent(e){return this._registry.add("window-event",e)}my(){return this._windowId}myGroup(){return this._groupId}execute(e,t,i){return this._agm.invoke("T42.Wnd.Execute",{command:e,options:i,windowId:t})}onCompositionChanged(e){return this._registry.add("composition-changed",e)}onGroupHeaderVisibilityChanged(e){return this._registry.add("group-header-changed",e)}onGroupVisibilityChanged(e){return this._registry.add("group-visibility-changed",e)}onGroupStateChanged(e){return this._registry.add("group-state-changed",e)}onWindowGotFocus(e){return this._registry.add("got-focus",e)}onWindowLostFocus(e){return this._registry.add("lost-focus",e)}onWindowsAutoArrangeChanged(e){return this._registry.add("windows-auto-arranged-changed",e)}respondToEvent(e){return"ShowFlydownBoundsRequested"===e.type?this.executor.handleFlydownBoundsRequested(e.data.windowId,e.data):"OnClosing"===e.type||"OnRefreshing"===e.type||"OnNavigating"===e.type?this.executor.handleOnEventRequested(e.data.callbackId,e.data.args):Promise.reject(`There isn't a handler for ${e.type}`)}updateWindow(e,t){var i;const n=this.getExtendedStreamEvent(e);if("Snapshot"===e.type){return e.windows.forEach((e=>{const t=ai.get(e.id);if(t)t.Events.handleUpdate(this.mapToWindowConstructorOptions(e)),t.GroupCreationArgs=this.mapToGroupCreationArgs(e);else{const t=this.createWindow(e.id,e);ai.markReadyToShow(t.API.id)}this._registry.execute("window-event",n)})),void t(this)}if("CommandExecuted"===e.type)return void this._registry.execute("window-event",n);if("Created"===e.type){const t=e,i=this.createWindow(t.windowId,t.data||{});return ai.setReadyState(i.API.id),void this._registry.execute("window-event",n)}if("OnGroupVisibilityChanged"===e.type){const t=e;return this._registry.execute("group-visibility-changed",t.data),void this._registry.execute("window-event",e)}if("OnGroupStateChanged"===e.type){const t=e;return this._registry.execute("group-state-changed",t.data),void this._registry.execute("window-event",e)}if("OnWindowsAutoArrangeChanged"===e.type){const t=e;return this._registry.execute("windows-auto-arranged-changed",t.data),void this._registry.execute("window-event",e)}const s=ai.get(e.windowId);if(!s)return void this._logger.error(`received update for unknown window. Stream:', ${JSON.stringify(e,null,4)}`);const r=s.API,o=s.Events;if("BoundsChanged"===e.type){const t=e;o.handleBoundsChanged(t.data)}if("UrlChanged"===e.type){const t=e;ai.setUrlChangedState(t.windowId),o.handleUrlChanged(t.data)}if("TitleChanged"===e.type){const t=e;o.handleTitleChanged(t.data)}if("IsStickyChanged"===e.type){const t=e;o.handleIsStickyChanged(t.data)}if("VisibilityChanged"===e.type&&o.handleVisibilityChanged(e.data),"ContextChanged"===e.type&&o.handleContextUpdated(e.data),"StateChanged"===e.type&&o.handleWindowChangeState(e.data),"FrameColorChanged"===e.type&&(o.handleFrameColorChanged(e.data),this._registry.execute("frame-color-changed",r)),"CompositionChanged"===e.type){const t=e;o.handleCompositionChanged(t.data),ai.setCompositionChangedState(t.data.windowId,null===(i=this._configuration)||void 0===i?void 0:i.windowAvailableOnURLChanged),this._registry.execute("composition-changed",t.data)}if("GroupHeaderVisibilityChanged"===e.type){const t=e;o.handleGroupHeaderVisibilityChanged(t.data.groupHeaderVisible),this._registry.execute("group-header-changed",t.data)}if("FocusChanged"===e.type){const t=e;this.focusChanged(o,r,t.data)}if("WindowFrameChanged"===e.type&&(o.handleFrameAttached(e.data.frameId,e.data.frameId,e.data.isTabHeaderVisible),this._registry.execute("frame-changed")),"WindowFrameAdded"===e.type){const t=li(r.id,e.data.frameId),i=e.data;o.handleAttached(i.frameId,i.frameId,i.isTabHeaderVisible,i.isLocked,t).then((async()=>{t.length>0&&(await gi.finished,this._registry.execute("tab-attached",r,e.data.frameId,e.data.isTabHeaderVisible))}))}if("WindowFrameRemoved"===e.type){const t=r.tabGroupId,i=li(r.id,t);o.handleDetached(e.data.isLocked,i).then((async()=>{i.length>0&&(await gi.finished,this._registry.execute("tab-detached",r,e.data.frameId,r.tabGroupId))}))}"TabHeaderVisibilityChanged"===e.type&&o.handleTabHeaderVisibilityChanged(e.data.isTabHeaderVisible),"FrameSelectionChanged"===e.type&&o.handleFrameSelectionChanged(e.data.newWindowId,e.data.prevWindowId),"ButtonClicked"===e.type&&o.handleFrameButtonClicked(e.data),"ButtonAdded"===e.type&&o.handleFrameButtonAdded(e.data),"ButtonRemoved"===e.type&&o.handleFrameButtonRemoved(e.data),"WindowZoomFactorChanged"===e.type&&o.handleZoomFactorChanged(e.data),"Closed"===e.type&&(ai.remove(s),o.handleWindowClose()),"FrameIsLockedChanged"===e.type&&o.handleFrameIsLockedChanged(e.data),"PlacementSettingsChanged"===e.type&&o.handlePlacementSettingsChanged(e.data),"DockingChanged"===e.type&&o.handleDockingChanged(e.data),"AllowWorkspaceDropChanged"===e.type&&o.handleAllowWorkspaceDropChanged(e.data),"IsPinnedChanged"===e.type&&o.handleIsPinnedChanged(e.data),"WindowChannelRestrictionsChanged"===e.type&&o.handleChannelRestrictionsChanged(e.data),this._registry.execute("window-event",n)}createWindow(e,t){const i=ui(e,this.mapToWindowConstructorOptions(t),gi,this._logger,this._appManagerGetter,this._displayAPIGetter,this._channelsAPIGetter,this._agm);return i.GroupCreationArgs=this.mapToGroupCreationArgs(t),ai.add(i),i}async focusChanged(e,t,i){e.handleFocusChanged(i);try{this._configuration.windowAvailableOnURLChanged||await ai.waitFor(t.id)}catch(e){return}i?this._registry.execute("got-focus",t):this._registry.execute("lost-focus",t)}mapToWindowConstructorOptions(e){return{name:e.name,context:e.context,bounds:e.bounds,url:e.url,title:e.title,isVisible:e.isVisible,focus:e.isFocused,state:e.state,frameColor:e.frameColor,groupId:e.groupId,neighbours:e.neighbors,isFocused:e.isFocused,isGroupHeaderVisible:e.groupHeaderVisible,isCollapsed:e.isCollapsed,tabGroupId:e.frameId,frameId:e.frameId,mode:e.mode,isTabHeaderVisible:e.isTabHeaderVisible,isTabSelected:e.isActiveTab,settings:e.settings,windowType:e.windowType,zoomFactor:e.zoomFactor,isLocked:e.isLocked,placementSettings:e.placementSettings,isSticky:e.isSticky,tabIndex:e.tabIndex,frameButtons:e.frameButtons,jumpListOptions:e.jumpList,applicationName:e.applicationName,allowWorkspaceDrop:e.allowWorkspaceDrop,isPinned:e.isPinned}}mapToGroupCreationArgs(e){return{isGroupHibernated:e.isGroupHibernated,isGroupVisible:e.isGroupVisible}}getExtendedStreamEvent(e){try{if(!e.windowId)return e;const t=ai.get(e.windowId);if(!t)return e;const i={state:e.type,windowName:t.API.name,...e};return"WindowFrameAdded"===i.state&&(i.state="TabAttached"),"StateChanged"===i.state&&(i.state=i.data.charAt(0).toUpperCase()+i.data.slice(1)),"ButtonAdded"===i.state&&(i.state="FrameButtonAdded"),"ButtonRemoved"===i.state&&(i.state="FrameButtonRemoved"),i}catch(t){return e}}}var fi=(e,t)=>{const i=Jt(),n=[];let s,r;async function o(e,i,...n){return await t.execute(e,i,...n),d}function a(){const e=[];return n.forEach((t=>{const i=c(t);void 0!==i&&e.push(i)})),e}function c(e){return ai.get(e)?ai.get(e).API:void 0}const d={id:e,get windows(){return function(e){const t=a();return"function"==typeof e&&e(t),t}()},find:function(e,t,i){let n;"string"==typeof e?n=e:Ze(e)||(n=e.id);const s=c(n);if(s)return"function"==typeof t&&t(s),s;"function"==typeof i&&i(`No window with ID: ${n}`)},get isHeaderVisible(){return void 0===a().find((e=>!e.isGroupHeaderVisible))},get isHibernated(){return s},get isVisible(){return r},showHeader:(e,t)=>si.callbackifyPromise((()=>o("setGroupHeaderVisibility",{windowId:n[0],options:{toShow:!0}},...n.map((e=>`GroupHeaderVisibilityChanged-${e}`)))),e,t),hideHeader:(e,t)=>si.callbackifyPromise((()=>o("setGroupHeaderVisibility",{windowId:n[0],options:{toShow:!1}},...n.map((e=>`GroupHeaderVisibilityChanged-${e}`)))),e,t),getTitle:async()=>(await t.execute("getGroupTitle",{windowId:n[0]})).title,setTitle:async e=>{if(Xe(e))throw new Error("`title` must not be null or undefined.");return o("setGroupTitle",{windowId:n[0],options:{title:e}})},capture:e=>t.captureGroup(n,e),maximize:(e,t)=>si.callbackifyPromise((()=>o("maximizeGroup",{windowId:n[0]},...n.map((e=>`StateChanged-${e}`)))),e,t),restore:(e,t)=>si.callbackifyPromise((()=>o("restoreGroup",{windowId:n[0]},...n.map((e=>`StateChanged-${e}`)))),e,t),show:i=>{if(!Ze(i)&&!Ye(i))throw new Error("Activate flag must be a boolean!");return i=!!Ze(i)||i,t.executeGroup("showGroup",{groupId:e,options:{activate:i}})},hide:()=>t.executeGroup("hideGroup",{groupId:e}),close:()=>t.executeGroup("closeGroup",{groupId:e}),showPopup:i=>t.showGroupPopup(e,i),onHeaderVisibilityChanged:function(e){return i.add("header-visibility-changed",e)},onWindowAdded:function(e){return i.add("window-added",e)},onWindowRemoved:function(e){return i.add("window-removed",e)},onVisibilityChanged:function(e){if(!e)throw new Error("Callback argument is required");if(e&&"function"!=typeof e)throw new Error("Callback argument must be a function");return i.add("group-visibility-changed",e)},onClosing:function(e){if("function"!=typeof e)throw new Error("callback must be a function");return t.onGroupClosing(((t,i,n)=>{const s=e(n);(null==s?void 0:s.then)?s.then(t).catch(i):t()}),d)}},h={get windows(){return n},addWindow:async function(e){var o,a,c,h;if(-1===n.indexOf(e)){n.push(e);const u=ai.get(e);u.Events.handleGroupChanged(d,void 0),s=null!==(a=null!==(o=u.GroupCreationArgs.isGroupHibernated)&&void 0!==o?o:s)&&void 0!==a&&a,r=null===(h=null!==(c=u.GroupCreationArgs.isGroupVisible)&&void 0!==c?c:r)||void 0===h||h,await t.finished,i.execute("window-added",d,u.API)}},removeWindow:async function(e){const s=n.indexOf(e.API.id);-1!==s&&(n.splice(s,1),e.Events.handleGroupChanged(void 0,d),await t.finished,i.execute("window-removed",d,e.API))},handleGroupHeaderVisibilityChanged:function(e){i.execute("header-visibility-changed",d)},handleGroupVisibilityChanged:function(e){r=e,i.execute("group-visibility-changed",d)},handleGroupHibernateChanged:function(e){s=e}};return{groupAPI:d,groupInternal:h}},yi=(e,t)=>{const i=Jt(),n={};let s=-1;const r=ai.list;function o(e,t,i){let s;"string"==typeof e?s=e:Ze(e)||(s=e.id);const r=Object.values(n).find((e=>e.groupAPI.windows.filter((e=>e.id===s)).length));if(r)return"function"==typeof t&&t(r.groupAPI),r.groupAPI;"function"==typeof i&&i("Cannot find the group of the window.")}function a(e){return e?new Promise(((t,i)=>{const s=n[e];if(s)t(s.groupAPI);else{const i=c((n=>{n.id===e&&(i(),t(n))}))}})):Promise.reject(new Error("groupId must be defined"))}function c(e){return i.add("group-added",e)}function d(t,s){const r=function(t){if(n.hasOwnProperty(t))return n[t];{const s=fi(t,e.executor);n[t]=s;const r=s.groupAPI;return i.execute("group-added",r),s}}(t);return r.groupInternal.addWindow(s),r}function h(e,t){e&&(e.groupInternal.removeWindow(t),function(e){const t=e.groupAPI;0===t.windows.length&&(delete n[t.id],gi.clearCallbacks(t.id),i.execute("group-removed",t))}(e))}function u(e){let t;return"string"==typeof e?t=e:Ze(e)||(t=e.id),Object.values(n).find((e=>e.groupInternal.windows.filter((e=>e===t)).length))}Object.keys(r).forEach((e=>{const t=r[e],i=t.API.groupId,n=t.API.id;Xe(i)||d(i,n)})),ai.onRemoved((e=>{h(u(e.API),e)})),e.onCompositionChanged((e=>{!function(e){const t=e.groupId,s=e.windowId,r=ai.get(s);if(!r)return;const o=u(r.API);if(Ze(t))return void h(o,r);if(Ze(o)&&!Ze(t))return void d(t,r.API.id);o.groupAPI.id!==t&&function(e,t,s){const r=e.API.id,o=n[t];h(o,e);const a=d(s,r);e.Events.handleGroupChanged(a.groupAPI,o.groupAPI),i.execute("window-moved",r,t,s)}(r,o.groupAPI.id,t)}(e)})),e.onGroupHeaderVisibilityChanged((e=>{const t=o(e.windowId);if(void 0!==t){const i=n[t.id];-1===s&&(s=t.windows.length),s--,0===s&&(s=-1,i.groupInternal.handleGroupHeaderVisibilityChanged(e))}})),e.onGroupVisibilityChanged((e=>{const t=n[e.groupId];t&&t.groupInternal.handleGroupVisibilityChanged(e.visible)})),e.onGroupStateChanged((e=>{const t=n[e.groupId];"hibernated"===e.state?((null==t?void 0:t.groupAPI)&&t.groupInternal.handleGroupHibernateChanged(!0),i.execute("group-hibernated",e.groupId)):"resumed"===e.state&&((null==t?void 0:t.groupAPI)&&t.groupInternal.handleGroupHibernateChanged(!1),i.execute("group-resumed",t.groupAPI))}));const l={get my(){return function(){var t;return o(null!==(t=e.myGroup())&&void 0!==t?t:e.my())}()},create:async function(e){if(Ze(e))throw new Error("options must be defined");if(Ze(e.groups)||!Array.isArray(e.groups)||0===e.groups.length)throw new Error("options.groups must be defined");const{groupIds:t}=await gi.executeGroup("createGroups",{options:e}),i=t.map((e=>a(e)));return Promise.all(i)},close:async function(e,t){if(Ze(e))throw new Error("group must be defined");let i="";if(i="string"==typeof e?e:e.id,Ze(t))throw new Error("options must be defined");await gi.executeGroup("closeGroup",{groupId:i,options:t})},list:function(e){const t=Object.keys(n).map((e=>{if(n[e])return n[e].groupAPI}));return"function"==typeof e&&e(t),t},findGroupByWindow:o,waitForGroup:a,getMyGroup:function(){var t;return a(null!==(t=e.myGroup())&&void 0!==t?t:e.my())},onGroupAdded:c,onGroupRemoved:function(e){return i.add("group-removed",e)},hibernate:async function(e){return await gi.executeGroup("hibernateGroup",{groupId:e}),e},resume:async function(e,t){if(!Ze(t)&&!Ye(t))throw new Error("Activate flag must be a boolean!");t=!!Ze(t)||t,await gi.executeGroup("resumeGroup",{groupId:e,options:{activate:t}})},onHibernated:function(e){if(!e)throw new Error("Callback argument is required");if(e&&"function"!=typeof e)throw new Error("Callback argument must be a function");return i.add("group-hibernated",e)},onResumed:function(e){if(!e)throw new Error("Callback argument is required");if(e&&"function"!=typeof e)throw new Error("Callback argument must be a function");return i.add("group-resumed",e)}};return{groupsAPI:l,groupsEvents:{onWindowMoved:function(e){return i.add("window-moved",e)}}}},wi=(e,t,i,n,s,r)=>{const o=Jt(),a=t;let c,d;ai.init(a);const h=new Promise(((t,o)=>{((e,t,i,n,s,r)=>{var o;const a=t;if(2===r)throw a.trace("running in HC"),new Error("GD2 not supported");return r>=3?(a.trace("running in GD 3"),new mi(e,a,i,n,s,window.glue42gd.windowId,null===(o=window.webGroupsManager)||void 0===o?void 0:o.id).init()):new mi(e,a,i,n,s).init()})(e,a,i,n,s,r).then((i=>{d=i,c=yi(i),oi.init(i.executor,e,a),t()})).catch((e=>{const t=`Timed out waiting for connection to Glue42 Enterprise: Error: ${e.message}`;a.error(t,e),o(new Error(t))}))}));function u(){const e=ai.getIfReady(d.my());return e?e.API:void 0}function l(e){return o.add("window-added",e)}function p(e){return o.add("window-removed",e)}return ai.onReadyWindow((function(e){o.execute("window-added",e.API)})),ai.onRemoved((function(e){o.execute("window-removed",e.API)})),{my:u,open:function(e,t,i,n,s){return si.callbackifyPromise((()=>{if(Xe(e))throw new Error("The window name is missing.");if(Xe(t))throw new Error("The window URL is missing.");if(!Ze(i)){const e=i;for(const t of["minHeight","maxHeight","minWidth","maxWidth","width","height","top","left"])if(t in e){const i=e[t];if(Ze(i)){delete e[t];continue}if(!Je(i)){throw new Error(`${t} must be a number`)}if(("width"===e[t]||"height"===e[t])&&i<=0){throw new Error(`${t} must be a positive number`)}}}return d.open(e,t,i)}),n,s)},find:function(e,t,i){const n=ai.list,s=Object.keys(n).reduce(((t,i)=>{var s;const r=n[i];return(null===(s=null==r?void 0:r.API)||void 0===s?void 0:s.name)===e&&t.push(r.API),t}),[]);if(s[0])return"function"==typeof t&&t(s[0]),s[0];"function"==typeof i&&i("There is no window with name:"+e)},findById:function(e,t,i){const n=ai.list,s=Object.keys(n).reduce(((t,i)=>{const s=n[i];return void 0!==s&&s.API.id===e&&t.push(s.API),t}),[]);if(s[0])return"function"==typeof t&&t(s[0]),s[0];"function"==typeof i&&i("There is no window with such id:"+e)},list:function(e){const t=ai.list,i=Object.keys(t).map((e=>t[e].API));if("function"!=typeof e)return i;e(i)},ready:function(){return h},onWindowAdded:l,windowAdded:l,onWindowRemoved:p,windowRemoved:p,onTabAttached:function(e){let t,i=!1;return h.then((()=>{i||(t=d.tabAttached(e))})),()=>{i=!0,t&&t()}},onTabDetached:function(e){let t,i=!1;return h.then((()=>{i||(t=d.tabDetached(e))})),()=>{i=!0,t&&t()}},onWindowFrameColorChanged:function(e){let t,i=!1;return h.then((()=>{i||(t=d.onWindowFrameColorChanged(e))})),()=>{i=!0,t&&t()}},onArrangementChanged:function(e){return d.onWindowsAutoArrangeChanged(e)},get groups(){return c.groupsAPI},onWindowGotFocus:function(e){let t,i=!1;return h.then((()=>{i||(t=d.onWindowGotFocus(e))})),()=>{i=!0,t&&t()}},onWindowLostFocus:function(e){let t,i=!1;return h.then((()=>{i||(t=d.onWindowLostFocus(e))})),()=>{i=!0,t&&t()}},onEvent:function(e){let t,i=!1;return h.then((()=>{i||(t=d.onEvent(e))})),()=>{i=!0,t&&t()}},createFlydown:function(e,t){return d.createFlydown(e,t)},showPopup:function(e,t){return d.showPopup(e,t)},configure:function(e){const t=u(),i=t?t.id:"";return gi.configure(i,e)},autoArrange:function(e){return gi.autoArrange(e)}}};var vi=new class{constructor(){this.layouts=[]}removeWhere(e){this.layouts=this.layouts.filter(e)}removeAll(){this.layouts=[]}add(e){this.layouts.push(e)}get all(){return this.layouts}where(e){return this.layouts.filter(e)}first(e){return this.where(e)[0]}};class bi{constructor(e,t,i,n){this.config=e,this.activitiesGetter=t,this.callbacks=i,this.logger=n,this.interop=e.agm,this.registerRequestMethods()}onSaveRequested(e){return this.callbacks.add("saveRequested",e)}isActivityOwner(){if("undefined"!=typeof htmlContainer){const e=htmlContainer.getContext();return e&&e._t42&&e._t42.activityIsOwner}const e=this.activitiesGetter();if(!e)return!1;if(!e.inActivity)return!1;const t=e.my.window,i=e.my.activity;return!(!i&&!t)&&i.owner.id===t.id}registerRequestMethods(){this.interop.register("T42.HC.GetSaveContext",(e=>{const t=this.callbacks.execute("saveRequested",e);(null==t?void 0:t.length)>1&&this.logger.warn('Multiple subscriptions for "glue.layouts.onSaveRequested" - only the first one will be used');const i=t[0],n=this.config.autoSaveWindowContext;if("boolean"==typeof n&&n)return{autoSaveWindowContext:n};if(Array.isArray(n)&&n.length>0)return{autoSaveWindowContext:n};const s={windowContext:null==i?void 0:i.windowContext,activityContext:void 0};return this.isActivityOwner()&&(s.activityContext=null==i?void 0:i.activityContext),s}))}}function _i(e){if(!e)return e;if(Array.isArray(e))return e.map((e=>_i(e)));if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;return Object.keys(e).reduce(((t,i)=>{var n;const s=_i(e[i]);let r=i;return(null===(n=i[0])||void 0===n?void 0:n.toLowerCase())!==i[0]&&(r=i[0].toLowerCase()+i.substr(1)),t[r]=s,t}),{})}class Ii{constructor(e){this.name=e.name,this.type=e.type,this.components=e.components,this.context=e.context,this.metadata=e.metadata,this.version=e.version,this.displays=e.displays}}const Ci="T42.ACS.Command";class Ai{constructor(e,t,i,n){this.config=e,this.stream=t,this.callbacks=i,this.isRegisterMethodForLayoutModified=!1,this.appManager=e.appManager,this.provider=new bi(e,e.activityGetter,i,n),t.subscribe()}async setDefaultGlobal(e){await this.invokeMethodCore("SelectDefaultLayout",{name:e})}async clearDefaultGlobal(){this.invokeMethodCore("DeselectDefaultLayout")}async getDefaultGlobal(){const e=(await this.invokeMethodCore("GetDefaultLayout")).returned;if(e)return this.isSlimMode()?e:this.list().find((t=>t.name===e.name&&"Global"===t.type))}ready(){return"fullWaitSnapshot"===this.config.mode?this.stream.gotSnapshot:this.stream.ready}save(e){return new Promise(((t,i)=>{var n,s;if(this.verifyNotSlimMode(),Ze(e))return i(new Error("layout is required"));if(Xe(e.name))return i(new Error("layout.name argument is required"));Xe(e.type)&&(e.type="Global"),Xe(e.activityId)||(e.type="Activity");const r={name:e.name,type:e.type,context:null!==(n=e.context)&&void 0!==n?n:{},metadata:null!==(s=e.metadata)&&void 0!==s?s:{},options:{}};if("Activity"===e.type){let t=e.activityId;if(!t){if(!this.appManager.myInstance.inActivity)return i(new Error("Current application is not in activity. Cannot save activity layout for it."));t=this.appManager.myInstance.activityId}r.activityId=t}else{if("Global"!==e.type)return i(new Error(`layout type ${e.type} is not supported`));Array.isArray(e.ignoreInstances)&&(r.options.ignoreInstances=e.ignoreInstances),Array.isArray(e.instances)&&(r.options.instances=e.instances),"boolean"==typeof e.setAsCurrent&&(r.options.setAsCurrent=e.setAsCurrent)}this.invokeMethodAndTrack("SaveLayout",r,t,i)}))}restore(e){return new Promise(((t,i)=>{var n,s,r;if(this.verifyNotSlimMode(),Ze(e))return i(new Error("options argument is required"));if(Xe(e.name))return i(new Error("options.name argument is required"));if(Xe(e.type)&&(e.type="Global"),Xe(e.activityIdToJoin)||(e.type="Activity"),"Activity"===e.type){if(Ze(e.setActivityContext)&&(e.setActivityContext=!0),"boolean"!=typeof e.setActivityContext)return i(new Error("`setActivityContext` must hold a boolean value."));e.activityIdToJoin=null!==(n=e.activityIdToJoin)&&void 0!==n?n:this.appManager.myInstance.activityId}if(Ze(e.closeRunningInstance)||(e.closeRunningInstances=e.closeRunningInstance),Ze(e.closeRunningInstances)&&(e.closeRunningInstances=!0),!Ye(e.closeRunningInstances))return i(new Error("`closeRunningInstances` must hold a boolean value."));if(Ze(e.closeMe)&&(e.closeMe=e.closeRunningInstances),!Ye(e.closeMe))return i(new Error("`closeMe` must hold a boolean value."));if(!Ze(e.context)&&!ze(e.context))return i(new Error("`context` must hold an object value."));if(!Ze(e.timeout)&&"number"!=typeof e.timeout)return i(new Error("`timeout` must hold an number value."));e.context=null!==(s=e.context)&&void 0!==s?s:{};const o={activityToJoin:e.activityIdToJoin,setActivityContext:e.setActivityContext,ignoreActivityWindowTypes:e.ignoreActivityWindowTypes,reuseExistingWindows:e.reuseWindows,closeRunningInstances:e.closeRunningInstances,excludeFromClosing:e.closeMe?[]:[null===(r=this.appManager.myInstance)||void 0===r?void 0:r.id]},a={type:e.type,name:e.name,context:e.context,options:o};e.timeout&&(a.timeout=e.timeout),this.invokeMethodAndTrack("RestoreLayout",a,t,i,!0)}))}reset(e){return new Promise(((t,i)=>{if(this.verifyNotSlimMode(),"object"!=typeof e)return i(new Error("options argument is required"));if(Xe(e.layoutId))return i(new Error("options.layoutId argument is required"));const n={...e};this.invokeMethodAndTrack("ResetLayout",n,t,i,!0)}))}remove(e,t){return new Promise(((i,n)=>{if(this.verifyNotSlimMode(),!t)return n(new Error("name argument is required"));if(!e)return n(new Error("type argument is required"));const s={type:e,name:t};this.invokeMethodAndTrack("RemoveLayout",s,i,n)}))}list(){return this.verifyNotSlimMode(),vi.all}import(e,t){return new Promise(((i,n)=>{if(this.verifyNotSlimMode(),!Ze(t)&&"merge"!==t&&"replace"!==t)return n(new Error(`${t} is not supported - only "merge" and "replace"`));if(!Array.isArray(e))return n(new Error("layouts arguments is not an array"));const s={mode:t||"replace",layouts:e};this.invokeMethodAndTrack("ImportLayouts",s,i,n,!0)}))}export(e){return new Promise(((t,i)=>{this.invokeMethodAndTrack("ExportLayouts",{},(i=>{let n=this.getObjectValues(i.Layouts).map((e=>new Ii(_i(e))));e&&(n=n.filter((t=>t.type===e))),t(n)}),i,!0)}))}rename(e,t){return new Promise(((i,n)=>{if(this.verifyNotSlimMode(),!e)return n(new Error("layout argument is required"));if(!e.name)return n(new Error("name argument is required"));if(!e.type)return n(new Error("type argument is required"));const s={type:e.type,oldName:e.name,newName:t};this.invokeMethodAndTrack("RenameLayout",s,i,n)}))}updateMetadata(e){return new Promise(((t,i)=>{if(!e)return i(new Error("layout argument is required"));if(!e.name)return i(new Error("name argument is required"));if(!e.type)return i(new Error("type argument is required"));if(!e.metadata)return i(new Error("metadata argument is required"));const n={name:e.name,type:e.type,metadata:e.metadata};this.invokeMethodAndTrack("UpdateMetadata",n,t,i,!0)}))}hibernate(e,t){return new Promise(((i,n)=>{if(!e)return n(new Error("name cannot be empty"));const s={name:e,type:"Global",context:(t=t||{}).context||{},metadata:t.metadata||{}};this.invokeMethodAndTrack("HibernateLayout",s,i,n,!0)}))}resume(e,t,i){return new Promise(((n,s)=>{if(!e)return s(new Error("name cannot be empty"));const r={name:e,type:"Global",context:t,...i};this.invokeMethodAndTrack("ResumeLayout",r,n,s,!0)}))}async getCurrentLayout(){let e=(await this.invokeMethodCore("GetCurrentLayout")).returned.layout;if(e)return this.isSlimMode()||(e=this.list().find((t=>t.name===e.name&&t.type===e.type))),e}getRestoredLayoutsInfo(){return new Promise(((e,t)=>{this.invokeMethodCore("GetRestoredLayoutsInfo").then((t=>{const i=t.returned;e(i)})).catch(t)}))}onAdded(e){const t=this.callbacks.add("added",e);return vi.all.length>0&&vi.all.forEach((t=>{try{e(t)}catch(e){}})),t}onRemoved(e){return this.callbacks.add("removed",e)}onChanged(e){return this.callbacks.add("changed",e)}onRestored(e){return this.callbacks.add("restored",e)}onRenamed(e){return this.callbacks.add("renamed",e)}onEvent(e){return this.stream.onEvent(e)}onSaveRequested(e){return this.provider.onSaveRequested(e)}onLayoutModified(e){return!1===this.isRegisterMethodForLayoutModified&&(this.isRegisterMethodForLayoutModified=!0,this.registerMethodForLayoutModified()),this.callbacks.add("layout-modified",e)}updateAppContextInCurrent(e){return new Promise(((t,i)=>{if(e&&"object"!=typeof e)return i(new Error("context must be an object"));const n={context:e=null!=e?e:{}};this.invokeMethodAndTrack("UpdateLayoutComponentContext",n,t,i,!0)}))}updateDefaultContext(e){return new Promise(((t,i)=>{if(e&&"object"!=typeof e)return i(new Error("context must be an object"));const n={context:e=null!=e?e:{}};this.invokeMethodAndTrack("UpdateDefaultContext",n,t,i,!0)}))}async get(e,t){const i=this.list().find((i=>i.name===e&&i.type===t));if(!i)throw new Error(`cannot find layout with name=${e} and type=${t}`);return i}async getAll(e){return this.list().filter((t=>e===t.type))}async forceRefresh(){await this.invokeMethodCore("RefreshLayouts")}isSlimMode(){return"slim"===this.config.mode}verifyNotSlimMode(){if(this.isSlimMode())throw Error("Operation not allowed in slim mode. Run in full mode.")}async registerMethodForLayoutModified(){await this.config.agm.register("T42.ACS.LayoutModified",((e,t)=>{this.callbacks.execute("layout-modified",e)}))}invokeMethodAndTrack(e,t,i,n,s){let r,o=s;const a=si.generateId();t.token=a;const c=()=>{o&&r&&i(r)},d=12e4;s||this.stream.waitFor(a,d).then((()=>{o=!0,c()})).catch((e=>{n(e)}));this.invokeMethodCore(e,t,"best",{methodResponseTimeoutMs:d}).then((t=>{if(!t.returned)return n(new Error("No result from method "+e));if(t.returned.status&&"Success"!==t.returned.status&&"PartialSuccess"!==t.returned.status){if("string"==typeof t.returned)return n(new Error(t.returned));if("object"==typeof t.returned)return t.returned.status&&t.returned.failed?n(new Error(`${t.returned.status}: ${JSON.stringify(t.returned.failed)}`)):n(new Error(t.returned))}r=t.returned,c()})).catch((e=>n(e)))}async invokeMethodCore(e,t,i,n){return this.isCommandMethodPresent()?await this.config.agm.invoke(Ci,{command:e,data:t},i,n):await this.config.agm.invoke(`T42.ACS.${e}`,t,i,n)}getObjectValues(e){return e?Object.keys(e).map((t=>e[t])):[]}isCommandMethodPresent(){return this.config.agm.methods().some((e=>e.name===Ci))}}class Si{constructor(e,t){this.agm=e,this.callbacks=t,this.StreamName="T42.ACS.OnLayoutEvent",this.ready=new Promise(((e,t)=>{this.resolveReady=e,this.rejectReady=t})),this.gotSnapshot=new Promise(((e,t)=>{this.resolveGotSnapshot=e,this.rejectGotSnapshot=t}))}subscribe(e){const t=e=>this.getObjectValues(e).map((e=>_i(e)));this.checkForLayoutEventMethod()?this.agm.subscribe(this.StreamName,{waitTimeoutMs:1e4}).then((e=>{e.onData((e=>{const i=e.data;i.IsSnapshot&&this.resolveGotSnapshot(),this.addLayouts(t(i.OnLayoutAdded),i.IsSnapshot),this.removeLayouts(t(i.OnLayoutRemoved)),this.changeLayouts(t(i.OnLayoutChanged)),this.renameLayouts(t(i.OnLayoutRenamed)),this.restoredLayout(t(i.OnLayoutRestored)),this.callbacks.execute("streamEvent",i)})),e.onFailed((e=>{const t=`Can not subscribe to "${this.StreamName}" stream - ${JSON.stringify(e)}`;this.rejectReady(t),this.rejectGotSnapshot(t)})),this.resolveReady()})).catch((e=>{const t=`Error subscribing to "${this.StreamName}" stream - ${JSON.stringify(e)}`;this.rejectReady(t),this.rejectGotSnapshot(t)})):(e&&this.resolveReady(),setTimeout((()=>{this.subscribe(!0)}),500))}onEvent(e){return this.callbacks.add("streamEvent",e)}waitFor(e,t){return t||(t=3e4),new Promise(((i,n)=>{let s=!1;const r=this.onEvent((t=>{t.Token===e&&(s=!0,r(),i())}));setTimeout((()=>{s||n("timed out")}),t)}))}checkForLayoutEventMethod(){try{return-1!==this.agm.methods().map((e=>e.name)).indexOf(this.StreamName)}catch(e){return!1}}addLayouts(e,t){if(!e)return;const i=e=>{const t=new Ii(e);vi.add(t),this.callbacks.execute("added",t)};e.forEach((e=>{if(t){vi.first((t=>this.compareLayouts(t,e)))||i(e)}else i(e)}))}removeLayouts(e){e&&e.forEach((e=>{vi.removeWhere((t=>!this.compareLayouts(t,e))),this.callbacks.execute("removed",e)}))}changeLayouts(e){e&&e.forEach((e=>{vi.removeWhere((t=>!this.compareLayouts(t,e))),vi.add(new Ii(e)),this.callbacks.execute("changed",e)}))}renameLayouts(e){e&&e.forEach((e=>{const t=vi.first((t=>this.compareLayouts(t,{type:e.type,name:e.oldName})));if(!t)throw Error(`received rename event for unknown layout with type ${e.type} and name ${e.oldName}`);t.name=e.newName,this.callbacks.execute("renamed",t)}))}compareLayouts(e,t){return e.name===t.name&&e.type===t.type}getObjectValues(e){return e?Object.keys(e).map((t=>e[t])):[]}restoredLayout(e){e&&e.forEach((e=>{const t=vi.first((t=>this.compareLayouts(t,{type:e.type,name:e.name})));this.callbacks.execute("restored",t)}))}}function xi(e){if(!e.agm)throw Error("config.agm is required");if(!e.logger)throw Error("config.logger is required");e.mode=e.mode||"slim";const t=e.logger,i=Jt();let n;return e.mode,n=new Si(e.agm,i),new Ai(e,n,i,t)}class ki{constructor(e,t){this._agm=e,this._logger=t,this._registry=Jt(),this._registered=!1,this.all=async()=>(await this.callGD(Ti.GetAll,{})).map(this.decorateDisplay),this.get=async e=>{const t=await this.callGD(Ti.Get,{id:e});return this.decorateDisplay(t)},this.getPrimary=async()=>(await this.all()).find((e=>e.isPrimary)),this.capture=async e=>await this.callGD(Ti.Capture,{...e}),this.captureAll=async e=>await this.callGD(Ti.CaptureAll,{...e}),this.getMousePosition=async()=>await this.callGD(Ti.GetMousePosition),this.callGD=async(e,t)=>(await this._agm.invoke("T42.Displays.Command",{options:{...t},command:e})).returned.data,this.decorateDisplay=e=>{const t={...e,capture:t=>this.capture({id:e.id,size:t})},i=t.workArea;return i.x=i.left,i.y=t.workArea.top,t}}getByWindowId(e){return this.callGD(Ti.GetByWindowId,{id:e})}onDisplayChanged(e){return this.register(),this._registry.add("on-display-changed",e)}register(){this._registered||(this._registered=!0,this._agm.register("T42.Displays.OnEvent",((e,t)=>{const i=e.event,n=e.data;if("display-changed"===i)this._registry.execute("on-display-changed",n.displays.map(this.decorateDisplay));else this._logger.warn(`unknown event - ${i}`)})))}}var Ti;let Ei,Pi;!function(e){e.Capture="capture",e.CaptureAll="captureAll",e.GetAll="getAll",e.Get="get",e.GetByWindowId="getByWindowId",e.GetMousePosition="getMousePosition"}(Ti||(Ti={}));const Mi="T42.Channels.Announce";async function Ri(e,t){Ei.invoke("T42.Channels.Announce",{swId:null!=t?t:Pi,command:"switchChannel",data:{newChannel:e}})}async function Ni(e){try{return(await Ei.invoke(Mi,{swId:null!=e?e:Pi,command:"getRestrictions"})).returned}catch(e){return}}async function ji(e,t,i){await Ei.invoke(Mi,{command:e,data:{id:t,color:i}})}const Wi="___channel___",Oi="latest_fdc3_type";class Fi{constructor(e){this.contexts=e}subscribe(e){this.callback=e}subscribeFor(e,t){if(!this.isChannel(e))return Promise.reject(new Error(`Channel with name: ${e} doesn't exist!`));const i=this.createContextName(e);return this.contexts.subscribe(i,((e,i,n,s,r)=>{t(e.data,e,null==r?void 0:r.updaterId)}))}async switchChannel(e){this.unsubscribe();const t=this.createContextName(e);this.unsubscribeFunc=await this.contexts.subscribe(t,((e,t,i,n,s)=>{this.callback&&this.callback(e.data,e,null==s?void 0:s.updaterId)}))}leave(){this.callback&&this.callback({},void 0),this.unsubscribe()}all(){return this.contexts.all().filter((e=>e.startsWith(Wi))).map((e=>e.substr(13)))}async getContextData(e){if(!this.isChannel(e))throw new Error(`A channel with name: ${e} doesn't exist!`);const t=this.createContextName(e),i=await this.contexts.get(t);return i[Oi]?this.getContextWithFdc3Data(i):i}updateChannel(e,t){const i=this.createContextName(e);return this.contexts.update(i,t)}updateData(e,t){const i=this.createContextName(e),n=this.getFDC3Type(t);if(this.contexts.setPathSupported){const e=Object.keys(t).map((e=>({path:"data."+e,value:t[e]})));return n&&e.push({path:Oi,value:n}),this.contexts.setPaths(i,e)}return n&&(t[Oi]=n),this.contexts.update(i,{data:t})}setPaths(e,t){const i=this.createContextName(e);if(this.contexts.setPathSupported){const e=t.map((e=>({path:"data."+e.path,value:e.value})));return e.map((t=>{const i=this.getFDC3Type(t.value);i&&e.push({path:Oi,value:i})})),this.contexts.setPaths(i,e)}throw new Error("setPaths is not supported!")}isChannel(e){return this.all().some((t=>t===e))}async remove(e){if(!this.isChannel(e))throw new Error(`A channel with name: ${e} doesn't exist!`);const t=this.createContextName(e);await this.contexts.destroy(t)}unsubscribe(){this.unsubscribeFunc&&this.unsubscribeFunc()}createContextName(e){return Wi+e}getFDC3Type(e){const t=Object.keys(e).filter((e=>0===e.indexOf("fdc3_")));if(0!==t.length){if(t.length>1)throw new Error("FDC3 does not support updating of multiple context keys");return t[0].split("_").slice(1).join("_")}}getContextWithFdc3Data(e){const{latest_fdc3_type:t,...i}=e,n={type:t.split("&").join("."),...i.data[`fdc3_${t}`]};delete i.data[`fdc3_${t}`];return{name:e.name,meta:e.meta,data:{...i.data,fdc3:n}}}}class Di{constructor(e,t,i,n){this.shared=e,this.interop=t,this.getWindows=i,this.logger=n,this.subsKey="subs",this.changedKey="changed",this.isInitialJoin=!0,this.registry=Jt(),this.pendingReplays={},this.pendingRestrictionCallbacks=new Map,this.shared.subscribe(this.handler.bind(this)),this.subscribeForChannelRestrictionsChange(),"undefined"!=typeof window&&void 0!==window.glue42gd&&(this.currentContext=window.glue42gd.initialChannel,this.currentContext&&this.joinNoSelectorSwitch(this.currentContext))}subscribe(e){if("function"!=typeof e)throw new Error("Please provide the callback as a function!");const t=si.generateId();this.pendingReplays[t]=!0;const i=this.getWrappedSubscribeCallback(e,t);if(this.lastUpdate){let e=Object.assign({},this.lastUpdate);setTimeout((async()=>{this.pendingReplays[t]&&(this.lastUpdate&&(e=this.lastUpdate),i(e.context.data,e.context,e.updaterId)),delete this.pendingReplays[t]}),0)}const n=this.registry.add(this.subsKey,i);return()=>{this.pendingReplays[t]=!1,this.pendingRestrictionCallbacks.delete(t),n()}}async subscribeFor(e,t){if("string"!=typeof e)throw new Error("Please provide the name as a string!");if("function"!=typeof t)throw new Error("Please provide the callback as a function!");const i=si.generateId(),n=this.getWrappedSubscribeCallback(t,i),s=await this.shared.subscribeFor(e,n);return()=>{this.pendingRestrictionCallbacks.delete(i),s()}}async publish(e,t){if("object"!=typeof e)throw new Error("Please provide the data as an object!");if(t&&this.validatePublishOptions(t),"object"==typeof t)return this.publishWithOptions(e,t);const i="string"==typeof t?t:this.currentContext;if(!i)throw new Error("Not joined to any channel!");if(!this.shared.isChannel(i))return Promise.reject(new Error(`A channel with name: ${i} doesn't exist!`));if(!(await this.getRestrictionsByChannel(i)).write)throw new Error(`Window does not have permission to write to channel ${this.currentContext}`);return this.shared.updateData(i,e)}async setPaths(e,t){if(t){if("string"!=typeof t)throw new Error("Please provide the name as a string!");if(!this.shared.isChannel(t))return Promise.reject(new Error(`A channel with name: ${t} doesn't exist!`));if(!(await this.getRestrictionsByChannel(t)).write)throw new Error(`Window does not have permission to write to channel ${t}`);return this.shared.setPaths(t,e)}if(!this.currentContext)throw new Error("Not joined to any channel!");if(!(await this.getRestrictionsByChannel(this.currentContext)).write)throw new Error(`Window does not have permission to write to channel ${this.currentContext}`);if(!Array.isArray(e))throw new Error("Path Values argument is not a valid array");return e.forEach((e=>{this.validatePathArgs(e)})),this.shared.setPaths(this.currentContext,e)}async setPath(e,t){if(t){if("string"!=typeof t)throw new Error("Please provide the name as a string!");if(!this.shared.isChannel(t))return Promise.reject(new Error(`A channel with name: ${t} doesn't exist!`));if(!(await this.getRestrictionsByChannel(t)).write)throw new Error(`Window does not have permission to write to channel ${t}`);return this.shared.setPaths(t,[e])}if(!this.currentContext)throw new Error("Not joined to any channel!");if(!(await this.getRestrictionsByChannel(this.currentContext)).write)throw new Error(`Window does not have permission to write to channel ${this.currentContext}`);return this.validatePathArgs(e),this.shared.setPaths(this.currentContext,[e])}all(){const e=this.shared.all();return Promise.resolve(e)}async list(){const e=await this.all();return await Promise.all(e.map((e=>this.get(e))))}get(e){return"string"!=typeof e?Promise.reject(new Error("Please provide the channel name as a string!")):this.shared.getContextData(e)}getMy(){return this.currentContext?this.get(this.currentContext):Promise.resolve(void 0)}async join(e,t){return t?Ri(e,t):this.joinCore(e)}async joinNoSelectorSwitch(e){return this.joinCore(e,!1)}leave(e){return e?Ri(void 0,e):this.leaveCore()}leaveNoSelectorSwitch(){return this.leaveCore(!1)}current(){return this.currentContext}my(){return this.current()}changed(e){if("function"!=typeof e)throw new Error("Please provide the callback as a function!");return this.current()&&setTimeout((()=>{e(this.current())}),0),this.registry.add(this.changedKey,e)}onChanged(e){return this.changed(e)}async add(e){if("object"!=typeof e)throw new Error("Please provide the info as an object!");if(void 0===e.name)throw new Error("info.name is missing!");if("string"!=typeof e.name)throw new Error("Please provide the info.name as a string!");if(void 0===e.meta)throw new Error("info.meta is missing!");if("object"!=typeof e.meta)throw new Error("Please provide the info.meta as an object!");if(void 0===e.meta.color)throw new Error("info.meta.color is missing!");if("string"!=typeof e.meta.color)throw new Error("Please provide the info.meta.color as a string!");const t={name:e.name,meta:e.meta||{},data:e.data||{}};return await this.shared.updateChannel(e.name,t),await ji("addChannel",e.name,e.meta.color),t}async remove(e){if("string"!=typeof e)throw new Error("Please provide the channel name as a string!");await this.shared.remove(e),await ji("removeChannel",e)}async getWindowsOnChannel(e){if("string"!=typeof e)throw new Error("Please provide the channel name as a string!");return(await this.getWindowsWithChannels({channels:[e]})).map((e=>e.window))}async getWindowsWithChannels(e){try{const t=await async function(e){return(await Ei.invoke(Mi,{command:"getChannelsInfo",data:{filter:e}})).returned}(e),i=this.getWindows();if(null==t?void 0:t.windows)return t.windows.map((e=>({window:i.findById(e.windowId),channel:e.channel,application:e.application})))}catch(e){this.logger.error("Error getting all channel enabled windows. This method is available since Glue42 3.12",e)}return[]}async restrict(e){return async function(e){var t;await Ei.invoke(Mi,{swId:null!==(t=e.windowId)&&void 0!==t?t:Pi,command:"restrict",data:e})}(e)}async getRestrictions(e){return Ni(e)}async restrictAll(e){return async function(e){var t;await Ei.invoke(Mi,{swId:null!==(t=e.windowId)&&void 0!==t?t:Pi,command:"restrictAll",data:e})}(e)}handleRestrictionsChanged(e,t){this.registry.execute("restrictions-changed",{restrictions:e,windowId:t})}handler(e,t,i){t||i?(this.lastUpdate={context:t,updaterId:i},this.pendingReplays={},this.registry.execute(this.subsKey,e,t,i)):this.lastUpdate=void 0}async joinCore(e,t=!0){if("string"!=typeof e)throw new Error("Please provide the channel name as a string!");if(!this.isInitialJoin&&e===this.currentContext)return;this.isInitialJoin=!1;const i=e=>this.shared.all().includes(e);if(!i(e)){const t=new Promise(((t,n)=>{const s=setInterval((()=>{i(e)&&(clearTimeout(r),clearInterval(s),t())}),100),r=setTimeout((()=>(clearInterval(s),n(new Error(`A channel with name: ${e} doesn't exist!`)))),3e3)}));await t}this.currentContext=e,this.lastUpdate=void 0,await this.shared.switchChannel(e),t&&Ri(e),this.registry.execute(this.changedKey,e)}leaveCore(e=!0){return this.currentContext=void 0,this.registry.execute(this.changedKey,void 0),this.shared.leave(),e&&Ri(),Promise.resolve()}async getRestrictionsByChannel(e){var t;const i=null!==(t=this.channelRestrictions)&&void 0!==t?t:await Ni();if(!i||!Array.isArray(i.channels)||!i.channels.find((t=>t.name===e)))return{read:!0,write:!0};return i.channels.find((t=>t.name===e))}onRestrictionsChanged(e,t,i){this.pendingRestrictionCallbacks.set(t,{cb:e,channelName:i}),this.onRestrictionsChangedSub||(this.onRestrictionsChangedSub=this.registry.add("restrictions-changed",(({restrictions:e})=>{this.pendingRestrictionCallbacks.forEach((({cb:t,channelName:i},n)=>{const s=e.channels.find((e=>e.name===i));s&&s.read&&(this.pendingRestrictionCallbacks.delete(n),0===this.pendingRestrictionCallbacks.values.length&&this.onRestrictionsChangedSub&&(this.onRestrictionsChangedSub(),this.onRestrictionsChangedSub=null),t())}))})))}subscribeForChannelRestrictionsChange(){this.registry.add("restrictions-changed",(e=>{this.channelRestrictions=e.restrictions}))}validatePathArgs(e){if(!e)throw new Error("Please provide a valid path value argument");if("object"!=typeof e)throw new Error(`Path Value argument is not a valid object: ${JSON.stringify(e)}`);if(!e.path)throw new Error(`path property is missing from Path Value argument: ${JSON.stringify(e)}`);if(!e.value)throw new Error(`value property is missing from Path Value argument: ${JSON.stringify(e)}`);if("string"!=typeof e.path)throw new Error(`path property is not a valid string from the Path Value argument: ${JSON.stringify(e)}`)}validatePublishOptions(e){if("string"!=typeof e&&"object"!=typeof e||Array.isArray(e))throw new Error("Provide options as a string or an object");if("object"!=typeof e){if("string"===e&&!e.length)throw new Error("Provide options as a non-empty string")}else this.validatePublishOptionsObject(e)}validatePublishOptionsObject(e){if("object"!=typeof e||Array.isArray(e))throw new Error("Provide options as an object");if(e.name&&("string"!=typeof e.name||!e.name.length))throw new Error("Provide options.name as a non-empty string");if(Object.keys(e).includes("fdc3")&&"boolean"!=typeof e.fdc3)throw new Error("Provide options.fdc3 as a boolean")}async publishWithOptions(e,t){const i=t.name||this.currentContext;if(!this.shared.isChannel(i))throw new Error(`A channel with name: ${t.name} doesn't exist!`);if(!i)throw new Error("Cannot publish to channel, because not joined to a channel!");if(!(await this.getRestrictionsByChannel(i)).write)throw new Error(`Window does not have permission to write to channel ${this.currentContext}`);return t.fdc3?this.publishFdc3Data(i,e):this.shared.updateData(i,e)}async publishFdc3Data(e,t){var i;if("string"!=typeof t.type||!(null===(i=t.type)||void 0===i?void 0:i.length))throw new Error("Expected a valid FDC3 Context with compulsory 'type' field");const{type:n,...s}=t,r={[`fdc3_${n.split(".").join("&")}`]:s};return this.shared.updateData(e,r)}getWrappedSubscribeCallback(e,t){return async(i,n,s)=>{const r=await this.getRestrictionsByChannel(n.name),o=this.getDataWithFdc3Encoding(n);r.read?e(o,n,s):this.onRestrictionsChanged((()=>{e(o,n,s)}),t,n.name)}}getDataWithFdc3Encoding(e){const{data:t,latest_fdc3_type:i}=e;if(!i)return t;const n=i.split("&").join("."),s=`fdc3_${i}`,r={type:n,...t[s]},{[s]:o,...a}=t;return{...a,fdc3:r}}}function Li(e,t,i,n){const s=new Fi(e),r=new Di(s,t,i,n),o=async function(e,t){var i,n;if(Ei=e,"undefined"!=typeof window&&window.glue42gd&&(Pi=window.glue42gd.windowId),!Pi)return;await Ei.register("T42.Channels.Command",(e=>{const i=e.command;if(!i)throw new Error("missing command argument");if("join"!==i)if("leave"!==i){if("get"===i)return{id:t.current()};if("restrictions-changed"!==i){if("isFdc3DataWrappingSupported"===i)return{isSupported:!0};throw new Error(`unknown command ${i}`)}{const i=e.restrictions,n=e.swId;t.handleRestrictionsChanged(i,n)}}else t.leaveNoSelectorSwitch();else{const i=e.channel;if(!i)throw new Error("missing argument id");t.joinNoSelectorSwitch(i)}}));const s=await Ei.invoke("T42.Channels.Announce",{swId:Pi,instance:Ei.instance.instance});(null===(i=s.returned)||void 0===i?void 0:i.restrictions)&&t.handleRestrictionsChanged(null===(n=s.returned)||void 0===n?void 0:n.restrictions,Pi)}(t,r);return{subscribe:r.subscribe.bind(r),subscribeFor:r.subscribeFor.bind(r),publish:r.publish.bind(r),setPath:r.setPath.bind(r),setPaths:r.setPaths.bind(r),all:r.all.bind(r),list:r.list.bind(r),get:r.get.bind(r),join:r.join.bind(r),leave:r.leave.bind(r),restrict:r.restrict.bind(r),getRestrictions:r.getRestrictions.bind(r),restrictAll:r.restrictAll.bind(r),current:r.current.bind(r),my:r.my.bind(r),changed:r.changed.bind(r),onChanged:r.onChanged.bind(r),add:r.add.bind(r),remove:r.remove.bind(r),getWindowsOnChannel:r.getWindowsOnChannel.bind(r),getWindowsWithChannels:r.getWindowsWithChannels.bind(r),getMy:r.getMy.bind(r),ready:async()=>{await Promise.all([e.ready(),o])}}}const $i="T42.Hotkeys.Command";class Gi{constructor(e){this.agm=e,this.registry=Jt(),this.firstHotkey=!0,this.hotkeys=new Map}async register(e,t){if(void 0===e)throw new Error("Hotkey parameter missing");if("string"==typeof e)e={hotkey:e};else{if(!e.hotkey)throw new Error("Info's hotkey parameter missing");e={hotkey:e.hotkey,description:e.description}}const i=this.formatHotkey(e.hotkey);if(this.hotkeys.has(i))throw new Error(`Shortcut for ${i} already registered`);this.firstHotkey&&(this.firstHotkey=!1,await this.registerInvokeAGMMethod()),this.registry.add(i,t),await this.agm.invoke($i,{command:"register",hotkey:i,description:e.description}),this.hotkeys.set(i,e)}async unregister(e){if(void 0===e)throw new Error("hotkey parameter missing");if("string"!=typeof e)throw new Error("hotkey parameter must be string");const t=this.formatHotkey(e);await this.agm.invoke($i,{command:"unregister",hotkey:t}),this.hotkeys.delete(t),this.registry.clearKey(t)}async unregisterAll(){await this.agm.invoke($i,{command:"unregisterAll"}),this.hotkeys.clear(),this.registry.clear()}isRegistered(e){const t=this.formatHotkey(e);return this.hotkeys.has(t)}registerInvokeAGMMethod(){return this.agm.register("T42.Hotkeys.Invoke",(e=>{const t=e.key.toLowerCase(),i=this.hotkeys.get(t);this.registry.execute(t,i)}))}formatHotkey(e){if(e)return e.replace(/\s/g,"").toLowerCase()}}var Bi="6.8.2",Hi=e=>{function t(e,t,n){if("boolean"==typeof e&&!e)return;const s=i(e,t,n);return void 0!==s?"object"==typeof e?(e.mode=s,e):{mode:s}:void 0}function i(e,t,n){return"object"==typeof e?i(e.mode,t,n).toString():void 0===e?"boolean"!=typeof t||t?"boolean"==typeof t&&t?void 0===n?t:n:void 0===t?void 0:t:void 0:"boolean"==typeof e?e?void 0===n?t:n:void 0:e}const n=!si.isNode()&&"trackMyTypeAndInitiatedFromMe",s="slim",r=s,o="boolean"==typeof e.exposeAPI||"boolean"==typeof e.exposeGlue;return{layouts:t(e.layouts,s,r),activities:t(e.activities,n,"trackMyTypeAndInitiatedFromMe"),appManager:t(e.appManager,!0,"startOnly"),windows:t(e.windows,!0,!0),channels:t(e.channels,!1,!0),displays:t(e.displays,!0,!0),exposeAPI:o||!0}};class Ui{constructor(e){this.options=e,this.callbacks=Jt(),this.actions=e.actions,this.body=e.body,this.badge=e.badge,this.data=e.data,this.dir=e.dir,this.icon=e.icon,this.image=e.image,this.lang=e.lang,this.renotify=e.renotify,this.requireInteraction=e.requireInteraction,this.silent=e.silent,this.tag=e.tag,this.timestamp=e.timestamp,this.title=e.title}close(){throw new Error("Method not implemented.")}addEventListener(e,t,i){this.callbacks.add(e,t)}removeEventListener(e,t,i){}dispatchEvent(e){return this.callbacks.execute(e.type,e),!0}}class qi{constructor(e,t){this.interop=e,this.onStreamEvent=t}onVisibilityChanged(e){return this.onStreamEvent("on-panel-visibility-changed",e)}toggle(){return this.interop.invoke("T42.Notifications.Show")}show(){return this.interop.invoke("T42.Notifications.Show",{show:!0})}hide(){return this.interop.invoke("T42.Notifications.Hide")}async isVisible(){return(await this.interop.invoke("T42.Notifications.Execute",{command:"isPanelVisible"})).returned.panelVisible}toAPI(){return{onVisibilityChanged:this.onVisibilityChanged.bind(this),toggle:this.toggle.bind(this),show:this.show.bind(this),hide:this.hide.bind(this),isVisible:this.isVisible.bind(this)}}}class Ji{constructor(e,t){this.interop=e,this.NotificationsSubscribeStream="T42.GNS.Subscribe.Notifications",this.NotificationsCounterStream="T42.Notifications.Counter",this.RaiseNotificationMethodName="T42.GNS.Publish.RaiseNotification",this.NotificationsExecuteMethod="T42.Notifications.Execute",this.methodsRegistered=!1,this.NOTIFICATIONS_CONFIGURE_METHOD_NAME="T42.Notifications.Configure",this.methodNameRoot="T42.Notifications.Handler-"+si.generateId(),this.nextId=0,this.notifications={},this.registry=Jt(),this.subscribedForNotifications=!1,this.subscribedCounterStream=!1,this.subscriptionsCountForNotifications=0,this.subscriptionsCountForCounter=0,this.logger=t.subLogger("notifications"),this._panel=new qi(e,this.onStreamEventCore.bind(this)),this._panelAPI=this._panel.toAPI(),this.subscribeInternalEvents()}get maxActions(){return 2}get panel(){return this._panelAPI}async raise(e){var t,i,n,s;if(this.validate(e),!this.methodsRegistered){const e=[];for(let t=0;t<this.maxActions;t++)e.push(this.interop.register(`${this.methodNameRoot}_${t}`,this.handleNotificationEvent.bind(this)));this.methodsRegistered=!0,await Promise.all(e)}const r=String(this.nextId++),o=null!==(t=e.type)&&void 0!==t?t:"Notification",a={id:e.id,state:null!==(i=e.state)&&void 0!==i?i:"Active",title:e.title,type:o,severity:null!==(n=e.severity)&&void 0!==n?n:"None",description:e.body,glueRoutingDetailMethodName:`${this.methodNameRoot}_0`,actions:[],sourceId:r,source:e.source,publishExtraEvents:!0,clickInterop:e.clickInterop};e.actions&&this.handleActions(e,r,a),this.handleOptions(e,a);const c=new Ui(e);this.notifications[r]=c;try{const e=await this.interop.invoke(this.RaiseNotificationMethodName,{notification:a});c.id=null===(s=e.returned)||void 0===s?void 0:s.id}catch(e){const t=e.message;setTimeout((()=>{this.handleNotificationErrorEvent(c,t)}),1)}return c}async setFilter(e){return(await this.interop.invoke("T42.Notifications.Filter",e)).returned}async getFilter(){return(await this.interop.invoke("T42.Notifications.Filter")).returned}async configure(e){var t,i,n,s,r,o,a,c;if(!e||Array.isArray(e))throw new Error("Invalid options - should be an object.");if(0===Object.values(e).length)throw new Error("The argument must be a non-empty object.");if(void 0!==e.enable&&"boolean"!=typeof e.enable)throw new Error("Expected type of enabled - boolean.");if(void 0!==e.enableToasts&&"boolean"!=typeof e.enableToasts)throw new Error("Expected type of enableToasts - boolean.");if(void 0!==e.toastExpiry&&"number"!=typeof e.toastExpiry)throw new Error("Expected type of toastExpiry - number.");if(e.sourceFilter&&"object"!=typeof e.sourceFilter)throw new Error("Expected type of sourceFilter - object.");if((null===(t=e.sourceFilter)||void 0===t?void 0:t.allowed)&&!Array.isArray(null===(i=e.sourceFilter)||void 0===i?void 0:i.allowed))throw new Error("Expected type of sourceFilter.allowed - array.");if((null===(n=e.sourceFilter)||void 0===n?void 0:n.blocked)&&!Array.isArray(null===(s=e.sourceFilter)||void 0===s?void 0:s.blocked))throw new Error("Expected type of sourceFilter.blocked - array.");if(e.toasts&&"object"!=typeof e.toasts)throw new Error("Expected type of (options.toasts - object.");if((null===(r=e.toasts)||void 0===r?void 0:r.mode)&&"string"!=typeof e.toasts.mode)throw new Error("Expected type of (options.toasts.mode - string.");if((null===(o=e.toasts)||void 0===o?void 0:o.stackBy)&&"string"!=typeof e.toasts.stackBy)throw new Error("Expected type of (options.toasts.stackBy - string.");if(e.placement&&"object"!=typeof e.placement)throw new Error("Expected type of (options.placement - object.");if((null===(a=e.placement)||void 0===a?void 0:a.toasts)&&"string"!=typeof e.placement.toasts)throw new Error("Expected type of (options.placement.toasts - string.");if((null===(c=e.placement)||void 0===c?void 0:c.panel)&&"string"!=typeof e.placement.panel)throw new Error("Expected type of (options.placement.panel - string.");return(await this.interop.invoke(this.NOTIFICATIONS_CONFIGURE_METHOD_NAME,e)).returned}async getConfiguration(){return(await this.interop.invoke(this.NotificationsExecuteMethod,{command:"getConfiguration"})).returned}async list(){return(await this.interop.invoke(this.NotificationsExecuteMethod,{command:"list",data:{statesVersion2:!0}})).returned.notifications}async updateData(e,t){const i={key:"data",value:{stringValue:JSON.stringify(t,((e,t)=>void 0===t?null:t))}};return(await this.interop.invoke(this.NotificationsExecuteMethod,{command:"create-or-update-attribute",data:{id:e,attribute:i}})).returned}onRaised(e){return this.onStreamEventCore("on-notification-raised",e)}onStateChanged(e){return this.onStreamEventCore("on-state-changed",e)}onClosed(e){return this.onStreamEventCore("on-notification-closed",e)}onConfigurationChanged(e){if("function"!=typeof e)throw new Error("Please provide the callback as a function!");this.subscribe();const t=this.registry.add("on-configuration-changed",e);return()=>{t(),this.closeStreamSubscriptionIfNoNeeded()}}onCounterChanged(e){if("function"!=typeof e)throw new Error("Please provide the callback as a function!");this.subscribeForCounterStream();const t=this.registry.add("on-counter-changed",e);return()=>{t(),this.closeStreamCounterSubscriptionIfNoNeeded()}}onDataChanged(e){if("function"!=typeof e)throw new Error("Please provide the callback as a function!");this.subscribe();const t=this.registry.add("on-notification-data-changed",e);return()=>{t(),this.closeStreamSubscriptionIfNoNeeded()}}async clearAll(){await this.interop.invoke(this.NotificationsExecuteMethod,{command:"clearAll"})}async clearOld(){await this.interop.invoke(this.NotificationsExecuteMethod,{command:"clearAllOld",data:{statesVersion2:!0}})}async clear(e){if(!e)throw new Error("The 'id' argument cannot be null or undefined");if("string"!=typeof e)throw new Error("The 'id' argument must be a string");await this.interop.invoke(this.NotificationsExecuteMethod,{command:"clear",data:{id:e}})}async clearMany(e){this.validateNotificationsArr(e),await this.interop.invoke(this.NotificationsExecuteMethod,{command:"clearMany",data:{notifications:e}})}async click(e,t,i){await this.interop.invoke(this.NotificationsExecuteMethod,{command:"click",data:{id:e,action:t,options:i}})}async snooze(e,t){await this.interop.invoke(this.NotificationsExecuteMethod,{command:"snooze",data:{id:e,duration:t}})}async snoozeMany(e,t){if(!t)throw new Error("The 'duration' argument cannot be null or undefined");if("number"!=typeof t)throw new Error("The 'duration' argument must be a valid number");this.validateNotificationsArr(e),await this.interop.invoke(this.NotificationsExecuteMethod,{command:"snoozeMany",data:{notifications:e,duration:t}})}async setState(e,t){if(!e)throw new Error("The 'id' argument cannot be null or undefined");if("string"!=typeof e)throw new Error("The 'id' argument must be a string");if(!t)throw new Error("The 'state' argument cannot be null or undefined");this.validateState(t),await this.interop.invoke(this.NotificationsExecuteMethod,{command:"updateState",data:{id:e,state:t}})}async setStates(e,t){if(!t)throw new Error("The 'state' argument cannot be null or undefined");if("string"!=typeof t)throw new Error("The 'state' argument must be a valid string");this.validateNotificationsArr(e),await this.interop.invoke(this.NotificationsExecuteMethod,{command:"updateStates",data:{notifications:e,state:t}})}toAPI(){return{maxActions:this.maxActions,panel:this._panel.toAPI(),raise:this.raise.bind(this),setFilter:this.setFilter.bind(this),getFilter:this.getFilter.bind(this),configure:this.configure.bind(this),getConfiguration:this.getConfiguration.bind(this),list:this.list.bind(this),onRaised:this.onRaised.bind(this),onStateChanged:this.onStateChanged.bind(this),onClosed:this.onClosed.bind(this),onConfigurationChanged:this.onConfigurationChanged.bind(this),onCounterChanged:this.onCounterChanged.bind(this),onDataChanged:this.onDataChanged.bind(this),clearAll:this.clearAll.bind(this),clearOld:this.clearOld.bind(this),clear:this.clear.bind(this),click:this.click.bind(this),setState:this.setState.bind(this),updateData:this.updateData.bind(this),snooze:this.snooze.bind(this),snoozeMany:this.snoozeMany.bind(this),clearMany:this.clearMany.bind(this),setStates:this.setStates.bind(this)}}onStreamEventCore(e,t){if("function"!=typeof t)throw new Error("Please provide the callback as a function!");this.subscribe();const i=this.registry.add(e,t);return()=>{i(),this.closeStreamSubscriptionIfNoNeeded()}}handleOptions(e,t){if(e.icon&&(t.attributes=t.attributes||[],t.attributes.push({key:"icon",value:{stringValue:e.icon}})),e.data){t.attributes=t.attributes||[];const i=JSON.stringify(e.data);t.attributes.push({key:"data",value:{stringValue:i}})}"number"==typeof e.panelExpiry&&(t.attributes=t.attributes||[],t.attributes.push({key:"panelExpiry",value:{stringValue:e.panelExpiry.toString()}})),"number"==typeof e.toastExpiry&&(t.attributes=t.attributes||[],t.attributes.push({key:"toastExpiry",value:{stringValue:e.toastExpiry.toString()}}))}handleActions(e,t,i){var n,s,r;const o=e.actions.slice(0,this.maxActions);let a=0;for(const e of o){const o={g42notificationId:t,g42action:e.action,g42interopMethod:null===(n=e.interop)||void 0===n?void 0:n.method,g42interopTarget:null===(s=e.interop)||void 0===s?void 0:s.target,g42interopArguments:JSON.stringify(null===(r=e.interop)||void 0===r?void 0:r.arguments)},c=Object.keys(o).map((e=>({name:e,value:{stringValue:o[e]}}))),d={name:`${this.methodNameRoot}_${a}`,description:e.title,displayName:e.title,parameters:c};i.actions.push(d),a++}}validate(e){if(!e)throw new Error("invalid options - should be an object");if("object"!=typeof e)throw new Error("invalid options - should be an object");if(!e.title)throw new Error("invalid options - should have a title");if("string"!=typeof e.title)throw new Error("invalid options - title should be a string");if(e.severity&&"string"!=typeof e.severity)throw new Error("invalid options - severity should be a string");if(e.panelExpiry&&"number"!=typeof e.panelExpiry)throw new Error("invalid options - panelExpiry should be a number");if(e.toastExpiry&&"number"!=typeof e.toastExpiry)throw new Error("invalid options - toastExpiry should be a number");e.state&&this.validateState(e.state)}validateState(e){if("string"!=typeof e)throw new Error("The 'state' argument must be a string");if(!["Active","Acknowledged","Stale"].includes(e))throw new Error(`The state argument: ${e} is not valid!`)}subscribe(){this.subscriptionsCountForNotifications++,this.subscribedForNotifications||(this.subscribedForNotifications=!0,this.logger.info(`Attempting to subscribe to "${this.NotificationsSubscribeStream}".`),this.interop.subscribe(this.NotificationsSubscribeStream,{arguments:{sendDeltaOnly:!0,statesVersion2:!0}}).then((e=>{this.subscriptionForNotifications=e,this.logger.info(`Successfully subscribed to "${this.NotificationsSubscribeStream}".`),e.onData((({data:e})=>{this.handleData(e)})),e.onClosed(((...e)=>{this.subscribedForNotifications=!1,this.logger.info(`Stream subscription Closed - ${JSON.stringify(e)}`)})),e.onFailed(((...e)=>{this.subscribedForNotifications=!1,this.logger.warn(`Stream subscription Failed - ${JSON.stringify(e)}`)}))})).catch((e=>{this.subscribedForNotifications=!1,this.logger.error(`Unable to subscribe to "${this.NotificationsSubscribeStream}"`,e)})))}subscribeForCounterStream(){this.subscriptionsCountForCounter++,this.subscribedCounterStream||(this.subscribedCounterStream=!0,this.logger.info(`Attempting to subscribe to "${this.NotificationsCounterStream}".`),this.interop.subscribe(this.NotificationsCounterStream,{arguments:{sendDeltaOnly:!0}}).then((e=>{this.subscriptionForCounter=e,this.logger.info(`Successfully subscribed to "${this.NotificationsCounterStream}".`),e.onData((({data:e})=>{this.registry.execute("on-counter-changed",{count:e.count})})),e.onClosed(((...e)=>{this.subscribedCounterStream=!1,this.logger.info(`Stream subscription Closed - ${JSON.stringify(e)}`)})),e.onFailed(((...e)=>{this.subscribedCounterStream=!1,this.logger.warn(`Stream subscription Failed - ${JSON.stringify(e)}`)}))})).catch((e=>{this.subscribedCounterStream=!1,this.logger.error(`Unable to subscribe to "${this.NotificationsCounterStream}"`,e)})))}subscribeInternalEvents(){this.registry.add("on-notification-closed",(e=>{this.handleOnClosed(e)})),this.registry.add("on-notification-raised",(e=>{this.handleOnShow(e.id)}))}handleData(e){var t;try{"items"in e&&Array.isArray(e.items)?this.handleItemsData(e):"deltas"in e&&Array.isArray(e.deltas)&&this.handleDeltas(e),"configuration"in e&&"object"==typeof e.configuration&&(this.logger.info(`Received configuration ${JSON.stringify(e.configuration)} from the stream`),this.registry.execute("on-configuration-changed",e.configuration,e.configuration.allApplications)),"command"in e&&"string"==typeof e.command&&(this.logger.info(`Received command "${null!==(t=e.command)&&void 0!==t?t:JSON.stringify(e)}" from the stream`),"showPanel"!==e.command&&"hidePanel"!==e.command||this.registry.execute("on-panel-visibility-changed","showPanel"===e.command))}catch(e){this.logger.error("Failed to parse data from the stream",e)}}handleItemsData(e){const t=e.items;this.logger.info(`Received ${t.length} notifications from the stream`);const i=t;if(e.isSnapshot)i.forEach((e=>{this.registry.execute("on-notification-raised",e)}));else{const e=i[0];"Closed"===e.state?this.registry.execute("on-notification-closed",{id:e.id}):this.registry.execute("on-notification-raised",e)}}handleDeltas(e){e.deltas.forEach((e=>{var t;const i=e.id,n=null!==(t=e.delta)&&void 0!==t?t:{};if("Closed"===n.state)this.registry.execute("on-notification-closed",{id:i,...n});else if(n.state)this.registry.execute("on-state-changed",{id:i},n.state);else if(n.attributes){const e=n.attributes.find((e=>"data"===e.key));e&&this.registry.execute("on-notification-data-changed",{id:i},JSON.parse(e.value.stringValue))}}))}handleOnClosed(e){const{notification:t,key:i}=this.getNotification(e);t&&(this.handleEvent(t,"close"),delete this.notifications[i])}handleOnShow(e){const{notification:t}=this.getNotification(e);t&&this.handleEvent(t,"show")}getNotification(e){let t,i;for(const n in this.notifications)if(this.notifications[n].id===e){t=this.notifications[n],i=n;break}return{notification:t,key:i}}handleNotificationEvent(e){const t=this.getGnsNotificationArgs(e);if("unknown"===t.event)return;const i=this.notifications[t.notificationId];i&&this.handleNotificationEventCore(i,t)}handleNotificationEventCore(e,t){switch(t.event){case"action":return this.handleNotificationActionEvent(e,t.notificationActionPayload);case"click":return this.handleNotificationClickEvent(e);case"close":return this.handleEvent(e,"close");case"error":return this.handleNotificationErrorEvent(e,t.error);case"show":return this.handleEvent(e,"show")}}handleNotificationActionEvent(e,t){const i={type:"onaction",action:t.g42action};e.onaction&&e.onaction(i),e.dispatchEvent(i)}handleNotificationClickEvent(e){const t={type:"onclick"};e.onclick&&e.onclick(t),e.dispatchEvent(t)}handleEvent(e,t){var i;const n={type:t};null===(i=e[`on${t}`])||void 0===i||i.call(e,n),e.dispatchEvent(n)}handleNotificationErrorEvent(e,t){const i={type:"onerror",error:t};e.onerror&&e.onerror(i),e.dispatchEvent(i)}getGnsNotificationArgs(e){var t;let i;const n=null===(t=e.notification)||void 0===t?void 0:t.event;return i=n?{event:n,notificationId:e.notification.sourceNotificationId,notificationActionPayload:e}:this.getBackwardGnsNotificationArgs(e),i}getBackwardGnsNotificationArgs(e){var t;let i;return i=e.g42notificationId?{event:"action",notificationId:e.g42notificationId,notificationActionPayload:e}:(null===(t=e.notification)||void 0===t?void 0:t.sourceNotificationId)?{event:"click",notificationId:e.notification.sourceNotificationId,notificationActionPayload:e}:{event:"unknown",notificationId:void 0,notificationActionPayload:e},i}closeStreamSubscriptionIfNoNeeded(){this.subscriptionsCountForNotifications--,this.subscriptionForNotifications&&0===this.subscriptionsCountForNotifications&&(this.subscriptionForNotifications.close(),this.subscriptionForNotifications=void 0)}closeStreamCounterSubscriptionIfNoNeeded(){this.subscriptionsCountForCounter--,this.subscriptionForCounter&&0===this.subscriptionsCountForCounter&&(this.subscriptionForCounter.close(),this.subscriptionForCounter=void 0)}validateNotificationsArr(e){if(!Array.isArray(e))throw new Error("The 'notifications' argument must be an array with valid notification IDs");if(e.some((e=>"string"!=typeof e)))throw new Error("The 'notifications' argument must contain only valid string notification IDs")}}class Vi{constructor(e,t){this.contexts=e,this.interop=t,this.registry=Jt(),this.isSubscribed=!1,this.getConfiguration()}async list(){if(await this.getConfiguration(),!this.getMethodName)throw new Error("not supported");return(await this.getAll()).returned.all}async getCurrent(){if(await this.getConfiguration(),!this.getMethodName)throw new Error("not supported");const e=await this.getAll();return e.returned.all.find((t=>t.name===e.returned.selected))}async select(e){if(await this.getConfiguration(),!this.setMethodName)throw new Error("not supported");await this.interop.invoke(this.setMethodName,{theme:e})}onChanged(e){return this.subscribe(),this.registry.add("changed",e)}async getConfiguration(){try{if(this.sharedContextName)return;const e=await this.interop.invoke("T42.Themes.Configuration");this.sharedContextName=e.returned.sharedContextName,this.getMethodName=e.returned.getThemesMethodName,this.setMethodName=e.returned.setThemesMethodName}catch(e){return}}async getAll(){return await this.getConfiguration(),await this.interop.invoke(this.getMethodName)}async subscribe(){await this.getConfiguration(),this.isSubscribed||(this.isSubscribed=!0,this.contexts.subscribe(this.sharedContextName,(e=>{e&&e.all&&e.selected&&this.registry.execute("changed",e.all.find((t=>t.name===e.selected)))})))}}const zi="Tick42.FDC3.Intents.",Ki=["applicationName","type"],Qi=(e,t,i)=>new Promise(((n,s)=>{let r=!0;const o=setTimeout((()=>{if(!r)return;r=!1;s(i||`Promise timeout hit: ${t}`)}),t);e().then((e=>{r&&(r=!1,clearTimeout(o),n(e))})).catch((e=>{r&&(r=!1,clearTimeout(o),s(e))}))})),Zi=e=>{var t,i;if("string"!=typeof e.intent)return{isValid:!1,error:"Response object has invalid 'intent' key. Expected a string, got "+typeof e.intent};if((null===(t=e.userSettings)||void 0===t?void 0:t.preserveChoice)&&"boolean"!=typeof(null===(i=e.userSettings)||void 0===i?void 0:i.preserveChoice))return{isValid:!1,error:"Response object has invalid 'userSettings.preserveChoice' key. Expected a boolean, got "+typeof e.userSettings.preserveChoice};const{isValid:n,error:s}=(e=>{if("object"!=typeof e)return{isValid:!1,error:"Response object has invalid 'handler' key. Expected an object, got "+typeof e};const t=Ki.filter((t=>!(t in e)));return t.length?{isValid:!1,error:`Handler in Response object does not provide compulsory keys: ${t.join(", ")}`}:{isValid:!0,ok:e}})(e.handler);return n?{isValid:!0,ok:e}:{isValid:n,error:s}},Xi=e=>{if((e=>{if(e){if("object"!=typeof e)throw new Error("Please provide the intent context as an object");if(e.type&&"string"!=typeof e.type)throw new Error("Please provide the intent context as an object with 'type' property as string");if(e.data&&"object"!=typeof e.data)throw new Error("Please provide the intent context as an object with 'data' property as object")}})(e.context),(e=>{if(e&&"string"!=typeof e&&"object"!=typeof e)throw new Error('Please provide the intent target as one of the valid values: "reuse", "startNew", { app: string }, { instance: string } ')})(e.target),(e=>{if(e){if("number"!=typeof e)throw new Error("Please provide the timeout as a number");if(e<=0)throw new Error("Please provide the timeout as a positive number")}})(e.timeout),(e=>{if(e&&"boolean"!=typeof e)throw new Error("Please provide waitUserResponseIndefinitely as a boolean")})(e.waitUserResponseIndefinitely),void 0!==e.clearSavedHandler&&"boolean"!=typeof e.clearSavedHandler)throw new Error("Please provide 'clearSavedHandler' as a boolean");e.handlers&&e.handlers.forEach((e=>(e=>{if(!e.applicationName)throw new Error(`Please provide applicationName for handler ${JSON.stringify(e)}`);if(!e.type)throw new Error(`Please provide type for handler ${JSON.stringify(e)}`);if("instance"===e.type&&!e.instanceId)throw new Error(`Please provide instanceId for handler ${JSON.stringify(e)}`)})(e)))};class Yi{constructor(e,t,i,n,s,r){this.interop=e,this.windows=t,this.logger=i,this.prefsController=s,this.appManager=r,this.myIntents=new Set,this.intentsResolverResponsePromises={},this.useIntentsResolverUI=!0,this.unregisterIntentPromises=[],this.checkIfIntentsResolverIsEnabled(n,r)}async find(e){await Promise.all(this.unregisterIntentPromises);let t=await this.all();if(void 0===e)return t;if("string"==typeof e)return t.filter((t=>t.name===e));if("object"!=typeof e)throw new Error("Please provide the intentFilter as a string or an object!");if(e.contextType){const i=e.contextType.toLowerCase();t=t.filter((e=>e.handlers.some((e=>{var t;return null===(t=e.contextTypes)||void 0===t?void 0:t.some((e=>e.toLowerCase()===i))}))))}if(e.resultType){const i=e.resultType.toLowerCase();t=t.filter((e=>e.handlers.some((e=>{var t;return(null===(t=e.resultType)||void 0===t?void 0:t.toLowerCase())===i}))))}return e.name&&(t=t.filter((t=>t.name===e.name))),t}async raise(e){if("string"!=typeof e&&"object"!=typeof e||"object"==typeof e&&"string"!=typeof e.intent)throw new Error("Please provide the intent as a string or an object with an intent property!");"string"==typeof e&&(e={intent:e}),Xi(e),await Promise.all(this.unregisterIntentPromises),e.clearSavedHandler&&(this.logger.trace(`User removes saved handler for intent ${e.intent}`),await this.removeRememberedHandler(e.intent));const t={},i=e.waitUserResponseIndefinitely?2147483647:e.timeout||9e4,n=await this.checkHandleRaiseWithRememberedHandler(e,t,i);if(n)return n;const s=this.coreRaiseIntent.bind(this,{request:e,resolverInstance:t,timeout:i});if(e.waitUserResponseIndefinitely)return s();const r=Qi(s,i,`Timeout of ${i}ms hit for intent request ${JSON.stringify(e)}`);return r.catch((()=>this.handleRaiseOnError(t.instanceId))),r}async all(){let e;await Promise.all(this.unregisterIntentPromises);try{const t=await this.interop.invoke("T42.ACS.GetApplications",{withIntentsInfo:!0});e=t.returned.applications}catch(e){return this.logger.error("Failed to get the applications!",e),[]}const t={},i=e.filter((e=>e.intents&&e.intents.length>0));for(const e of i)for(const i of e.intents){let n=t[i.name];n||(n={name:i.name,handlers:[]},t[i.name]=n);const s={applicationName:e.name,applicationTitle:e.title||"",applicationDescription:e.caption,displayName:i.displayName,contextTypes:i.contexts,applicationIcon:e.icon,type:"app",resultType:i.resultType};n.handlers.push(s)}const n=this.interop.servers(),s=n.map((e=>e.windowId)).filter((e=>void 0!==e)),r="T42.Wnd.GetInfo";let o;if(this.interop.methods().some((e=>e.name===r)))try{const e=await this.interop.invoke(r,{ids:s});o=e.returned.windows}catch(e){}for(const i of n)await Promise.all(i.getMethods().filter((e=>e.name.startsWith(zi))).map((async n=>{const s=n.name.replace(zi,"");let r=t[s];r||(r={name:s,handlers:[]},t[s]=r);const a=n.flags.intent,c=e.find((e=>e.name===i.application));let d;c&&c.intents&&(d=c.intents.find((e=>e.name===s)));const h=await this.windowsIdToTitle(i.windowId,o),u={instanceId:i.instance,applicationName:i.application,applicationIcon:a.icon||(null==c?void 0:c.icon),applicationTitle:(null==c?void 0:c.title)||"",applicationDescription:a.description||(null==c?void 0:c.caption),displayName:a.displayName||(null==d?void 0:d.displayName),contextTypes:a.contextTypes||(null==d?void 0:d.contexts),instanceTitle:h,type:"instance",resultType:(null==d?void 0:d.resultType)||a.resultType};r.handlers.push(u)})));return Object.values(t)}addIntentListener(e,t){if("string"!=typeof e&&"object"!=typeof e||"object"==typeof e&&"string"!=typeof e.intent)throw new Error("Please provide the intent as a string or an object with an intent property!");if("function"!=typeof t)throw new Error("Please provide the handler as a function!");const i="string"==typeof e?e:e.intent,n=`${zi}${i}`;let s,r={};if(this.myIntents.has(i))throw new Error(`Intent listener for intent ${i} already registered!`);this.myIntents.add(i);const o={unsubscribe:()=>{this.myIntents.delete(i),s.then((()=>this.interop.unregister(n))).catch((e=>this.logger.trace(`Unregistration of a method with name ${n} failed with reason: ${JSON.stringify(e)}`)))}};if("object"==typeof e){const{intent:t,...i}=e;r=i}return s=this.interop.register({name:n,flags:{intent:r}},(e=>{if(this.myIntents.has(i))return t(e)})),s.catch((e=>{this.myIntents.delete(i),this.logger.warn(`Registration of a method with name ${n} failed with reason: ${JSON.stringify(e)}`)})),o}async register(e,t){if("string"!=typeof e&&"object"!=typeof e||"object"==typeof e&&"string"!=typeof e.intent)throw new Error("Please provide the intent as a string or an object with an intent property!");if("function"!=typeof t)throw new Error("Please provide the handler as a function!");await Promise.all(this.unregisterIntentPromises);const i="string"==typeof e?e:e.intent,n=this.buildInteropMethodName(i);let s={};if(this.myIntents.has(i))throw new Error(`Intent listener for intent ${i} already registered!`);if(this.myIntents.add(i),"object"==typeof e){const{intent:t,...i}=e;s=i}try{await this.interop.register({name:n,flags:{intent:s}},((e,n)=>{if(this.myIntents.has(i))return t(e,n)}))}catch(e){throw this.myIntents.delete(i),new Error(`Registration of a method with name ${n} failed with reason: ${JSON.stringify(e)}`)}return{unsubscribe:()=>this.unsubscribeIntent(i)}}async filterHandlers(e){var t,i;if((e=>{if(!e)throw new Error("Provide 'handlerFilter' with at least one filter criteria of the following: 'intent' | 'contextTypes' | 'resultType' | 'applicationNames'");const{title:t,openResolver:i,timeout:n,intent:s,contextTypes:r,resultType:o,applicationNames:a}=e;if(void 0!==t&&("string"!=typeof t||!t.length))throw new Error("Provide 'title' as a non empty string");if(void 0!==i&&"boolean"!=typeof i)throw new Error("Provide 'openResolver' prop as a boolean");if(void 0!==n&&("number"!=typeof n||n<=0))throw new Error("Provide 'timeout' prop as a positive number");if(void 0!==s&&("string"!=typeof s||!s.length))throw new Error("Provide 'intent' as a non empty string");if(void 0!==r&&(!Array.isArray(r)||r.some((e=>"string"!=typeof e))))throw new Error("Provide 'contextTypes' as an array of non empty strings");if(void 0!==o&&("string"!=typeof o||!o.length))throw new Error("Provide 'resultType' as a non empty string");if(void 0!==a&&(!Array.isArray(a)||a.some((e=>"string"!=typeof e))))throw new Error("Provide 'applicationNames' as an array of non empty strings");const c="Provide at least one filter criteria of the following: 'intent' | 'contextTypes' | 'resultType' | 'applicationNames'";if(!Object.keys(e).length)throw new Error(c);if(!(s||o||r&&r.length||a&&a.length))throw new Error(c)})(e),e.openResolver&&!this.useIntentsResolverUI)throw new Error("Cannot resolve 'filterHandlers' request using Intents Resolver UI because it's globally disabled");null===(t=this.logger)||void 0===t||t.trace(`Received 'filterHandlers' command with request: ${JSON.stringify(e)}`);const n=this.filterHandlersBy(await this.all(),e);if(!n||!n.length)return{handlers:[]};const{open:s,reason:r}=this.checkIfResolverShouldBeOpenedForFilterHandlers(n,e);if(!s)return null===(i=this.logger)||void 0===i||i.trace(`Intent Resolver UI won't be used. Reason: ${r}`),{handlers:n};const o={instanceId:void 0},a=e.timeout||9e4;return{handlers:[await Qi((()=>this.startResolverApp({request:e,resolverInstance:o,method:"filterHandlers"})),a,`Timeout of ${a}ms hit for 'filterHandlers' request with filter: ${JSON.stringify(e)}`)]}}async getIntents(e){var t;this.logger.trace(`Received 'getIntents' command with handler ${JSON.stringify(e)}`),(e=>{if("object"!=typeof e)throw new Error("IntentHandler must be an object");if("string"!=typeof e.applicationName||!e.applicationName.length)throw new Error("Please provide 'applicationName' as a non-empty string");if("string"!=typeof e.type||!["app","instance"].includes(e.type))throw new Error(`Invalid 'type' property. Expected 'app' | 'instance' got ${e.type}`);if(void 0!==e.applicationTitle&&"string"!=typeof e.applicationTitle)throw new Error("Provide 'applicationTitle' as a string");if(void 0!==e.applicationDescription&&"string"!=typeof e.applicationDescription)throw new Error("Provide 'applicationDescription' as a string");if(void 0!==e.applicationIcon&&"string"!=typeof e.applicationIcon)throw new Error("Provide 'applicationIcon' as a string");if(void 0!==e.displayName&&"string"!=typeof e.displayName)throw new Error("Provide 'displayName' as a string");if(void 0!==e.contextTypes&&(!Array.isArray(e.contextTypes)||e.contextTypes.some((e=>"string"!=typeof e))))throw new Error("Provide 'contextTypes' as an array of non empty strings");if(void 0!==e.instanceId&&"string"!=typeof e.instanceId)throw new Error("Provide 'instanceId' as a string");if(void 0!==e.instanceTitle&&"string"!=typeof e.instanceTitle)throw new Error("Provide 'instanceTitle' as a string");if(void 0!==e.resultType&&"string"!=typeof e.resultType)throw new Error("Provide 'resultType' as a string")})(e);const i=await this.all();var n;n=e,Object.keys(n).forEach((e=>{null!==n[e]&&void 0!==n[e]||delete n[e]})),null===(t=this.logger)||void 0===t||t.trace("Extracting valid intents for the passed handler");const s=this.extractIntentsWithInfoByHandler(i,e);return this.logger.trace(`Returning intents for handler ${JSON.stringify(e)}`),{intents:s}}async clearSavedHandlers(){this.logger.trace("Removing all saved handlers from prefs storage for current app"),await this.prefsController.update({intents:void 0})}filterHandlersBy(e,t){const i=e.filter((e=>{if(!t.intent||t.intent===e.name){if(t.resultType){const i=e.handlers.filter((e=>e.resultType&&e.resultType===t.resultType));if(!i.length)return;e.handlers=i}if(t.contextTypes){const i=e.handlers.filter((e=>{var i;return null===(i=t.contextTypes)||void 0===i?void 0:i.every((t=>{var i;return null===(i=e.contextTypes)||void 0===i?void 0:i.includes(t)}))}));if(!i.length)return;e.handlers=i}if(t.applicationNames){const i=e.handlers.filter((e=>{var i;return null===(i=t.applicationNames)||void 0===i?void 0:i.includes(e.applicationName)}));if(!i.length)return;e.handlers=i}return e}}));return i.map((e=>e.handlers)).flat(1)}async coreRaiseIntent({request:e,resolverInstance:t,timeout:i}){var n,s;const r=await this.get(e.intent);if(void 0===r)throw new Error(`Intent ${e.intent} not found.`);const{open:o,reason:a}=this.checkIfResolverShouldBeOpenedForRaise(r,e);if(!o)return this.logger.trace(`Intent Resolver UI won't be used. Reason: ${a}`),e.waitUserResponseIndefinitely?Qi((()=>this.raiseIntent(e,i)),i,`Timeout of ${i}ms hit for raise to resolve`):this.raiseIntent(e,i);const c=await this.startResolverApp({request:e,method:"raise",resolverInstance:t});if(null===(n=this.logger)||void 0===n||n.trace(`Raising intent to target handler: ${JSON.stringify(c)} with timeout of ${i}`),e.waitUserResponseIndefinitely)return Qi((()=>this.raiseIntentToTargetHandler(e,c,i)),i,`Timeout of ${i}ms hit for raise to resolve`);const d=await this.raiseIntentToTargetHandler(e,c,i);return null===(s=this.logger)||void 0===s||s.trace(`Result from raise() method for intent ${JSON.stringify(e.intent)}: ${JSON.stringify(d)}`),d}async get(e){return(await this.all()).find((t=>t.name===e))}async raiseIntent(e,t){const i=e.intent,n=await this.get(i);if(void 0===n)throw new Error(`Intent ${i} not found.`);const s=e.handlers?this.findHandlerByFilter(e.handlers,{type:"app"}):this.findHandlerByFilter(n.handlers,{type:"app"}),r=e.handlers?this.findHandlerByFilter(e.handlers,{type:"instance"}):this.findHandlerByFilter(n.handlers,{type:"instance"});let o;if(e.target&&"reuse"!==e.target||(o=r||s),"startNew"===e.target&&(o=s),"object"==typeof e.target&&e.target.app&&(o=this.findHandlerByFilter(n.handlers,{app:e.target.app})),"object"==typeof e.target&&e.target.instance&&(o=this.findHandlerByFilter(n.handlers,{instance:e.target.instance,app:e.target.app})),!o)throw new Error(`Can not raise intent for request ${JSON.stringify(e)} - can not find intent handler!`);return await this.raiseIntentToTargetHandler(e,o,t)}async raiseIntentToTargetHandler(e,t,i){var n,s;null===(n=this.logger)||void 0===n||n.trace(`Raising intent to target handler:${JSON.stringify(t)}`),t.instanceId||(t.instanceId=await this.invokeStartApp(t.applicationName,e.context,e.options));const r=`${zi}${e.intent}`,o={methodResponseTimeoutMs:i?i+1e3:6e4,waitTimeoutMs:i?i+1e3:6e4},a=await this.interop.invoke(r,e.context,{instance:t.instanceId},o);return null===(s=this.logger)||void 0===s||s.trace(`raiseIntent command completed. Returning result: ${JSON.stringify(a)}`),{request:e,handler:{...t,type:"instance"},result:a.returned}}async startResolverApp({request:e,method:t,resolverInstance:i}){var n,s,r,o;null===(n=this.logger)||void 0===n||n.trace(`Intents Resolver UI with app name ${this.intentsResolverAppName} will be used for request: ${JSON.stringify(e)}`);const a=await this.registerIntentResolverMethod();null===(s=this.logger)||void 0===s||s.trace(`Registered interop method ${a}`);const c=this.buildStartContext(t,e,a),d=await this.buildStartOptions();null===(r=this.logger)||void 0===r||r.trace(`Starting Intents Resolver UI with context: ${JSON.stringify(c)} and options: ${JSON.stringify(d)}`);const h=await this.appManager.application(this.intentsResolverAppName).start(c,d);i.instanceId=h.id,null===(o=this.logger)||void 0===o||o.trace(`Intents Resolver instance with id ${h.id} opened`),this.subscribeOnInstanceStopped(h,t);const u=(e.timeout,9e4);this.createResponsePromise({intent:"raise"===t?e.intent:void 0,instanceId:h.id,responseMethodName:a,timeout:u,errorMsg:`Timeout of ${u}ms hit waiting for the user to choose a handler ${"raise"===t?`for intent ${e.intent}`:`for '${t}' method with filter ${JSON.stringify(e)}`}`});return await this.handleInstanceResponse({instanceId:h.id,caller:c.initialCaller,method:t,request:e})}async windowsIdToTitle(e,t){var i,n;if(void 0!==t)return null===(i=t.find((t=>t.id===e)))||void 0===i?void 0:i.title;const s=null===(n=this.windows)||void 0===n?void 0:n.findById(e);return await(null==s?void 0:s.getTitle())}async handleInstanceResponse({instanceId:e,method:t,request:i,caller:n}){var s,r,o;try{const a=await this.intentsResolverResponsePromises[e].promise,c="raise"===t?`for intent ${a.intent} `:"";return null===(s=this.logger)||void 0===s||s.trace(`Intent handler chosen ${c}: ${JSON.stringify(a.handler)}. Stopping resolver instance with id ${e}`),this.stopResolverInstance(e),null===(r=this.logger)||void 0===r||r.trace(`Instance with id ${e} successfully stopped`),(null===(o=a.userSettings)||void 0===o?void 0:o.preserveChoice)&&await this.saveUserChoice({intent:a.intent,handler:a.handler,filter:"filterHandlers"===t?{applicationNames:i.applicationNames,contextTypes:i.contextTypes,resultType:i.resultType}:void 0,caller:n}),a.handler}catch(t){throw this.stopResolverInstance(e),new Error(t)}}async registerIntentResolverMethod(){const e="T42.Intents.Resolver.Control"+si.generateId();return await this.interop.register(e,((e,t)=>this.resolverResponseHandler(e,t))),e}resolverResponseHandler(e,t){const{instance:i}=t,n=Zi(e);if(!n)return this.logger.trace(`Intent Resolver instance with id ${t.instance} sent invalid response. Error: ${n.error}`),this.intentsResolverResponsePromises[i].reject(n.error),void this.stopResolverInstance(i);const s=n.ok;this.intentsResolverResponsePromises[i].resolve(s),this.cleanUpIntentResolverPromise(i)}buildStartContext(e,t,i){var n;const s=this.interop.instance.application||this.interop.instance.applicationName,r=(null===(n=this.appManager.application(s))||void 0===n?void 0:n.title)||"",o={callerId:this.interop.instance.instance,methodName:i,initialCaller:{id:this.interop.instance.instance,applicationName:s,applicationTitle:r},resolverApi:"1.0"};return"raise"===e?{...o,intent:t}:{...o,handlerFilter:t}}async buildStartOptions(){const e=this.windows.my();if(!e)return;const t=await e.getBounds();return{top:(t.height-440)/2+t.top,left:(t.width-400)/2+t.left,width:400,height:440}}createResponsePromise({instanceId:e,intent:t,responseMethodName:i,timeout:n,errorMsg:s}){let r=()=>{},o=()=>{};const a=((e,t,i)=>new Promise(((n,s)=>{const r=setTimeout((()=>{s(i||`Promise timeout hit: ${t}`)}),t);new Promise(e).then((e=>{clearTimeout(r),n(e)})).catch((e=>{clearTimeout(r),s(e)}))})))(((e,t)=>{r=e,o=t}),n,s);this.intentsResolverResponsePromises[e]={intent:t,resolve:r,reject:o,promise:a,methodName:i}}async invokeStartApp(e,t,i){return(await this.interop.invoke("T42.ACS.StartApplication",{Name:e,options:{...i,startedByIntentAPI:!0}})).returned.Id}subscribeOnInstanceStopped(e,t){const{application:i}=e,n=i.onInstanceStopped((i=>{if(i.id!==e.id)return;const s=this.intentsResolverResponsePromises[i.id];if(!s)return n();const r=`Cannot resolve ${"raise"===t?`raised intent ${s.intent}`:`'${t}' method`} - User closed ${e.application.name} app without choosing a handler`;s.reject(r),this.cleanUpIntentResolverPromise(i.id),n()}))}async cleanUpIntentResolverPromise(e){const t=this.intentsResolverResponsePromises[e];if(!t)return;this.interop.unregister(t.methodName).catch((e=>this.logger.warn(e))),delete this.intentsResolverResponsePromises[e]}handleRaiseOnError(e){e&&this.stopResolverInstance(e)}stopResolverInstance(e){const t=this.windows.findById(e);null==t||t.close().catch((e=>this.logger.error(e)))}checkIfIntentsResolverIsEnabled(e,t){var i,n,s,r,o;t?(this.useIntentsResolverUI="boolean"!=typeof(null===(i=e.intents)||void 0===i?void 0:i.enableIntentsResolverUI)||e.intents.enableIntentsResolverUI,this.intentsResolverAppName=null!==(s=null===(n=e.intents)||void 0===n?void 0:n.intentsResolverAppName)&&void 0!==s?s:"intentsResolver",this.intentsResolverResponseTimeout=null!==(o=null===(r=e.intents)||void 0===r?void 0:r.methodResponseTimeoutMs)&&void 0!==o?o:6e4):this.useIntentsResolverUI=!1}checkIfResolverShouldBeOpenedForRaise(e,t){const i=this.checkIfIntentsResolverShouldBeOpened();if(!i.open)return i;return this.checkIfIntentHasMoreThanOneHandler(e,t)?{open:!0}:{open:!1,reason:`Raised intent ${e.name} has only one handler`}}checkIfResolverShouldBeOpenedForFilterHandlers(e,t){return 1===e.length?{open:!1,reason:`There's only one valid intent handler for filter ${JSON.stringify(t)}`}:"boolean"!=typeof(null==t?void 0:t.openResolver)||t.openResolver?this.checkIfIntentsResolverShouldBeOpened():{open:!1,reason:"Intents resolver is disabled by IntentHandler filter"}}checkIfIntentsResolverShouldBeOpened(){if(!this.useIntentsResolverUI)return{open:!1,reason:"Intent Resolver is disabled. Resolving to first found handler"};return this.appManager.application(this.intentsResolverAppName)?{open:!0}:{open:!1,reason:`Intent Resolver Application with name ${this.intentsResolverAppName} not found.`}}checkIfIntentHasMoreThanOneHandler(e,t){return t.target?"reuse"===t.target?t.handlers?t.handlers.filter((e=>"instance"===e.type&&e.instanceId)).length>1||t.handlers.filter((e=>"app"===e.type)).length>1:e.handlers.filter((e=>"instance"===e.type&&e.instanceId)).length>1||e.handlers.filter((e=>"app"===e.type)).length>1:"startNew"===t.target?t.handlers?t.handlers.filter((e=>"app"===e.type)).length>1:e.handlers.filter((e=>"app"===e.type)).length>1:(t.target,!1):t.handlers?t.handlers.length>1:e.handlers.length>1}buildInteropMethodName(e){return`${zi}${e}`}clearUnregistrationPromise(e){this.unregisterIntentPromises=this.unregisterIntentPromises.filter((t=>t!==e))}unsubscribeIntent(e){this.myIntents.delete(e);const t=this.buildInteropMethodName(e),i=this.interop.unregister(t);this.unregisterIntentPromises.push(i),i.then((()=>{this.clearUnregistrationPromise(i)})).catch((e=>{this.logger.error(`Unregistration of a method with name ${t} failed with reason: `,e),this.clearUnregistrationPromise(i)}))}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}extractIntentsWithInfoByHandler(e,t){const i=e.reduce(((e,i)=>(i.handlers.forEach((n=>{const s=Object.keys(t).every((e=>{var i;return"contextTypes"===e?null===(i=t.contextTypes)||void 0===i?void 0:i.every((e=>{var t;return null===(t=n.contextTypes)||void 0===t?void 0:t.includes(e)})):n[e]===t[e]}));if(!s)return;const r={intent:i.name,contextTypes:n.contextTypes,description:n.applicationDescription,displayName:n.displayName,icon:n.applicationIcon,resultType:n.resultType};e.push(r)})),e)),[]);return i}async removeRememberedHandler(e){var t;this.logger.trace(`Removing saved handler from prefs storage for intent ${e}`);const i=await this.prefsController.get(),n=null===(t=i.data)||void 0===t?void 0:t.intents;if(!n)return void this.logger.trace("No app prefs found for current app");delete n[e];const s={...i.data,intents:n};await this.prefsController.update(s),this.logger.trace(`Handler saved choice for intent ${e} removed successfully`)}async checkForRememberedHandler(e){var t,i;const n=null===(i=null===(t=(await this.prefsController.get()).data)||void 0===t?void 0:t.intents)||void 0===i?void 0:i[e.intent];return null==n?void 0:n.handler}async checkHandleRaiseWithRememberedHandler(e,t,i){const n=await this.checkForRememberedHandler(e);if(!n)return;const s={...e,target:{app:n.applicationName,instance:n.instanceId}};try{return await this.coreRaiseIntent({request:s,resolverInstance:t,timeout:i})}catch(t){this.logger.trace("Could not raise intent to remembered handler. Removing it from Prefs store"),await this.removeRememberedHandler(e.intent)}}async saveUserChoice({intent:e,handler:t,filter:i,caller:n}){var s,r;const o=await this.prefsController.get(n.applicationName),a=(null===(s=null==o?void 0:o.data)||void 0===s?void 0:s.intents)||{},c={...o.data,intents:{...a,[e]:{handler:t,filter:i}}};await this.prefsController.update(c,{app:n.applicationName}),null===(r=this.logger)||void 0===r||r.info(`Saved user's choice of handler for '${n.applicationName}' app`)}}class en{constructor(e,t){this.appName=e,this.interop=t,this.registry=Jt(),this.interopMethodRegistered=!1}async get(e){return(await this.interop.invoke("T42.Prefs.Get",{app:null!=e?e:this.appName})).returned}async set(e,t){var i;this.verifyDataObject(e),await this.interop.invoke("T42.Prefs.Set",{app:null!==(i=null==t?void 0:t.app)&&void 0!==i?i:this.appName,data:e,merge:!1})}async setFor(e,t){return this.verifyApp(e),this.verifyDataObject(t),this.set(t,{app:e})}async update(e,t){var i;this.verifyDataObject(e),await this.interop.invoke("T42.Prefs.Set",{app:null!==(i=null==t?void 0:t.app)&&void 0!==i?i:this.appName,data:e,merge:!0})}async updateFor(e,t){return this.verifyApp(e),this.verifyDataObject(t),this.update(t,{app:e})}async clear(e){await this.interop.invoke("T42.Prefs.Set",{app:null!=e?e:this.appName,clear:!0})}async clearFor(e){this.verifyApp(e),await this.interop.invoke("T42.Prefs.Set",{app:e,clear:!0})}async getAll(){return(await this.interop.invoke("T42.Prefs.Get")).returned}async clearAll(){await this.interop.invoke("T42.Prefs.Set",{clear:!0})}subscribe(e){return this.verifyCallback(e),this.subscribeFor(this.appName,e)}subscribeFor(e,t){this.verifyApp(e),this.verifyCallback(t);const i=this.registry.add(e,t);return this.registerInteropIfNeeded().then((()=>{this.interop.invoke("T42.Prefs.Get",{app:e,subscribe:!0})})),()=>{i()}}async registerInteropIfNeeded(){this.interopMethodRegistered||(this.interopMethodRegistered=!0,await this.interop.register("T42.Prefs.Update",(e=>{this.registry.execute(e.app,e)})))}verifyApp(e){if(!e)throw new Error("app should be defined");if(!Ve(e))throw new Error("app should be a string")}verifyDataObject(e){if(!e)throw new Error("data should be defined");if(!ze(e))throw new Error("data should be an object")}verifyCallback(e){if(!et(e))throw new Error("callback should be defined")}}class tn{constructor(e,t){this.methodName=e,this.interop=t}async get(e){return(await this.invoke("get-cookies",{filter:e})).returned.cookies}async set(e){this.verifyCookieObject(e),await this.invoke("set-cookie",e)}async remove(e,t){if(!Ve(e))throw new Error("url should be a string");if(!Ve(t))throw new Error("name should be a string");await this.invoke("remove-cookie",{url:e,name:t})}invoke(e,t){return this.interop.invoke(this.methodName,{command:e,args:t})}verifyCookieObject(e){if(!e)throw new Error("cookie should be defined");if(!ze(e))throw new Error("cookie should be an object")}}class nn{constructor(e){this.config=e,this.glue42EventName="Glue42",this.events={notifyStarted:{name:"notifyStarted",handle:this.handleNotifyStarted.bind(this)},requestGlue:{name:"requestGlue",handle:this.handleRequestGlue.bind(this)}}}start(e){si.isNode()||(this.glue=e,this.wireCustomEventListener(),this.announceStarted())}wireCustomEventListener(){window.addEventListener(this.glue42EventName,(e=>{const t=e.detail;if(!t||!t.glue42)return;const i=t.glue42.event,n=this.events[i];n&&n.handle(t.glue42.message)}))}announceStarted(){this.send("start")}handleRequestGlue(){this.config.exposeAPI?this.send("requestGlueResponse",{glue:this.glue}):this.send("requestGlueResponse",{error:"Will not give access to the underlying Glue API, because it was explicitly denied upon initialization."})}handleNotifyStarted(){this.announceStarted()}send(e,t){const i={glue42:{event:e,message:t}},n=new CustomEvent(this.glue42EventName,{detail:i});window.dispatchEvent(n)}}const sn=new class{constructor(){this.initialized=!1,this.details=[],this.reject=()=>{},this.resolve=()=>{}}init(e){this.initialized=!0,this.addCall(e),this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}addCall(e){this.details.push({date:new Date,config:e})}done(e){this.resolve(e)}error(e){this.reject(e)}},rn=async e=>{let t=!1;sn.initialized||(t=!0,sn.init(e));const i="undefined"!=typeof window&&window.glue42gd;if(i&&!t)return sn.addCall(e),sn.promise;const n=await on(e,i);return sn.resolve(n),n},on=async(e,t)=>{const i=si.getGDMajorVersion(),n=Hi(e=e||{});let s,r,o,a,c,d;e.gateway=e.gateway||{};const h=new nn(n);function u(e,t,i){const n=t.subLogger(e);if(i&&i.logger){const e=i.logger;e.console&&n.consoleLevel(e.console),e.publish&&n.publishLevel(e.publish)}return n}const l={libs:[{name:"windows",create:function(e){if(n.windows){const t=u("windows",e.logger,n.windows);return o=wi(e.agm,t,(()=>s),(()=>a),(()=>c),i),g(o),o}}},{name:"activities",create:function(e){var a;if(n.activities&&Lt.checkIsUsingGW3Implementation&&Lt.checkIsUsingGW3Implementation(e.connection)){const c=u("activity",e.logger,n.activities);return r=new Lt({connection:e.connection,contexts:e.contexts,agm:e.agm,logger:c,logLevel:"info",disableAutoAnnounce:!1,disposeRequestHandling:"exit",announcementInfo:null,windows:o,appManagerGetter:()=>s,mode:n.activities.mode,typesToTrack:n.activities.typesToTrack,activityId:null===(a=null==t?void 0:t.activityInfo)||void 0===a?void 0:a.activityId,gdMajorVersion:i}).api,g(r),r}}},{name:"appManager",create:function(e){if(!n.appManager)return;const t=u("appManager",e.logger,n.appManager);return s=ni({agm:e.agm,windows:o,logger:t,activities:r,mode:n.appManager.mode,gdMajorVersion:i}),g(s),s}},{name:"layouts",create:function(e){var t;if(!n.layouts)return;const o=u("layouts",e.logger,n.layouts),a=n.layouts,c=xi({agm:e.agm,appManager:s,activityGetter:()=>r,logger:o,mode:a.mode,autoSaveWindowContext:null!==(t=a.autoSaveWindowContext)&&void 0!==t&&t,gdMajorVersion:i});return g(c),c}},{name:"channels",create:function(e){if(!n.channels)return;if(!e.contexts)return;const t=u("channels",e.logger,n.channels);return c=Li(e.contexts,e.agm,(()=>o),t),g(c),c}},{name:"hotkeys",create:function(e){const t=function(e){const t=new Gi(e);return{register:t.register.bind(t),unregister:t.unregister.bind(t),unregisterAll:t.unregisterAll.bind(t),isRegistered:t.isRegistered.bind(t),ready:()=>Promise.resolve()}}(e.agm);return g(t),t}},{name:"displays",create:function(e){if(n.displays){const t=u("displays",e.logger,n.displays);return a=new ki(e.agm,t),g(a),a}}},{name:"prefs",create:function(i){var n,s;const r=null!==(s=null!==(n=e.application)&&void 0!==n?n:null==t?void 0:t.applicationName)&&void 0!==s?s:i.interop.instance.application;return d=new en(r,i.interop),g(d),d}},{name:"intents",create:function(t){const i=new Yi(t.agm,o,t.logger.subLogger("intents"),e,d,s);return g(i),i}},{name:"notifications",create:function(e){const t=new Ji(e.interop,e.logger).toAPI();return g(t),t}},{name:"themes",create:function(e){if(!e.contexts)return;const t=function(e,t){const i=new Vi(e,t);return{list:i.list.bind(i),getCurrent:i.getCurrent.bind(i),select:i.select.bind(i),onChanged:i.onChanged.bind(i),ready:()=>Promise.resolve()}}(e.contexts,e.interop);return g(t),t}},{name:"cookies",create:function(e){const t=function(e,t){const i=new tn(t,e);return{get:i.get.bind(i),remove:i.remove.bind(i),set:i.set.bind(i),ready:()=>Promise.resolve()}}(e.interop,"T42.GD.Execute");return g(t),t}}],version:Bi,enrichGlue:e=>{e.config.activities=n.activities,e.config.windows=n.windows,e.config.appManager=n.appManager,e.config.layouts=n.layouts,e.config.channels=n.channels,e.config.displays=n.displays}},p=[];function g(e){p.push(e)}"undefined"!=typeof window&&(window.glueFactoryLog||(window.glueFactoryLog=[]),window.glueFactoryLog.push(p));const m=await Ue(e,l);return Array.isArray(null==e?void 0:e.libraries)&&e.libraries.length&&await Promise.all(e.libraries.map((t=>t(m,e)))),h.start(m),m};var an,cn;rn.coreVersion=Ue.version,rn.version=Bi,rn.calls=sn;let dn=rn,hn=!0;if("undefined"!=typeof window){const e=window,t=null!==(an=e.iodesktop)&&void 0!==an?an:e.glue42gd;t&&t.autoInjected&&(dn=null!==(cn=e.IODesktop)&&void 0!==cn?cn:e.Glue,hn=!1),hn&&(e.Glue=dn,e.IODesktop=dn),delete e.IOBrowser,delete e.GlueCore}return dn.default=dn,dn}));
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):((e="undefined"!=typeof globalThis?globalThis:e||self).desktop=e.desktop||{},e.desktop.browser=e.desktop.browser||{},e.desktop.browser.min=t())}(this,(function(){"use strict";var e={STRING:1,NUMBER:2,TIMESTAMP:3,OBJECT:4};function t(t){return t.type===e.TIMESTAMP?"timestamp":t.type===e.NUMBER?"number":t.type===e.STRING?"string":t.type===e.OBJECT?"object":"unknown"}function i(e){return e.constructor===Date?"timestamp":"number"==typeof e?"number":"string"==typeof e?"string":"object"==typeof e?"object":"string"}function n(e){const n={},o=t(e);if("object"===o){const t=Object.keys(e.value).reduce(((t,n)=>{const r=i(e.value[n]);if("object"===r){const i=s(e.value[n]);t[n]={type:"object",description:"",context:{},composite:i}}else t[n]={type:r,description:"",context:{}};return t}),{});n.composite=t}return n.name=r(e.path.join("/")+"/"+e.name),n.type=o,n.description=e.description,n.context={},n}function s(e){return Object.keys(e).reduce(((t,n)=>{const r=i(e[n]);return t[n]="object"===r?{type:"object",description:"",context:{},composite:s(e[n])}:{type:r,description:"",context:{}},t}),{})}function r(e){return void 0!==e&&e.length>0&&"/"!==e[0]?"/"+e:e}function o(e){return"timestamp"===t(e)?Date.now():a(e.value)}function a(e){return"object"!=typeof e?e:Object.keys(e).reduce(((t,i)=>{const n=e[i];return"object"==typeof n&&n.constructor!==Date?t[i]=a(n):n.constructor===Date?t[i]=new Date(n).getTime():n.constructor===Boolean?t[i]=n.toString():t[i]=n,t}),{})}function c(e){return e.reduce(((e,t)=>e.concat(Array.isArray(t)?c(t):t)),[])}function d(e){const t=c(e.root.getAggregateState()),i=t.sort(((e,t)=>e.state?t.state?t.state-e.state:-1:1))[0];const n=function(e){let t="";return e.forEach(((e,i,n)=>{const s=e.path.join(".");i===n.length-1?t+=s+"."+e.name+": "+e.description:t+=s+"."+e.name+": "+e.description+","})),t.length>100?t.slice(0,100)+"...":t}(t);return{description:n,value:i.state}}var h=(e,t,i)=>{if(null===e||"object"!=typeof e)throw new Error("Missing definition");if(null===t||"object"!=typeof t)throw new Error("Missing parent");if(null===i||"object"!=typeof i)throw new Error("Missing transport")};class u{definition;system;transport;value;type;path=[];name;description;get repo(){return this.system?.repo}get id(){return`${this.system.path}/${name}`}constructor(e,t,i,n,s){this.definition=e,this.system=t,this.transport=i,this.value=n,this.type=s,h(e,t,i),this.path=t.path.slice(0),this.path.push(t.name),this.name=e.name,this.description=e.description,i.createMetric(this)}update(e){return this.value=e,this.transport.updateMetric(this)}}class l extends u{constructor(t,i,n,s){super(t,i,n,s,e.NUMBER)}incrementBy(e){this.update(this.value+e)}increment(){this.incrementBy(1)}decrement(){this.incrementBy(-1)}decrementBy(e){this.incrementBy(-1*e)}}class p extends u{constructor(t,i,n,s){super(t,i,n,s,e.OBJECT)}update(e){return this.mergeValues(e),this.transport.updateMetric(this)}mergeValues(e){return Object.keys(this.value).forEach((t=>{void 0!==e[t]&&(this.value[t]=e[t])}))}}class g extends u{constructor(t,i,n,s){super(t,i,n,s,e.STRING)}}class m extends u{constructor(t,i,n,s){super(t,i,n,s,e.TIMESTAMP)}now(){this.update(new Date)}}function f(t,i,n,s,r){if(!i)throw new Error("Repository is required");if(!n)throw new Error("Transport is required");const o=n,a=t,c=r||"",d=i,h=s,u=function e(t){if(!t||!t.parent)return[];const i=e(t.parent);return i.push(t.name),i}(s);let y={};const w=(b="/",((v=u)&&v.length>0?v.join(b):"")+t);var v,b;const _=i.root,I=[],C=[];function A(e,t,i,n){let s={name:""};s="string"==typeof e?{name:e}:e;const r=C.filter((e=>e.name===s.name));if(r.length>0){const e=r[0];if(e.type!==t)throw new Error(`A metric named ${s.name} is already defined with different type.`);return void 0!==i&&e.update(i).catch((()=>{})),e}const o=n(s);return C.push(o),o}const S={get name(){return a},get description(){return c},get repo(){return d},get parent(){return h},path:u,id:w,root:_,get subSystems(){return I},get metrics(){return C},subSystem:function(e,t){if(!e||0===e.length)throw new Error("name is required");const i=I.filter((t=>t.name===e));if(i.length>0)return i[0];const n=f(e,d,o,S,t);return I.push(n),n},getState:()=>y,setState:function(e,t){y={state:e,description:t},o.updateSystem(S,y)},stringMetric:function(t,i){return A(t,e.STRING,i,(e=>new g(e,S,o,i)))},timestampMetric:function(t,i){return A(t,e.TIMESTAMP,i,(e=>new m(e,S,o,i)))},objectMetric:function(t,i){return A(t,e.OBJECT,i,(e=>new p(e,S,o,i)))},numberMetric:function(t,i){return A(t,e.NUMBER,i,(e=>new l(e,S,o,i)))},getAggregateState:function(){const e=[];return Object.keys(y).length>0&&e.push({name:a,path:u,state:y.state,description:y.description}),I.forEach((t=>{const i=t.getAggregateState();i.length>0&&e.push(...i)})),e}};return o.createSystem(S),S}class y{root;constructor(e,t){t.init(this),this.root=f("",this,t),this.addSystemMetrics(this.root,e.clickStream||void 0===e.clickStream)}addSystemMetrics(e,t){if("undefined"!=typeof navigator&&e.stringMetric("UserAgent",navigator.userAgent),t&&"undefined"!=typeof document){const t=e.subSystem("ClickStream"),i=e=>{if(!e.target)return;const i=e.target,n=i?i.getAttribute("class")??"":"";t.objectMetric("LastBrowserEvent",{type:"click",timestamp:new Date,target:{className:n,id:i.id,type:"<"+i.tagName.toLowerCase()+">",href:i.href||""}})};t.objectMetric("Page",{title:document.title,page:window.location.href}),document.addEventListener?document.addEventListener("click",i):document.attachEvent("onclick",i)}e.stringMetric("StartTime",(new Date).toString());const i=e.stringMetric("StartURL",""),n=e.stringMetric("AppName","");if("undefined"!=typeof window){if(void 0!==window.location){const e=window.location.href;i.update(e)}void 0!==window.glue42gd&&n.update(window.glue42gd.appName)}}}class w{init(e){}createSystem(e){return Promise.resolve()}updateSystem(e,t){return Promise.resolve()}createMetric(e){return Promise.resolve()}updateMetric(e){return Promise.resolve()}}class v{api;lastCount=0;initialPublishTimeout=1e4;publishInterval=6e4;system;constructor(e,t,i){this.api=e,this.initialPublishTimeout=t??this.initialPublishTimeout,this.publishInterval=i??this.publishInterval,this.scheduleCollection(),this.system=this.api.subSystem("performance","Performance data published by the web application")}scheduleCollection(){setTimeout((()=>{this.collect(),setInterval((()=>{this.collect()}),this.publishInterval)}),this.initialPublishTimeout)}collect(){try{this.collectMemory(),this.collectEntries()}catch{}}collectMemory(){const e=window.performance.memory;this.system.stringMetric("memory",JSON.stringify({totalJSHeapSize:e.totalJSHeapSize,usedJSHeapSize:e.usedJSHeapSize}))}collectEntries(){const e=window.performance.getEntries();if(e.length<=this.lastCount)return;this.lastCount=e.length;const t=e.map((e=>e.toJSON()));this.system.stringMetric("entries",JSON.stringify(t))}}var b=e=>{let t;t=e.connection&&"object"==typeof e.connection?function(e,t){if(!e||"object"!=typeof e)throw new Error("Connection is required parameter");let i,s;const a=e=>{c(e.root)},c=e=>{h(e),e.metrics.forEach((e=>{u(e)})),e.subSystems.forEach((e=>{c(e)}))},h=async e=>{if(void 0===e.parent)return;await i;const t={type:"define",metrics:[{name:r(e.path.join("/")+"/"+e.name+"/State"),type:"object",composite:{Description:{type:"string",description:""},Value:{type:"number",description:""}},description:"System state",context:{}}]};s.send(t)},u=async e=>{const t=p(e);await i;const r={type:"define",metrics:[n(t)]};s.send(r),void 0!==t.value&&l(t)},l=e=>{if(g()){const t=o(e),i={type:"publish",values:[{name:r(e.path.join("/")+"/"+e.name),value:t,timestamp:Date.now()}]};return s.sendFireAndForget(i)}return Promise.resolve()},p=e=>{const t={...e};return"object"==typeof e.value&&null!==e.value&&(t.value={...e.value}),t},g=()=>{try{return(t.canUpdateMetric??(()=>!0))()}catch{return!0}};return{init:n=>{let r;i=new Promise((e=>{r=e})),s=e.domain("metrics"),s.onJoined((e=>{!e&&r&&(r(),r=void 0);const t={type:"define",metrics:[{name:"/State",type:"object",composite:{Description:{type:"string",description:""},Value:{type:"number",description:""}},description:"System state",context:{}}]};s.send(t),e&&a(n)})),s.join({system:t.system,service:t.service,instance:t.instance})},createSystem:h,updateSystem:async(t,n)=>{await i;const o={type:"publish",values:[{name:r(t.path.join("/")+"/"+t.name+"/State"),value:{Description:n.description,Value:n.state},timestamp:Date.now()}]};s.send(o);const a=d(t),c={type:"publish",peer_id:e.peerId,values:[{name:"/State",value:{Description:a.description,Value:a.value},timestamp:Date.now()}]};s.send(c)},createMetric:u,updateMetric:async e=>{const t=p(e);await i,l(t)}}}(e.connection,e):new w;let i=new y(e,t).root;e.disableAutoAppSystem||(i=i.subSystem("App"));const s=function(e){const t=e.subSystem("reporting"),i={name:"features"};let n;const s=(e,s,r)=>{if(void 0===e||""===e)throw new Error("name is mandatory");if(void 0===s||""===s)throw new Error("action is mandatory");if(void 0===r||""===r)throw new Error("payload is mandatory");n?n.update({name:e,action:s,payload:r}):n=t.objectMetric(i,{name:e,action:s,payload:r})};return e.featureMetric=s,e}(i);return function(e,t){if("undefined"==typeof window)return;const i=window?.glue42gd?.metrics?.pagePerformanceMetrics;i&&(t=i);t?.enabled&&new v(e,t.initialPublishTimeout,t.publishInterval)}(s,e.pagePerformanceMetrics),s};var _="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function I(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function C(e){if(e&&e.errorHandling&&"function"!=typeof e.errorHandling&&"log"!==e.errorHandling&&"silent"!==e.errorHandling&&"throw"!==e.errorHandling)throw new Error('Invalid options passed to createRegistry. Prop errorHandling should be ["log" | "silent" | "throw" | (err) => void], but '+typeof e.errorHandling+" was passed");var t=e&&"function"==typeof e.errorHandling&&e.errorHandling,i={};function n(i,n){var s=i instanceof Error?i:new Error(i);if(t)t(s);else{var r='[ERROR] callback-registry: User callback for key "'+n+'" failed: '+s.stack;if(e)switch(e.errorHandling){case"log":return console.error(r);case"silent":return;case"throw":throw new Error(r)}console.error(r)}}return{add:function(e,t,s){var r=i[e];return r||(r=[],i[e]=r),r.push(t),s&&setTimeout((function(){s.forEach((function(s){var r;if(null===(r=i[e])||void 0===r?void 0:r.includes(t))try{Array.isArray(s)?t.apply(void 0,s):t.apply(void 0,[s])}catch(t){n(t,e)}}))}),0),function(){var n=i[e];n&&(0===(n=n.reduce((function(e,i,n){return i===t&&e.length===n||e.push(i),e}),[])).length?delete i[e]:i[e]=n)}},execute:function(e){for(var t=[],s=1;s<arguments.length;s++)t[s-1]=arguments[s];var r=i[e];if(!r||0===r.length)return[];var o=[];return r.forEach((function(i){try{var s=i.apply(void 0,t);o.push(s)}catch(t){o.push(void 0),n(t,e)}})),o},clear:function(){i={}},clearKey:function(e){i[e]&&delete i[e]}}}C.default=C;var A=I(C);class S{gw;registry=A();client;constructor(e,t){this.gw=e.facade,this.gw.connect(((e,t)=>{this.messageHandler(t)})).then((e=>{this.client=e}))}get isObjectBasedTransport(){return!0}sendObject(e){return this.client?(this.client.send(e),Promise.resolve(void 0)):Promise.reject("not connected")}send(e){return Promise.reject("not supported")}onMessage(e){return this.registry.add("onMessage",e)}onConnectedChanged(e){return e(!0),()=>{}}close(){return Promise.resolve()}open(){return Promise.resolve()}name(){return"in-memory"}reconnect(){return Promise.resolve()}messageHandler(e){this.registry.execute("onMessage",e)}}class x{logger;worker;registry=A();constructor(e,t){this.logger=t,this.worker=new SharedWorker(e),this.worker.port.onmessage=e=>{this.messageHandler(e.data)}}get isObjectBasedTransport(){return!0}sendObject(e){return this.worker.port.postMessage(e),Promise.resolve()}send(e){return Promise.reject("not supported")}onMessage(e){return this.registry.add("onMessage",e)}onConnectedChanged(e){return e(!0),()=>{}}close(){return Promise.resolve()}open(){return Promise.resolve()}name(){return"shared-worker"}reconnect(){return Promise.resolve()}messageHandler(e){this.registry.execute("onMessage",e)}}let k=class e{static isNode(){if(void 0!==e._isNode)return e._isNode;if("undefined"!=typeof window)return e._isNode=!1,!1;try{e._isNode="[object process]"===Object.prototype.toString.call(global.process)}catch(t){e._isNode=!1}return e._isNode}static _isNode};class T{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)}}))}}const E={};function P(e){const t=E[e];if(t)return t;const i=[];function n(){return(new Date).getTime()}const s=n();let r,o;function a(e,t){const s=t??n();let r=0;i.length>0&&(r=s-i[i.length-1].time),i.push({name:e,time:s,diff:r})}a("start",s);const c={get startTime(){return s},get endTime(){return r},get period(){return o},stop:function(){return r=n(),a("end",r),o=r-s,o},mark:a,marks:i};return E[e]=c,c}const M=k.isNode()?null:window.WebSocket;class R{ws;logger;settings;startupTimer=P("connection");_running=!0;_registry=A();wsRequests=[];constructor(e,t){if(this.settings=e,this.logger=t,!this.settings.ws)throw new Error("ws is missing")}onMessage(e){return this._registry.add("onMessage",e)}send(e,t){return new Promise(((t,i)=>{this.waitForSocketConnection((()=>{try{this.ws?.send(e),t()}catch(e){i(e)}}),i)}))}open(){return this.logger.info("opening ws..."),this._running=!0,new Promise(((e,t)=>{this.waitForSocketConnection(e,t)}))}close(){return this._running=!1,this.ws&&this.ws.close(),Promise.resolve()}onConnectedChanged(e){return this._registry.add("onConnectedChanged",e)}name(){return this.settings.ws}reconnect(){this.ws?.close();const e=new T;return this.waitForSocketConnection((()=>{e.resolve()})),e.promise}waitForSocketConnection(e,t){t=t??(()=>{}),this._running?1!==this.ws?.readyState?(this.wsRequests.push({callback:e,failed:t}),this.wsRequests.length>1||this.openSocket()):e():t(`wait for socket on ${this.settings.ws} failed - socket closed by user`)}async openSocket(e,t){if(this.logger.info(`opening ws to ${this.settings.ws}, retryInterval: ${e}, retriesLeft: ${t}...`),this.startupTimer.mark("opening-socket"),void 0===e&&(e=this.settings.reconnectInterval),void 0===t&&(t=this.settings.reconnectAttempts),void 0!==t){if(0===t)return void this.notifyForSocketState(`wait for socket on ${this.settings.ws} failed - no more retries left`);this.logger.debug(`will retry ${t} more times (every ${e} ms)`)}try{await this.initiateSocket(),this.startupTimer.mark("socket-initiated"),this.notifyForSocketState()}catch{setTimeout((()=>{const i=void 0===t?void 0:t-1;this.openSocket(e,i)}),e)}}initiateSocket(){const e=new T;return this.logger.debug(`initiating ws to ${this.settings.ws}...`),this.ws=new M(this.settings.ws??""),this.ws.onerror=t=>{let i="";try{i=JSON.stringify(t)}catch(e){const n=new WeakSet,s=(e,t)=>{if("object"==typeof t&&null!==t){if(n.has(t))return;n.add(t)}return t};i=JSON.stringify(t,s)}this.logger.info(`ws error - reason: ${i}`),e.reject("error"),this.notifyStatusChanged(!1,i)},this.ws.onclose=t=>{this.logger.info(`ws closed - code: ${t?.code} reason: ${t?.reason}`),e.reject("closed"),this.notifyStatusChanged(!1)},this.ws.onopen=()=>{this.startupTimer.mark("ws-opened"),this.logger.info(`ws opened ${this.settings.identity?.application}`),e.resolve(),this.notifyStatusChanged(!0)},this.ws.onmessage=e=>{this._registry.execute("onMessage",e.data)},e.promise}notifyForSocketState(e){this.wsRequests.forEach((t=>{e?t.failed&&t.failed(e):t.callback()})),this.wsRequests=[]}notifyStatusChanged(e,t){this._registry.execute("onConnectedChanged",e,t)}}class N{specs;specsNames=[];messages={};isDone;subs={};subsRefCount={};connection;constructor(e){this.specs={};for(const t of e)this.specs[t.name]=t,this.specsNames.push(t.name)}init(e){this.connection=e;for(const t of this.specsNames)for(const i of this.specs[t].types){let t=this.subsRefCount[i];if(t||(t=0),t+=1,this.subsRefCount[i]=t,t>1)continue;const n=e.on(i,(e=>this.processMessage(i,e)));this.subs[i]=n}}processMessage(e,t){if(!this.isDone&&t)for(const i of this.specsNames)if(-1!==this.specs[i].types.indexOf(e)){const e=this.messages[i]||[];this.messages[i]=e,e.push(t)}}drain(e,t){t&&(this.messages[e]||[]).forEach(t),delete this.messages[e];for(const t of this.specs[e].types)this.subsRefCount[t]-=1,this.subsRefCount[t]<=0&&(this.connection?.off(this.subs[t]),delete this.subs[t],delete this.subsRefCount[t]);delete this.specs[e],this.specs.length||(this.isDone=!0)}}let j=(e=21)=>{let t="",i=e;for(;i--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return t};const W=(e,t,i)=>new Promise(((n,s)=>{const r=setTimeout((()=>{s(i||`Promise timeout hit: ${t}`)}),t);new Promise(e).then((e=>{clearTimeout(r),n(e)})).catch((e=>{clearTimeout(r),s(e)}))}));class O{settings;logger;identity;isPreferredActivated;_communicationId;publicWindowId;selfAssignedWindowId;iAmConnected=!1;parentReady=!1;rejected=!1;parentPingResolve;parentPingInterval;connectionResolve;extConnectionResolve;extConnectionReject;connectionReject;port;myClientId;children=[];extContentAvailable=!1;extContentConnecting=!1;extContentConnected=!1;parentWindowId;parentInExtMode=!1;webNamespace="g42_core_web";parent;parentType;parentPingTimeout=5e3;connectionRequestTimeout=7e3;defaultTargetString="*";registry=A();messages={connectionAccepted:{name:"connectionAccepted",handle:this.handleConnectionAccepted.bind(this)},connectionRejected:{name:"connectionRejected",handle:this.handleConnectionRejected.bind(this)},connectionRequest:{name:"connectionRequest",handle:this.handleConnectionRequest.bind(this)},parentReady:{name:"parentReady",handle:()=>{}},parentPing:{name:"parentPing",handle:this.handleParentPing.bind(this)},platformPing:{name:"platformPing",handle:this.handlePlatformPing.bind(this)},platformReady:{name:"platformReady",handle:this.handlePlatformReady.bind(this)},clientUnload:{name:"clientUnload",handle:this.handleClientUnload.bind(this)},manualUnload:{name:"manualUnload",handle:this.handleManualUnload.bind(this)},extConnectionResponse:{name:"extConnectionResponse",handle:this.handleExtConnectionResponse.bind(this)},extSetupRequest:{name:"extSetupRequest",handle:this.handleExtSetupRequest.bind(this)},gatewayDisconnect:{name:"gatewayDisconnect",handle:this.handleGatewayDisconnect.bind(this)},gatewayInternalConnect:{name:"gatewayInternalConnect",handle:this.handleGatewayInternalConnect.bind(this)}};constructor(e,t,i){this.settings=e,this.logger=t,this.identity=i,this.extContentAvailable=!!window.glue42ext,this.setUpMessageListener(),this.setUpUnload(),this.setupPlatformUnloadListener(),this.parentType=window.name.includes("#wsp")?"workspace":void 0}manualSetReadyState(){this.iAmConnected=!0,this.parentReady=!0}get transportWindowId(){return this.publicWindowId}get communicationId(){return this._communicationId}async sendObject(e){if(this.extContentConnected)return window.postMessage({glue42ExtOut:e},this.defaultTargetString);if(!this.port)throw new Error("Cannot send message, because the port was not opened yet");this.port.postMessage(e)}get isObjectBasedTransport(){return!0}onMessage(e){return this.registry.add("onMessage",e)}send(){return Promise.reject("not supported")}onConnectedChanged(e){return this.registry.add("onConnectedChanged",e)}async open(){this.logger.debug("opening a connection to the web platform gateway."),await this.connect(),this.notifyStatusChanged(!0)}close(){const e={glue42core:{type:this.messages.gatewayDisconnect.name,data:{clientId:this.myClientId,ownWindowId:this.identity?.windowId}}};return this.port?.postMessage(e),this.parentReady=!1,this.notifyStatusChanged(!1,"manual reconnection"),Promise.resolve()}name(){return"web-platform"}async reconnect(){return await this.close(),Promise.resolve()}initiateInternalConnection(){return new Promise(((e,t)=>{this.logger.debug("opening an internal web platform connection"),this.port=this.settings.port,this.iAmConnected?this.logger.warn("cannot open a new connection, because this client is currently connected"):(this.port.onmessage=i=>{if(this.iAmConnected&&!i.data?.glue42core)return void this.registry.execute("onMessage",i.data);const n=i.data?.glue42core;n&&(n.type===this.messages.gatewayInternalConnect.name&&n.success&&(this.publicWindowId=this.settings.windowId,this.identity&&this.publicWindowId&&(this.identity.windowId=this.publicWindowId,this.identity.instance=this.publicWindowId),e()),n.type===this.messages.gatewayInternalConnect.name&&n.error&&t(n.error))},this.port.postMessage({glue42core:{type:this.messages.gatewayInternalConnect.name}}))}))}initiateRemoteConnection(e){return W(((t,i)=>{this.connectionResolve=t,this.connectionReject=i,this.myClientId=this.myClientId??j(10);const n=this.getMyWindowId()||j(10),s={glue42core:{type:this.messages.connectionRequest.name,clientId:this.myClientId,clientType:"child",bridgeInstanceId:n,selfAssignedWindowId:this.selfAssignedWindowId}};if(this.logger.debug("sending connection request"),this.extContentConnecting)return s.glue42core.clientType="child",s.glue42core.bridgeInstanceId=this.myClientId,s.glue42core.parentWindowId=this.parentWindowId,window.postMessage(s,this.defaultTargetString);if(!e)throw new Error("Cannot send a connection request, because no glue target was specified!");e.postMessage(s,this.defaultTargetString)}),this.connectionRequestTimeout,"The connection to the target glue window timed out")}async isParentCheckSuccess(e){try{return await e,{success:!0}}catch(e){return{success:!1}}}setUpMessageListener(){this.settings.port?this.logger.debug("skipping generic message listener, because this is an internal client"):window.addEventListener("message",(e=>{const t=e.data?.glue42core;if(!t||this.rejected)return;const i=this.settings.allowedOrigins||[];if(i.length&&!i.includes(e.origin))return void this.logger.warn(`received a message from an origin which is not in the allowed list: ${e.origin}`);if(!this.checkMessageTypeValid(t.type))return void this.logger.error(`cannot handle the incoming glue42 core message, because the type is invalid: ${t.type}`);const n=t.type;this.logger.debug(`received valid glue42core message of type: ${n}`),this.messages[n].handle(e)}))}setUpUnload(){this.settings.port?this.logger.debug("skipping unload event listener, because this is an internal client"):window.addEventListener("beforeunload",(()=>{if(this.extContentConnected)return;const e={glue42core:{type:this.messages.clientUnload.name,data:{clientId:this.myClientId,ownWindowId:this.identity?.windowId}}};this.parent&&this.parent.postMessage(e,this.defaultTargetString),this.port?.postMessage(e)}))}handlePlatformReady(e){this.logger.debug("the web platform gave the ready signal"),this.parentReady=!0,this.parentPingResolve&&(this.parentPingResolve(),delete this.parentPingResolve),this.parentPingInterval&&(clearInterval(this.parentPingInterval),delete this.parentPingInterval),this.parent=e.source,this.parentType=window.name.includes("#wsp")?"workspace":"window"}handleConnectionAccepted(e){const t=e.data?.glue42core;return this.myClientId===t.clientId?this.handleAcceptanceOfMyRequest(t):this.handleAcceptanceOfGrandChildRequest(t,e)}handleAcceptanceOfMyRequest(e){if(this.logger.debug("handling a connection accepted signal targeted at me."),this.isPreferredActivated=e.isPreferredActivated,this.extContentConnecting)return this.processExtContentConnection(e);if(e.port){if(this.publicWindowId=this.getMyWindowId(),this.identity&&(this.identity.windowId=this.publicWindowId,this.identity.instance=this.identity.instance?this.identity.instance:this.publicWindowId||j(10)),this.identity&&e.appName&&(this.identity.application=e.appName,this.identity.applicationName=e.appName),this._communicationId=e.communicationId,this.port=e.port,this.port.onmessage=e=>this.registry.execute("onMessage",e.data),this.connectionResolve)return this.logger.debug("my connection is set up, calling the connection resolve."),this.connectionResolve(),void delete this.connectionResolve;this.logger.error("unable to call the connection resolve, because no connection promise was found")}else this.logger.error("cannot set up my connection, because I was not provided with a port")}processExtContentConnection(e){if(this.logger.debug("handling a connection accepted signal targeted at me for extension content connection."),this.extContentConnecting=!1,this.extContentConnected=!0,this.publicWindowId=this.parentWindowId||this.myClientId,this.extContentConnecting&&this.identity&&(this.identity.windowId=this.publicWindowId),this.identity&&e.appName&&(this.identity.application=e.appName,this.identity.applicationName=e.appName),window.addEventListener("message",(e=>{const t=e.data?.glue42ExtInc;if(!t)return;const i=this.settings.allowedOrigins||[];!i.length||i.includes(e.origin)?this.registry.execute("onMessage",t):this.logger.warn(`received a message from an origin which is not in the allowed list: ${e.origin}`)})),this.connectionResolve)return this.logger.debug("my connection is set up, calling the connection resolve."),this.connectionResolve(),void delete this.connectionResolve}handleAcceptanceOfGrandChildRequest(e,t){if(this.extContentConnecting||this.extContentConnected)return void this.logger.debug("cannot process acceptance of a grandchild, because I am connected to a content script");this.logger.debug(`handling a connection accepted signal targeted at a grandchild: ${e.clientId}`);const i=this.children.find((t=>t.grandChildId===e.clientId));i?(i.connected=!0,this.logger.debug(`the grandchild connection for ${e.clientId} is set up, forwarding the success message and the gateway port`),e.parentWindowId=this.publicWindowId,i.source.postMessage(t.data,i.origin,[e.port])):this.logger.error(`cannot handle connection accepted for grandchild: ${e.clientId}, because there is no grandchild with this id`)}handleConnectionRejected(){this.logger.debug("handling a connection rejection. Most likely the reason is that this window was not created by a glue API call"),this.connectionReject&&(this.connectionReject("The platform connection was rejected. Most likely because this window was not created by a glue API call"),delete this.connectionReject)}handleConnectionRequest(e){if(this.extContentConnecting)return void this.logger.debug("This connection request event is targeted at the extension content");const t=e.source,i=e.data.glue42core;return i.clientType&&"grandChild"===i.clientType?i.clientId?this.parent?(this.logger.debug(`handling a connection request for a grandchild: ${i.clientId}`),this.children.push({grandChildId:i.clientId,source:t,connected:!1,origin:e.origin}),this.logger.debug(`grandchild: ${i.clientId} is prepared, forwarding connection request to the platform`),void this.parent.postMessage(e.data,this.defaultTargetString)):this.rejectConnectionRequest(t,e.origin,"Cannot forward the connection request, because no direct connection to the platform was found"):this.rejectConnectionRequest(t,e.origin,"rejecting a connection request, because the source did not provide a valid id"):this.rejectConnectionRequest(t,e.origin,"rejecting a connection request, because the source was not opened by a glue API call")}handleParentPing(e){if(!this.parentReady)return void this.logger.debug("my parent is not ready, I am ignoring the parent ping");if(!this.iAmConnected)return void this.logger.debug("i am not fully connected yet, I am ignoring the parent ping");const t={glue42core:{type:this.messages.parentReady.name}};this.extContentConnected&&(t.glue42core.extMode={windowId:this.myClientId});const i=e.source;this.logger.debug("responding to a parent ping with a ready message"),i.postMessage(t,e.origin)}setupPlatformUnloadListener(){this.onMessage((e=>{"platformUnload"===e.type&&(this.logger.debug("detected a web platform unload"),this.parentReady=!1,this.notifyStatusChanged(!1,"Gateway unloaded"))}))}handleManualUnload(){const e={glue42core:{type:this.messages.clientUnload.name,data:{clientId:this.myClientId,ownWindowId:this.identity?.windowId}}};if(this.extContentConnected)return window.postMessage({glue42ExtOut:e},this.defaultTargetString);this.port?.postMessage(e)}handleClientUnload(e){const t=e.data.glue42core,i=t?.data.clientId;if(!i)return void this.logger.warn("cannot process grand child unload, because the provided id was not valid");this.children.find((e=>e.grandChildId===i))?(this.logger.debug(`handling grandchild unload for id: ${i}`),this.children=this.children.filter((e=>e.grandChildId!==i))):this.logger.warn("cannot process grand child unload, because this client is unaware of this grandchild")}handlePlatformPing(){}notifyStatusChanged(e,t){this.iAmConnected=e,this.registry.execute("onConnectedChanged",e,t)}checkMessageTypeValid(e){return"string"==typeof e&&!!this.messages[e]}rejectConnectionRequest(e,t,i){this.rejected=!0,this.logger.error(i);const n={glue42core:{type:this.messages.connectionRejected.name}};e.postMessage(n,t)}requestConnectionPermissionFromExt(){return this.waitForContentScript().then((()=>W(((e,t)=>{this.extConnectionResolve=e,this.extConnectionReject=t;this.logger.debug("permission request to the extension content script was sent"),window.postMessage({glue42core:{type:"extSetupRequest"}},this.defaultTargetString)}),this.parentPingTimeout,"Cannot initialize glue, because this app was not opened or created by a Glue Client and the request for extension connection timed out")))}handleExtConnectionResponse(e){const t=e.data?.glue42core;if(!t.approved)return this.extConnectionReject?this.extConnectionReject("Cannot initialize glue, because this app was not opened or created by a Glue Client and the request for extension connection was rejected"):void 0;this.extConnectionResolve&&(this.extConnectionResolve(),delete this.extConnectionResolve),this.extContentConnecting=!0,this.parentType="extension",this.logger.debug("The extension connection was approved, proceeding.")}handleExtSetupRequest(){}handleGatewayDisconnect(){}handleGatewayInternalConnect(){}waitForContentScript(){return!!window.glue42ext?.content?Promise.resolve():W((e=>{window.addEventListener("Glue42EXTReady",(()=>{e()}))}),this.connectionRequestTimeout,"The content script was available, but was never heard to be ready")}async connect(){if(this.settings.port)return await this.initiateInternalConnection(),void this.logger.debug("internal web platform connection completed");this.logger.debug("opening a client web platform connection"),await this.findParent(),await this.initiateRemoteConnection(this.parent),this.logger.debug("the client is connected")}async findParent(){const e="Cannot initiate glue, because this window was not opened or created by a glue client",t=this.getPossibleParentsInWindow(window),i=this.getPossibleParentsOutsideWindow(window.top?.opener,window.top),n=new Set([...t,...i]);if(!n.size&&!this.extContentAvailable)throw new Error(e);if(!n.size&&this.extContentAvailable)return void await this.requestConnectionPermissionFromExt();if((await this.isParentCheckSuccess(this.confirmParent(Array.from(n)))).success)this.logger.debug("The default parent was found!");else{if(!this.extContentAvailable)throw new Error(e);await this.requestConnectionPermissionFromExt()}}getPossibleParentsInWindow(e){return e&&e!==e.top?[e.parent,...this.getPossibleParentsInWindow(e.parent)]:[]}getPossibleParentsOutsideWindow(e,t){return e&&t&&e!==t?[e,...this.getPossibleParentsInWindow(e),...this.getPossibleParentsOutsideWindow(e.opener,e)]:[]}confirmParent(e){const t=W((t=>{this.parentPingResolve=t;const i={glue42core:{type:this.messages.platformPing.name}};this.parentPingInterval=setInterval((()=>{e.forEach((e=>{e.postMessage(i,this.defaultTargetString)}))}),1e3)}),this.parentPingTimeout,"Cannot initiate glue, because this window was not opened or created by a glue client");return t.catch((()=>{this.parentPingInterval&&(clearInterval(this.parentPingInterval),delete this.parentPingInterval)})),t}getMyWindowId(){return"workspace"===this.parentType?window.name.substring(0,window.name.indexOf("#wsp")):window===window.top?window.name?.includes("g42")?window.name:(this.selfAssignedWindowId=this.selfAssignedWindowId||`g42-${j(10)}`,this.selfAssignedWindowId):void 0}}class F{minSequenceInterval;queue=[];isExecutingQueue=!1;constructor(e=0){this.minSequenceInterval=e}enqueue(e){return new Promise(((t,i)=>{this.queue.push({action:e,resolve:t,reject:i}),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)))}}function D(e,t,i,n,s){null==e&&(e="global"),n=n??["success"],s=s??["error"];let r,o="global"===e,a=!1,c=!1;const d=A();t.disconnected((function(){c=!1,i.debug("connection is down"),o=!1,a=!0,d.execute("onLeft",{disconnected:!0})})),t.loggedIn((function(){c=!0,a&&(i.debug("connection is now up - trying to reconnect..."),u(r))})),t.on("success",(e=>g(e))),t.on("error",(e=>p(e))),t.on("result",(e=>g(e))),n&&n.forEach((e=>{t.on(e,(e=>g(e)))})),s&&s.forEach((e=>{t.on(e,(e=>p(e)))}));const h={};function u(t){return r=t,new Promise(((n,s)=>{if(o)return void n({});let r;if("global"===e)r=c?Promise.resolve({}):Promise.reject("not connected to gateway");else{i.debug(`joining domain ${e}`);r=y({type:"join",destination:e,domain:"global",options:t})}r.then((()=>{!function(){i.debug("did join "+e),o=!0;const t=a;a=!1,d.execute("onJoined",t)}(),n({})})).catch((t=>{i.debug("error joining "+e+" domain: "+JSON.stringify(t)),s(t)}))}))}function l(e){return o&&e(!1),d.add("onJoined",e)}function p(t){if(e!==t.domain)return;const i=t.request_id;if(!i)return;const n=h[i];n&&n.error(t)}function g(t){if(t.domain!==e)return;const i=t.request_id;if(!i)return;const n=h[i];n&&n.success(t)}function m(){return j(10)}let f=[];function y(n,s,r){if(n.type&&-1===["hello","join"].indexOf(n.type)&&!o){console.warn(`trying to send a message (${n.domain} ${n.type}) but not connected, will queue`);const e=new T;if(f.push({msg:n,tag:s,options:r,pw:e}),1===f.length){const e=l((()=>{i.info(`joined - will now send queued messages (${f.length} -> [${f.map((e=>e.msg.type))}])`),f.forEach((e=>{y(e.msg,e.tag,e.options).then((t=>e.pw.resolve(t))).catch((t=>e.pw.reject(t)))})),f=[],e()}))}return e.promise}r=r??{},n.request_id=n.request_id??m(),n.domain=n.domain??e,r.skipPeerId||(n.peer_id=t.peerId);const a=n.request_id;return new Promise(((e,o)=>{h[a]={success:t=>{delete h[a],t._tag=s,e(t)},error:e=>{i.warn(`Gateway error - ${JSON.stringify(e)}`),delete h[a],e._tag=s,o(e)}},t.send(n,r).catch((e=>{h[a].error({err:e})}))}))}return{join:u,leave:function(){return"global"===e?Promise.resolve():(i.debug("stopping session "+e+"..."),a=!1,y({type:"leave",destination:e,domain:"global"}).then((()=>{o=!1,d.execute("onLeft")})).catch((()=>{o=!1,d.execute("onLeft")})))},onJoined:l,onLeft:function(e){return o||e(),d.add("onLeft",e)},send:y,sendFireAndForget:function(i){return i.request_id=i.request_id?i.request_id:m(),i.domain=i.domain??e,i.peer_id=t.peerId,t.send(i)},on:(n,s)=>{t.on(n,(t=>{if(t.domain===e)try{s(t)}catch(e){i.error(`Callback failed: ${e} \n ${e.stack} \n msg was: ${JSON.stringify(t)}`,e)}}))},loggedIn:e=>t.loggedIn(e),connected:e=>t.connected(e),disconnected:e=>t.disconnected(e),get peerId(){return t.peerId},get domain(){return e}}}class L{settings;logger;protocolVersion=3;peerId;token;info;resolvedIdentity;availableDomains;gatewayToken;replayer;messageHandlers={};ids=1;registry=A();_connected=!1;isTrace=!1;transport;_defaultTransport;_defaultAuth;_targetTransport;_targetAuth;_swapTransport=!1;_switchInProgress=!1;_transportSubscriptions=[];datePrefix="#T42_DATE#";datePrefixLen=this.datePrefix.length;dateMinLen=this.datePrefixLen+1;datePrefixFirstChar=this.datePrefix[0];_sequelizer=new F;_isLoggedIn=!1;shouldTryLogin=!0;pingTimer;sessions=[];globalDomain;initialLogin=!0;initialLoginAttempts=3;loginConfig;constructor(e,t){if(this.settings=e,this.logger=t,(e=e||{}).reconnectAttempts=e.reconnectAttempts??10,e.reconnectInterval=e.reconnectInterval??1e3,e.inproc)this.transport=new S(e.inproc,t.subLogger("inMemory"));else if(e.sharedWorker)this.transport=new x(e.sharedWorker,t.subLogger("shared-worker"));else if(e.webPlatform)this.transport=new O(e.webPlatform,t.subLogger("web-platform"),e.identity);else{if(void 0===e.ws)throw new Error("No connection information specified");this.transport=new R(e,t.subLogger("ws"))}this.isTrace=t.canPublish("trace"),t.debug(`starting with ${this.transport.name()} transport`);const i=this.transport.onConnectedChanged(this.handleConnectionChanged.bind(this)),n=this.transport.onMessage(this.handleTransportMessage.bind(this));this._transportSubscriptions.push(i),this._transportSubscriptions.push(n),this._defaultTransport=this.transport,this.ping()}async switchTransport(e){return this._sequelizer.enqueue((async()=>{if(!e||"object"!=typeof e)throw new Error("Cannot switch transports, because the settings are missing or invalid.");if(void 0===e.type)throw new Error("Cannot switch the transport, because the type is not defined");this.logger.trace(`Starting transport switch with settings: ${JSON.stringify(e)}`);const t="secondary"===e.type?this.getNewSecondaryTransport(e):this._defaultTransport;this._targetTransport=t,this._targetAuth="secondary"===e.type?this.getNewSecondaryAuth(e):this._defaultAuth;const i=this.verifyConnection();this._swapTransport=!0,this._switchInProgress=!0,this.logger.trace("The new transport has been set, closing the current transport"),await this.transport.close();try{await i;const e=this.transport===t;return this.logger.info(`The reconnection after the switch was completed. Was the switch a success: ${e}`),this._switchInProgress=!1,{success:e}}catch(e){return this.logger.info("The reconnection after the switch timed out, reverting back to the default transport."),this.switchTransport({type:"default"}),this._switchInProgress=!1,{success:!1}}}))}onLibReAnnounced(e){return this.registry.add("libReAnnounced",e)}setLibReAnnounced(e){this.registry.execute("libReAnnounced",e)}send(e,t){if(this.transport.sendObject&&this.transport.isObjectBasedTransport){const i=this.createObjectMessage(e);return this.isTrace&&this.logger.trace(`>> ${JSON.stringify(i)}`),this.transport.sendObject(i,t)}{const i=this.createStringMessage(e);return this.isTrace&&this.logger.trace(`>> ${i}`),this.transport.send(i,t)}}on(e,t){e=e.toLowerCase(),void 0===this.messageHandlers[e]&&(this.messageHandlers[e]={});const i=this.ids++;return this.messageHandlers[e][i]=t,{type:e,id:i}}off(e){delete this.messageHandlers[e.type.toLowerCase()][e.id]}get isConnected(){return this._isLoggedIn}connected(e){return this.loggedIn((()=>{const t=this.transport.name();e(t)}))}disconnected(e){return this.registry.add("disconnected",e)}async login(e,t){if(this._defaultAuth||(this._defaultAuth=e),this._swapTransport){this.logger.trace("Detected a transport swap, swapping transports");e=this.transportSwap()??e}this.logger.trace(`Starting login for transport: ${this.transport.name()} and auth ${JSON.stringify(e)}`);try{await this.transport.open(),this.logger.trace(`Transport: ${this.transport.name()} opened, logging in`),P("connection").mark("transport-opened");const i=await this.loginCore(e,t);return this.logger.trace(`Logged in with identity: ${JSON.stringify(i)}`),P("connection").mark("protocol-logged-in"),i}catch(e){throw this._switchInProgress&&(this.logger.trace("An error while logging in after a transport swap, preparing a default swap."),this.prepareDefaultSwap()),new Error(e)}}async logout(){await this.logoutCore(),await this.transport.close()}loggedIn(e){return this._isLoggedIn&&e(),this.registry.add("onLoggedIn",e)}domain(e,t,i){let n=this.sessions.find((t=>t.domain===e));return n||(n=D(e,this,this.logger.subLogger(`domain=${e}`),t,i),this.sessions.push(n)),n}authToken(){return this.globalDomain?this.globalDomain.send({domain:"global",type:"create-token"}).then((e=>e.token)):Promise.reject(new Error("no global domain session"))}reconnect(){return this.transport.reconnect()}setLoggedIn(e){this._isLoggedIn=e,this._isLoggedIn&&this.registry.execute("onLoggedIn")}distributeMessage(e,t){const i=this.messageHandlers[t.toLowerCase()];void 0!==i&&Object.keys(i).forEach((t=>{const n=i[t];if(void 0!==n)try{n(e)}catch(e){try{this.logger.error(`Message handler failed with ${e.stack}`,e)}catch(t){console.log("Message handler failed",e)}}}))}handleConnectionChanged(e){this._connected!==e&&(this._connected=e,e?(this.settings?.replaySpecs?.length&&(this.replayer=new N(this.settings.replaySpecs),this.replayer.init(this)),this.registry.execute("connected")):(this.handleDisconnected(),this.registry.execute("disconnected")))}handleDisconnected(){this.setLoggedIn(!1);if(this.shouldTryLogin&&this.initialLogin){if(this.initialLoginAttempts<=0)return;this.initialLoginAttempts--}if(this.logger.debug("disconnected - will try new login?"+this.shouldTryLogin),this.shouldTryLogin){if(!this.loginConfig)throw new Error("no login info");this.login(this.loginConfig,!0).catch((()=>{setTimeout(this.handleDisconnected.bind(this),this.settings.reconnectInterval||1e3)}))}}handleTransportMessage(e){let t;t="string"==typeof e?this.processStringMessage(e):this.processObjectMessage(e),this.isTrace&&this.logger.trace(`<< ${JSON.stringify(t)}`),this.distributeMessage(t.msg,t.msgType)}verifyConnection(){return W((e=>{let t;const i=((e,t)=>{let i=e;return()=>{i--,0===i&&t()}})(2,(()=>{t&&t(),e()}));t=this.onLibReAnnounced((e=>"interop"===e.name||"contexts"===e.name?i():void 0))}),1e4,"Transport switch timed out waiting for all libraries to be re-announced")}getNewSecondaryTransport(e){if(!e.transportConfig?.url)throw new Error("Missing secondary transport URL.");return new R(Object.assign({},this.settings,{ws:e.transportConfig.url,reconnectAttempts:1}),this.logger.subLogger("ws-secondary"))}getNewSecondaryAuth(e){if(!e.transportConfig?.auth)throw new Error("Missing secondary transport auth information.");return e.transportConfig.auth}transportSwap(){if(this._swapTransport=!1,!this._targetTransport||!this._targetAuth)return void this.logger.warn(`Error while switching transports - either the target transport or auth is not defined: transport defined -> ${!!this._defaultTransport}, auth defined -> ${!!this._targetAuth}. Staying on the current one.`);this._transportSubscriptions.forEach((e=>e())),this._transportSubscriptions=[],this.transport=this._targetTransport;const e=this.transport.onConnectedChanged(this.handleConnectionChanged.bind(this)),t=this.transport.onMessage(this.handleTransportMessage.bind(this));return this._transportSubscriptions.push(e),this._transportSubscriptions.push(t),this._targetAuth}prepareDefaultSwap(){this._transportSubscriptions.forEach((e=>e())),this._transportSubscriptions=[],this.transport.close().catch((e=>this.logger.warn(`Error closing the ${this.transport.name()} transport after a failed connection attempt: ${JSON.stringify(e)}`))),this._targetTransport=this._defaultTransport,this._targetAuth=this._defaultAuth,this._swapTransport=!0}processStringMessage(e){const t=JSON.parse(e,((e,t)=>{if("string"!=typeof t)return t;if(t.length<this.dateMinLen)return t;if(!t.startsWith(this.datePrefixFirstChar))return t;if(t.substring(0,this.datePrefixLen)!==this.datePrefix)return t;try{const e=parseInt(t.substring(this.datePrefixLen,t.length),10);return isNaN(e)?t:new Date(e)}catch(e){return t}}));return{msg:t,msgType:t.type}}createStringMessage(e){const t=Date.prototype.toJSON;try{const t=this.datePrefix;Date.prototype.toJSON=function(){return t+this.getTime()};return JSON.stringify(e)}finally{Date.prototype.toJSON=t}}processObjectMessage(e){if(!e.type)throw new Error("Object should have type property");return{msg:e,msgType:e.type}}createObjectMessage(e){return e}async loginCore(e,t){this.logger.info("logging in..."),this.loginConfig=e,this.loginConfig||(this.loginConfig={username:"",password:""}),this.shouldTryLogin=!0;const i=await this.setupAuthConfig(e,t),n={type:"hello",identity:this.settings.identity,authentication:i};e.sessionId&&(n.request_id=e.sessionId),this.globalDomain=D("global",this,this.logger.subLogger("global-domain"),["welcome","token","authentication-request"]);const s={skipPeerId:!0};this.initialLogin&&(s.retryInterval=this.settings.reconnectInterval,s.maxRetries=this.settings.reconnectAttempts);try{const t=await this.tryAuthenticate(this.globalDomain,n,s,e);return this.initialLogin=!1,this.logger.info("login successful with peerId "+t.peer_id),this.peerId=t.peer_id,this.resolvedIdentity=t.resolved_identity,this.availableDomains=t.available_domains,t.options&&(this.token=t.options.access_token,this.info=t.options.info),this.setLoggedIn(!0),t.resolved_identity}catch(e){throw this.logger.error("error sending hello message - "+(e.message||e.msg||e.reason||e),e),e}finally{e?.flowCallback&&e.sessionId&&e.flowCallback(e.sessionId,null)}}async tryAuthenticate(e,t,i,n){let s;for(;;){const r=await e.send(t,void 0,i);if("authentication-request"!==r.type){if("welcome"===r.type){s=r;break}throw"error"===r.type?new Error("Authentication failed: "+r.reason):new Error("Unexpected message type during authentication: "+r.type)}{const e=Buffer.from(r.authentication.token,"base64");n.flowCallback&&n.sessionId&&(t.authentication.token=(await n.flowCallback(n.sessionId,e)).data.toString("base64")),t.request_id=n.sessionId}}return s}async setupAuthConfig(e,t){const i={};if(this.gatewayToken=e.gatewayToken,e.gatewayToken){if(t)try{e.gatewayToken=await this.getNewGWToken()}catch(e){this.logger.warn(`failed to get GW token when reconnecting ${e?.message||e}`)}i.method="gateway-token",i.token=e.gatewayToken,this.gatewayToken=e.gatewayToken}else if("sspi"===e.flowName){if(i.provider="win",i.method="access-token",!e.flowCallback||!e.sessionId)throw new Error("Invalid SSPI config");i.token=(await e.flowCallback(e.sessionId,null)).data.toString("base64")}else if(e.token)i.method="access-token",i.token=e.token;else if(e.username)i.method="secret",i.login=e.username,i.secret=e.password;else{if(!e.provider)throw new Error("invalid auth message"+JSON.stringify(e));i.provider=e.provider,i.providerContext=e.providerContext}return i}async logoutCore(){this.logger.debug("logging out..."),this.shouldTryLogin=!1,this.pingTimer&&clearTimeout(this.pingTimer);const e=this.sessions.map((e=>{e.leave()}));await Promise.all(e)}getNewGWToken(){if("undefined"!=typeof window){const e=window.glue42gd;if(e)return e.getGWToken()}return Promise.reject(new Error("not running in GD"))}ping(){this.shouldTryLogin&&(this._isLoggedIn&&this.send({type:"ping"}),this.pingTimer=setTimeout((()=>{this.ping()}),3e4))}}const $=["trace","debug","info","warn","error","off"];let G=class e{name;parent;static Interop;static InteropMethodName="T42.AppLogger.Log";static Instance;path;subLoggers=[];_consoleLevel;_publishLevel;loggerFullName;includeTimeAndLevel;logFn=console;customLogFn=!1;constructor(e,t,i){this.name=e,this.parent=t,this.name=e,this.path=t?`${t.path}.${e}`:e,this.loggerFullName=`[${this.path}]`,this.includeTimeAndLevel=!i,i&&(this.logFn=i,this.customLogFn=!0)}subLogger(t){const i=this.subLoggers.filter((e=>e.name===t))[0];if(void 0!==i)return i;Object.keys(this).forEach((e=>{if(e===t)throw new Error("This sub logger name is not allowed.")}));const n=new e(t,this,this.customLogFn?this.logFn:void 0);return this.subLoggers.push(n),n}publishLevel(e){return e&&(this._publishLevel=e),this._publishLevel||this.parent?.publishLevel()}consoleLevel(e){return e&&(this._consoleLevel=e),this._consoleLevel||this.parent?.consoleLevel()}log(e,t,i){this.publishMessage(t||"info",e,i)}trace(e){this.log(e,"trace")}debug(e){this.log(e,"debug")}info(e){this.log(e,"info")}warn(e){this.log(e,"warn")}error(e,t){this.log(e,"error")}canPublish(e,t){return $.indexOf(e)>=$.indexOf(t||this.consoleLevel()||"trace")}publishMessage(t,i,n){const s=this.loggerFullName;if("error"===t&&!n){const e=new Error;e.stack&&(i=i+"\n"+e.stack.split("\n").slice(3).join("\n"))}if(this.canPublish(t,this.publishLevel())){const n=e.Interop;if(n)try{n.methods({name:e.InteropMethodName}).length>0&&n.invoke(e.InteropMethodName,{msg:`${i}`,logger:s,level:t})}catch{}}if(this.canPublish(t)){let e="";if(this.includeTimeAndLevel){const i=new Date;e=`[${`${i.getHours()}:${i.getMinutes()}:${i.getSeconds()}:${i.getMilliseconds()}`}] [${t}] `}const r=`${e}${s}: ${i}`;switch(t){case"trace":this.logFn.debug(r);break;case"debug":this.logFn.debug?this.logFn.debug(r):this.logFn.log(r);break;case"info":this.logFn.info(r);break;case"warn":this.logFn.warn(r);break;case"error":this.logFn.error(r,n)}}}};const B="create-context",H="created",U="destroyed",q="context-created",J="context-added",V="subscribe-context",z="subscribed-context",K="unsubscribe-context",Q="destroy-context",Z="context-destroyed",X="update-context",Y="context-updated",ee="joined",te={get name(){return"context"},get types(){return[B,H,U,q,J,V,z,K,Q,Z,X,Y,ee]}};var ie="6.4.2";class ne{name;contextId;context;isAnnounced;joinedActivity;updateCallbacks={};activityId;sentExplicitSubscription;hasReceivedSnapshot;constructor(e,t,i,n){this.contextId=e,this.name=t,this.isAnnounced=i,this.activityId=n,this.context={}}hasCallbacks(){return Object.keys(this.updateCallbacks).length>0}getState(){return this.isAnnounced&&this.hasCallbacks()?3:this.isAnnounced?2:this.hasCallbacks()?1:0}}var se={exports:{}};!function(e,t){var i="__lodash_hash_undefined__",n=9007199254740991,s="[object Arguments]",r="[object Boolean]",o="[object Date]",a="[object Function]",c="[object GeneratorFunction]",d="[object Map]",h="[object Number]",u="[object Object]",l="[object Promise]",p="[object RegExp]",g="[object Set]",m="[object String]",f="[object Symbol]",y="[object WeakMap]",w="[object ArrayBuffer]",v="[object DataView]",b="[object Float32Array]",I="[object Float64Array]",C="[object Int8Array]",A="[object Int16Array]",S="[object Int32Array]",x="[object Uint8Array]",k="[object Uint8ClampedArray]",T="[object Uint16Array]",E="[object Uint32Array]",P=/\w*$/,M=/^\[object .+?Constructor\]$/,R=/^(?:0|[1-9]\d*)$/,N={};N[s]=N["[object Array]"]=N[w]=N[v]=N[r]=N[o]=N[b]=N[I]=N[C]=N[A]=N[S]=N[d]=N[h]=N[u]=N[p]=N[g]=N[m]=N[f]=N[x]=N[k]=N[T]=N[E]=!0,N["[object Error]"]=N[a]=N[y]=!1;var j="object"==typeof _&&_&&_.Object===Object&&_,W="object"==typeof self&&self&&self.Object===Object&&self,O=j||W||Function("return this")(),F=t&&!t.nodeType&&t,D=F&&e&&!e.nodeType&&e,L=D&&D.exports===F;function $(e,t){return e.set(t[0],t[1]),e}function G(e,t){return e.add(t),e}function B(e,t,i,n){var s=-1,r=e?e.length:0;for(n&&r&&(i=e[++s]);++s<r;)i=t(i,e[s],s,e);return i}function H(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(e){}return t}function U(e){var t=-1,i=Array(e.size);return e.forEach((function(e,n){i[++t]=[n,e]})),i}function q(e,t){return function(i){return e(t(i))}}function J(e){var t=-1,i=Array(e.size);return e.forEach((function(e){i[++t]=e})),i}var V,z=Array.prototype,K=Function.prototype,Q=Object.prototype,Z=O["__core-js_shared__"],X=(V=/[^.]+$/.exec(Z&&Z.keys&&Z.keys.IE_PROTO||""))?"Symbol(src)_1."+V:"",Y=K.toString,ee=Q.hasOwnProperty,te=Q.toString,ie=RegExp("^"+Y.call(ee).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),ne=L?O.Buffer:void 0,se=O.Symbol,re=O.Uint8Array,oe=q(Object.getPrototypeOf,Object),ae=Object.create,ce=Q.propertyIsEnumerable,de=z.splice,he=Object.getOwnPropertySymbols,ue=ne?ne.isBuffer:void 0,le=q(Object.keys,Object),pe=De(O,"DataView"),ge=De(O,"Map"),me=De(O,"Promise"),fe=De(O,"Set"),ye=De(O,"WeakMap"),we=De(Object,"create"),ve=He(pe),be=He(ge),_e=He(me),Ie=He(fe),Ce=He(ye),Ae=se?se.prototype:void 0,Se=Ae?Ae.valueOf:void 0;function xe(e){var t=-1,i=e?e.length:0;for(this.clear();++t<i;){var n=e[t];this.set(n[0],n[1])}}function ke(e){var t=-1,i=e?e.length:0;for(this.clear();++t<i;){var n=e[t];this.set(n[0],n[1])}}function Te(e){var t=-1,i=e?e.length:0;for(this.clear();++t<i;){var n=e[t];this.set(n[0],n[1])}}function Ee(e){this.__data__=new ke(e)}function Pe(e,t){var i=qe(e)||function(e){return function(e){return function(e){return!!e&&"object"==typeof e}(e)&&Je(e)}(e)&&ee.call(e,"callee")&&(!ce.call(e,"callee")||te.call(e)==s)}(e)?function(e,t){for(var i=-1,n=Array(e);++i<e;)n[i]=t(i);return n}(e.length,String):[],n=i.length,r=!!n;for(var o in e)!t&&!ee.call(e,o)||r&&("length"==o||Ge(o,n))||i.push(o);return i}function Me(e,t,i){var n=e[t];ee.call(e,t)&&Ue(n,i)&&(void 0!==i||t in e)||(e[t]=i)}function Re(e,t){for(var i=e.length;i--;)if(Ue(e[i][0],t))return i;return-1}function Ne(e,t,i,n,l,y,_){var M;if(n&&(M=y?n(e,l,y,_):n(e)),void 0!==M)return M;if(!Ke(e))return e;var R=qe(e);if(R){if(M=function(e){var t=e.length,i=e.constructor(t);t&&"string"==typeof e[0]&&ee.call(e,"index")&&(i.index=e.index,i.input=e.input);return i}(e),!t)return function(e,t){var i=-1,n=e.length;t||(t=Array(n));for(;++i<n;)t[i]=e[i];return t}(e,M)}else{var j=$e(e),W=j==a||j==c;if(Ve(e))return function(e,t){if(t)return e.slice();var i=new e.constructor(e.length);return e.copy(i),i}(e,t);if(j==u||j==s||W&&!y){if(H(e))return y?e:{};if(M=function(e){return"function"!=typeof e.constructor||Be(e)?{}:(t=oe(e),Ke(t)?ae(t):{});var t}(W?{}:e),!t)return function(e,t){return Oe(e,Le(e),t)}(e,function(e,t){return e&&Oe(t,Qe(t),e)}(M,e))}else{if(!N[j])return y?e:{};M=function(e,t,i,n){var s=e.constructor;switch(t){case w:return We(e);case r:case o:return new s(+e);case v:return function(e,t){var i=t?We(e.buffer):e.buffer;return new e.constructor(i,e.byteOffset,e.byteLength)}(e,n);case b:case I:case C:case A:case S:case x:case k:case T:case E:return function(e,t){var i=t?We(e.buffer):e.buffer;return new e.constructor(i,e.byteOffset,e.length)}(e,n);case d:return function(e,t,i){var n=t?i(U(e),!0):U(e);return B(n,$,new e.constructor)}(e,n,i);case h:case m:return new s(e);case p:return function(e){var t=new e.constructor(e.source,P.exec(e));return t.lastIndex=e.lastIndex,t}(e);case g:return function(e,t,i){var n=t?i(J(e),!0):J(e);return B(n,G,new e.constructor)}(e,n,i);case f:return a=e,Se?Object(Se.call(a)):{}}var a}(e,j,Ne,t)}}_||(_=new Ee);var O=_.get(e);if(O)return O;if(_.set(e,M),!R)var F=i?function(e){return function(e,t,i){var n=t(e);return qe(e)?n:function(e,t){for(var i=-1,n=t.length,s=e.length;++i<n;)e[s+i]=t[i];return e}(n,i(e))}(e,Qe,Le)}(e):Qe(e);return function(e,t){for(var i=-1,n=e?e.length:0;++i<n&&!1!==t(e[i],i,e););}(F||e,(function(s,r){F&&(s=e[r=s]),Me(M,r,Ne(s,t,i,n,r,e,_))})),M}function je(e){return!(!Ke(e)||(t=e,X&&X in t))&&(ze(e)||H(e)?ie:M).test(He(e));var t}function We(e){var t=new e.constructor(e.byteLength);return new re(t).set(new re(e)),t}function Oe(e,t,i,n){i||(i={});for(var s=-1,r=t.length;++s<r;){var o=t[s],a=n?n(i[o],e[o],o,i,e):void 0;Me(i,o,void 0===a?e[o]:a)}return i}function Fe(e,t){var i,n,s=e.__data__;return("string"==(n=typeof(i=t))||"number"==n||"symbol"==n||"boolean"==n?"__proto__"!==i:null===i)?s["string"==typeof t?"string":"hash"]:s.map}function De(e,t){var i=function(e,t){return null==e?void 0:e[t]}(e,t);return je(i)?i:void 0}xe.prototype.clear=function(){this.__data__=we?we(null):{}},xe.prototype.delete=function(e){return this.has(e)&&delete this.__data__[e]},xe.prototype.get=function(e){var t=this.__data__;if(we){var n=t[e];return n===i?void 0:n}return ee.call(t,e)?t[e]:void 0},xe.prototype.has=function(e){var t=this.__data__;return we?void 0!==t[e]:ee.call(t,e)},xe.prototype.set=function(e,t){return this.__data__[e]=we&&void 0===t?i:t,this},ke.prototype.clear=function(){this.__data__=[]},ke.prototype.delete=function(e){var t=this.__data__,i=Re(t,e);return!(i<0)&&(i==t.length-1?t.pop():de.call(t,i,1),!0)},ke.prototype.get=function(e){var t=this.__data__,i=Re(t,e);return i<0?void 0:t[i][1]},ke.prototype.has=function(e){return Re(this.__data__,e)>-1},ke.prototype.set=function(e,t){var i=this.__data__,n=Re(i,e);return n<0?i.push([e,t]):i[n][1]=t,this},Te.prototype.clear=function(){this.__data__={hash:new xe,map:new(ge||ke),string:new xe}},Te.prototype.delete=function(e){return Fe(this,e).delete(e)},Te.prototype.get=function(e){return Fe(this,e).get(e)},Te.prototype.has=function(e){return Fe(this,e).has(e)},Te.prototype.set=function(e,t){return Fe(this,e).set(e,t),this},Ee.prototype.clear=function(){this.__data__=new ke},Ee.prototype.delete=function(e){return this.__data__.delete(e)},Ee.prototype.get=function(e){return this.__data__.get(e)},Ee.prototype.has=function(e){return this.__data__.has(e)},Ee.prototype.set=function(e,t){var i=this.__data__;if(i instanceof ke){var n=i.__data__;if(!ge||n.length<199)return n.push([e,t]),this;i=this.__data__=new Te(n)}return i.set(e,t),this};var Le=he?q(he,Object):function(){return[]},$e=function(e){return te.call(e)};function Ge(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||Q)}function He(e){if(null!=e){try{return Y.call(e)}catch(e){}try{return e+""}catch(e){}}return""}function Ue(e,t){return e===t||e!=e&&t!=t}(pe&&$e(new pe(new ArrayBuffer(1)))!=v||ge&&$e(new ge)!=d||me&&$e(me.resolve())!=l||fe&&$e(new fe)!=g||ye&&$e(new ye)!=y)&&($e=function(e){var t=te.call(e),i=t==u?e.constructor:void 0,n=i?He(i):void 0;if(n)switch(n){case ve:return v;case be:return d;case _e:return l;case Ie:return g;case Ce:return y}return t});var qe=Array.isArray;function Je(e){return null!=e&&function(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=n}(e.length)&&!ze(e)}var Ve=ue||function(){return!1};function ze(e){var t=Ke(e)?te.call(e):"";return t==a||t==c}function Ke(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function Qe(e){return Je(e)?Pe(e):function(e){if(!Be(e))return le(e);var t=[];for(var i in Object(e))ee.call(e,i)&&"constructor"!=i&&t.push(i);return t}(e)}e.exports=function(e){return Ne(e,!0,!0)}}(se,se.exports);var re=I(se.exports);function oe(e,t,i){try{if(i?.canPublish("trace")&&i?.trace(`applying context delta ${JSON.stringify(t)} on context ${JSON.stringify(e)}`),!t)return e;if(t.reset)return e={...t.reset};if(e=ae(e,void 0),t.commands){for(const i of t.commands)"remove"===i.type?le(e,i.path):"set"===i.type&&he(e,i.value,i.path);return e}const n=t.added,s=t.updated,r=t.removed;return n&&Object.keys(n).forEach((t=>{e[t]=n[t]})),s&&Object.keys(s).forEach((t=>{ce(t,e,s)})),r&&r.forEach((t=>{delete e[t]})),e}catch(n){return i?.error(`error applying context delta ${JSON.stringify(t)} on context ${JSON.stringify(e)}`,n),e}}function ae(e,t){return re(e)}const ce=(e,t,i)=>{const n=i[e];if(void 0===n)return t;const s=t[e];return s&&n?"string"==typeof s||"number"==typeof s||"boolean"==typeof s||"string"==typeof n||"number"==typeof n||"boolean"==typeof n||Array.isArray(s)||Array.isArray(n)?(t[e]=n,t):(t[e]=Object.assign({},s,n),t):(t[e]=n,t)};function de(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 i in e)if(e.hasOwnProperty(i)){if(!t.hasOwnProperty(i))return!1;if(e[i]!==t[i]){if("object"!=typeof e[i])return!1;if(!de(e[i],t[i]))return!1}}for(const i in t)if(t.hasOwnProperty(i)&&!e.hasOwnProperty(i))return!1;return!0}function he(e,t,i){const n=i.split(".");let s;for(s=0;s<n.length-1;s++)e[n[s]]||(e[n[s]]={}),"object"!=typeof e[n[s]]&&(e[n[s]]={}),e=e[n[s]];e[n[s]]=t}function ue(e,t){return Object.keys(t).every((i=>"object"==typeof t[i]?ue(e?.[i]||{},t[i]||{}):t[i]===e?.[i]))}function le(e,t){const i=t.split(".");let n;for(n=0;n<i.length-1;n++){if(!e[i[n]])return;e=e[i[n]]}delete e[i[n]]}class pe{initTime;initStartTime;initEndTime;_bridge;constructor(e){this._bridge=new class{_logger;_connection;_trackAllContexts;_reAnnounceKnownContexts;_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._gw3Session=this._connection.domain("global",[q,z,Z,Y]),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"}))):this._connection.setLibReAnnounced({name:"contexts"})})),this.subscribeToContextCreatedMessages(),this.subscribeToContextUpdatedMessages(),this.subscribeToContextDestroyedMessages(),this._connection.replayer?.drain(te.name,(e=>{const t=e.type;t&&(t===q||t===J||t===H?this.handleContextCreatedMessage(e):t===z||t===Y||t===ee?this.handleContextUpdatedMessage(e):t!==Z&&t!==U||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){return e in this._creationPromises||(this._creationPromises[e]=this._gw3Session.send({type:B,domain:"global",name:e,data:t,lifetime:"retained"}).then((i=>{this._contextNameToId[e]=i.context_id,this._contextIdToName[i.context_id]=e;const n=this._contextNameToData[e]||new ne(i.context_id,e,!0,void 0);return n.isAnnounced=!0,n.name=e,n.contextId=i.context_id,n.context=i.data||ae(t),n.hasReceivedSnapshot=!0,this._contextNameToData[e]=n,delete this._creationPromises[e],i.context_id}))),this._creationPromises[e]}all(){return Object.keys(this._contextNameToData).filter((e=>this._contextNameToData[e].isAnnounced))}async update(e,t){t&&(t=ae(t)),e in this._creationPromises&&await this._creationPromises[e];const i=this._contextNameToData[e];if(!i||!i.isAnnounced)return this.createContext(e,t);let n=i.context;i.hasCallbacks()||(n=await this.get(i.name));const s=this.setPathSupported?this.calculateContextDeltaV2(n,t):this.calculateContextDeltaV1(n,t);return Object.keys(s.added).length||Object.keys(s.updated).length||s.removed.length||s.commands?.length?this._gw3Session.send({type:X,domain:"global",context_id:i.contextId,delta:s},{},{skipPeerId:!1}).then((e=>{this.handleUpdated(i,s,{updaterId:e.peer_id})})):Promise.resolve()}async set(e,t){t&&(t=ae(t)),e in this._creationPromises&&await this._creationPromises[e];const i=this._contextNameToData[e];return i&&i.isAnnounced?this._gw3Session.send({type:X,domain:"global",context_id:i.contextId,delta:{reset:t}},{},{skipPeerId:!1}).then((e=>{this.handleUpdated(i,{reset:t,added:{},removed:[],updated:{}},{updaterId:e.peer_id})})):this.createContext(e,t)}setPath(e,t,i){return this.setPathSupported?this.setPaths(e,[{path:t,value:i}]):Promise.reject("glue.contexts.setPath operation is not supported, use Glue42 3.10 or later")}async setPaths(e,t){if(!this.setPathSupported)return Promise.reject("glue.contexts.setPaths operation is not supported, use Glue42 3.10 or later");t&&(t=ae(t)),e in this._creationPromises&&await this._creationPromises[e];const i=this._contextNameToData[e];if(!i||!i.isAnnounced){const i={};for(const e of t)he(i,e.value,e.path);return this.createContext(e,i)}const n=[];for(const e of t)null===e.value?n.push({type:"remove",path:e.path}):n.push({type:"set",path:e.path,value:e.value});return this._gw3Session.send({type:X,domain:"global",context_id:i.contextId,delta:{commands:n}},{},{skipPeerId:!1}).then((e=>{this.handleUpdated(i,{added:{},removed:[],updated:{},commands:n},{updaterId:e.peer_id})}))}async get(e){e in this._creationPromises&&await this._creationPromises[e];const t=this._contextNameToData[e];if(!t||!t.isAnnounced)return Promise.resolve({});if(t&&(!t.hasCallbacks()||!t.hasReceivedSnapshot))return new Promise((t=>{this.subscribe(e,((e,i,n,s)=>{this.unsubscribe(s),t(e)}))}));const i=t?.context??{};return Promise.resolve(ae(i))}async subscribe(e,t,i){e in this._creationPromises&&await this._creationPromises[e];const n=void 0===i?this._nextCallbackSubscriptionNumber:i;void 0===i&&(this._nextCallbackSubscriptionNumber+=1),this._contextsSubscriptionsCache.every((e=>e.subKey!==this._nextCallbackSubscriptionNumber))&&this._contextsSubscriptionsCache.push({contextName:e,subKey:n,callback:t});let s=this._contextNameToData[e];if(!s||!s.isAnnounced)return s=s||new ne(void 0,e,!1,void 0),this._contextNameToData[e]=s,s.updateCallbacks[n]=t,Promise.resolve(n);const r=s.hasCallbacks();if(s.updateCallbacks[n]=t,r){if(s.hasReceivedSnapshot){const e=ae(s.context);t(e,e,[],n)}return Promise.resolve(n)}if(s.joinedActivity){if(s.hasReceivedSnapshot){const e=ae(s.context);t(e,e,[],n)}return Promise.resolve(n)}if(s.context&&s.sentExplicitSubscription){if(s.hasReceivedSnapshot){const e=ae(s.context);t(e,e,[],n)}return Promise.resolve(n)}return this.sendSubscribe(s).then((()=>n))}unsubscribe(e){this._contextsSubscriptionsCache=this._contextsSubscriptionsCache.filter((t=>t.subKey!==e));for(const t of Object.keys(this._contextNameToData)){const i=this._contextNameToData[t];if(!i)return;const n=i.hasCallbacks();delete i.updateCallbacks[e],i.isAnnounced&&n&&!i.hasCallbacks()&&i.sentExplicitSubscription&&this.sendUnsubscribe(i).catch((()=>{})),i.isAnnounced||i.hasCallbacks()||delete this._contextNameToData[t]}}async destroy(e){e in this._creationPromises&&await this._creationPromises[e];const t=this._contextNameToData[e];return t?this._gw3Session.send({type:Q,domain:"global",context_id:t.contextId}).then((e=>{})):Promise.reject(`context with ${e} does not exist`)}handleUpdated(e,t,i){const n=e.context;e.context=oe(e.context,t,this._logger),e.hasReceivedSnapshot=!0,this._contextNameToData[e.name]!==e||de(n,e.context)||this.invokeUpdateCallbacks(e,t,i)}subscribeToContextCreatedMessages(){const e=[J,q,H];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===H?(this._contextNameToId[e.activity_id]=e.context_id,this._contextIdToName[e.context_id]=e.activity_id):t===J&&(this._contextNameToId[e.name]=e.context_id,this._contextIdToName[e.context_id]=e.name);const i=this._contextIdToName[e.context_id];if(!i)throw new Error("Received created event for context with unknown name: "+e.context_id);if(!this._contextNameToId[i])throw new Error("Received created event for context with unknown id: "+e.context_id);let n=this._contextNameToData[i];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)}else this._contextNameToData[i]=n=new ne(e.context_id,i,!0,e.activity_id),this._trackAllContexts&&this.subscribe(i,(()=>{})).then((e=>this._systemContextsSubKey=e))}subscribeToContextUpdatedMessages(){const e=[Y,z,ee];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,i=e.context_id;let n=this._contextNameToData[this._contextIdToName[i]];const s=!n||!n.isAnnounced;if(t===ee)n||(n=this._contextNameToData[e.activity_id]||new ne(i,e.activity_id,!0,e.activity_id)),this._contextNameToData[e.activity_id]=n,this._contextIdToName[i]=e.activity_id,this._contextNameToId[e.activity_id]=i,n.contextId=i,n.isAnnounced=!0,n.activityId=e.activity_id,n.joinedActivity=!0;else if(!n||!n.isAnnounced)return void(t===z?(n=n||new ne(i,e.name,!0,void 0),n.sentExplicitSubscription=!0,this._contextNameToData[e.name]=n,this._contextIdToName[i]=e.name,this._contextNameToId[e.name]=i):this._logger.error(`Received 'update' for unknown context: ${i}`));const r=n.context;if(n.hasReceivedSnapshot=!0,t===z)n.context=e.data||{};else if(t===ee)n.context=e.context_snapshot||{};else{if(t!==Y)throw new Error("Unrecognized context update message "+t);n.context=oe(n.context,e.delta,this._logger)}!s&&de(n.context,r)&&t!==z||this.invokeUpdateCallbacks(n,e.delta,{updaterId:e.updater_id})}invokeUpdateCallbacks(e,t,i){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),he(t.updated,null,e.path)):"set"===e.type&&he(t.updated,e.value,e.path)}for(const n in e.updateCallbacks)if(e.updateCallbacks.hasOwnProperty(n))try{(0,e.updateCallbacks[n])(ae(e.context),ae(Object.assign({},t.added||{},t.updated||{},t.reset||{})),t.removed,parseInt(n,10),i)}catch(e){this._logger.debug("callback error: "+JSON.stringify(e))}}subscribeToContextDestroyedMessages(){const e=[Z,U];for(const t of e){const e=this._connection.on(t,this.handleContextDestroyedMessage.bind(this));this._gw3Subscriptions.push(e)}}handleContextDestroyedMessage(e){let t,i;if(e.type===U){if(i=e.activity_id,t=this._contextNameToId[i],!t)return void this._logger.error(`Received 'destroyed' for unknown activity: ${e.activity_id}`)}else if(t=e.context_id,i=this._contextIdToName[t],!i)return void this._logger.error(`Received 'destroyed' for unknown context: ${e.context_id}`);delete this._contextIdToName[t],delete this._contextNameToId[i];const n=this._contextNameToData[i];delete this._contextNameToData[i],n&&n.isAnnounced||this._logger.error(`Received 'destroyed' for unknown context: ${t}`)}sendSubscribe(e){return e.sentExplicitSubscription=!0,this._gw3Session.send({type:V,domain:"global",context_id:e.contextId}).then((e=>{}))}sendUnsubscribe(e){return e.sentExplicitSubscription=!1,this._gw3Session.send({type:K,domain:"global",context_id:e.contextId}).then((e=>{}))}calculateContextDeltaV1(e,t){const i={added:{},updated:{},removed:[],reset:void 0};if(e)for(const n of Object.keys(e))-1===Object.keys(t).indexOf(n)||null===t[n]||de(e[n],t[n])||(i.updated[n]=t[n]);for(const n of Object.keys(t))e&&-1!==Object.keys(e).indexOf(n)?null===t[n]&&i.removed.push(n):null!==t[n]&&(i.added[n]=t[n]);return i}calculateContextDeltaV2(e,t){const i={added:{},updated:{},removed:[],reset:void 0,commands:[]};for(const n of Object.keys(t))null!==t[n]?de(e?e[n]:null,t[n])||i.commands?.push({type:"set",path:n,value:t[n]}):i.commands?.push({type:"remove",path:n});return i}resetState(){for(const e of this._gw3Subscriptions)this._connection.off(e);this._systemContextsSubKey&&(this.unsubscribe(this._systemContextsSubKey),delete this._systemContextsSubKey),this._gw3Subscriptions=[],this._contextNameToId={},this._contextIdToName={},delete this._protocolVersion,this._contextsTempCache=Object.keys(this._contextNameToData).reduce(((e,t)=>(e[t]=this._contextNameToData[t].context,e)),{}),this._contextNameToData={}}async reInitiateState(){this.subscribeToContextCreatedMessages(),this.subscribeToContextUpdatedMessages(),this.subscribeToContextDestroyedMessages(),this._connection.replayer?.drain(te.name,(e=>{const t=e.type;t&&(t===q||t===J||t===H?this.handleContextCreatedMessage(e):t===z||t===Y||t===ee?this.handleContextUpdatedMessage(e):t!==Z&&t!==U||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)))}}(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,i){this.checkName(e),this.checkPath(t);return""===t?(this.checkData(i),this.set(e,i)):this._bridge.setPath(e,t,i)}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:i}of t){this.checkPath(e);""===e&&this.checkData(i)}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,i,n,s,r)=>t(e,i,n,(()=>this._bridge.unsubscribe(s)),r))).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 ge(e,t,i){return"function"!=typeof t&&"function"!=typeof i?e:("function"!=typeof t?t=()=>{}:"function"!=typeof i&&(i=()=>{}),e.then(t,i))}function me(e=0,t,i){let n;const s=()=>{n&&clearTimeout(n)};return t.then((()=>{s()})).catch((()=>{s()})),new Promise(((t,s)=>{n=setTimeout((()=>s(i)),e)}))}var fe;!function(e){e[e.Success=0]="Success",e[e.Error=1]="Error"}(fe||(fe={}));class ye{protocol;repo;instance;configuration;constructor(e,t,i,n){this.protocol=e,this.repo=t,this.instance=i,this.configuration=n}subscribe(e,t,i,n,s){const r=(e,i,n,r)=>{t.methodResponseTimeout=t.methodResponseTimeout??t.waitTimeoutMs,this.protocol.client.subscribe(i,t,e,n,r,s)};return ge(new Promise(((i,n)=>{const s=e=>{i(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 d=0,h=this.getServerMethodsByFilterAndTarget(a,c);if(h.length>0)r(h,h[0].methods[0],s,o);else{const i=()=>{if(c&&t.waitTimeoutMs)if(d+=500,h=this.getServerMethodsByFilterAndTarget(a,c),h.length>0){const e=h[0].methods[0];r(h,e,s,o)}else if(d>=t.waitTimeoutMs){r(h,"string"==typeof e?{name:e}:e,s,o)}else setTimeout(i,500)};setTimeout(i,500)}})),i,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,i)=>{e(t,i)}))}serverMethodAdded(e){return this.repo.onServerMethodAdded(((t,i)=>{e({server:t,method:i})}))}serverMethodRemoved(e){return this.repo.onServerMethodRemoved(((t,i)=>{e({server:t,method:i})}))}async invoke(e,t,i,n,s,r){return ge((async()=>{let s;if(s="string"==typeof e?{name:e}:{...e},!s.name)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(t||(t={}),i||(i="best"),"string"==typeof i&&"all"!==i&&"best"!==i&&"skipMine"!==i)return Promise.reject(new Error(`"${i}" is not a valid target. Valid targets are "all" and "best".`));if(n||(n={}),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)),void 0!==n.waitTimeoutMs&&"number"!=typeof n.waitTimeoutMs)return Promise.reject(new Error(`"${n.waitTimeoutMs}" is not a valid number for "waitTimeoutMs" `));if("object"!=typeof t)return Promise.reject(new Error(`The method arguments must be an object. method: ${s.name}`));let r=this.getServerMethodsByFilterAndTarget(s,i);if(0===r.length)try{r=await this.tryToAwaitForMethods(s,i,n)}catch(n){const r={method:{...s,getServers:()=>[],supportsStreaming:!1,objectTypes:s.objectTypes??[],flags:s.flags?.metadata??{}},called_with:t,message:`Can not find a method matching ${JSON.stringify(e)} with server filter ${JSON.stringify(i)}`,executed_by:void 0,returned:void 0,status:void 0};return Promise.reject(r)}const o=n.methodResponseTimeoutMs,a=n,c=r.map((e=>{const i=j(10),n=e.methods[0],s=e.server,r=this.protocol.client.invoke(i,n,t,s,a);return Promise.race([r,me(o,r,{invocationId:i,message:`Invocation timeout (${o} ms) reached for method name: ${n?.name}, target instance: ${JSON.stringify(s.instance)}, options: ${JSON.stringify(a)}`,status:fe.Error})])})),d=await Promise.all(c),h=this.getInvocationResultObj(d,s,t);return d.every((e=>e.status===fe.Error))?Promise.reject(h):h})(),s,r)}getInvocationResultObj(e,t,i){const n=e.filter((e=>e.status===fe.Success)).reduce(((e,n)=>e=[...e,{executed_by:n.instance,returned:n.result,called_with:i,method:t,message:n.message,status:n.status}]),[]),s=e.filter((e=>e.status===fe.Error)).reduce(((e,n)=>e=[...e,{executed_by:n.instance,called_with:i,name:t.name,message:n.message}]),[]),r=e[0];return{method:t,called_with:i,returned:r.result,executed_by:r.instance,all_return_values:n,all_errors:s,message:r.message,status:r.status}}tryToAwaitForMethods(e,t,i){return new Promise(((n,s)=>{if(0===i.waitTimeoutMs)return void s();let r=0;const o=setInterval((()=>{r+=500;const a=this.getServerMethodsByFilterAndTarget(e,t);if(a.length>0)clearInterval(o),n(a);else if(r>=(i.waitTimeoutMs||1e4))return clearInterval(o),void s()}),500)}))}filterByTarget(e,t){if("string"!=typeof e){let i;i=Array.isArray(e)?e:[e];return i.reduce(((e,i)=>{const n=t.filter((e=>this.instanceMatch(i,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((i=>{let n;const s=e[i],r=t[i];switch(i){case"objectTypes":n=(s||[]).every((e=>(r||[]).includes(e)));break;case"flags":n=ue(r||{},s||{});break;default:n=String(s).toLowerCase()===String(r).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 i={};return 1===t.length?i=t[0].methods:t.forEach((e=>{Object.keys(e.methods).forEach((t=>{const n=e.methods[t];i[n.identifier]=n}))})),Object.keys(i).map((e=>i[e]))}getServers(e){const t=this.repo.getServers();return void 0===e?t.map((e=>({server:e,methods:[]}))):t.reduce(((t,i)=>{const n=Object.values(i.methods).filter((t=>this.methodMatch(e,t)));return n.length>0&&t.push({server:i,methods:n}),t}),[])}getServerMethodsByFilterAndTarget(e,t){const i=this.getServers(e);return this.filterByTarget(t,i)}}class we{protocol;repoMethod;subscription;constructor(e,t,i){this.protocol=e,this.repoMethod=t,this.subscription=i}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)}}class ve{protocol;repoMethod;requestContext;arguments;instance;constructor(e,t,i){this.protocol=e,this.repoMethod=t,this.requestContext=i,this.arguments=i.arguments,this.instance=i.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)}}class be{key;protocol;repoMethod;constructor(e,t,i){this.key=e,this.protocol=t,this.repoMethod=i}subscriptions(){return this.protocol.server.getSubscriptionList(this.repoMethod,this.key).map((e=>new we(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 _e{_protocol;_repoMethod;_server;name;constructor(e,t,i){this._protocol=e,this._repoMethod=t,this._server=i,this.name=this._repoMethod.definition.name}branches(e){const t=this._protocol.server.getBranchList(this._repoMethod);return e?t.indexOf(e)>-1?new be(e,this._protocol,this._repoMethod):void 0:t.map((e=>new be(e,this._protocol,this._repoMethod)))}branch(e){return this.branches(e)}subscriptions(){return this._protocol.server.getSubscriptionList(this._repoMethod).map((e=>new we(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}}close(){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.");this._protocol.server.pushData(this._repoMethod,e,t)}updateRepoMethod(e){this._repoMethod=e}}class Ie{protocol;serverRepository;streaming;invocations=0;currentlyUnregistering={};constructor(e,t){this.protocol=e,this.serverRepository=t,this.streaming=new 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 i=new ve(this.protocol,t,e);t.streamCallbacks.subscriptionRequestHandler(i)}handleSubAdded(e,t){if(!t||!t.streamCallbacks||"function"!=typeof t.streamCallbacks.subscriptionAddedHandler)return;const i=new we(this.protocol,t,e);t.streamCallbacks.subscriptionAddedHandler(i)}handleSubRemoved(e,t){if(!t||!t.streamCallbacks||"function"!=typeof t.streamCallbacks.subscriptionRemovedHandler)return;const i=new we(this.protocol,t,e);t.streamCallbacks.subscriptionRemovedHandler(i)}}(e,this),this.protocol.server.onInvoked(this.onMethodInvoked.bind(this))}createStream(e,t,i,n,s){return ge(new Promise(((i,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 r;if(r="string"==typeof e?{name:""+e}:{...e},!r.name)return n(`The “name” property is required for the “streamDefinition” object and must be unique. Stream definition: ${JSON.stringify(r)}`);if(this.serverRepository.getList().some((e=>e.definition.name===r.name)))return n(`A stream with the name "${r.name}" already exists! Please, provide a unique name for the stream.`);r.supportsStreaming=!0,t||(t={}),"function"!=typeof t.subscriptionRequestHandler&&(t.subscriptionRequestHandler=e=>{e.accept()});const o=this.serverRepository.add({definition:r,streamCallbacks:t,protocolState:{}});this.protocol.server.createStream(o).then((()=>{let e;s?(e=s,s.updateRepoMethod(o)):e=new _e(this.protocol,o,this),o.stream=e,i(e)})).catch((e=>{o.repoId&&this.serverRepository.remove(o.repoId),n(e)}))})),i,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("function"!=typeof t)return Promise.reject(`The second parameter must be a callback function. Method: ${"string"==typeof e?e:e.name}`);const i=async(e,i)=>{try{const n=t(e.args,e.instance);if(n&&"function"==typeof n.then){i(void 0,await n)}else i(void 0,n)}catch(e){i(e??"",e??"")}};return i.userCallback=t,this.registerCore(e,i)}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("function"!=typeof t)return Promise.reject(`The second parameter must be a callback function. Method: ${"string"==typeof e?e:e.name}`);const i=async(e,i)=>{try{let n=!1;const s=e=>{n||i(void 0,e),n=!0},r=e=>{n||(e||(e=""),i(e,e)),n=!0},o=t(e.args,e.instance,s,r);o&&"function"==typeof o.then&&o.then(s).catch(r)}catch(e){i(e,void 0)}};return i.userCallbackAsync=t,this.registerCore(e,i)}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("function"==typeof e)return void await this.unregisterWithPredicate(e,t);let i;if(i="string"==typeof e?{name:e}:e,void 0===i.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===i.name&&(e.definition.supportsStreaming||!1)===t));if(!n)return Promise.reject(`Method with a name "${i.name}" does not exist or is not registered by your application!`);await this.removeMethodsOrStreams([n])}async unregisterWithPredicate(e,t){const i=this.serverRepository.getList().filter((t=>e(t.definition))).filter((e=>(e.definition.supportsStreaming||!1)===t));if(!i||0===i.length)return Promise.reject(`Could not find a ${t?"stream":"method"} matching the specified condition!`);await this.removeMethodsOrStreams(i)}removeMethodsOrStreams(e){const t=[];return e.forEach((e=>{const i=this.protocol.server.unregister(e).then((()=>{e.repoId&&this.serverRepository.remove(e.repoId)}));t.push(i),this.addAsCurrentlyUnregistering(e.definition.name,i)})),Promise.all(t)}async addAsCurrentlyUnregistering(e,t){const i=new Promise((e=>setTimeout(e,5e3)));this.currentlyUnregistering[e]=Promise.race([t,i]).then((()=>{delete this.currentlyUnregistering[e]}))}async registerCore(e,t){let i;if(i="string"==typeof e?{name:""+e}:{...e},!i.name)return Promise.reject(`Please, provide a (unique) string value for the “name” property in the “methodDefinition” object: ${JSON.stringify(e)}`);const n=this.currentlyUnregistering[i.name];void 0!==n&&await n;if(this.serverRepository.getList().some((e=>e.definition.name===i.name)))return Promise.reject(`A method with the name "${i.name}" already exists! Please, provide a unique name for the method.`);if(i.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 “${i.name}” to be a stream, please use the “glue.interop.createStream()” method.`);const s=this.serverRepository.add({definition:i,theFunction:t,protocolState:{}});return this.protocol.server.register(s).catch((e=>{throw s?.repoId&&this.serverRepository.remove(s.repoId),e}))}onMethodInvoked(e,t,i){e&&e.theFunction&&e.theFunction(i,((i,n)=>{if(null!=i)if(i.message&&"string"==typeof i.message)i=i.message;else if("string"!=typeof i)try{i=JSON.stringify(i)}catch(e){i=`un-stringifyable error in onMethodInvoked! Top level prop names: ${Object.keys(i)}`}n?("object"!=typeof n||Array.isArray(n))&&(n={_value:n}):n={},this.protocol.server.methodInvocationResult(e,t,i,n)}))}}class Ce{wrapped={};constructor(e,t,i){this.wrapped.getMethods=function(){return e.methodsForInstance(this)},this.wrapped.getStreams=function(){return e.methodsForInstance(this).filter((e=>e.supportsStreaming))},t&&this.refreshWrappedObject(t),i&&(i.loggedIn((()=>{this.refresh(i)})),this.refresh(i))}unwrap(){return this.wrapped}refresh(e){if(!e)return;const t=e?.resolvedIdentity,i=Object.assign({},t??{},{peerId:e?.peerId});this.refreshWrappedObject(i)}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??j(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 Ae=e=>({...e,flags:e.flags.metadata||{}});class Se{logger;API;servers={};myServer;methodsCount={};callbacks=A();constructor(e,t){this.logger=e,this.API=t;const i=this.API.instance.peerId;this.myServer={id:i,methods:{},instance:this.API.instance,wrapper:this.API.unwrappedInstance},this.servers[i]=this.myServer}addServer(e,t){this.logger.debug(`adding server ${t}`);const i=this.servers[t];if(i)return i.id;const n=new Ce(this.API,e),s={id:t,methods:{},instance:n.unwrap(),wrapper:n};return this.servers[t]=s,this.callbacks.execute("onServerAdded",s.instance),t}removeServerById(e,t){const i=this.servers[e];i?(this.logger.debug(`removing server ${e}`),Object.keys(i.methods).forEach((t=>{this.removeServerMethod(e,t)})),delete this.servers[e],this.callbacks.execute("onServerRemoved",i.instance,t)):this.logger.warn(`not aware of server ${e}, my state ${JSON.stringify(Object.keys(this.servers))}`)}addServerMethod(e,t){const i=this.servers[e];if(!i)throw new Error("server does not exists");if(i.methods[t.id])return;const n=this.createMethodIdentifier(t),s=this,r={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:()=>s.getServersByMethod(n)};r.object_types=r.objectTypes,r.display_name=r.displayName,r.version=r.version,i.methods[t.id]=r;const o=Ae(r);return this.methodsCount[n]||(this.methodsCount[n]=0,this.callbacks.execute("onMethodAdded",o)),this.methodsCount[n]=this.methodsCount[n]+1,this.callbacks.execute("onServerMethodAdded",i.instance,o),r}removeServerMethod(e,t){const i=this.servers[e];if(!i)throw new Error("server does not exists");const n=i.methods[t];delete i.methods[t];const s=Ae(n);this.methodsCount[n.identifier]=this.methodsCount[n.identifier]-1,0===this.methodsCount[n.identifier]&&this.callbacks.execute("onMethodRemoved",s),this.callbacks.execute("onServerMethodRemoved",i.instance,s)}getMethods(){return this.extractMethodsFromServers(Object.values(this.servers)).map(Ae)}getServers(){return Object.values(this.servers).map(this.hideServerMethodSystemFlags)}onServerAdded(e){const t=this.callbacks.add("onServerAdded",e),i=this.getServers().map((e=>e.instance));return this.returnUnsubWithDelayedReplay(t,i,e)}onMethodAdded(e){const t=this.callbacks.add("onMethodAdded",e),i=this.getMethods();return this.returnUnsubWithDelayedReplay(t,i,e)}onServerMethodAdded(e){const t=this.callbacks.add("onServerMethodAdded",e);let i=!1;const n=this.getServers();return setTimeout((()=>{n.forEach((t=>{const n=t.methods;Object.keys(n).forEach((s=>{i||e(t.instance,n[s])}))}))}),0),()=>{i=!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??"",i=e.result_signature??"";return(e.name+t+i).toLowerCase()}getServersByMethod(e){const t=[];return Object.values(this.servers).forEach((i=>{Object.values(i.methods).forEach((n=>{n.identifier===e&&t.push(i.instance)}))})),t}returnUnsubWithDelayedReplay(e,t,i){let n=!1;return setTimeout((()=>{t.forEach((e=>{n||i(e)}))}),0),()=>{n=!0,e()}}hideServerMethodSystemFlags(e){const t={};return Object.entries(e.methods).forEach((([e,i])=>{t[e]=Ae(i)})),{...e,methods:t}}extractMethodsFromServers(e){return Object.values(e).reduce(((e,t)=>[...e,...Object.values(t.methods)]),[])}}class xe{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 ke="onSubscriptionRequest",Te="onSubscriptionAdded",Ee="onSubscriptionRemoved";class Pe{session;repository;serverRepository;ERR_URI_SUBSCRIPTION_FAILED="com.tick42.agm.errors.subscription.failure";callbacks=A();nextStreamId=0;constructor(e,t,i){this.session=e,this.repository=t,this.serverRepository=i,e.on("add-interest",(e=>{this.handleAddInterest(e)})),e.on("remove-interest",(e=>{this.handleRemoveInterest(e)}))}acceptRequestOnBranch(e,t,i){if("string"!=typeof i&&(i=""),"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,i),s=e.msg.subscription_id,r={id:s,arguments:e.arguments,instance:e.instance,branchKey:i,streamId:n,subscribeMsg:e.msg};t.protocolState.subscriptionsMap[s]=r,this.session.sendFireAndForget({type:"accepted",subscription_id:s,stream_id:n}),this.callbacks.execute(Te,r,t)}rejectRequest(e,t,i){"string"!=typeof i&&(i=""),this.sendSubscriptionFailed("Subscription rejected by user. "+i,e.msg.subscription_id)}pushData(e,t,i){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 i?i=[i]:(!Array.isArray(i)||i.length<=0)&&(i=[]);e.protocolState.branchKeyToStreamIdMap.filter((e=>!i||0===i.length||i.indexOf(e.key)>=0)).map((e=>e.streamId)).forEach((e=>{const i={type:"publish",stream_id:e,data:t};this.session.sendFireAndForget(i)}))}pushDataToSingle(e,t,i){if("object"!=typeof i)throw new Error("Invalid arguments. Data must be an object.");const n={type:"post",subscription_id:t.id,data:i};this.session.sendFireAndForget(n)}closeSingleSubscription(e,t){e.protocolState.subscriptionsMap&&delete e.protocolState.subscriptionsMap[t.id];const i={type:"drop-subscription",subscription_id:t.id,reason:"Server dropping a single subscription"};this.session.sendFireAndForget(i),t.instance,this.callbacks.execute(Ee,t,e)}closeMultipleSubscriptions(e,t){if("object"!=typeof e||"object"!=typeof e.protocolState.subscriptionsMap)return;if(!e.protocolState.subscriptionsMap)return;const i=e.protocolState.subscriptionsMap;let n=Object.keys(i).map((e=>i[e]));"string"==typeof t&&(n=n.filter((e=>e.branchKey===t))),n.forEach((e=>{delete i[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)}))}getSubscriptionList(e,t){if("object"!=typeof e)return[];let i=[];if(!e.protocolState.subscriptionsMap)return[];const n=e.protocolState.subscriptionsMap,s=Object.keys(n).map((e=>n[e]));return i="string"!=typeof t?s:s.filter((e=>e.branchKey===t)),i}getBranchList(e){if("object"!=typeof e)return[];if(!e.protocolState.subscriptionsMap)return[];const t=e.protocolState.subscriptionsMap,i=Object.keys(t).map((e=>t[e])),n=[];return i.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(Te,e)}onSubRequest(e){this.onSubscriptionLifetimeEvent(ke,e)}onSubRemoved(e){this.onSubscriptionLifetimeEvent(Ee,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 i=t.protocolState.subscriptionsMap[e.subscription_id];delete t.protocolState.subscriptionsMap[e.subscription_id],this.callbacks.execute(Ee,i,t)}onSubscriptionLifetimeEvent(e,t){this.callbacks.add(e,t)}getNextStreamId(){return this.nextStreamId+++""}handleAddInterest(e){const t=this.repository.getServerById(e.caller_id),i=t?.instance??{},n={msg:e,arguments:e.arguments_kv||{},instance:i},s=this.serverRepository.getById(e.method_id);if(void 0!==s)s.protocolState.subscriptionsMap&&s.protocolState.subscriptionsMap[e.subscription_id]?this.sendSubscriptionFailed("A subscription with id "+e.subscription_id+" already exists.",e.subscription_id):this.callbacks.execute(ke,n,s);else{const t="No method with id "+e.method_id+" on this server.";this.sendSubscriptionFailed(t,e.subscription_id)}}sendSubscriptionFailed(e,t){const i={type:"error",reason_uri:this.ERR_URI_SUBSCRIPTION_FAILED,reason:e,request_id:t};this.session.sendFireAndForget(i)}getStreamId(e,t){if("string"!=typeof t&&(t=""),!e.protocolState.branchKeyToStreamIdMap)throw new Error(`streaming ${e.definition.name} method without protocol state`);const i=e.protocolState.branchKeyToStreamIdMap.filter((e=>e.key===t))[0];let n=i?i.streamId:void 0;return"string"==typeof n&&""!==n||(n=this.getNextStreamId(),e.protocolState.branchKeyToStreamIdMap.push({key:t,streamId:n})),n}}class Me{session;clientRepository;serverRepository;logger;callbacks=A();streaming;constructor(e,t,i,n){this.session=e,this.clientRepository=t,this.serverRepository=i,this.logger=n,this.streaming=new Pe(e,t,i),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 i=e.definition,n=Object.assign({},{metadata:i.flags??{}},{streaming:t||!1}),s={type:"register",methods:[{id:e.repoId,name:i.name,display_name:i.displayName,description:i.description,version:i.version,flags:n,object_types:i.objectTypes||i.object_types,input_signature:i.accepts,result_signature:i.returns,restrictions:void 0}]};return this.session.send(s,{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,i,n){let s;s=i||""===i?{type:"error",request_id:t,reason_uri:"agm.errors.client_error",reason:i,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(s)}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,i){this.streaming.pushData(e,t,i)}pushDataToSingle(e,t,i){this.streaming.pushDataToSingle(e,t,i)}closeSingleSubscription(e,t){this.streaming.closeSingleSubscription(e,t)}acceptRequestOnBranch(e,t,i){this.streaming.acceptRequestOnBranch(e,t,i)}rejectRequest(e,t,i){this.streaming.rejectRequest(e,t,i)}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,i=e.caller_id,n=e.method_id,s=e.arguments_kv,r=this.serverRepository.getList().filter((e=>e.repoId===n))[0];if(void 0===r)return;const o=this.clientRepository.getServerById(i)?.instance,a={args:s,instance:o};this.callbacks.execute("onInvoked",r,t,a)}}class Re{repository;subscriptionData;get requestArguments(){return this.subscriptionData.params.arguments||{}}get servers(){return this.subscriptionData.trackedServers.reduce(((e,t)=>{if(t.subscriptionId){const i=this.repository.getServerById(t.serverId)?.instance;i&&e.push(i)}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 Ne{config;cache=[];timeoutIds=[];constructor(e){this.config=e}add(e){const t=j(10);this.cache.push({id:t,element:e});const i=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(i)}flush(){const e=this.cache.map((e=>e.element));return this.timeoutIds.forEach((e=>clearInterval(e))),this.cache=[],this.timeoutIds=[],e}}const je="awaitingAccept",We="subscribed",Oe="Subscription failed.",Fe="ClientInitiated";class De{session;repository;logger;subscriptionsList={};timedCache=new Ne({ELEMENT_TTL_MS:1e4});subscriptionIdToLocalKeyMap={};nextSubLocalKey=0;constructor(e,t,i){this.session=e,this.repository=t,this.logger=i,e.on("subscribed",this.handleSubscribed),e.on("event",this.handleEventData),e.on("subscription-cancelled",this.handleSubscriptionCancelled)}subscribe(e,t,i,n,s,r){if(0===i.length)return void s({method:e,called_with:t.arguments,message:Oe+" No available servers matched the target params."});const o=this.getNextSubscriptionLocalKey(),a=this.registerSubscription(o,e,t,n,s,t.methodResponseTimeout||1e4,r);"object"==typeof a?i.forEach((i=>{const n=i.server.id,s=i.methods.find((t=>t.name===e.name));if(!s)return void this.logger.error(`can not find method ${e.name} for target ${i.server.id}`);a.trackedServers.push({serverId:n,subscriptionId:void 0});const r={type:"subscribe",server_id:n,method_id:s.gatewayId,arguments_kv:t.arguments};this.session.send(r,{serverId:n,subLocalKey:o}).then((e=>this.handleSubscribed(e))).catch((e=>this.handleErrorSubscribing(e)))})):s({method:e,called_with:t.arguments,message:Oe+" 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,i,n,s,r,o){const a={localKey:e,status:je,method:t,params:i,success:n,error:s,trackedServers:[],handlers:{onData:o?.handlers.onData||[],onClosed:o?.handlers.onClosed||[],onConnected:o?.handlers.onConnected||[]},queued:{data:[],closers:[]},timeoutId:void 0,close:()=>this.closeSubscription(e),subscription:o?.subscription};return o||(i.onData&&a.handlers.onData.push(i.onData),i.onClosed&&a.handlers.onClosed.push(i.onClosed),i.onConnected&&a.handlers.onConnected.push(i.onConnected)),this.subscriptionsList[e]=a,a.timeoutId=setTimeout((()=>{if(void 0===this.subscriptionsList[e])return;const n=this.subscriptionsList[e];n.status===je?(s({method:t,called_with:i.arguments,message:Oe+" Subscription attempt timed out after "+r+" ms."}),delete this.subscriptionsList[e]):n.status===We&&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]))}),r),a}handleErrorSubscribing=e=>{const t=e._tag,i=t.subLocalKey,n=this.subscriptionsList[i];if("object"==typeof n&&(n.trackedServers=n.trackedServers.filter((e=>e.serverId!==t.serverId)),n.trackedServers.length<=0)){if(clearTimeout(n.timeoutId),n.status===je){const t="string"==typeof e.reason&&""!==e.reason?' Publisher said "'+e.reason+'".':" No reason given.",i="object"==typeof n.params.arguments?JSON.stringify(n.params.arguments):"{}";n.error({message:"Subscription rejected."+t+" Called with:"+i,called_with:n.params.arguments,method:n.method})}else n.status===We&&this.callOnClosedHandlers(n);delete this.subscriptionsList[i]}};handleSubscribed=e=>{const t=e._tag.subLocalKey,i=this.subscriptionsList[t];if("object"!=typeof i)return;const n=e._tag.serverId,s=i.trackedServers.filter((e=>e.serverId===n))[0];if("object"!=typeof s)return;s.subscriptionId=e.subscription_id,this.subscriptionIdToLocalKeyMap[e.subscription_id]=t;const r=i.status===je;if(i.status=We,r){let e=!1,t=i.subscription;t?(t.setNewSubscription(i),i.success(t),e=!0):(t=new Re(this.repository,i),i.subscription=t,i.success(t));for(const n of i.handlers.onConnected)try{n(t.serverInstance,e)}catch(e){}}};handleEventData=e=>{const t=this.subscriptionIdToLocalKeyMap[e.subscription_id];if(void 0===t)return;const i=this.subscriptionsList[t];if("object"!=typeof i)return;const n=i.trackedServers.filter((t=>t.subscriptionId===e.subscription_id));if(1!==n.length)return;const s=e.oob,r=n[0].serverId,o=this.repository.getServerById(r),a=()=>({data:e.data,server:o?.instance??{},requestArguments:i.params.arguments,message:void 0,private:s}),c=i.handlers.onData,d=i.queued.data;c.length>0?c.forEach((e=>{"function"==typeof e&&e(a())})):d.push(a())};handleSubscriptionCancelled=e=>{const t=this.subscriptionIdToLocalKeyMap[e.subscription_id];if(void 0===t)return;const i=this.subscriptionsList[t];if("object"!=typeof i)return;const n=i.trackedServers.length-1;i.trackedServers=i.trackedServers.filter((t=>t.subscriptionId!==e.subscription_id||(i.queued.closers.push(t.serverId),!1))),i.trackedServers.length===n&&(i.trackedServers.length<=0&&(this.timedCache.add(i),clearTimeout(i.timeoutId),this.callOnClosedHandlers(i),delete this.subscriptionsList[t]),delete this.subscriptionIdToLocalKeyMap[e.subscription_id])};callOnClosedHandlers(e,t){const i=e.queued.closers.length,n=i>0?e.queued.closers[i-1]:null;let s;void 0!==n&&"string"==typeof n&&(s=this.repository.getServerById(n)?.instance??{}),e.handlers.onClosed.forEach((i=>{"function"==typeof i&&i({message:t||"ServerInitiated",requestArguments:e.params.arguments||{},server:s,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:Fe}),delete this.subscriptionIdToLocalKeyMap[e.subscriptionId])})),t.trackedServers=[],this.callOnClosedHandlers(t,Fe),delete this.subscriptionsList[e])}}class Le{session;repository;logger;streaming;constructor(e,t,i){this.session=e,this.repository=t,this.logger=i,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 De(e,t,i)}subscribe(e,t,i,n,s,r){this.streaming.subscribe(e,t,i,n,s,r)}invoke(e,t,i,n){const s=n.id,r={type:"call",server_id:s,method_id:t.gatewayId,arguments_kv:i};return this.session.send(r,{invocationId:e,serverId:s}).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,i=e.identity,n=!e.meta||e.meta.local,s=Number(i.process),r={machine:i.machine,pid:isNaN(s)?i.process:s,instance:i.instance,application:i.application,applicationName:i.applicationName,environment:i.environment,region:i.region,user:i.user,windowId:i.windowId,peerId:t,api:i.api,isLocal:n};this.repository.addServer(r,t)}handlePeerRemoved(e){const t=e.removed_id,i=e.reason;this.repository.removeServerById(t,i)}handleMethodsAddedMessage(e){const t=e.server_id;e.methods.forEach((e=>{this.repository.addServerMethod(t,e)}))}handleMethodsRemovedMessage(e){const t=e.server_id,i=e.methods,n=this.repository.getServerById(t);if(n){Object.keys(n.methods).forEach((e=>{const s=n.methods[e];i.indexOf(s.gatewayId)>-1&&this.repository.removeServerMethod(t,e)}))}}handleResultMessage(e){const t=e._tag.invocationId,i=e.result,n=e._tag.serverId,s=this.repository.getServerById(n);return{invocationId:t,result:i,instance:s?.instance,status:fe.Success,message:""}}handleInvocationError(e){if(this.logger.debug(`handle invocation error ${JSON.stringify(e)}`),"_tag"in e){const t=e._tag.invocationId,i=e._tag.serverId,n=this.repository.getServerById(i),s=e.reason;return{invocationId:t,result:e.context,instance:n?.instance,status:fe.Error,message:s}}return{invocationId:"",message:e.message,status:fe.Error,error:e}}}function $e(e,t,i,n,s,r){const o=s.logger.subLogger("gw3-protocol");let a;const c=new Promise((e=>{a=e})),d=t.domain("agm",["subscribed"]),h=new Me(d,i,n,o.subLogger("server")),u=new Le(d,i,o.subLogger("client"));return d.onJoined((s=>{i.addServer(e,t.peerId),s?async function(){o.info("reconnected - will replay registered methods and subscriptions"),u.drainSubscriptionsCache().forEach((e=>{const t=e.method,i=Object.assign({},e.params);o.info(`trying to soft-re-subscribe to method ${t.name}, with params: ${JSON.stringify(i)}`),r.client.subscribe(t,i,void 0,void 0,e).then((()=>o.info(`soft-subscribing to method ${t.name} DONE`))).catch((e=>o.warn(`subscribing to method ${t.name} failed: ${JSON.stringify(e)}}`)))}));const e=[],t=u.drainSubscriptions();for(const i of t){const t=i.method,n=Object.assign({},i.params);o.info(`trying to re-subscribe to method ${t.name}, with params: ${JSON.stringify(n)}`),e.push(r.client.subscribe(t,n,void 0,void 0,i).then((()=>o.info(`subscribing to method ${t.name} DONE`))))}const i=n.getList();n.reset();for(const t of i){const i=t.definition;t.stream?e.push(r.server.createStream(i,t.streamCallbacks,void 0,void 0,t.stream).then((()=>o.info(`subscribing to method ${i.name} DONE`))).catch((()=>o.warn(`subscribing to method ${i.name} FAILED`)))):t?.theFunction?.userCallback?e.push(r.register(i,t.theFunction.userCallback).then((()=>o.info(`registering method ${i.name} DONE`))).catch((()=>o.warn(`registering method ${i.name} FAILED`)))):t?.theFunction?.userCallbackAsync&&e.push(r.registerAsync(i,t.theFunction.userCallbackAsync).then((()=>o.info(`registering method ${i.name} DONE`))).catch((()=>o.warn(`registering method ${i.name} FAILED`))))}await Promise.all(e),o.info("Interop is re-announced")}().then((()=>t.setLibReAnnounced({name:"interop"}))).catch((e=>o.warn(`Error while re-announcing interop: ${JSON.stringify(e)}`))):a&&(a({client:u,server:h}),a=void 0)})),d.onLeft((()=>{i.reset()})),d.join(),c}class Ge{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 i;if("number"!=typeof e.methodResponseTimeout&&(e.methodResponseTimeout=3e4),"number"!=typeof e.waitTimeoutMs&&(e.waitTimeoutMs=3e4),this.unwrappedInstance=new Ce(this,void 0,t),this.instance=this.unwrappedInstance.unwrap(),this.clientRepository=new Se(e.logger.subLogger("cRep"),this),this.serverRepository=new xe,3!==t.protocolVersion)throw new Error(`protocol ${t.protocolVersion} not supported`);i=$e(this.instance,t,this.clientRepository,this.serverRepository,e,this),this.readyPromise=i.then((t=>(this.protocol=t,this.client=new ye(this.protocol,this.clientRepository,this.instance,e),this.server=new Ie(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,i,n){return this.client.subscribe(e,t,i,n)}createStream(e,t,i,n){return this.server.createStream(e,t,i,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,i,n,s,r){return this.client.invoke(e,t,i,n,s,r)}waitForMethod(e){const t=new T,i=this.client.methodAdded((n=>{n.name===e&&(i(),t.resolve(n))}));return t.promise}}const Be=["subscribed","success"];class He{connection;logger;peerId;session;subscriptions;readyPromise;constructor(e,t){this.connection=e,this.logger=t,this.peerId=e.peerId,this.subscriptions=[],this.session=e.domain("bus",Be),this.readyPromise=this.session.join(),this.readyPromise.then((()=>{this.watchOnEvent()}))}ready(){return this.readyPromise}publish=(e,t,i)=>{const{routingKey:n,target:s}=i||{},r=this.removeEmptyValues({type:"publish",topic:e,data:t,peer_id:this.peerId,routing_key:n,target_identity:s});this.session.send(r)};subscribe=(e,t,i)=>new Promise(((n,s)=>{const{routingKey:r,target:o}=i||{},a=this.removeEmptyValues({type:"subscribe",topic:e,peer_id:this.peerId,routing_key:r,source:o});this.session.send(a).then((i=>{const{subscription_id:s}=i;this.subscriptions.push({subscription_id:s,topic:e,callback:t,source:o}),n({unsubscribe:()=>(this.session.send({type:"unsubscribe",subscription_id:s,peer_id:this.peerId}),this.subscriptions=this.subscriptions.filter((e=>e.subscription_id!==s)),Promise.resolve())})})).catch((e=>s(e)))}));watchOnEvent=()=>{this.session.on("event",(e=>{const{data:t,subscription_id:i}=e,n=e["publisher-identity"],s=this.subscriptions.find((e=>e.subscription_id===i));s&&(s.source?this.keysMatch(s.source,n)&&s.callback(t,s.topic,n):s.callback(t,s.topic,n))}))};removeEmptyValues(e){const t={};return Object.keys(e).forEach((i=>{void 0!==e[i]&&null!==e[i]&&(t[i]=e[i])})),t}keysMatch(e,t){const i=Object.keys(e);let n=!0;return i.forEach((i=>{e[i]!==t[i]&&(n=!1)})),n}}const Ue=(e,t)=>{const i="object"==typeof window?window.iodesktop??window.glue42gd:void 0,n="object"==typeof window?window.gdPreloadPromise??Promise.resolve():Promise.resolve(),s=P("glue"),r=function(e,t,i){let n;if(k.isNode()){const e=process.env._GD_STARTING_CONTEXT_;if(e)try{n=JSON.parse(e)}catch{}}function s(){if(e.application)return e.application;if(i)return i.applicationName;if("undefined"!=typeof window&&void 0!==window.glue42electron)return window.glue42electron.application;const t=j(10);return k.isNode()?n?n.applicationConfig.name:"NodeJS"+t:"undefined"!=typeof window&&"undefined"!=typeof document?document.title+` (${t})`:t}const r=function(){const r=e.gateway,o=r?.protocolVersion??3,a=r?.reconnectInterval,c=r?.reconnectAttempts;let d=r?.ws;const h=r?.sharedWorker,u=r?.inproc,l=r?.webPlatform??void 0;let p,g,m,f,y;i&&(d=i.gwURL),k.isNode()&&n&&n.gwURL&&(d=n.gwURL),d||h||u||(d="ws://localhost:8385");const w=s();let v=w;void 0!==i?(g=i.windowId,m=i.pid,i.env&&(f=i.env.env,y=i.env.region),v=i.application??"glue-app",p=i.appInstanceId):k.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,v=window?.glue42electron.application??"glue-app",p=window?.glue42electron.instanceId);const b=e.gateway?.replaySpecs??[];b.push(te);let _={application:v,applicationName:w,windowId:g,instance:p,process:m,region:y,environment:f,api:t.version||ie};return e.identity&&(_=Object.assign(_,e.identity)),{identity:_,reconnectInterval:a,ws:d,sharedWorker:h,webPlatform:l,inproc:u,protocolVersion:o,reconnectAttempts:c,replaySpecs:b}}();let o=s();if("undefined"!=typeof window){const e=window,t=e.htmlContainer?`${e.htmlContainer.containerName}.${e.htmlContainer.application}`:e?.glue42gd?.application;t&&(o=t)}return{bus:e.bus??!1,application:o,auth:"string"==typeof e.auth?{token:e.auth}:e.auth?e.auth:k.isNode()&&n&&n.gwToken?{gatewayToken:n.gwToken}:e.gateway?.webPlatform||e.gateway?.inproc||e.gateway?.sharedWorker?{username:"glue42",password:"glue42"}:void 0,logger:function(){let t=e.logger;const n="warn";let s;return t||(t=n),i&&(s=i.consoleLogLevel),"string"==typeof t?{console:s??t,publish:n}:{console:s??t.console??n,publish:t.publish??n}}(),connection:r,metrics:e.metrics??!0,contexts:void 0===e.contexts||"boolean"==typeof e.contexts&&e.contexts?{reAnnounceKnownContexts:!0}:"object"==typeof e.contexts&&Object.assign({},{reAnnounceKnownContexts:!0},e.contexts),version:t.version||ie,libs:t.libs??[],customLogger:e.customLogger}}(e=e||{},t=t||{},i);let o,a,c,d,h,u,l;const p={};function g(e,t,i){l=c.canPublish("trace"),l&&c.trace(`registering ${e} module`);const n=()=>{t.initTime=i.stop(),t.initEndTime=i.endTime,t.marks=i.marks,l&&c.trace(`${e} is ready - ${i.endTime-i.startTime}`)};t.initStartTime=i.startTime,t.ready?t.ready().then((()=>{n()})):n(),Array.isArray(e)||(e=[e]),e.forEach((e=>{p[e]=t,Ue[e]=t}))}function m(){const e=P("metrics"),t=r.metrics,n=i?.getMetricsPublishingEnabled,s=r.connection.identity,a=n||(()=>!0),h=("boolean"!=typeof t&&t.disableAutoAppSystem)??!1;return d=b({connection:t?o:void 0,logger:c.subLogger("metrics"),canUpdateMetric:a,system:"Glue42",service:s?.service??i?.applicationName??r.application,instance:s?.instance??s?.windowId??j(10),disableAutoAppSystem:h,pagePerformanceMetrics:"boolean"!=typeof t?t?.pagePerformanceMetrics:void 0}),g("metrics",d,e),Promise.resolve()}function f(){const e=P("interop"),t={connection:o,logger:c.subLogger("interop")};return a=new Ge(t),G.Interop=a,g(["interop","agm"],a,e),Promise.resolve()}function y(){const e=r.activities&&3===o.protocolVersion;if(r.contexts||e){const e=P("contexts");return h=new pe({connection:o,logger:c.subLogger("contexts"),trackAllContexts:"object"==typeof r.contexts&&r.contexts.trackAllContexts,reAnnounceKnownContexts:"object"==typeof r.contexts&&r.contexts.reAnnounceKnownContexts}),g("contexts",h,e),h}{const e=o.replayer;e&&e.drain(te.name)}}async function w(){if(!r.bus)return Promise.resolve();const e=P("bus");return u=new He(o,c.subLogger("bus")),g("bus",u,e),Promise.resolve()}function v(e){try{return e.forEach((e=>{!function(e,t){const i=P(e),n=t(p);n&&g(e,n,i)}(e.name,e.create)})),Promise.resolve()}catch(e){return Promise.reject(e)}}return n.then((function(){const e=P("logger");return c=new G(`${r.connection.identity?.application}`,void 0,r.customLogger),c.consoleLevel(r.logger.console),c.publishLevel(r.logger.publish),c.canPublish("debug")&&c.debug("initializing glue..."),g("logger",c,e),Promise.resolve(void 0)})).then((function(){const e=P("connection");o=new L(r.connection,c.subLogger("connection"));let t=Promise.resolve(r.auth);return r.connection&&!r.auth&&(i?t=i.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 i;if(e.mark("auth-promise-resolved"),"[object Object]"!==Object.prototype.toString.call(t))throw new Error("Invalid auth object - "+JSON.stringify(t));return i=t,o.login(i)})).then((()=>(g("connection",o,e),r))).catch((e=>{throw o&&o.logout(),e}))})).then((()=>Promise.all([m(),f(),y(),w()]))).then((()=>a.readyPromise)).then((()=>async function(){const t="T42.ACS.RegisterInstance";if(k.isNode()&&void 0===process.env._GD_STARTING_CONTEXT_&&void 0!==e?.application&&a.methods({name:t}).length>0)try{await a.invoke(t,{appName:e?.application,pid:process.pid})}catch(e){const t=e;c.error(`Cannot register as an instance: ${JSON.stringify(t.message)}`)}}())).then((()=>v(r.libs||[]))).then((function(){const e=Object.keys(p).map((e=>{const t=p[e];return t.ready?t.ready():Promise.resolve()}));return Promise.all(e)})).then((function(){const n={coreVersion:ie,version:r.version};s.stop();const l={feedback:e=>{a&&a.invoke("T42.ACS.Feedback",e,"best")},info:n,logger:c,interop:a,agm:a,connection:o,metrics:d,contexts:h,bus:u,version:r.version,userConfig:e,done:()=>(c?.info("done called by user..."),o.logout())};if(l.performance={get glueVer(){return r.version},get glueConfig(){return JSON.stringify(e)},get browser(){return window.performance.timing.toJSON()},get memory(){return window.performance.memory},get initTimes(){const e=E;return Object.keys(e).map((t=>{const i=e[t];return{name:t,duration:i.endTime-i.startTime,marks:i.marks,startTime:i.startTime,endTime:i.endTime}}))}},Object.keys(p).forEach((e=>{const t=p[e];l[e]=t})),l.config={},Object.keys(r).forEach((e=>{l.config[e]=r[e]})),t&&t.extOptions&&Object.keys(t.extOptions).forEach((e=>{l.config[e]=t?.extOptions[e]})),t?.enrichGlue&&t.enrichGlue(l),i&&i.updatePerfData&&i.updatePerfData(l.performance),l.agm){const e=(e,t,i)=>function(){return l.logger.warn(`glue.js - 'glue.agm.${t}' method is deprecated, use 'glue.interop.${i}' instead.`),e.apply(l.agm,arguments)},t=l.agm;t.method_added=e(l.agm.methodAdded,"method_added","methodAdded"),t.method_removed=e(l.agm.methodRemoved,"method_removed","methodRemoved"),t.server_added=e(l.agm.serverAdded,"server_added","serverAdded"),t.server_method_aded=e(l.agm.serverMethodAdded,"server_method_aded","serverMethodAdded"),t.server_method_removed=e(l.agm.serverMethodRemoved,"server_method_removed","serverMethodRemoved")}return l})).catch((e=>Promise.reject({err:e,libs:p})))};"undefined"!=typeof window&&(window.IOConnectCore=Ue),Ue.version=ie,Ue.default=Ue;class qe{constructor(e){this._id=e}get id(){return this._id}_update(e){if(e._id!==this._id)throw Error("Can not update from entity with different id.");this._updateCore(e)}_updateCore(e){}_beforeDelete(e){}}function Je(e){return"number"==typeof e}function Ve(e){return"string"==typeof e}function ze(e){return"object"==typeof e&&null!==e}function Ke(e){return Array.isArray?Array.isArray(e):"[object Array]"===toString.call(e)}function Qe(e){return void 0===e}function Ze(e){return null==e}function Xe(e){return"string"!=typeof e||!e||0===e.length||/^\s*$/.test(e)}function Ye(e){return!0===e||!1===e||"[object Boolean]"===toString.call(e)}function et(e){return!!(e&&e.constructor&&e.call&&e.apply)}function tt(e,t){void 0!==e&&t(e)}class it extends qe{constructor(e,t,i,n){super(e),this._name=e,this._description=n,this._ownerWindow=t,this._helperWindows=i||[]}get name(){return this._name}get description(){return this._description}get helperWindows(){return this._helperWindows.map((e=>this.covertToWindowDef(e)))}get ownerWindow(){return this.covertToWindowDef(this._ownerWindow)}initiate(e,t,i){return this._manager.initiate(this._name,e,t,i)}_updateCore(e){super._updateCore(e),tt(e._description,(e=>this._description=e)),tt(e._ownerWindow,(e=>this._ownerWindow=e)),tt(e._helperWindows,(e=>this._helperWindows=e))}covertToWindowDef(e){var t,i;return{type:null===(t=null==e?void 0:e.id)||void 0===t?void 0:t.type,name:null===(i=null==e?void 0:e.id)||void 0===i?void 0:i.name}}}class nt extends qe{constructor(e,t){super(e),this._name=e,this._appByWindowTypeGetter=t}get name(){return this._name}get config(){return this._appByWindowTypeGetter(this._name)}get windows(){return this._manager.getWindows({type:this._name})}create(e,t){const i=Object.assign({type:this.name,name:this.name,isIndependent:!1},t);return this._manager.createWindow(e,i)}}class st{constructor(e,t){this.entity=e,this.context=t}}class rt{constructor(e){this.type=e}}class ot extends rt{constructor(e,t){super(ct.StatusChange),this.newStatus=e,this.oldStatus=t}}class at extends rt{constructor(e,t,i){super(ct.ActivityContextChange),this.context="string"==typeof e?JSON.parse(e):e,this.updated=t,this.removed=i}}class ct{}ct.Added="added",ct.Removed="removed",ct.Updated="updated",ct.Closed="closed",ct.StatusChange="statusChange",ct.ActivityContextChange="activityContextUpdate",ct.ActivityWindowEvent="activityWindowEvent",ct.ActivityWindowJoinedActivity="joined",ct.ActivityWindowLeftActivity="left";class dt{}dt.Created="created",dt.Started="started",dt.Destroyed="destroyed";class ht{constructor(e){this._activity=e}register(e,t){this._ensureHasAgm(),ht.AGM.register(e,t)}servers(){return this._ensureHasAgm(),Ze(this._activity)?[]:this._activity.windows.map((e=>e.instance))}methods(){if(this._ensureHasAgm(),Ze(this._activity))return[];const e=this._activity.windows,t=[],i=[];return e.forEach((e=>{this.methodsForWindow(e).forEach((e=>{-1===t.indexOf(e.name)&&(t.push(e.name),i.push(e))}))})),i}methodsForWindow(e){return this._ensureHasAgm(),e.instance?ht.AGM.methodsForInstance(e.instance):[]}invoke(e,t,i,n,s,r){this._ensureHasAgm();const o=this.servers();if(Ze(i)&&(i="activity.all"),Ve(i))if("activity.all"===i);else{if("activity.best"!==i){if("all"===i||"best"===i)return function(e,t,i){if("function"!=typeof t&&"function"!=typeof i)return e;"function"!=typeof t?t=()=>{}:"function"!=typeof i&&(i=()=>{}),e.then(t,i)}(ht.AGM.invoke(e,t,i,n),s,r);throw new Error("Invalid invoke target "+i)}{const t=o.filter((t=>ht.AGM.methodsForInstance(t).filter((t=>t.name===e)).length>0));t.length>0&&t[0]}}else if(Ke(i)){if(i.length>=0){const e=i[0];if(this._isInstance(e))i.map((e=>e));else{if(!this._isActivityWindow(e))throw new Error("Unknown target object");i.map((e=>e.instance))}}}else if(this._isInstance(i));else{if(!this._isActivityWindow(i))throw new Error("Unknown target object");i.instance}throw new Error("Not implemented")}unregister(e){return this._ensureHasAgm(),ht.AGM.unregister(e)}createStream(e,t,i){this._ensureHasAgm(),ht.AGM.createStream(e,{subscriptionAddedHandler:t,subscriptionRemovedHandler:i,subscriptionRequestHandler:void 0})}subscribe(e,t,i){return this._ensureHasAgm(),ht.AGM.subscribe(e,t)}_ensureHasAgm(){if(Ze(ht.AGM))throw new Error("Agm should be configured to be used in activity")}_isInstance(e){return void 0!==e.application}_isActivityWindow(e){return void 0!==e.instance}}class ut{constructor(e,t,i){this._manager=e,this._ownerActivityId=t,this._state=i}get ownerId(){return this._state.ownerId}get windowIds(){return this._state.windowIds}get frameColor(){return this._state.frameColor}get context(){return this._state.context}get tag(){return this._state.tag}detach(e){e=e||{};const t={};return Object.keys(this._state).forEach((e=>{t[e]=this._state[e]})),t.context=e.context||t.context,t.frameColor=e.frameColor||t.frameColor,this._manager.detachActivities(this._ownerActivityId,t)}}const lt=e=>{setTimeout(e,0)};function pt(e,t){if(!et(t))return e;e.then((e=>{lt((()=>{t(null,e)}))}),(e=>{lt((()=>{t(e,null)}))}))}class gt extends qe{constructor(e,t,i,n,s){super(e),this._id=e,this._actType=t,this._status=i,this._context=n,this._ownerId=s,this._agm=new ht(this)}get type(){if(this._manager)return this._manager.getActivityType(this._actType)}get context(){return this._context}get status(){return this._status}get owner(){return this._ownerId?this._manager.getWindows({id:this._ownerId})[0]:null}get windows(){return this._manager.getWindows({activityId:this._id})}get agm(){return this._agm}addWindow(e,t){return this._manager.addWindowToActivity(this,e,t)}createWindow(e,t){return this._manager.createWindow(this,e,t)}createStackedWindows(e,t,i){return this._manager.createStackedWindows(this,e,t,i)}leave(e,t){return this._manager.leaveWindowFromActivity(this,e,t)}getWindowsByType(e){const t={activityId:this._id,type:e};return this._manager.getWindows(t)}setContext(e,t){return this._manager.setActivityContext(this,e,t)}updateContext(e,t){return this._manager.updateActivityContext(this,e,t)}onStatusChange(e){return this._manager.subscribeActivityEvents(((t,i,n)=>{t.id===this.id&&e(t,i,n)}))}onWindowEvent(e){return this._manager.subscribeWindowEvents(((t,i,n)=>{t.id===this.id&&e(t,i,n)}))}onContextChanged(e){this._manager.subscribeActivityContextChanged(((t,i,n,s)=>{t.id===this.id&&e(i,n,s,t)}));try{e(this.context,this.context,[],this)}catch(e){return}}stop(){this._manager.stopActivity(this)}clone(e){return this._manager.clone(this,e)}attach(e,t){let i;return i="string"==typeof e?e:e.id,this._manager.attachActivities(i,this.id,t)}onActivityAttached(e){this._manager.subscribeActivitiesAttached(((t,i,n)=>{t===this._id&&e(n)}))}onDetached(e){this._manager.subscribeActivitiesDetached(((t,i,n)=>{i.id===this._id&&e(t,n)}))}_updateCore(e){super._updateCore(e),tt(e._actType,(e=>this._actType=e)),tt(e._context,(e=>this._context=e)),tt(e._ownerId,(e=>this._ownerId=e)),!e._status||this._status&&this._status.state===e._status.state||(this._status=e._status)}_updateDescriptors(e){this._attached=e.map((e=>new ut(this._manager,this._id,e)))}get attached(){return this._attached}setFrameColor(e,t){return pt(new Promise(((t,i)=>{let n=this.windows.length;0===n&&t(this),this.windows.forEach((i=>{i.underlyingWindow.setFrameColor(e,(()=>{n--,n<=0&&t(this)}))})),setTimeout((()=>{n>0&&i(this.id+" - timed out waiting for setFrameColor with"+e)}),5e3)})),t)}getFrameColor(){return this.windows&&0!==this.windows.length?this.windows[0].underlyingWindow.frameColor:""}}class mt{}mt.Trace="trace",mt.Debug="debug",mt.Info="info",mt.Warn="warn",mt.Error="error";class ft{static GetNamed(e){return new ft(e)}static Get(e){return new ft(ft.GetTypeName(e))}constructor(e){this._name=e,Ze(ft.GlueLogger)||(this._glueLogger=ft.GlueLogger.subLogger(e))}trace(e){Ze(this._glueLogger)?ft.Level===mt.Trace&&console.info(this._getMessage(e,mt.Trace)):this._glueLogger.trace(e)}debug(e){Ze(this._glueLogger)?ft.Level!==mt.Debug&&ft.Level!==mt.Trace||console.info(this._getMessage(e,mt.Debug)):this._glueLogger.debug(e)}info(e){Ze(this._glueLogger)?ft.Level!==mt.Debug&&ft.Level!==mt.Trace&&ft.Level!==mt.Info||console.info(this._getMessage(e,mt.Info)):this._glueLogger.info(e)}warn(e){Ze(this._glueLogger)?ft.Level!==mt.Debug&&ft.Level!==mt.Trace&&ft.Level!==mt.Info&&ft.Level!==mt.Warn||console.info(this._getMessage(e,mt.Info)):this._glueLogger.warn(e)}error(e){Ze(this._glueLogger)?(console.error(this._getMessage(e,mt.Error)),console.trace()):this._glueLogger.error(e)}_getMessage(e,t){return"["+t+"] "+this._name+" - "+e}static GetTypeName(e){const t=/function (.{1,})\(/.exec(e.constructor.toString());return t&&t.length>1?t[1]:""}}ft.Level=mt.Info;class yt extends qe{constructor(e,t,i,n,s,r,o,a){super(e),this._logger=ft.Get("window"),this._type=i,this._activityId=n,this._name=t,this._instance=s,this._isIndependent=r,this._windowGetter=o,this._hcWindowId=a}getBounds(){return this._manager.getWindowBounds(this.id)}get name(){return this._name}get isIndependent(){return this._isIndependent}get type(){if(this._manager)return this._manager.getWindowType(this._type)}get activity(){if(!Qe(this._activityId))return this._manager.getActivityById(this._activityId)}get isOwner(){const e=this.activity;return!Qe(e)&&e.owner.id===this.id}setVisible(e,t){return this._manager.setWindowVisibility(this.id,e)}activate(e){return this._manager.activateWindow(this.id,e)}setBounds(e,t){return this._manager.setWindowBounds(this.id,e,t)}close(){return this._manager.closeWindow(this.id)}get instance(){return this._instance}get underlyingWindow(){const e=this._windowGetter();return e||{id:this._hcWindowId}}onActivityJoined(e){this._subscribeForActivityWindowEvent(ct.ActivityWindowJoinedActivity,e)}onActivityRemoved(e){this._subscribeForActivityWindowEvent(ct.ActivityWindowLeftActivity,e)}_updateCore(e){tt(e._activityId,(e=>this._activityId=e)),tt(e._isIndependent,(e=>this._isIndependent=e)),tt(e._hcWindowId,(e=>this._hcWindowId=e)),tt(e._type,(e=>this._type=e)),tt(e._name,(e=>this._name=e)),Ze(e._instance)||(this._instance=e._instance)}_subscribeForActivityWindowEvent(e,t){this._manager.subscribeWindowEvents(((i,n,s)=>{n.id===this.id&&s===e&&t(i)}))}_beforeDelete(e){this._hcWindowId=e._hcWindowId}}class wt{constructor(e,t,i){this.state=e,this.message=t,this.time=i}getState(){return this.state}getMessage(){return this.message}getTime(){return this.time}}const vt="error",bt="add-types",_t="created",It="destroyed",Ct="initiated",At="joined",St="activity-joined",xt="left",kt="owner-changed",Tt="add-peer-factories",Et="peer-factories-added",Pt="peer-factories-removed",Mt="peer-created";class Rt{static activityTypeGwMessageEntityToActivityType(e,t){const i=e=>new nt(e,void 0);return new it(e.name,e.owner_type&&i(e.owner_type),e.helper_types&&e.helper_types.map(i),t)}static peerFactoryGwMessageEntityToWindowType(e){return new nt(e.peer_type,(e=>{}))}static activityGwMessageToActivity(e,t){const i=void 0!==e.owner?e.owner.peer_id:e.owner_id;return new gt(e.activity_id,e.activity_type,t,e.context_snapshot,i)}static activityToActivityStatusChangeEvent(e){return new st(e,new ot(e.status,void 0))}constructor(e){if(this._activityChangeCallbacks=[],this._activityTypeStatusChangeCallbacks=[],this._activityWindowChangeCallbacks=[],this._windowTypeStatusChangeCallbacks=[],this._peerIdAndFactoryIdToPeerType={},this._peerFactoriesRegisteredByUs={},this._gw3Subscriptions=[],this._contextSubscriptions={},this._activityTypesInitiatedFromMe={},this._config=e,this._connection=e.connection,this._logger=e.logger,this._contexts=e.contexts,this._windows=e.windows,this._sessionJoinedPromise=new Promise((e=>{this._sessionJoinedPromiseResolve=e})),this._activityJoinedPromise=new Promise((e=>{this._activityJoinedPromiseResolve=e})),this._config.activityId||this._activityJoinedPromiseResolve({}),this._gw3Session=this._connection.domain("activity",["joined","initiated","peer-created","token"]),"undefined"!=typeof window){const e=window.glue42gd;e&&e.activityInfo&&("function"==typeof e.addRefreshHandler&&e.addRefreshHandler(((t,i)=>{this._gw3Session.send({type:"reload"}).then((n=>{if(n.token){try{e.setGWToken(n.token)}catch(e){return void i(e.message||e)}t()}else i("Expected gateway token for refreshing.")}),i)})),e&&"function"==typeof e.addWillNavigateHandler&&e.addWillNavigateHandler(((t,i)=>{this._gw3Session.send({type:"reload"}).then((n=>{if(n.token){try{e.setGWToken(n.token)}catch(e){return void i(e.message||e)}t()}else i("Expected gateway token for refreshing.")}),i)})))}}get bridgeType(){return"GW3"}init(){this.forwardActivityTypeMessagesToStatusEventHandlers(),this.subscribe(_t,this.handleActivityCreatedMessage),this.subscribe(It,this.handleActivityDestroyedMessage),this.forwardActivityMessagesToStatusEventHandlers(),this.forwardActivityCreatedAndJoinedActivityToActivityWindowEventHandlers(),this.forwardPeerFactoryMessagesToStatusEventHandlers(),this.forwardPeerFactoryMessagesToPeerFactoryRequests(),this.subscribe(Et,this.handlePeerFactoriesAdded),this.subscribe(Pt,this.handlePeerFactoriesRemoved),this.forwardActivityWindowMessagesToEventHandlers(),this.subscribe("dispose-peer",(()=>{if("dispose"!==this._config.disposeRequestHandling){if("exit"===this._config.disposeRequestHandling){if(this._windows&&void 0!==this._windows.my())return void this._windows.my().close();if("undefined"!=typeof window&&"function"==typeof window.close)return void window.close();if("undefined"!=typeof process&&"function"==typeof process.exit)return void process.exit()}}else this.dispose()})),this._gw3Session.onJoined((()=>{"trackMyOnly"===this._config.mode||"trackMyTypeAndInitiatedFromMe"===this._config.mode?this._sessionJoinedPromiseResolve(this):this._gw3Session.send({type:"subscribe",activity_types:"trackAll"===this._config.mode?[]:"trackTypes"===this._config.mode?this._config.typesToTrack:[]}).then((()=>{this._sessionJoinedPromiseResolve(this)}))})),this._gw3Session.join()}dispose(){this._gw3Subscriptions.forEach((e=>e&&this._connection.off(e))),this._gw3Subscriptions.length=0}ready(){return Promise.all([this._sessionJoinedPromise,this._activityJoinedPromise])}initReady(){return this._sessionJoinedPromise}onActivityTypeStatusChange(e){this._activityTypeStatusChangeCallbacks.push(e)}registerActivityType(e,t,i,n,s){const r={};r.name=e;const o=e=>({type:e.type,name:e.name,configuration:e});return r.owner_type=o(t),r.helper_types=i.map(o),this._gw3Session.send({type:bt,types:[r]}).then((()=>{const e=Rt.activityTypeGwMessageEntityToActivityType(r,s);return this.invokeCallbacks(this._activityTypeStatusChangeCallbacks,new st(e,new rt(ct.Added)),bt),e}))}unregisterActivityType(e){return this._gw3Session.send({type:"remove-types",types:[e]}).then((()=>{const t=new it(e,void 0,void 0,void 0);this.invokeCallbacks(this._activityTypeStatusChangeCallbacks,new st(t,new rt(ct.Removed)),bt)}))}onWindowTypeStatusChange(e){this._windowTypeStatusChangeCallbacks.push(e)}registerWindowFactory(e,t,i){if(this._peerFactoriesRegisteredByUs[e])return Promise.reject(new Error(`Factory for windowType ${e} already registered.`));this._peerFactoriesRegisteredByUs[e]=t;const n={id:e,peer_type:e,configuration:i};return this._gw3Session.send({type:Tt,factories:[n]}).then((()=>{this.invokeCallbacks(this._windowTypeStatusChangeCallbacks,new st(Rt.peerFactoryGwMessageEntityToWindowType(n),new rt(ct.Added)),Tt)})).catch((()=>{delete this._peerFactoriesRegisteredByUs[e]}))}unregisterWindowFactory(e){return this._peerFactoriesRegisteredByUs[e]?(delete this._peerFactoriesRegisteredByUs[e],this._gw3Session.send({type:"remove-peer-factories",factory_ids:[e]}).then((()=>{this.invokeCallbacks(this._windowTypeStatusChangeCallbacks,new st(new nt(e,void 0),new rt(ct.Removed)),Tt)}))):Promise.reject(new Error(`Factory for windowType ${e} not registered.`))}onActivityStatusChange(e){this._activityChangeCallbacks.push(e)}initiateActivity(e,t,i){const n={type:"create",activity_type:e,initial_context:t};return this.isOverrideTypeDefinition(i)?n.types_override={owner_type:{type:i.owner.type,name:i.owner.name,configuration:i.owner},helper_types:i.helpers&&i.helpers.map((e=>({type:e.type,name:e.name,configuration:e})))}:n.configuration=i&&i.map((e=>({type:e.type,name:e.name,configuration:e}))),this.sendCreateAndMapResultingMessagesToPromise(n,Ct,((e,t)=>e.request_id===t),_t,((e,t,i)=>e.activity_id===i.activity_id),It,((e,t,i)=>e.activity_id===i.activity_id),(e=>e.activity_id),null).then((t=>"trackMyTypeAndInitiatedFromMe"!==this._config.mode||this._activityTypesInitiatedFromMe[e]?t:(this._activityTypesInitiatedFromMe[e]=!0,this._gw3Session.send({type:"subscribe",activity_types:[e]}).then((()=>t)))))}stopActivity(e){return this._gw3Session.send({type:"destroy",activity_id:e.id,reason_uri:"com.tick42.glue.activity.constants.destroyReason.general",reason:"Destroying activity"}).then((e=>!0))}updateActivityContext(e,t,i,n){if(i)return this._contexts.set(e.id,t);n=n||[];for(const e of n)t[e]=null;return this._contexts.update(e.id,t)}announceWindow(e,t){throw new Error("Invalid operation 'announceWindow' for GW3 protocol")}registerWindow(e,t,i){let n=void 0!==this._connection.gatewayToken;const s=this._connection.peerId;if("undefined"!=typeof window){const e=window.glue42gd;e&&(n=void 0!==e.activityInfo)}return n&&this._gw3Session.send({type:"ready"}),this.invokeCallbacks(this._activityWindowChangeCallbacks,new st(new yt(s,t,e,void 0,this.getAgmInstance(s),i,this.generateWindowGetter(s),void 0),new rt(ct.Added)),"register window"),Promise.resolve(s)}onActivityWindowChange(e){this._activityWindowChangeCallbacks.push(e)}createWindow(e,t){t.layout||(t.left||t.width||t.height||t.top)&&(t.layout={mode:"pixels",cellSize:1});const i=i=>{if(e)return this.joinActivity(e,i,t.name).then((()=>i))};return this.sendCreateAndMapResultingMessagesToPromise({type:"create-peer",peer_type:t.type,peer_name:t.name||t.type,configuration:t,activity_id:e},void 0,void 0,Mt,((e,t)=>e.request_id===t),void 0,void 0,(e=>e.created_id),i).then(i)}closeWindow(e){return this._gw3Session.send({type:"destroy-peer",destroy_peer_id:e}).then((e=>{}))}getAnnouncementInfo(){let e=this._config.activityId||this._config.announcementInfo&&this._config.announcementInfo.activityId,t=this._config.announcementInfo&&this._config.announcementInfo.activityWindowType,i=this._config.announcementInfo&&this._config.announcementInfo.activityWindowIndependent,n=this._config.announcementInfo&&this._config.announcementInfo.activityWindowName;if("undefined"!=typeof window&&void 0!==window.location&&window.location.search&&"function"==typeof URLSearchParams){const s=new URLSearchParams(location.search.slice(1));t=t||s.get("t42PeerType"),t=t||s.get("t42ActivityWindowType"),void 0===i&&(i=s.get("t42ActivityWindowIndependent")),n=n||s.get("t42ActivityWindowName"),e=e||s.get("t42ActivityId")}return t=t||"unknown",i=i||!1,n=n||this._connection.peerId,{activityWindowId:void 0,activityId:e,activityWindowType:t,activityWindowIndependent:i,activityWindowName:n}}joinActivity(e,t,i){const n=i&&{name:i}||{};return this._gw3Session.send({type:"join-activity",target_id:t,activity_id:e,...n}).then((()=>{this.invokeCallbacks(this._activityWindowChangeCallbacks,new st(new yt(t,void 0,void 0,e,this.getAgmInstance(t),void 0,this.generateWindowGetter(t),void 0),new rt(ct.ActivityWindowJoinedActivity)),"activity joined - ActivityWindow"),this.invokeCallbacks(this._activityChangeCallbacks,new st(new gt(e,void 0,new wt("created",void 0,void 0),void 0,void 0),new rt(ct.Updated)),"activity joined - Activity")}))}leaveActivity(e,t){return this._gw3Session.send({type:"leave-activity",target_id:t,activity_id:e}).then((()=>{this.invokeCallbacks(this._activityWindowChangeCallbacks,new st(new yt(t,void 0,void 0,null,this.getAgmInstance(t),void 0,this.generateWindowGetter(t),void 0),new rt(ct.ActivityWindowLeftActivity)),"activity left - ActivityWindow"),this.invokeCallbacks(this._activityChangeCallbacks,new st(new gt(e,void 0,new wt("created",void 0,void 0),void 0,void 0),new rt(ct.Updated)),"activity left - Activity")}))}getActivityTypes(){return Promise.resolve([])}getWindowTypes(){return Promise.resolve([])}getActivities(){return Promise.resolve([])}getActivityWindows(){return Promise.resolve([])}createStackedWindows(e,t,i){}getWindowBounds(e){}setWindowBounds(e,t){}activateWindow(e,t){}setWindowVisibility(e,t){}cloneActivity(e,t){}attachActivities(e,t,i){return this._gw3Session.send({type:"merge",into:t,merge:e})}detachActivities(e,t){return this._gw3Session.send({type:"split",from:e}).then((()=>""))}onActivitiesAttached(e){}onActivitiesDetached(e){}onActivityAttachedDescriptorsRefreshed(e){}getAttachedDescriptors(){return Promise.resolve([])}getRandomRequestId(){return this._connection.peerId+":"+Math.floor(1e9*Math.random())}forwardAddedAndRemovedMessagesToEventHandler(e,t,i,n){const s=e=>t=>new st(t,new rt(e?ct.Added:ct.Removed));return[e&&this.forwardMessageToEventHandler(e,(e=>i(e,!0)),s(!0),n),t&&this.forwardMessageToEventHandler(t,(e=>i(e,!1)),s(!1),n)].filter((e=>e))}forwardMessageToEventHandler(e,t,i,n){return this.subscribe(e,(e=>{t(e).forEach((t=>n.forEach((n=>n(i(t,e))))))}))}sendCreateAndMapResultingMessagesToPromise(e,t,i,n,s,r,o,a,c){const d=this.getRandomRequestId();let h,u;const l=new Promise(((e,t)=>{h=e,u=t}));let p,g,m,f,y=null;const w=()=>{this.dropSubscription(p),c||this.dropSubscription(g),this.dropSubscription(m),this.dropSubscription(f)};p=t&&this.subscribe(t,(e=>{i(e,d)&&(y=e,this.dropSubscription(p))}));let v=!1;g=this.subscribe(n,(e=>{s(e,d,y)&&(v?c&&c(a(e)):(v=!0,h(a(e))))})),m=r&&this.subscribe(r,(e=>{o(e,d,y)&&u(e)})),f=r&&this.subscribe(vt,(e=>{e.request_id===d&&u(e)})),e.request_id=d;const b=this._gw3Session.send(e).then((()=>l));return b.then(w,w),b}peerFactoryIdAndOwnerIdToWindowType(e,t){const i=this._peerIdAndFactoryIdToPeerType[t+":"+e];return i?new nt(i,void 0):null}subscribe(e,t){const i=this._connection.on(e,(e=>t.bind(this)(e)));return this._gw3Subscriptions.push(i),i}dropSubscription(e){e&&(this._connection.off(e),delete this._gw3Subscriptions[this._gw3Subscriptions.indexOf(e)])}invokeCallbacks(e,t,i){e.forEach((e=>{try{e(t)}catch(e){this._logger.error(`Error in ${i||t.context.type} callback: `+JSON.stringify(e))}}))}handleActivityCreatedMessage(e){e.context_id?this._contextSubscriptions[e.activity_id]||this.subscribeToContext(e):this._logger.error("Activity created with unknown context_id: "+e.activity_id)}async subscribeToContext(e){const t=e.activity_id;this._contextSubscriptions[t]=await this._contexts.subscribe(t,((e,i,n)=>{const s=new st(new gt(t,void 0,void 0,e,void 0),new at(e,i,n));this.invokeCallbacks(this._activityChangeCallbacks,s,"context updated")}))}handleActivityDestroyedMessage(e){const t=this._contextSubscriptions[e.activity_id];"function"==typeof t&&t(),delete this._contextSubscriptions[e.activity_id]}handlePeerFactoriesAdded(e){e.factories.forEach((t=>{this._peerIdAndFactoryIdToPeerType[e.owner_id+":"+t.id]=t.peer_type}))}handlePeerFactoriesRemoved(e){e.factory_ids.forEach((t=>{delete this._peerIdAndFactoryIdToPeerType[e.owner_id+":"+t]}))}forwardActivityTypeMessagesToStatusEventHandlers(){this.forwardAddedAndRemovedMessagesToEventHandler("types-added","types-removed",((e,t)=>t?e.types.map((e=>Rt.activityTypeGwMessageEntityToActivityType(e,void 0))):e.types.map((e=>new it(e.name,void 0,void 0,void 0)))),this._activityTypeStatusChangeCallbacks)}forwardActivityCreatedAndJoinedActivityToActivityWindowEventHandlers(){for(const e of[_t,At,kt])this.forwardMessageToEventHandler(e,(e=>[e.owner||{...e,type:e.peer_type,name:e.peer_name,peer_id:e.owner_id}].concat(e.participants||[]).map((t=>new yt(t.peer_id,t.name,t.type,e.activity_id,this.getAgmInstance(t.peer_id),void 0,this.generateWindowGetter(t.peer_id),void 0)))),((e,t)=>new st(e,new rt(ct.ActivityWindowJoinedActivity))),this._activityWindowChangeCallbacks)}forwardActivityMessagesToStatusEventHandlers(){for(const e of[_t,At])this.forwardMessageToEventHandler(e,(e=>[Rt.activityGwMessageToActivity(e,new wt("started","",new Date))]),((e,t)=>Rt.activityToActivityStatusChangeEvent(e)),this._activityChangeCallbacks);this.forwardMessageToEventHandler(It,(e=>[Rt.activityGwMessageToActivity(e,new wt("destroyed",e.reason,new Date))]),((e,t)=>Rt.activityToActivityStatusChangeEvent(e)),this._activityChangeCallbacks),this.forwardMessageToEventHandler(Ct,(e=>[Rt.activityGwMessageToActivity(e,new wt("created","",new Date))]),((e,t)=>Rt.activityToActivityStatusChangeEvent(e)),this._activityChangeCallbacks),this.forwardMessageToEventHandler(kt,(e=>[Rt.activityGwMessageToActivity(e,new wt("created","",new Date))]),((e,t)=>Rt.activityToActivityStatusChangeEvent(e)),this._activityChangeCallbacks)}forwardPeerFactoryMessagesToStatusEventHandlers(){this.forwardAddedAndRemovedMessagesToEventHandler(Et,Pt,((e,t)=>t?e.factories.map(Rt.peerFactoryGwMessageEntityToWindowType):e.factory_ids.map((t=>this.peerFactoryIdAndOwnerIdToWindowType(t,e.owner_id))).filter((e=>null!=e))),this._windowTypeStatusChangeCallbacks)}forwardPeerFactoryMessagesToPeerFactoryRequests(){this.subscribe("peer-requested",(e=>{const t=this._peerFactoriesRegisteredByUs[e.peer_factory];if(t)try{const i=e.configuration||{};i.gateway_token=i.gateway_token||e.gateway_token,i.peer_factory=i.peer_factory||e.peer_factory;const n=t({activityId:e.activity&&e.activity.id,activityType:e.activity&&e.activity.type,type:e.configuration&&e.configuration.type,gwToken:i.gateway_token,configuration:i});n&&n.then&&n.catch&&n.catch((t=>this._gw3Session.send({type:vt,request_id:e.request_id,reason:t&&(t.message||JSON.stringify(t))})))}catch(t){this._gw3Session.send({type:vt,request_id:e.request_id,reason:t&&(t.message||JSON.stringify(t))})}else this._gw3Session.send({type:vt,request_id:e.request_id,reason:`Unknown peer factory ${e.peer_factory}`})}))}forwardActivityWindowMessagesToEventHandlers(){for(const e of[St,At])this.subscribe(e,(t=>{const i=e===St?t.joined_id:t.peer_id,n=e===St?t.joined_type:t.peer_type,s=e===St?t.joined_name:t.peer_name,r=new yt(i,s,n,t.activity_id,this.getAgmInstance(i),void 0,this.generateWindowGetter(i),void 0);this._contextSubscriptions[t.activity_id]?e===At&&this._activityJoinedPromiseResolve({}):this.subscribeToContext(t).then((()=>{e===At&&this._activityJoinedPromiseResolve({})})),this.invokeCallbacks(this._activityWindowChangeCallbacks,new st(r,new rt(ct.ActivityWindowJoinedActivity)),e)}));this.subscribe(xt,(e=>{const t=new yt(e.left_id,void 0,void 0,null,this.getAgmInstance(e.left_id),void 0,this.generateWindowGetter(e.left_id),void 0);this.invokeCallbacks(this._activityWindowChangeCallbacks,new st(t,new rt(ct.ActivityWindowLeftActivity)),xt)})),this.forwardAddedAndRemovedMessagesToEventHandler(Mt,void 0,(e=>[new yt(e.created_id,void 0,void 0,void 0,void 0,void 0,this.generateWindowGetter(e.created_id),void 0)]),this._activityWindowChangeCallbacks)}getAgmInstance(e){return this._config.agm.servers().find((t=>t.peerId===e||t.windowId===e))}generateWindowGetter(e){return()=>{const t=this.getAgmInstance(e);if(!t)return;const i=t.windowId;return this._config.windows.list().filter((e=>e.id===i))[0]}}isOverrideTypeDefinition(e){return void 0!==e&&!!e.owner}}class Nt{constructor(e,t){this._myAttached=[],this._myDetached=[],this._myAttachedTo=[],this._myDetachedFrom=[],this._myActivityFrameColorChanged=[],this._myActivityJoinedCallbacks=[],this._myActivityRemovedCallbacks=[],this._myContextUpdateCallbacks=[],this._logger=ft.Get(this),this._m=e,e.ready().then((e=>{e.subscribeActivityContextChanged(this._subscribeMyContextChanged.bind(this)),e.subscribeWindowEvents(this._subscribeMyWindowEvent.bind(this)),e.subscribeActivitiesAttached(this._subscribeActivitiesAttached.bind(this)),e.subscribeActivitiesDetached(this._subscribeActivitiesDetached.bind(this)),t&&t.onWindowFrameColorChanged(this._subscribeWindowFrameColorChanged.bind(this))}))}get window(){if(Ze(this._w)){const e=this._m.announcedWindows;e.length>0&&(this._w=e[0])}return this._w}get activity(){const e=this.window;if(!Ze(e))return e.activity}createWindow(e){return this._m.createWindow(this.activity,e)}createStackedWindows(e,t){return this._m.createStackedWindows(this.activity,e,t)}get context(){const e=this.activity;return Qe(e)?{}:e.context}updateContext(e,t){const i=this.activity;return Qe(i)?new Promise(((e,t)=>{t("Not in activity")})):i.updateContext(e,t)}setContext(e,t){const i=this.activity;return Qe(i)?new Promise(((e,t)=>{t("Not in activity")})):i.setContext(e,t)}onActivityJoined(e){this._myActivityJoinedCallbacks.push(e);const t=this.window;Ze(t)||Ze(t.activity)||e(t.activity)}onActivityLeft(e){this._myActivityRemovedCallbacks.push(e)}onContextChanged(e){this._myContextUpdateCallbacks.push(e);const t=this.window;if(Ze(t))return;const i=t.activity;Ze(i)||e(i.context,i.context,[],i)}clone(e,t){const i=this.activity;return this._m.clone(i,e,t)}attach(e,t){let i;return i="string"==typeof e?e:e.id,this._m.attachActivities(i,this.activity.id,t)}onActivityAttached(e){this._myAttached.push(e)}onActivityDetached(e){this._myDetached.push(e)}onAttachedToActivity(e){this._myAttachedTo.push(e)}onDetachedFromActivity(e){this._myDetachedFrom.push(e)}get attached(){return this.activity?this.activity.attached:[]}setFrameColor(e,t){return this.activity?this.activity.setFrameColor(e,t):Promise.resolve(null)}getFrameColor(){return this.activity?this.activity.getFrameColor():""}onFrameColorChanged(e){this._myActivityFrameColorChanged.push(e)}_subscribeMyContextChanged(e,t,i,n){const s=this.window;if(Ze(s))return;const r=s.activity;Ze(r)||e.id===r.id&&this._notifyMyContextChanged(e,t,i,n)}_subscribeMyWindowEvent(e,t,i){Ze(this.window)||this.window.id===t.id&&(i===ct.ActivityWindowJoinedActivity?(this._notifyMyWindowEvent(e,this._myActivityJoinedCallbacks),this._notifyMyContextChanged(e,e.context,null,null)):i===ct.ActivityWindowLeftActivity&&this._notifyMyWindowEvent(e,this._myActivityRemovedCallbacks))}_notifyMyWindowEvent(e,t){t.forEach((t=>{try{t(e,event)}catch(e){this._logger.warn("error in user callback "+e)}}))}_notifyMyContextChanged(e,t,i,n){i=i||{},n=n||[],this._myContextUpdateCallbacks.forEach((s=>{try{s(t,i,n,e)}catch(e){this._logger.warn("error in user callback "+e)}}))}_notifyAttached(e){this._myAttached.forEach((t=>{try{t(e)}catch(e){this._logger.warn("error in user callback "+e)}}))}_notifyDetached(e){this._myDetached.forEach((t=>{try{t(e)}catch(e){this._logger.warn("error in user callback "+e)}}))}_notifyAttachedTo(e){this._myAttachedTo.forEach((t=>{try{t(this.activity,e)}catch(e){this._logger.warn("error in user callback "+e)}}))}_notifyDetachedFrom(e,t,i){this._myDetachedFrom.forEach((n=>{try{n(e,t,i)}catch(e){this._logger.warn("error in user callback "+e)}}))}_subscribeActivitiesAttached(e,t){const i=this.window;if(Ze(i))return;const n=i.activity;Ze(n)||e.id===n.id&&(t.windowIds.indexOf(i.id)>=0?this._notifyAttachedTo(t):this._notifyAttached(t))}_subscribeActivitiesDetached(e,t,i){const n=this.window;if(Ze(n))return;const s=n.activity;Ze(s)||(t.id===s.id&&this._notifyDetached(i),e.id===s.id&&this._notifyDetachedFrom(e,t,i))}_subscribeWindowFrameColorChanged(e){const t=this.activity;t&&t.owner&&t.owner.underlyingWindow.id===e.id&&this._myActivityFrameColorChanged.forEach((t=>{t(e.frameColor)}))}}class jt{constructor(e,t){if(this._logger=ft.Get("ReadyMarker ["+e+"]"),this._logger.debug("Initializing ready marker for '"+e+"' with "+t+" signals to wait"),t<=0)throw new Error("Invalid signal number. Should be > 0");this._signals=t,this._callbacks=[],this._name=e}setCallback(e){this.isSet()?e(void 0):this.isError()?e(this._error):this._callbacks.push(e)}signal(e){if(this._logger.debug("Signaled - "+e+" - signals left "+(this._signals-1)),this._signals--,this._signals<0)throw new Error("Error in ready marker '"+this._name+" - signals are "+this._signals);this.isSet()&&this._callbacks.forEach((e=>{e(void 0)}))}error(e){this._error=e,this._callbacks.forEach((t=>{t(e)}))}isSet(){return!this.isError()&&0===this._signals}isError(){return!Qe(this._error)}getError(){return this._error}}class Wt{constructor(e){this._items={},this._listeners=[],this._processNew=e}addOne(e){this.add([e])}add(e){e.forEach((e=>{this.process(new st(e,new rt(ct.Added)))}))}process(e){const t=e.context,i=t.type,n=e.entity;if(i===ct.StatusChange&&!t.oldStatus){const e=this._items[n.id];e&&(t.oldStatus=e.status)}i===ct.StatusChange&&t.oldStatus&&t.newStatus&&t.oldStatus.state===t.newStatus.state&&(t.type=ct.Updated),"undefined"==typeof htmlContainer&&(i===ct.ActivityWindowJoinedActivity&&this._items[n.id]&&this._items[n.id].activity&&(t.type=ct.Updated),i===ct.ActivityWindowLeftActivity&&this._items[n.id]&&!this._items[n.id].activity&&(t.type=ct.Updated));const s=this._updateInternalCollections(n,i,t);return this._notifyListeners(s,t),s}get(){const e=[];for(const t in this._items)if(this._items.hasOwnProperty(t)){const i=this._items[t];e.push(i)}return e}getByName(e){for(const t in this._items)if(t===e)return this._items[t]}getOrWait(e){return new Promise((t=>{const i=n=>{n.id===e&&(t(n),this.unsubscribe(i))};this.subscribe(i);const n=this.getByName(e);if(n)return this.unsubscribe(i),void t(n)}))}subscribe(e){return this._listeners.push(e),Object.keys(this._items).forEach((t=>{const i=this._items[t];e(i,new rt(ct.Added.toString()))})),()=>{this.unsubscribe(e)}}unsubscribe(e){const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}_notifyListeners(e,t){this._listeners.forEach((i=>{try{i(e,t)}catch(e){return}}))}_updateInternalCollections(e,t,i){const n=e,s=t===ct.StatusChange&&n.status&&n.status.state===dt.Destroyed||t===ct.StatusChange&&i&&i.newStatus&&i.newStatus.state===dt.Destroyed,r=t===ct.Closed;if(t===ct.Removed&&void 0===n.isIndependent||r||s){const t=this._items[e.id];return delete this._items[e.id],this._processNew(e),t&&e._beforeDelete(t),e}{const t=e.id;this._items.hasOwnProperty(t)?this._items[e.id]._update(e):(this._processNew(e),this._items[e.id]=e)}return this._items[e.id]}}class Ot{get usingHc(){return"HC"===this._bridge.bridgeType}get announcedWindows(){return this._announcedWindows}set announcedWindows(e){throw new Error("not allowed")}constructor(e,t,i){this._logger=ft.Get("activityManager"),this._announcedWindows=[],this._attachedCallbacks=[],this._detachedCallbacks=[],this._frameColorChangesCallbacks=[],this._windowHandlers=[],this._bridge=e,this._activityTypes=new Wt((e=>this._grabEntity(e))),this._windowTypes=new Wt((e=>this._grabEntity(e))),this._activities=new Wt((e=>this._grabEntity(e))),this._windows=new Wt((e=>this._grabEntity(e))),this._dataReadyMarker=new jt("Activity Manager Data",4),this._descriptorsMarker=new jt("Attached Activities Descriptors",1),t?(this._readyMarker=new jt("Activity Manager Announce",1),this._dataReadyMarker.setCallback((e=>{e&&this._readyMarker.error(e),this._descriptorsMarker.setCallback((e=>{e&&this._readyMarker.error(e),this._logger.debug("Auto announcing window"),this.announceWindow().then((e=>{this._announcedWindows.push(e),this._readyMarker.signal("Successfully announced window with id '"+e.id+"'")})).catch((e=>{this._logger.debug("Will not announce window - "+e),this._readyMarker.signal()}))})),this.refreshDescriptors()}))):this._readyMarker=this._dataReadyMarker,this._bridge.onActivitiesAttached((e=>{this._handleActivitiesAttached(e)})),this._bridge.onActivitiesDetached((e=>{this._handleActivitiesDetached(e)})),this._bridge.onActivityAttachedDescriptorsRefreshed((e=>{this._handleActivityDescriptorsRefreshed(e)})),i&&i.onWindowFrameColorChanged(this._handleWindowFrameColorChanged.bind(this)),this._bridge.init(),this._subscribeForData(),this._bridge.initReady().then((e=>{this._getInitialData()})).catch((e=>{console.log(e)}))}ready(e){const t=new Promise(((e,t)=>{this._readyMarker.setCallback((i=>{i?t(this._readyMarker.getError()):e(this)}))}));return pt(Promise.all([this._bridge.ready(),t]).then((()=>this)),e)}getActivityTypes(){return this._activityTypes.get()}getActivityType(e){return this._activityTypes.getByName(e)}registerActivityType(e,t,i,n,s,r){return pt(new Promise(((r,o)=>{if(Ze(e))return void o("activityTypeName argument can not be undefined");if(!Ve(e))return void o("activityTypeName should be string");if(!Ze(this.getActivityType(e)))return void o("Activity type '"+e+"' already exists");let a;if(Qe(t))return void o("Owner window type can not be undefined");a=Ve(t)?{type:t,name:"",isIndependent:!1,arguments:{}}:t;const c=[];if(!Qe(i)&&Ke(i))for(const e in i){const t=i[e];if(Ve(t)){const e={type:t,name:"",isIndependent:!1,arguments:{},relativeTo:"",relativeDirection:"",windowStyleAttributes:{}};c.push(e)}else c.push(t)}this._bridge.registerActivityType(e,a,c,n,s).then((e=>{this._grabEntity(e),r(e)})).catch((e=>{o(e)}))})),r)}unregisterActivityType(e,t){return pt(new Promise(((t,i)=>{const n=this.getActivityType(e);Qe(n)?i("Activity type '"+e+"' does not exists"):this._bridge.unregisterActivityType(e).then((()=>t(n)),i)})),t)}initiate(e,t,i,n){return pt(new Promise(((i,s)=>{Qe(this.getActivityType(e))?s("Activity type '"+e+"' does not exists"):this._bridge.initiateActivity(e,t,n).then((e=>{this._activities.getOrWait(e).then((e=>{i(e)})).catch((e=>s(e)))})).catch((e=>{s(e)}))})),i)}subscribeActivityTypeEvents(e){this._activityTypes.subscribe(((t,i)=>{e(t,i.type)}))}getWindowTypes(){return this._windowTypes.get()}getWindowType(e){return this._windowTypes.getByName(e)}registerWindowFactory(e,t,i){return pt(new Promise(((i,n)=>{if(Ze(e))n("no windowType specified");else{if(ze(e))e=e.getName();else if(!Ve(e))return void n("windowType should be string or object that has getName method");this._bridge.registerWindowFactory(e,t).then((e=>{i(e)})).catch((e=>{n(e)}))}})),i)}unregisterWindowFactory(e,t){return pt(new Promise(((t,i)=>{Ze(e)?i("no windowType specified"):Ve(e)?this._bridge.unregisterWindowFactory(e).then((e=>{t(e)})).catch((e=>{i(e)})):i("windowType should be a string")})),t)}getActivities(e){let t=this._activities.get();if(t=t.filter((e=>e._ownerId)),!e)return t;let i=e;if(Ve(e))i=[e];else if(e instanceof it)i=[e.name];else if(!(e instanceof Array))throw new Error("Invalid input argument 'activityType' = "+e);return t.filter((e=>{const t=e.type;return function(e,t){for(let i=0;i<e.length;i++)if(t(e[i],i))return!0;return!1}(i,(e=>t.id===e.id))}))}getActivityById(e){return this._activities.getByName(e)}announceWindow(e,t){return new Promise(((i,n)=>{const s=this._bridge.getAnnouncementInfo();if(Qe(e)&&(e=s.activityWindowId),Qe(t)&&(t=s.activityWindowType),Ze(t))throw new Error("Can not announce - unknown windowType");const r=s&&s.activityId;if(Ze(e))this._logger.debug("Registering window with type:'"+t+"', name:'"+s.activityWindowName+"', ind.:'"+s.activityWindowIndependent+"'"),this._bridge.registerWindow(t,s.activityWindowName,s.activityWindowIndependent).then(this._windows.getOrWait.bind(this._windows)).then((e=>r?this._activities.getOrWait(r).then((t=>e)):e)).then((e=>{i(e)})).catch((e=>{this._logger.error(e)}));else{this._logger.debug("Announcing window with id '"+e+"' and type '"+t+"'");const s=this._windows.getByName(e);if(!Ze(s))return this._logger.debug("Window with id '"+e+"' already announced - reusing the window"),void i(s);const r=(t,s,o)=>{if(e===s.id&&o===ct.ActivityWindowJoinedActivity){Qe(s.activity)&&n("UNDEFINED ACTIVITY"),this._logger.trace("Got joined event for id '"+e+"'"),i(s),this.unsubscribeWindowEvents(r)}};this.subscribeWindowEvents(r),this._logger.trace("Waiting for joined event for id '"+e+"'"),this._bridge.announceWindow(t,e)}}))}subscribeWindowTypeEvents(e){this._windowTypes.subscribe(((t,i)=>{e(t,i.type)}))}subscribeActivityEvents(e){return this._activities.subscribe(((t,i)=>{if(i.type===ct.StatusChange){const n=i;e(t,n.newStatus,n.oldStatus)}if(i.type===ct.Removed||i.type===ct.StatusChange&&i.newStatus.getState()===dt.Destroyed)for(const e of this._windows.get())e.activity&&e.activity.id===t.id&&this._windows.process(new st(e,new rt(ct.ActivityWindowLeftActivity)))}))}subscribeWindowEvents(e){const t=(t,i)=>{let n=i.type;n===ct.Added&&(n="opened"),e(t.activity,t,n)};return this._windowHandlers.push([e,t]),this._windows.subscribe(t)}unsubscribeWindowEvents(e){const t=this._windowHandlers.find((t=>t[0]===e));t&&(this._windowHandlers.splice(this._windowHandlers.indexOf(t),1),this._windows.unsubscribe(t[1]))}createWindow(e,t,i){return pt(new Promise(((i,n)=>{let s,r;if(Ze(t)&&n("windowType is undefined"),Ve(t))s={type:t,name:"",isIndependent:!1,arguments:{}};else if(t instanceof nt)s={type:t.type||t.id,name:t.name||t.type||t.id,isIndependent:!1};else{const e=["url"],i={};Object.keys(t).forEach((n=>{-1===e.indexOf(n)&&(i[n]=t[n])})),s=i}if(!Ze(s.relativeTo))if(r=s.relativeTo,"string"==typeof r){const e=this.getWindows({type:r});!Ze(e)&&e.length>0&&(s.relativeTo=e[0].id)}else if(Ze(r.type))Ze(r.windowId)||(s.relativeTo=r.windowId);else{const e=this.getWindows({type:r.type});!Ze(e)&&e.length>0&&(s.relativeTo=e[0].id)}this._bridge.createWindow(e&&e.id,s).then((t=>{this._logger.debug("Window created, waiting for window entity with id "+t);const n=(s,r)=>{s.id!==t||e&&!s.activity||(this._logger.debug("Got entity window with id "+t),i(s),this._windows.unsubscribe(n))};this._windows.subscribe(n)})).catch((e=>{n(e)}))})),i)}createStackedWindows(e,t,i,n){return pt(new Promise(((n,s)=>{Ze(e)&&s("activity is undefined"),Ze(t)&&s("relativeWindowTypes is undefined"),Array.isArray(t)||s("relativeWindowTypes has to be an array"),Ze(i)&&(i=2e4);const r=[];t.forEach((e=>{let t,n;if(t=Ve(e)?{type:e,name:"",isIndependent:!1,arguments:{}}:e,t.stackedWindow=!0,t.timeout=i,!Ze(t.relativeTo))if(n=t.relativeTo,Ze(n.type)){if(!Ze(n.windowId)){const e=this.getWindows({id:n.windowId});!Ze(e)&&e.length>0&&(t.relativeTo=e[0].type.name)}}else t.relativeTo=n.type;r.push(t)}));const o=[];r.forEach((t=>o.push(this.createWindow(e,t)))),Promise.all(o).then(n).catch(s)})),n)}addWindowToActivity(e,t,i){const n=this._bridge.joinActivity(e.id,t.id).then((()=>t));return pt(n,i),n}leaveWindowFromActivity(e,t,i){const n=this._bridge.leaveActivity(e.id,t.id).then((()=>t));return pt(n,i),n}setActivityContext(e,t,i){return pt(new Promise(((i,n)=>{Ze(e)&&n("activity can not be null"),this._bridge.updateActivityContext(e,t,!0).then((t=>{i(e)})).catch((e=>{n(e)}))})),i)}updateActivityContext(e,t,i){return pt(new Promise(((i,n)=>{Ze(e)&&n("activity can not be null");const s=[];for(const e in t)t.hasOwnProperty(e)&&null===t[e]&&s.push(e);for(const e of s)delete t[e];this._bridge.updateActivityContext(e,t,!1,s).then((t=>{i(e)})).catch((e=>{n(e)}))})),i)}subscribeActivityContextChanged(e){this._activities.subscribe(((t,i)=>{if(i.type===ct.ActivityContextChange){const n=i;e(t,n.context,n.updated,n.removed)}}))}stopActivity(e,t){return pt(this._bridge.stopActivity(e),t)}getWindows(e){if(Qe(e))return this._windows.get();if(!Qe(e.id))return[this._windows.getByName(e.id)];return this._windows.get().filter((t=>{if(!Qe(e.type)&&t.type.id!==e.type)return!1;if(!Qe(e.name)&&t.name!==e.name)return!1;if(!Qe(e.activityId)){if(Ze(t.activity))return!1;if(t.activity.id!==e.activityId)return!1}return!0}))}getWindowBounds(e){return this._bridge.getWindowBounds(e)}setWindowBounds(e,t,i){return pt(new Promise(((i,n)=>{this._bridge.setWindowBounds(e,t).then((()=>i())).catch((e=>n(e)))})),i)}closeWindow(e){return this._bridge.closeWindow(e)}activateWindow(e,t){return this._bridge.activateWindow(e,t)}setWindowVisibility(e,t){return this._bridge.setWindowVisibility(e,t)}clone(e,t,i){return pt(new Promise(((i,n)=>{e||n("activity can not be null"),this._bridge.cloneActivity(e.id,t).then((e=>{this._activities.getOrWait(e).then((e=>{i(e)})).catch((e=>n(e)))})).catch((e=>n(e)))})),i)}attachActivities(e,t,i,n){i=i||{};return pt(new Promise(((n,s)=>{if(!this._activities.getByName(e))return void s("can not find activity with id "+e);if(this._activities.getByName(t))return this._bridge.attachActivities(e,t,i).then((e=>{const t=e.to,i=e.descriptor,s=e.descriptors;this._activities.getOrWait(t).then((e=>{e._updateDescriptors(s);const t=e.attached.filter((e=>e.ownerId===i.ownerId))[0];n(t)}))})).catch((e=>{s(e)}));s("can not find activity with id "+t)})),n)}detachActivities(e,t,i){return pt(new Promise(((i,n)=>this._bridge.detachActivities(e,t).then((()=>{this._activities.getOrWait(undefined).then((e=>{e._updateDescriptors(undefined),this._activities.getOrWait(undefined).then((e=>{i(e)}))})).catch((e=>n(e)))})).catch((e=>{n(e)})))),i)}subscribeActivitiesAttached(e){this._attachedCallbacks.push(e)}subscribeActivitiesDetached(e){this._detachedCallbacks.push(e)}subscribeActivityFrameColorChanged(e){this._frameColorChangesCallbacks.push(e)}_grabEntity(e){e._manager=this}_getInitialData(){this._logger.debug("Request initial data..."),this._bridge.getActivityTypes().then((e=>{this._activityTypes.add(e),this._dataReadyMarker.signal("Got act types")})).catch((e=>{this._logger.error(e),this._dataReadyMarker.error("Can not initialize ActivityManager - error getting activity types -"+e)})),this._bridge.getWindowTypes().then((e=>{this._windowTypes.add(e),this._dataReadyMarker.signal("Got window types")})).catch((e=>{this._logger.error(e),this._dataReadyMarker.error("Can not initialize ActivityManager - error getting window types "+e)})),this._bridge.getActivities().then((e=>{this._activities.add(e),this._dataReadyMarker.signal("Got activities")})).catch((e=>{this._logger.error(e),this._dataReadyMarker.error("Can not initialize ActivityManager - error getting activity instances -"+e)})),this._bridge.getActivityWindows().then((e=>{this._windows.add(e),this._dataReadyMarker.signal("Got windows")})).catch((e=>{this._logger.error(e),this._dataReadyMarker.error("Can not initialize ActivityManager - error getting activity windows -"+e)}))}_subscribeForData(){this._logger.debug("Subscribe for data..."),this._bridge.onActivityTypeStatusChange((e=>{this._activityTypes.process(e)})),this._bridge.onWindowTypeStatusChange((e=>{this._windowTypes.process(e)})),this._bridge.onActivityWindowChange((e=>{this._windows.process(e)})),this._bridge.onActivityStatusChange((e=>{this._activities.process(e)}))}_handleActivitiesAttached(e){const t=e.to,i=e.descriptor,n=e.descriptors;this._activities.getOrWait(t).then((e=>{e._updateDescriptors(n);const t=e.attached.filter((e=>e.ownerId===i.ownerId))[0];this._attachedCallbacks.forEach((i=>{try{i(e,t)}catch(e){return}}))}))}_handleActivitiesDetached(e){const t=e.oldActivityId,i=e.newActivityId,n=e.descriptors,s=e.descriptor;this._activities.getOrWait(t).then((e=>{e._updateDescriptors(n),this._activities.getOrWait(i).then((t=>{this._detachedCallbacks.forEach((i=>{try{i(t,e,s)}catch(e){return}}))}))}))}_handleActivityDescriptorsRefreshed(e){const t=e.id,i=e.descriptors,n=this._activities.getByName(t);n&&n._updateDescriptors(i)}refreshDescriptors(){this._bridge.getAttachedDescriptors().then((e=>{e&&Object.keys(e).forEach((t=>{const i=t,n=e[t],s=this._activities.getByName(i);s&&s._updateDescriptors(n)})),this._descriptorsMarker.signal("Successfully got descriptors")})).catch((e=>{this._descriptorsMarker.error("failed to get descriptors - "+e)}))}_handleWindowFrameColorChanged(e){if(!e.activityId)return;const t=this._activities.getByName(e.activityId);t&&t.owner&&t.owner.underlyingWindow.id===e.id&&this._frameColorChangesCallbacks.forEach((i=>{try{i(t,e.frameColor)}catch(e){return}}))}}class Ft{constructor(e,t){this._m=e,this._my=t,this.activityTypes={get:this._getActivityTypesWrapper.bind(this),register:this._m.registerActivityType.bind(this._m),unregister:this._m.unregisterActivityType.bind(this._m),subscribe:this._m.subscribeActivityTypeEvents.bind(this._m),unsubscribe:void 0,initiate:this._m.initiate.bind(this._m)},this.windowTypes={get:this._getWindowTypesWrapper.bind(this),registerFactory:this._m.registerWindowFactory.bind(this._m),unregisterFactory:this._m.unregisterWindowFactory.bind(this._m),subscribe:this._m.subscribeWindowTypeEvents.bind(this._m),unsubscribe:void 0},this.windows={get:this._m.getWindows.bind(this._m),subscribe:this._m.subscribeWindowEvents.bind(this._m),announce:this._m.announceWindow.bind(this._m),unsubscribe:void 0,create:this._m.createWindow.bind(this._m)},this.instances={get:this._m.getActivities.bind(this._m),subscribe:this._m.subscribeActivityEvents.bind(this._m),unsubscribe:void 0}}onAttached(e){this._m.subscribeActivitiesAttached(e)}onDetached(e){this._m.subscribeActivitiesDetached(e)}onActivityFrameColorChanged(e){this._m.subscribeActivityFrameColorChanged(e)}_getActivityTypesWrapper(e){return Qe(e)?this._m.getActivityTypes():this._m.getActivityType(e)}_getWindowTypesWrapper(e){return Qe(e)?this._m.getWindowTypes():this._m.getWindowType(e)}}class Dt{constructor(e,t){this._mgr=e,this._my=t,this.all=new Ft(e,t)}ready(e){return pt(new Promise(((e,t)=>{this._mgr.ready().then((()=>{e(this)})).catch((e=>{t(e)}))})),e)}get my(){return this._my}get aware(){return void 0!==this._my.window}get inActivity(){return this.aware&&void 0!==this._my.activity}get agm(){if(this.aware)return this.inActivity?this._my.activity.agm:new ht(null)}getAvailableFrameColors(){return[]}}class Lt{static checkIsUsingGW3Implementation(e){return 3===e.protocolVersion}get api(){return this._api}set api(e){this._api=e}constructor(e){if(!e)throw new Error("config can not be null");let t;if(Qe(e.logLevel)||(ft.Level=e.logLevel),Ze(e.logger)||(ft.GlueLogger=e.logger),this._isUsingHCImplementation=2===e.gdMajorVersion,this._isUsingGW3Implementation=Lt.checkIsUsingGW3Implementation(e.connection),this._isUsingHCImplementation)throw new Error("GD2 not supported");if(!this._isUsingGW3Implementation)throw new Error("Unable to instantiate activity bridge implementation");if(t=new Rt(e),!t)throw new Error("A bridge to native activity is needed to create activity lib.");ht.AGM=e.agm;const i=new Ot(t,!e.disableAutoAnnounce,e.windows),n=new Nt(i,e.windows);this._api=new Dt(i,n),this._readyPromise=i.ready().then((e=>this))}get isUsingHCImplementation(){return this._isUsingHCImplementation}get isUsingGW3Implementation(){return this._isUsingGW3Implementation}ready(e){return pt(this._readyPromise,e)}}const $t="T42.ACS.GetFunctionalEntitlement",Gt="T42.ACS.CanI",Bt="T42.ACS.OnEvent",Ht="T42.ACS.GetApplications";function Ut(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function qt(e){if(e&&e.errorHandling&&"function"!=typeof e.errorHandling&&"log"!==e.errorHandling&&"silent"!==e.errorHandling&&"throw"!==e.errorHandling)throw new Error('Invalid options passed to createRegistry. Prop errorHandling should be ["log" | "silent" | "throw" | (err) => void], but '+typeof e.errorHandling+" was passed");var t=e&&"function"==typeof e.errorHandling&&e.errorHandling,i={};function n(i,n){var s=i instanceof Error?i:new Error(i);if(t)t(s);else{var r='[ERROR] callback-registry: User callback for key "'+n+'" failed: '+s.stack;if(e)switch(e.errorHandling){case"log":return console.error(r);case"silent":return;case"throw":throw new Error(r)}console.error(r)}}return{add:function(e,t,s){var r=i[e];return r||(r=[],i[e]=r),r.push(t),s&&setTimeout((function(){s.forEach((function(s){var r;if(null===(r=i[e])||void 0===r?void 0:r.includes(t))try{Array.isArray(s)?t.apply(void 0,s):t.apply(void 0,[s])}catch(t){n(t,e)}}))}),0),function(){var n=i[e];n&&(0===(n=n.reduce((function(e,i,n){return i===t&&e.length===n||e.push(i),e}),[])).length?delete i[e]:i[e]=n)}},execute:function(e){for(var t=[],s=1;s<arguments.length;s++)t[s-1]=arguments[s];var r=i[e];if(!r||0===r.length)return[];var o=[];return r.forEach((function(i){try{var s=i.apply(void 0,t);o.push(s)}catch(t){o.push(void 0),n(t,e)}})),o},clear:function(){i={}},clearKey:function(e){i[e]&&delete i[e]}}}qt.default=qt;var Jt=Ut(qt);function Vt(e){return e?Object.keys(e).map((t=>e[t])):[]}function zt(e){let t;try{t=JSON.parse(JSON.stringify(e||{}))}catch(e){t={}}return t}function Kt(e,t){if(t.throwErrors&&"function"!=typeof e)throw new Error("Please provide the callback as a function!")}class Qt{constructor(e,t,i,n){this._appManager=e,this._name=t,this._agm=i,this._configuration=n,this._registry=Jt(),e.onInstanceStarted((e=>{e.application&&e.application.name!==this._name||this._registry.execute("instanceStarted",e)})),e.onInstanceStopped((e=>{e.application&&e.application.name!==this._name||this._registry.execute("instanceStopped",e)})),e.onAppRemoved((e=>{e.name===this._name&&this._registry.execute("appRemoved",e)})),e.onAppChanged((e=>{e.name===this._name&&this._registry.execute("appChanged",e)})),e.onAppAvailable((e=>{e.name===this._name&&(this._props.IsReady=!0,this._registry.execute("appAvailable",e))})),e.onAppUnavailable((e=>{e.name===this._name&&(this._props.IsReady=!1,this._registry.execute("appUnavailable",e))}))}get name(){return this._name}get title(){return this._props.Title}get version(){return this._props.Version}get autoStart(){return this._props.AutoStart}get isShell(){return this._props.IsShell}get caption(){return this._props.Caption}get hidden(){return this._props.IsHidden}get container(){return this._props.ApplicationName}get activityType(){return this._props.ActivityType}get activityWindowType(){return this._props.ActivityWindowType}get windowSettings(){return this._props.Arguments?zt(this._props.Arguments):{}}get allowMultiple(){return this._props.AllowMultiple}get available(){return this._props.IsReady||!0}get icon(){return this._props.Icon}get iconURL(){return this._props.IconUrl}get sortOrder(){return this._props.SortOrder}get userProperties(){return this._props.UserProperties?zt(this._props.UserProperties):{}}get keywords(){return this._props.Keywords?this._props.Keywords:[]}get isActivity(){return void 0!==this._props.ActivityType&&""!==this._props.ActivityType}get configuration(){return{autoStart:this._props.AutoStart,caption:this._props.Caption,hidden:this._props.IsHidden,container:this._props.ApplicationName,activityType:this._props.ActivityType,allowMultiple:this._props.AllowMultiple}}get instances(){return this._appManager.instances().filter((e=>e.application.name===this._name))}get type(){return this._props.Type}get mode(){if(!this._props)return"unknown";if(this._props.Mode&&"string"==typeof this._props.Mode)return this._props.Mode.toLowerCase();if(this.isActivity)return"unknown";if(this._props.Arguments&&this._props.Arguments.mode&&"string"==typeof this._props.Arguments.mode)return this._props.Arguments.mode.toLowerCase();let e=this._props.WindowStyleAttributes;if(e){e=e.split(" ").join("");const t='mode:"',i=e.indexOf(t);if(-1!==i){const n=i+t.length,s=e.indexOf('"',n),r=e.substr(n,s-n);if(r&&"string"==typeof r)return r.toLowerCase()}}return"flat"}async getConfiguration(){return(await this._agm.invoke(Ht,{v2:{apps:[this._name]}})).returned.applications[0]}updateFromProps(e){this._props||(this._props={Name:e.Name}),Object.keys(e).forEach((t=>{this._props[t]=e[t]}))}start(e,t){return new Promise((async(i,n)=>{var s,r,o,a,c;if(Ze(e))e={};else if((null===(s=this._configuration())||void 0===s?void 0:s.throwErrors)&&"object"!=typeof e||Array.isArray(e))return n(new Error('Invalid "context" parameter - must be an object.'));if(Ze(t))t={};else if((null===(r=this._configuration())||void 0===r?void 0:r.throwErrors)&&"object"!=typeof t)return n(new Error('Invalid "options" parameter - must be an object.'));const d=this._name;let h=null===(a=null!==(o=t.awaitInterop)&&void 0!==o?o:t.waitForAGMReady)||void 0===a||a,u=6e4;"number"==typeof t.timeout&&(u=1e3*t.timeout);const l=e=>{let t;const s=setTimeout((()=>{t&&t(),n(`timed out while waiting for instance id ${e} for app ${this.name}`)}),u),r=n=>{n.id===e&&(t&&(t(),t=void 0),clearTimeout(s),i(n))};t=h?this._appManager.onInstanceAgmServerReady(r):this._appManager.onInstanceStarted(r)};try{const n=(await this._agm.invoke("T42.ACS.StartApplication",{Name:d,Context:e,Options:t},"best",{methodResponseTimeoutMs:u})).returned;if(void 0!==n.timeout&&void 0===t.timeout&&(u=1e3*n.timeout),void 0!==n.waitForInterop&&void 0===t.waitForAGMReady&&void 0===t.awaitInterop&&(h=n.waitForInterop),n&&n.Id)if("startOnly"===this._appManager.mode){const e=this._appManager.handleInstanceStarted({ActivityId:void 0,IsActivityOwner:void 0,Context:void 0,Title:void 0,AgmServers:void 0,Id:n.Id,Name:n.Name});i(e)}else l(n.Id);else i(void 0)}catch(e){n(null!==(c=e.message)&&void 0!==c?c:e)}}))}onInstanceStarted(e){return Kt(e,this._configuration()),this._registry.add("instanceStarted",e)}onInstanceStopped(e){return Kt(e,this._configuration()),this._registry.add("instanceStopped",e)}onAvailable(e){return Kt(e,this._configuration()),this._props.IsReady&&setTimeout((()=>{this._registry.execute("appAvailable",this)}),0),this._registry.add("appAvailable",e)}onUnavailable(e){return Kt(e,this._configuration()),!1===this._props.IsReady&&setTimeout((()=>{this._registry.execute("appUnavailable",this)}),0),this._registry.add("appUnavailable",e)}onChanged(e){Kt(e,this._configuration()),this._registry.add("appChanged",e)}onRemoved(e){Kt(e,this._configuration()),this._registry.add("appRemoved",e)}}class Zt{constructor(e,t,i,n,s,r,o,a){this._id=e,this._appName=t,this._appManager=i,this._agm=n,this._activities=s,this._windows=r,this._configuration=a,this._registry=Jt(),o||(this._unsubscribeInstanceStopped=this._appManager.onInstanceStopped((e=>{e.id===this._id&&this._registry.execute("stopped",e)})),this._unsubscribeInstanceAgmServerReady=this._appManager.onInstanceAgmServerReady((e=>{e.id===this._id&&this._registry.execute("agmReady",e)})))}get id(){return this._id}get application(){return this._appManager.application(this._appName)}get activity(){if(!this._activities)throw new Error("This method requires glue.activities library to be enabled.");return this._activities.all.instances.get().filter((e=>e.id===this._activityId))[0]}get isActivityOwner(){return this._isActivityOwner}get activityInstances(){return this._appManager.instances().filter((e=>"activity"!==e.application.type&&e.activityId&&e.activityId===this._activityId))}get activityOwnerInstance(){if(this._activityId)return this.activityInstances.filter((e=>null==e?void 0:e.isActivityOwner))[0]}get window(){if(!this._windows)throw new Error("This method requires glue.windows library to be enabled.");let e=this._windows.list().filter((e=>e.id===this._id))[0];return!e&&this._activities&&this.activity&&this.activityOwnerInstance&&(e=this.activityOwnerInstance.window),e}get context(){var e,t,i;return null!==(i=null!==(e=this._startUpContext)&&void 0!==e?e:null===(t=this.window)||void 0===t?void 0:t.context)&&void 0!==i?i:{}}get title(){return this._title}get isActivityInstance(){return this._isActivityInstance}get activityId(){return this._activityId}get inActivity(){return this._inActivity}get isSingleWindowApp(){return!this._inActivity}get agm(){return this._agmInstance}get interopInstance(){return this._agmInstance}onInteropReady(e){return Kt(e,this._configuration()),this._agmInstance&&setTimeout((()=>{this._registry.execute("agmReady",this)}),0),this._registry.add("agmReady",e)}onAgmReady(e){return this.onInteropReady(e)}onStopped(e){return Kt(e,this._configuration()),this._registry.add("stopped",e)}getWindow(){return new Promise(((e,t)=>{const i=this.window;if(i)return void e(i);const n=(i,n)=>{i&&t(i),n&&e(n),setTimeout((()=>{clearTimeout(s),r()}),0)},s=setTimeout((()=>{n(new Error(`can not find a window with id ${this._id}`))}),3e4),r=this._windows.onWindowAdded((e=>{e.id===this._id&&n(void 0,e)}))}))}updateFromProps(e){this._startUpContext=e.Context,this._title=e.Title,this._isActivityInstance=!1,e.ActivityId&&""!==e.ActivityId&&(this._activityId=e.ActivityId,this._isActivityInstance=!0),this._isActivityOwner=e.IsActivityOwner,!this._activityId&&this._startUpContext&&this._startUpContext.activityId&&(this._activityId=this._startUpContext.activityId),this._inActivity=Boolean(this._activityId),this.updateAgmInstanceFromProps(e)}updateAgmInstanceFromProps(e){if(!e.AgmServers)return;const t=e.AgmServers;t&&t.length>0&&!Ze(t[0])&&(this._agmInstance=t[0])}stop(){return new Promise(((e,t)=>{let i=this._id;this.isActivityOwner&&(i=this.activityId);const n=this._appManager.onInstanceStopped((t=>{t.id===i&&(n(),e())}));this._agm.invoke("T42.ACS.StopApplication",{Name:this._appName,Id:this._id}).then((()=>{"startOnly"===this._appManager.mode&&(this._appManager.handleInstanceStopped({Name:this._appName,Id:this.id}),e())})).catch((e=>t(e)))}))}activate(){return this._agm.invoke("T42.ACS.ActivateApplication",{Name:this._appName,Id:this._id})}done(){this._registry.clear(),this._unsubscribeInstanceAgmServerReady(),this._unsubscribeInstanceStopped()}getContext(){return Promise.resolve(this.context)}async startedBy(){return(await this._agm.invoke("T42.ACS.Execute",{command:"getStartedBy",Name:this._appName,Id:this._id})).returned}}class Xt{constructor(e,t,i,n,s,r,o){this.mode=e,this._agm=t,this._activities=i,this._windows=n,this._logger=s,this._gdMajorVersion=r,this._configuration=o,this._apps={},this._instances=[],this._registry=Jt(),this.getConfigurations=async e=>{const t={v2:{apps:void 0}};Array.isArray(e)&&(t.v2={apps:e});return(await this._agm.invoke(Ht,t)).returned.applications},this.application=e=>{var t;if((null===(t=this._configuration())||void 0===t?void 0:t.throwErrors)&&"string"!=typeof e)throw new Error('"name" must be string');return this._apps[e]},this.applications=()=>Object.keys(this._apps).map((e=>this._apps[e])),this.instances=()=>this._instances.map((e=>e)),this.getMyInstance=()=>{const e="undefined"!=typeof window&&window.glue42gd;if(!e){const e=this._agm.instance.instance;return this._instances.find((t=>t.id===e))}if(this._gdMajorVersion>=3){const t=e.appInstanceId;return this._instances.find((e=>e.id===t))}},this.getMyApplication=()=>{var e;if(this._agm.instance)return null!==(e=this.application(this._agm.instance.applicationName))&&void 0!==e?e:this.application(this._agm.instance.application)},this.handleSnapshotAppsAdded=e=>{const t=this.applications();t.length>0&&t.forEach((t=>{const i=t.name;e.find((e=>e.Name===t.name))||this.handleAppRemoved({Name:i})})),e.forEach((e=>{t.find((t=>t.name===e.Name))||this.handleAppAdded(e)}))},this.handleSnapshotInstanceStarted=e=>{const t=this.instances();t.length>0&&t.forEach((t=>{const i=t.id;e.find((e=>e.Id===i))||this.handleInstanceStopped({Name:t.application.name,Id:i})})),e.forEach((e=>{t.find((t=>t.id===e.Id))||this.handleInstanceStarted(e)}))},this.handleAppAdded=e=>{const t=this._getAppId(e);this._logger.trace(`adding app ${t}`),this._apps[t]=new Qt(this,t,this._agm,this._configuration);const i=this._updateAppFromProps(e);this._registry.execute("appAdded",i),this._registry.execute("appAvailable",i)},this.handleAppUpdated=e=>{const t=this._updateAppFromProps(e);this._registry.execute("appChanged",t)},this.handleAppRemoved=e=>{const t=this._getAppId(e);this._logger.trace(`removing app ${t}`);const i=this.application(t);this._instances=this._instances.filter((e=>e.application.name!==i.name)),delete this._apps[t],this._registry.execute("appRemoved",i)},this.handleAppReady=e=>{const t=this._getAppId(e),i=this._getAppOrThrow(t);i.updateFromProps(e),i.available?this._registry.execute("appAvailable",i):this._registry.execute("appUnavailable",i)},this.handleInstanceStarted=e=>{this._logger.trace(`started app ${e.Name} ${e.Id}`);const t=this._getInstanceId(e),i=this._getInstanceAppName(e),n=new Zt(t,i,this,this._agm,this._activities,this._windows,!1,this._configuration);return this._updateInstanceFromProps(n,e),this._instances.push(n),this._registry.execute("instanceStarted",n),n},this.handleInstanceStopped=e=>{this._logger.trace(`failed to start app ${e.Name} ${e.Id}`);const t=this._getInstanceId(e),i=this._getInstanceAppName(e),n=this._getInstanceOrThrow(t,i);this._instances=this._instances.filter((e=>!this._matchInstance(e,t,i))),this._registry.execute("instanceStopped",n),n.done()},this.handleInstanceAgmServerReady=e=>{const t=this._getInstanceId(e),i=this._getInstanceAppName(e),n=this._getInstanceOrThrow(t,i);n.updateAgmInstanceFromProps(e),this._registry.execute("instanceAgmServerReady",n)},this.handleInstanceStartFailed=e=>{const t=this._getInstanceId(e),i=this._getInstanceAppName(e),n=new Zt(t,i,void 0,void 0,void 0,void 0,!0,this._configuration);this._updateInstanceFromProps(n,e),this._registry.execute("instanceStartFailed",n)},this.handleInstanceUpdated=e=>{const t=this._getInstanceId(e),i=this._getInstanceAppName(e),n=this._getInstanceOrThrow(t,i);this._updateInstanceFromProps(n,e)},this.onInstanceStarted=e=>(Kt(e,this._configuration()),this._registry.add("instanceStarted",e,this._instances)),this.onInstanceStartFailed=e=>(Kt(e,this._configuration()),this._registry.add("instanceStartFailed",e)),this.onInstanceStopped=e=>(Kt(e,this._configuration()),this._registry.add("instanceStopped",e)),this.onInstanceUpdated=e=>(Kt(e,this._configuration()),this._registry.add("instanceChanged",e)),this.onInstanceAgmServerReady=e=>(Kt(e,this._configuration()),this._registry.add("instanceAgmServerReady",e)),this.onAppAdded=e=>(Kt(e,this._configuration()),this._registry.add("appAdded",e,Object.values(this._apps))),this.onAppRemoved=e=>(Kt(e,this._configuration()),this._registry.add("appRemoved",e)),this.onAppAvailable=e=>(Kt(e,this._configuration()),this._registry.add("appAvailable",e)),this.onAppUnavailable=e=>(Kt(e,this._configuration()),this._registry.add("appUnavailable",e)),this.onAppChanged=e=>(Kt(e,this._configuration()),this._registry.add("appChanged",e))}_getAppOrThrow(e){const t=this.application(e);if(!t)throw Error(`app with id ${e} not found`);return t}_getAppId(e){return e.Name}_matchInstance(e,t,i){return e.id===t&&e.application.name===i}_getInstanceByIdAndName(e,t){return this._instances.filter((i=>this._matchInstance(i,e,t)))[0]}_getInstanceOrThrow(e,t){const i=this._getInstanceByIdAndName(e,t);if(!i)throw Error(`instance with id ${e} not found`);return i}_getInstanceId(e){return e.Id}_getInstanceAppName(e){return e.Name}_updateAppFromProps(e){const t=this._getAppId(e);this._logger.trace(`updating app with + ${t}, ${JSON.stringify(e)}`);const i=this._getAppOrThrow(t);return i.updateFromProps(e),i}_updateInstanceFromProps(e,t){this._logger.trace("updating instance with "+this._getInstanceId(t)+" for app "+this._getInstanceAppName(t)),e.updateFromProps(t)}}function Yt(e,t,i){const n=e=>!!(e&&e.constructor&&e.call&&e.apply);return n(t)||n(i)?(n(t)?n(i)||(i=()=>{}):t=()=>{},e.then(t,i)):e}class ei{constructor(e){this._agm=e,this._registry=Jt(),this._isMethodRegistered=!1,this.handleBranchModified=e=>{this._registry.execute("branchChanged",e)},this.handleBranchesModified=e=>{this._registry.execute("branchesChanged",e)},this.getRegion=(e,t)=>Yt(this._agmInvoke("T42.ACS.GetConfigurationRegion",(e=>e.returned.Region)),e,t),this.getBranches=(e,t)=>Yt(this._agmInvoke("T42.ACS.GetBranches",(e=>{const t=e.returned.Branches;return Object.keys(t).map((e=>t[e]))})),e,t),this.getCurrentBranch=(e,t)=>Yt(this._agmInvoke("T42.ACS.GetCurrentBranch",(e=>e.returned.Branch),void 0),e,t),this.setRegion=(e,t,i)=>Yt(this._agmInvoke("T42.ACS.SetConfigurationRegion",(e=>e.returned.ResultMessage),{Region:e}),t,i),this.setCurrentBranch=(e,t,i)=>Yt(this._agmInvoke("T42.ACS.SetCurrentBranch",(e=>e.returned.ResultMessage),{Branch:e}),t,i),this.currentUser=(e,t)=>Yt(this._agmInvoke("T42.ACS.GetUser"),e,t),this.getFunctionalEntitlement=(e,t,i)=>Yt(this._agmInvoke($t,(e=>e.returned.Entitlement),{Function:e}),t,i),this.getFunctionalEntitlementBranch=(e,t,i,n)=>Yt(this._agmInvoke($t,(e=>e.returned.Entitlement),{Function:e,Branch:t}),i,n),this.canI=(e,t,i)=>Yt(this._agmInvoke(Gt,(e=>e.returned.Result),{Function:e}),t,i),this.canIBranch=(e,t,i,n)=>Yt(this._agmInvoke(Gt,(e=>e.returned.Result),{Function:e,Branch:t}),i,n),this.onBranchesChanged=e=>this._registry.add("branchesChanged",e),this.onBranchChanged=e=>this._registry.add("branchChanged",e),this.exit=e=>this._agmInvoke("T42.ACS.Shutdown",null,e),this.onShuttingDown=e=>(this.registerMethod(),this._registry.add("onShuttingDown",e)),this.restart=e=>this._agmInvoke("T42.ACS.Restart",null,e),this._agmInvoke=(e,t,i)=>(i=i||{},new Promise(((n,s)=>{this._agm.invoke(e,i).then((e=>{t||(t=e=>e.returned),n(t(e))})).catch((e=>s(e)))})))}registerMethod(){this._isMethodRegistered||(this._agm.register("T42.ACS.OnGDShutdown",(async e=>{try{const t=await Promise.all(this._registry.execute("onShuttingDown",e));return{prevent:t.some((e=>e.prevent))}}catch(e){}})),this._isMethodRegistered=!0)}}const ti="T42.ACS.InMemoryStoreCommand";class ii{constructor(e){this.interop=e}import(e,t){if(!e||!Array.isArray(e))return Promise.reject("invalid apps argument - should be an array of application definitions");if(t&&"replace"!==t&&"merge"!==t)return Promise.reject("invalid mode argument - should be 'replace' or 'merge'");const i={command:"import",args:{apps:e,mode:t=null!=t?t:"replace"}};return this.interop.invoke(ti,i).then((e=>e.returned))}export(){return this.interop.invoke(ti,{command:"export"}).then((e=>e.returned.apps))}remove(e){if(!e||"string"!=typeof e)return Promise.reject("invalid app name, should be a string value");const t={command:"remove",args:{apps:[e]}};return this.interop.invoke(ti,t).then((e=>e.returned))}clear(){return this.interop.invoke(ti,{command:"clear"}).then((e=>e.returned))}createAppDef(e,t){return t||(t="https://google.com"),{name:e,type:"window",title:e,details:{url:t}}}}var ni=e=>{if(!e)throw Error("config not set");if(!e.agm)throw Error("config.agm is missing");const t="startOnly",i="skipIcons",n=e.mode||t;if(n!==t&&n!==i&&"full"!==n)throw new Error(`Invalid mode for appManager lib - ${n} is not supported`);const s=e.activities,r=e.agm,o=e.logger,a=e.windows;let c={};const d=new Xt(n,r,s,a,o.subLogger("applications"),e.gdMajorVersion,(()=>c)),h=new ei(r);let u;if(n===t)u=function(e,t){return new Promise(((i,n)=>{e.invoke(Ht,{skipIcon:!0}).then((e=>{var n;const s=e.returned,r=null!==(n=e.returned.configuration)&&void 0!==n?n:{};s||i(r);const o=s.applications;o||i(r),Vt(o).map((e=>t.handleAppAdded(e))),i(r)})).catch((e=>n(`Error getting application snapshot: ${e.message}`)))}))}(r,d);else{const e=function(e,t,i,n){let s,r=!1;return{start:()=>{let o,a;const c=new Promise(((e,t)=>{o=e,a=t}));return e.subscribe(Bt,{arguments:{skipIcon:n},waitTimeoutMs:1e4}).then((n=>{s=n,s.onData((n=>{var s;const a=n.data,c=null!==(s=a.configuration)&&void 0!==s?s:{},d=Vt(a.OnApplicationAdded);n.data.isSnapshot?t.handleSnapshotAppsAdded(d):d.forEach((e=>t.handleAppAdded(e))),Vt(a.OnApplicationChanged).forEach((e=>t.handleAppUpdated(e))),Vt(a.OnApplicationRemoved).forEach((e=>t.handleAppRemoved(e))),Vt(a.OnApplicationReady).forEach((e=>t.handleAppReady(e)));const h=Vt(a.OnApplicationStarted);if(n.data.isSnapshot?t.handleSnapshotInstanceStarted(h):h.forEach((e=>t.handleInstanceStarted(e))),Vt(a.OnApplicationStartFailed).forEach((e=>t.handleInstanceStartFailed(e))),Vt(a.OnApplicationStopped).forEach((e=>t.handleInstanceStopped(e))),Vt(a.OnApplicationUpdated).forEach((e=>t.handleInstanceUpdated(e))),Vt(a.OnApplicationAgmServerReady).forEach((e=>t.handleInstanceAgmServerReady(e))),Vt(a.OnBranchChanged).forEach((e=>i.handleBranchModified(e))),Vt(a.OnBranchesModified).forEach((e=>i.handleBranchesModified(e))),!r){r=!0;const i=d.some((t=>t.Name===e.instance.application)),n=h.some((t=>t.Id===e.instance.instance));if(i)if(n)o(c);else{const i=t.onInstanceStarted((t=>{t.id===e.instance.instance&&(i(),o(c))}))}else o(c)}})),s.onFailed((e=>a(e)))})).catch((e=>{var t;return a(`Error subscribing for ${Bt} stream. Err: ${null!==(t=e.message)&&void 0!==t?t:JSON.stringify(e)}`)})),c},stop:()=>{s&&s.close()}}}(r,d,h,n===i);u=e.start()}return{ready:()=>u.then((e=>{c=e})),applications:d.applications,application:d.application,getConfigurations:d.getConfigurations,onAppAdded:d.onAppAdded,onAppRemoved:d.onAppRemoved,onAppChanged:d.onAppChanged,onAppAvailable:d.onAppAvailable,onAppUnavailable:d.onAppUnavailable,instances:d.instances,get myInstance(){return d.getMyInstance()},get myApplication(){return d.getMyApplication()},onInstanceStarted:d.onInstanceStarted,onInstanceStopped:d.onInstanceStopped,onInstanceUpdated:d.onInstanceUpdated,onInstanceStartFailed:d.onInstanceStartFailed,getRegion:h.getRegion,getBranches:h.getBranches,getCurrentBranch:h.getCurrentBranch,getFunctionalEntitlement:h.getFunctionalEntitlement,getFunctionalEntitlementBranch:h.getFunctionalEntitlementBranch,setCurrentBranch:h.setCurrentBranch,setRegion:h.setRegion,currentUser:h.currentUser,canI:h.canI,canIBranch:h.canIBranch,onBranchesChanged:h.onBranchesChanged,exit:h.exit,restart:h.restart,onShuttingDown:h.onShuttingDown,inMemory:new ii(r)}};class si{static getGDMajorVersion(){if("undefined"==typeof window)return-1;if(!window.glueDesktop)return-1;if(!window.glueDesktop.version)return-1;const e=Number(window.glueDesktop.version.substr(0,1));return isNaN(e)?-1:e}static callbackifyPromise(e,t,i){const n=e=>{let t=e;if(e instanceof Error&&(t=e.message),"function"!=typeof i)return Promise.reject(t);i(t)};try{return e().then((e=>("function"==typeof t&&t(e),e))).catch((e=>n(e)))}catch(e){return n(e)}}static getMonitor(e,t){return t.map((t=>{const{left:i,top:n,workingAreaWidth:s,workingAreaHeight:r}=t;return{monitor:t,totalOverlap:this.calculateTotalOverlap({left:i,top:n,width:s,height:r},e)}})).sort(((e,t)=>t.totalOverlap-e.totalOverlap))[0].monitor}static getDisplayCenterOfScreen(e,t,i){const n=e.width/t.scaleFactor,s=e.height/t.scaleFactor,r=t.workArea.left/i.scaleFactor,o=t.workArea.top/i.scaleFactor,a=t.workArea.width/t.scaleFactor,c=t.workArea.height/t.scaleFactor,d=Math.max((a-n)/2,0),h=Math.max((c-s)/2,0),u=Math.floor(r+d),l=Math.floor(o+h);return{left:u*i.scaleFactor,top:l*i.scaleFactor,width:e.width,height:e.height}}static isNode(){if(void 0!==si._isNode)return si._isNode;if("undefined"!=typeof window)return si._isNode=!1,!1;try{si._isNode="[object process]"===Object.prototype.toString.call(global.process)}catch(e){si._isNode=!1}return si._isNode}static generateId(){return((e=21)=>{let t="",i=e;for(;i--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return t})(10)}static calculateTotalOverlap(e,t){const i=e.left,n=e.top,s=i+e.width,r=n+e.height,o=t.left,a=t.top,c=o+t.width,d=a+t.height;return Math.max(0,Math.min(s,c)-Math.max(i,o))*Math.max(0,Math.min(r,d)-Math.max(n,a))}}const ri="T42.JumpList.Action";var oi=new class{constructor(){this._groupActionCallbacks=new Map,this._registered=!1}init(e,t,i){this._executor=e,this._agm=t,this._logger=i,this.registerCallbackMethod()}setEnabled(e,t){const i={enabled:t};return this._executor.updateJumpList(e,i)}createCategory(e,t,i){this.validateActions(t,i);const n={category:{title:t,operation:"create",actions:this.toUpdateActions(e,"create",t,i)}};return this._executor.updateJumpList(e,n)}removeCategory(e,t){const i={category:{title:t,operation:"remove",actions:[]}};return this.manageActionCallback(e,i.category.operation,t),this._executor.updateJumpList(e,i)}createActions(e,t,i){this.validateActions(t,i);const n={category:{title:t,operation:"update",actions:this.toUpdateActions(e,"create",t,i)}};return this._executor.updateJumpList(e,n)}removeActions(e,t,i){const n={category:{title:t,operation:"update",actions:this.toUpdateActions(e,"remove",t,i)}};return this._executor.updateJumpList(e,n)}async getActions(e,t){const i=[],n=(await this.getJumpListSettings(e)).categories.find((e=>e.title===t));return n&&n.actions.forEach((e=>{const t=this.getActionCallback(e.callbackId);t&&(e.callback=t.callback),i.push({icon:e.icon,callback:e.callback,singleInstanceTitle:e.singleInstanceTitle,multiInstanceTitle:e.multiInstanceTitle})})),Promise.resolve(i)}getJumpListSettings(e){return this._executor.getJumpList(e)}toUpdateActions(e,t,i,n){return n.map((n=>{const s={icon:n.icon,callback:n.callback,callbackId:si.generateId(),singleInstanceTitle:n.singleInstanceTitle,multiInstanceTitle:n.multiInstanceTitle,operation:t};return this.manageActionCallback(e,t,i,s),s}))}manageActionCallback(e,t,i,n){var s;const r=`${i}-${e}`;if("create"===t){this._groupActionCallbacks.has(r)||this._groupActionCallbacks.set(r,[]);this._groupActionCallbacks.get(r).push({callbackId:n.callbackId,callback:n.callback})}else if("remove"===t)if(n){let e=null!==(s=this._groupActionCallbacks.get(r))&&void 0!==s?s:[];e=e.filter((e=>e.callbackId!==n.callbackId)),0===e.length?this._groupActionCallbacks.delete(r):this._groupActionCallbacks.set(r,e)}else this._groupActionCallbacks.delete(r)}registerCallbackMethod(){if(!this._registered){this._registered=!0;try{this._agm.register(ri,((e,t)=>{const i=this.getActionCallback(e.callbackId);if(i)try{i.callback()}catch(e){this._logger.error("Unable to execute user callback for jump list action!",e)}}))}catch(e){return this._logger.error(`Unable to register method ${ri} for invoking jump list action callbacks!`,e),Promise.reject(e)}}}getActionCallback(e){let t;return[...this._groupActionCallbacks.values()].forEach((i=>{const n=i.find((t=>t.callbackId===e));n&&(t=n)})),t}validateActions(e,t){if(!(t&&t.length>0))throw new Error(`Category '${e}' doesn't contain any actions!`);t.forEach((t=>{if(!t.singleInstanceTitle)throw new Error(`Category '${e}' contains an action with undefined singleInstanceTitle!`);if(!t.multiInstanceTitle)throw new Error(`Category '${e}' contains an action with undefined multiInstanceTitle!`);if(!t.callback)throw new Error(`Category '${e}' contains an action with undefined callback function!`)}))}};var ai=new class{constructor(){this.waitForTimeoutInMilliseconds=6e4,this._windows={},this._pendingWindows={},this._pendingWindowsStates={},this._registry=Jt()}init(e){this._logger=e}get(e){return this._windows[e]||this._pendingWindows[e]}getIfReady(e){return this._windows[e]}get list(){return this._windows}add(e){if(!!this._pendingWindows[e.API.id])return void this._logger.error(`trying to add window with id ${e.API.id} from windowStore, which already exists`);const t="remote"===e.API.windowType;this._pendingWindows[e.API.id]=e,this._pendingWindowsStates[e.API.id]={ready:!1,urlChanged:t},this._registry.execute("on-added",e)}remove(e){delete this._windows[e.API.id],delete this._pendingWindows[e.API.id],delete this._pendingWindowsStates[e.API.id],this._registry.execute("on-removed",e)}setReadyState(e){const t=this._pendingWindowsStates[e];void 0!==t&&(t.ready=!0,t.urlChanged&&this.markReadyToShow(e))}setUrlChangedState(e){const t=this._pendingWindowsStates[e];void 0!==t&&(t.urlChanged=!0,t.ready&&this.markReadyToShow(e))}setCompositionChangedState(e,t){void 0!==this._pendingWindowsStates[e]&&!1===t&&this.markReadyToShow(e)}waitFor(e){return new Promise(((t,i)=>{let n,s;const r=setTimeout((()=>{n(),s(),i(`Window with id "${e}" was not ready within ${this.waitForTimeoutInMilliseconds} milliseconds.`)}),this.waitForTimeoutInMilliseconds),o=this._windows[e];if(o)clearTimeout(r),t(o);else{const o=()=>{clearTimeout(r),n(),s()};n=this.onReadyWindow((i=>{i.API.id===e&&(o(),t(i))})),s=this.onRemoved((t=>{t.API.id===e&&(o(),i(`Window with id "${e}" was removed before it became ready.`))}))}}))}onReadyWindow(e){return this._registry.add("on-ready",e)}onAdded(e){return this._registry.add("on-added",e)}onRemoved(e){return this._registry.add("on-removed",e)}markReadyToShow(e){this._pendingWindows[e]&&(this._windows[e]=this._pendingWindows[e],delete this._pendingWindows[e],delete this._pendingWindowsStates[e]),this._registry.execute("on-ready",this._windows[e])}};class ci{constructor(e,t){this.windowId=e,this._categoryTitle=t.title}list(){return oi.getActions(this.windowId,this._categoryTitle)}create(e){return oi.createActions(this.windowId,this._categoryTitle,e)}remove(e){return oi.removeActions(this.windowId,this._categoryTitle,e)}}class di{constructor(e){this.windowId=e}list(){return this.getCategories()}create(e,t){return oi.createCategory(this.windowId,e,t)}remove(e){return oi.removeCategory(this.windowId,e)}async find(e){return(await this.getCategories()).find((t=>t.title===e))}async getCategories(){const e=[];return(await oi.getJumpListSettings(this.windowId)).categories.forEach((t=>{e.push({title:t.title,actions:new ci(this.windowId,t)})})),e}}class hi{constructor(e){this.windowId=e,this._categories=new di(e)}get categories(){return this._categories}async isEnabled(){return(await oi.getJumpListSettings(this.windowId)).enabled}setEnabled(e){return oi.setEnabled(this.windowId,e)}}var ui=(e,t,i,n,s,r,o,a)=>{var c,d,h,u;const l=Jt(),p=()=>{const e=o();if(!e)throw new Error("To use this method you need to enable channels API - set the channels property to true when initializing the Glue42 library");return e},g=e,m=t.name,f=t.mode;let y=t.bounds,w=t.url,v=t.title,b=null!==(c=t.context)&&void 0!==c?c:{},_=t.frameColor,I=t.focus,C=null!==(d=t.neighbours)&&void 0!==d?d:{},A=t.groupId,S=t.isGroupHeaderVisible,x=t.isTabHeaderVisible,k=t.isGroupHibernated,T=t.isGroupVisible,E=null!==(h=t.isTabSelected)&&void 0!==h&&h,P=t.settings;const M=t.applicationName;let R,N=t.isVisible,j=t.isSticky,W=t.isCollapsed,O=t.state,F=t.tabGroupId,D=t.tabIndex,L=t.frameId,$=t.isLocked,G=t.allowWorkspaceDrop,B=t.isPinned,H=null!==(u=t.frameButtons)&&void 0!==u?u:[],U=t.zoomFactor,q=t.placementSettings;const J=new hi(e);function V(e,t,n){return si.callbackifyPromise((()=>{if(Ze(e))throw new Error("The properties of `bounds` cannot be null or undefined.");return i.moveResize(ee,e)}),t,n)}function z(e,t,n){return si.callbackifyPromise((()=>i.setVisible(ee,e)),t,n)}function K(e){return Q("group-changed",e)}function Q(e,t,i){if(!et(t))throw new Error("callback must be a function");return l.add(e,t,i)}function Z(e){const t=C[e];if(void 0!==t)return t.reduce(((e,t)=>{const i=ai.get(t);return i&&e.push(i.API),e}),[])}function X(){var t;if(M)return M;if(b._APPLICATION_NAME)return b._APPLICATION_NAME;if(b&&b._t42&&b._t42.application)return b._t42.application;const i=Y();if(i&&i.applicationName)return i.applicationName;const n=s();if(n){const i=n.instances().find((t=>e===t.id));if(i)return null===(t=i.application)||void 0===t?void 0:t.name}}function Y(){if("undefined"!=typeof window&&window.glue42gd&&window.glue42gd.getWindowInfo){const t=window.glue42gd.getWindowInfo(e);return t||void 0}}const ee={get id(){return g},get name(){return m},get application(){const e=s(),t=X();if(t&&e)return e.application(t)},get hostInstance(){return i.hostInstance},get interopInstance(){const e=a.servers().find((e=>e.windowId===this.id));if(e)return e;{const e=X();if(e)return{application:e}}},get agmInstance(){return ee.interopInstance},get url(){return w},get title(){return v},get windowStyleAttributes(){return P},get settings(){return P},get tabGroupId(){return"tab"===f.toLowerCase()?F:void 0},get tabIndex(){return"tab"===f.toLowerCase()?D:void 0},get frameId(){return L},get frameButtons(){return H.sort(((e,t)=>e.order-t.order))},get mode(){return f},get state(){return O},get isCollapsed(){return W},get isVisible(){return N},get isLocked(){return $},get context(){return b},get bounds(){return y},get minHeight(){return P.minHeight},get maxHeight(){return P.maxHeight},get minWidth(){return P.minWidth},get maxWidth(){return P.maxWidth},get isFocused(){return I},get frameColor(){return _},get opened(){return void 0!==ee.id},get group(){return R},get groupId(){return A},get isSticky(){return j},get topNeighbours(){return Z("top")},get leftNeighbours(){return Z("left")},get rightNeighbours(){return Z("right")},get bottomNeighbours(){return Z("bottom")},get isGroupHeaderVisible(){return S},get activityId(){if(b._t42)return b._t42.activityId;const e=Y();return e?e.activityId:void 0},get activityWindowId(){if(b._t42)return b._t42.activityWindowId;const e=Y();return e?e.activityWindowId:void 0},get windowType(){return t.windowType||"electron"},get zoomFactor(){return U},get screen(){if("undefined"!=typeof window&&window.glue42gd)return si.getMonitor(ee.bounds,window.glue42gd.monitors)},get placementSettings(){return Object.assign({},q)},get jumpList(){return J},get allowWorkspaceDrop(){return G},get isPinned(){return B},maximize:function(e,t){return si.callbackifyPromise((()=>"maximized"===O?Promise.resolve(ee):i.maximize(ee)),e,t)},restore:function(e,t){return si.callbackifyPromise((()=>"normal"===O?Promise.resolve(ee):i.restore(ee)),e,t)},minimize:function(e,t){return si.callbackifyPromise((()=>"minimized"===O?Promise.resolve(ee):i.minimize(ee)),e,t)},maximizeRestore:function(e,t){return si.callbackifyPromise((()=>i.maximizeRestore(ee)),e,t)},collapse:function(e,t){return si.callbackifyPromise((()=>W?Promise.resolve(ee):i.collapse(ee)),e,t)},expand:function(e,t){return si.callbackifyPromise((()=>W?i.expand(ee):Promise.resolve(ee)),e,t)},toggleCollapse:function(e,t){return si.callbackifyPromise((()=>i.toggleCollapse(ee)),e,t)},focus:function(e,t){return si.callbackifyPromise((()=>I?Promise.resolve(ee):i.focus(ee)),e,t)},activate:function(e,t){return si.callbackifyPromise((()=>I?Promise.resolve(ee):i.activate(ee)),e,t)},moveResize:V,setTitle:function(e,t,n){return si.callbackifyPromise((()=>{if(Ze(e))throw new Error("`newTitle` must not be null or undefined.");return e===v?Promise.resolve(ee):i.setTitle(ee,e)}),t,n)},setStyle:function(e,t,n){return si.callbackifyPromise((()=>{if(!e||0===Object.keys(e).length||Object.keys(e).every((e=>!e)))throw new Error("Invalid style arguments: "+JSON.stringify(e));if(e&&void 0!==e.focus){if("boolean"!=typeof e.focus)throw new Error("Focus must be a boolean value. Currently, only `focus: true` is supported.");!1===e.focus&&console.warn("`focus: false` is not supported!")}if(e&&void 0!==e.hidden&&"boolean"!=typeof e.hidden)throw new Error("The `hidden` property must hold a boolean value.");for(const t of["minHeight","maxHeight","minWidth","maxWidth"]){const i=e,n=i[t];if(t in e){if(Ze(n)){delete i[t];continue}if(!Je(i[t]))throw new Error(`"${t}" must be a number`)}}return i.setStyle(ee,e)}),t,n)},setOnTop:function(e,t,n){return si.callbackifyPromise((()=>{if("string"==typeof e){if("always"!==e)throw new Error("`onTop` must hold a `always` value.")}else if("boolean"!=typeof e)throw new Error("`onTop` must hold a boolean or `always` value.");return i.setOnTop(ee,e)}),t,n)},resetButtons:function(e,t,n){return si.callbackifyPromise((()=>i.resetButtons(ee,e)),t,n)},getButtons:function(){return i.getButtons(ee)},setSizeConstraints:function(e,t,n){return si.callbackifyPromise((()=>{if(!e||Object.keys(e).every((e=>void 0===e)))throw new Error("The properties of `constraints` cannot be null or undefined.");return i.setSizeConstraints(ee,e)}),t,n)},getSizeConstraints:function(){return i.getSizeConstraints(ee)},navigate:function(e,t,n){if("function"==typeof t)return si.callbackifyPromise((()=>{if(Xe(e))throw new Error("The new URL must be a non-empty string.");return i.navigate(ee,e)}),t,n);if(Xe(e))throw new Error("The new URL must be a non-empty string.");return i.navigate(ee,e,t)},addFrameButton:function(e,t,n){return si.callbackifyPromise((()=>{if(void 0===e||0===Object.keys(e).length)throw new Error("Button info is not available.");if(Xe(e.buttonId))throw new Error("`buttonId` must not be null or undefined.");if(Xe(e.imageBase64))throw new Error("`imageBase64` must not be null or undefined.");return i.addFrameButton(ee,e)}),t,n)},removeFrameButton:function(e,t,n){return si.callbackifyPromise((()=>{if(Xe(e))throw new Error("`buttonId` must not be null or undefined.");return i.removeFrameButton(ee,e)}),t,n)},setVisible:z,show:()=>z(!0),hide:()=>z(!1),center:async function(e){return e&&function(e){if("object"!=typeof e)throw Error("display argument must be a valid display object");if(!e.workArea||!e.scaleFactor)throw Error("display argument is not a valid display object")}(e),i.center(ee,e)},close:function(t,n){return void 0===t||"function"==typeof t?si.callbackifyPromise((()=>{if(!e)throw new Error("The window is already closed.");return i.close(ee)}),t,n):i.close(ee,t)},snap:function(e,t,n,s){return si.callbackifyPromise((()=>{if(Ze(e))throw new Error(`A target window is not specified - ${"string"==typeof e?e:JSON.stringify(e)}`);if("string"==typeof e){const t=ai.get(e);if(!t)throw new Error(`Invalid "target" parameter or no such window. Invoked with: ${e}`);e=t.API}return"string"==typeof t&&(t={direction:t,autoAlign:!0}),i.snap(ee,e,t)}),n,s)},showLoader:function(e){return i.showLoader(ee,e)},hideLoader:function(){return i.hideLoader(ee)},updateContext:function(e,t,n){return si.callbackifyPromise((()=>{if(Ze(e))throw new Error('"context" must not be null or undefined.');return i.updateContext(ee,e,!1)}),t,n)},lock:function(e,t){return si.callbackifyPromise((()=>i.lock(ee)),e,t)},unlock:function(e,t){return si.callbackifyPromise((()=>i.unlock(ee)),e,t)},getIcon:function(e,t){return si.callbackifyPromise((()=>i.getIcon(ee)),e,t)},setIcon:function(e,t,n){return si.callbackifyPromise((()=>{if(Xe(e))throw new Error('"base64Image" must be a non-empty string.');return i.setIcon(ee,e)}),t,n)},setFrameColor:function(e,t,n){return si.callbackifyPromise((()=>{if(Xe(e))throw new Error('"frameColor" must be a non-empty string');return i.setFrameColor(ee,e)}),t,n)},setTabTooltip:async function(e){if(Xe(e))throw new Error(`"${e}" must not be null or undefined`);return i.setTabTooltip(ee,e)},getTabTooltip:async function(){return i.getTabTooltip(ee)},attachTab:function(e,t,n,s){return si.callbackifyPromise((()=>{var n;const s='Invalid "tab" parameter - must be an object with an "id" property or a string. Invoked for source window with ID:';if(Ze(e)){const t=`${s} ${"string"==typeof e?e:JSON.stringify(e)}`;throw new Error(t)}let r;if("string"==typeof e){if(r=null===(n=ai.get(e))||void 0===n?void 0:n.API,Ze(r)){const e=`${s} ${"string"==typeof r?r:JSON.stringify(r)}`;throw new Error(e)}}else{if(Ze(e.id))throw new Error(s);r=e}const o={};return Ze(t)||("number"==typeof t?o.index=t:(o.selected=t.selected,o.index=t.index)),i.attachTab(ee,r,o)}),n,s)},detachTab:function(e={},t,n){return si.callbackifyPromise((()=>{const t={};return void 0!==e.relativeTo?("string"==typeof e.relativeTo?t.relativeTo=e.relativeTo:Ze(e.relativeTo.id)||(t.relativeTo=e.relativeTo.id),Ze(e.relativeDirection)||(t.relativeDirection=e.relativeDirection),Ze(e.width)||(t.width=e.width),Ze(e.height)||(t.height=e.height)):Ze(e.bounds)||(t.bounds=e.bounds),Ze(e.hideTabHeader)||(t.hideTabHeader=e.hideTabHeader),i.detachTab(ee,t)}),t,n)},setTabHeaderVisible:function(e,t,n){return si.callbackifyPromise((()=>{if("boolean"!=typeof e)throw new Error('"toBeTabHeaderVisible" must hold a boolean value.');return i.setTabHeaderVisible(ee,e)}),t,n)},showPopup:function(e){return i.showPopup(ee,e)},createFlydown:function(e){return i.createFlydown(ee.id,e)},setModalState:function(e){return i.setModalState(ee.id,e||!1)},setZoomFactor:function(e,t,n){return si.callbackifyPromise((()=>{if(isNaN(e))throw new Error("zoomFactor is not a number");return i.setZoomFactor(ee,e)}),t,n)},zoomIn:function(e,t){return si.callbackifyPromise((()=>i.zoomIn(ee)),e,t)},zoomOut:function(e,t){return si.callbackifyPromise((()=>i.zoomOut(ee)),e,t)},showDevTools:function(){return i.showDevTools(ee)},capture:function(e){return i.capture(ee,e)},flash:function(e,t){const n={shouldFlash:!0,mode:"auto"};return"boolean"==typeof e&&(n.shouldFlash=e),void 0!==t&&(n.mode=t),i.flash(ee,n)},flashTab:function(e){const t={shouldFlash:!0};return"boolean"==typeof e&&(t.shouldFlash=e),i.flashTab(ee,t)},setSticky:function(e,t,n){return si.callbackifyPromise((()=>{if("boolean"!=typeof e)throw new Error("`isSticky` must hold a boolean value.");return i.setSticky(ee,e)}),t,n)},setAllowWorkspaceDrop:function(e){if("boolean"!=typeof e)throw new Error("`allowWorkspaceDrop` must hold a boolean value.");return i.setAllowWorkspaceDrop(ee,e)},pin:function(){return i.pin(ee)},unpin:function(){return i.unpin(ee)},print:function(e){return i.print(ee,e)},printToPDF:function(e){return i.printToPDF(ee,e)},place:function(e){return i.place(ee,e)},ungroup:function(t){return new Promise(((n,s)=>{const r=K(((t,i,s)=>{e===t.id&&(r(),n(ee))}));i.ungroup(ee,t).catch((e=>{r(),s(e)}))}))},refresh:function(e){return i.refresh(ee,e)},goBack:function(){return i.goBack(ee)},goForward:function(){return i.goForward(ee)},download:function(e,t){return i.download(ee,e,t)},configure:function(e){return i.configureWindow(ee,e)},getConfiguration:function(){return i.getWindowConfiguration(ee)},getDockingPlacement:function(){return i.getDockingPlacement(ee)},dock:function(e){return i.dock(ee,e)},clone:async function(e){return i.clone(ee,e)},executeCode:async function(e){if(!e)throw new Error("Code argument is missing");if("string"!=typeof e)throw new Error("Code argument must be a valid string");return(await i.executeCode(ee,e)).result},getChannel:async()=>{var e;return null===(e=(await p().getWindowsWithChannels({windowIds:[g]}))[0])||void 0===e?void 0:e.channel},startDrag:function(e){return i.startDrag(ee,e)},showDialog:function(e){if((null==e?void 0:e.timerDuration)&&isNaN(null==e?void 0:e.timerDuration))throw new Error("timerDuration must be a number");if((null==e?void 0:e.showTimer)&&"boolean"!=typeof(null==e?void 0:e.showTimer))throw new Error("showTimer must be a boolean");return i.showDialog(ee,e)},onClose:function(t){if(!et(t))throw new Error("callback should be a function");return void 0===e&&t(ee),l.add("onClose",t)},onUrlChanged:function(e){return Q("onUrlChanged",e)},onTitleChanged:function(e){if(!et(e))throw new Error("callback should be a function");return e(ee.title,ee),Q("onTitleChanged",e)},onFrameButtonAdded:function(e){return Q("onFrameButtonAdded",e)},onFrameButtonRemoved:function(e){return Q("onFrameButtonRemoved",e)},onFrameButtonClicked:function(e){return Q("onFrameButtonClicked",e)},onCollapsed:function(e){if(!et(e))throw new Error("callback should be a function");return W&&e(ee),l.add("collapsed",e)},onExpanded:function(e){if(!et(e))throw new Error("callback should be a function");return W||e(ee),l.add("expanded",e)},onMinimized:function(e){return"minimized"===O?Q("minimized",e,[ee]):Q("minimized",e)},onMaximized:function(e){return"maximized"===O?Q("maximized",e,[ee]):Q("maximized",e)},onNormal:function(e){return"normal"===O?Q("normal",e,[ee]):Q("normal",e)},onAttached:function(e){return Q("attached",e)},onDetached:function(e){return Q("detached",e)},onVisibilityChanged:function(e){return Q("visibility-changed",e)},onContextUpdated:function(e){return Q("context-updated",e)},onLockingChanged:function(e){return Q("lock-changed",e)},onBoundsChanged:function(e){return Q("bounds-changed",e)},onFrameColorChanged:function(e){return Q("frame-color-changed",e)},onFocusChanged:function(e){return Q("focus-changed",e)},onStickyChanged:function(e){return Q("sticky-changed",e)},onGroupChanged:K,onWindowAttached:function(e){return Q("window-attached",e)},onWindowDetached:function(e){return Q("window-detached",e)},onTabSelectionChanged:function(e){return Q("tab-selection-changed",e)},onTabHeaderVisibilityChanged:function(e){return Q("tab-header-visibility-changed",e)},onClosing:function(e){if(!et(e))throw new Error("callback must be a function");return i.onClosing(((t,i,n)=>{const s=e(n);(null==s?void 0:s.then)?s.then(t).catch(i):t()}),ee)},onRefreshing:function(e){if(!et(e))throw new Error("callback must be a function");return i.onRefreshing(((t,i,n)=>{const s=e(n);(null==s?void 0:s.then)?s.then(t).catch(i):t()}),ee)},onZoomFactorChanged:function(e){return Q("zoom-factor-changed",e)},onPlacementSettingsChanged:function(e){return Q("placementSettingsChanged",e)},onNeighboursChanged:function(e){return Q("neighbours-changed",e)},onDockingChanged:function(e){return Q("docking-changed",e)},onNavigating:function(e){if(!et(e))throw new Error("callback must be a function");return i.onNavigating(((t,i,n,s)=>{const r=e(s);(null==r?void 0:r.then)?r.then(t).catch(i):t()}),ee)},onChannelRestrictionsChanged:function(e){if(!et(e))throw new Error("callback must be a function");return Q("channel-restrictions-changed",e)},get tabs(){return function(){const e=ai.list;return"tab"!==f.toLowerCase()?[]:Object.keys(e).reduce(((t,i)=>{const n=e[i];return n&&n.API.tabGroupId&&void 0!==n.API.tabGroupId&&void 0!==ee.tabGroupId&&n.API.tabGroupId===ee.tabGroupId&&t.push(n.API),t}),[]).sort(((e,t)=>{if(e.tabIndex!==t.tabIndex){if(-1===e.tabIndex)return Number.MAX_SAFE_INTEGER;if(-1===t.tabIndex)return Number.MIN_SAFE_INTEGER}return e.tabIndex-t.tabIndex}))}()},get isTabHeaderVisible(){return x},get isTabSelected(){return E},getURL:()=>Promise.resolve(w),getTitle:()=>Promise.resolve(v),getBounds:()=>Promise.resolve(y),getContext:()=>Promise.resolve(b),setContext(e){if(Ze(e))throw new Error('"context" must not be null or undefined, set to empty object if you want to clear it out.');return i.updateContext(ee,e,!0)},getDisplay:()=>r().getByWindowId(e),resizeTo:(e,t)=>V({width:e,height:t}),moveTo:(e,t)=>V({top:e,left:t}),async getParentWindow(){var e;const t=P.parentInstanceId;if(t)return null===(e=ai.list[t])||void 0===e?void 0:e.API},getChildWindows:async()=>Object.keys(ai.list).map((e=>ai.list[e].API)).filter((t=>t.settings.parentInstanceId===e)),joinChannel:t=>p().join(t,e),leaveChannel:()=>p().leave(e)};return{API:ee,Events:{handleUpdate:function(e){w=e.url,v=e.title,b=e.context||{},y=e.bounds,_=e.frameColor,I=e.focus,C=e.neighbours||{},A=e.groupId,S=e.isGroupHeaderVisible,x=e.isTabHeaderVisible,k=e.isGroupHibernated,T=e.isGroupVisible,E=e.isTabSelected,P=e.settings,N=e.isVisible,j=e.isSticky,W=e.isCollapsed,O=e.state,F=e.tabGroupId,L=e.frameId,$=e.isLocked,G=e.allowWorkspaceDrop,B=e.isPinned,U=e.zoomFactor,q=e.placementSettings},handleWindowClose:function(){void 0!==e&&(l.execute("onClose",ee),e=void 0)},handleWindowChangeState:async function(e){"collapsed"===e?W=!0:"expanded"===e?W=!1:O=e,await i.finished,l.execute(e,ee)},handleTitleChanged:function(e){v=e,i.finished.finally((()=>{l.execute("onTitleChanged",e,ee)}))},handleVisibilityChanged:function(e){e!==N&&(N=e,l.execute("visibility-changed",ee))},handleUrlChanged:function(e){w=e,l.execute("onUrlChanged",e,ee)},handleWindowSettingsChanged:function(e){P=e,l.execute("settings-changed",ee)},handleContextUpdated:function(e){b=e,l.execute("context-updated",b,ee)},handleFrameIsLockedChanged:function(e){$=e,l.execute("lock-changed",ee)},handleBoundsChanged:function(e){y.top===e.top&&y.left===e.left&&y.width===e.width&&y.height===e.height||(y=e,l.execute("bounds-changed",ee))},handleFocusChanged:function(e){I=e,l.execute("focus-changed",ee)},handleFrameButtonAdded:function(e){const t=["buttonId","imageBase64","order","tooltip"].reduce(((t,i)=>(t[i]=e[i],t)),{});-1===H.map((e=>e.buttonId)).indexOf(e.buttonId)&&H.push(t),l.execute("onFrameButtonAdded",t,ee)},handleFrameButtonRemoved:function(e){let t;H=H.reduce(((i,n)=>(n.buttonId===e?t=n:i.push(n),i)),[]),void 0!==t&&l.execute("onFrameButtonRemoved",t,ee)},handleFrameButtonClicked:function(e){const t=H.filter((t=>t.buttonId===e.buttonId));t.length>0&&l.execute("onFrameButtonClicked",t[0],ee)},handleFrameColorChanged:function(e){_=e,l.execute("frame-color-changed",ee)},handleFrameAttached:function(e,t,i){F=e,L=t,x=i,l.execute("frame-attached",ee)},handleFrameSelectionChanged:async function(t,n){let s;t===e?(E=!0,s=ee):(E=!1,s=ai.get(t)?ai.get(t).API:void 0);const r=ai.get(n)?ai.get(n).API:void 0;await i.finished,l.execute("tab-selection-changed",s,r,ee)},handleCompositionChanged:function(e){C=e.neighbors||{},D=e.index,l.execute("neighbours-changed",C,ee)},handleAllowWorkspaceDropChanged:function(e){G=e,l.execute("allow-workspace-drop-changed",ee)},handleIsPinnedChanged:function(e){B=e,l.execute("is-pinned-changed",ee)},handleGroupHeaderVisibilityChanged:function(e){S=e},handleTabHeaderVisibilityChanged:function(e){x!==e&&(x=e,l.execute("tab-header-visibility-changed",ee))},handleGroupChanged:function(e,t){R=e,A=null==e?void 0:e.id,Ze(e)||Ze(t)||l.execute("group-changed",ee,e,t)},handleAttached:async function(e,t,n,s,r){F=e,x=n,L=t,void 0!==s&&($=s),await i.finished,r.forEach((e=>{e.Events.handleWindowAttached(ee)})),l.execute("attached",ee)},handleDetached:async function(e,t){F=void 0,E=!1,void 0!==e&&($=e),await i.finished,t.forEach((e=>{e.Events.handleWindowDetached(ee)})),l.execute("detached",ee)},handleWindowAttached:function(e){l.execute("window-attached",e)},handleWindowDetached:function(e){l.execute("window-detached",e)},handleZoomFactorChanged:function(e){U=e,l.execute("zoom-factor-changed",ee)},handleIsStickyChanged:function(e){j=e,l.execute("sticky-changed",e,ee)},handlePlacementSettingsChanged:function(e){let t;const i=e;if(i.display){const e=r();if(e){const n=i.display-1;t=new Promise(((t,i)=>{e.all().then((e=>{const i=e.find((e=>e.index===n));t(i)})).catch(i)}))}else t=Promise.resolve(void 0)}else t=Promise.resolve(void 0);t.then((e=>{i.display=e,q=i,l.execute("placementSettingsChanged",ee)}))},handleDockingChanged:function(e){l.execute("docking-changed",ee,{docked:e.docked,position:e.position,claimScreenArea:e.claimScreenArea})},handleChannelRestrictionsChanged:function(e){l.execute("channel-restrictions-changed",e)}},GroupCreationArgs:{get isGroupHibernated(){return k},get isGroupVisible(){return T}}}};function li(e,t){const i=ai.list;return Object.keys(i).reduce(((n,s)=>{const r=i[s];return r.API.tabGroupId===t&&r.API.id!==e&&n.push(r),n}),[])}function pi(e){return!(e&&!Object.keys(e).every((t=>void 0===e[t])))}var gi=new class{constructor(){this.GroupMethodName="T42.Group.Execute",this.WndMethodName="T42.Wnd.Execute",this._registry=Jt(),this._finished=Promise.resolve(),this.unsubCallbacks={}}get hostInstance(){return this.agmTarget}get finished(){return this._finished}get configuration(){return this._configuration}init(e,t){this.agm=e,this.agmTarget=t,this._registry.add("event",(e=>{if("Closed"===e.type){Object.keys(this.unsubCallbacks).forEach((t=>{t.startsWith(e.windowId)&&delete this.unsubCallbacks[t]}))}}))}setConfiguration(e){this._configuration=e}handleEvent(e){this._registry.execute("event",e)}async open(e){let t;this._finished=new Promise((e=>{t=e}));try{const t=await this.agm.invoke("T42.Wnd.Create",e,this.agmTarget);if(void 0===t.returned)throw new Error("failed to execute T42.Wnd.Create - unknown reason");const i=t.returned.id,n=await ai.waitFor(i);return this.configuration&&!this.configuration.windowAvailableOnURLChanged||setTimeout((()=>{"electron"===n.API.windowType&&n.Events.handleUrlChanged(n.API.url)}),0),n.API}finally{t()}}async close(e,t){const i=await this.execute("close",{windowId:e.id,options:t},"Closed");return t?i.closed:e}async navigate(e,t,i){return await this.execute("navigate",{windowId:e.id,options:{url:t,urlLoadOptions:i}},"UrlChanged"),e}async setStyle(e,t){var i;const n=[],s=e=>n.push(e);if(Ze(t.focus)||e.isFocused||s(e.focus()),!Ze(t.hidden)){const i=!t.hidden;s(e.setVisible(i))}if(Ze(t.onTop)||s(e.setOnTop(t.onTop)),!Xe(t.tabTooltip)||!Xe(t.tabToolTip)){const n=null!==(i=t.tabTooltip)&&void 0!==i?i:t.tabToolTip;s(e.setTabTooltip(n))}Xe(t.tabTitle)||s(this.execute("setTabTitle",{windowId:e.id,options:{tabTitle:t.tabTitle}}));const r={minHeight:t.minHeight,minWidth:t.minWidth,maxHeight:t.maxHeight,maxWidth:t.maxWidth};!pi(r)&&s(e.setSizeConstraints(r));const o={allowClose:t.allowClose,allowCollapse:t.allowCollapse,allowLockUnlock:t.allowLockUnlock,allowMaximize:t.allowMaximize,allowMinimize:t.allowMinimize};return!pi(o)&&s(e.resetButtons(o)),await Promise.all(n),e}async setSizeConstraints(e,t){return await this.execute("setSizeConstraints",{windowId:e.id,options:t}),e}async getSizeConstraints(e){return await this.execute("getSizeConstraints",{windowId:e.id})}async setTabTooltip(e,t){return await this.execute("setTabTooltip",{windowId:e.id,options:{tabTooltip:t}}),e}async getTabTooltip(e){return(await this.execute("getTabTooltip",{windowId:e.id})).tabTooltip}async resetButtons(e,t){return await this.execute("resetButtons",{windowId:e.id,options:t}),e}async getButtons(e){return await this.execute("getButtons",{windowId:e.id})}async setOnTop(e,t){return await this.execute("setOnTop",{windowId:e.id,options:{onTop:t}}),e}async setTitle(e,t){const i={windowId:e.id,options:{title:t}};return await this.execute("setTitle",i,"TitleChanged"),e}async setSticky(e,t){const i={windowId:e.id,options:{isSticky:t}};return await this.execute("setSticky",i),e}async setAllowWorkspaceDrop(e,t){const i={windowId:e.id,options:{allowWorkspaceDrop:t}};return await this.execute("setAllowWorkspaceDrop",i),e}async pin(e){const t={windowId:e.id};return await this.execute("pinTab",t),e}async unpin(e){const t={windowId:e.id};return await this.execute("unpinTab",t),e}async moveResize(e,t){return"undefined"!=typeof window&&window.glueDesktop.versionNum<31200?new Promise((async(i,n)=>{const s=this.areBoundsEqual(t,e);let r=!1;const o=()=>{r||(r=!0,c&&(c(),c=void 0),i(e),a&&(clearTimeout(a),a=void 0))};let a,c;s||(c=e.onBoundsChanged((e=>{this.areBoundsEqual(t,e)&&o()})));try{await this.execute("moveResize",{windowId:e.id,options:{bounds:t}})}catch(e){return void n(e)}s?o():a=setTimeout((()=>{o()}),1e3)})):(await this.execute("moveResize",{windowId:e.id,options:{bounds:t}}),e)}async addFrameButton(e,t){return await this.execute("addButton",{windowId:e.id,options:t},"ButtonAdded"),e}async removeFrameButton(e,t){return await this.execute("removeButton",{windowId:e.id,options:t},"ButtonRemoved"),e}async activate(e){let t,i;try{const n=new Promise(((n,s)=>{t=e.onFocusChanged((()=>{n()})),i=e.onClose((()=>{s(new Error("Window was closed"))}))}));return await Promise.all([this.execute("activate",{windowId:e.id},"FocusChanged"),n]),e}finally{t&&t(),i&&i()}}async focus(e){let t,i;try{const n=new Promise(((n,s)=>{t=e.onFocusChanged((()=>{n()})),i=e.onClose((()=>{s(new Error("Window was closed"))}))}));return await Promise.all([this.execute("focus",{windowId:e.id},"FocusChanged"),n]),e}finally{t&&t(),i&&i()}}async maximizeRestore(e){return await this.execute("maximizeRestore",{windowId:e.id},"StateChanged"),e}async maximize(e){return await this.execute("maximize",{windowId:e.id},"StateChanged"),e}async restore(e){return await this.execute("restore",{windowId:e.id},"StateChanged"),e}async minimize(e){return await this.execute("minimize",{windowId:e.id},"StateChanged"),e}async collapse(e){return await this.execute("collapse",{windowId:e.id},"StateChanged"),e}async expand(e){return await this.execute("expand",{windowId:e.id},"StateChanged"),e}async toggleCollapse(e){return await this.execute("toggleCollapse",{windowId:e.id},"StateChanged"),e}async snap(e,t,i){const n={targetWindowId:t.id};return n.snappingEdge=i.direction,n.autoAlign=i.autoAlign,await this.execute("snap",{windowId:e.id,options:n},"CompositionChanged",`CompositionChanged-${t.id}`),e}async attachTab(e,t,i){return await this.execute("attachTab",{windowId:e.id,options:{index:i,sourceWindowId:t.id,targetWindowId:e.id}},`WindowFrameAdded-${t.id}`,`WindowFrameRemoved-${t.id}`),e}async detachTab(e,t){const i=["WindowFrameRemoved","WindowFrameAdded"];return Ze(null==t?void 0:t.relativeTo)?i.push("BoundsChanged"):(i.push("CompositionChanged"),i.push(`CompositionChanged-${t.relativeTo}`)),await this.execute("detachTab",{windowId:e.id,options:t},...i),e}async setVisible(e,t=!0){let i;return i=t?"show":"hide",await this.execute(i,{windowId:e.id},"VisibilityChanged"),e}async center(e,t){return await this.execute("center",{windowId:e.id,options:t}),e}async showLoader(e,t){return await this.execute("showLoadingAnimation",{windowId:e.id,options:t}),e}async hideLoader(e){return await this.execute("hideLoadingAnimation",{windowId:e.id}),e}async updateContext(e,t,i){let n;try{const s=this.swapUndefinedToNull(t),r=new Promise(((t,i)=>{n=e.onContextUpdated((()=>{t()}))}));return await Promise.all([this.execute("updateContext",{windowId:e.id,context:s,replace:i}),r]),e}finally{n&&n()}}async lock(e){return await this.execute("lockUnlock",{windowId:e.id,options:{lock:!0}},"FrameIsLockedChanged"),e}async unlock(e){return await this.execute("lockUnlock",{windowId:e.id,options:{lock:!1}},"FrameIsLockedChanged"),e}async getIcon(e){return(await this.execute("getIcon",{windowId:e.id,options:{}})).icon}async setIcon(e,t){return await this.execute("setIcon",{windowId:e.id,options:{dataURL:t}}),e}async setFrameColor(e,t){return await this.execute("setFrameColor",{windowId:e.id,options:{frameColor:t}},"FrameColorChanged"),e}async setTabHeaderVisible(e,t){return await this.execute("setTabHeaderVisible",{windowId:e.id,options:{toShow:t}},"TabHeaderVisibilityChanged"),e}async showGroupPopup(e,t){const i=this.showPopupCore(e,t);await this.executeGroup("showGroupPopup",{groupId:e,options:i})}async showPopup(e,t){const i=this.showPopupCore(e.id,t);return await this.execute("showPopupWindow",{windowId:e.id,options:i}),e}async createFlydown(e,t){if(!t)throw new Error("The options object is not valid!");const i={...t};i.horizontalOffset||(i.horizontalOffset=0),i.verticalOffset||(i.verticalOffset=0);const n=this.reformatFlydownOptions(e,i);return this.execute("setFlydownArea",{windowId:e,options:n}).then((()=>{const e=n.zones.map((e=>e.id));return n.zones.forEach((e=>{let i="function"==typeof e.flydownSize?e.flydownSize:()=>e.flydownSize;t.size instanceof Function&&e.flydownSize&&(i=async(i,n)=>{let s;return t.size instanceof Function&&(s=await t.size(i,n)),e.flydownSize instanceof Function&&e.flydownSize!==t.size?await e.flydownSize(i,n)||s:s||e.flydownSize}),this._registry.clearKey(`${n.targetId}_${e.id}`),this._registry.add(`${n.targetId}_${e.id}`,i)})),{destroy:()=>this.clearFlydownArea(n.targetId,e),options:i}}))}async setModalState(e,t){return this.execute("setModalState",{windowId:e,options:{isModal:t}})}async autoArrange(e){return this.execute("autoArrange",{options:{displayId:e}})}async handleFlydownBoundsRequested(e,t){const i={zoneId:t.flydownId,flydownWindowBounds:t.flydownWindowBounds,flydownWindowId:t.flydownWindowId},n=await Promise.all(this._registry.execute(`${e}_${t.flydownId}`,i,(()=>t.cancel=!0)));if(1===n.length){const e={height:0,width:0,top:0,left:0},i="object"!=typeof n[0]||Array.isArray(n[0])?e:n[0];return{...t,flydownWindowBounds:i}}}async handleOnEventRequested(e,t){var i;const n=null!==(i=this.unsubCallbacks[e])&&void 0!==i?i:[];let s=!1;const r=[];return await Promise.all(n.map((e=>new Promise(((i,n)=>{e((()=>{i()}),(()=>{n()}),(e=>{s=!0,r.push(e)}),t)}))))),{prevented:s,preventArgs:r}}async zoomIn(e){return await this.execute("zoomIn",{windowId:e.id}),e}async zoomOut(e){return await this.execute("zoomOut",{windowId:e.id}),e}async setZoomFactor(e,t){return await this.execute("setZoomFactor",{windowId:e.id,options:{zoomFactor:t}}),e}async showDevTools(e){return await this.execute("showDevTools",{windowId:e.id}),e}async capture(e,t){return(await this.execute("captureScreenshot",{windowId:e.id,options:{...t}})).data}async captureGroup(e,t){return(await this.execute("captureGroupScreenshot",{windowId:e[0],options:{groupWindowIds:e,...t}})).data}async flash(e,t){return await this.execute("flash",{windowId:e.id,options:{...t}}),e}async flashTab(e,t){return await this.execute("flashTab",{windowId:e.id,options:{...t}}),e}async configure(e,t){return this.execute("configure",{windowId:e,options:{...t}})}async print(e,t){return await this.execute("print",{windowId:e.id,options:{...t}}),e}async printToPDF(e,t){return(await this.execute("printToPDF",{windowId:e.id,options:{...t}})).filePath}async place(e,t){const i={...t};return t.display&&"current"!==t.display||(i.display=await e.getDisplay()),i.display&&"string"!=typeof i.display&&"number"!=typeof i.display&&(i.display=i.display.index+1),this.execute("place",{windowId:e.id,options:{...i}})}async refresh(e,t){return await this.execute("refresh",{windowId:e.id,options:{ignoreCache:t}}),e}async download(e,t,i={}){i.enableDownloadBar=!i.silent;const n=await this.execute("downloadURL",{windowId:e.id,options:{url:t,options:i}});return{url:t,path:n.fullPath,size:n.fileSize}}async configureWindow(e,t){return await this.execute("configureWindow",{windowId:e.id,options:t}),e}async getWindowConfiguration(e){return await this.execute("getWindowConfiguration",{windowId:e.id})}async startDrag(e,t){return await this.execute("startDrag",{windowId:e.id,options:t}),e}showDialog(e,t){return new Promise(((i,n)=>{const s=si.generateId(),r=this._registry.add("event",(t=>{if("DialogResult"===t.type&&t.windowId===e.id&&t.data.token===s){r();const e=t.data;"status"in e&&("failed"===e.status?n(e.message):"successful"===e.status&&i(e.result))}}));this.execute("showDialog",{windowId:e.id,options:Object.assign({},{...t},{token:s})})}))}async execute(e,t,...i){return this.executeCore(this.WndMethodName,e,t,...i)}async executeGroup(e,t,...i){return this.executeCore(this.GroupMethodName,e,t,...i)}async ungroup(e,t){const i={windowId:e.id,options:t};return await this.execute("ungroup",i),e}async updateJumpList(e,t){const i={windowId:e,options:t};await this.execute("updateJumplist",i)}async getJumpList(e){const t={windowId:e};return await this.execute("getJumplist",t)}onClosing(e,t){const i="undefined"!=typeof window&&window.glue42gd;return i&&"electron"===t.windowType?i.addCloseHandler(e,t.id):this.nonWindowHandlers(e,t.id,"OnClosing")}onGroupClosing(e,t){return this.nonWindowHandlersCore(t.id,"OnClosing",!0,e)}onRefreshing(e,t){const i="undefined"!=typeof window&&window.glue42gd;return i&&"electron"===t.windowType?i.addRefreshHandler(e,t.id):this.nonWindowHandlers(e,t.id,"OnRefreshing")}onNavigating(e,t){const i="undefined"!=typeof window&&window.glue42gd;return i&&"electron"===t.windowType?i.addWillNavigateHandler(e,t.id):this.nonWindowHandlers(e,t.id,"OnNavigating")}async clone(e,t){const i={windowId:e.id,options:t},n=await this.execute("clone",i);return(await ai.waitFor(n.id)).API}async executeCode(e,t){const i={windowId:e.id,options:{code:t}};return this.execute("executeCode",i)}async goBack(e){await this.execute("goBack",{windowId:e.id})}async goForward(e){await this.execute("goForward",{windowId:e.id})}async getDockingPlacement(e){return this.execute("getDockingPlacement",{windowId:e.id})}dock(e,t){return this.execute("dock",{windowId:e.id,options:t})}clearCallbacks(e){Object.keys(this.unsubCallbacks).forEach((t=>{t.startsWith(e)&&delete this.unsubCallbacks[t]}))}nonWindowHandlers(e,t,i){return this.nonWindowHandlersCore(t,i,!1,e)}nonWindowHandlersCore(e,t,i,n){const s=`${e}-${t}`,r=()=>{var r;if(this.unsubCallbacks[s]){const e=this.unsubCallbacks[s];this.unsubCallbacks[s]=e.filter((e=>e!==n)),0===this.unsubCallbacks[s].length&&delete this.unsubCallbacks[s]}if(0===(null!==(r=this.unsubCallbacks[s])&&void 0!==r?r:[]).length){const n={unsubscribe:!0};i?this.executeGroup(t,{groupId:e,options:n}):this.execute(t,{windowId:e,options:n})}};return this.unsubCallbacks[s]?(this.unsubCallbacks[s].push(n),r):(this.unsubCallbacks[s]=[n],i?this.executeGroup(t,{groupId:e}):this.execute(t,{windowId:e}),r)}reformatFlydownOptions(e,t){const i=(e,i)=>{if(t[i]&&(void 0===e[i]||null===e[i])){const n=t[i];e[i]=n}},n=t.zones.map((e=>(i(e,"windowId"),i(e,"targetLocation"),!t.size||void 0!==e.flydownSize&&null!==e.flydownSize||(e.flydownSize=t.size),e.flydownBounds=e.flydownSize,e.flydownId=e.windowId,e.targetLocation||(e.targetLocation="bottom"),e)));return{...t,zones:n,targetId:e,flydownBounds:t.size,flydownActiveArea:t.activeArea}}clearFlydownArea(e,t){return this.execute("clearFlydownWindowArea",{windowId:e,options:{}}).then((()=>{t.forEach((t=>{this._registry.clearKey(`${e}_${t}`)}))}))}executeWithoutToken(e,...t){const i=[],n=null==t?void 0:t.filter((e=>!Ze(e))).map((t=>new Promise((n=>{const[s,r=e.windowId]=t.split("-");i.push(this._registry.add("event",(e=>{e.type===s&&e.windowId===r&&n()})))})))),s=new Promise(((t,i)=>{this.agm.invoke("T42.Wnd.Execute",e,this.agmTarget).then((e=>{e.returned&&e.returned.errorMsg?i(e):t(e.returned)})).catch((e=>i(e)))}));return Promise.all([s,...n]).then((e=>e[0])).finally((()=>{i.forEach((e=>e()))}))}async executeCore(e,t,i,...n){const s={...i,command:t};let r;this._finished=new Promise((e=>{r=e}));try{return"undefined"!=typeof window&&window.glueDesktop.versionNum<31200?await this.executeWithoutToken(s,...n):await this.executeWithToken(e,s)}finally{r()}}async executeWithToken(e,t){let i;try{const n=si.generateId(),s=new Promise((e=>{i=this._registry.add("event",(t=>{t.token===n&&e()}))})),r=new Promise(((i,s)=>{t.token=n,this.agm.invoke(e,t,this.agmTarget).then((e=>{e.returned&&e.returned.errorMsg?s(e):i(e.returned)})).catch((e=>{s(e)}))}));return(await Promise.all([r,s]))[0]}finally{i&&i()}}areBoundsEqual(e,t){const i=t.bounds,n=t.settings;let s=e.height,r=e.width;e.height<n.minHeight&&(s=n.minHeight),e.height>n.maxHeight&&(s=n.maxHeight),e.width<n.minWidth&&(r=n.minWidth),e.width>n.maxWidth&&(r=n.maxWidth);const o=!s||i.height===s,a=!r||i.width===r,c=!e.left||i.left===e.left,d=!e.top||i.top===e.top;return o&&a&&c&&d}swapUndefinedToNull(e){try{const t={};for(const i of Object.keys(e)){let n=e[i];void 0===n&&(n=null),t[i]=n}return t}catch{return e}}showPopupCore(e,t){if(!t)throw new Error("The options object is not valid!");const i={...t};i.targetLocation||(i.targetLocation="bottom");return{...i,popupBounds:i.size,targetId:e,popupId:i.windowId}}};class mi{constructor(e,t,i,n,s,r,o){this._registry=Jt(),this._waitTimeout=1e4,this._agm=e,this._logger=t.subLogger("gd-env"),this._windowId=r,this._groupId=o,this._appManagerGetter=i,this._displayAPIGetter=n,this._channelsAPIGetter=s}init(){return new Promise(((e,t)=>{this._agm.register("T42.Wnd.OnEventWithResponse",((e,t)=>this.respondToEvent(e))),new Promise(((i,n)=>{this._agm.subscribe("T42.Wnd.OnEvent",{waitTimeoutMs:this._waitTimeout,target:"best",arguments:{withConfig:!0},onData:t=>{if("Configuration"===t.data.type)return this._configuration=t.data,void gi.setConfiguration(this._configuration);this.updateWindow(t.data,e),gi.handleEvent(t.data)},onConnected:e=>{this._agmInstance=e,gi.init(this._agm,this._agmInstance)}}).catch((e=>{var i;const n=`${null===(i=null==e?void 0:e.method)||void 0===i?void 0:i.name} - ${JSON.stringify(null==e?void 0:e.called_with)} - ${null==e?void 0:e.message}`;t(new Error(n))}))}))}))}get executor(){return gi}open(e,t,i){i=i||{};const n={...i};return void 0!==n.relativeTo&&"string"!=typeof n.relativeTo&&(n.relativeTo=n.relativeTo.id||""),n.name=e,n.url=t,n.windowState=i.windowState||i.state,delete n.state,this.executor.open(n)}createFlydown(e,t){return this.executor.createFlydown(e,t)}async showPopup(e,t){const i=ai.get(e);await this.executor.showPopup(i.API,t)}tabAttached(e){return this._registry.add("tab-attached",e)}tabDetached(e){return this._registry.add("tab-detached",e)}onWindowFrameColorChanged(e){return this._registry.add("frame-color-changed",e)}onEvent(e){return this._registry.add("window-event",e)}my(){return this._windowId}myGroup(){return this._groupId}execute(e,t,i){return this._agm.invoke("T42.Wnd.Execute",{command:e,options:i,windowId:t})}onCompositionChanged(e){return this._registry.add("composition-changed",e)}onGroupHeaderVisibilityChanged(e){return this._registry.add("group-header-changed",e)}onGroupVisibilityChanged(e){return this._registry.add("group-visibility-changed",e)}onGroupStateChanged(e){return this._registry.add("group-state-changed",e)}onWindowGotFocus(e){return this._registry.add("got-focus",e)}onWindowLostFocus(e){return this._registry.add("lost-focus",e)}onWindowsAutoArrangeChanged(e){return this._registry.add("windows-auto-arranged-changed",e)}respondToEvent(e){return"ShowFlydownBoundsRequested"===e.type?this.executor.handleFlydownBoundsRequested(e.data.windowId,e.data):"OnClosing"===e.type||"OnRefreshing"===e.type||"OnNavigating"===e.type?this.executor.handleOnEventRequested(e.data.callbackId,e.data.args):Promise.reject(`There isn't a handler for ${e.type}`)}updateWindow(e,t){var i;const n=this.getExtendedStreamEvent(e);if("Snapshot"===e.type){return e.windows.forEach((e=>{const t=ai.get(e.id);if(t)t.Events.handleUpdate(this.mapToWindowConstructorOptions(e)),t.GroupCreationArgs=this.mapToGroupCreationArgs(e);else{const t=this.createWindow(e.id,e);ai.markReadyToShow(t.API.id)}this._registry.execute("window-event",n)})),void t(this)}if("CommandExecuted"===e.type)return void this._registry.execute("window-event",n);if("Created"===e.type){const t=e,i=this.createWindow(t.windowId,t.data||{});return ai.setReadyState(i.API.id),void this._registry.execute("window-event",n)}if("OnGroupVisibilityChanged"===e.type){const t=e;return this._registry.execute("group-visibility-changed",t.data),void this._registry.execute("window-event",e)}if("OnGroupStateChanged"===e.type){const t=e;return this._registry.execute("group-state-changed",t.data),void this._registry.execute("window-event",e)}if("OnWindowsAutoArrangeChanged"===e.type){const t=e;return this._registry.execute("windows-auto-arranged-changed",t.data),void this._registry.execute("window-event",e)}const s=ai.get(e.windowId);if(!s)return void this._logger.error(`received update for unknown window. Stream:', ${JSON.stringify(e,null,4)}`);const r=s.API,o=s.Events;if("BoundsChanged"===e.type){const t=e;o.handleBoundsChanged(t.data)}if("UrlChanged"===e.type){const t=e;ai.setUrlChangedState(t.windowId),o.handleUrlChanged(t.data)}if("TitleChanged"===e.type){const t=e;o.handleTitleChanged(t.data)}if("IsStickyChanged"===e.type){const t=e;o.handleIsStickyChanged(t.data)}if("VisibilityChanged"===e.type&&o.handleVisibilityChanged(e.data),"ContextChanged"===e.type&&o.handleContextUpdated(e.data),"StateChanged"===e.type&&o.handleWindowChangeState(e.data),"FrameColorChanged"===e.type&&(o.handleFrameColorChanged(e.data),this._registry.execute("frame-color-changed",r)),"CompositionChanged"===e.type){const t=e;o.handleCompositionChanged(t.data),ai.setCompositionChangedState(t.data.windowId,null===(i=this._configuration)||void 0===i?void 0:i.windowAvailableOnURLChanged),this._registry.execute("composition-changed",t.data)}if("GroupHeaderVisibilityChanged"===e.type){const t=e;o.handleGroupHeaderVisibilityChanged(t.data.groupHeaderVisible),this._registry.execute("group-header-changed",t.data)}if("FocusChanged"===e.type){const t=e;this.focusChanged(o,r,t.data)}if("WindowFrameChanged"===e.type&&(o.handleFrameAttached(e.data.frameId,e.data.frameId,e.data.isTabHeaderVisible),this._registry.execute("frame-changed")),"WindowFrameAdded"===e.type){const t=li(r.id,e.data.frameId),i=e.data;o.handleAttached(i.frameId,i.frameId,i.isTabHeaderVisible,i.isLocked,t).then((async()=>{t.length>0&&(await gi.finished,this._registry.execute("tab-attached",r,e.data.frameId,e.data.isTabHeaderVisible))}))}if("WindowFrameRemoved"===e.type){const t=r.tabGroupId,i=li(r.id,t);o.handleDetached(e.data.isLocked,i).then((async()=>{i.length>0&&(await gi.finished,this._registry.execute("tab-detached",r,e.data.frameId,r.tabGroupId))}))}"TabHeaderVisibilityChanged"===e.type&&o.handleTabHeaderVisibilityChanged(e.data.isTabHeaderVisible),"FrameSelectionChanged"===e.type&&o.handleFrameSelectionChanged(e.data.newWindowId,e.data.prevWindowId),"ButtonClicked"===e.type&&o.handleFrameButtonClicked(e.data),"ButtonAdded"===e.type&&o.handleFrameButtonAdded(e.data),"ButtonRemoved"===e.type&&o.handleFrameButtonRemoved(e.data),"WindowZoomFactorChanged"===e.type&&o.handleZoomFactorChanged(e.data),"Closed"===e.type&&(ai.remove(s),o.handleWindowClose()),"FrameIsLockedChanged"===e.type&&o.handleFrameIsLockedChanged(e.data),"PlacementSettingsChanged"===e.type&&o.handlePlacementSettingsChanged(e.data),"DockingChanged"===e.type&&o.handleDockingChanged(e.data),"AllowWorkspaceDropChanged"===e.type&&o.handleAllowWorkspaceDropChanged(e.data),"IsPinnedChanged"===e.type&&o.handleIsPinnedChanged(e.data),"WindowChannelRestrictionsChanged"===e.type&&o.handleChannelRestrictionsChanged(e.data),this._registry.execute("window-event",n)}createWindow(e,t){const i=ui(e,this.mapToWindowConstructorOptions(t),gi,this._logger,this._appManagerGetter,this._displayAPIGetter,this._channelsAPIGetter,this._agm);return i.GroupCreationArgs=this.mapToGroupCreationArgs(t),ai.add(i),i}async focusChanged(e,t,i){e.handleFocusChanged(i);try{this._configuration.windowAvailableOnURLChanged||await ai.waitFor(t.id)}catch(e){return}i?this._registry.execute("got-focus",t):this._registry.execute("lost-focus",t)}mapToWindowConstructorOptions(e){return{name:e.name,context:e.context,bounds:e.bounds,url:e.url,title:e.title,isVisible:e.isVisible,focus:e.isFocused,state:e.state,frameColor:e.frameColor,groupId:e.groupId,neighbours:e.neighbors,isFocused:e.isFocused,isGroupHeaderVisible:e.groupHeaderVisible,isCollapsed:e.isCollapsed,tabGroupId:e.frameId,frameId:e.frameId,mode:e.mode,isTabHeaderVisible:e.isTabHeaderVisible,isTabSelected:e.isActiveTab,settings:e.settings,windowType:e.windowType,zoomFactor:e.zoomFactor,isLocked:e.isLocked,placementSettings:e.placementSettings,isSticky:e.isSticky,tabIndex:e.tabIndex,frameButtons:e.frameButtons,jumpListOptions:e.jumpList,applicationName:e.applicationName,allowWorkspaceDrop:e.allowWorkspaceDrop,isPinned:e.isPinned}}mapToGroupCreationArgs(e){return{isGroupHibernated:e.isGroupHibernated,isGroupVisible:e.isGroupVisible}}getExtendedStreamEvent(e){try{if(!e.windowId)return e;const t=ai.get(e.windowId);if(!t)return e;const i={state:e.type,windowName:t.API.name,...e};return"WindowFrameAdded"===i.state&&(i.state="TabAttached"),"StateChanged"===i.state&&(i.state=i.data.charAt(0).toUpperCase()+i.data.slice(1)),"ButtonAdded"===i.state&&(i.state="FrameButtonAdded"),"ButtonRemoved"===i.state&&(i.state="FrameButtonRemoved"),i}catch(t){return e}}}var fi=(e,t)=>{const i=Jt(),n=[];let s,r;async function o(e,i,...n){return await t.execute(e,i,...n),d}function a(){const e=[];return n.forEach((t=>{const i=c(t);void 0!==i&&e.push(i)})),e}function c(e){return ai.get(e)?ai.get(e).API:void 0}const d={id:e,get windows(){return function(e){const t=a();return"function"==typeof e&&e(t),t}()},find:function(e,t,i){let n;"string"==typeof e?n=e:Ze(e)||(n=e.id);const s=c(n);if(s)return"function"==typeof t&&t(s),s;"function"==typeof i&&i(`No window with ID: ${n}`)},get isHeaderVisible(){return void 0===a().find((e=>!e.isGroupHeaderVisible))},get isHibernated(){return s},get isVisible(){return r},showHeader:(e,t)=>si.callbackifyPromise((()=>o("setGroupHeaderVisibility",{windowId:n[0],options:{toShow:!0}},...n.map((e=>`GroupHeaderVisibilityChanged-${e}`)))),e,t),hideHeader:(e,t)=>si.callbackifyPromise((()=>o("setGroupHeaderVisibility",{windowId:n[0],options:{toShow:!1}},...n.map((e=>`GroupHeaderVisibilityChanged-${e}`)))),e,t),getTitle:async()=>(await t.execute("getGroupTitle",{windowId:n[0]})).title,setTitle:async e=>{if(Xe(e))throw new Error("`title` must not be null or undefined.");return o("setGroupTitle",{windowId:n[0],options:{title:e}})},capture:e=>t.captureGroup(n,e),maximize:(e,t)=>si.callbackifyPromise((()=>o("maximizeGroup",{windowId:n[0]},...n.map((e=>`StateChanged-${e}`)))),e,t),restore:(e,t)=>si.callbackifyPromise((()=>o("restoreGroup",{windowId:n[0]},...n.map((e=>`StateChanged-${e}`)))),e,t),show:i=>{if(!Ze(i)&&!Ye(i))throw new Error("Activate flag must be a boolean!");return i=!!Ze(i)||i,t.executeGroup("showGroup",{groupId:e,options:{activate:i}})},hide:()=>t.executeGroup("hideGroup",{groupId:e}),close:()=>t.executeGroup("closeGroup",{groupId:e}),showPopup:i=>t.showGroupPopup(e,i),onHeaderVisibilityChanged:function(e){return i.add("header-visibility-changed",e)},onWindowAdded:function(e){return i.add("window-added",e)},onWindowRemoved:function(e){return i.add("window-removed",e)},onVisibilityChanged:function(e){if(!e)throw new Error("Callback argument is required");if(e&&"function"!=typeof e)throw new Error("Callback argument must be a function");return i.add("group-visibility-changed",e)},onClosing:function(e){if("function"!=typeof e)throw new Error("callback must be a function");return t.onGroupClosing(((t,i,n)=>{const s=e(n);(null==s?void 0:s.then)?s.then(t).catch(i):t()}),d)}},h={get windows(){return n},addWindow:async function(e){var o,a,c,h;if(-1===n.indexOf(e)){n.push(e);const u=ai.get(e);u.Events.handleGroupChanged(d,void 0),s=null!==(a=null!==(o=u.GroupCreationArgs.isGroupHibernated)&&void 0!==o?o:s)&&void 0!==a&&a,r=null===(h=null!==(c=u.GroupCreationArgs.isGroupVisible)&&void 0!==c?c:r)||void 0===h||h,await t.finished,i.execute("window-added",d,u.API)}},removeWindow:async function(e){const s=n.indexOf(e.API.id);-1!==s&&(n.splice(s,1),e.Events.handleGroupChanged(void 0,d),await t.finished,i.execute("window-removed",d,e.API))},handleGroupHeaderVisibilityChanged:function(e){i.execute("header-visibility-changed",d)},handleGroupVisibilityChanged:function(e){r=e,i.execute("group-visibility-changed",d)},handleGroupHibernateChanged:function(e){s=e}};return{groupAPI:d,groupInternal:h}},yi=(e,t)=>{const i=Jt(),n={};let s=-1;const r=ai.list;function o(e,t,i){let s;"string"==typeof e?s=e:Ze(e)||(s=e.id);const r=Object.values(n).find((e=>e.groupAPI.windows.filter((e=>e.id===s)).length));if(r)return"function"==typeof t&&t(r.groupAPI),r.groupAPI;"function"==typeof i&&i("Cannot find the group of the window.")}function a(e){return e?new Promise(((t,i)=>{const s=n[e];if(s)t(s.groupAPI);else{const i=c((n=>{n.id===e&&(i(),t(n))}))}})):Promise.reject(new Error("groupId must be defined"))}function c(e){return i.add("group-added",e)}function d(t,s){const r=function(t){if(n.hasOwnProperty(t))return n[t];{const s=fi(t,e.executor);n[t]=s;const r=s.groupAPI;return i.execute("group-added",r),s}}(t);return r.groupInternal.addWindow(s),r}function h(e,t){e&&(e.groupInternal.removeWindow(t),function(e){const t=e.groupAPI;0===t.windows.length&&(delete n[t.id],gi.clearCallbacks(t.id),i.execute("group-removed",t))}(e))}function u(e){let t;return"string"==typeof e?t=e:Ze(e)||(t=e.id),Object.values(n).find((e=>e.groupInternal.windows.filter((e=>e===t)).length))}Object.keys(r).forEach((e=>{const t=r[e],i=t.API.groupId,n=t.API.id;Xe(i)||d(i,n)})),ai.onRemoved((e=>{h(u(e.API),e)})),e.onCompositionChanged((e=>{!function(e){const t=e.groupId,s=e.windowId,r=ai.get(s);if(!r)return;const o=u(r.API);if(Ze(t))return void h(o,r);if(Ze(o)&&!Ze(t))return void d(t,r.API.id);o.groupAPI.id!==t&&function(e,t,s){const r=e.API.id,o=n[t];h(o,e);const a=d(s,r);e.Events.handleGroupChanged(a.groupAPI,o.groupAPI),i.execute("window-moved",r,t,s)}(r,o.groupAPI.id,t)}(e)})),e.onGroupHeaderVisibilityChanged((e=>{const t=o(e.windowId);if(void 0!==t){const i=n[t.id];-1===s&&(s=t.windows.length),s--,0===s&&(s=-1,i.groupInternal.handleGroupHeaderVisibilityChanged(e))}})),e.onGroupVisibilityChanged((e=>{const t=n[e.groupId];t&&t.groupInternal.handleGroupVisibilityChanged(e.visible)})),e.onGroupStateChanged((e=>{const t=n[e.groupId];"hibernated"===e.state?((null==t?void 0:t.groupAPI)&&t.groupInternal.handleGroupHibernateChanged(!0),i.execute("group-hibernated",e.groupId)):"resumed"===e.state&&((null==t?void 0:t.groupAPI)&&t.groupInternal.handleGroupHibernateChanged(!1),i.execute("group-resumed",t.groupAPI))}));const l={get my(){return function(){var t;return o(null!==(t=e.myGroup())&&void 0!==t?t:e.my())}()},create:async function(e){if(Ze(e))throw new Error("options must be defined");if(Ze(e.groups)||!Array.isArray(e.groups)||0===e.groups.length)throw new Error("options.groups must be defined");const{groupIds:t}=await gi.executeGroup("createGroups",{options:e}),i=t.map((e=>a(e)));return Promise.all(i)},close:async function(e,t){if(Ze(e))throw new Error("group must be defined");let i="";if(i="string"==typeof e?e:e.id,Ze(t))throw new Error("options must be defined");await gi.executeGroup("closeGroup",{groupId:i,options:t})},list:function(e){const t=Object.keys(n).map((e=>{if(n[e])return n[e].groupAPI}));return"function"==typeof e&&e(t),t},findGroupByWindow:o,waitForGroup:a,getMyGroup:function(){var t;return a(null!==(t=e.myGroup())&&void 0!==t?t:e.my())},onGroupAdded:c,onGroupRemoved:function(e){return i.add("group-removed",e)},hibernate:async function(e){return await gi.executeGroup("hibernateGroup",{groupId:e}),e},resume:async function(e,t){if(!Ze(t)&&!Ye(t))throw new Error("Activate flag must be a boolean!");t=!!Ze(t)||t,await gi.executeGroup("resumeGroup",{groupId:e,options:{activate:t}})},onHibernated:function(e){if(!e)throw new Error("Callback argument is required");if(e&&"function"!=typeof e)throw new Error("Callback argument must be a function");return i.add("group-hibernated",e)},onResumed:function(e){if(!e)throw new Error("Callback argument is required");if(e&&"function"!=typeof e)throw new Error("Callback argument must be a function");return i.add("group-resumed",e)}};return{groupsAPI:l,groupsEvents:{onWindowMoved:function(e){return i.add("window-moved",e)}}}},wi=(e,t,i,n,s,r)=>{const o=Jt(),a=t;let c,d;ai.init(a);const h=new Promise(((t,o)=>{((e,t,i,n,s,r)=>{var o;const a=t;if(2===r)throw a.trace("running in HC"),new Error("GD2 not supported");return r>=3?(a.trace("running in GD 3"),new mi(e,a,i,n,s,window.glue42gd.windowId,null===(o=window.webGroupsManager)||void 0===o?void 0:o.id).init()):new mi(e,a,i,n,s).init()})(e,a,i,n,s,r).then((i=>{d=i,c=yi(i),oi.init(i.executor,e,a),t()})).catch((e=>{const t=`Timed out waiting for connection to Glue42 Enterprise: Error: ${e.message}`;a.error(t,e),o(new Error(t))}))}));function u(){const e=ai.getIfReady(d.my());return e?e.API:void 0}function l(e){return o.add("window-added",e)}function p(e){return o.add("window-removed",e)}return ai.onReadyWindow((function(e){o.execute("window-added",e.API)})),ai.onRemoved((function(e){o.execute("window-removed",e.API)})),{my:u,open:function(e,t,i,n,s){return si.callbackifyPromise((()=>{if(Xe(e))throw new Error("The window name is missing.");if(Xe(t))throw new Error("The window URL is missing.");if(!Ze(i)){const e=i;for(const t of["minHeight","maxHeight","minWidth","maxWidth","width","height","top","left"])if(t in e){const i=e[t];if(Ze(i)){delete e[t];continue}if(!Je(i)){throw new Error(`${t} must be a number`)}if(("width"===e[t]||"height"===e[t])&&i<=0){throw new Error(`${t} must be a positive number`)}}}return d.open(e,t,i)}),n,s)},find:function(e,t,i){const n=ai.list,s=Object.keys(n).reduce(((t,i)=>{var s;const r=n[i];return(null===(s=null==r?void 0:r.API)||void 0===s?void 0:s.name)===e&&t.push(r.API),t}),[]);if(s[0])return"function"==typeof t&&t(s[0]),s[0];"function"==typeof i&&i("There is no window with name:"+e)},findById:function(e,t,i){const n=ai.list,s=Object.keys(n).reduce(((t,i)=>{const s=n[i];return void 0!==s&&s.API.id===e&&t.push(s.API),t}),[]);if(s[0])return"function"==typeof t&&t(s[0]),s[0];"function"==typeof i&&i("There is no window with such id:"+e)},list:function(e){const t=ai.list,i=Object.keys(t).map((e=>t[e].API));if("function"!=typeof e)return i;e(i)},ready:function(){return h},onWindowAdded:l,windowAdded:l,onWindowRemoved:p,windowRemoved:p,onTabAttached:function(e){let t,i=!1;return h.then((()=>{i||(t=d.tabAttached(e))})),()=>{i=!0,t&&t()}},onTabDetached:function(e){let t,i=!1;return h.then((()=>{i||(t=d.tabDetached(e))})),()=>{i=!0,t&&t()}},onWindowFrameColorChanged:function(e){let t,i=!1;return h.then((()=>{i||(t=d.onWindowFrameColorChanged(e))})),()=>{i=!0,t&&t()}},onArrangementChanged:function(e){return d.onWindowsAutoArrangeChanged(e)},get groups(){return c.groupsAPI},onWindowGotFocus:function(e){let t,i=!1;return h.then((()=>{i||(t=d.onWindowGotFocus(e))})),()=>{i=!0,t&&t()}},onWindowLostFocus:function(e){let t,i=!1;return h.then((()=>{i||(t=d.onWindowLostFocus(e))})),()=>{i=!0,t&&t()}},onEvent:function(e){let t,i=!1;return h.then((()=>{i||(t=d.onEvent(e))})),()=>{i=!0,t&&t()}},createFlydown:function(e,t){return d.createFlydown(e,t)},showPopup:function(e,t){return d.showPopup(e,t)},configure:function(e){const t=u(),i=t?t.id:"";return gi.configure(i,e)},autoArrange:function(e){return gi.autoArrange(e)}}};var vi=new class{constructor(){this.layouts=[]}removeWhere(e){this.layouts=this.layouts.filter(e)}removeAll(){this.layouts=[]}add(e){this.layouts.push(e)}get all(){return this.layouts}where(e){return this.layouts.filter(e)}first(e){return this.where(e)[0]}};class bi{constructor(e,t,i,n){this.config=e,this.activitiesGetter=t,this.callbacks=i,this.logger=n,this.interop=e.agm,this.registerRequestMethods()}onSaveRequested(e){return this.callbacks.add("saveRequested",e)}isActivityOwner(){if("undefined"!=typeof htmlContainer){const e=htmlContainer.getContext();return e&&e._t42&&e._t42.activityIsOwner}const e=this.activitiesGetter();if(!e)return!1;if(!e.inActivity)return!1;const t=e.my.window,i=e.my.activity;return!(!i&&!t)&&i.owner.id===t.id}registerRequestMethods(){this.interop.register("T42.HC.GetSaveContext",(e=>{const t=this.callbacks.execute("saveRequested",e);(null==t?void 0:t.length)>1&&this.logger.warn('Multiple subscriptions for "glue.layouts.onSaveRequested" - only the first one will be used');const i=t[0],n=this.config.autoSaveWindowContext;if("boolean"==typeof n&&n)return{autoSaveWindowContext:n};if(Array.isArray(n)&&n.length>0)return{autoSaveWindowContext:n};const s={windowContext:null==i?void 0:i.windowContext,activityContext:void 0};return this.isActivityOwner()&&(s.activityContext=null==i?void 0:i.activityContext),s}))}}function _i(e){if(!e)return e;if(Array.isArray(e))return e.map((e=>_i(e)));if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;return Object.keys(e).reduce(((t,i)=>{var n;const s=_i(e[i]);let r=i;return(null===(n=i[0])||void 0===n?void 0:n.toLowerCase())!==i[0]&&(r=i[0].toLowerCase()+i.substr(1)),t[r]=s,t}),{})}class Ii{constructor(e){this.name=e.name,this.type=e.type,this.components=e.components,this.context=e.context,this.metadata=e.metadata,this.version=e.version,this.displays=e.displays}}const Ci="T42.ACS.Command";class Ai{constructor(e,t,i,n){this.config=e,this.stream=t,this.callbacks=i,this.isRegisterMethodForLayoutModified=!1,this.appManager=e.appManager,this.provider=new bi(e,e.activityGetter,i,n),t.subscribe()}async setDefaultGlobal(e){await this.invokeMethodCore("SelectDefaultLayout",{name:e})}async clearDefaultGlobal(){this.invokeMethodCore("DeselectDefaultLayout")}async getDefaultGlobal(){const e=(await this.invokeMethodCore("GetDefaultLayout")).returned;if(e)return this.isSlimMode()?e:this.list().find((t=>t.name===e.name&&"Global"===t.type))}ready(){return"fullWaitSnapshot"===this.config.mode?this.stream.gotSnapshot:this.stream.ready}save(e){return new Promise(((t,i)=>{var n,s;if(this.verifyNotSlimMode(),Ze(e))return i(new Error("layout is required"));if(Xe(e.name))return i(new Error("layout.name argument is required"));Xe(e.type)&&(e.type="Global"),Xe(e.activityId)||(e.type="Activity");const r={name:e.name,type:e.type,context:null!==(n=e.context)&&void 0!==n?n:{},metadata:null!==(s=e.metadata)&&void 0!==s?s:{},options:{}};if("Activity"===e.type){let t=e.activityId;if(!t){if(!this.appManager.myInstance.inActivity)return i(new Error("Current application is not in activity. Cannot save activity layout for it."));t=this.appManager.myInstance.activityId}r.activityId=t}else{if("Global"!==e.type)return i(new Error(`layout type ${e.type} is not supported`));Array.isArray(e.ignoreInstances)&&(r.options.ignoreInstances=e.ignoreInstances),Array.isArray(e.instances)&&(r.options.instances=e.instances),"boolean"==typeof e.setAsCurrent&&(r.options.setAsCurrent=e.setAsCurrent)}this.invokeMethodAndTrack("SaveLayout",r,t,i)}))}restore(e){return new Promise(((t,i)=>{var n,s,r;if(this.verifyNotSlimMode(),Ze(e))return i(new Error("options argument is required"));if(Xe(e.name))return i(new Error("options.name argument is required"));if(Xe(e.type)&&(e.type="Global"),Xe(e.activityIdToJoin)||(e.type="Activity"),"Activity"===e.type){if(Ze(e.setActivityContext)&&(e.setActivityContext=!0),"boolean"!=typeof e.setActivityContext)return i(new Error("`setActivityContext` must hold a boolean value."));e.activityIdToJoin=null!==(n=e.activityIdToJoin)&&void 0!==n?n:this.appManager.myInstance.activityId}if(Ze(e.closeRunningInstance)||(e.closeRunningInstances=e.closeRunningInstance),Ze(e.closeRunningInstances)&&(e.closeRunningInstances=!0),!Ye(e.closeRunningInstances))return i(new Error("`closeRunningInstances` must hold a boolean value."));if(Ze(e.closeMe)&&(e.closeMe=e.closeRunningInstances),!Ye(e.closeMe))return i(new Error("`closeMe` must hold a boolean value."));if(!Ze(e.context)&&!ze(e.context))return i(new Error("`context` must hold an object value."));if(!Ze(e.timeout)&&"number"!=typeof e.timeout)return i(new Error("`timeout` must hold an number value."));e.context=null!==(s=e.context)&&void 0!==s?s:{};const o={activityToJoin:e.activityIdToJoin,setActivityContext:e.setActivityContext,ignoreActivityWindowTypes:e.ignoreActivityWindowTypes,reuseExistingWindows:e.reuseWindows,closeRunningInstances:e.closeRunningInstances,excludeFromClosing:e.closeMe?[]:[null===(r=this.appManager.myInstance)||void 0===r?void 0:r.id]},a={type:e.type,name:e.name,context:e.context,options:o};e.timeout&&(a.timeout=e.timeout),this.invokeMethodAndTrack("RestoreLayout",a,t,i,!0)}))}reset(e){return new Promise(((t,i)=>{if(this.verifyNotSlimMode(),"object"!=typeof e)return i(new Error("options argument is required"));if(Xe(e.layoutId))return i(new Error("options.layoutId argument is required"));const n={...e};this.invokeMethodAndTrack("ResetLayout",n,t,i,!0)}))}remove(e,t){return new Promise(((i,n)=>{if(this.verifyNotSlimMode(),!t)return n(new Error("name argument is required"));if(!e)return n(new Error("type argument is required"));const s={type:e,name:t};this.invokeMethodAndTrack("RemoveLayout",s,i,n)}))}list(){return this.verifyNotSlimMode(),vi.all}import(e,t){return new Promise(((i,n)=>{if(this.verifyNotSlimMode(),!Ze(t)&&"merge"!==t&&"replace"!==t)return n(new Error(`${t} is not supported - only "merge" and "replace"`));if(!Array.isArray(e))return n(new Error("layouts arguments is not an array"));const s={mode:t||"replace",layouts:e};this.invokeMethodAndTrack("ImportLayouts",s,i,n,!0)}))}export(e){return new Promise(((t,i)=>{this.invokeMethodAndTrack("ExportLayouts",{},(i=>{let n=this.getObjectValues(i.Layouts).map((e=>new Ii(_i(e))));e&&(n=n.filter((t=>t.type===e))),t(n)}),i,!0)}))}rename(e,t){return new Promise(((i,n)=>{if(this.verifyNotSlimMode(),!e)return n(new Error("layout argument is required"));if(!e.name)return n(new Error("name argument is required"));if(!e.type)return n(new Error("type argument is required"));const s={type:e.type,oldName:e.name,newName:t};this.invokeMethodAndTrack("RenameLayout",s,i,n)}))}updateMetadata(e){return new Promise(((t,i)=>{if(!e)return i(new Error("layout argument is required"));if(!e.name)return i(new Error("name argument is required"));if(!e.type)return i(new Error("type argument is required"));if(!e.metadata)return i(new Error("metadata argument is required"));const n={name:e.name,type:e.type,metadata:e.metadata};this.invokeMethodAndTrack("UpdateMetadata",n,t,i,!0)}))}hibernate(e,t){return new Promise(((i,n)=>{if(!e)return n(new Error("name cannot be empty"));const s={name:e,type:"Global",context:(t=t||{}).context||{},metadata:t.metadata||{}};this.invokeMethodAndTrack("HibernateLayout",s,i,n,!0)}))}resume(e,t,i){return new Promise(((n,s)=>{if(!e)return s(new Error("name cannot be empty"));const r={name:e,type:"Global",context:t,...i};this.invokeMethodAndTrack("ResumeLayout",r,n,s,!0)}))}async getCurrentLayout(){let e=(await this.invokeMethodCore("GetCurrentLayout")).returned.layout;if(e)return this.isSlimMode()||(e=this.list().find((t=>t.name===e.name&&t.type===e.type))),e}getRestoredLayoutsInfo(){return new Promise(((e,t)=>{this.invokeMethodCore("GetRestoredLayoutsInfo").then((t=>{const i=t.returned;e(i)})).catch(t)}))}onAdded(e){const t=this.callbacks.add("added",e);return vi.all.length>0&&vi.all.forEach((t=>{try{e(t)}catch(e){}})),t}onRemoved(e){return this.callbacks.add("removed",e)}onChanged(e){return this.callbacks.add("changed",e)}onRestored(e){return this.callbacks.add("restored",e)}onRenamed(e){return this.callbacks.add("renamed",e)}onEvent(e){return this.stream.onEvent(e)}onSaveRequested(e){return this.provider.onSaveRequested(e)}onLayoutModified(e){return!1===this.isRegisterMethodForLayoutModified&&(this.isRegisterMethodForLayoutModified=!0,this.registerMethodForLayoutModified()),this.callbacks.add("layout-modified",e)}updateAppContextInCurrent(e){return new Promise(((t,i)=>{if(e&&"object"!=typeof e)return i(new Error("context must be an object"));const n={context:e=null!=e?e:{}};this.invokeMethodAndTrack("UpdateLayoutComponentContext",n,t,i,!0)}))}updateDefaultContext(e){return new Promise(((t,i)=>{if(e&&"object"!=typeof e)return i(new Error("context must be an object"));const n={context:e=null!=e?e:{}};this.invokeMethodAndTrack("UpdateDefaultContext",n,t,i,!0)}))}async get(e,t){const i=this.list().find((i=>i.name===e&&i.type===t));if(!i)throw new Error(`cannot find layout with name=${e} and type=${t}`);return i}async getAll(e){return this.list().filter((t=>e===t.type))}async forceRefresh(){await this.invokeMethodCore("RefreshLayouts")}isSlimMode(){return"slim"===this.config.mode}verifyNotSlimMode(){if(this.isSlimMode())throw Error("Operation not allowed in slim mode. Run in full mode.")}async registerMethodForLayoutModified(){await this.config.agm.register("T42.ACS.LayoutModified",((e,t)=>{this.callbacks.execute("layout-modified",e)}))}invokeMethodAndTrack(e,t,i,n,s){let r,o=s;const a=si.generateId();t.token=a;const c=()=>{o&&r&&i(r)},d=12e4;s||this.stream.waitFor(a,d).then((()=>{o=!0,c()})).catch((e=>{n(e)}));this.invokeMethodCore(e,t,"best",{methodResponseTimeoutMs:d}).then((t=>{if(!t.returned)return n(new Error("No result from method "+e));if(t.returned.status&&"Success"!==t.returned.status&&"PartialSuccess"!==t.returned.status){if("string"==typeof t.returned)return n(new Error(t.returned));if("object"==typeof t.returned)return t.returned.status&&t.returned.failed?n(new Error(`${t.returned.status}: ${JSON.stringify(t.returned.failed)}`)):n(new Error(t.returned))}r=t.returned,c()})).catch((e=>n(e)))}async invokeMethodCore(e,t,i,n){return this.isCommandMethodPresent()?await this.config.agm.invoke(Ci,{command:e,data:t},i,n):await this.config.agm.invoke(`T42.ACS.${e}`,t,i,n)}getObjectValues(e){return e?Object.keys(e).map((t=>e[t])):[]}isCommandMethodPresent(){return this.config.agm.methods().some((e=>e.name===Ci))}}class Si{constructor(e,t){this.agm=e,this.callbacks=t,this.StreamName="T42.ACS.OnLayoutEvent",this.ready=new Promise(((e,t)=>{this.resolveReady=e,this.rejectReady=t})),this.gotSnapshot=new Promise(((e,t)=>{this.resolveGotSnapshot=e,this.rejectGotSnapshot=t}))}subscribe(e){const t=e=>this.getObjectValues(e).map((e=>_i(e)));this.checkForLayoutEventMethod()?this.agm.subscribe(this.StreamName,{waitTimeoutMs:1e4}).then((e=>{e.onData((e=>{const i=e.data;i.IsSnapshot&&this.resolveGotSnapshot(),this.addLayouts(t(i.OnLayoutAdded),i.IsSnapshot),this.removeLayouts(t(i.OnLayoutRemoved)),this.changeLayouts(t(i.OnLayoutChanged)),this.renameLayouts(t(i.OnLayoutRenamed)),this.restoredLayout(t(i.OnLayoutRestored)),this.callbacks.execute("streamEvent",i)})),e.onFailed((e=>{const t=`Can not subscribe to "${this.StreamName}" stream - ${JSON.stringify(e)}`;this.rejectReady(t),this.rejectGotSnapshot(t)})),this.resolveReady()})).catch((e=>{const t=`Error subscribing to "${this.StreamName}" stream - ${JSON.stringify(e)}`;this.rejectReady(t),this.rejectGotSnapshot(t)})):(e&&this.resolveReady(),setTimeout((()=>{this.subscribe(!0)}),500))}onEvent(e){return this.callbacks.add("streamEvent",e)}waitFor(e,t){return t||(t=3e4),new Promise(((i,n)=>{let s=!1;const r=this.onEvent((t=>{t.Token===e&&(s=!0,r(),i())}));setTimeout((()=>{s||n("timed out")}),t)}))}checkForLayoutEventMethod(){try{return-1!==this.agm.methods().map((e=>e.name)).indexOf(this.StreamName)}catch(e){return!1}}addLayouts(e,t){if(!e)return;const i=e=>{const t=new Ii(e);vi.add(t),this.callbacks.execute("added",t)};e.forEach((e=>{if(t){vi.first((t=>this.compareLayouts(t,e)))||i(e)}else i(e)}))}removeLayouts(e){e&&e.forEach((e=>{vi.removeWhere((t=>!this.compareLayouts(t,e))),this.callbacks.execute("removed",e)}))}changeLayouts(e){e&&e.forEach((e=>{vi.removeWhere((t=>!this.compareLayouts(t,e))),vi.add(new Ii(e)),this.callbacks.execute("changed",e)}))}renameLayouts(e){e&&e.forEach((e=>{const t=vi.first((t=>this.compareLayouts(t,{type:e.type,name:e.oldName})));if(!t)throw Error(`received rename event for unknown layout with type ${e.type} and name ${e.oldName}`);t.name=e.newName,this.callbacks.execute("renamed",t)}))}compareLayouts(e,t){return e.name===t.name&&e.type===t.type}getObjectValues(e){return e?Object.keys(e).map((t=>e[t])):[]}restoredLayout(e){e&&e.forEach((e=>{const t=vi.first((t=>this.compareLayouts(t,{type:e.type,name:e.name})));this.callbacks.execute("restored",t)}))}}function xi(e){if(!e.agm)throw Error("config.agm is required");if(!e.logger)throw Error("config.logger is required");e.mode=e.mode||"slim";const t=e.logger,i=Jt();let n;return e.mode,n=new Si(e.agm,i),new Ai(e,n,i,t)}class ki{constructor(e,t){this._agm=e,this._logger=t,this._registry=Jt(),this._registered=!1,this.all=async()=>(await this.callGD(Ti.GetAll,{})).map(this.decorateDisplay),this.get=async e=>{const t=await this.callGD(Ti.Get,{id:e});return this.decorateDisplay(t)},this.getPrimary=async()=>(await this.all()).find((e=>e.isPrimary)),this.capture=async e=>await this.callGD(Ti.Capture,{...e}),this.captureAll=async e=>await this.callGD(Ti.CaptureAll,{...e}),this.getMousePosition=async()=>await this.callGD(Ti.GetMousePosition),this.callGD=async(e,t)=>(await this._agm.invoke("T42.Displays.Command",{options:{...t},command:e})).returned.data,this.decorateDisplay=e=>{const t={...e,capture:t=>this.capture({id:e.id,size:t})},i=t.workArea;return i.x=i.left,i.y=t.workArea.top,t}}getByWindowId(e){return this.callGD(Ti.GetByWindowId,{id:e})}onDisplayChanged(e){return this.register(),this._registry.add("on-display-changed",e)}register(){this._registered||(this._registered=!0,this._agm.register("T42.Displays.OnEvent",((e,t)=>{const i=e.event,n=e.data;if("display-changed"===i)this._registry.execute("on-display-changed",n.displays.map(this.decorateDisplay));else this._logger.warn(`unknown event - ${i}`)})))}}var Ti;let Ei,Pi;!function(e){e.Capture="capture",e.CaptureAll="captureAll",e.GetAll="getAll",e.Get="get",e.GetByWindowId="getByWindowId",e.GetMousePosition="getMousePosition"}(Ti||(Ti={}));const Mi="T42.Channels.Announce";async function Ri(e,t){Ei.invoke("T42.Channels.Announce",{swId:null!=t?t:Pi,command:"switchChannel",data:{newChannel:e}})}async function Ni(e){try{return(await Ei.invoke(Mi,{swId:null!=e?e:Pi,command:"getRestrictions"})).returned}catch(e){return}}async function ji(e,t,i){await Ei.invoke(Mi,{command:e,data:{id:t,color:i}})}const Wi="___channel___",Oi="latest_fdc3_type";class Fi{constructor(e){this.contexts=e}subscribe(e){this.callback=e}subscribeFor(e,t){if(!this.isChannel(e))return Promise.reject(new Error(`Channel with name: ${e} doesn't exist!`));const i=this.createContextName(e);return this.contexts.subscribe(i,((e,i,n,s,r)=>{t(e.data,e,null==r?void 0:r.updaterId)}))}async switchChannel(e){this.unsubscribe();const t=this.createContextName(e);this.unsubscribeFunc=await this.contexts.subscribe(t,((e,t,i,n,s)=>{this.callback&&this.callback(e.data,e,null==s?void 0:s.updaterId)}))}leave(){this.callback&&this.callback({},void 0),this.unsubscribe()}all(){return this.contexts.all().filter((e=>e.startsWith(Wi))).map((e=>e.substr(13)))}async getContextData(e){if(!this.isChannel(e))throw new Error(`A channel with name: ${e} doesn't exist!`);const t=this.createContextName(e),i=await this.contexts.get(t);return i[Oi]?this.getContextWithFdc3Data(i):i}updateChannel(e,t){const i=this.createContextName(e);return this.contexts.update(i,t)}updateData(e,t){const i=this.createContextName(e),n=this.getFDC3Type(t);if(this.contexts.setPathSupported){const e=Object.keys(t).map((e=>({path:"data."+e,value:t[e]})));return n&&e.push({path:Oi,value:n}),this.contexts.setPaths(i,e)}return n&&(t[Oi]=n),this.contexts.update(i,{data:t})}setPaths(e,t){const i=this.createContextName(e);if(this.contexts.setPathSupported){const e=t.map((e=>({path:"data."+e.path,value:e.value})));return e.map((t=>{const i=this.getFDC3Type(t.value);i&&e.push({path:Oi,value:i})})),this.contexts.setPaths(i,e)}throw new Error("setPaths is not supported!")}isChannel(e){return this.all().some((t=>t===e))}async remove(e){if(!this.isChannel(e))throw new Error(`A channel with name: ${e} doesn't exist!`);const t=this.createContextName(e);await this.contexts.destroy(t)}unsubscribe(){this.unsubscribeFunc&&this.unsubscribeFunc()}createContextName(e){return Wi+e}getFDC3Type(e){const t=Object.keys(e).filter((e=>0===e.indexOf("fdc3_")));if(0!==t.length){if(t.length>1)throw new Error("FDC3 does not support updating of multiple context keys");return t[0].split("_").slice(1).join("_")}}getContextWithFdc3Data(e){const{latest_fdc3_type:t,...i}=e,n={type:t.split("&").join("."),...i.data[`fdc3_${t}`]};delete i.data[`fdc3_${t}`];return{name:e.name,meta:e.meta,data:{...i.data,fdc3:n}}}}class Di{constructor(e,t,i,n){this.shared=e,this.interop=t,this.getWindows=i,this.logger=n,this.subsKey="subs",this.changedKey="changed",this.isInitialJoin=!0,this.registry=Jt(),this.pendingReplays={},this.pendingRestrictionCallbacks=new Map,this.shared.subscribe(this.handler.bind(this)),this.subscribeForChannelRestrictionsChange(),"undefined"!=typeof window&&void 0!==window.glue42gd&&(this.currentContext=window.glue42gd.initialChannel,this.currentContext&&this.joinNoSelectorSwitch(this.currentContext))}subscribe(e){if("function"!=typeof e)throw new Error("Please provide the callback as a function!");const t=si.generateId();this.pendingReplays[t]=!0;const i=this.getWrappedSubscribeCallback(e,t);if(this.lastUpdate){let e=Object.assign({},this.lastUpdate);setTimeout((async()=>{this.pendingReplays[t]&&(this.lastUpdate&&(e=this.lastUpdate),i(e.context.data,e.context,e.updaterId)),delete this.pendingReplays[t]}),0)}const n=this.registry.add(this.subsKey,i);return()=>{this.pendingReplays[t]=!1,this.pendingRestrictionCallbacks.delete(t),n()}}async subscribeFor(e,t){if("string"!=typeof e)throw new Error("Please provide the name as a string!");if("function"!=typeof t)throw new Error("Please provide the callback as a function!");const i=si.generateId(),n=this.getWrappedSubscribeCallback(t,i),s=await this.shared.subscribeFor(e,n);return()=>{this.pendingRestrictionCallbacks.delete(i),s()}}async publish(e,t){if("object"!=typeof e)throw new Error("Please provide the data as an object!");if(t&&this.validatePublishOptions(t),"object"==typeof t)return this.publishWithOptions(e,t);const i="string"==typeof t?t:this.currentContext;if(!i)throw new Error("Not joined to any channel!");if(!this.shared.isChannel(i))return Promise.reject(new Error(`A channel with name: ${i} doesn't exist!`));if(!(await this.getRestrictionsByChannel(i)).write)throw new Error(`Window does not have permission to write to channel ${this.currentContext}`);return this.shared.updateData(i,e)}async setPaths(e,t){if(t){if("string"!=typeof t)throw new Error("Please provide the name as a string!");if(!this.shared.isChannel(t))return Promise.reject(new Error(`A channel with name: ${t} doesn't exist!`));if(!(await this.getRestrictionsByChannel(t)).write)throw new Error(`Window does not have permission to write to channel ${t}`);return this.shared.setPaths(t,e)}if(!this.currentContext)throw new Error("Not joined to any channel!");if(!(await this.getRestrictionsByChannel(this.currentContext)).write)throw new Error(`Window does not have permission to write to channel ${this.currentContext}`);if(!Array.isArray(e))throw new Error("Path Values argument is not a valid array");return e.forEach((e=>{this.validatePathArgs(e)})),this.shared.setPaths(this.currentContext,e)}async setPath(e,t){if(t){if("string"!=typeof t)throw new Error("Please provide the name as a string!");if(!this.shared.isChannel(t))return Promise.reject(new Error(`A channel with name: ${t} doesn't exist!`));if(!(await this.getRestrictionsByChannel(t)).write)throw new Error(`Window does not have permission to write to channel ${t}`);return this.shared.setPaths(t,[e])}if(!this.currentContext)throw new Error("Not joined to any channel!");if(!(await this.getRestrictionsByChannel(this.currentContext)).write)throw new Error(`Window does not have permission to write to channel ${this.currentContext}`);return this.validatePathArgs(e),this.shared.setPaths(this.currentContext,[e])}all(){const e=this.shared.all();return Promise.resolve(e)}async list(){const e=await this.all();return await Promise.all(e.map((e=>this.get(e))))}get(e){return"string"!=typeof e?Promise.reject(new Error("Please provide the channel name as a string!")):this.shared.getContextData(e)}getMy(){return this.currentContext?this.get(this.currentContext):Promise.resolve(void 0)}async join(e,t){return t?Ri(e,t):this.joinCore(e)}async joinNoSelectorSwitch(e){return this.joinCore(e,!1)}leave(e){return e?Ri(void 0,e):this.leaveCore()}leaveNoSelectorSwitch(){return this.leaveCore(!1)}current(){return this.currentContext}my(){return this.current()}changed(e){if("function"!=typeof e)throw new Error("Please provide the callback as a function!");return this.current()&&setTimeout((()=>{e(this.current())}),0),this.registry.add(this.changedKey,e)}onChanged(e){return this.changed(e)}async add(e){if("object"!=typeof e)throw new Error("Please provide the info as an object!");if(void 0===e.name)throw new Error("info.name is missing!");if("string"!=typeof e.name)throw new Error("Please provide the info.name as a string!");if(void 0===e.meta)throw new Error("info.meta is missing!");if("object"!=typeof e.meta)throw new Error("Please provide the info.meta as an object!");if(void 0===e.meta.color)throw new Error("info.meta.color is missing!");if("string"!=typeof e.meta.color)throw new Error("Please provide the info.meta.color as a string!");const t={name:e.name,meta:e.meta||{},data:e.data||{}};return await this.shared.updateChannel(e.name,t),await ji("addChannel",e.name,e.meta.color),t}async remove(e){if("string"!=typeof e)throw new Error("Please provide the channel name as a string!");await this.shared.remove(e),await ji("removeChannel",e)}async getWindowsOnChannel(e){if("string"!=typeof e)throw new Error("Please provide the channel name as a string!");return(await this.getWindowsWithChannels({channels:[e]})).map((e=>e.window))}async getWindowsWithChannels(e){try{const t=await async function(e){return(await Ei.invoke(Mi,{command:"getChannelsInfo",data:{filter:e}})).returned}(e),i=this.getWindows();if(null==t?void 0:t.windows)return t.windows.map((e=>({window:i.findById(e.windowId),channel:e.channel,application:e.application})))}catch(e){this.logger.error("Error getting all channel enabled windows. This method is available since Glue42 3.12",e)}return[]}async restrict(e){return async function(e){var t;await Ei.invoke(Mi,{swId:null!==(t=e.windowId)&&void 0!==t?t:Pi,command:"restrict",data:e})}(e)}async getRestrictions(e){return Ni(e)}async restrictAll(e){return async function(e){var t;await Ei.invoke(Mi,{swId:null!==(t=e.windowId)&&void 0!==t?t:Pi,command:"restrictAll",data:e})}(e)}handleRestrictionsChanged(e,t){this.registry.execute("restrictions-changed",{restrictions:e,windowId:t})}handler(e,t,i){t||i?(this.lastUpdate={context:t,updaterId:i},this.pendingReplays={},this.registry.execute(this.subsKey,e,t,i)):this.lastUpdate=void 0}async joinCore(e,t=!0){if("string"!=typeof e)throw new Error("Please provide the channel name as a string!");if(!this.isInitialJoin&&e===this.currentContext)return;this.isInitialJoin=!1;const i=e=>this.shared.all().includes(e);if(!i(e)){const t=new Promise(((t,n)=>{const s=setInterval((()=>{i(e)&&(clearTimeout(r),clearInterval(s),t())}),100),r=setTimeout((()=>(clearInterval(s),n(new Error(`A channel with name: ${e} doesn't exist!`)))),3e3)}));await t}this.currentContext=e,this.lastUpdate=void 0,await this.shared.switchChannel(e),t&&Ri(e),this.registry.execute(this.changedKey,e)}leaveCore(e=!0){return this.currentContext=void 0,this.registry.execute(this.changedKey,void 0),this.shared.leave(),e&&Ri(),Promise.resolve()}async getRestrictionsByChannel(e){var t;const i=null!==(t=this.channelRestrictions)&&void 0!==t?t:await Ni();if(!i||!Array.isArray(i.channels)||!i.channels.find((t=>t.name===e)))return{read:!0,write:!0};return i.channels.find((t=>t.name===e))}onRestrictionsChanged(e,t,i){this.pendingRestrictionCallbacks.set(t,{cb:e,channelName:i}),this.onRestrictionsChangedSub||(this.onRestrictionsChangedSub=this.registry.add("restrictions-changed",(({restrictions:e})=>{this.pendingRestrictionCallbacks.forEach((({cb:t,channelName:i},n)=>{const s=e.channels.find((e=>e.name===i));s&&s.read&&(this.pendingRestrictionCallbacks.delete(n),0===this.pendingRestrictionCallbacks.values.length&&this.onRestrictionsChangedSub&&(this.onRestrictionsChangedSub(),this.onRestrictionsChangedSub=null),t())}))})))}subscribeForChannelRestrictionsChange(){this.registry.add("restrictions-changed",(e=>{this.channelRestrictions=e.restrictions}))}validatePathArgs(e){if(!e)throw new Error("Please provide a valid path value argument");if("object"!=typeof e)throw new Error(`Path Value argument is not a valid object: ${JSON.stringify(e)}`);if(!e.path)throw new Error(`path property is missing from Path Value argument: ${JSON.stringify(e)}`);if(!e.value)throw new Error(`value property is missing from Path Value argument: ${JSON.stringify(e)}`);if("string"!=typeof e.path)throw new Error(`path property is not a valid string from the Path Value argument: ${JSON.stringify(e)}`)}validatePublishOptions(e){if("string"!=typeof e&&"object"!=typeof e||Array.isArray(e))throw new Error("Provide options as a string or an object");if("object"!=typeof e){if("string"===e&&!e.length)throw new Error("Provide options as a non-empty string")}else this.validatePublishOptionsObject(e)}validatePublishOptionsObject(e){if("object"!=typeof e||Array.isArray(e))throw new Error("Provide options as an object");if(e.name&&("string"!=typeof e.name||!e.name.length))throw new Error("Provide options.name as a non-empty string");if(Object.keys(e).includes("fdc3")&&"boolean"!=typeof e.fdc3)throw new Error("Provide options.fdc3 as a boolean")}async publishWithOptions(e,t){const i=t.name||this.currentContext;if(!this.shared.isChannel(i))throw new Error(`A channel with name: ${t.name} doesn't exist!`);if(!i)throw new Error("Cannot publish to channel, because not joined to a channel!");if(!(await this.getRestrictionsByChannel(i)).write)throw new Error(`Window does not have permission to write to channel ${this.currentContext}`);return t.fdc3?this.publishFdc3Data(i,e):this.shared.updateData(i,e)}async publishFdc3Data(e,t){var i;if("string"!=typeof t.type||!(null===(i=t.type)||void 0===i?void 0:i.length))throw new Error("Expected a valid FDC3 Context with compulsory 'type' field");const{type:n,...s}=t,r={[`fdc3_${n.split(".").join("&")}`]:s};return this.shared.updateData(e,r)}getWrappedSubscribeCallback(e,t){return async(i,n,s)=>{const r=await this.getRestrictionsByChannel(n.name),o=this.getDataWithFdc3Encoding(n);r.read?e(o,n,s):this.onRestrictionsChanged((()=>{e(o,n,s)}),t,n.name)}}getDataWithFdc3Encoding(e){const{data:t,latest_fdc3_type:i}=e;if(!i)return t;const n=i.split("&").join("."),s=`fdc3_${i}`,r={type:n,...t[s]},{[s]:o,...a}=t;return{...a,fdc3:r}}}function Li(e,t,i,n){const s=new Fi(e),r=new Di(s,t,i,n),o=async function(e,t){var i,n;if(Ei=e,"undefined"!=typeof window&&window.glue42gd&&(Pi=window.glue42gd.windowId),!Pi)return;await Ei.register("T42.Channels.Command",(e=>{const i=e.command;if(!i)throw new Error("missing command argument");if("join"!==i)if("leave"!==i){if("get"===i)return{id:t.current()};if("restrictions-changed"!==i){if("isFdc3DataWrappingSupported"===i)return{isSupported:!0};throw new Error(`unknown command ${i}`)}{const i=e.restrictions,n=e.swId;t.handleRestrictionsChanged(i,n)}}else t.leaveNoSelectorSwitch();else{const i=e.channel;if(!i)throw new Error("missing argument id");t.joinNoSelectorSwitch(i)}}));const s=await Ei.invoke("T42.Channels.Announce",{swId:Pi,instance:Ei.instance.instance});(null===(i=s.returned)||void 0===i?void 0:i.restrictions)&&t.handleRestrictionsChanged(null===(n=s.returned)||void 0===n?void 0:n.restrictions,Pi)}(t,r);return{subscribe:r.subscribe.bind(r),subscribeFor:r.subscribeFor.bind(r),publish:r.publish.bind(r),setPath:r.setPath.bind(r),setPaths:r.setPaths.bind(r),all:r.all.bind(r),list:r.list.bind(r),get:r.get.bind(r),join:r.join.bind(r),leave:r.leave.bind(r),restrict:r.restrict.bind(r),getRestrictions:r.getRestrictions.bind(r),restrictAll:r.restrictAll.bind(r),current:r.current.bind(r),my:r.my.bind(r),changed:r.changed.bind(r),onChanged:r.onChanged.bind(r),add:r.add.bind(r),remove:r.remove.bind(r),getWindowsOnChannel:r.getWindowsOnChannel.bind(r),getWindowsWithChannels:r.getWindowsWithChannels.bind(r),getMy:r.getMy.bind(r),ready:async()=>{await Promise.all([e.ready(),o])}}}const $i="T42.Hotkeys.Command";class Gi{constructor(e){this.agm=e,this.registry=Jt(),this.firstHotkey=!0,this.hotkeys=new Map}async register(e,t){if(void 0===e)throw new Error("Hotkey parameter missing");if("string"==typeof e)e={hotkey:e};else{if(!e.hotkey)throw new Error("Info's hotkey parameter missing");e={hotkey:e.hotkey,description:e.description}}const i=this.formatHotkey(e.hotkey);if(this.hotkeys.has(i))throw new Error(`Shortcut for ${i} already registered`);this.firstHotkey&&(this.firstHotkey=!1,await this.registerInvokeAGMMethod()),this.registry.add(i,t),await this.agm.invoke($i,{command:"register",hotkey:i,description:e.description}),this.hotkeys.set(i,e)}async unregister(e){if(void 0===e)throw new Error("hotkey parameter missing");if("string"!=typeof e)throw new Error("hotkey parameter must be string");const t=this.formatHotkey(e);await this.agm.invoke($i,{command:"unregister",hotkey:t}),this.hotkeys.delete(t),this.registry.clearKey(t)}async unregisterAll(){await this.agm.invoke($i,{command:"unregisterAll"}),this.hotkeys.clear(),this.registry.clear()}isRegistered(e){const t=this.formatHotkey(e);return this.hotkeys.has(t)}registerInvokeAGMMethod(){return this.agm.register("T42.Hotkeys.Invoke",(e=>{const t=e.key.toLowerCase(),i=this.hotkeys.get(t);this.registry.execute(t,i)}))}formatHotkey(e){if(e)return e.replace(/\s/g,"").toLowerCase()}}var Bi="6.8.3",Hi=e=>{function t(e,t,n){if("boolean"==typeof e&&!e)return;const s=i(e,t,n);return void 0!==s?"object"==typeof e?(e.mode=s,e):{mode:s}:void 0}function i(e,t,n){return"object"==typeof e?i(e.mode,t,n).toString():void 0===e?"boolean"!=typeof t||t?"boolean"==typeof t&&t?void 0===n?t:n:void 0===t?void 0:t:void 0:"boolean"==typeof e?e?void 0===n?t:n:void 0:e}const n=!si.isNode()&&"trackMyTypeAndInitiatedFromMe",s="slim",r=s,o="boolean"==typeof e.exposeAPI||"boolean"==typeof e.exposeGlue;return{layouts:t(e.layouts,s,r),activities:t(e.activities,n,"trackMyTypeAndInitiatedFromMe"),appManager:t(e.appManager,!0,"startOnly"),windows:t(e.windows,!0,!0),channels:t(e.channels,!1,!0),displays:t(e.displays,!0,!0),exposeAPI:o||!0}};class Ui{constructor(e){this.options=e,this.callbacks=Jt(),this.actions=e.actions,this.body=e.body,this.badge=e.badge,this.data=e.data,this.dir=e.dir,this.icon=e.icon,this.image=e.image,this.lang=e.lang,this.renotify=e.renotify,this.requireInteraction=e.requireInteraction,this.silent=e.silent,this.tag=e.tag,this.timestamp=e.timestamp,this.title=e.title}close(){throw new Error("Method not implemented.")}addEventListener(e,t,i){this.callbacks.add(e,t)}removeEventListener(e,t,i){}dispatchEvent(e){return this.callbacks.execute(e.type,e),!0}}class qi{constructor(e,t){this.interop=e,this.onStreamEvent=t}onVisibilityChanged(e){return this.onStreamEvent("on-panel-visibility-changed",e)}toggle(){return this.interop.invoke("T42.Notifications.Show")}show(){return this.interop.invoke("T42.Notifications.Show",{show:!0})}hide(){return this.interop.invoke("T42.Notifications.Hide")}async isVisible(){return(await this.interop.invoke("T42.Notifications.Execute",{command:"isPanelVisible"})).returned.panelVisible}toAPI(){return{onVisibilityChanged:this.onVisibilityChanged.bind(this),toggle:this.toggle.bind(this),show:this.show.bind(this),hide:this.hide.bind(this),isVisible:this.isVisible.bind(this)}}}class Ji{constructor(e,t){this.interop=e,this.NotificationsSubscribeStream="T42.GNS.Subscribe.Notifications",this.NotificationsCounterStream="T42.Notifications.Counter",this.RaiseNotificationMethodName="T42.GNS.Publish.RaiseNotification",this.NotificationsExecuteMethod="T42.Notifications.Execute",this.methodsRegistered=!1,this.NOTIFICATIONS_CONFIGURE_METHOD_NAME="T42.Notifications.Configure",this.methodNameRoot="T42.Notifications.Handler-"+si.generateId(),this.nextId=0,this.notifications={},this.registry=Jt(),this.subscribedForNotifications=!1,this.subscribedCounterStream=!1,this.subscriptionsCountForNotifications=0,this.subscriptionsCountForCounter=0,this.logger=t.subLogger("notifications"),this._panel=new qi(e,this.onStreamEventCore.bind(this)),this._panelAPI=this._panel.toAPI(),this.subscribeInternalEvents()}get maxActions(){return 2}get panel(){return this._panelAPI}async raise(e){var t,i,n,s;if(this.validate(e),!this.methodsRegistered){const e=[];for(let t=0;t<this.maxActions;t++)e.push(this.interop.register(`${this.methodNameRoot}_${t}`,this.handleNotificationEvent.bind(this)));this.methodsRegistered=!0,await Promise.all(e)}const r=String(this.nextId++),o=null!==(t=e.type)&&void 0!==t?t:"Notification",a={id:e.id,state:null!==(i=e.state)&&void 0!==i?i:"Active",title:e.title,type:o,severity:null!==(n=e.severity)&&void 0!==n?n:"None",description:e.body,glueRoutingDetailMethodName:`${this.methodNameRoot}_0`,actions:[],sourceId:r,source:e.source,publishExtraEvents:!0,clickInterop:e.clickInterop};e.actions&&this.handleActions(e,r,a),this.handleOptions(e,a);const c=new Ui(e);this.notifications[r]=c;try{const e=await this.interop.invoke(this.RaiseNotificationMethodName,{notification:a});c.id=null===(s=e.returned)||void 0===s?void 0:s.id}catch(e){const t=e.message;setTimeout((()=>{this.handleNotificationErrorEvent(c,t)}),1)}return c}async setFilter(e){return(await this.interop.invoke("T42.Notifications.Filter",e)).returned}async getFilter(){return(await this.interop.invoke("T42.Notifications.Filter")).returned}async configure(e){var t,i,n,s,r,o,a,c;if(!e||Array.isArray(e))throw new Error("Invalid options - should be an object.");if(0===Object.values(e).length)throw new Error("The argument must be a non-empty object.");if(void 0!==e.enable&&"boolean"!=typeof e.enable)throw new Error("Expected type of enabled - boolean.");if(void 0!==e.enableToasts&&"boolean"!=typeof e.enableToasts)throw new Error("Expected type of enableToasts - boolean.");if(void 0!==e.toastExpiry&&"number"!=typeof e.toastExpiry)throw new Error("Expected type of toastExpiry - number.");if(e.sourceFilter&&"object"!=typeof e.sourceFilter)throw new Error("Expected type of sourceFilter - object.");if((null===(t=e.sourceFilter)||void 0===t?void 0:t.allowed)&&!Array.isArray(null===(i=e.sourceFilter)||void 0===i?void 0:i.allowed))throw new Error("Expected type of sourceFilter.allowed - array.");if((null===(n=e.sourceFilter)||void 0===n?void 0:n.blocked)&&!Array.isArray(null===(s=e.sourceFilter)||void 0===s?void 0:s.blocked))throw new Error("Expected type of sourceFilter.blocked - array.");if(e.toasts&&"object"!=typeof e.toasts)throw new Error("Expected type of (options.toasts - object.");if((null===(r=e.toasts)||void 0===r?void 0:r.mode)&&"string"!=typeof e.toasts.mode)throw new Error("Expected type of (options.toasts.mode - string.");if((null===(o=e.toasts)||void 0===o?void 0:o.stackBy)&&"string"!=typeof e.toasts.stackBy)throw new Error("Expected type of (options.toasts.stackBy - string.");if(e.placement&&"object"!=typeof e.placement)throw new Error("Expected type of (options.placement - object.");if((null===(a=e.placement)||void 0===a?void 0:a.toasts)&&"string"!=typeof e.placement.toasts)throw new Error("Expected type of (options.placement.toasts - string.");if((null===(c=e.placement)||void 0===c?void 0:c.panel)&&"string"!=typeof e.placement.panel)throw new Error("Expected type of (options.placement.panel - string.");return(await this.interop.invoke(this.NOTIFICATIONS_CONFIGURE_METHOD_NAME,e)).returned}async getConfiguration(){return(await this.interop.invoke(this.NotificationsExecuteMethod,{command:"getConfiguration"})).returned}async list(){return(await this.interop.invoke(this.NotificationsExecuteMethod,{command:"list",data:{statesVersion2:!0}})).returned.notifications}async updateData(e,t){const i={key:"data",value:{stringValue:JSON.stringify(t,((e,t)=>void 0===t?null:t))}};return(await this.interop.invoke(this.NotificationsExecuteMethod,{command:"create-or-update-attribute",data:{id:e,attribute:i}})).returned}onRaised(e){return this.onStreamEventCore("on-notification-raised",e)}onStateChanged(e){return this.onStreamEventCore("on-state-changed",e)}onClosed(e){return this.onStreamEventCore("on-notification-closed",e)}onConfigurationChanged(e){if("function"!=typeof e)throw new Error("Please provide the callback as a function!");this.subscribe();const t=this.registry.add("on-configuration-changed",e);return()=>{t(),this.closeStreamSubscriptionIfNoNeeded()}}onCounterChanged(e){if("function"!=typeof e)throw new Error("Please provide the callback as a function!");this.subscribeForCounterStream();const t=this.registry.add("on-counter-changed",e);return()=>{t(),this.closeStreamCounterSubscriptionIfNoNeeded()}}onDataChanged(e){if("function"!=typeof e)throw new Error("Please provide the callback as a function!");this.subscribe();const t=this.registry.add("on-notification-data-changed",e);return()=>{t(),this.closeStreamSubscriptionIfNoNeeded()}}async clearAll(){await this.interop.invoke(this.NotificationsExecuteMethod,{command:"clearAll"})}async clearOld(){await this.interop.invoke(this.NotificationsExecuteMethod,{command:"clearAllOld",data:{statesVersion2:!0}})}async clear(e){if(!e)throw new Error("The 'id' argument cannot be null or undefined");if("string"!=typeof e)throw new Error("The 'id' argument must be a string");await this.interop.invoke(this.NotificationsExecuteMethod,{command:"clear",data:{id:e}})}async clearMany(e){this.validateNotificationsArr(e),await this.interop.invoke(this.NotificationsExecuteMethod,{command:"clearMany",data:{notifications:e}})}async click(e,t,i){await this.interop.invoke(this.NotificationsExecuteMethod,{command:"click",data:{id:e,action:t,options:i}})}async snooze(e,t){await this.interop.invoke(this.NotificationsExecuteMethod,{command:"snooze",data:{id:e,duration:t}})}async snoozeMany(e,t){if(!t)throw new Error("The 'duration' argument cannot be null or undefined");if("number"!=typeof t)throw new Error("The 'duration' argument must be a valid number");this.validateNotificationsArr(e),await this.interop.invoke(this.NotificationsExecuteMethod,{command:"snoozeMany",data:{notifications:e,duration:t}})}async setState(e,t){if(!e)throw new Error("The 'id' argument cannot be null or undefined");if("string"!=typeof e)throw new Error("The 'id' argument must be a string");if(!t)throw new Error("The 'state' argument cannot be null or undefined");this.validateState(t),await this.interop.invoke(this.NotificationsExecuteMethod,{command:"updateState",data:{id:e,state:t}})}async setStates(e,t){if(!t)throw new Error("The 'state' argument cannot be null or undefined");if("string"!=typeof t)throw new Error("The 'state' argument must be a valid string");this.validateNotificationsArr(e),await this.interop.invoke(this.NotificationsExecuteMethod,{command:"updateStates",data:{notifications:e,state:t}})}toAPI(){return{maxActions:this.maxActions,panel:this._panel.toAPI(),raise:this.raise.bind(this),setFilter:this.setFilter.bind(this),getFilter:this.getFilter.bind(this),configure:this.configure.bind(this),getConfiguration:this.getConfiguration.bind(this),list:this.list.bind(this),onRaised:this.onRaised.bind(this),onStateChanged:this.onStateChanged.bind(this),onClosed:this.onClosed.bind(this),onConfigurationChanged:this.onConfigurationChanged.bind(this),onCounterChanged:this.onCounterChanged.bind(this),onDataChanged:this.onDataChanged.bind(this),clearAll:this.clearAll.bind(this),clearOld:this.clearOld.bind(this),clear:this.clear.bind(this),click:this.click.bind(this),setState:this.setState.bind(this),updateData:this.updateData.bind(this),snooze:this.snooze.bind(this),snoozeMany:this.snoozeMany.bind(this),clearMany:this.clearMany.bind(this),setStates:this.setStates.bind(this)}}onStreamEventCore(e,t){if("function"!=typeof t)throw new Error("Please provide the callback as a function!");this.subscribe();const i=this.registry.add(e,t);return()=>{i(),this.closeStreamSubscriptionIfNoNeeded()}}handleOptions(e,t){if(e.icon&&(t.attributes=t.attributes||[],t.attributes.push({key:"icon",value:{stringValue:e.icon}})),e.data){t.attributes=t.attributes||[];const i=JSON.stringify(e.data);t.attributes.push({key:"data",value:{stringValue:i}})}"number"==typeof e.panelExpiry&&(t.attributes=t.attributes||[],t.attributes.push({key:"panelExpiry",value:{stringValue:e.panelExpiry.toString()}})),"number"==typeof e.toastExpiry&&(t.attributes=t.attributes||[],t.attributes.push({key:"toastExpiry",value:{stringValue:e.toastExpiry.toString()}}))}handleActions(e,t,i){var n,s,r;const o=e.actions.slice(0,this.maxActions);let a=0;for(const e of o){const o={g42notificationId:t,g42action:e.action,g42interopMethod:null===(n=e.interop)||void 0===n?void 0:n.method,g42interopTarget:null===(s=e.interop)||void 0===s?void 0:s.target,g42interopArguments:JSON.stringify(null===(r=e.interop)||void 0===r?void 0:r.arguments)},c=Object.keys(o).map((e=>({name:e,value:{stringValue:o[e]}}))),d={name:`${this.methodNameRoot}_${a}`,description:e.title,displayName:e.title,parameters:c};i.actions.push(d),a++}}validate(e){if(!e)throw new Error("invalid options - should be an object");if("object"!=typeof e)throw new Error("invalid options - should be an object");if(!e.title)throw new Error("invalid options - should have a title");if("string"!=typeof e.title)throw new Error("invalid options - title should be a string");if(e.severity&&"string"!=typeof e.severity)throw new Error("invalid options - severity should be a string");if(e.panelExpiry&&"number"!=typeof e.panelExpiry)throw new Error("invalid options - panelExpiry should be a number");if(e.toastExpiry&&"number"!=typeof e.toastExpiry)throw new Error("invalid options - toastExpiry should be a number");e.state&&this.validateState(e.state)}validateState(e){if("string"!=typeof e)throw new Error("The 'state' argument must be a string");if(!["Active","Acknowledged","Stale"].includes(e))throw new Error(`The state argument: ${e} is not valid!`)}subscribe(){this.subscriptionsCountForNotifications++,this.subscribedForNotifications||(this.subscribedForNotifications=!0,this.logger.info(`Attempting to subscribe to "${this.NotificationsSubscribeStream}".`),this.interop.subscribe(this.NotificationsSubscribeStream,{arguments:{sendDeltaOnly:!0,statesVersion2:!0}}).then((e=>{this.subscriptionForNotifications=e,this.logger.info(`Successfully subscribed to "${this.NotificationsSubscribeStream}".`),e.onData((({data:e})=>{this.handleData(e)})),e.onClosed(((...e)=>{this.subscribedForNotifications=!1,this.logger.info(`Stream subscription Closed - ${JSON.stringify(e)}`)})),e.onFailed(((...e)=>{this.subscribedForNotifications=!1,this.logger.warn(`Stream subscription Failed - ${JSON.stringify(e)}`)}))})).catch((e=>{this.subscribedForNotifications=!1,this.logger.error(`Unable to subscribe to "${this.NotificationsSubscribeStream}"`,e)})))}subscribeForCounterStream(){this.subscriptionsCountForCounter++,this.subscribedCounterStream||(this.subscribedCounterStream=!0,this.logger.info(`Attempting to subscribe to "${this.NotificationsCounterStream}".`),this.interop.subscribe(this.NotificationsCounterStream,{arguments:{sendDeltaOnly:!0}}).then((e=>{this.subscriptionForCounter=e,this.logger.info(`Successfully subscribed to "${this.NotificationsCounterStream}".`),e.onData((({data:e})=>{this.registry.execute("on-counter-changed",{count:e.count})})),e.onClosed(((...e)=>{this.subscribedCounterStream=!1,this.logger.info(`Stream subscription Closed - ${JSON.stringify(e)}`)})),e.onFailed(((...e)=>{this.subscribedCounterStream=!1,this.logger.warn(`Stream subscription Failed - ${JSON.stringify(e)}`)}))})).catch((e=>{this.subscribedCounterStream=!1,this.logger.error(`Unable to subscribe to "${this.NotificationsCounterStream}"`,e)})))}subscribeInternalEvents(){this.registry.add("on-notification-closed",(e=>{this.handleOnClosed(e)})),this.registry.add("on-notification-raised",(e=>{this.handleOnShow(e.id)}))}handleData(e){var t;try{"items"in e&&Array.isArray(e.items)?this.handleItemsData(e):"deltas"in e&&Array.isArray(e.deltas)&&this.handleDeltas(e),"configuration"in e&&"object"==typeof e.configuration&&(this.logger.info(`Received configuration ${JSON.stringify(e.configuration)} from the stream`),this.registry.execute("on-configuration-changed",e.configuration,e.configuration.allApplications)),"command"in e&&"string"==typeof e.command&&(this.logger.info(`Received command "${null!==(t=e.command)&&void 0!==t?t:JSON.stringify(e)}" from the stream`),"showPanel"!==e.command&&"hidePanel"!==e.command||this.registry.execute("on-panel-visibility-changed","showPanel"===e.command))}catch(e){this.logger.error("Failed to parse data from the stream",e)}}handleItemsData(e){const t=e.items;this.logger.info(`Received ${t.length} notifications from the stream`);const i=t;if(e.isSnapshot)i.forEach((e=>{this.registry.execute("on-notification-raised",e)}));else{const e=i[0];"Closed"===e.state?this.registry.execute("on-notification-closed",{id:e.id}):this.registry.execute("on-notification-raised",e)}}handleDeltas(e){e.deltas.forEach((e=>{var t;const i=e.id,n=null!==(t=e.delta)&&void 0!==t?t:{};if("Closed"===n.state)this.registry.execute("on-notification-closed",{id:i,...n});else if(n.state)this.registry.execute("on-state-changed",{id:i},n.state);else if(n.attributes){const e=n.attributes.find((e=>"data"===e.key));e&&this.registry.execute("on-notification-data-changed",{id:i},JSON.parse(e.value.stringValue))}}))}handleOnClosed(e){const{notification:t,key:i}=this.getNotification(e);t&&(this.handleEvent(t,"close"),delete this.notifications[i])}handleOnShow(e){const{notification:t}=this.getNotification(e);t&&this.handleEvent(t,"show")}getNotification(e){let t,i;for(const n in this.notifications)if(this.notifications[n].id===e){t=this.notifications[n],i=n;break}return{notification:t,key:i}}handleNotificationEvent(e){const t=this.getGnsNotificationArgs(e);if("unknown"===t.event)return;const i=this.notifications[t.notificationId];i&&this.handleNotificationEventCore(i,t)}handleNotificationEventCore(e,t){switch(t.event){case"action":return this.handleNotificationActionEvent(e,t.notificationActionPayload);case"click":return this.handleNotificationClickEvent(e);case"close":return this.handleEvent(e,"close");case"error":return this.handleNotificationErrorEvent(e,t.error);case"show":return this.handleEvent(e,"show")}}handleNotificationActionEvent(e,t){const i={type:"onaction",action:t.g42action};e.onaction&&e.onaction(i),e.dispatchEvent(i)}handleNotificationClickEvent(e){const t={type:"onclick"};e.onclick&&e.onclick(t),e.dispatchEvent(t)}handleEvent(e,t){var i;const n={type:t};null===(i=e[`on${t}`])||void 0===i||i.call(e,n),e.dispatchEvent(n)}handleNotificationErrorEvent(e,t){const i={type:"onerror",error:t};e.onerror&&e.onerror(i),e.dispatchEvent(i)}getGnsNotificationArgs(e){var t;let i;const n=null===(t=e.notification)||void 0===t?void 0:t.event;return i=n?{event:n,notificationId:e.notification.sourceNotificationId,notificationActionPayload:e}:this.getBackwardGnsNotificationArgs(e),i}getBackwardGnsNotificationArgs(e){var t;let i;return i=e.g42notificationId?{event:"action",notificationId:e.g42notificationId,notificationActionPayload:e}:(null===(t=e.notification)||void 0===t?void 0:t.sourceNotificationId)?{event:"click",notificationId:e.notification.sourceNotificationId,notificationActionPayload:e}:{event:"unknown",notificationId:void 0,notificationActionPayload:e},i}closeStreamSubscriptionIfNoNeeded(){this.subscriptionsCountForNotifications--,this.subscriptionForNotifications&&0===this.subscriptionsCountForNotifications&&(this.subscriptionForNotifications.close(),this.subscriptionForNotifications=void 0)}closeStreamCounterSubscriptionIfNoNeeded(){this.subscriptionsCountForCounter--,this.subscriptionForCounter&&0===this.subscriptionsCountForCounter&&(this.subscriptionForCounter.close(),this.subscriptionForCounter=void 0)}validateNotificationsArr(e){if(!Array.isArray(e))throw new Error("The 'notifications' argument must be an array with valid notification IDs");if(e.some((e=>"string"!=typeof e)))throw new Error("The 'notifications' argument must contain only valid string notification IDs")}}class Vi{constructor(e,t){this.contexts=e,this.interop=t,this.registry=Jt(),this.isSubscribed=!1,this.getConfiguration()}async list(){if(await this.getConfiguration(),!this.getMethodName)throw new Error("not supported");return(await this.getAll()).returned.all}async getCurrent(){if(await this.getConfiguration(),!this.getMethodName)throw new Error("not supported");const e=await this.getAll();return e.returned.all.find((t=>t.name===e.returned.selected))}async select(e){if(await this.getConfiguration(),!this.setMethodName)throw new Error("not supported");await this.interop.invoke(this.setMethodName,{theme:e})}onChanged(e){return this.subscribe(),this.registry.add("changed",e)}async getConfiguration(){try{if(this.sharedContextName)return;const e=await this.interop.invoke("T42.Themes.Configuration");this.sharedContextName=e.returned.sharedContextName,this.getMethodName=e.returned.getThemesMethodName,this.setMethodName=e.returned.setThemesMethodName}catch(e){return}}async getAll(){return await this.getConfiguration(),await this.interop.invoke(this.getMethodName)}async subscribe(){await this.getConfiguration(),this.isSubscribed||(this.isSubscribed=!0,this.contexts.subscribe(this.sharedContextName,(e=>{e&&e.all&&e.selected&&this.registry.execute("changed",e.all.find((t=>t.name===e.selected)))})))}}const zi="Tick42.FDC3.Intents.",Ki=["applicationName","type"],Qi=(e,t,i)=>new Promise(((n,s)=>{let r=!0;const o=setTimeout((()=>{if(!r)return;r=!1;s(i||`Promise timeout hit: ${t}`)}),t);e().then((e=>{r&&(r=!1,clearTimeout(o),n(e))})).catch((e=>{r&&(r=!1,clearTimeout(o),s(e))}))})),Zi=e=>{var t,i;if("string"!=typeof e.intent)return{isValid:!1,error:"Response object has invalid 'intent' key. Expected a string, got "+typeof e.intent};if((null===(t=e.userSettings)||void 0===t?void 0:t.preserveChoice)&&"boolean"!=typeof(null===(i=e.userSettings)||void 0===i?void 0:i.preserveChoice))return{isValid:!1,error:"Response object has invalid 'userSettings.preserveChoice' key. Expected a boolean, got "+typeof e.userSettings.preserveChoice};const{isValid:n,error:s}=(e=>{if("object"!=typeof e)return{isValid:!1,error:"Response object has invalid 'handler' key. Expected an object, got "+typeof e};const t=Ki.filter((t=>!(t in e)));return t.length?{isValid:!1,error:`Handler in Response object does not provide compulsory keys: ${t.join(", ")}`}:{isValid:!0,ok:e}})(e.handler);return n?{isValid:!0,ok:e}:{isValid:n,error:s}},Xi=e=>{if((e=>{if(e){if("object"!=typeof e)throw new Error("Please provide the intent context as an object");if(e.type&&"string"!=typeof e.type)throw new Error("Please provide the intent context as an object with 'type' property as string");if(e.data&&"object"!=typeof e.data)throw new Error("Please provide the intent context as an object with 'data' property as object")}})(e.context),(e=>{if(e&&"string"!=typeof e&&"object"!=typeof e)throw new Error('Please provide the intent target as one of the valid values: "reuse", "startNew", { app: string }, { instance: string } ')})(e.target),(e=>{if(e){if("number"!=typeof e)throw new Error("Please provide the timeout as a number");if(e<=0)throw new Error("Please provide the timeout as a positive number")}})(e.timeout),(e=>{if(e&&"boolean"!=typeof e)throw new Error("Please provide waitUserResponseIndefinitely as a boolean")})(e.waitUserResponseIndefinitely),void 0!==e.clearSavedHandler&&"boolean"!=typeof e.clearSavedHandler)throw new Error("Please provide 'clearSavedHandler' as a boolean");e.handlers&&e.handlers.forEach((e=>(e=>{if(!e.applicationName)throw new Error(`Please provide applicationName for handler ${JSON.stringify(e)}`);if(!e.type)throw new Error(`Please provide type for handler ${JSON.stringify(e)}`);if("instance"===e.type&&!e.instanceId)throw new Error(`Please provide instanceId for handler ${JSON.stringify(e)}`)})(e)))};class Yi{constructor(e,t,i,n,s,r){this.interop=e,this.windows=t,this.logger=i,this.prefsController=s,this.appManager=r,this.myIntents=new Set,this.intentsResolverResponsePromises={},this.useIntentsResolverUI=!0,this.unregisterIntentPromises=[],this.checkIfIntentsResolverIsEnabled(n,r)}async find(e){await Promise.all(this.unregisterIntentPromises);let t=await this.all();if(void 0===e)return t;if("string"==typeof e)return t.filter((t=>t.name===e));if("object"!=typeof e)throw new Error("Please provide the intentFilter as a string or an object!");if(e.contextType){const i=e.contextType.toLowerCase();t=t.filter((e=>e.handlers.some((e=>{var t;return null===(t=e.contextTypes)||void 0===t?void 0:t.some((e=>e.toLowerCase()===i))}))))}if(e.resultType){const i=e.resultType.toLowerCase();t=t.filter((e=>e.handlers.some((e=>{var t;return(null===(t=e.resultType)||void 0===t?void 0:t.toLowerCase())===i}))))}return e.name&&(t=t.filter((t=>t.name===e.name))),t}async raise(e){if("string"!=typeof e&&"object"!=typeof e||"object"==typeof e&&"string"!=typeof e.intent)throw new Error("Please provide the intent as a string or an object with an intent property!");"string"==typeof e&&(e={intent:e}),Xi(e),await Promise.all(this.unregisterIntentPromises),e.clearSavedHandler&&(this.logger.trace(`User removes saved handler for intent ${e.intent}`),await this.removeRememberedHandler(e.intent));const t={},i=e.waitUserResponseIndefinitely?2147483647:e.timeout||9e4,n=await this.checkHandleRaiseWithRememberedHandler(e,t,i);if(n)return n;const s=this.coreRaiseIntent.bind(this,{request:e,resolverInstance:t,timeout:i});if(e.waitUserResponseIndefinitely)return s();const r=Qi(s,i,`Timeout of ${i}ms hit for intent request ${JSON.stringify(e)}`);return r.catch((()=>this.handleRaiseOnError(t.instanceId))),r}async all(){let e;await Promise.all(this.unregisterIntentPromises);try{const t=await this.interop.invoke("T42.ACS.GetApplications",{withIntentsInfo:!0});e=t.returned.applications}catch(e){return this.logger.error("Failed to get the applications!",e),[]}const t={},i=e.filter((e=>e.intents&&e.intents.length>0));for(const e of i)for(const i of e.intents){let n=t[i.name];n||(n={name:i.name,handlers:[]},t[i.name]=n);const s={applicationName:e.name,applicationTitle:e.title||"",applicationDescription:e.caption,displayName:i.displayName,contextTypes:i.contexts,applicationIcon:e.icon,type:"app",resultType:i.resultType};n.handlers.push(s)}const n=this.interop.servers(),s=n.map((e=>e.windowId)).filter((e=>void 0!==e)),r="T42.Wnd.GetInfo";let o;if(this.interop.methods().some((e=>e.name===r)))try{const e=await this.interop.invoke(r,{ids:s});o=e.returned.windows}catch(e){}for(const i of n)await Promise.all(i.getMethods().filter((e=>e.name.startsWith(zi))).map((async n=>{const s=n.name.replace(zi,"");let r=t[s];r||(r={name:s,handlers:[]},t[s]=r);const a=n.flags.intent,c=e.find((e=>e.name===i.application));let d;c&&c.intents&&(d=c.intents.find((e=>e.name===s)));const h=await this.windowsIdToTitle(i.windowId,o),u={instanceId:i.instance,applicationName:i.application,applicationIcon:a.icon||(null==c?void 0:c.icon),applicationTitle:(null==c?void 0:c.title)||"",applicationDescription:a.description||(null==c?void 0:c.caption),displayName:a.displayName||(null==d?void 0:d.displayName),contextTypes:a.contextTypes||(null==d?void 0:d.contexts),instanceTitle:h,type:"instance",resultType:(null==d?void 0:d.resultType)||a.resultType};r.handlers.push(u)})));return Object.values(t)}addIntentListener(e,t){if("string"!=typeof e&&"object"!=typeof e||"object"==typeof e&&"string"!=typeof e.intent)throw new Error("Please provide the intent as a string or an object with an intent property!");if("function"!=typeof t)throw new Error("Please provide the handler as a function!");const i="string"==typeof e?e:e.intent,n=`${zi}${i}`;let s,r={};if(this.myIntents.has(i))throw new Error(`Intent listener for intent ${i} already registered!`);this.myIntents.add(i);const o={unsubscribe:()=>{this.myIntents.delete(i),s.then((()=>this.interop.unregister(n))).catch((e=>this.logger.trace(`Unregistration of a method with name ${n} failed with reason: ${JSON.stringify(e)}`)))}};if("object"==typeof e){const{intent:t,...i}=e;r=i}return s=this.interop.register({name:n,flags:{intent:r}},(e=>{if(this.myIntents.has(i))return t(e)})),s.catch((e=>{this.myIntents.delete(i),this.logger.warn(`Registration of a method with name ${n} failed with reason: ${JSON.stringify(e)}`)})),o}async register(e,t){if("string"!=typeof e&&"object"!=typeof e||"object"==typeof e&&"string"!=typeof e.intent)throw new Error("Please provide the intent as a string or an object with an intent property!");if("function"!=typeof t)throw new Error("Please provide the handler as a function!");await Promise.all(this.unregisterIntentPromises);const i="string"==typeof e?e:e.intent,n=this.buildInteropMethodName(i);let s={};if(this.myIntents.has(i))throw new Error(`Intent listener for intent ${i} already registered!`);if(this.myIntents.add(i),"object"==typeof e){const{intent:t,...i}=e;s=i}try{await this.interop.register({name:n,flags:{intent:s}},((e,n)=>{if(this.myIntents.has(i))return t(e,n)}))}catch(e){throw this.myIntents.delete(i),new Error(`Registration of a method with name ${n} failed with reason: ${JSON.stringify(e)}`)}return{unsubscribe:()=>this.unsubscribeIntent(i)}}async filterHandlers(e){var t,i;if((e=>{if(!e)throw new Error("Provide 'handlerFilter' with at least one filter criteria of the following: 'intent' | 'contextTypes' | 'resultType' | 'applicationNames'");const{title:t,openResolver:i,timeout:n,intent:s,contextTypes:r,resultType:o,applicationNames:a}=e;if(void 0!==t&&("string"!=typeof t||!t.length))throw new Error("Provide 'title' as a non empty string");if(void 0!==i&&"boolean"!=typeof i)throw new Error("Provide 'openResolver' prop as a boolean");if(void 0!==n&&("number"!=typeof n||n<=0))throw new Error("Provide 'timeout' prop as a positive number");if(void 0!==s&&("string"!=typeof s||!s.length))throw new Error("Provide 'intent' as a non empty string");if(void 0!==r&&(!Array.isArray(r)||r.some((e=>"string"!=typeof e))))throw new Error("Provide 'contextTypes' as an array of non empty strings");if(void 0!==o&&("string"!=typeof o||!o.length))throw new Error("Provide 'resultType' as a non empty string");if(void 0!==a&&(!Array.isArray(a)||a.some((e=>"string"!=typeof e))))throw new Error("Provide 'applicationNames' as an array of non empty strings");const c="Provide at least one filter criteria of the following: 'intent' | 'contextTypes' | 'resultType' | 'applicationNames'";if(!Object.keys(e).length)throw new Error(c);if(!(s||o||r&&r.length||a&&a.length))throw new Error(c)})(e),e.openResolver&&!this.useIntentsResolverUI)throw new Error("Cannot resolve 'filterHandlers' request using Intents Resolver UI because it's globally disabled");null===(t=this.logger)||void 0===t||t.trace(`Received 'filterHandlers' command with request: ${JSON.stringify(e)}`);const n=this.filterHandlersBy(await this.all(),e);if(!n||!n.length)return{handlers:[]};const{open:s,reason:r}=this.checkIfResolverShouldBeOpenedForFilterHandlers(n,e);if(!s)return null===(i=this.logger)||void 0===i||i.trace(`Intent Resolver UI won't be used. Reason: ${r}`),{handlers:n};const o={instanceId:void 0},a=e.timeout||9e4;return{handlers:[await Qi((()=>this.startResolverApp({request:e,resolverInstance:o,method:"filterHandlers"})),a,`Timeout of ${a}ms hit for 'filterHandlers' request with filter: ${JSON.stringify(e)}`)]}}async getIntents(e){var t;this.logger.trace(`Received 'getIntents' command with handler ${JSON.stringify(e)}`),(e=>{if("object"!=typeof e)throw new Error("IntentHandler must be an object");if("string"!=typeof e.applicationName||!e.applicationName.length)throw new Error("Please provide 'applicationName' as a non-empty string");if("string"!=typeof e.type||!["app","instance"].includes(e.type))throw new Error(`Invalid 'type' property. Expected 'app' | 'instance' got ${e.type}`);if(void 0!==e.applicationTitle&&"string"!=typeof e.applicationTitle)throw new Error("Provide 'applicationTitle' as a string");if(void 0!==e.applicationDescription&&"string"!=typeof e.applicationDescription)throw new Error("Provide 'applicationDescription' as a string");if(void 0!==e.applicationIcon&&"string"!=typeof e.applicationIcon)throw new Error("Provide 'applicationIcon' as a string");if(void 0!==e.displayName&&"string"!=typeof e.displayName)throw new Error("Provide 'displayName' as a string");if(void 0!==e.contextTypes&&(!Array.isArray(e.contextTypes)||e.contextTypes.some((e=>"string"!=typeof e))))throw new Error("Provide 'contextTypes' as an array of non empty strings");if(void 0!==e.instanceId&&"string"!=typeof e.instanceId)throw new Error("Provide 'instanceId' as a string");if(void 0!==e.instanceTitle&&"string"!=typeof e.instanceTitle)throw new Error("Provide 'instanceTitle' as a string");if(void 0!==e.resultType&&"string"!=typeof e.resultType)throw new Error("Provide 'resultType' as a string")})(e);const i=await this.all();var n;n=e,Object.keys(n).forEach((e=>{null!==n[e]&&void 0!==n[e]||delete n[e]})),null===(t=this.logger)||void 0===t||t.trace("Extracting valid intents for the passed handler");const s=this.extractIntentsWithInfoByHandler(i,e);return this.logger.trace(`Returning intents for handler ${JSON.stringify(e)}`),{intents:s}}async clearSavedHandlers(){this.logger.trace("Removing all saved handlers from prefs storage for current app"),await this.prefsController.update({intents:void 0})}filterHandlersBy(e,t){const i=e.filter((e=>{if(!t.intent||t.intent===e.name){if(t.resultType){const i=e.handlers.filter((e=>e.resultType&&e.resultType===t.resultType));if(!i.length)return;e.handlers=i}if(t.contextTypes){const i=e.handlers.filter((e=>{var i;return null===(i=t.contextTypes)||void 0===i?void 0:i.every((t=>{var i;return null===(i=e.contextTypes)||void 0===i?void 0:i.includes(t)}))}));if(!i.length)return;e.handlers=i}if(t.applicationNames){const i=e.handlers.filter((e=>{var i;return null===(i=t.applicationNames)||void 0===i?void 0:i.includes(e.applicationName)}));if(!i.length)return;e.handlers=i}return e}}));return i.map((e=>e.handlers)).flat(1)}async coreRaiseIntent({request:e,resolverInstance:t,timeout:i}){var n,s;const r=await this.get(e.intent);if(void 0===r)throw new Error(`Intent ${e.intent} not found.`);const{open:o,reason:a}=this.checkIfResolverShouldBeOpenedForRaise(r,e);if(!o)return this.logger.trace(`Intent Resolver UI won't be used. Reason: ${a}`),e.waitUserResponseIndefinitely?Qi((()=>this.raiseIntent(e,i)),i,`Timeout of ${i}ms hit for raise to resolve`):this.raiseIntent(e,i);const c=await this.startResolverApp({request:e,method:"raise",resolverInstance:t});if(null===(n=this.logger)||void 0===n||n.trace(`Raising intent to target handler: ${JSON.stringify(c)} with timeout of ${i}`),e.waitUserResponseIndefinitely)return Qi((()=>this.raiseIntentToTargetHandler(e,c,i)),i,`Timeout of ${i}ms hit for raise to resolve`);const d=await this.raiseIntentToTargetHandler(e,c,i);return null===(s=this.logger)||void 0===s||s.trace(`Result from raise() method for intent ${JSON.stringify(e.intent)}: ${JSON.stringify(d)}`),d}async get(e){return(await this.all()).find((t=>t.name===e))}async raiseIntent(e,t){const i=e.intent,n=await this.get(i);if(void 0===n)throw new Error(`Intent ${i} not found.`);const s=e.handlers?this.findHandlerByFilter(e.handlers,{type:"app"}):this.findHandlerByFilter(n.handlers,{type:"app"}),r=e.handlers?this.findHandlerByFilter(e.handlers,{type:"instance"}):this.findHandlerByFilter(n.handlers,{type:"instance"});let o;if(e.target&&"reuse"!==e.target||(o=r||s),"startNew"===e.target&&(o=s),"object"==typeof e.target&&e.target.app&&(o=this.findHandlerByFilter(n.handlers,{app:e.target.app})),"object"==typeof e.target&&e.target.instance&&(o=this.findHandlerByFilter(n.handlers,{instance:e.target.instance,app:e.target.app})),!o)throw new Error(`Can not raise intent for request ${JSON.stringify(e)} - can not find intent handler!`);return await this.raiseIntentToTargetHandler(e,o,t)}async raiseIntentToTargetHandler(e,t,i){var n,s;null===(n=this.logger)||void 0===n||n.trace(`Raising intent to target handler:${JSON.stringify(t)}`),t.instanceId||(t.instanceId=await this.invokeStartApp(t.applicationName,e.context,e.options));const r=`${zi}${e.intent}`,o={methodResponseTimeoutMs:i?i+1e3:6e4,waitTimeoutMs:i?i+1e3:6e4},a=await this.interop.invoke(r,e.context,{instance:t.instanceId},o);return null===(s=this.logger)||void 0===s||s.trace(`raiseIntent command completed. Returning result: ${JSON.stringify(a)}`),{request:e,handler:{...t,type:"instance"},result:a.returned}}async startResolverApp({request:e,method:t,resolverInstance:i}){var n,s,r,o;null===(n=this.logger)||void 0===n||n.trace(`Intents Resolver UI with app name ${this.intentsResolverAppName} will be used for request: ${JSON.stringify(e)}`);const a=await this.registerIntentResolverMethod();null===(s=this.logger)||void 0===s||s.trace(`Registered interop method ${a}`);const c=this.buildStartContext(t,e,a),d=await this.buildStartOptions();null===(r=this.logger)||void 0===r||r.trace(`Starting Intents Resolver UI with context: ${JSON.stringify(c)} and options: ${JSON.stringify(d)}`);const h=await this.appManager.application(this.intentsResolverAppName).start(c,d);i.instanceId=h.id,null===(o=this.logger)||void 0===o||o.trace(`Intents Resolver instance with id ${h.id} opened`),this.subscribeOnInstanceStopped(h,t);const u=(e.timeout,9e4);this.createResponsePromise({intent:"raise"===t?e.intent:void 0,instanceId:h.id,responseMethodName:a,timeout:u,errorMsg:`Timeout of ${u}ms hit waiting for the user to choose a handler ${"raise"===t?`for intent ${e.intent}`:`for '${t}' method with filter ${JSON.stringify(e)}`}`});return await this.handleInstanceResponse({instanceId:h.id,caller:c.initialCaller,method:t,request:e})}async windowsIdToTitle(e,t){var i,n;if(void 0!==t)return null===(i=t.find((t=>t.id===e)))||void 0===i?void 0:i.title;const s=null===(n=this.windows)||void 0===n?void 0:n.findById(e);return await(null==s?void 0:s.getTitle())}async handleInstanceResponse({instanceId:e,method:t,request:i,caller:n}){var s,r,o;try{const a=await this.intentsResolverResponsePromises[e].promise,c="raise"===t?`for intent ${a.intent} `:"";return null===(s=this.logger)||void 0===s||s.trace(`Intent handler chosen ${c}: ${JSON.stringify(a.handler)}. Stopping resolver instance with id ${e}`),this.stopResolverInstance(e),null===(r=this.logger)||void 0===r||r.trace(`Instance with id ${e} successfully stopped`),(null===(o=a.userSettings)||void 0===o?void 0:o.preserveChoice)&&await this.saveUserChoice({intent:a.intent,handler:a.handler,filter:"filterHandlers"===t?{applicationNames:i.applicationNames,contextTypes:i.contextTypes,resultType:i.resultType}:void 0,caller:n}),a.handler}catch(t){throw this.stopResolverInstance(e),new Error(t)}}async registerIntentResolverMethod(){const e="T42.Intents.Resolver.Control"+si.generateId();return await this.interop.register(e,((e,t)=>this.resolverResponseHandler(e,t))),e}resolverResponseHandler(e,t){const{instance:i}=t,n=Zi(e);if(!n)return this.logger.trace(`Intent Resolver instance with id ${t.instance} sent invalid response. Error: ${n.error}`),this.intentsResolverResponsePromises[i].reject(n.error),void this.stopResolverInstance(i);const s=n.ok;this.intentsResolverResponsePromises[i].resolve(s),this.cleanUpIntentResolverPromise(i)}buildStartContext(e,t,i){var n;const s=this.interop.instance.application||this.interop.instance.applicationName,r=(null===(n=this.appManager.application(s))||void 0===n?void 0:n.title)||"",o={callerId:this.interop.instance.instance,methodName:i,initialCaller:{id:this.interop.instance.instance,applicationName:s,applicationTitle:r},resolverApi:"1.0"};return"raise"===e?{...o,intent:t}:{...o,handlerFilter:t}}async buildStartOptions(){const e=this.windows.my();if(!e)return;const t=await e.getBounds();return{top:(t.height-440)/2+t.top,left:(t.width-400)/2+t.left,width:400,height:440}}createResponsePromise({instanceId:e,intent:t,responseMethodName:i,timeout:n,errorMsg:s}){let r=()=>{},o=()=>{};const a=((e,t,i)=>new Promise(((n,s)=>{const r=setTimeout((()=>{s(i||`Promise timeout hit: ${t}`)}),t);new Promise(e).then((e=>{clearTimeout(r),n(e)})).catch((e=>{clearTimeout(r),s(e)}))})))(((e,t)=>{r=e,o=t}),n,s);this.intentsResolverResponsePromises[e]={intent:t,resolve:r,reject:o,promise:a,methodName:i}}async invokeStartApp(e,t,i){return(await this.interop.invoke("T42.ACS.StartApplication",{Name:e,options:{...i,startedByIntentAPI:!0}})).returned.Id}subscribeOnInstanceStopped(e,t){const{application:i}=e,n=i.onInstanceStopped((i=>{if(i.id!==e.id)return;const s=this.intentsResolverResponsePromises[i.id];if(!s)return n();const r=`Cannot resolve ${"raise"===t?`raised intent ${s.intent}`:`'${t}' method`} - User closed ${e.application.name} app without choosing a handler`;s.reject(r),this.cleanUpIntentResolverPromise(i.id),n()}))}async cleanUpIntentResolverPromise(e){const t=this.intentsResolverResponsePromises[e];if(!t)return;this.interop.unregister(t.methodName).catch((e=>this.logger.warn(e))),delete this.intentsResolverResponsePromises[e]}handleRaiseOnError(e){e&&this.stopResolverInstance(e)}stopResolverInstance(e){const t=this.windows.findById(e);null==t||t.close().catch((e=>this.logger.error(e)))}checkIfIntentsResolverIsEnabled(e,t){var i,n,s,r,o;t?(this.useIntentsResolverUI="boolean"!=typeof(null===(i=e.intents)||void 0===i?void 0:i.enableIntentsResolverUI)||e.intents.enableIntentsResolverUI,this.intentsResolverAppName=null!==(s=null===(n=e.intents)||void 0===n?void 0:n.intentsResolverAppName)&&void 0!==s?s:"intentsResolver",this.intentsResolverResponseTimeout=null!==(o=null===(r=e.intents)||void 0===r?void 0:r.methodResponseTimeoutMs)&&void 0!==o?o:6e4):this.useIntentsResolverUI=!1}checkIfResolverShouldBeOpenedForRaise(e,t){const i=this.checkIfIntentsResolverShouldBeOpened();if(!i.open)return i;return this.checkIfIntentHasMoreThanOneHandler(e,t)?{open:!0}:{open:!1,reason:`Raised intent ${e.name} has only one handler`}}checkIfResolverShouldBeOpenedForFilterHandlers(e,t){return 1===e.length?{open:!1,reason:`There's only one valid intent handler for filter ${JSON.stringify(t)}`}:"boolean"!=typeof(null==t?void 0:t.openResolver)||t.openResolver?this.checkIfIntentsResolverShouldBeOpened():{open:!1,reason:"Intents resolver is disabled by IntentHandler filter"}}checkIfIntentsResolverShouldBeOpened(){if(!this.useIntentsResolverUI)return{open:!1,reason:"Intent Resolver is disabled. Resolving to first found handler"};return this.appManager.application(this.intentsResolverAppName)?{open:!0}:{open:!1,reason:`Intent Resolver Application with name ${this.intentsResolverAppName} not found.`}}checkIfIntentHasMoreThanOneHandler(e,t){return t.target?"reuse"===t.target?t.handlers?t.handlers.filter((e=>"instance"===e.type&&e.instanceId)).length>1||t.handlers.filter((e=>"app"===e.type)).length>1:e.handlers.filter((e=>"instance"===e.type&&e.instanceId)).length>1||e.handlers.filter((e=>"app"===e.type)).length>1:"startNew"===t.target?t.handlers?t.handlers.filter((e=>"app"===e.type)).length>1:e.handlers.filter((e=>"app"===e.type)).length>1:(t.target,!1):t.handlers?t.handlers.length>1:e.handlers.length>1}buildInteropMethodName(e){return`${zi}${e}`}clearUnregistrationPromise(e){this.unregisterIntentPromises=this.unregisterIntentPromises.filter((t=>t!==e))}unsubscribeIntent(e){this.myIntents.delete(e);const t=this.buildInteropMethodName(e),i=this.interop.unregister(t);this.unregisterIntentPromises.push(i),i.then((()=>{this.clearUnregistrationPromise(i)})).catch((e=>{this.logger.error(`Unregistration of a method with name ${t} failed with reason: `,e),this.clearUnregistrationPromise(i)}))}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}extractIntentsWithInfoByHandler(e,t){const i=e.reduce(((e,i)=>(i.handlers.forEach((n=>{const s=Object.keys(t).every((e=>{var i;return"contextTypes"===e?null===(i=t.contextTypes)||void 0===i?void 0:i.every((e=>{var t;return null===(t=n.contextTypes)||void 0===t?void 0:t.includes(e)})):n[e]===t[e]}));if(!s)return;const r={intent:i.name,contextTypes:n.contextTypes,description:n.applicationDescription,displayName:n.displayName,icon:n.applicationIcon,resultType:n.resultType};e.push(r)})),e)),[]);return i}async removeRememberedHandler(e){var t;this.logger.trace(`Removing saved handler from prefs storage for intent ${e}`);const i=await this.prefsController.get(),n=null===(t=i.data)||void 0===t?void 0:t.intents;if(!n)return void this.logger.trace("No app prefs found for current app");delete n[e];const s={...i.data,intents:n};await this.prefsController.update(s),this.logger.trace(`Handler saved choice for intent ${e} removed successfully`)}async checkForRememberedHandler(e){var t,i;const n=null===(i=null===(t=(await this.prefsController.get()).data)||void 0===t?void 0:t.intents)||void 0===i?void 0:i[e.intent];return null==n?void 0:n.handler}async checkHandleRaiseWithRememberedHandler(e,t,i){const n=await this.checkForRememberedHandler(e);if(!n)return;const s={...e,target:{app:n.applicationName,instance:n.instanceId}};try{return await this.coreRaiseIntent({request:s,resolverInstance:t,timeout:i})}catch(t){this.logger.trace("Could not raise intent to remembered handler. Removing it from Prefs store"),await this.removeRememberedHandler(e.intent)}}async saveUserChoice({intent:e,handler:t,filter:i,caller:n}){var s,r;const o=await this.prefsController.get(n.applicationName),a=(null===(s=null==o?void 0:o.data)||void 0===s?void 0:s.intents)||{},c={...o.data,intents:{...a,[e]:{handler:t,filter:i}}};await this.prefsController.update(c,{app:n.applicationName}),null===(r=this.logger)||void 0===r||r.info(`Saved user's choice of handler for '${n.applicationName}' app`)}}class en{constructor(e,t){this.appName=e,this.interop=t,this.registry=Jt(),this.interopMethodRegistered=!1}async get(e){return(await this.interop.invoke("T42.Prefs.Get",{app:null!=e?e:this.appName})).returned}async set(e,t){var i;this.verifyDataObject(e),await this.interop.invoke("T42.Prefs.Set",{app:null!==(i=null==t?void 0:t.app)&&void 0!==i?i:this.appName,data:e,merge:!1})}async setFor(e,t){return this.verifyApp(e),this.verifyDataObject(t),this.set(t,{app:e})}async update(e,t){var i;this.verifyDataObject(e),await this.interop.invoke("T42.Prefs.Set",{app:null!==(i=null==t?void 0:t.app)&&void 0!==i?i:this.appName,data:e,merge:!0})}async updateFor(e,t){return this.verifyApp(e),this.verifyDataObject(t),this.update(t,{app:e})}async clear(e){await this.interop.invoke("T42.Prefs.Set",{app:null!=e?e:this.appName,clear:!0})}async clearFor(e){this.verifyApp(e),await this.interop.invoke("T42.Prefs.Set",{app:e,clear:!0})}async getAll(){return(await this.interop.invoke("T42.Prefs.Get")).returned}async clearAll(){await this.interop.invoke("T42.Prefs.Set",{clear:!0})}subscribe(e){return this.verifyCallback(e),this.subscribeFor(this.appName,e)}subscribeFor(e,t){this.verifyApp(e),this.verifyCallback(t);const i=this.registry.add(e,t);return this.registerInteropIfNeeded().then((()=>{this.interop.invoke("T42.Prefs.Get",{app:e,subscribe:!0})})),()=>{i()}}async registerInteropIfNeeded(){this.interopMethodRegistered||(this.interopMethodRegistered=!0,await this.interop.register("T42.Prefs.Update",(e=>{this.registry.execute(e.app,e)})))}verifyApp(e){if(!e)throw new Error("app should be defined");if(!Ve(e))throw new Error("app should be a string")}verifyDataObject(e){if(!e)throw new Error("data should be defined");if(!ze(e))throw new Error("data should be an object")}verifyCallback(e){if(!et(e))throw new Error("callback should be defined")}}class tn{constructor(e,t){this.methodName=e,this.interop=t}async get(e){return(await this.invoke("get-cookies",{filter:e})).returned.cookies}async set(e){this.verifyCookieObject(e),await this.invoke("set-cookie",e)}async remove(e,t){if(!Ve(e))throw new Error("url should be a string");if(!Ve(t))throw new Error("name should be a string");await this.invoke("remove-cookie",{url:e,name:t})}invoke(e,t){return this.interop.invoke(this.methodName,{command:e,args:t})}verifyCookieObject(e){if(!e)throw new Error("cookie should be defined");if(!ze(e))throw new Error("cookie should be an object")}}class nn{constructor(e){this.config=e,this.glue42EventName="Glue42",this.events={notifyStarted:{name:"notifyStarted",handle:this.handleNotifyStarted.bind(this)},requestGlue:{name:"requestGlue",handle:this.handleRequestGlue.bind(this)}}}start(e){si.isNode()||(this.glue=e,this.wireCustomEventListener(),this.announceStarted())}wireCustomEventListener(){window.addEventListener(this.glue42EventName,(e=>{const t=e.detail;if(!t||!t.glue42)return;const i=t.glue42.event,n=this.events[i];n&&n.handle(t.glue42.message)}))}announceStarted(){this.send("start")}handleRequestGlue(){this.config.exposeAPI?this.send("requestGlueResponse",{glue:this.glue}):this.send("requestGlueResponse",{error:"Will not give access to the underlying Glue API, because it was explicitly denied upon initialization."})}handleNotifyStarted(){this.announceStarted()}send(e,t){const i={glue42:{event:e,message:t}},n=new CustomEvent(this.glue42EventName,{detail:i});window.dispatchEvent(n)}}const sn=new class{constructor(){this.initialized=!1,this.details=[],this.reject=()=>{},this.resolve=()=>{}}init(e){this.initialized=!0,this.addCall(e),this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}addCall(e){this.details.push({date:new Date,config:e})}done(e){this.resolve(e)}error(e){this.reject(e)}},rn=async e=>{let t=!1;sn.initialized||(t=!0,sn.init(e));const i="undefined"!=typeof window&&window.glue42gd;if(i&&!t)return sn.addCall(e),sn.promise;const n=await on(e,i);return sn.resolve(n),n},on=async(e,t)=>{const i=si.getGDMajorVersion(),n=Hi(e=e||{});let s,r,o,a,c,d;e.gateway=e.gateway||{};const h=new nn(n);function u(e,t,i){const n=t.subLogger(e);if(i&&i.logger){const e=i.logger;e.console&&n.consoleLevel(e.console),e.publish&&n.publishLevel(e.publish)}return n}const l={libs:[{name:"windows",create:function(e){if(n.windows){const t=u("windows",e.logger,n.windows);return o=wi(e.agm,t,(()=>s),(()=>a),(()=>c),i),g(o),o}}},{name:"activities",create:function(e){var a;if(n.activities&&Lt.checkIsUsingGW3Implementation&&Lt.checkIsUsingGW3Implementation(e.connection)){const c=u("activity",e.logger,n.activities);return r=new Lt({connection:e.connection,contexts:e.contexts,agm:e.agm,logger:c,logLevel:"info",disableAutoAnnounce:!1,disposeRequestHandling:"exit",announcementInfo:null,windows:o,appManagerGetter:()=>s,mode:n.activities.mode,typesToTrack:n.activities.typesToTrack,activityId:null===(a=null==t?void 0:t.activityInfo)||void 0===a?void 0:a.activityId,gdMajorVersion:i}).api,g(r),r}}},{name:"appManager",create:function(e){if(!n.appManager)return;const t=u("appManager",e.logger,n.appManager);return s=ni({agm:e.agm,windows:o,logger:t,activities:r,mode:n.appManager.mode,gdMajorVersion:i}),g(s),s}},{name:"layouts",create:function(e){var t;if(!n.layouts)return;const o=u("layouts",e.logger,n.layouts),a=n.layouts,c=xi({agm:e.agm,appManager:s,activityGetter:()=>r,logger:o,mode:a.mode,autoSaveWindowContext:null!==(t=a.autoSaveWindowContext)&&void 0!==t&&t,gdMajorVersion:i});return g(c),c}},{name:"channels",create:function(e){if(!n.channels)return;if(!e.contexts)return;const t=u("channels",e.logger,n.channels);return c=Li(e.contexts,e.agm,(()=>o),t),g(c),c}},{name:"hotkeys",create:function(e){const t=function(e){const t=new Gi(e);return{register:t.register.bind(t),unregister:t.unregister.bind(t),unregisterAll:t.unregisterAll.bind(t),isRegistered:t.isRegistered.bind(t),ready:()=>Promise.resolve()}}(e.agm);return g(t),t}},{name:"displays",create:function(e){if(n.displays){const t=u("displays",e.logger,n.displays);return a=new ki(e.agm,t),g(a),a}}},{name:"prefs",create:function(i){var n,s;const r=null!==(s=null!==(n=e.application)&&void 0!==n?n:null==t?void 0:t.applicationName)&&void 0!==s?s:i.interop.instance.application;return d=new en(r,i.interop),g(d),d}},{name:"intents",create:function(t){const i=new Yi(t.agm,o,t.logger.subLogger("intents"),e,d,s);return g(i),i}},{name:"notifications",create:function(e){const t=new Ji(e.interop,e.logger).toAPI();return g(t),t}},{name:"themes",create:function(e){if(!e.contexts)return;const t=function(e,t){const i=new Vi(e,t);return{list:i.list.bind(i),getCurrent:i.getCurrent.bind(i),select:i.select.bind(i),onChanged:i.onChanged.bind(i),ready:()=>Promise.resolve()}}(e.contexts,e.interop);return g(t),t}},{name:"cookies",create:function(e){const t=function(e,t){const i=new tn(t,e);return{get:i.get.bind(i),remove:i.remove.bind(i),set:i.set.bind(i),ready:()=>Promise.resolve()}}(e.interop,"T42.GD.Execute");return g(t),t}}],version:Bi,enrichGlue:e=>{e.config.activities=n.activities,e.config.windows=n.windows,e.config.appManager=n.appManager,e.config.layouts=n.layouts,e.config.channels=n.channels,e.config.displays=n.displays}},p=[];function g(e){p.push(e)}"undefined"!=typeof window&&(window.glueFactoryLog||(window.glueFactoryLog=[]),window.glueFactoryLog.push(p));const m=await Ue(e,l);return Array.isArray(null==e?void 0:e.libraries)&&e.libraries.length&&await Promise.all(e.libraries.map((t=>t(m,e)))),h.start(m),m};var an,cn;rn.coreVersion=Ue.version,rn.version=Bi,rn.calls=sn;let dn=rn,hn=!0;if("undefined"!=typeof window){const e=window,t=null!==(an=e.iodesktop)&&void 0!==an?an:e.glue42gd;t&&t.autoInjected&&(dn=null!==(cn=e.IODesktop)&&void 0!==cn?cn:e.Glue,hn=!1),hn&&(e.Glue=dn,e.IODesktop=dn),delete e.IOBrowser,delete e.GlueCore}return dn.default=dn,dn}));
2
2
  //# sourceMappingURL=desktop.browser.min.js.map