@interopio/desktop 6.0.0

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.
@@ -0,0 +1,2 @@
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):((t="undefined"!=typeof globalThis?globalThis:t||self).desktop=t.desktop||{},t.desktop.min=e())}(this,(function(){"use strict";var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};function e(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function i(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}var n=function(){return n=Object.assign||function(t){for(var e,n=1,i=arguments.length;n<i;n++)for(var o in e=arguments[n])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t},n.apply(this,arguments)};function i(t,e,n,i){return new(n||(n=Promise))((function(o,r){function s(t){try{c(i.next(t))}catch(t){r(t)}}function a(t){try{c(i.throw(t))}catch(t){r(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(s,a)}c((i=i.apply(t,e||[])).next())}))}function o(t,e){var n,i,o,r,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return r={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function a(a){return function(c){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;r&&(r=0,a[0]&&(s=0)),s;)try{if(n=1,i&&(o=2&a[0]?i.return:a[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,a[1])).done)return o;switch(i=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,i=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!(o=s.trys,(o=o.length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){s.label=a[1];break}if(6===a[0]&&s.label<o[1]){s.label=o[1],o=a;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(a);break}o[2]&&s.ops.pop(),s.trys.pop();continue}a=e.call(t,s)}catch(t){a=[6,t],i=0}finally{n=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}}function r(t,e,n){if(n||2===arguments.length)for(var i,o=0,r=e.length;o<r;o++)!i&&o in e||(i||(i=Array.prototype.slice.call(e,0,o)),i[o]=e[o]);return t.concat(i||Array.prototype.slice.call(e))}var s={STRING:1,NUMBER:2,TIMESTAMP:3,OBJECT:4};function a(t){return t.type===s.TIMESTAMP?"timestamp":t.type===s.NUMBER?"number":t.type===s.STRING?"string":t.type===s.OBJECT?"object":"unknown"}function c(t){return t.constructor===Date?"timestamp":"number"==typeof t?"number":"string"==typeof t?"string":"object"==typeof t?"object":"string"}function d(t){var e={},n=a(t);if("object"===n){var i=Object.keys(t.value).reduce((function(e,n){var i=c(t.value[n]);if("object"===i){var o=u(t.value[n]);e[n]={type:"object",description:"",context:{},composite:o}}else e[n]={type:i,description:"",context:{}};return e}),{});e.composite=i}return e.name=h(t.path.join("/")+"/"+t.name),e.type=n,e.description=t.description,e.context={},e}function u(t){return Object.keys(t).reduce((function(e,n){var i=c(t[n]);return e[n]="object"===i?{type:"object",description:"",context:{},composite:u(t[n])}:{type:i,description:"",context:{}},e}),{})}function h(t){return void 0!==t&&t.length>0&&"/"!==t[0]?"/"+t:t}function l(t){return"timestamp"===a(t)?Date.now():p(t.value)}function p(t){return"object"!=typeof t?t:Object.keys(t).reduce((function(e,n){var i=t[n];return"object"==typeof i&&i.constructor!==Date?e[n]=p(i):i.constructor===Date?e[n]=new Date(i).getTime():i.constructor===Boolean?e[n]=i.toString():e[n]=i,e}),{})}function g(t){return t.reduce((function(t,e){return t.concat(Array.isArray(e)?g(e):e)}),[])}function f(t){var e=g(t.root.getAggregateState()),n=e.sort((function(t,e){return t.state?e.state?e.state-t.state:-1:1}))[0],i=function(t){var e="";return t.forEach((function(t,n,i){var o=t.path.join(".");n===i.length-1?e+=o+"."+t.name+": "+t.description:e+=o+"."+t.name+": "+t.description+","})),e.length>100?e.slice(0,100)+"...":e}(e);return{description:i,value:n.state}}var y=function(t,e,n){if(null===t||"object"!=typeof t)throw new Error("Missing definition");if(null===e||"object"!=typeof e)throw new Error("Missing parent");if(null===n||"object"!=typeof n)throw new Error("Missing transport")},m=function(){function t(t,e,n,i,o){this.definition=t,this.system=e,this.transport=n,this.value=i,this.type=o,this.path=[],y(t,e,n),this.path=e.path.slice(0),this.path.push(e.name),this.name=t.name,this.description=t.description,n.createMetric(this)}return Object.defineProperty(t.prototype,"repo",{get:function(){var t;return null===(t=this.system)||void 0===t?void 0:t.repo},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"id",{get:function(){return"".concat(this.system.path,"/").concat(name)},enumerable:!1,configurable:!0}),t.prototype.update=function(t){return this.value=t,this.transport.updateMetric(this)},t}(),v=function(t){function n(e,n,i,o){return t.call(this,e,n,i,o,s.NUMBER)||this}return e(n,t),n.prototype.incrementBy=function(t){this.update(this.value+t)},n.prototype.increment=function(){this.incrementBy(1)},n.prototype.decrement=function(){this.incrementBy(-1)},n.prototype.decrementBy=function(t){this.incrementBy(-1*t)},n}(m),w=function(t){function n(e,n,i,o){return t.call(this,e,n,i,o,s.OBJECT)||this}return e(n,t),n.prototype.update=function(t){return this.mergeValues(t),this.transport.updateMetric(this)},n.prototype.mergeValues=function(t){var e=this;return Object.keys(this.value).forEach((function(n){void 0!==t[n]&&(e.value[n]=t[n])}))},n}(m),b=function(t){function n(e,n,i,o){return t.call(this,e,n,i,o,s.STRING)||this}return e(n,t),n}(m),_=function(t){function n(e,n,i,o){return t.call(this,e,n,i,o,s.TIMESTAMP)||this}return e(n,t),n.prototype.now=function(){this.update(new Date)},n}(m);function I(t,e,n,i,o){if(!e)throw new Error("Repository is required");if(!n)throw new Error("Transport is required");var r,a,c=n,d=t,u=o||"",h=e,l=i,p=function t(e){if(!e||!e.parent)return[];var n=t(e.parent);return n.push(e.name),n}(i),g={},f=(a="/",((r=p)&&r.length>0?r.join(a):"")+t),y=e.root,m=[],C=[];function A(t,e,n,i){var o={name:""};o="string"==typeof t?{name:t}:t;var r=C.filter((function(t){return t.name===o.name}));if(r.length>0){var s=r[0];if(s.type!==e)throw new Error("A metric named ".concat(o.name," is already defined with different type."));return void 0!==n&&s.update(n).catch((function(){})),s}var a=i(o);return C.push(a),a}var S={get name(){return d},get description(){return u},get repo(){return h},get parent(){return l},path:p,id:f,root:y,get subSystems(){return m},get metrics(){return C},subSystem:function(t,e){if(!t||0===t.length)throw new Error("name is required");var n=m.filter((function(e){return e.name===t}));if(n.length>0)return n[0];var i=I(t,h,c,S,e);return m.push(i),i},getState:function(){return g},setState:function(t,e){g={state:t,description:e},c.updateSystem(S,g)},stringMetric:function(t,e){return A(t,s.STRING,e,(function(t){return new b(t,S,c,e)}))},timestampMetric:function(t,e){return A(t,s.TIMESTAMP,e,(function(t){return new _(t,S,c,e)}))},objectMetric:function(t,e){return A(t,s.OBJECT,e,(function(t){return new w(t,S,c,e)}))},numberMetric:function(t,e){return A(t,s.NUMBER,e,(function(t){return new v(t,S,c,e)}))},getAggregateState:function(){var t=[];return Object.keys(g).length>0&&t.push({name:d,path:p,state:g.state,description:g.description}),m.forEach((function(e){var n=e.getAggregateState();n.length>0&&t.push.apply(t,n)})),t}};return c.createSystem(S),S}var C=function(){function t(t,e){e.init(this),this.root=I("",this,e),this.addSystemMetrics(this.root,t.clickStream||void 0===t.clickStream)}return t.prototype.addSystemMetrics=function(t,e){if("undefined"!=typeof navigator&&t.stringMetric("UserAgent",navigator.userAgent),e&&"undefined"!=typeof document){var n=t.subSystem("ClickStream"),i=function(t){var e;if(t.target){var i=t.target,o=i&&null!==(e=i.getAttribute("class"))&&void 0!==e?e:"";n.objectMetric("LastBrowserEvent",{type:"click",timestamp:new Date,target:{className:o,id:i.id,type:"<"+i.tagName.toLowerCase()+">",href:i.href||""}})}};n.objectMetric("Page",{title:document.title,page:window.location.href}),document.addEventListener?document.addEventListener("click",i):document.attachEvent("onclick",i)}t.stringMetric("StartTime",(new Date).toString());var o=t.stringMetric("StartURL",""),r=t.stringMetric("AppName","");if("undefined"!=typeof window){if(void 0!==window.location){var s=window.location.href;o.update(s)}void 0!==window.glue42gd&&r.update(window.glue42gd.appName)}},t}(),A=function(){function t(){}return t.prototype.init=function(t){},t.prototype.createSystem=function(t){return Promise.resolve()},t.prototype.updateSystem=function(t,e){return Promise.resolve()},t.prototype.createMetric=function(t){return Promise.resolve()},t.prototype.updateMetric=function(t){return Promise.resolve()},t}(),S=function(){function t(t,e,n){this.api=t,this.lastCount=0,this.initialPublishTimeout=1e4,this.publishInterval=6e4,this.initialPublishTimeout=null!=e?e:this.initialPublishTimeout,this.publishInterval=null!=n?n:this.publishInterval,this.scheduleCollection(),this.system=this.api.subSystem("performance","Performance data published by the web application")}return t.prototype.scheduleCollection=function(){var t=this;setTimeout((function(){t.collect(),setInterval((function(){t.collect()}),t.publishInterval)}),this.initialPublishTimeout)},t.prototype.collect=function(){try{this.collectMemory(),this.collectEntries()}catch(t){}},t.prototype.collectMemory=function(){var t=window.performance.memory;this.system.stringMetric("memory",JSON.stringify({totalJSHeapSize:t.totalJSHeapSize,usedJSHeapSize:t.usedJSHeapSize}))},t.prototype.collectEntries=function(){var t=window.performance.getEntries();if(!(t.length<=this.lastCount)){this.lastCount=t.length;var e=t.map((function(t){return t.toJSON()}));this.system.stringMetric("entries",JSON.stringify(e))}},t}(),x=function(t){var e;e=t.connection&&"object"==typeof t.connection?function(t,e){var r,s,a=this;if(!t||"object"!=typeof t)throw new Error("Connection is required parameter");var c=function(t){u(t.root)},u=function(t){p(t),t.metrics.forEach((function(t){g(t)})),t.subSystems.forEach((function(t){u(t)}))},p=function(t){return i(a,void 0,void 0,(function(){var e,n;return o(this,(function(i){switch(i.label){case 0:return void 0===t.parent?[2]:[4,r];case 1:return i.sent(),e={name:h(t.path.join("/")+"/"+t.name+"/State"),type:"object",composite:{Description:{type:"string",description:""},Value:{type:"number",description:""}},description:"System state",context:{}},n={type:"define",metrics:[e]},s.send(n),[2]}}))}))},g=function(t){return i(a,void 0,void 0,(function(){var e,n,i;return o(this,(function(o){switch(o.label){case 0:return e=m(t),[4,r];case 1:return o.sent(),n=d(e),i={type:"define",metrics:[n]},s.send(i),void 0!==e.value&&y(e),[2]}}))}))},y=function(t){if(v()){var e=l(t),n={type:"publish",values:[{name:h(t.path.join("/")+"/"+t.name),value:e,timestamp:Date.now()}]};return s.sendFireAndForget(n)}return Promise.resolve()},m=function(t){var e=n({},t);return"object"==typeof t.value&&null!==t.value&&(e.value=n({},t.value)),e},v=function(){var t;try{return(null!==(t=e.canUpdateMetric)&&void 0!==t?t:function(){return!0})()}catch(t){return!0}};return{init:function(n){var i;r=new Promise((function(t){i=t})),(s=t.domain("metrics")).onJoined((function(t){!t&&i&&(i(),i=void 0);var e={type:"define",metrics:[{name:"/State",type:"object",composite:{Description:{type:"string",description:""},Value:{type:"number",description:""}},description:"System state",context:{}}]};s.send(e),t&&c(n)})),s.join({system:e.system,service:e.service,instance:e.instance})},createSystem:p,updateSystem:function(e,n){return i(a,void 0,void 0,(function(){var i,a,c;return o(this,(function(o){switch(o.label){case 0:return[4,r];case 1:return o.sent(),i={type:"publish",values:[{name:h(e.path.join("/")+"/"+e.name+"/State"),value:{Description:n.description,Value:n.state},timestamp:Date.now()}]},s.send(i),a=f(e),c={type:"publish",peer_id:t.peerId,values:[{name:"/State",value:{Description:a.description,Value:a.value},timestamp:Date.now()}]},s.send(c),[2]}}))}))},createMetric:g,updateMetric:function(t){return i(a,void 0,void 0,(function(){var e;return o(this,(function(n){switch(n.label){case 0:return e=m(t),[4,r];case 1:return n.sent(),y(e),[2]}}))}))}}}(t.connection,t):new A;var r=new C(t,e).root;t.disableAutoAppSystem||(r=r.subSystem("App"));var s=function(t){var e,n=t.subSystem("reporting"),i={name:"features"},o=function(t,o,r){if(void 0===t||""===t)throw new Error("name is mandatory");if(void 0===o||""===o)throw new Error("action is mandatory");if(void 0===r||""===r)throw new Error("payload is mandatory");e?e.update({name:t,action:o,payload:r}):e=n.objectMetric(i,{name:t,action:o,payload:r})};return t.featureMetric=o,t}(r);return function(t,e){var n,i;if("undefined"==typeof window)return;var o=null===(i=null===(n=null===window||void 0===window?void 0:window.glue42gd)||void 0===n?void 0:n.metrics)||void 0===i?void 0:i.pagePerformanceMetrics;o&&(e=o);(null==e?void 0:e.enabled)&&new S(t,e.initialPublishTimeout,e.publishInterval)}(s,t.pagePerformanceMetrics),s};var k="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function T(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function E(t){if(t&&t.errorHandling&&"function"!=typeof t.errorHandling&&"log"!==t.errorHandling&&"silent"!==t.errorHandling&&"throw"!==t.errorHandling)throw new Error('Invalid options passed to createRegistry. Prop errorHandling should be ["log" | "silent" | "throw" | (err) => void], but '+typeof t.errorHandling+" was passed");var e=t&&"function"==typeof t.errorHandling&&t.errorHandling,n={};function i(n,i){var o=n instanceof Error?n:new Error(n);if(e)e(o);else{var r='[ERROR] callback-registry: User callback for key "'+i+'" failed: '+o.stack;if(t)switch(t.errorHandling){case"log":return console.error(r);case"silent":return;case"throw":throw new Error(r)}console.error(r)}}return{add:function(t,e,o){var r=n[t];return r||(r=[],n[t]=r),r.push(e),o&&setTimeout((function(){o.forEach((function(o){var r;if(null===(r=n[t])||void 0===r?void 0:r.includes(e))try{Array.isArray(o)?e.apply(void 0,o):e.apply(void 0,[o])}catch(e){i(e,t)}}))}),0),function(){var i=n[t];i&&(0===(i=i.reduce((function(t,n,i){return n===e&&t.length===i||t.push(n),t}),[])).length?delete n[t]:n[t]=i)}},execute:function(t){for(var e=[],o=1;o<arguments.length;o++)e[o-1]=arguments[o];var r=n[t];if(!r||0===r.length)return[];var s=[];return r.forEach((function(n){try{var o=n.apply(void 0,e);s.push(o)}catch(e){s.push(void 0),i(e,t)}})),s},clear:function(){n={}},clearKey:function(t){n[t]&&delete n[t]}}}E.default=E;var P=E,M=function(){function t(t,e){var n=this;this.registry=P(),this.gw=t.facade,this.gw.connect((function(t,e){n.messageHandler(e)})).then((function(t){n.client=t}))}return Object.defineProperty(t.prototype,"isObjectBasedTransport",{get:function(){return!0},enumerable:!1,configurable:!0}),t.prototype.sendObject=function(t){return this.client?(this.client.send(t),Promise.resolve(void 0)):Promise.reject("not connected")},t.prototype.send=function(t){return Promise.reject("not supported")},t.prototype.onMessage=function(t){return this.registry.add("onMessage",t)},t.prototype.onConnectedChanged=function(t){return t(!0),function(){}},t.prototype.close=function(){return Promise.resolve()},t.prototype.open=function(){return Promise.resolve()},t.prototype.name=function(){return"in-memory"},t.prototype.reconnect=function(){return Promise.resolve()},t.prototype.messageHandler=function(t){this.registry.execute("onMessage",t)},t}(),R=function(){function t(t,e){var n=this;this.logger=e,this.registry=P(),this.worker=new SharedWorker(t),this.worker.port.onmessage=function(t){n.messageHandler(t.data)}}return Object.defineProperty(t.prototype,"isObjectBasedTransport",{get:function(){return!0},enumerable:!1,configurable:!0}),t.prototype.sendObject=function(t){return this.worker.port.postMessage(t),Promise.resolve()},t.prototype.send=function(t){return Promise.reject("not supported")},t.prototype.onMessage=function(t){return this.registry.add("onMessage",t)},t.prototype.onConnectedChanged=function(t){return t(!0),function(){}},t.prototype.close=function(){return Promise.resolve()},t.prototype.open=function(){return Promise.resolve()},t.prototype.name=function(){return"shared-worker"},t.prototype.reconnect=function(){return Promise.resolve()},t.prototype.messageHandler=function(t){this.registry.execute("onMessage",t)},t}(),N=function(){function t(){}return t.isNode=function(){if(void 0!==t._isNode)return t._isNode;if("undefined"!=typeof window)return t._isNode=!1,!1;try{t._isNode="[object process]"===Object.prototype.toString.call(global.process)}catch(e){t._isNode=!1}return t._isNode},t}(),j=function(){function t(){var t=this;this.rejected=!1,this.resolved=!1,this.promise=new Promise((function(e,n){t.resolve=function(n){t.resolved=!0,e(n)},t.reject=function(e){t.rejected=!0,n(e)}}))}return t.delay=function(t){return new Promise((function(e){return setTimeout(e,t)}))},Object.defineProperty(t.prototype,"ended",{get:function(){return this.rejected||this.resolved},enumerable:!1,configurable:!0}),t}(),O={};function W(t){var e=O[t];if(e)return e;var n=[];function i(){return(new Date).getTime()}var o,r,s=i();function a(t,e){var o=null!=e?e:i(),r=0;n.length>0&&(r=o-n[n.length-1].time),n.push({name:t,time:o,diff:r})}a("start",s);var c={get startTime(){return s},get endTime(){return o},get period(){return r},stop:function(){return a("end",o=i()),r=o-s},mark:a,marks:n};return O[t]=c,c}var F=N.isNode()?require("ws"):window.WebSocket,L=function(){function t(t,e){if(this.startupTimer=W("connection"),this._running=!0,this._registry=P(),this.wsRequests=[],this.settings=t,this.logger=e,!this.settings.ws)throw new Error("ws is missing")}return t.prototype.onMessage=function(t){return this._registry.add("onMessage",t)},t.prototype.send=function(t,e){var n=this;return new Promise((function(e,i){n.waitForSocketConnection((function(){var o;try{null===(o=n.ws)||void 0===o||o.send(t),e()}catch(t){i(t)}}),i)}))},t.prototype.open=function(){var t=this;return this.logger.info("opening ws..."),this._running=!0,new Promise((function(e,n){t.waitForSocketConnection(e,n)}))},t.prototype.close=function(){return this._running=!1,this.ws&&this.ws.close(),Promise.resolve()},t.prototype.onConnectedChanged=function(t){return this._registry.add("onConnectedChanged",t)},t.prototype.name=function(){return this.settings.ws},t.prototype.reconnect=function(){var t;null===(t=this.ws)||void 0===t||t.close();var e=new j;return this.waitForSocketConnection((function(){e.resolve()})),e.promise},t.prototype.waitForSocketConnection=function(t,e){var n;e=null!=e?e:function(){},this._running?1!==(null===(n=this.ws)||void 0===n?void 0:n.readyState)?(this.wsRequests.push({callback:t,failed:e}),this.wsRequests.length>1||this.openSocket()):t():e("wait for socket on ".concat(this.settings.ws," failed - socket closed by user"))},t.prototype.openSocket=function(t,e){return i(this,void 0,void 0,(function(){var n=this;return o(this,(function(i){switch(i.label){case 0:if(this.startupTimer.mark("opening-socket"),void 0===t&&(t=this.settings.reconnectInterval),void 0===e&&(e=this.settings.reconnectAttempts),void 0!==e){if(0===e)return this.notifyForSocketState("wait for socket on ".concat(this.settings.ws," failed - no more retries left")),[2];this.logger.debug("will retry ".concat(e," more times (every ").concat(t," ms)"))}i.label=1;case 1:return i.trys.push([1,3,,4]),[4,this.initiateSocket()];case 2:return i.sent(),this.startupTimer.mark("socket-initiated"),this.notifyForSocketState(),[3,4];case 3:return i.sent(),setTimeout((function(){var i=void 0===e?void 0:e-1;n.openSocket(t,i)}),t),[3,4];case 4:return[2]}}))}))},t.prototype.initiateSocket=function(){var t=this,e=new j;return this.logger.debug("initiating ws to ".concat(this.settings.ws,"...")),this.ws=new F(this.settings.ws||""),this.ws.onerror=function(n){var i="";try{i=JSON.stringify(n)}catch(t){var o=new WeakSet;i=JSON.stringify(n,(function(t,e){if("object"==typeof e&&null!==e){if(o.has(e))return;o.add(e)}return e}))}e.reject("error"),t.notifyStatusChanged(!1,i)},this.ws.onclose=function(n){t.logger.info("ws closed ".concat(n)),e.reject("closed"),t.notifyStatusChanged(!1)},this.ws.onopen=function(){var n;t.startupTimer.mark("ws-opened"),t.logger.info("ws opened ".concat(null===(n=t.settings.identity)||void 0===n?void 0:n.application)),e.resolve(),t.notifyStatusChanged(!0)},this.ws.onmessage=function(e){t._registry.execute("onMessage",e.data)},e.promise},t.prototype.notifyForSocketState=function(t){this.wsRequests.forEach((function(e){t?e.failed&&e.failed(t):e.callback()})),this.wsRequests=[]},t.prototype.notifyStatusChanged=function(t,e){this._registry.execute("onConnectedChanged",t,e)},t}(),D={},G={get exports(){return D},set exports(t){D=t}},B={},q={get exports(){return B},set exports(t){B=t}},U=1;var H,$,J,V={nextValue:function(){return(U=(9301*U+49297)%233280)/233280},seed:function(t){U=t}},z="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-";function K(){J=!1}function Q(t){if(t){if(t!==H){if(t.length!==z.length)throw new Error("Custom alphabet for shortid must be "+z.length+" unique characters. You submitted "+t.length+" characters: "+t);var e=t.split("").filter((function(t,e,n){return e!==n.lastIndexOf(t)}));if(e.length)throw new Error("Custom alphabet for shortid must be "+z.length+" unique characters. These characters were not unique: "+e.join(", "));H=t,K()}}else H!==z&&(H=z,K())}function Z(){return J||(J=function(){H||Q(z);for(var t,e=H.split(""),n=[],i=V.nextValue();e.length>0;)i=V.nextValue(),t=Math.floor(i*e.length),n.push(e.splice(t,1)[0]);return n.join("")}())}var X,Y={get:function(){return H||z},characters:function(t){return Q(t),H},seed:function(t){V.seed(t),$!==t&&(K(),$=t)},lookup:function(t){return Z()[t]},shuffled:Z},tt="object"==typeof window&&(window.crypto||window.msCrypto);X=tt&&tt.getRandomValues?function(t){return tt.getRandomValues(new Uint8Array(t))}:function(t){for(var e=[],n=0;n<t;n++)e.push(Math.floor(256*Math.random()));return e};var et=Y,nt=X,it=function(t,e,n){for(var i=(2<<Math.log(e.length-1)/Math.LN2)-1,o=-~(1.6*i*n/e.length),r="";;)for(var s=t(o),a=o;a--;)if((r+=e[s[a]&i]||"").length===+n)return r};var ot,rt,st=function(t){for(var e,n=0,i="";!e;)i+=it(nt,et.get(),1),e=t<Math.pow(16,n+1),n++;return i};var at=function(t){var e="",n=Math.floor(.001*(Date.now()-1567752802062));return n===rt?ot++:(ot=0,rt=n),e+=st(7),e+=st(t),ot>0&&(e+=st(ot)),e+=st(n)},ct=Y;var dt=function(t){return!(!t||"string"!=typeof t||t.length<6)&&!new RegExp("[^"+ct.get().replace(/[|\\{}()[\]^$+*?.-]/g,"\\$&")+"]").test(t)};!function(t){var e=Y,n=at,i=dt,o=0;function r(){return n(o)}t.exports=r,t.exports.generate=r,t.exports.seed=function(n){return e.seed(n),t.exports},t.exports.worker=function(e){return o=e,t.exports},t.exports.characters=function(t){return void 0!==t&&e.characters(t),e.shuffled()},t.exports.isValid=i}(q),function(t){t.exports=B}(G);var ut=T(D);function ht(t,e,n,i,o){null==t&&(t="global"),i=i||["success"],o=o||["error"];var r,s=!1,a=!1,c=!1,d=P();e.disconnected((function(){c=!1,n.debug("connection is down"),s=!1,a=!0,d.execute("onLeft",{disconnected:!0})})),e.loggedIn((function(){c=!0,a&&(n.debug("connection is now up - trying to reconnect..."),h(r))})),e.on("success",(function(t){return p(t)})),e.on("error",(function(t){return l(t)})),e.on("result",(function(t){return p(t)})),i&&i.forEach((function(t){e.on(t,(function(t){return p(t)}))})),o&&o.forEach((function(t){e.on(t,(function(t){return l(t)}))}));var u={};function h(e){return r=e,new Promise((function(i,o){if(s)i({});else{var r;if("global"===t)r=c?Promise.resolve({}):Promise.reject("not connected to gateway");else n.debug("joining domain ".concat(t)),r=f({type:"join",destination:t,domain:"global",options:e});r.then((function(){!function(){n.debug("did join "+t),s=!0;var e=a;a=!1,d.execute("onJoined",e)}(),i({})})).catch((function(e){n.debug("error joining "+t+" domain: "+JSON.stringify(e)),o(e)}))}}))}function l(e){if(t===e.domain){var n=e.request_id;if(n){var i=u[n];i&&i.error(e)}}}function p(e){if(e.domain===t){var n=e.request_id;if(n){var i=u[n];i&&i.success(e)}}}function g(){return ut()}function f(i,o,r){r=r||{},i.request_id=i.request_id||g(),i.domain=i.domain||t,r.skipPeerId||(i.peer_id=e.peerId);var s=i.request_id;return new Promise((function(t,a){u[s]={success:function(e){delete u[s],e._tag=o,t(e)},error:function(t){n.warn("GW error - ".concat(JSON.stringify(t)," for request ").concat(JSON.stringify(i))),delete u[s],t._tag=o,a(t)}},e.send(i,r).catch((function(t){u[s].error({err:t})}))}))}return{join:h,leave:function(){return"global"===t?Promise.resolve():(n.debug("stopping session "+t+"..."),a=!1,f({type:"leave",destination:t,domain:"global"}).then((function(){s=!1,d.execute("onLeft")})).catch((function(){s=!1,d.execute("onLeft")})))},onJoined:function(t){return s&&t(!1),d.add("onJoined",t)},onLeft:function(t){return s||t(),d.add("onLeft",t)},send:f,sendFireAndForget:function(n){return n.request_id=n.request_id?n.request_id:g(),n.domain=n.domain||t,n.peer_id=e.peerId,e.send(n)},on:function(i,o){e.on(i,(function(e){if(e.domain===t)try{o(e)}catch(t){n.error("Callback failed: ".concat(t," \n ").concat(t.stack," \n msg was: ").concat(JSON.stringify(e)),t)}}))},loggedIn:function(t){return e.loggedIn(t)},connected:function(t){return e.connected(t)},disconnected:function(t){return e.disconnected(t)},get peerId(){return e.peerId},get domain(){return t}}}var lt=function(){function t(t,e,n){var i=this;this.connection=t,this.settings=e,this.logger=n,this.protocolVersion=3,this.datePrefix="#T42_DATE#",this.datePrefixLen=this.datePrefix.length,this.dateMinLen=this.datePrefixLen+1,this.datePrefixFirstChar=this.datePrefix[0],this.registry=P(),this._isLoggedIn=!1,this.shouldTryLogin=!0,this.initialLogin=!0,this.initialLoginAttempts=3,this.sessions=[],t.disconnected((function(){i.handleDisconnected()})),this.ping()}return Object.defineProperty(t.prototype,"isLoggedIn",{get:function(){return this._isLoggedIn},enumerable:!1,configurable:!0}),t.prototype.processStringMessage=function(t){var e=this,n=JSON.parse(t,(function(t,n){if("string"!=typeof n)return n;if(n.length<e.dateMinLen)return n;if(n[0]!==e.datePrefixFirstChar)return n;if(n.substring(0,e.datePrefixLen)!==e.datePrefix)return n;try{var i=parseInt(n.substring(e.datePrefixLen,n.length),10);return isNaN(i)?n:new Date(i)}catch(t){return n}}));return{msg:n,msgType:n.type}},t.prototype.createStringMessage=function(t){var e=Date.prototype.toJSON;try{var n=this.datePrefix;return Date.prototype.toJSON=function(){return n+this.getTime()},JSON.stringify(t)}finally{Date.prototype.toJSON=e}},t.prototype.processObjectMessage=function(t){if(!t.type)throw new Error("Object should have type property");return{msg:t,msgType:t.type}},t.prototype.createObjectMessage=function(t){return t},t.prototype.login=function(t,e){return i(this,void 0,void 0,(function(){var n,i,r,s,a,c,d,u,h,l;return o(this,(function(o){switch(o.label){case 0:if(this.logger.debug("logging in..."),this.loginConfig=t,this.loginConfig||(this.loginConfig={username:"",password:""}),this.shouldTryLogin=!0,n={},this.connection.gatewayToken=t.gatewayToken,!t.gatewayToken)return[3,5];if(!e)return[3,4];o.label=1;case 1:return o.trys.push([1,3,,4]),[4,this.getNewGWToken()];case 2:return u=o.sent(),t.gatewayToken=u,[3,4];case 3:return i=o.sent(),this.logger.warn("failed to get GW token when reconnecting ".concat((null==i?void 0:i.message)||i)),[3,4];case 4:return n.method="gateway-token",n.token=t.gatewayToken,this.connection.gatewayToken=t.gatewayToken,[3,10];case 5:return"sspi"!==t.flowName?[3,9]:(n.provider="win",n.method="access-token",t.flowCallback&&t.sessionId?(r=n,[4,t.flowCallback(t.sessionId,null)]):[3,7]);case 6:return r.token=o.sent().data.toString("base64"),[3,8];case 7:throw new Error("Invalid SSPI config");case 8:return[3,10];case 9:if(t.token)n.method="access-token",n.token=t.token;else if(t.username)n.method="secret",n.login=t.username,n.secret=t.password;else{if(!t.provider)throw new Error("invalid auth message"+JSON.stringify(t));n.provider=t.provider,n.providerContext=t.providerContext}o.label=10;case 10:s={type:"hello",identity:this.settings.identity,authentication:n},t.sessionId&&(s.request_id=t.sessionId),this.globalDomain=ht("global",this.connection,this.logger.subLogger("global-domain"),["welcome","token","authentication-request"]),a={skipPeerId:!0},this.initialLogin&&(a.retryInterval=this.settings.reconnectInterval,a.maxRetries=this.settings.reconnectAttempts),o.label=11;case 11:o.trys.push([11,19,20,21]),c=void 0,o.label=12;case 12:return[4,this.globalDomain.send(s,void 0,a)];case 13:return"authentication-request"!==(d=o.sent()).type?[3,16]:(u=Buffer.from(d.authentication.token,"base64"),t.flowCallback&&t.sessionId?(h=s.authentication,[4,t.flowCallback(t.sessionId,u)]):[3,15]);case 14:h.token=o.sent().data.toString("base64"),o.label=15;case 15:return s.request_id=t.sessionId,[3,12];case 16:if("welcome"===d.type)return c=d,[3,18];throw"error"===d.type?new Error("Authentication failed: "+d.reason):new Error("Unexpected message type during authentication: "+d.type);case 17:return[3,12];case 18:return this.initialLogin=!1,this.logger.debug("login successful with peerId "+c.peer_id),this.connection.peerId=c.peer_id,this.connection.resolvedIdentity=c.resolved_identity,this.connection.availableDomains=c.available_domains,c.options&&(this.connection.token=c.options.access_token,this.connection.info=c.options.info),this.setLoggedIn(!0),[2,c.resolved_identity];case 19:throw l=o.sent(),this.logger.error("error sending hello message - "+(l.message||l.msg||l.reason||l),l),l;case 20:return t&&t.flowCallback&&t.sessionId&&t.flowCallback(t.sessionId,null),[7];case 21:return[2]}}))}))},t.prototype.logout=function(){return i(this,void 0,void 0,(function(){var t;return o(this,(function(e){switch(e.label){case 0:return this.logger.debug("logging out..."),this.shouldTryLogin=!1,this.pingTimer&&clearTimeout(this.pingTimer),t=this.sessions.map((function(t){t.leave()})),[4,Promise.all(t)];case 1:return e.sent(),[2]}}))}))},t.prototype.loggedIn=function(t){return this._isLoggedIn&&t(),this.registry.add("onLoggedIn",t)},t.prototype.domain=function(t,e,n,i){var o=this.sessions.filter((function(e){return e.domain===t}))[0];return o||(o=ht(t,this.connection,e,n,i),this.sessions.push(o)),o},t.prototype.handleDisconnected=function(){var t=this;if(this.setLoggedIn(!1),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.connection.login(this.loginConfig,!0).catch((function(){setTimeout(t.handleDisconnected.bind(t),t.settings.reconnectInterval||1e3)}))}},t.prototype.setLoggedIn=function(t){this._isLoggedIn=t,this._isLoggedIn&&this.registry.execute("onLoggedIn")},t.prototype.ping=function(){var t=this;this.shouldTryLogin&&(this._isLoggedIn&&this.connection.send({type:"ping"}),this.pingTimer=setTimeout((function(){t.ping()}),3e4))},t.prototype.authToken=function(){return this.globalDomain?this.globalDomain.send({type:"create-token"}).then((function(t){return t.token})):Promise.reject(new Error("no global domain session"))},t.prototype.getNewGWToken=function(){if(void 0!==typeof window){var t=window.glue42gd;if(t)return t.getGWToken()}return Promise.reject(new Error("not running in GD"))},t}(),pt=function(){function t(t){this.specsNames=[],this.messages={},this.subs={},this.subsRefCount={},this.specs={};for(var e=0,n=t;e<n.length;e++){var i=n[e];this.specs[i.name]=i,this.specsNames.push(i.name)}}return t.prototype.init=function(t){var e=this;this.connection=t;for(var n=0,i=this.specsNames;n<i.length;n++)for(var o=i[n],r=function(n){var i=s.subsRefCount[n];if(i||(i=0),i+=1,s.subsRefCount[n]=i,i>1)return"continue";var o=t.on(n,(function(t){return e.processMessage(n,t)}));s.subs[n]=o},s=this,a=0,c=this.specs[o].types;a<c.length;a++){r(c[a])}},t.prototype.processMessage=function(t,e){if(!this.isDone&&e)for(var n=0,i=this.specsNames;n<i.length;n++){var o=i[n];if(-1!==this.specs[o].types.indexOf(t)){var r=this.messages[o]||[];this.messages[o]=r,r.push(e)}}},t.prototype.drain=function(t,e){var n;e&&(this.messages[t]||[]).forEach(e),delete this.messages[t];for(var i=0,o=this.specs[t].types;i<o.length;i++){var r=o[i];this.subsRefCount[r]-=1,this.subsRefCount[r]<=0&&(null===(n=this.connection)||void 0===n||n.off(this.subs[r]),delete this.subs[r],delete this.subsRefCount[r])}delete this.specs[t],this.specs.length||(this.isDone=!0)},t}(),gt=function(t,e,n){return new Promise((function(i,o){var r=setTimeout((function(){var t=n||"Promise timeout hit: ".concat(e);o(t)}),e);new Promise(t).then((function(t){clearTimeout(r),i(t)})).catch((function(t){clearTimeout(r),o(t)}))}))},ft=function(){function t(t,e,n){this.settings=t,this.logger=e,this.identity=n,this.iAmConnected=!1,this.parentReady=!1,this.rejected=!1,this.children=[],this.extContentAvailable=!1,this.extContentConnecting=!1,this.extContentConnected=!1,this.parentInExtMode=!1,this.webNamespace="g42_core_web",this.parentPingTimeout=5e3,this.connectionRequestTimeout=7e3,this.defaultTargetString="*",this.registry=P(),this.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:function(){}},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)}},this.extContentAvailable=!!window.glue42ext,this.setUpMessageListener(),this.setUpUnload(),this.setupPlatformUnloadListener(),this.parentType=window.name.includes("#wsp")?"workspace":void 0}return t.prototype.manualSetReadyState=function(){this.iAmConnected=!0,this.parentReady=!0},Object.defineProperty(t.prototype,"transportWindowId",{get:function(){return this.publicWindowId},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"communicationId",{get:function(){return this._communicationId},enumerable:!1,configurable:!0}),t.prototype.sendObject=function(t){return i(this,void 0,void 0,(function(){return o(this,(function(e){if(this.extContentConnected)return[2,window.postMessage({glue42ExtOut:t},this.defaultTargetString)];if(!this.port)throw new Error("Cannot send message, because the port was not opened yet");return this.port.postMessage(t),[2]}))}))},Object.defineProperty(t.prototype,"isObjectBasedTransport",{get:function(){return!0},enumerable:!1,configurable:!0}),t.prototype.onMessage=function(t){return this.registry.add("onMessage",t)},t.prototype.send=function(){return Promise.reject("not supported")},t.prototype.onConnectedChanged=function(t){return this.registry.add("onConnectedChanged",t)},t.prototype.open=function(){return i(this,void 0,void 0,(function(){return o(this,(function(t){switch(t.label){case 0:return this.logger.debug("opening a connection to the web platform gateway."),[4,this.connect()];case 1:return t.sent(),this.notifyStatusChanged(!0),[2]}}))}))},t.prototype.close=function(){var t,e,n={glue42core:{type:this.messages.gatewayDisconnect.name,data:{clientId:this.myClientId,ownWindowId:null===(t=this.identity)||void 0===t?void 0:t.windowId}}};return null===(e=this.port)||void 0===e||e.postMessage(n),this.parentReady=!1,this.notifyStatusChanged(!1,"manual reconnection"),Promise.resolve()},t.prototype.name=function(){return"web-platform"},t.prototype.reconnect=function(){return i(this,void 0,void 0,(function(){return o(this,(function(t){switch(t.label){case 0:return[4,this.close()];case 1:return t.sent(),[2,Promise.resolve()]}}))}))},t.prototype.initiateInternalConnection=function(){var t=this;return new Promise((function(e,n){t.logger.debug("opening an internal web platform connection"),t.port=t.settings.port,t.iAmConnected?t.logger.warn("cannot open a new connection, because this client is currently connected"):(t.port.onmessage=function(i){var o,r;if(!t.iAmConnected||(null===(o=i.data)||void 0===o?void 0:o.glue42core)){var s=null===(r=i.data)||void 0===r?void 0:r.glue42core;s&&(s.type===t.messages.gatewayInternalConnect.name&&s.success&&(t.publicWindowId=t.settings.windowId,t.identity&&t.publicWindowId&&(t.identity.windowId=t.publicWindowId,t.identity.instance=t.publicWindowId),e()),s.type===t.messages.gatewayInternalConnect.name&&s.error&&n(s.error))}else t.registry.execute("onMessage",i.data)},t.port.postMessage({glue42core:{type:t.messages.gatewayInternalConnect.name}}))}))},t.prototype.initiateRemoteConnection=function(t){var e=this;return gt((function(n,i){var o;e.connectionResolve=n,e.connectionReject=i,e.myClientId=null!==(o=e.myClientId)&&void 0!==o?o:ut();var r=e.getMyWindowId()||ut(),s={glue42core:{type:e.messages.connectionRequest.name,clientId:e.myClientId,clientType:"child",bridgeInstanceId:r,selfAssignedWindowId:e.selfAssignedWindowId}};if(e.logger.debug("sending connection request"),e.extContentConnecting)return s.glue42core.clientType="child",s.glue42core.bridgeInstanceId=e.myClientId,s.glue42core.parentWindowId=e.parentWindowId,window.postMessage(s,e.defaultTargetString);if(!t)throw new Error("Cannot send a connection request, because no glue target was specified!");t.postMessage(s,e.defaultTargetString)}),this.connectionRequestTimeout,"The connection to the target glue window timed out")},t.prototype.isParentCheckSuccess=function(t){return i(this,void 0,void 0,(function(){return o(this,(function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),[4,t];case 1:return e.sent(),[2,{success:!0}];case 2:return e.sent(),[2,{success:!1}];case 3:return[2]}}))}))},t.prototype.setUpMessageListener=function(){var t=this;this.settings.port?this.logger.debug("skipping generic message listener, because this is an internal client"):window.addEventListener("message",(function(e){var n,i=null===(n=e.data)||void 0===n?void 0:n.glue42core;if(i&&!t.rejected)if(t.checkMessageTypeValid(i.type)){var o=i.type;t.logger.debug("received valid glue42core message of type: ".concat(o)),t.messages[o].handle(e)}else t.logger.error("cannot handle the incoming glue42 core message, because the type is invalid: ".concat(i.type))}))},t.prototype.setUpUnload=function(){var t=this;this.settings.port?this.logger.debug("skipping unload event listener, because this is an internal client"):window.addEventListener("beforeunload",(function(){var e,n;if(!t.extContentConnected){var i={glue42core:{type:t.messages.clientUnload.name,data:{clientId:t.myClientId,ownWindowId:null===(e=t.identity)||void 0===e?void 0:e.windowId}}};t.parent&&t.parent.postMessage(i,t.defaultTargetString),null===(n=t.port)||void 0===n||n.postMessage(i)}}))},t.prototype.handlePlatformReady=function(t){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=t.source,this.parentType=window.name.includes("#wsp")?"workspace":"window"},t.prototype.handleConnectionAccepted=function(t){var e,n=null===(e=t.data)||void 0===e?void 0:e.glue42core;return this.myClientId===n.clientId?this.handleAcceptanceOfMyRequest(n):this.handleAcceptanceOfGrandChildRequest(n,t)},t.prototype.handleAcceptanceOfMyRequest=function(t){var e=this;if(this.logger.debug("handling a connection accepted signal targeted at me."),this.isPreferredActivated=t.isPreferredActivated,this.extContentConnecting)return this.processExtContentConnection(t);if(t.port){if(this.publicWindowId=this.getMyWindowId(),this.identity&&(this.identity.windowId=this.publicWindowId,this.identity.instance=this.identity.instance?this.identity.instance:this.publicWindowId||ut()),this.identity&&t.appName&&(this.identity.application=t.appName,this.identity.applicationName=t.appName),this._communicationId=t.communicationId,this.port=t.port,this.port.onmessage=function(t){return e.registry.execute("onMessage",t.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")},t.prototype.processExtContentConnection=function(t){var e=this;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&&t.appName&&(this.identity.application=t.appName,this.identity.applicationName=t.appName),window.addEventListener("message",(function(t){var n,i=null===(n=t.data)||void 0===n?void 0:n.glue42ExtInc;i&&e.registry.execute("onMessage",i)})),this.connectionResolve)return this.logger.debug("my connection is set up, calling the connection resolve."),this.connectionResolve(),void delete this.connectionResolve},t.prototype.handleAcceptanceOfGrandChildRequest=function(t,e){if(this.extContentConnecting||this.extContentConnected)this.logger.debug("cannot process acceptance of a grandchild, because I am connected to a content script");else{this.logger.debug("handling a connection accepted signal targeted at a grandchild: ".concat(t.clientId));var n=this.children.find((function(e){return e.grandChildId===t.clientId}));n?(n.connected=!0,this.logger.debug("the grandchild connection for ".concat(t.clientId," is set up, forwarding the success message and the gateway port")),t.parentWindowId=this.publicWindowId,n.source.postMessage(e.data,n.origin,[t.port])):this.logger.error("cannot handle connection accepted for grandchild: ".concat(t.clientId,", because there is no grandchild with this id"))}},t.prototype.handleConnectionRejected=function(){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)},t.prototype.handleConnectionRequest=function(t){if(this.extContentConnecting)this.logger.debug("This connection request event is targeted at the extension content");else{var e=t.source,n=t.data.glue42core;if(!n.clientType||"grandChild"!==n.clientType)return this.rejectConnectionRequest(e,t.origin,"rejecting a connection request, because the source was not opened by a glue API call");if(!n.clientId)return this.rejectConnectionRequest(e,t.origin,"rejecting a connection request, because the source did not provide a valid id");if(!this.parent)return this.rejectConnectionRequest(e,t.origin,"Cannot forward the connection request, because no direct connection to the platform was found");this.logger.debug("handling a connection request for a grandchild: ".concat(n.clientId)),this.children.push({grandChildId:n.clientId,source:e,connected:!1,origin:t.origin}),this.logger.debug("grandchild: ".concat(n.clientId," is prepared, forwarding connection request to the platform")),this.parent.postMessage(t.data,this.defaultTargetString)}},t.prototype.handleParentPing=function(t){if(this.parentReady)if(this.iAmConnected){var e={glue42core:{type:this.messages.parentReady.name}};this.extContentConnected&&(e.glue42core.extMode={windowId:this.myClientId});var n=t.source;this.logger.debug("responding to a parent ping with a ready message"),n.postMessage(e,t.origin)}else this.logger.debug("i am not fully connected yet, I am ignoring the parent ping");else this.logger.debug("my parent is not ready, I am ignoring the parent ping")},t.prototype.setupPlatformUnloadListener=function(){var t=this;this.onMessage((function(e){"platformUnload"===e.type&&(t.logger.debug("detected a web platform unload"),t.parentReady=!1,t.notifyStatusChanged(!1,"Gateway unloaded"))}))},t.prototype.handleManualUnload=function(){var t,e,n={glue42core:{type:this.messages.clientUnload.name,data:{clientId:this.myClientId,ownWindowId:null===(t=this.identity)||void 0===t?void 0:t.windowId}}};if(this.extContentConnected)return window.postMessage({glue42ExtOut:n},this.defaultTargetString);null===(e=this.port)||void 0===e||e.postMessage(n)},t.prototype.handleClientUnload=function(t){var e=t.data.glue42core,n=null==e?void 0:e.data.clientId;n?this.children.find((function(t){return t.grandChildId===n}))?(this.logger.debug("handling grandchild unload for id: ".concat(n)),this.children=this.children.filter((function(t){return t.grandChildId!==n}))):this.logger.warn("cannot process grand child unload, because this client is unaware of this grandchild"):this.logger.warn("cannot process grand child unload, because the provided id was not valid")},t.prototype.handlePlatformPing=function(){},t.prototype.notifyStatusChanged=function(t,e){this.iAmConnected=t,this.registry.execute("onConnectedChanged",t,e)},t.prototype.checkMessageTypeValid=function(t){return"string"==typeof t&&!!this.messages[t]},t.prototype.rejectConnectionRequest=function(t,e,n){this.rejected=!0,this.logger.error(n);var i={glue42core:{type:this.messages.connectionRejected.name}};t.postMessage(i,e)},t.prototype.requestConnectionPermissionFromExt=function(){var t=this;return this.waitForContentScript().then((function(){return gt((function(e,n){t.extConnectionResolve=e,t.extConnectionReject=n;t.logger.debug("permission request to the extension content script was sent"),window.postMessage({glue42core:{type:"extSetupRequest"}},t.defaultTargetString)}),t.parentPingTimeout,"Cannot initialize glue, because this app was not opened or created by a Glue Client and the request for extension connection timed out")}))},t.prototype.handleExtConnectionResponse=function(t){var e;if(!(null===(e=t.data)||void 0===e?void 0:e.glue42core).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.")},t.prototype.handleExtSetupRequest=function(){},t.prototype.handleGatewayDisconnect=function(){},t.prototype.handleGatewayInternalConnect=function(){},t.prototype.waitForContentScript=function(){var t;return!!(null===(t=window.glue42ext)||void 0===t?void 0:t.content)?Promise.resolve():gt((function(t){window.addEventListener("Glue42EXTReady",(function(){t()}))}),this.connectionRequestTimeout,"The content script was available, but was never heard to be ready")},t.prototype.connect=function(){return i(this,void 0,void 0,(function(){return o(this,(function(t){switch(t.label){case 0:return this.settings.port?[4,this.initiateInternalConnection()]:[3,2];case 1:return t.sent(),this.logger.debug("internal web platform connection completed"),[2];case 2:return this.logger.debug("opening a client web platform connection"),[4,this.findParent()];case 3:return t.sent(),[4,this.initiateRemoteConnection(this.parent)];case 4:return t.sent(),this.logger.debug("the client is connected"),[2]}}))}))},t.prototype.findParent=function(){var t;return i(this,void 0,void 0,(function(){var e,n,i,s;return o(this,(function(o){switch(o.label){case 0:if(e="Cannot initiate glue, because this window was not opened or created by a glue client",n=this.getPossibleParentsInWindow(window),i=this.getPossibleParentsOutsideWindow(null===(t=window.top)||void 0===t?void 0:t.opener,window.top),!(s=new Set(r(r([],n,!0),i,!0))).size&&!this.extContentAvailable)throw new Error(e);return s.size||!this.extContentAvailable?[3,2]:[4,this.requestConnectionPermissionFromExt()];case 1:case 4:return o.sent(),[2];case 2:return[4,this.isParentCheckSuccess(this.confirmParent(Array.from(s)))];case 3:if(o.sent().success)return this.logger.debug("The default parent was found!"),[2];if(!this.extContentAvailable)throw new Error(e);return[4,this.requestConnectionPermissionFromExt()]}}))}))},t.prototype.getPossibleParentsInWindow=function(t){return t&&t!==t.top?r([t.parent],this.getPossibleParentsInWindow(t.parent),!0):[]},t.prototype.getPossibleParentsOutsideWindow=function(t,e){return t&&e&&t!==e?r(r([t],this.getPossibleParentsInWindow(t),!0),this.getPossibleParentsOutsideWindow(t.opener,t),!0):[]},t.prototype.confirmParent=function(t){var e=this,n=gt((function(n){e.parentPingResolve=n;var i={glue42core:{type:e.messages.platformPing.name}};e.parentPingInterval=setInterval((function(){t.forEach((function(t){t.postMessage(i,e.defaultTargetString)}))}),1e3)}),this.parentPingTimeout,"Cannot initiate glue, because this window was not opened or created by a glue client");return n.catch((function(){e.parentPingInterval&&(clearInterval(e.parentPingInterval),delete e.parentPingInterval)})),n},t.prototype.getMyWindowId=function(){var t;return"workspace"===this.parentType?window.name.substring(0,window.name.indexOf("#wsp")):window===window.top?(null===(t=window.name)||void 0===t?void 0:t.includes("g42"))?window.name:(this.selfAssignedWindowId=this.selfAssignedWindowId||"g42-".concat(ut()),this.selfAssignedWindowId):void 0},t}(),yt=function(){function t(t){void 0===t&&(t=0),this.minSequenceInterval=t,this.queue=[],this.isExecutingQueue=!1}return t.prototype.enqueue=function(t){var e=this;return new Promise((function(n,i){e.queue.push({action:t,resolve:n,reject:i}),e.executeQueue()}))},t.prototype.executeQueue=function(){return i(this,void 0,void 0,(function(){var t,e,n;return o(this,(function(i){switch(i.label){case 0:if(this.isExecutingQueue)return[2];this.isExecutingQueue=!0,i.label=1;case 1:if(!this.queue.length)return[3,7];if(!(t=this.queue.shift()))return this.isExecutingQueue=!1,[2];i.label=2;case 2:return i.trys.push([2,4,,5]),[4,t.action()];case 3:return e=i.sent(),t.resolve(e),[3,5];case 4:return n=i.sent(),t.reject(n),[3,5];case 5:return[4,this.intervalBreak()];case 6:return i.sent(),[3,1];case 7:return this.isExecutingQueue=!1,[2]}}))}))},t.prototype.intervalBreak=function(){var t=this;return new Promise((function(e){return setTimeout(e,t.minSequenceInterval)}))},t}(),mt=function(){function t(t,e){if(this.settings=t,this.logger=e,this.messageHandlers={},this.ids=1,this.registry=P(),this._connected=!1,this.isTrace=!1,this._swapTransport=!1,this._switchInProgress=!1,this._transportSubscriptions=[],this._sequelizer=new yt,(t=t||{}).reconnectAttempts=t.reconnectAttempts||10,t.reconnectInterval=t.reconnectInterval||1e3,t.inproc)this.transport=new M(t.inproc,e.subLogger("inMemory"));else if(t.sharedWorker)this.transport=new R(t.sharedWorker,e.subLogger("shared-worker"));else if(t.webPlatform)this.transport=new ft(t.webPlatform,e.subLogger("web-platform"),t.identity);else{if(void 0===t.ws)throw new Error("No connection information specified");this.transport=new L(t,e.subLogger("ws"))}this.isTrace=e.canPublish("trace"),e.debug("starting with ".concat(this.transport.name()," transport")),this.protocol=new lt(this,t,e.subLogger("protocol"));var n=this.transport.onConnectedChanged(this.handleConnectionChanged.bind(this)),i=this.transport.onMessage(this.handleTransportMessage.bind(this));this._transportSubscriptions.push(n),this._transportSubscriptions.push(i),this._defaultTransport=this.transport}return Object.defineProperty(t.prototype,"protocolVersion",{get:function(){var t;return null===(t=this.protocol)||void 0===t?void 0:t.protocolVersion},enumerable:!1,configurable:!0}),t.prototype.switchTransport=function(t){return i(this,void 0,void 0,(function(){var e=this;return o(this,(function(n){return[2,this._sequelizer.enqueue((function(){return i(e,void 0,void 0,(function(){var e,n,i;return o(this,(function(o){switch(o.label){case 0:if(!t||"object"!=typeof t)throw new Error("Cannot switch transports, because the settings are missing or invalid.");if(void 0===t.type)throw new Error("Cannot switch the transport, because the type is not defined");return this.logger.trace("Starting transport switch with settings: ".concat(JSON.stringify(t))),e="secondary"===t.type?this.getNewSecondaryTransport(t):this._defaultTransport,this._targetTransport=e,this._targetAuth="secondary"===t.type?this.getNewSecondaryAuth(t):this._defaultAuth,n=this.verifyConnection(),this._swapTransport=!0,this._switchInProgress=!0,this.logger.trace("The new transport has been set, closing the current transport"),[4,this.transport.close()];case 1:o.sent(),o.label=2;case 2:return o.trys.push([2,4,,5]),[4,n];case 3:return o.sent(),i=this.transport===e,this.logger.info("The reconnection after the switch was completed. Was the switch a success: ".concat(i)),this._switchInProgress=!1,[2,{success:i}];case 4:return o.sent(),this.logger.info("The reconnection after the switch timed out, reverting back to the default transport."),this.switchTransport({type:"default"}),this._switchInProgress=!1,[2,{success:!1}];case 5:return[2]}}))}))}))]}))}))},t.prototype.onLibReAnnounced=function(t){return this.registry.add("libReAnnounced",t)},t.prototype.setLibReAnnounced=function(t){this.registry.execute("libReAnnounced",t)},t.prototype.send=function(t,e){if(this.transport.sendObject&&this.transport.isObjectBasedTransport){var n=this.protocol.createObjectMessage(t);return this.isTrace&&this.logger.trace(">> ".concat(JSON.stringify(n))),this.transport.sendObject(n,e)}var i=this.protocol.createStringMessage(t);return this.isTrace&&this.logger.trace(">> ".concat(i)),this.transport.send(i,e)},t.prototype.on=function(t,e){t=t.toLowerCase(),void 0===this.messageHandlers[t]&&(this.messageHandlers[t]={});var n=this.ids++;return this.messageHandlers[t][n]=e,{type:t,id:n}},t.prototype.off=function(t){delete this.messageHandlers[t.type.toLowerCase()][t.id]},Object.defineProperty(t.prototype,"isConnected",{get:function(){return this.protocol.isLoggedIn},enumerable:!1,configurable:!0}),t.prototype.connected=function(t){var e=this;return this.protocol.loggedIn((function(){var n=e.transport.name();t(n)}))},t.prototype.disconnected=function(t){return this.registry.add("disconnected",t)},t.prototype.login=function(t,e){return i(this,void 0,void 0,(function(){var n,i,r;return o(this,(function(o){switch(o.label){case 0:this._defaultAuth||(this._defaultAuth=t),this._swapTransport&&(this.logger.trace("Detected a transport swap, swapping transports"),n=this.transportSwap(),t=null!=n?n:t),this.logger.trace("Starting login for transport: ".concat(this.transport.name()," and auth ").concat(JSON.stringify(t))),o.label=1;case 1:return o.trys.push([1,4,,5]),[4,this.transport.open()];case 2:return o.sent(),this.logger.trace("Transport: ".concat(this.transport.name()," opened, logging in")),W("connection").mark("transport-opened"),[4,this.protocol.login(t,e)];case 3:return i=o.sent(),this.logger.trace("Logged in with identity: ".concat(JSON.stringify(i))),W("connection").mark("protocol-logged-in"),[2,i];case 4:throw r=o.sent(),this._switchInProgress&&(this.logger.trace("An error while logging in after a transport swap, preparing a default swap."),this.prepareDefaultSwap()),new Error(r);case 5:return[2]}}))}))},t.prototype.logout=function(){return i(this,void 0,void 0,(function(){return o(this,(function(t){switch(t.label){case 0:return[4,this.protocol.logout()];case 1:return t.sent(),[4,this.transport.close()];case 2:return t.sent(),[2]}}))}))},t.prototype.loggedIn=function(t){return this.protocol.loggedIn(t)},t.prototype.domain=function(t,e,n){return this.protocol.domain(t,this.logger.subLogger("domain=".concat(t)),e,n)},t.prototype.authToken=function(){return this.protocol.authToken()},t.prototype.reconnect=function(){return this.transport.reconnect()},t.prototype.distributeMessage=function(t,e){var n=this,i=this.messageHandlers[e.toLowerCase()];void 0!==i&&Object.keys(i).forEach((function(e){var o=i[e];if(void 0!==o)try{o(t)}catch(t){try{n.logger.error("Message handler failed with ".concat(t.stack),t)}catch(e){console.log("Message handler failed",t)}}}))},t.prototype.handleConnectionChanged=function(t){this._connected!==t&&(this._connected=t,t?(this.settings.replaySpecs&&this.settings.replaySpecs.length&&(this.replayer=new pt(this.settings.replaySpecs),this.replayer.init(this)),this.registry.execute("connected")):this.registry.execute("disconnected"))},t.prototype.handleTransportMessage=function(t){var e;e="string"==typeof t?this.protocol.processStringMessage(t):this.protocol.processObjectMessage(t),this.isTrace&&this.logger.trace("<< ".concat(JSON.stringify(e))),this.distributeMessage(e.msg,e.msgType)},t.prototype.verifyConnection=function(){var t=this;return gt((function(e){var n,i,o,r=(i=function(){n&&n(),e()},o=2,function(){0==--o&&i()});n=t.onLibReAnnounced((function(t){return"interop"===t.name||"contexts"===t.name?r():void 0}))}),1e4,"Transport switch timed out waiting for all libraries to be re-announced")},t.prototype.getNewSecondaryTransport=function(t){var e;if(!(null===(e=t.transportConfig)||void 0===e?void 0:e.url))throw new Error("Missing secondary transport URL.");return new L(Object.assign({},this.settings,{ws:t.transportConfig.url,reconnectAttempts:1}),this.logger.subLogger("ws-secondary"))},t.prototype.getNewSecondaryAuth=function(t){var e;if(!(null===(e=t.transportConfig)||void 0===e?void 0:e.auth))throw new Error("Missing secondary transport auth information.");return t.transportConfig.auth},t.prototype.transportSwap=function(){if(this._swapTransport=!1,this._targetTransport&&this._targetAuth){this._transportSubscriptions.forEach((function(t){return t()})),this._transportSubscriptions=[],this.transport=this._targetTransport;var t=this.transport.onConnectedChanged(this.handleConnectionChanged.bind(this)),e=this.transport.onMessage(this.handleTransportMessage.bind(this));return this._transportSubscriptions.push(t),this._transportSubscriptions.push(e),this._targetAuth}this.logger.warn("Error while switching transports - either the target transport or auth is not defined: transport defined -> ".concat(!!this._defaultTransport,", auth defined -> ").concat(!!this._targetAuth,". Staying on the current one."))},t.prototype.prepareDefaultSwap=function(){var t=this;this._transportSubscriptions.forEach((function(t){return t()})),this._transportSubscriptions=[],this.transport.close().catch((function(e){return t.logger.warn("Error closing the ".concat(t.transport.name()," transport after a failed connection attempt: ").concat(JSON.stringify(e)))})),this._targetTransport=this._defaultTransport,this._targetAuth=this._defaultAuth,this._swapTransport=!0},t}(),vt=["trace","debug","info","warn","error","off"],wt=function(){function t(t,e,n){this.name=t,this.parent=e,this.subLoggers=[],this.logFn=console,this.customLogFn=!1,this.name=t,this.path=e?"".concat(e.path,".").concat(t):t,this.loggerFullName="[".concat(this.path,"]"),this.includeTimeAndLevel=!n,n&&(this.logFn=n,this.customLogFn=!0)}return t.prototype.subLogger=function(e){var n=this.subLoggers.filter((function(t){return t.name===e}))[0];if(void 0!==n)return n;Object.keys(this).forEach((function(t){if(t===e)throw new Error("This sub logger name is not allowed.")}));var i=new t(e,this,this.customLogFn?this.logFn:void 0);return this.subLoggers.push(i),i},t.prototype.publishLevel=function(t){var e;return t&&(this._publishLevel=t),this._publishLevel||(null===(e=this.parent)||void 0===e?void 0:e.publishLevel())},t.prototype.consoleLevel=function(t){var e;return t&&(this._consoleLevel=t),this._consoleLevel||(null===(e=this.parent)||void 0===e?void 0:e.consoleLevel())},t.prototype.log=function(t,e,n){this.publishMessage(e||"info",t,n)},t.prototype.trace=function(t){this.log(t,"trace")},t.prototype.debug=function(t){this.log(t,"debug")},t.prototype.info=function(t){this.log(t,"info")},t.prototype.warn=function(t){this.log(t,"warn")},t.prototype.error=function(t,e){this.log(t,"error")},t.prototype.canPublish=function(t,e){return vt.indexOf(t)>=vt.indexOf(e||this.consoleLevel()||"trace")},t.prototype.publishMessage=function(e,n,i){var o=this.loggerFullName;if("error"===e&&!i){var r=new Error;r.stack&&(n=n+"\n"+r.stack.split("\n").slice(3).join("\n"))}if(this.canPublish(e,this.publishLevel())){var s=t.Interop;if(s)try{s.methods({name:t.InteropMethodName}).length>0&&s.invoke(t.InteropMethodName,{msg:"".concat(n),logger:o,level:e})}catch(t){}}if(this.canPublish(e)){var a="";if(this.includeTimeAndLevel){var c=new Date,d="".concat(c.getHours(),":").concat(c.getMinutes(),":").concat(c.getSeconds(),":").concat(c.getMilliseconds());a="[".concat(d,"] [").concat(e,"] ")}var u="".concat(a).concat(o,": ").concat(n);switch(e){case"trace":this.logFn.debug(u);break;case"debug":this.logFn.debug?this.logFn.debug(u):this.logFn.log(u);break;case"info":this.logFn.info(u);break;case"warn":this.logFn.warn(u);break;case"error":this.logFn.error(u,i)}}},t.InteropMethodName="T42.AppLogger.Log",t}(),bt="create-context",_t="created",It="destroyed",Ct="context-created",At="context-added",St="subscribe-context",xt="subscribed-context",kt="unsubscribe-context",Tt="destroy-context",Et="context-destroyed",Pt="update-context",Mt="context-updated",Rt="joined",Nt={get name(){return"context"},get types(){return[bt,_t,It,Ct,At,St,xt,kt,Tt,Et,Pt,Mt,Rt]}},jt="6.0.2";var Ot=function(){function t(t,e,n,i){this.updateCallbacks={},this.contextId=t,this.name=e,this.isAnnounced=n,this.activityId=i,this.context={}}return t.prototype.hasCallbacks=function(){return Object.keys(this.updateCallbacks).length>0},t.prototype.getState=function(){return this.isAnnounced&&this.hasCallbacks()?3:this.isAnnounced?2:this.hasCallbacks()?1:0},t}(),Wt={};!function(t,e){var n="__lodash_hash_undefined__",i=9007199254740991,o="[object Arguments]",r="[object Boolean]",s="[object Date]",a="[object Function]",c="[object GeneratorFunction]",d="[object Map]",u="[object Number]",h="[object Object]",l="[object Promise]",p="[object RegExp]",g="[object Set]",f="[object String]",y="[object Symbol]",m="[object WeakMap]",v="[object ArrayBuffer]",w="[object DataView]",b="[object Float32Array]",_="[object Float64Array]",I="[object Int8Array]",C="[object Int16Array]",A="[object Int32Array]",S="[object Uint8Array]",x="[object Uint8ClampedArray]",T="[object Uint16Array]",E="[object Uint32Array]",P=/\w*$/,M=/^\[object .+?Constructor\]$/,R=/^(?:0|[1-9]\d*)$/,N={};N[o]=N["[object Array]"]=N[v]=N[w]=N[r]=N[s]=N[b]=N[_]=N[I]=N[C]=N[A]=N[d]=N[u]=N[h]=N[p]=N[g]=N[f]=N[y]=N[S]=N[x]=N[T]=N[E]=!0,N["[object Error]"]=N[a]=N[m]=!1;var j="object"==typeof k&&k&&k.Object===Object&&k,O="object"==typeof self&&self&&self.Object===Object&&self,W=j||O||Function("return this")(),F=e&&!e.nodeType&&e,L=F&&t&&!t.nodeType&&t,D=L&&L.exports===F;function G(t,e){return t.set(e[0],e[1]),t}function B(t,e){return t.add(e),t}function q(t,e,n,i){var o=-1,r=t?t.length:0;for(i&&r&&(n=t[++o]);++o<r;)n=e(n,t[o],o,t);return n}function U(t){var e=!1;if(null!=t&&"function"!=typeof t.toString)try{e=!!(t+"")}catch(t){}return e}function H(t){var e=-1,n=Array(t.size);return t.forEach((function(t,i){n[++e]=[i,t]})),n}function $(t,e){return function(n){return t(e(n))}}function J(t){var e=-1,n=Array(t.size);return t.forEach((function(t){n[++e]=t})),n}var V,z=Array.prototype,K=Function.prototype,Q=Object.prototype,Z=W["__core-js_shared__"],X=(V=/[^.]+$/.exec(Z&&Z.keys&&Z.keys.IE_PROTO||""))?"Symbol(src)_1."+V:"",Y=K.toString,tt=Q.hasOwnProperty,et=Q.toString,nt=RegExp("^"+Y.call(tt).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),it=D?W.Buffer:void 0,ot=W.Symbol,rt=W.Uint8Array,st=$(Object.getPrototypeOf,Object),at=Object.create,ct=Q.propertyIsEnumerable,dt=z.splice,ut=Object.getOwnPropertySymbols,ht=it?it.isBuffer:void 0,lt=$(Object.keys,Object),pt=Lt(W,"DataView"),gt=Lt(W,"Map"),ft=Lt(W,"Promise"),yt=Lt(W,"Set"),mt=Lt(W,"WeakMap"),vt=Lt(Object,"create"),wt=Ut(pt),bt=Ut(gt),_t=Ut(ft),It=Ut(yt),Ct=Ut(mt),At=ot?ot.prototype:void 0,St=At?At.valueOf:void 0;function xt(t){var e=-1,n=t?t.length:0;for(this.clear();++e<n;){var i=t[e];this.set(i[0],i[1])}}function kt(t){var e=-1,n=t?t.length:0;for(this.clear();++e<n;){var i=t[e];this.set(i[0],i[1])}}function Tt(t){var e=-1,n=t?t.length:0;for(this.clear();++e<n;){var i=t[e];this.set(i[0],i[1])}}function Et(t){this.__data__=new kt(t)}function Pt(t,e){var n=$t(t)||function(t){return function(t){return function(t){return!!t&&"object"==typeof t}(t)&&Jt(t)}(t)&&tt.call(t,"callee")&&(!ct.call(t,"callee")||et.call(t)==o)}(t)?function(t,e){for(var n=-1,i=Array(t);++n<t;)i[n]=e(n);return i}(t.length,String):[],i=n.length,r=!!i;for(var s in t)!e&&!tt.call(t,s)||r&&("length"==s||Bt(s,i))||n.push(s);return n}function Mt(t,e,n){var i=t[e];tt.call(t,e)&&Ht(i,n)&&(void 0!==n||e in t)||(t[e]=n)}function Rt(t,e){for(var n=t.length;n--;)if(Ht(t[n][0],e))return n;return-1}function Nt(t,e,n,i,l,m,k){var M;if(i&&(M=m?i(t,l,m,k):i(t)),void 0!==M)return M;if(!Kt(t))return t;var R=$t(t);if(R){if(M=function(t){var e=t.length,n=t.constructor(e);e&&"string"==typeof t[0]&&tt.call(t,"index")&&(n.index=t.index,n.input=t.input);return n}(t),!e)return function(t,e){var n=-1,i=t.length;e||(e=Array(i));for(;++n<i;)e[n]=t[n];return e}(t,M)}else{var j=Gt(t),O=j==a||j==c;if(Vt(t))return function(t,e){if(e)return t.slice();var n=new t.constructor(t.length);return t.copy(n),n}(t,e);if(j==h||j==o||O&&!m){if(U(t))return m?t:{};if(M=function(t){return"function"!=typeof t.constructor||qt(t)?{}:(e=st(t),Kt(e)?at(e):{});var e}(O?{}:t),!e)return function(t,e){return Wt(t,Dt(t),e)}(t,function(t,e){return t&&Wt(e,Qt(e),t)}(M,t))}else{if(!N[j])return m?t:{};M=function(t,e,n,i){var o=t.constructor;switch(e){case v:return Ot(t);case r:case s:return new o(+t);case w:return function(t,e){var n=e?Ot(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.byteLength)}(t,i);case b:case _:case I:case C:case A:case S:case x:case T:case E:return function(t,e){var n=e?Ot(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.length)}(t,i);case d:return function(t,e,n){var i=e?n(H(t),!0):H(t);return q(i,G,new t.constructor)}(t,i,n);case u:case f:return new o(t);case p:return function(t){var e=new t.constructor(t.source,P.exec(t));return e.lastIndex=t.lastIndex,e}(t);case g:return function(t,e,n){var i=e?n(J(t),!0):J(t);return q(i,B,new t.constructor)}(t,i,n);case y:return a=t,St?Object(St.call(a)):{}}var a}(t,j,Nt,e)}}k||(k=new Et);var W=k.get(t);if(W)return W;if(k.set(t,M),!R)var F=n?function(t){return function(t,e,n){var i=e(t);return $t(t)?i:function(t,e){for(var n=-1,i=e.length,o=t.length;++n<i;)t[o+n]=e[n];return t}(i,n(t))}(t,Qt,Dt)}(t):Qt(t);return function(t,e){for(var n=-1,i=t?t.length:0;++n<i&&!1!==e(t[n],n,t););}(F||t,(function(o,r){F&&(o=t[r=o]),Mt(M,r,Nt(o,e,n,i,r,t,k))})),M}function jt(t){return!(!Kt(t)||(e=t,X&&X in e))&&(zt(t)||U(t)?nt:M).test(Ut(t));var e}function Ot(t){var e=new t.constructor(t.byteLength);return new rt(e).set(new rt(t)),e}function Wt(t,e,n,i){n||(n={});for(var o=-1,r=e.length;++o<r;){var s=e[o],a=i?i(n[s],t[s],s,n,t):void 0;Mt(n,s,void 0===a?t[s]:a)}return n}function Ft(t,e){var n,i,o=t.__data__;return("string"==(i=typeof(n=e))||"number"==i||"symbol"==i||"boolean"==i?"__proto__"!==n:null===n)?o["string"==typeof e?"string":"hash"]:o.map}function Lt(t,e){var n=function(t,e){return null==t?void 0:t[e]}(t,e);return jt(n)?n:void 0}xt.prototype.clear=function(){this.__data__=vt?vt(null):{}},xt.prototype.delete=function(t){return this.has(t)&&delete this.__data__[t]},xt.prototype.get=function(t){var e=this.__data__;if(vt){var i=e[t];return i===n?void 0:i}return tt.call(e,t)?e[t]:void 0},xt.prototype.has=function(t){var e=this.__data__;return vt?void 0!==e[t]:tt.call(e,t)},xt.prototype.set=function(t,e){return this.__data__[t]=vt&&void 0===e?n:e,this},kt.prototype.clear=function(){this.__data__=[]},kt.prototype.delete=function(t){var e=this.__data__,n=Rt(e,t);return!(n<0)&&(n==e.length-1?e.pop():dt.call(e,n,1),!0)},kt.prototype.get=function(t){var e=this.__data__,n=Rt(e,t);return n<0?void 0:e[n][1]},kt.prototype.has=function(t){return Rt(this.__data__,t)>-1},kt.prototype.set=function(t,e){var n=this.__data__,i=Rt(n,t);return i<0?n.push([t,e]):n[i][1]=e,this},Tt.prototype.clear=function(){this.__data__={hash:new xt,map:new(gt||kt),string:new xt}},Tt.prototype.delete=function(t){return Ft(this,t).delete(t)},Tt.prototype.get=function(t){return Ft(this,t).get(t)},Tt.prototype.has=function(t){return Ft(this,t).has(t)},Tt.prototype.set=function(t,e){return Ft(this,t).set(t,e),this},Et.prototype.clear=function(){this.__data__=new kt},Et.prototype.delete=function(t){return this.__data__.delete(t)},Et.prototype.get=function(t){return this.__data__.get(t)},Et.prototype.has=function(t){return this.__data__.has(t)},Et.prototype.set=function(t,e){var n=this.__data__;if(n instanceof kt){var i=n.__data__;if(!gt||i.length<199)return i.push([t,e]),this;n=this.__data__=new Tt(i)}return n.set(t,e),this};var Dt=ut?$(ut,Object):function(){return[]},Gt=function(t){return et.call(t)};function Bt(t,e){return!!(e=null==e?i:e)&&("number"==typeof t||R.test(t))&&t>-1&&t%1==0&&t<e}function qt(t){var e=t&&t.constructor;return t===("function"==typeof e&&e.prototype||Q)}function Ut(t){if(null!=t){try{return Y.call(t)}catch(t){}try{return t+""}catch(t){}}return""}function Ht(t,e){return t===e||t!=t&&e!=e}(pt&&Gt(new pt(new ArrayBuffer(1)))!=w||gt&&Gt(new gt)!=d||ft&&Gt(ft.resolve())!=l||yt&&Gt(new yt)!=g||mt&&Gt(new mt)!=m)&&(Gt=function(t){var e=et.call(t),n=e==h?t.constructor:void 0,i=n?Ut(n):void 0;if(i)switch(i){case wt:return w;case bt:return d;case _t:return l;case It:return g;case Ct:return m}return e});var $t=Array.isArray;function Jt(t){return null!=t&&function(t){return"number"==typeof t&&t>-1&&t%1==0&&t<=i}(t.length)&&!zt(t)}var Vt=ht||function(){return!1};function zt(t){var e=Kt(t)?et.call(t):"";return e==a||e==c}function Kt(t){var e=typeof t;return!!t&&("object"==e||"function"==e)}function Qt(t){return Jt(t)?Pt(t):function(t){if(!qt(t))return lt(t);var e=[];for(var n in Object(t))tt.call(t,n)&&"constructor"!=n&&e.push(n);return e}(t)}t.exports=function(t){return Nt(t,!0,!0)}}({get exports(){return Wt},set exports(t){Wt=t}},Wt);var Ft=Wt;function Lt(t,e,i){try{if((null==i?void 0:i.canPublish("trace"))&&(null==i||i.trace("applying context delta ".concat(JSON.stringify(e)," on context ").concat(JSON.stringify(t)))),!e)return t;if(e.reset)return t=n({},e.reset);if(t=Dt(t,void 0),e.commands){for(var o=0,r=e.commands;o<r.length;o++){var s=r[o];"remove"===s.type?Ht(t,s.path):"set"===s.type&&qt(t,s.value,s.path)}return t}var a=e.added,c=e.updated,d=e.removed;return a&&Object.keys(a).forEach((function(e){t[e]=a[e]})),c&&Object.keys(c).forEach((function(e){Gt(e,t,c)})),d&&d.forEach((function(e){delete t[e]})),t}catch(n){return null==i||i.error("error applying context delta ".concat(JSON.stringify(e)," on context ").concat(JSON.stringify(t)),n),t}}function Dt(t,e){return Ft(t)}var Gt=function(t,e,n){var i=n[t];if(void 0===i)return e;var o=e[t];return o&&i?"string"==typeof o||"number"==typeof o||"boolean"==typeof o||"string"==typeof i||"number"==typeof i||"boolean"==typeof i||Array.isArray(o)||Array.isArray(i)?(e[t]=i,e):(e[t]=Object.assign({},o,i),e):(e[t]=i,e)};function Bt(t,e){if(t===e)return!0;if(!(t instanceof Object&&e instanceof Object))return!1;if(t.constructor!==e.constructor)return!1;for(var n in t)if(t.hasOwnProperty(n)){if(!e.hasOwnProperty(n))return!1;if(t[n]!==e[n]){if("object"!=typeof t[n])return!1;if(!Bt(t[n],e[n]))return!1}}for(var n in e)if(e.hasOwnProperty(n)&&!t.hasOwnProperty(n))return!1;return!0}function qt(t,e,n){var i,o=n.split(".");for(i=0;i<o.length-1;i++)t[o[i]]||(t[o[i]]={}),"object"!=typeof t[o[i]]&&(t[o[i]]={}),t=t[o[i]];t[o[i]]=e}function Ut(t,e){return Object.keys(e).every((function(n){return"object"==typeof e[n]?Ut((null==t?void 0:t[n])||{},e[n]||{}):e[n]===(null==t?void 0:t[n])}))}function Ht(t,e){var n,i=e.split(".");for(n=0;n<i.length-1;n++){if(!t[i[n]])return;t=t[i[n]]}delete t[i[n]]}var $t,Jt=function(){function t(t){var e,n=this;this._contextNameToData={},this._gw3Subscriptions=[],this._nextCallbackSubscriptionNumber=0,this._creationPromises={},this._contextNameToId={},this._contextIdToName={},this._protocolVersion=void 0,this._contextsTempCache={},this._contextsSubscriptionsCache=[],this._connection=t.connection,this._logger=t.logger,this._trackAllContexts=t.trackAllContexts,this._reAnnounceKnownContexts=t.reAnnounceKnownContexts,this._gw3Session=this._connection.domain("global",[Ct,xt,Et,Mt]),this._gw3Session.disconnected(this.resetState.bind(this)),this._gw3Session.onJoined((function(t){if(t)return n._reAnnounceKnownContexts?void n.reInitiateState().then((function(){return n._connection.setLibReAnnounced({name:"contexts"})})):n._connection.setLibReAnnounced({name:"contexts"})})),this.subscribeToContextCreatedMessages(),this.subscribeToContextUpdatedMessages(),this.subscribeToContextDestroyedMessages(),null===(e=this._connection.replayer)||void 0===e||e.drain(Nt.name,(function(t){var e=t.type;e&&(e===Ct||e===At||e===_t?n.handleContextCreatedMessage(t):e===xt||e===Mt||e===Rt?n.handleContextUpdatedMessage(t):e!==Et&&e!==It||n.handleContextDestroyedMessage(t))}))}return Object.defineProperty(t.prototype,"protocolVersion",{get:function(){var t;if(!this._protocolVersion){var e=this._connection.availableDomains.find((function(t){return"context"===t.uri}));this._protocolVersion=null!==(t=null==e?void 0:e.version)&&void 0!==t?t:1}return this._protocolVersion},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"setPathSupported",{get:function(){return this.protocolVersion>=2},enumerable:!1,configurable:!0}),t.prototype.dispose=function(){for(var t=0,e=this._gw3Subscriptions;t<e.length;t++){var n=e[t];this._connection.off(n)}for(var i in this._gw3Subscriptions.length=0,this._contextNameToData)this._contextNameToId.hasOwnProperty(i)&&delete this._contextNameToData[i]},t.prototype.createContext=function(t,e){var n=this;return t in this._creationPromises||(this._creationPromises[t]=this._gw3Session.send({type:bt,domain:"global",name:t,data:e,lifetime:"retained"}).then((function(i){n._contextNameToId[t]=i.context_id,n._contextIdToName[i.context_id]=t;var o=n._contextNameToData[t]||new Ot(i.context_id,t,!0,void 0);return o.isAnnounced=!0,o.name=t,o.contextId=i.context_id,o.context=i.data||Dt(e),o.hasReceivedSnapshot=!0,n._contextNameToData[t]=o,delete n._creationPromises[t],i.context_id}))),this._creationPromises[t]},t.prototype.all=function(){var t=this;return Object.keys(this._contextNameToData).filter((function(e){return t._contextNameToData[e].isAnnounced}))},t.prototype.update=function(t,e){var n;return i(this,void 0,void 0,(function(){var i,r,s,a=this;return o(this,(function(o){switch(o.label){case 0:return e&&(e=Dt(e)),t in this._creationPromises?[4,this._creationPromises[t]]:[3,2];case 1:o.sent(),o.label=2;case 2:return(i=this._contextNameToData[t])&&i.isAnnounced?(r=i.context,i.hasCallbacks()?[3,4]:[4,this.get(i.name)]):[2,this.createContext(t,e)];case 3:r=o.sent(),o.label=4;case 4:return s=2===this.protocolVersion?this.calculateContextDeltaV2(r,e):this.calculateContextDeltaV1(r,e),Object.keys(s.added).length||Object.keys(s.updated).length||s.removed.length||(null===(n=s.commands)||void 0===n?void 0:n.length)?[2,this._gw3Session.send({type:Pt,domain:"global",context_id:i.contextId,delta:s},{},{skipPeerId:!1}).then((function(t){a.handleUpdated(i,s,{updaterId:t.peer_id})}))]:[2,Promise.resolve()]}}))}))},t.prototype.set=function(t,e){return i(this,void 0,void 0,(function(){var n,i=this;return o(this,(function(o){switch(o.label){case 0:return e&&(e=Dt(e)),t in this._creationPromises?[4,this._creationPromises[t]]:[3,2];case 1:o.sent(),o.label=2;case 2:return(n=this._contextNameToData[t])&&n.isAnnounced?[2,this._gw3Session.send({type:Pt,domain:"global",context_id:n.contextId,delta:{reset:e}},{},{skipPeerId:!1}).then((function(t){i.handleUpdated(n,{reset:e,added:{},removed:[],updated:{}},{updaterId:t.peer_id})}))]:[2,this.createContext(t,e)]}}))}))},t.prototype.setPath=function(t,e,n){return this.setPathSupported?this.setPaths(t,[{path:e,value:n}]):Promise.reject("glue.contexts.setPath operation is not supported, use Glue42 3.10 or later")},t.prototype.setPaths=function(t,e){return i(this,void 0,void 0,(function(){var n,i,r,s,a,c,d,u,h=this;return o(this,(function(o){switch(o.label){case 0:return this.setPathSupported?(e&&(e=Dt(e)),t in this._creationPromises?[4,this._creationPromises[t]]:[3,2]):[2,Promise.reject("glue.contexts.setPaths operation is not supported, use Glue42 3.10 or later")];case 1:o.sent(),o.label=2;case 2:if(!(n=this._contextNameToData[t])||!n.isAnnounced){for(i={},r=0,s=e;r<s.length;r++)u=s[r],qt(i,u.value,u.path);return[2,this.createContext(t,i)]}for(a=[],c=0,d=e;c<d.length;c++)null===(u=d[c]).value?a.push({type:"remove",path:u.path}):a.push({type:"set",path:u.path,value:u.value});return[2,this._gw3Session.send({type:Pt,domain:"global",context_id:n.contextId,delta:{commands:a}},{},{skipPeerId:!1}).then((function(t){h.handleUpdated(n,{added:{},removed:[],updated:{},commands:a},{updaterId:t.peer_id})}))]}}))}))},t.prototype.get=function(t){var e;return i(this,void 0,void 0,(function(){var n,i,r=this;return o(this,(function(o){switch(o.label){case 0:return t in this._creationPromises?[4,this._creationPromises[t]]:[3,2];case 1:o.sent(),o.label=2;case 2:return(n=this._contextNameToData[t])&&n.isAnnounced?!n||n.hasCallbacks()&&n.hasReceivedSnapshot?(i=null!==(e=null==n?void 0:n.context)&&void 0!==e?e:{},[2,Promise.resolve(Dt(i))]):[2,new Promise((function(e){r.subscribe(t,(function(t,n,i,o){r.unsubscribe(o),e(t)}))}))]:[2,Promise.resolve({})]}}))}))},t.prototype.subscribe=function(t,e,n){return i(this,void 0,void 0,(function(){var i,r,s,a,c=this;return o(this,(function(o){switch(o.label){case 0:return t in this._creationPromises?[4,this._creationPromises[t]]:[3,2];case 1:o.sent(),o.label=2;case 2:return i=void 0===n?this._nextCallbackSubscriptionNumber:n,void 0===n&&(this._nextCallbackSubscriptionNumber+=1),this._contextsSubscriptionsCache.every((function(t){return t.subKey!==c._nextCallbackSubscriptionNumber}))&&this._contextsSubscriptionsCache.push({contextName:t,subKey:i,callback:e}),(r=this._contextNameToData[t])&&r.isAnnounced?(s=r.hasCallbacks(),r.updateCallbacks[i]=e,s||r.joinedActivity||r.context&&r.sentExplicitSubscription?(r.hasReceivedSnapshot&&(a=Dt(r.context),e(a,a,[],i)),[2,Promise.resolve(i)]):[2,this.sendSubscribe(r).then((function(){return i}))]):(r=r||new Ot(void 0,t,!1,void 0),this._contextNameToData[t]=r,r.updateCallbacks[i]=e,[2,Promise.resolve(i)])}}))}))},t.prototype.unsubscribe=function(t){this._contextsSubscriptionsCache=this._contextsSubscriptionsCache.filter((function(e){return e.subKey!==t}));for(var e=0,n=Object.keys(this._contextNameToData);e<n.length;e++){var i=n[e],o=this._contextNameToData[i];if(!o)return;var r=o.hasCallbacks();delete o.updateCallbacks[t],o.isAnnounced&&r&&!o.hasCallbacks()&&o.sentExplicitSubscription&&this.sendUnsubscribe(o),o.isAnnounced||o.hasCallbacks()||delete this._contextNameToData[i]}},t.prototype.destroy=function(t){return i(this,void 0,void 0,(function(){var e;return o(this,(function(n){switch(n.label){case 0:return t in this._creationPromises?[4,this._creationPromises[t]]:[3,2];case 1:n.sent(),n.label=2;case 2:return(e=this._contextNameToData[t])?[2,this._gw3Session.send({type:Tt,domain:"global",context_id:e.contextId}).then((function(t){}))]:[2,Promise.reject("context with ".concat(t," does not exist"))]}}))}))},t.prototype.handleUpdated=function(t,e,n){var i=t.context;t.context=Lt(t.context,e,this._logger),t.hasReceivedSnapshot=!0,this._contextNameToData[t.name]!==t||Bt(i,t.context)||this.invokeUpdateCallbacks(t,e,n)},t.prototype.subscribeToContextCreatedMessages=function(){for(var t=0,e=[At,Ct,_t];t<e.length;t++){var n=e[t],i=this._connection.on(n,this.handleContextCreatedMessage.bind(this));this._gw3Subscriptions.push(i)}},t.prototype.handleContextCreatedMessage=function(t){var e=this,n=t.type;n===_t?(this._contextNameToId[t.activity_id]=t.context_id,this._contextIdToName[t.context_id]=t.activity_id):n===At&&(this._contextNameToId[t.name]=t.context_id,this._contextIdToName[t.context_id]=t.name);var i=this._contextIdToName[t.context_id];if(!i)throw new Error("Received created event for context with unknown name: "+t.context_id);if(!this._contextNameToId[i])throw new Error("Received created event for context with unknown id: "+t.context_id);var o=this._contextNameToData[i];if(o){if(o.isAnnounced)return;if(!o.hasCallbacks())throw new Error("Assertion failure: contextData.hasCallbacks()");o.isAnnounced=!0,o.contextId=t.context_id,o.activityId=t.activity_id,o.sentExplicitSubscription||this.sendSubscribe(o)}else this._contextNameToData[i]=o=new Ot(t.context_id,i,!0,t.activity_id),this._trackAllContexts&&this.subscribe(i,(function(){})).then((function(t){return e._systemContextsSubKey=t}))},t.prototype.subscribeToContextUpdatedMessages=function(){for(var t=0,e=[Mt,xt,Rt];t<e.length;t++){var n=e[t],i=this._connection.on(n,this.handleContextUpdatedMessage.bind(this));this._gw3Subscriptions.push(i)}},t.prototype.handleContextUpdatedMessage=function(t){var e=t.type,n=t.context_id,i=this._contextNameToData[this._contextIdToName[n]],o=!i||!i.isAnnounced;if(e===Rt)i||(i=this._contextNameToData[t.activity_id]||new Ot(n,t.activity_id,!0,t.activity_id)),this._contextNameToData[t.activity_id]=i,this._contextIdToName[n]=t.activity_id,this._contextNameToId[t.activity_id]=n,i.contextId=n,i.isAnnounced=!0,i.activityId=t.activity_id,i.joinedActivity=!0;else if(!i||!i.isAnnounced)return void(e===xt?((i=i||new Ot(n,t.name,!0,void 0)).sentExplicitSubscription=!0,this._contextNameToData[t.name]=i,this._contextIdToName[n]=t.name,this._contextNameToId[t.name]=n):this._logger.error("Received 'update' for unknown context: ".concat(n)));var r=i.context;if(i.hasReceivedSnapshot=!0,e===xt)i.context=t.data||{};else if(e===Rt)i.context=t.context_snapshot||{};else{if(e!==Mt)throw new Error("Unrecognized context update message "+e);i.context=Lt(i.context,t.delta,this._logger)}!o&&Bt(i.context,r)&&e!==xt||this.invokeUpdateCallbacks(i,t.delta,{updaterId:t.updater_id})},t.prototype.invokeUpdateCallbacks=function(t,e,n){if((e=e||{added:{},updated:{},reset:{},removed:[]}).commands){e.added=e.updated=e.reset={},e.removed=[];for(var i=0,o=e.commands;i<o.length;i++){var r=o[i];"remove"===r.type?(-1===r.path.indexOf(".")&&e.removed.push(r.path),qt(e.updated,null,r.path)):"set"===r.type&&qt(e.updated,r.value,r.path)}}for(var s in t.updateCallbacks)if(t.updateCallbacks.hasOwnProperty(s))try{(0,t.updateCallbacks[s])(Dt(t.context),Dt(Object.assign({},e.added||{},e.updated||{},e.reset||{})),e.removed,parseInt(s,10),n)}catch(t){this._logger.debug("callback error: "+JSON.stringify(t))}},t.prototype.subscribeToContextDestroyedMessages=function(){for(var t=0,e=[Et,It];t<e.length;t++){var n=e[t],i=this._connection.on(n,this.handleContextDestroyedMessage.bind(this));this._gw3Subscriptions.push(i)}},t.prototype.handleContextDestroyedMessage=function(t){var e,n;if(t.type===It){if(n=t.activity_id,!(e=this._contextNameToId[n]))return void this._logger.error("Received 'destroyed' for unknown activity: ".concat(t.activity_id))}else if(e=t.context_id,!(n=this._contextIdToName[e]))return void this._logger.error("Received 'destroyed' for unknown context: ".concat(t.context_id));delete this._contextIdToName[e],delete this._contextNameToId[n];var i=this._contextNameToData[n];delete this._contextNameToData[n],i&&i.isAnnounced||this._logger.error("Received 'destroyed' for unknown context: ".concat(e))},t.prototype.sendSubscribe=function(t){return t.sentExplicitSubscription=!0,this._gw3Session.send({type:St,domain:"global",context_id:t.contextId}).then((function(t){}))},t.prototype.sendUnsubscribe=function(t){return t.sentExplicitSubscription=!1,this._gw3Session.send({type:kt,domain:"global",context_id:t.contextId}).then((function(t){}))},t.prototype.calculateContextDeltaV1=function(t,e){var n={added:{},updated:{},removed:[],reset:void 0};if(t)for(var i=0,o=Object.keys(t);i<o.length;i++){var r=o[i];-1===Object.keys(e).indexOf(r)||null===e[r]||Bt(t[r],e[r])||(n.updated[r]=e[r])}for(var s=0,a=Object.keys(e);s<a.length;s++){r=a[s];t&&-1!==Object.keys(t).indexOf(r)?null===e[r]&&n.removed.push(r):null!==e[r]&&(n.added[r]=e[r])}return n},t.prototype.calculateContextDeltaV2=function(t,e){for(var n,i,o={added:{},updated:{},removed:[],reset:void 0,commands:[]},r=0,s=Object.keys(e);r<s.length;r++){var a=s[r];if(null!==e[a])Bt(t?t[a]:null,e[a])||null===(n=o.commands)||void 0===n||n.push({type:"set",path:a,value:e[a]});else null===(i=o.commands)||void 0===i||i.push({type:"remove",path:a})}return o},t.prototype.resetState=function(){for(var t=this,e=0,n=this._gw3Subscriptions;e<n.length;e++){var i=n[e];this._connection.off(i)}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((function(e,n){return e[n]=t._contextNameToData[n].context,e}),{}),this._contextNameToData={}},t.prototype.reInitiateState=function(){var t;return i(this,void 0,void 0,(function(){var e,n,i,r,s,a,c=this;return o(this,(function(o){switch(o.label){case 0:return this.subscribeToContextCreatedMessages(),this.subscribeToContextUpdatedMessages(),this.subscribeToContextDestroyedMessages(),null===(t=this._connection.replayer)||void 0===t||t.drain(Nt.name,(function(t){var e=t.type;e&&(e===Ct||e===At||e===_t?c.handleContextCreatedMessage(t):e===xt||e===Mt||e===Rt?c.handleContextUpdatedMessage(t):e!==Et&&e!==It||c.handleContextDestroyedMessage(t))})),[4,Promise.all(this._contextsSubscriptionsCache.map((function(t){return c.subscribe(t.contextName,t.callback,t.subKey)})))];case 1:return o.sent(),[4,this.flushQueue()];case 2:for(i in o.sent(),e=this._contextsTempCache,n=[],e)n.push(i);r=0,o.label=3;case 3:return r<n.length?(i=n[r])in e?(s=i,"object"!=typeof this._contextsTempCache[s]||0===Object.keys(this._contextsTempCache[s]).length?[3,6]:(a=this._contextsTempCache[s],this._logger.info("Re-announcing known context: ".concat(s)),[4,this.flushQueue()])):[3,6]:[3,7];case 4:return o.sent(),[4,this.update(s,a)];case 5:o.sent(),o.label=6;case 6:return r++,[3,3];case 7:return this._contextsTempCache={},this._logger.info("Contexts are re-announced"),[2]}}))}))},t.prototype.flushQueue=function(){return new Promise((function(t){return setTimeout((function(){return t()}),0)}))},t}(),Vt=function(){function t(t){this._bridge=new Jt(t)}return t.prototype.all=function(){return this._bridge.all()},t.prototype.update=function(t,e){return this.checkName(t),this.checkData(e),this._bridge.update(t,e)},t.prototype.set=function(t,e){return this.checkName(t),this.checkData(e),this._bridge.set(t,e)},t.prototype.setPath=function(t,e,n){return this.checkName(t),this.checkPath(e),""===e?(this.checkData(n),this.set(t,n)):this._bridge.setPath(t,e,n)},t.prototype.setPaths=function(t,e){if(this.checkName(t),!Array.isArray(e))throw new Error("Please provide the paths as an array of PathValues!");for(var n=0,i=e;n<i.length;n++){var o=i[n],r=o.path,s=o.value;this.checkPath(r),""===r&&this.checkData(s)}return this._bridge.setPaths(t,e)},t.prototype.subscribe=function(t,e){var n=this;if(this.checkName(t),"function"!=typeof e)throw new Error("Please provide the callback as a function!");return this._bridge.subscribe(t,(function(t,i,o,r,s){return e(t,i,o,(function(){return n._bridge.unsubscribe(r)}),s)})).then((function(t){return function(){n._bridge.unsubscribe(t)}}))},t.prototype.get=function(t){return this.checkName(t),this._bridge.get(t)},t.prototype.ready=function(){return Promise.resolve(this)},t.prototype.destroy=function(t){return this.checkName(t),this._bridge.destroy(t)},Object.defineProperty(t.prototype,"setPathSupported",{get:function(){return this._bridge.setPathSupported},enumerable:!1,configurable:!0}),t.prototype.checkName=function(t){if("string"!=typeof t||""===t)throw new Error("Please provide the name as a non-empty string!")},t.prototype.checkPath=function(t){if("string"!=typeof t)throw new Error("Please provide the path as a dot delimited string!")},t.prototype.checkData=function(t){if("object"!=typeof t)throw new Error("Please provide the data as an object!")},t}();function zt(t,e,n){return"function"!=typeof e&&"function"!=typeof n?t:("function"!=typeof e?e=function(){}:"function"!=typeof n&&(n=function(){}),t.then(e,n))}function Kt(t,e,n){var i;void 0===t&&(t=0);var o=function(){i&&clearTimeout(i)};return e.then((function(){o()})).catch((function(){o()})),new Promise((function(e,o){i=setTimeout((function(){return o(n)}),t)}))}!function(t){t[t.Success=0]="Success",t[t.Error=1]="Error"}($t||($t={}));var Qt=function(){function t(t,e,n,i){this.protocol=t,this.repo=e,this.instance=n,this.configuration=i}return t.prototype.subscribe=function(t,e,n,i,o){var r=this,s=function(t,n,i,s){var a;e.methodResponseTimeout=null!==(a=e.methodResponseTimeout)&&void 0!==a?a:e.waitTimeoutMs,r.protocol.client.subscribe(n,e,t,i,s,o)};return zt(new Promise((function(n,i){var o,a=function(t){n(t)},c=function(t){i(t)};if(t)if((o="string"==typeof t?{name:t}:t).name){void 0===e&&(e={});var d=e.target;if(void 0===d&&(d="best"),"string"!=typeof d||"all"===d||"best"===d){void 0===e.methodResponseTimeout&&(e.methodResponseTimeout=e.method_response_timeout,void 0===e.methodResponseTimeout&&(e.methodResponseTimeout=r.configuration.methodResponseTimeout)),void 0===e.waitTimeoutMs&&(e.waitTimeoutMs=e.wait_for_method_timeout,void 0===e.waitTimeoutMs&&(e.waitTimeoutMs=r.configuration.waitTimeoutMs));var u=0,h=r.getServerMethodsByFilterAndTarget(o,d);if(h.length>0)s(h,h[0].methods[0],a,c);else{var l=function(){if(d&&e.waitTimeoutMs)if(u+=500,(h=r.getServerMethodsByFilterAndTarget(o,d)).length>0){var n=h[0].methods[0];s(h,n,a,c)}else if(u>=e.waitTimeoutMs){s(h,"string"==typeof t?{name:t}:t,a,c)}else setTimeout(l,500)};setTimeout(l,500)}}else i(new Error('"'.concat(d,'" is not a valid target. Valid targets are "all", "best", or an instance.')))}else i("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");else i("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.")})),n,i)},t.prototype.servers=function(t){var e=void 0===t?void 0:n({},t);return this.getServers(e).map((function(t){return t.server.instance}))},t.prototype.methods=function(t){return t="string"==typeof t?{name:t}:n({},t),this.getMethods(t)},t.prototype.methodsForInstance=function(t){return this.getMethodsForInstance(t)},t.prototype.methodAdded=function(t){return this.repo.onMethodAdded(t)},t.prototype.methodRemoved=function(t){return this.repo.onMethodRemoved(t)},t.prototype.serverAdded=function(t){return this.repo.onServerAdded(t)},t.prototype.serverRemoved=function(t){return this.repo.onServerRemoved((function(e,n){t(e,n)}))},t.prototype.serverMethodAdded=function(t){return this.repo.onServerMethodAdded((function(e,n){t({server:e,method:n})}))},t.prototype.serverMethodRemoved=function(t){return this.repo.onServerMethodRemoved((function(e,n){t({server:e,method:n})}))},t.prototype.invoke=function(t,e,r,s,a,c){return i(this,void 0,void 0,(function(){var d,u=this;return o(this,(function(h){return d=function(){return i(u,void 0,void 0,(function(){var i,a,c,d,u,h,l,p,g,f,y,m,v=this;return o(this,(function(o){switch(o.label){case 0:if(!(i="string"==typeof t?{name:t}:n({},t)).name)return[2,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(e||(e={}),r||(r="best"),"string"==typeof r&&"all"!==r&&"best"!==r&&"skipMine"!==r)return[2,Promise.reject(new Error('"'.concat(r,'" is not a valid target. Valid targets are "all" and "best".')))];if(s||(s={}),void 0===s.methodResponseTimeoutMs&&(s.methodResponseTimeoutMs=s.method_response_timeout,void 0===s.methodResponseTimeoutMs&&(s.methodResponseTimeoutMs=this.configuration.methodResponseTimeout)),void 0===s.waitTimeoutMs&&(s.waitTimeoutMs=s.wait_for_method_timeout,void 0===s.waitTimeoutMs&&(s.waitTimeoutMs=this.configuration.waitTimeoutMs)),void 0!==s.waitTimeoutMs&&"number"!=typeof s.waitTimeoutMs)return[2,Promise.reject(new Error('"'.concat(s.waitTimeoutMs,'" is not a valid number for "waitTimeoutMs" ')))];if("object"!=typeof e)return[2,Promise.reject(new Error("The method arguments must be an object. method: ".concat(i.name)))];if(0!==(a=this.getServerMethodsByFilterAndTarget(i,r)).length)return[3,4];o.label=1;case 1:return o.trys.push([1,3,,4]),[4,this.tryToAwaitForMethods(i,r,s)];case 2:return a=o.sent(),[3,4];case 3:return o.sent(),c=n(n({},i),{getServers:function(){return[]},supportsStreaming:!1,objectTypes:null!==(f=i.objectTypes)&&void 0!==f?f:[],flags:null!==(m=null===(y=i.flags)||void 0===y?void 0:y.metadata)&&void 0!==m?m:{}}),d={method:c,called_with:e,message:"Can not find a method matching ".concat(JSON.stringify(t)," with server filter ").concat(JSON.stringify(r)),executed_by:void 0,returned:void 0,status:void 0},[2,Promise.reject(d)];case 4:return u=s.methodResponseTimeoutMs,h=s,l=a.map((function(t){var n=ut(),i=t.methods[0],o=t.server,r=v.protocol.client.invoke(n,i,e,o,h);return Promise.race([r,Kt(u,r,{invocationId:n,message:"Invocation timeout (".concat(u," ms) reached for method name: ").concat(null==i?void 0:i.name,", target instance: ").concat(JSON.stringify(o.instance),", options: ").concat(JSON.stringify(h)),status:$t.Error})])})),[4,Promise.all(l)];case 5:return p=o.sent(),g=this.getInvocationResultObj(p,i,e),p.every((function(t){return t.status===$t.Error}))?[2,Promise.reject(g)]:[2,g]}}))}))},[2,zt(d(),a,c)]}))}))},t.prototype.getInvocationResultObj=function(t,e,n){var i=t.filter((function(t){return t.status===$t.Success})).reduce((function(t,i){return t=r(r([],t,!0),[{executed_by:i.instance,returned:i.result,called_with:n,method:e,message:i.message,status:i.status}],!1)}),[]),o=t.filter((function(t){return t.status===$t.Error})).reduce((function(t,i){return t=r(r([],t,!0),[{executed_by:i.instance,called_with:n,name:e.name,message:i.message}],!1)}),[]),s=t[0];return{method:e,called_with:n,returned:s.result,executed_by:s.instance,all_return_values:i,all_errors:o,message:s.message,status:s.status}},t.prototype.tryToAwaitForMethods=function(t,e,n){var i=this;return new Promise((function(o,r){if(0!==n.waitTimeoutMs)var s=0,a=setInterval((function(){s+=500;var c=i.getServerMethodsByFilterAndTarget(t,e);if(c.length>0)clearInterval(a),o(c);else if(s>=(n.waitTimeoutMs||1e4))return clearInterval(a),void r()}),500);else r()}))},t.prototype.filterByTarget=function(t,e){var n=this;if("string"!=typeof t){return(Array.isArray(t)?t:[t]).reduce((function(t,i){var o=e.filter((function(t){return n.instanceMatch(i,t.server.instance)}));return t.concat(o)}),[])}if("all"===t)return r([],e,!0);if("best"===t){var i=e.find((function(t){return t.server.instance.isLocal}));if(i)return[i];if(void 0!==e[0])return[e[0]]}else if("skipMine"===t)return e.filter((function(t){return t.server.instance.peerId!==n.instance.peerId}));return[]},t.prototype.instanceMatch=function(t,e){return this.containsProps(t,e)},t.prototype.methodMatch=function(t,e){return this.containsProps(t,e)},t.prototype.containsProps=function(t,e){return Object.keys(t).filter((function(e){return void 0!==t[e]&&null!==t[e]&&"function"!=typeof t[e]&&"object_types"!==e&&"display_name"!==e&&"id"!==e&&"gatewayId"!==e&&"identifier"!==e&&"_"!==e[0]})).every((function(n){var i,o=t[n],r=e[n];switch(n){case"objectTypes":i=(o||[]).every((function(t){return(r||[]).includes(t)}));break;case"flags":i=Ut(r||{},o||{});break;default:i=String(o).toLowerCase()===String(r).toLowerCase()}return i}))},t.prototype.getMethods=function(t){var e=this;return void 0===t?this.repo.getMethods():this.repo.getMethods().filter((function(n){return e.methodMatch(t,n)}))},t.prototype.getMethodsForInstance=function(t){var e=this,n=this.repo.getServers().filter((function(n){return e.instanceMatch(t,n.instance)}));if(0===n.length)return[];var i={};return 1===n.length?i=n[0].methods:n.forEach((function(t){Object.keys(t.methods).forEach((function(e){var n=t.methods[e];i[n.identifier]=n}))})),Object.keys(i).map((function(t){return i[t]}))},t.prototype.getServers=function(t){var e=this,n=this.repo.getServers();return void 0===t?n.map((function(t){return{server:t,methods:[]}})):n.reduce((function(n,i){var o=Object.values(i.methods).filter((function(n){return e.methodMatch(t,n)}));return o.length>0&&n.push({server:i,methods:o}),n}),[])},t.prototype.getServerMethodsByFilterAndTarget=function(t,e){var n=this.getServers(t);return this.filterByTarget(e,n)},t}(),Zt=function(){function t(t,e,n){this.protocol=t,this.repoMethod=e,this.subscription=n}return Object.defineProperty(t.prototype,"stream",{get:function(){if(!this.repoMethod.stream)throw new Error("no stream");return this.repoMethod.stream},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"arguments",{get:function(){return this.subscription.arguments||{}},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"branchKey",{get:function(){return this.subscription.branchKey},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"instance",{get:function(){if(!this.subscription.instance)throw new Error("no instance");return this.subscription.instance},enumerable:!1,configurable:!0}),t.prototype.close=function(){this.protocol.server.closeSingleSubscription(this.repoMethod,this.subscription)},t.prototype.push=function(t){this.protocol.server.pushDataToSingle(this.repoMethod,this.subscription,t)},t}(),Xt=function(){function t(t,e,n){this.protocol=t,this.repoMethod=e,this.requestContext=n,this.arguments=n.arguments,this.instance=n.instance}return t.prototype.accept=function(){this.protocol.server.acceptRequestOnBranch(this.requestContext,this.repoMethod,"")},t.prototype.acceptOnBranch=function(t){this.protocol.server.acceptRequestOnBranch(this.requestContext,this.repoMethod,t)},t.prototype.reject=function(t){this.protocol.server.rejectRequest(this.requestContext,this.repoMethod,t)},t}(),Yt=function(){function t(t,e){var n=this;this.protocol=t,this.server=e,t.server.onSubRequest((function(t,e){return n.handleSubRequest(t,e)})),t.server.onSubAdded((function(t,e){return n.handleSubAdded(t,e)})),t.server.onSubRemoved((function(t,e){return n.handleSubRemoved(t,e)}))}return t.prototype.handleSubRequest=function(t,e){if(e&&e.streamCallbacks&&"function"==typeof e.streamCallbacks.subscriptionRequestHandler){var n=new Xt(this.protocol,e,t);e.streamCallbacks.subscriptionRequestHandler(n)}},t.prototype.handleSubAdded=function(t,e){if(e&&e.streamCallbacks&&"function"==typeof e.streamCallbacks.subscriptionAddedHandler){var n=new Zt(this.protocol,e,t);e.streamCallbacks.subscriptionAddedHandler(n)}},t.prototype.handleSubRemoved=function(t,e){if(e&&e.streamCallbacks&&"function"==typeof e.streamCallbacks.subscriptionRemovedHandler){var n=new Zt(this.protocol,e,t);e.streamCallbacks.subscriptionRemovedHandler(n)}},t}(),te=function(){function t(t,e,n){this.key=t,this.protocol=e,this.repoMethod=n}return t.prototype.subscriptions=function(){var t=this;return this.protocol.server.getSubscriptionList(this.repoMethod,this.key).map((function(e){return new Zt(t.protocol,t.repoMethod,e)}))},t.prototype.close=function(){this.protocol.server.closeAllSubscriptions(this.repoMethod,this.key)},t.prototype.push=function(t){this.protocol.server.pushData(this.repoMethod,t,[this.key])},t}(),ee=function(){function t(t,e,n){this._protocol=t,this._repoMethod=e,this._server=n,this.name=this._repoMethod.definition.name}return t.prototype.branches=function(t){var e=this,n=this._protocol.server.getBranchList(this._repoMethod);return t?n.indexOf(t)>-1?new te(t,this._protocol,this._repoMethod):void 0:n.map((function(t){return new te(t,e._protocol,e._repoMethod)}))},t.prototype.branch=function(t){return this.branches(t)},t.prototype.subscriptions=function(){var t=this;return this._protocol.server.getSubscriptionList(this._repoMethod).map((function(e){return new Zt(t._protocol,t._repoMethod,e)}))},Object.defineProperty(t.prototype,"definition",{get:function(){var t,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:null===(t=e.flags)||void 0===t?void 0:t.metadata}},enumerable:!1,configurable:!0}),t.prototype.close=function(){this._protocol.server.closeAllSubscriptions(this._repoMethod),this._server.unregister(this._repoMethod.definition,!0)},t.prototype.push=function(t,e){if("string"!=typeof e&&!Array.isArray(e)&&void 0!==e)throw new Error("invalid branches should be string or string array");if("object"!=typeof t)throw new Error("Invalid arguments. Data must be an object.");this._protocol.server.pushData(this._repoMethod,t,e)},t.prototype.updateRepoMethod=function(t){this._repoMethod=t},t}(),ne=function(){function t(t,e){this.protocol=t,this.serverRepository=e,this.invocations=0,this.currentlyUnregistering={},this.streaming=new Yt(t,this),this.protocol.server.onInvoked(this.onMethodInvoked.bind(this))}return t.prototype.createStream=function(t,e,i,o,r){var s=this;return zt(new Promise((function(i,o){if(t){var a;if(!(a="string"==typeof t?{name:""+t}:n({},t)).name)return o("The “name” property is required for the “streamDefinition” object and must be unique. Stream definition: ".concat(JSON.stringify(a)));if(s.serverRepository.getList().some((function(t){return t.definition.name===a.name})))return o('A stream with the name "'.concat(a.name,'" already exists! Please, provide a unique name for the stream.'));a.supportsStreaming=!0,e||(e={}),"function"!=typeof e.subscriptionRequestHandler&&(e.subscriptionRequestHandler=function(t){t.accept()});var c=s.serverRepository.add({definition:a,streamCallbacks:e,protocolState:{}});s.protocol.server.createStream(c).then((function(){var t;r?(t=r,r.updateRepoMethod(c)):t=new ee(s.protocol,c,s),c.stream=t,i(t)})).catch((function(t){c.repoId&&s.serverRepository.remove(c.repoId),o(t)}))}else o("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.")})),i,o)},t.prototype.register=function(t,e){var n=this;if(!t)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 e)return Promise.reject("The second parameter must be a callback function. Method: ".concat("string"==typeof t?t:t.name));var r=function(t,r){return i(n,void 0,void 0,(function(){var n,i,s;return o(this,(function(o){switch(o.label){case 0:return o.trys.push([0,4,,5]),(n=e(t.args,t.instance))&&"function"==typeof n.then?[4,n]:[3,2];case 1:return i=o.sent(),r(void 0,i),[3,3];case 2:r(void 0,n),o.label=3;case 3:return[3,5];case 4:return s=o.sent(),r(null!=s?s:"",null!=s?s:""),[3,5];case 5:return[2]}}))}))};return r.userCallback=e,this.registerCore(t,r)},t.prototype.registerAsync=function(t,e){if(!t)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 e)return Promise.reject("The second parameter must be a callback function. Method: ".concat("string"==typeof t?t:t.name));var n=function(t,n){try{var i=!1,o=function(t){i||n(void 0,t),i=!0},r=function(t){i||(t||(t=""),n(t,t)),i=!0},s=e(t.args,t.instance,o,r);s&&"function"==typeof s.then&&s.then(o).catch(r)}catch(t){n(t,void 0)}};return n.userCallbackAsync=e,this.registerCore(t,n)},t.prototype.unregister=function(t,e){return void 0===e&&(e=!1),i(this,void 0,void 0,(function(){var n,i;return o(this,(function(o){switch(o.label){case 0:return void 0===t?[2,Promise.reject("Please, provide either a unique string for a name or an object containing a “name” property.")]:"function"!=typeof t?[3,2]:[4,this.unregisterWithPredicate(t,e)];case 1:case 3:return o.sent(),[2];case 2:return void 0===(n="string"==typeof t?{name:t}:t).name?[2,Promise.reject("Method name is required. Cannot find a method if the method name is undefined!")]:(i=this.serverRepository.getList().find((function(t){return t.definition.name===n.name&&(t.definition.supportsStreaming||!1)===e})))?[4,this.removeMethodsOrStreams([i])]:[2,Promise.reject('Method with a name "'.concat(n.name,'" does not exist or is not registered by your application!'))]}}))}))},t.prototype.unregisterWithPredicate=function(t,e){return i(this,void 0,void 0,(function(){var n;return o(this,(function(i){switch(i.label){case 0:return(n=this.serverRepository.getList().filter((function(e){return t(e.definition)})).filter((function(t){return(t.definition.supportsStreaming||!1)===e})))&&0!==n.length?[4,this.removeMethodsOrStreams(n)]:[2,Promise.reject("Could not find a ".concat(e?"stream":"method"," matching the specified condition!"))];case 1:return i.sent(),[2]}}))}))},t.prototype.removeMethodsOrStreams=function(t){var e=this,n=[];return t.forEach((function(t){var i=e.protocol.server.unregister(t).then((function(){t.repoId&&e.serverRepository.remove(t.repoId)}));n.push(i),e.addAsCurrentlyUnregistering(t.definition.name,i)})),Promise.all(n)},t.prototype.addAsCurrentlyUnregistering=function(t,e){return i(this,void 0,void 0,(function(){var n,i=this;return o(this,(function(o){return n=new Promise((function(t){return setTimeout(t,5e3)})),this.currentlyUnregistering[t]=Promise.race([e,n]).then((function(){delete i.currentlyUnregistering[t]})),[2]}))}))},t.prototype.registerCore=function(t,e){return i(this,void 0,void 0,(function(){var i,r,s,a=this;return o(this,(function(o){switch(o.label){case 0:return(i="string"==typeof t?{name:""+t}:n({},t)).name?(r=this.currentlyUnregistering[i.name])?[4,r]:[3,2]:[2,Promise.reject("Please, provide a (unique) string value for the “name” property in the “methodDefinition” object: ".concat(JSON.stringify(t)))];case 1:o.sent(),o.label=2;case 2:return this.serverRepository.getList().some((function(t){return t.definition.name===i.name}))?[2,Promise.reject('A method with the name "'.concat(i.name,'" already exists! Please, provide a unique name for the method.'))]:i.supportsStreaming?[2,Promise.reject("When you create methods with “glue.interop.register()” or “glue.interop.registerAsync()” the property “supportsStreaming” cannot be “true”. If you want “".concat(i.name,"” to be a stream, please use the “glue.interop.createStream()” method."))]:(s=this.serverRepository.add({definition:i,theFunction:e,protocolState:{}}),[2,this.protocol.server.register(s).catch((function(t){throw(null==s?void 0:s.repoId)&&a.serverRepository.remove(s.repoId),t}))])}}))}))},t.prototype.onMethodInvoked=function(t,e,n){var i=this;t&&t.theFunction&&t.theFunction(n,(function(n,o){if(null!=n)if(n.message&&"string"==typeof n.message)n=n.message;else if("string"!=typeof n)try{n=JSON.stringify(n)}catch(t){n="un-stringifyable error in onMethodInvoked! Top level prop names: ".concat(Object.keys(n))}o?("object"!=typeof o||Array.isArray(o))&&(o={_value:o}):o={},i.protocol.server.methodInvocationResult(t,e,n,o)}))},t}(),ie=function(){function t(t,e,n){var i=this;this.wrapped={},this.wrapped.getMethods=function(){return t.methodsForInstance(this)},this.wrapped.getStreams=function(){return t.methodsForInstance(this).filter((function(t){return t.supportsStreaming}))},e&&this.refreshWrappedObject(e),n&&(n.loggedIn((function(){i.refresh(n)})),this.refresh(n))}return t.prototype.unwrap=function(){return this.wrapped},t.prototype.refresh=function(t){if(t){var e=null==t?void 0:t.resolvedIdentity,n=Object.assign({},null!=e?e:{},{peerId:null==t?void 0:t.peerId});this.refreshWrappedObject(n)}},t.prototype.refreshWrappedObject=function(t){var e,n,i,o,r=this;Object.keys(t).forEach((function(e){r.wrapped[e]=t[e]})),this.wrapped.user=t.user,this.wrapped.instance=t.instance,this.wrapped.application=null!==(e=t.application)&&void 0!==e?e:ut(),this.wrapped.applicationName=t.applicationName,this.wrapped.pid=null!==(i=null!==(n=t.pid)&&void 0!==n?n:t.process)&&void 0!==i?i:Math.floor(1e10*Math.random()),this.wrapped.machine=t.machine,this.wrapped.environment=t.environment,this.wrapped.region=t.region,this.wrapped.windowId=t.windowId,this.wrapped.isLocal=null===(o=t.isLocal)||void 0===o||o,this.wrapped.api=t.api,this.wrapped.service=t.service,this.wrapped.peerId=t.peerId},t}(),oe=function(t){return n(n({},t),{flags:t.flags.metadata||{}})},re=function(){function t(t,e){this.logger=t,this.API=e,this.servers={},this.methodsCount={},this.callbacks=P();var n=this.API.instance.peerId;this.myServer={id:n,methods:{},instance:this.API.instance,wrapper:this.API.unwrappedInstance},this.servers[n]=this.myServer}return t.prototype.addServer=function(t,e){this.logger.debug("adding server ".concat(e));var n=this.servers[e];if(n)return n.id;var i=new ie(this.API,t),o={id:e,methods:{},instance:i.unwrap(),wrapper:i};return this.servers[e]=o,this.callbacks.execute("onServerAdded",o.instance),e},t.prototype.removeServerById=function(t,e){var n=this,i=this.servers[t];i?(this.logger.debug("removing server ".concat(t)),Object.keys(i.methods).forEach((function(e){n.removeServerMethod(t,e)})),delete this.servers[t],this.callbacks.execute("onServerRemoved",i.instance,e)):this.logger.warn("not aware of server ".concat(t,", my state ").concat(JSON.stringify(Object.keys(this.servers))))},t.prototype.addServerMethod=function(t,e){var n,i=this.servers[t];if(!i)throw new Error("server does not exists");if(!i.methods[e.id]){var o=this.createMethodIdentifier(e),r=this,s={identifier:o,gatewayId:e.id,name:e.name,displayName:e.display_name,description:e.description,version:e.version,objectTypes:e.object_types||[],accepts:e.input_signature,returns:e.result_signature,supportsStreaming:void 0!==e.flags&&e.flags.streaming,flags:null!==(n=e.flags)&&void 0!==n?n:{},getServers:function(){return r.getServersByMethod(o)}};s.object_types=s.objectTypes,s.display_name=s.displayName,s.version=s.version,i.methods[e.id]=s;var a=oe(s);return this.methodsCount[o]||(this.methodsCount[o]=0,this.callbacks.execute("onMethodAdded",a)),this.methodsCount[o]=this.methodsCount[o]+1,this.callbacks.execute("onServerMethodAdded",i.instance,a),s}},t.prototype.removeServerMethod=function(t,e){var n=this.servers[t];if(!n)throw new Error("server does not exists");var i=n.methods[e];delete n.methods[e];var o=oe(i);this.methodsCount[i.identifier]=this.methodsCount[i.identifier]-1,0===this.methodsCount[i.identifier]&&this.callbacks.execute("onMethodRemoved",o),this.callbacks.execute("onServerMethodRemoved",n.instance,o)},t.prototype.getMethods=function(){return this.extractMethodsFromServers(Object.values(this.servers)).map(oe)},t.prototype.getServers=function(){return Object.values(this.servers).map(this.hideServerMethodSystemFlags)},t.prototype.onServerAdded=function(t){var e=this.callbacks.add("onServerAdded",t),n=this.getServers().map((function(t){return t.instance}));return this.returnUnsubWithDelayedReplay(e,n,t)},t.prototype.onMethodAdded=function(t){var e=this.callbacks.add("onMethodAdded",t),n=this.getMethods();return this.returnUnsubWithDelayedReplay(e,n,t)},t.prototype.onServerMethodAdded=function(t){var e=this.callbacks.add("onServerMethodAdded",t),n=!1,i=this.getServers();return setTimeout((function(){i.forEach((function(e){var i=e.methods;Object.keys(i).forEach((function(o){n||t(e.instance,i[o])}))}))}),0),function(){n=!0,e()}},t.prototype.onMethodRemoved=function(t){return this.callbacks.add("onMethodRemoved",t)},t.prototype.onServerRemoved=function(t){return this.callbacks.add("onServerRemoved",t)},t.prototype.onServerMethodRemoved=function(t){return this.callbacks.add("onServerMethodRemoved",t)},t.prototype.getServerById=function(t){return this.hideServerMethodSystemFlags(this.servers[t])},t.prototype.reset=function(){var t,e=this;Object.keys(this.servers).forEach((function(t){e.removeServerById(t,"reset")})),this.servers=((t={})[this.myServer.id]=this.myServer,t),this.methodsCount={}},t.prototype.createMethodIdentifier=function(t){var e,n,i=null!==(e=t.input_signature)&&void 0!==e?e:"",o=null!==(n=t.result_signature)&&void 0!==n?n:"";return(t.name+i+o).toLowerCase()},t.prototype.getServersByMethod=function(t){var e=[];return Object.values(this.servers).forEach((function(n){Object.values(n.methods).forEach((function(i){i.identifier===t&&e.push(n.instance)}))})),e},t.prototype.returnUnsubWithDelayedReplay=function(t,e,n){var i=!1;return setTimeout((function(){e.forEach((function(t){i||n(t)}))}),0),function(){i=!0,t()}},t.prototype.hideServerMethodSystemFlags=function(t){var e={};return Object.entries(t.methods).forEach((function(t){var n=t[0],i=t[1];e[n]=oe(i)})),n(n({},t),{methods:e})},t.prototype.extractMethodsFromServers=function(t){return Object.values(t).reduce((function(t,e){return r(r([],t,!0),Object.values(e.methods),!0)}),[])},t}(),se=function(){function t(){this.nextId=0,this.methods=[]}return t.prototype.add=function(t){return t.repoId=String(this.nextId),this.nextId+=1,this.methods.push(t),t},t.prototype.remove=function(t){if("string"!=typeof t)return new TypeError("Expecting a string");this.methods=this.methods.filter((function(e){return e.repoId!==t}))},t.prototype.getById=function(t){if("string"==typeof t)return this.methods.find((function(e){return e.repoId===t}))},t.prototype.getList=function(){return this.methods.map((function(t){return t}))},t.prototype.length=function(){return this.methods.length},t.prototype.reset=function(){this.methods=[]},t}(),ae="onSubscriptionRequest",ce="onSubscriptionAdded",de="onSubscriptionRemoved",ue=function(){function t(t,e,n){var i=this;this.session=t,this.repository=e,this.serverRepository=n,this.ERR_URI_SUBSCRIPTION_FAILED="com.tick42.agm.errors.subscription.failure",this.callbacks=P(),this.nextStreamId=0,t.on("add-interest",(function(t){i.handleAddInterest(t)})),t.on("remove-interest",(function(t){i.handleRemoveInterest(t)}))}return t.prototype.acceptRequestOnBranch=function(t,e,n){if("string"!=typeof n&&(n=""),"object"!=typeof e.protocolState.subscriptionsMap)throw new TypeError("The streaming method is missing its subscriptions.");if(!Array.isArray(e.protocolState.branchKeyToStreamIdMap))throw new TypeError("The streaming method is missing its branches.");var i=this.getStreamId(e,n),o=t.msg.subscription_id,r={id:o,arguments:t.arguments,instance:t.instance,branchKey:n,streamId:i,subscribeMsg:t.msg};e.protocolState.subscriptionsMap[o]=r,this.session.sendFireAndForget({type:"accepted",subscription_id:o,stream_id:i}),this.callbacks.execute(ce,r,e)},t.prototype.rejectRequest=function(t,e,n){"string"!=typeof n&&(n=""),this.sendSubscriptionFailed("Subscription rejected by user. "+n,t.msg.subscription_id)},t.prototype.pushData=function(t,e,n){var i=this;if("object"==typeof t&&Array.isArray(t.protocolState.branchKeyToStreamIdMap)){if("object"!=typeof e)throw new Error("Invalid arguments. Data must be an object.");"string"==typeof n?n=[n]:(!Array.isArray(n)||n.length<=0)&&(n=[]),t.protocolState.branchKeyToStreamIdMap.filter((function(t){return!n||0===n.length||n.indexOf(t.key)>=0})).map((function(t){return t.streamId})).forEach((function(t){var n={type:"publish",stream_id:t,data:e};i.session.sendFireAndForget(n)}))}},t.prototype.pushDataToSingle=function(t,e,n){if("object"!=typeof n)throw new Error("Invalid arguments. Data must be an object.");var i={type:"post",subscription_id:e.id,data:n};this.session.sendFireAndForget(i)},t.prototype.closeSingleSubscription=function(t,e){t.protocolState.subscriptionsMap&&delete t.protocolState.subscriptionsMap[e.id];var n={type:"drop-subscription",subscription_id:e.id,reason:"Server dropping a single subscription"};this.session.sendFireAndForget(n),e.instance,this.callbacks.execute(de,e,t)},t.prototype.closeMultipleSubscriptions=function(t,e){var n=this;if("object"==typeof t&&"object"==typeof t.protocolState.subscriptionsMap&&t.protocolState.subscriptionsMap){var i=t.protocolState.subscriptionsMap,o=Object.keys(i).map((function(t){return i[t]}));"string"==typeof e&&(o=o.filter((function(t){return t.branchKey===e}))),o.forEach((function(t){delete i[t.id];var e={type:"drop-subscription",subscription_id:t.id,reason:"Server dropping all subscriptions on stream_id: "+t.streamId};n.session.sendFireAndForget(e)}))}},t.prototype.getSubscriptionList=function(t,e){if("object"!=typeof t)return[];if(!t.protocolState.subscriptionsMap)return[];var n=t.protocolState.subscriptionsMap,i=Object.keys(n).map((function(t){return n[t]}));return"string"!=typeof e?i:i.filter((function(t){return t.branchKey===e}))},t.prototype.getBranchList=function(t){if("object"!=typeof t)return[];if(!t.protocolState.subscriptionsMap)return[];var e=t.protocolState.subscriptionsMap,n=Object.keys(e).map((function(t){return e[t]})),i=[];return n.forEach((function(t){var e="";"object"==typeof t&&"string"==typeof t.branchKey&&(e=t.branchKey),-1===i.indexOf(e)&&i.push(e)})),i},t.prototype.onSubAdded=function(t){this.onSubscriptionLifetimeEvent(ce,t)},t.prototype.onSubRequest=function(t){this.onSubscriptionLifetimeEvent(ae,t)},t.prototype.onSubRemoved=function(t){this.onSubscriptionLifetimeEvent(de,t)},t.prototype.handleRemoveInterest=function(t){var e=this.serverRepository.getById(t.method_id);if("string"==typeof t.subscription_id&&"object"==typeof e&&e.protocolState.subscriptionsMap&&"object"==typeof e.protocolState.subscriptionsMap[t.subscription_id]){var n=e.protocolState.subscriptionsMap[t.subscription_id];delete e.protocolState.subscriptionsMap[t.subscription_id],this.callbacks.execute(de,n,e)}},t.prototype.onSubscriptionLifetimeEvent=function(t,e){this.callbacks.add(t,e)},t.prototype.getNextStreamId=function(){return this.nextStreamId+++""},t.prototype.handleAddInterest=function(t){var e=this.repository.getServerById(t.caller_id).instance,n={msg:t,arguments:t.arguments_kv||{},instance:e},i=this.serverRepository.getById(t.method_id);if(void 0!==i)i.protocolState.subscriptionsMap&&i.protocolState.subscriptionsMap[t.subscription_id]?this.sendSubscriptionFailed("A subscription with id "+t.subscription_id+" already exists.",t.subscription_id):this.callbacks.execute(ae,n,i);else{var o="No method with id "+t.method_id+" on this server.";this.sendSubscriptionFailed(o,t.subscription_id)}},t.prototype.sendSubscriptionFailed=function(t,e){var n={type:"error",reason_uri:this.ERR_URI_SUBSCRIPTION_FAILED,reason:t,request_id:e};this.session.sendFireAndForget(n)},t.prototype.getStreamId=function(t,e){if("string"!=typeof e&&(e=""),!t.protocolState.branchKeyToStreamIdMap)throw new Error("streaming ".concat(t.definition.name," method without protocol state"));var n=t.protocolState.branchKeyToStreamIdMap.filter((function(t){return t.key===e}))[0],i=n?n.streamId:void 0;return"string"==typeof i&&""!==i||(i=this.getNextStreamId(),t.protocolState.branchKeyToStreamIdMap.push({key:e,streamId:i})),i},t}(),he=function(){function t(t,e,n,i){var o=this;this.session=t,this.clientRepository=e,this.serverRepository=n,this.logger=i,this.callbacks=P(),this.streaming=new ue(t,e,n),this.session.on("invoke",(function(t){return o.handleInvokeMessage(t)}))}return t.prototype.createStream=function(t){return t.protocolState.subscriptionsMap={},t.protocolState.branchKeyToStreamIdMap=[],this.register(t,!0)},t.prototype.register=function(t,e){var n,i=this,o=t.definition,r=Object.assign({},{metadata:null!==(n=o.flags)&&void 0!==n?n:{}},{streaming:e||!1}),s={type:"register",methods:[{id:t.repoId,name:o.name,display_name:o.displayName,description:o.description,version:o.version,flags:r,object_types:o.objectTypes||o.object_types,input_signature:o.accepts,result_signature:o.returns,restrictions:void 0}]};return this.session.send(s,{methodId:t.repoId}).then((function(){i.logger.debug("registered method "+t.definition.name+" with id "+t.repoId)})).catch((function(e){throw i.logger.warn("failed to register method ".concat(t.definition.name," with id ").concat(t.repoId," - ").concat(JSON.stringify(e))),e}))},t.prototype.onInvoked=function(t){this.callbacks.add("onInvoked",t)},t.prototype.methodInvocationResult=function(t,e,n,i){var o;o=n||""===n?{type:"error",request_id:e,reason_uri:"agm.errors.client_error",reason:n,context:i,peer_id:void 0}:{type:"yield",invocation_id:e,peer_id:this.session.peerId,result:i,request_id:void 0},this.session.sendFireAndForget(o)},t.prototype.unregister=function(t){return i(this,void 0,void 0,(function(){var e;return o(this,(function(n){switch(n.label){case 0:return e={type:"unregister",methods:[t.repoId]},[4,this.session.send(e)];case 1:return n.sent(),[2]}}))}))},t.prototype.getBranchList=function(t){return this.streaming.getBranchList(t)},t.prototype.getSubscriptionList=function(t,e){return this.streaming.getSubscriptionList(t,e)},t.prototype.closeAllSubscriptions=function(t,e){this.streaming.closeMultipleSubscriptions(t,e)},t.prototype.pushData=function(t,e,n){this.streaming.pushData(t,e,n)},t.prototype.pushDataToSingle=function(t,e,n){this.streaming.pushDataToSingle(t,e,n)},t.prototype.closeSingleSubscription=function(t,e){this.streaming.closeSingleSubscription(t,e)},t.prototype.acceptRequestOnBranch=function(t,e,n){this.streaming.acceptRequestOnBranch(t,e,n)},t.prototype.rejectRequest=function(t,e,n){this.streaming.rejectRequest(t,e,n)},t.prototype.onSubRequest=function(t){this.streaming.onSubRequest(t)},t.prototype.onSubAdded=function(t){this.streaming.onSubAdded(t)},t.prototype.onSubRemoved=function(t){this.streaming.onSubRemoved(t)},t.prototype.handleInvokeMessage=function(t){var e=t.invocation_id,n=t.caller_id,i=t.method_id,o=t.arguments_kv,r=this.serverRepository.getList().filter((function(t){return t.repoId===i}))[0];if(void 0!==r){var s={args:o,instance:this.clientRepository.getServerById(n).instance};this.callbacks.execute("onInvoked",r,e,s)}},t}(),le=function(){function t(t,e){this.repository=t,this.subscriptionData=e}return Object.defineProperty(t.prototype,"requestArguments",{get:function(){return this.subscriptionData.params.arguments||{}},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"servers",{get:function(){var t=this;return this.subscriptionData.trackedServers.filter((function(t){return t.subscriptionId})).map((function(e){return t.repository.getServerById(e.serverId).instance}))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"serverInstance",{get:function(){return this.servers[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"stream",{get:function(){return this.subscriptionData.method},enumerable:!1,configurable:!0}),t.prototype.onData=function(t){if("function"!=typeof t)throw new TypeError("The data callback must be a function.");this.subscriptionData.handlers.onData.push(t),1===this.subscriptionData.handlers.onData.length&&this.subscriptionData.queued.data.length>0&&this.subscriptionData.queued.data.forEach((function(e){t(e)}))},t.prototype.onClosed=function(t){if("function"!=typeof t)throw new TypeError("The callback must be a function.");this.subscriptionData.handlers.onClosed.push(t)},t.prototype.onFailed=function(t){},t.prototype.onConnected=function(t){if("function"!=typeof t)throw new TypeError("The callback must be a function.");this.subscriptionData.handlers.onConnected.push(t)},t.prototype.close=function(){this.subscriptionData.close()},t.prototype.setNewSubscription=function(t){this.subscriptionData=t},t}(),pe=function(){function t(t){this.config=t,this.cache=[],this.timeoutIds=[]}return t.prototype.add=function(t){var e=this,n=ut();this.cache.push({id:n,element:t});var i=setTimeout((function(){var t=e.cache.findIndex((function(t){return t.id===n}));t<0||e.cache.splice(t,1)}),this.config.ELEMENT_TTL_MS);this.timeoutIds.push(i)},t.prototype.flush=function(){var t=this.cache.map((function(t){return t.element}));return this.timeoutIds.forEach((function(t){return clearInterval(t)})),this.cache=[],this.timeoutIds=[],t},t}(),ge="awaitingAccept",fe="subscribed",ye="Subscription failed.",me="ClientInitiated",ve=function(){function t(t,e,n){var i=this;this.session=t,this.repository=e,this.logger=n,this.subscriptionsList={},this.timedCache=new pe({ELEMENT_TTL_MS:1e4}),this.subscriptionIdToLocalKeyMap={},this.nextSubLocalKey=0,this.handleErrorSubscribing=function(t){var e=t._tag,n=e.subLocalKey,o=i.subscriptionsList[n];if("object"==typeof o&&(o.trackedServers=o.trackedServers.filter((function(t){return t.serverId!==e.serverId})),o.trackedServers.length<=0)){if(clearTimeout(o.timeoutId),o.status===ge){var r="string"==typeof t.reason&&""!==t.reason?' Publisher said "'+t.reason+'".':" No reason given.",s="object"==typeof o.params.arguments?JSON.stringify(o.params.arguments):"{}";o.error({message:"Subscription rejected."+r+" Called with:"+s,called_with:o.params.arguments,method:o.method})}else o.status===fe&&i.callOnClosedHandlers(o);delete i.subscriptionsList[n]}},this.handleSubscribed=function(t){var e=t._tag.subLocalKey,n=i.subscriptionsList[e];if("object"==typeof n){var o=t._tag.serverId,r=n.trackedServers.filter((function(t){return t.serverId===o}))[0];if("object"==typeof r){r.subscriptionId=t.subscription_id,i.subscriptionIdToLocalKeyMap[t.subscription_id]=e;var s=n.status===ge;if(n.status=fe,s){var a=!1,c=n.subscription;c?(c.setNewSubscription(n),n.success(c),a=!0):(c=new le(i.repository,n),n.subscription=c,n.success(c));for(var d=0,u=n.handlers.onConnected;d<u.length;d++){var h=u[d];try{h(c.serverInstance,a)}catch(t){}}}}}},this.handleEventData=function(t){var e=i.subscriptionIdToLocalKeyMap[t.subscription_id];if(void 0!==e){var n=i.subscriptionsList[e];if("object"==typeof n){var o=n.trackedServers.filter((function(e){return e.subscriptionId===t.subscription_id}));if(1===o.length){var r=t.oob,s=o[0].serverId,a=function(){return{data:t.data,server:i.repository.getServerById(s).instance,requestArguments:n.params.arguments,message:void 0,private:r}},c=n.handlers.onData,d=n.queued.data;c.length>0?c.forEach((function(t){"function"==typeof t&&t(a())})):d.push(a())}}}},this.handleSubscriptionCancelled=function(t){var e=i.subscriptionIdToLocalKeyMap[t.subscription_id];if(void 0!==e){var n=i.subscriptionsList[e];if("object"==typeof n){var o=n.trackedServers.length-1;n.trackedServers=n.trackedServers.filter((function(e){return e.subscriptionId!==t.subscription_id||(n.queued.closers.push(e.serverId),!1)})),n.trackedServers.length===o&&(n.trackedServers.length<=0&&(i.timedCache.add(n),clearTimeout(n.timeoutId),i.callOnClosedHandlers(n),delete i.subscriptionsList[e]),delete i.subscriptionIdToLocalKeyMap[t.subscription_id])}}},t.on("subscribed",this.handleSubscribed),t.on("event",this.handleEventData),t.on("subscription-cancelled",this.handleSubscriptionCancelled)}return t.prototype.subscribe=function(t,e,n,i,o,r){var s=this;if(0!==n.length){var a=this.getNextSubscriptionLocalKey(),c=this.registerSubscription(a,t,e,i,o,e.methodResponseTimeout||1e4,r);"object"==typeof c?n.forEach((function(n){var i=n.server.id,o=n.methods.find((function(e){return e.name===t.name}));if(o){c.trackedServers.push({serverId:i,subscriptionId:void 0});var r={type:"subscribe",server_id:i,method_id:o.gatewayId,arguments_kv:e.arguments};s.session.send(r,{serverId:i,subLocalKey:a}).then((function(t){return s.handleSubscribed(t)})).catch((function(t){return s.handleErrorSubscribing(t)}))}else s.logger.error("can not find method ".concat(t.name," for target ").concat(n.server.id))})):o({method:t,called_with:e.arguments,message:ye+" Unable to register the user callbacks."})}else o({method:t,called_with:e.arguments,message:ye+" No available servers matched the target params."})},t.prototype.drainSubscriptions=function(){var t=Object.values(this.subscriptionsList);return this.subscriptionsList={},this.subscriptionIdToLocalKeyMap={},t},t.prototype.drainSubscriptionsCache=function(){return this.timedCache.flush()},t.prototype.getNextSubscriptionLocalKey=function(){var t=this.nextSubLocalKey;return this.nextSubLocalKey+=1,t},t.prototype.registerSubscription=function(t,e,n,i,o,r,s){var a=this,c={localKey:t,status:ge,method:e,params:n,success:i,error:o,trackedServers:[],handlers:{onData:(null==s?void 0:s.handlers.onData)||[],onClosed:(null==s?void 0:s.handlers.onClosed)||[],onConnected:(null==s?void 0:s.handlers.onConnected)||[]},queued:{data:[],closers:[]},timeoutId:void 0,close:function(){return a.closeSubscription(t)},subscription:null==s?void 0:s.subscription};return s||(n.onData&&c.handlers.onData.push(n.onData),n.onClosed&&c.handlers.onClosed.push(n.onClosed),n.onConnected&&c.handlers.onConnected.push(n.onConnected)),this.subscriptionsList[t]=c,c.timeoutId=setTimeout((function(){if(void 0!==a.subscriptionsList[t]){var i=a.subscriptionsList[t];i.status===ge?(o({method:e,called_with:n.arguments,message:ye+" Subscription attempt timed out after "+r+" ms."}),delete a.subscriptionsList[t]):i.status===fe&&i.trackedServers.length>0&&(i.trackedServers=i.trackedServers.filter((function(t){return void 0!==t.subscriptionId})),delete i.timeoutId,i.trackedServers.length<=0&&(a.callOnClosedHandlers(i),delete a.subscriptionsList[t]))}}),r),c},t.prototype.callOnClosedHandlers=function(t,e){var n,i=t.queued.closers.length,o=i>0?t.queued.closers[i-1]:null;void 0!==o&&"string"==typeof o&&(n=this.repository.getServerById(o).instance),t.handlers.onClosed.forEach((function(i){"function"==typeof i&&i({message:e||"ServerInitiated",requestArguments:t.params.arguments||{},server:n,stream:t.method})}))},t.prototype.closeSubscription=function(t){var e=this,n=this.subscriptionsList[t];"object"==typeof n&&(n.trackedServers.forEach((function(t){void 0!==t.subscriptionId&&(n.queued.closers.push(t.serverId),e.session.sendFireAndForget({type:"unsubscribe",subscription_id:t.subscriptionId,reason_uri:"",reason:me}),delete e.subscriptionIdToLocalKeyMap[t.subscriptionId])})),n.trackedServers=[],this.callOnClosedHandlers(n,me),delete this.subscriptionsList[t])},t}(),we=function(){function t(t,e,n){var i=this;this.session=t,this.repository=e,this.logger=n,t.on("peer-added",(function(t){return i.handlePeerAdded(t)})),t.on("peer-removed",(function(t){return i.handlePeerRemoved(t)})),t.on("methods-added",(function(t){return i.handleMethodsAddedMessage(t)})),t.on("methods-removed",(function(t){return i.handleMethodsRemovedMessage(t)})),this.streaming=new ve(t,e,n)}return t.prototype.subscribe=function(t,e,n,i,o,r){this.streaming.subscribe(t,e,n,i,o,r)},t.prototype.invoke=function(t,e,n,i){var o=this,r=i.id,s={type:"call",server_id:r,method_id:e.gatewayId,arguments_kv:n};return this.session.send(s,{invocationId:t,serverId:r}).then((function(t){return o.handleResultMessage(t)})).catch((function(t){return o.handleInvocationError(t)}))},t.prototype.drainSubscriptions=function(){return this.streaming.drainSubscriptions()},t.prototype.drainSubscriptionsCache=function(){return this.streaming.drainSubscriptionsCache()},t.prototype.handlePeerAdded=function(t){var e=t.new_peer_id,n=t.identity,i=!t.meta||t.meta.local,o=Number(n.process),r={machine:n.machine,pid:isNaN(o)?n.process:o,instance:n.instance,application:n.application,applicationName:n.applicationName,environment:n.environment,region:n.region,user:n.user,windowId:n.windowId,peerId:e,api:n.api,isLocal:i};this.repository.addServer(r,e)},t.prototype.handlePeerRemoved=function(t){var e=t.removed_id,n=t.reason;this.repository.removeServerById(e,n)},t.prototype.handleMethodsAddedMessage=function(t){var e=this,n=t.server_id;t.methods.forEach((function(t){e.repository.addServerMethod(n,t)}))},t.prototype.handleMethodsRemovedMessage=function(t){var e=this,n=t.server_id,i=t.methods,o=this.repository.getServerById(n);Object.keys(o.methods).forEach((function(t){var r=o.methods[t];i.indexOf(r.gatewayId)>-1&&e.repository.removeServerMethod(n,t)}))},t.prototype.handleResultMessage=function(t){var e=t._tag.invocationId,n=t.result,i=t._tag.serverId;return{invocationId:e,result:n,instance:this.repository.getServerById(i).instance,status:$t.Success,message:""}},t.prototype.handleInvocationError=function(t){if(this.logger.debug("handle invocation error ".concat(JSON.stringify(t))),"_tag"in t){var e=t._tag.invocationId,n=t._tag.serverId,i=this.repository.getServerById(n),o=t.reason;return{invocationId:e,result:t.context,instance:i.instance,status:$t.Error,message:o}}return{invocationId:"",message:t.message,status:$t.Error,error:t}},t}();function be(t,e,n,r,s,a){var c,d=s.logger.subLogger("gw3-protocol"),u=new Promise((function(t){c=t})),h=e.domain("agm",["subscribed"]),l=new he(h,n,r,d.subLogger("server")),p=new we(h,n,d.subLogger("client"));return h.onJoined((function(s){n.addServer(t,e.peerId),s?function(){return i(this,void 0,void 0,(function(){var t,e,n,i,s,c,u,h,l,g,f;return o(this,(function(o){switch(o.label){case 0:for(d.info("reconnected - will replay registered methods and subscriptions"),p.drainSubscriptionsCache().forEach((function(t){var e=t.method,n=Object.assign({},t.params);d.info("trying to soft-re-subscribe to method ".concat(e.name,", with params: ").concat(JSON.stringify(n))),a.client.subscribe(e,n,void 0,void 0,t).then((function(){return d.info("soft-subscribing to method ".concat(e.name," DONE"))})).catch((function(t){return d.warn("subscribing to method ".concat(e.name," failed: ").concat(JSON.stringify(t),"}"))}))})),t=[],e=p.drainSubscriptions(),n=function(e){var n=e.method,i=Object.assign({},e.params);d.info("trying to re-subscribe to method ".concat(n.name,", with params: ").concat(JSON.stringify(i))),t.push(a.client.subscribe(n,i,void 0,void 0,e).then((function(){return d.info("subscribing to method ".concat(n.name," DONE"))})))},i=0,s=e;i<s.length;i++)c=s[i],n(c);for(u=r.getList(),r.reset(),h=function(e){var n=e.definition;d.info("re-publishing method ".concat(n.name)),e.stream?t.push(a.server.createStream(n,e.streamCallbacks,void 0,void 0,e.stream).then((function(){return d.info("subscribing to method ".concat(n.name," DONE"))}))):e.theFunction&&e.theFunction.userCallback?t.push(a.register(n,e.theFunction.userCallback).then((function(){return d.info("subscribing to method ".concat(n.name," DONE"))}))):e.theFunction&&e.theFunction.userCallbackAsync&&t.push(a.registerAsync(n,e.theFunction.userCallbackAsync).then((function(){return d.info("subscribing to method ".concat(n.name," DONE"))}))),d.info("re-publishing method ".concat(n.name," DONE"))},l=0,g=u;l<g.length;l++)f=g[l],h(f);return[4,Promise.all(t)];case 1:return o.sent(),d.info("Interop is re-announced"),[2]}}))}))}().then((function(){return e.setLibReAnnounced({name:"interop"})})).catch((function(t){return d.warn("Error while re-announcing interop: ".concat(JSON.stringify(t)))})):c&&(c({client:p,server:l}),c=void 0)})),h.onLeft((function(){n.reset()})),h.join(),u}var _e=function(){function t(t){var e=this;if(void 0===t)throw new Error("configuration is required");if(void 0===t.connection)throw new Error("configuration.connections is required");var n,i=t.connection;if("number"!=typeof t.methodResponseTimeout&&(t.methodResponseTimeout=3e4),"number"!=typeof t.waitTimeoutMs&&(t.waitTimeoutMs=3e4),this.unwrappedInstance=new ie(this,void 0,i),this.instance=this.unwrappedInstance.unwrap(),this.clientRepository=new re(t.logger.subLogger("cRep"),this),this.serverRepository=new se,3!==i.protocolVersion)throw new Error("protocol ".concat(i.protocolVersion," not supported"));n=be(this.instance,i,this.clientRepository,this.serverRepository,t,this),this.readyPromise=n.then((function(n){return e.protocol=n,e.client=new Qt(e.protocol,e.clientRepository,e.instance,t),e.server=new ne(e.protocol,e.serverRepository),e}))}return t.prototype.ready=function(){return this.readyPromise},t.prototype.serverRemoved=function(t){return this.client.serverRemoved(t)},t.prototype.serverAdded=function(t){return this.client.serverAdded(t)},t.prototype.serverMethodRemoved=function(t){return this.client.serverMethodRemoved(t)},t.prototype.serverMethodAdded=function(t){return this.client.serverMethodAdded(t)},t.prototype.methodRemoved=function(t){return this.client.methodRemoved(t)},t.prototype.methodAdded=function(t){return this.client.methodAdded(t)},t.prototype.methodsForInstance=function(t){return this.client.methodsForInstance(t)},t.prototype.methods=function(t){return this.client.methods(t)},t.prototype.servers=function(t){return this.client.servers(t)},t.prototype.subscribe=function(t,e,n,i){return this.client.subscribe(t,e,n,i)},t.prototype.createStream=function(t,e,n,i){return this.server.createStream(t,e,n,i)},t.prototype.unregister=function(t){return this.server.unregister(t)},t.prototype.registerAsync=function(t,e){return this.server.registerAsync(t,e)},t.prototype.register=function(t,e){return this.server.register(t,e)},t.prototype.invoke=function(t,e,n,i,o,r){return this.client.invoke(t,e,n,i,o,r)},t.prototype.waitForMethod=function(t){var e=new j,n=this.client.methodAdded((function(i){i.name===t&&(n(),e.resolve(i))}));return e.promise},t}(),Ie=["subscribed","success"],Ce=function(){function t(t,e){var n=this;this.publish=function(t,e,i){var o=i||{},r=o.routingKey,s=o.target,a=n.removeEmptyValues({type:"publish",topic:t,data:e,peer_id:n.peerId,routing_key:r,target_identity:s});n.session.send(a)},this.subscribe=function(t,e,i){return new Promise((function(o,r){var s=i||{},a=s.routingKey,c=s.target,d=n.removeEmptyValues({type:"subscribe",topic:t,peer_id:n.peerId,routing_key:a,source:c});n.session.send(d).then((function(i){var r=i.subscription_id;n.subscriptions.push({subscription_id:r,topic:t,callback:e,source:c}),o({unsubscribe:function(){return n.session.send({type:"unsubscribe",subscription_id:r,peer_id:n.peerId}),n.subscriptions=n.subscriptions.filter((function(t){return t.subscription_id!==r})),Promise.resolve()}})})).catch((function(t){return r(t)}))}))},this.watchOnEvent=function(){n.session.on("event",(function(t){var e=t.data,i=t.subscription_id,o=t["publisher-identity"],r=n.subscriptions.find((function(t){return t.subscription_id===i}));r&&(r.source?n.keysMatch(r.source,o)&&r.callback(e,r.topic,o):r.callback(e,r.topic,o))}))},this.connection=t,this.logger=e,this.peerId=t.peerId,this.subscriptions=[],this.session=t.domain("bus",Ie),this.readyPromise=this.session.join(),this.readyPromise.then((function(){n.watchOnEvent()}))}return t.prototype.ready=function(){return this.readyPromise},t.prototype.removeEmptyValues=function(t){var e={};return Object.keys(t).forEach((function(n){void 0!==t[n]&&null!==t[n]&&(e[n]=t[n])})),e},t.prototype.keysMatch=function(t,e){var n=Object.keys(t),i=!0;return n.forEach((function(n){t[n]!==e[n]&&(i=!1)})),i},t}(),Ae=function(t,e){var n,r,s,a,c,d,u,h,l,p="object"==typeof window?null!==(n=window.iodesktop)&&void 0!==n?n:window.glue42gd:void 0,g="object"==typeof window&&null!==(r=window.gdPreloadPromise)&&void 0!==r?r:Promise.resolve(),f=W("glue"),y=function(t,e,n){var i,o,r,s,a;if(N.isNode()){var c=process.env._GD_STARTING_CONTEXT_;if(c)try{a=JSON.parse(c)}catch(t){}}function d(){if(t.application)return t.application;if(n)return n.applicationName;if("undefined"!=typeof window&&void 0!==window.glue42electron)return window.glue42electron.application;var e=ut();return N.isNode()?a?a.applicationConfig.name:"NodeJS"+e:"undefined"!=typeof window&&"undefined"!=typeof document?document.title+" (".concat(e,")"):e}var u=function(){var i,o,r,s,c,u,h,l,p,g,f,y=t.gateway,m=null!==(i=null==y?void 0:y.protocolVersion)&&void 0!==i?i:3,v=null==y?void 0:y.reconnectInterval,w=null==y?void 0:y.reconnectAttempts,b=null==y?void 0:y.ws,_=null==y?void 0:y.sharedWorker,I=null==y?void 0:y.inproc,C=null!==(o=null==y?void 0:y.webPlatform)&&void 0!==o?o:void 0;n&&(b=n.gwURL),N.isNode()&&a&&a.gwURL&&(b=a.gwURL),b||_||I||(b="ws://localhost:8385");var A=d(),S=A;void 0!==n?(l=n.windowId,p=n.pid,n.env&&(g=n.env.env,f=n.env.region),S=null!==(r=n.application)&&void 0!==r?r:"glue-app",h=n.appInstanceId):N.isNode()?(p=process.pid,a&&(g=a.env,f=a.region,h=a.instanceId)):void 0!==(null===window||void 0===window?void 0:window.glue42electron)&&(l=null===window||void 0===window?void 0:window.glue42electron.instanceId,p=null===window||void 0===window?void 0:window.glue42electron.pid,g=null===window||void 0===window?void 0:window.glue42electron.env,f=null===window||void 0===window?void 0:window.glue42electron.region,S=null!==(s=null===window||void 0===window?void 0:window.glue42electron.application)&&void 0!==s?s:"glue-app",h=null===window||void 0===window?void 0:window.glue42electron.instanceId);var x=null!==(u=null===(c=t.gateway)||void 0===c?void 0:c.replaySpecs)&&void 0!==u?u:[];x.push(Nt);var k={application:S,applicationName:A,windowId:l,instance:h,process:p,region:f,environment:g,api:e.version||jt};return t.identity&&(k=Object.assign(k,t.identity)),{identity:k,reconnectInterval:v,ws:b,sharedWorker:_,webPlatform:C,inproc:I,protocolVersion:m,reconnectAttempts:w,replaySpecs:x}}(),h=d();if("undefined"!=typeof window){var l=window,p=l.htmlContainer?"".concat(l.htmlContainer.containerName,".").concat(l.htmlContainer.application):null===(i=null==l?void 0:l.glue42gd)||void 0===i?void 0:i.application;p&&(h=p)}return{bus:null!==(o=t.bus)&&void 0!==o&&o,application:h,auth:function(){var e,n,i;return"string"==typeof t.auth?{token:t.auth}:t.auth?t.auth:N.isNode()&&a&&a.gwToken?{gatewayToken:a.gwToken}:(null===(e=t.gateway)||void 0===e?void 0:e.webPlatform)||(null===(n=t.gateway)||void 0===n?void 0:n.inproc)||(null===(i=t.gateway)||void 0===i?void 0:i.sharedWorker)?{username:"glue42",password:"glue42"}:void 0}(),logger:function(){var e,i,o,r=t.logger,s="warn";return r||(r=s),n&&(o=n.consoleLogLevel),"string"==typeof r?{console:null!=o?o:r,publish:s}:{console:null!==(e=null!=o?o:r.console)&&void 0!==e?e:s,publish:null!==(i=r.publish)&&void 0!==i?i:s}}(),connection:u,metrics:null===(r=t.metrics)||void 0===r||r,contexts:void 0===t.contexts||"boolean"==typeof t.contexts&&t.contexts?{reAnnounceKnownContexts:!0}:"object"==typeof t.contexts&&Object.assign({},{reAnnounceKnownContexts:!0},t.contexts),version:e.version||jt,libs:null!==(s=e.libs)&&void 0!==s?s:[],customLogger:t.customLogger}}(t=t||{},e=e||{},p),m={};function v(t,e,n){(l=c.canPublish("trace"))&&c.trace("registering ".concat(t," module"));var i=function(){e.initTime=n.stop(),e.initEndTime=n.endTime,e.marks=n.marks,l&&c.trace("".concat(t," is ready - ").concat(n.endTime-n.startTime))};e.initStartTime=n.startTime,e.ready?e.ready().then((function(){i()})):i(),Array.isArray(t)||(t=[t]),t.forEach((function(t){m[t]=e,Ae[t]=e}))}function w(){var t,e,n,i,o,r=W("metrics"),a=y.metrics,u=null==p?void 0:p.getMetricsPublishingEnabled,h=y.connection.identity,l=u||function(){return!0},g=null!==(t="boolean"!=typeof a&&a.disableAutoAppSystem)&&void 0!==t&&t;return v("metrics",d=x({connection:a?s:void 0,logger:c.subLogger("metrics"),canUpdateMetric:l,system:"Glue42",service:null!==(n=null!==(e=null==h?void 0:h.service)&&void 0!==e?e:null==p?void 0:p.applicationName)&&void 0!==n?n:y.application,instance:null!==(o=null!==(i=null==h?void 0:h.instance)&&void 0!==i?i:null==h?void 0:h.windowId)&&void 0!==o?o:ut(),disableAutoAppSystem:g,pagePerformanceMetrics:"boolean"!=typeof a?null==a?void 0:a.pagePerformanceMetrics:void 0}),r),Promise.resolve()}function b(){var t=y.activities&&3===s.protocolVersion;if(y.contexts||t){var e=W("contexts");return v("contexts",u=new Vt({connection:s,logger:c.subLogger("contexts"),trackAllContexts:"object"==typeof y.contexts&&y.contexts.trackAllContexts,reAnnounceKnownContexts:"object"==typeof y.contexts&&y.contexts.reAnnounceKnownContexts}),e),u}var n=s.replayer;n&&n.drain(Nt.name)}function _(){return i(this,void 0,void 0,(function(){var t;return o(this,(function(e){return y.bus?(t=W("bus"),v("bus",h=new Ce(s,c.subLogger("bus")),t),[2,Promise.resolve()]):[2,Promise.resolve()]}))}))}function I(t){try{return t.forEach((function(t){!function(t,e){var n=W(t),i=e(m);i&&v(t,i,n)}(t.name,t.create)})),Promise.resolve()}catch(t){return Promise.reject(t)}}return g.then((function(){var t,e=W("logger");return(c=new wt("".concat(null===(t=y.connection.identity)||void 0===t?void 0:t.application),void 0,y.customLogger)).consoleLevel(y.logger.console),c.publishLevel(y.logger.publish),c.canPublish("debug")&&c.debug("initializing glue..."),v("logger",c,e),Promise.resolve(void 0)})).then((function(){var t=W("connection");s=new mt(y.connection,c.subLogger("connection"));var e=Promise.resolve(y.auth);return y.connection&&!y.auth&&(p?e=p.getGWToken().then((function(t){return{gatewayToken:t}})):"undefined"!=typeof window&&(null===window||void 0===window?void 0:window.glue42electron)?"string"==typeof window.glue42electron.gwToken&&(e=Promise.resolve({gatewayToken:window.glue42electron.gwToken})):e=Promise.reject("You need to provide auth information")),e.then((function(e){var n;if(t.mark("auth-promise-resolved"),"[object Object]"!==Object.prototype.toString.call(e))throw new Error("Invalid auth object - "+JSON.stringify(e));return n=e,s.login(n)})).then((function(){return v("connection",s,t),y})).catch((function(t){throw s&&s.logout(),t}))})).then((function(){return Promise.all([w(),(t=W("interop"),e={connection:s,logger:c.subLogger("interop")},a=new _e(e),wt.Interop=a,v(["interop","agm"],a,t),Promise.resolve()),b(),_()]);var t,e})).then((function(){return a.readyPromise})).then((function(){return function(){return i(this,void 0,void 0,(function(){var e,n,i;return o(this,(function(o){switch(o.label){case 0:if(e="T42.ACS.RegisterInstance",!N.isNode()||void 0!==process.env._GD_STARTING_CONTEXT_||void 0===(null==t?void 0:t.application))return[3,4];if(!(a.methods({name:e}).length>0))return[3,4];o.label=1;case 1:return o.trys.push([1,3,,4]),[4,a.invoke(e,{appName:null==t?void 0:t.application,pid:process.pid})];case 2:return o.sent(),[3,4];case 3:return n=o.sent(),i=n,c.error("Cannot register as an instance: ".concat(JSON.stringify(i.message))),[3,4];case 4:return[2]}}))}))}()})).then((function(){return I(y.libs||[])})).then((function(){var t=Object.keys(m).map((function(t){var e=m[t];return e.ready?e.ready():Promise.resolve()}));return Promise.all(t)})).then((function(){var n={coreVersion:jt,version:y.version};f.stop();var i={feedback:function(t){a&&a.invoke("T42.ACS.Feedback",t,"best")},info:n,logger:c,interop:a,agm:a,connection:s,metrics:d,contexts:u,bus:h,version:y.version,userConfig:t,done:function(){return null==c||c.info("done called by user..."),s.logout()}};if(i.performance={get glueVer(){return y.version},get glueConfig(){return JSON.stringify(t)},get browser(){return window.performance.timing.toJSON()},get memory(){return window.performance.memory},get initTimes(){var t=O;return Object.keys(t).map((function(e){var n=t[e];return{name:e,duration:n.endTime-n.startTime,marks:n.marks,startTime:n.startTime,endTime:n.endTime}}))}},Object.keys(m).forEach((function(t){var e=m[t];i[t]=e})),i.config={},Object.keys(y).forEach((function(t){i.config[t]=y[t]})),e&&e.extOptions&&Object.keys(e.extOptions).forEach((function(t){i.config[t]=null==e?void 0:e.extOptions[t]})),(null==e?void 0:e.enrichGlue)&&e.enrichGlue(i),p&&p.updatePerfData&&p.updatePerfData(i.performance),i.agm){var o=function(t,e,n){return function(){return i.logger.warn("glue.js - 'glue.agm.".concat(e,"' method is deprecated, use 'glue.interop.").concat(n,"' instead.")),t.apply(i.agm,arguments)}},r=i.agm;r.method_added=o(i.agm.methodAdded,"method_added","methodAdded"),r.method_removed=o(i.agm.methodRemoved,"method_removed","methodRemoved"),r.server_added=o(i.agm.serverAdded,"server_added","serverAdded"),r.server_method_aded=o(i.agm.serverMethodAdded,"server_method_aded","serverMethodAdded"),r.server_method_removed=o(i.agm.serverMethodRemoved,"server_method_removed","serverMethodRemoved")}return i})).catch((function(t){return Promise.reject({err:t,libs:m})}))};"undefined"!=typeof window&&(window.IOConnectCore=Ae),Ae.version=jt,Ae.default=Ae;class Se{constructor(t){this._id=t}get id(){return this._id}_update(t){if(t._id!==this._id)throw Error("Can not update from entity with different id.");this._updateCore(t)}_updateCore(t){}_beforeDelete(t){}}function xe(t){return"number"==typeof t}function ke(t){return"string"==typeof t}function Te(t){return"object"==typeof t&&null!==t}function Ee(t){return Array.isArray?Array.isArray(t):"[object Array]"===toString.call(t)}function Pe(t){return void 0===t}function Me(t){return null==t}function Re(t){return"string"!=typeof t||!t||0===t.length||/^\s*$/.test(t)}function Ne(t){return!0===t||!1===t||"[object Boolean]"===toString.call(t)}function je(t){return!!(t&&t.constructor&&t.call&&t.apply)}function Oe(t,e){void 0!==t&&e(t)}class We extends Se{constructor(t,e,n,i){super(t),this._name=t,this._description=i,this._ownerWindow=e,this._helperWindows=n||[]}get name(){return this._name}get description(){return this._description}get helperWindows(){return this._helperWindows.map((t=>this.covertToWindowDef(t)))}get ownerWindow(){return this.covertToWindowDef(this._ownerWindow)}initiate(t,e,n){return this._manager.initiate(this._name,t,e,n)}_updateCore(t){super._updateCore(t),Oe(t._description,(t=>this._description=t)),Oe(t._ownerWindow,(t=>this._ownerWindow=t)),Oe(t._helperWindows,(t=>this._helperWindows=t))}covertToWindowDef(t){var e,n;return{type:null===(e=null==t?void 0:t.id)||void 0===e?void 0:e.type,name:null===(n=null==t?void 0:t.id)||void 0===n?void 0:n.name}}}class Fe extends Se{constructor(t,e){super(t),this._name=t,this._appByWindowTypeGetter=e}get name(){return this._name}get config(){return this._appByWindowTypeGetter(this._name)}get windows(){return this._manager.getWindows({type:this._name})}create(t,e){const n=Object.assign({type:this.name,name:this.name,isIndependent:!1},e);return this._manager.createWindow(t,n)}}class Le{constructor(t,e){this.entity=t,this.context=e}}class De{constructor(t){this.type=t}}class Ge extends De{constructor(t,e){super(qe.StatusChange),this.newStatus=t,this.oldStatus=e}}class Be extends De{constructor(t,e,n){super(qe.ActivityContextChange),this.context="string"==typeof t?JSON.parse(t):t,this.updated=e,this.removed=n}}class qe{}qe.Added="added",qe.Removed="removed",qe.Updated="updated",qe.Closed="closed",qe.StatusChange="statusChange",qe.ActivityContextChange="activityContextUpdate",qe.ActivityWindowEvent="activityWindowEvent",qe.ActivityWindowJoinedActivity="joined",qe.ActivityWindowLeftActivity="left";class Ue{}Ue.Created="created",Ue.Started="started",Ue.Destroyed="destroyed";class He{constructor(t){this._activity=t}register(t,e){this._ensureHasAgm(),He.AGM.register(t,e)}servers(){return this._ensureHasAgm(),Me(this._activity)?[]:this._activity.windows.map((t=>t.instance))}methods(){if(this._ensureHasAgm(),Me(this._activity))return[];const t=this._activity.windows,e=[],n=[];return t.forEach((t=>{this.methodsForWindow(t).forEach((t=>{-1===e.indexOf(t.name)&&(e.push(t.name),n.push(t))}))})),n}methodsForWindow(t){return this._ensureHasAgm(),t.instance?He.AGM.methodsForInstance(t.instance):[]}invoke(t,e,n,i,o,r){this._ensureHasAgm();const s=this.servers();if(Me(n)&&(n="activity.all"),ke(n))if("activity.all"===n);else{if("activity.best"!==n){if("all"===n||"best"===n)return function(t,e,n){if("function"!=typeof e&&"function"!=typeof n)return t;"function"!=typeof e?e=()=>{}:"function"!=typeof n&&(n=()=>{}),t.then(e,n)}(He.AGM.invoke(t,e,n,i),o,r);throw new Error("Invalid invoke target "+n)}{const e=s.filter((e=>He.AGM.methodsForInstance(e).filter((e=>e.name===t)).length>0));e.length>0&&e[0]}}else if(Ee(n)){if(n.length>=0){const t=n[0];if(this._isInstance(t))n.map((t=>t));else{if(!this._isActivityWindow(t))throw new Error("Unknown target object");n.map((t=>t.instance))}}}else if(this._isInstance(n));else{if(!this._isActivityWindow(n))throw new Error("Unknown target object");n.instance}throw new Error("Not implemented")}unregister(t){return this._ensureHasAgm(),He.AGM.unregister(t)}createStream(t,e,n){this._ensureHasAgm(),He.AGM.createStream(t,{subscriptionAddedHandler:e,subscriptionRemovedHandler:n,subscriptionRequestHandler:void 0})}subscribe(t,e,n){return this._ensureHasAgm(),He.AGM.subscribe(t,e)}_ensureHasAgm(){if(Me(He.AGM))throw new Error("Agm should be configured to be used in activity")}_isInstance(t){return void 0!==t.application}_isActivityWindow(t){return void 0!==t.instance}}class $e{constructor(t,e,n){this._manager=t,this._ownerActivityId=e,this._state=n}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(t){t=t||{};const e={};return Object.keys(this._state).forEach((t=>{e[t]=this._state[t]})),e.context=t.context||e.context,e.frameColor=t.frameColor||e.frameColor,this._manager.detachActivities(this._ownerActivityId,e)}}const Je=t=>{setTimeout(t,0)};function Ve(t,e){if(!je(e))return t;t.then((t=>{Je((()=>{e(null,t)}))}),(t=>{Je((()=>{e(t,null)}))}))}class ze extends Se{constructor(t,e,n,i,o){super(t),this._id=t,this._actType=e,this._status=n,this._context=i,this._ownerId=o,this._agm=new He(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(t,e){return this._manager.addWindowToActivity(this,t,e)}createWindow(t,e){return this._manager.createWindow(this,t,e)}createStackedWindows(t,e,n){return this._manager.createStackedWindows(this,t,e,n)}leave(t,e){return this._manager.leaveWindowFromActivity(this,t,e)}getWindowsByType(t){const e={activityId:this._id,type:t};return this._manager.getWindows(e)}setContext(t,e){return this._manager.setActivityContext(this,t,e)}updateContext(t,e){return this._manager.updateActivityContext(this,t,e)}onStatusChange(t){return this._manager.subscribeActivityEvents(((e,n,i)=>{e.id===this.id&&t(e,n,i)}))}onWindowEvent(t){return this._manager.subscribeWindowEvents(((e,n,i)=>{e.id===this.id&&t(e,n,i)}))}onContextChanged(t){this._manager.subscribeActivityContextChanged(((e,n,i,o)=>{e.id===this.id&&t(n,i,o,e)}));try{t(this.context,this.context,[],this)}catch(t){return}}stop(){this._manager.stopActivity(this)}clone(t){return this._manager.clone(this,t)}attach(t,e){let n;return n="string"==typeof t?t:t.id,this._manager.attachActivities(n,this.id,e)}onActivityAttached(t){this._manager.subscribeActivitiesAttached(((e,n,i)=>{e===this._id&&t(i)}))}onDetached(t){this._manager.subscribeActivitiesDetached(((e,n,i)=>{n.id===this._id&&t(e,i)}))}_updateCore(t){super._updateCore(t),Oe(t._actType,(t=>this._actType=t)),Oe(t._context,(t=>this._context=t)),Oe(t._ownerId,(t=>this._ownerId=t)),!t._status||this._status&&this._status.state===t._status.state||(this._status=t._status)}_updateDescriptors(t){this._attached=t.map((t=>new $e(this._manager,this._id,t)))}get attached(){return this._attached}setFrameColor(t,e){return Ve(new Promise(((e,n)=>{let i=this.windows.length;0===i&&e(this),this.windows.forEach((n=>{n.underlyingWindow.setFrameColor(t,(()=>{i--,i<=0&&e(this)}))})),setTimeout((()=>{i>0&&n(this.id+" - timed out waiting for setFrameColor with"+t)}),5e3)})),e)}getFrameColor(){return this.windows&&0!==this.windows.length?this.windows[0].underlyingWindow.frameColor:""}}class Ke{}Ke.Trace="trace",Ke.Debug="debug",Ke.Info="info",Ke.Warn="warn",Ke.Error="error";class Qe{static GetNamed(t){return new Qe(t)}static Get(t){return new Qe(Qe.GetTypeName(t))}constructor(t){this._name=t,Me(Qe.GlueLogger)||(this._glueLogger=Qe.GlueLogger.subLogger(t))}trace(t){Me(this._glueLogger)?Qe.Level===Ke.Trace&&console.info(this._getMessage(t,Ke.Trace)):this._glueLogger.trace(t)}debug(t){Me(this._glueLogger)?Qe.Level!==Ke.Debug&&Qe.Level!==Ke.Trace||console.info(this._getMessage(t,Ke.Debug)):this._glueLogger.debug(t)}info(t){Me(this._glueLogger)?Qe.Level!==Ke.Debug&&Qe.Level!==Ke.Trace&&Qe.Level!==Ke.Info||console.info(this._getMessage(t,Ke.Info)):this._glueLogger.info(t)}warn(t){Me(this._glueLogger)?Qe.Level!==Ke.Debug&&Qe.Level!==Ke.Trace&&Qe.Level!==Ke.Info&&Qe.Level!==Ke.Warn||console.info(this._getMessage(t,Ke.Info)):this._glueLogger.warn(t)}error(t){Me(this._glueLogger)?(console.error(this._getMessage(t,Ke.Error)),console.trace()):this._glueLogger.error(t)}_getMessage(t,e){return"["+e+"] "+this._name+" - "+t}static GetTypeName(t){const e=/function (.{1,})\(/.exec(t.constructor.toString());return e&&e.length>1?e[1]:""}}Qe.Level=Ke.Info;class Ze extends Se{constructor(t,e,n,i,o,r,s,a){super(t),this._logger=Qe.Get("window"),this._type=n,this._activityId=i,this._name=e,this._instance=o,this._isIndependent=r,this._windowGetter=s,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(!Pe(this._activityId))return this._manager.getActivityById(this._activityId)}get isOwner(){const t=this.activity;return!Pe(t)&&t.owner.id===this.id}setVisible(t,e){return this._manager.setWindowVisibility(this.id,t)}activate(t){return this._manager.activateWindow(this.id,t)}setBounds(t,e){return this._manager.setWindowBounds(this.id,t,e)}close(){return this._manager.closeWindow(this.id)}get instance(){return this._instance}get underlyingWindow(){const t=this._windowGetter();return t||{id:this._hcWindowId}}onActivityJoined(t){this._subscribeForActivityWindowEvent(qe.ActivityWindowJoinedActivity,t)}onActivityRemoved(t){this._subscribeForActivityWindowEvent(qe.ActivityWindowLeftActivity,t)}_updateCore(t){Oe(t._activityId,(t=>this._activityId=t)),Oe(t._isIndependent,(t=>this._isIndependent=t)),Oe(t._hcWindowId,(t=>this._hcWindowId=t)),Oe(t._type,(t=>this._type=t)),Oe(t._name,(t=>this._name=t)),Me(t._instance)||(this._instance=t._instance)}_subscribeForActivityWindowEvent(t,e){this._manager.subscribeWindowEvents(((n,i,o)=>{i.id===this.id&&o===t&&e(n)}))}_beforeDelete(t){this._hcWindowId=t._hcWindowId}}class Xe{constructor(t,e,n){this.state=t,this.message=e,this.time=n}getState(){return this.state}getMessage(){return this.message}getTime(){return this.time}}const Ye="error",tn="add-types",en="created",nn="destroyed",on="initiated",rn="joined",sn="activity-joined",an="left",cn="owner-changed",dn="add-peer-factories",un="peer-factories-added",hn="peer-factories-removed",ln="peer-created";class pn{static activityTypeGwMessageEntityToActivityType(t,e){const n=t=>new Fe(t,void 0);return new We(t.name,t.owner_type&&n(t.owner_type),t.helper_types&&t.helper_types.map(n),e)}static peerFactoryGwMessageEntityToWindowType(t){return new Fe(t.peer_type,(t=>{}))}static activityGwMessageToActivity(t,e){const n=void 0!==t.owner?t.owner.peer_id:t.owner_id;return new ze(t.activity_id,t.activity_type,e,t.context_snapshot,n)}static activityToActivityStatusChangeEvent(t){return new Le(t,new Ge(t.status,void 0))}constructor(t){if(this._activityChangeCallbacks=[],this._activityTypeStatusChangeCallbacks=[],this._activityWindowChangeCallbacks=[],this._windowTypeStatusChangeCallbacks=[],this._peerIdAndFactoryIdToPeerType={},this._peerFactoriesRegisteredByUs={},this._gw3Subscriptions=[],this._contextSubscriptions={},this._activityTypesInitiatedFromMe={},this._config=t,this._connection=t.connection,this._logger=t.logger,this._contexts=t.contexts,this._windows=t.windows,this._sessionJoinedPromise=new Promise((t=>{this._sessionJoinedPromiseResolve=t})),this._activityJoinedPromise=new Promise((t=>{this._activityJoinedPromiseResolve=t})),this._config.activityId||this._activityJoinedPromiseResolve({}),this._gw3Session=this._connection.domain("activity",["joined","initiated","peer-created","token"]),"undefined"!=typeof window){const t=window.glue42gd;t&&t.activityInfo&&("function"==typeof t.addRefreshHandler&&t.addRefreshHandler(((e,n)=>{this._gw3Session.send({type:"reload"}).then((i=>{if(i.token){try{t.setGWToken(i.token)}catch(t){return void n(t.message||t)}e()}else n("Expected gateway token for refreshing.")}),n)})),t&&"function"==typeof t.addWillNavigateHandler&&t.addWillNavigateHandler(((e,n)=>{this._gw3Session.send({type:"reload"}).then((i=>{if(i.token){try{t.setGWToken(i.token)}catch(t){return void n(t.message||t)}e()}else n("Expected gateway token for refreshing.")}),n)})))}}get bridgeType(){return"GW3"}init(){this.forwardActivityTypeMessagesToStatusEventHandlers(),this.subscribe(en,this.handleActivityCreatedMessage),this.subscribe(nn,this.handleActivityDestroyedMessage),this.forwardActivityMessagesToStatusEventHandlers(),this.forwardActivityCreatedAndJoinedActivityToActivityWindowEventHandlers(),this.forwardPeerFactoryMessagesToStatusEventHandlers(),this.forwardPeerFactoryMessagesToPeerFactoryRequests(),this.subscribe(un,this.handlePeerFactoriesAdded),this.subscribe(hn,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((t=>t&&this._connection.off(t))),this._gw3Subscriptions.length=0}ready(){return Promise.all([this._sessionJoinedPromise,this._activityJoinedPromise])}initReady(){return this._sessionJoinedPromise}onActivityTypeStatusChange(t){this._activityTypeStatusChangeCallbacks.push(t)}registerActivityType(t,e,n,i,o){const r={};r.name=t;const s=t=>({type:t.type,name:t.name,configuration:t});return r.owner_type=s(e),r.helper_types=n.map(s),this._gw3Session.send({type:tn,types:[r]}).then((()=>{const t=pn.activityTypeGwMessageEntityToActivityType(r,o);return this.invokeCallbacks(this._activityTypeStatusChangeCallbacks,new Le(t,new De(qe.Added)),tn),t}))}unregisterActivityType(t){return this._gw3Session.send({type:"remove-types",types:[t]}).then((()=>{const e=new We(t,void 0,void 0,void 0);this.invokeCallbacks(this._activityTypeStatusChangeCallbacks,new Le(e,new De(qe.Removed)),tn)}))}onWindowTypeStatusChange(t){this._windowTypeStatusChangeCallbacks.push(t)}registerWindowFactory(t,e,n){if(this._peerFactoriesRegisteredByUs[t])return Promise.reject(new Error(`Factory for windowType ${t} already registered.`));this._peerFactoriesRegisteredByUs[t]=e;const i={id:t,peer_type:t,configuration:n};return this._gw3Session.send({type:dn,factories:[i]}).then((()=>{this.invokeCallbacks(this._windowTypeStatusChangeCallbacks,new Le(pn.peerFactoryGwMessageEntityToWindowType(i),new De(qe.Added)),dn)})).catch((()=>{delete this._peerFactoriesRegisteredByUs[t]}))}unregisterWindowFactory(t){return this._peerFactoriesRegisteredByUs[t]?(delete this._peerFactoriesRegisteredByUs[t],this._gw3Session.send({type:"remove-peer-factories",factory_ids:[t]}).then((()=>{this.invokeCallbacks(this._windowTypeStatusChangeCallbacks,new Le(new Fe(t,void 0),new De(qe.Removed)),dn)}))):Promise.reject(new Error(`Factory for windowType ${t} not registered.`))}onActivityStatusChange(t){this._activityChangeCallbacks.push(t)}initiateActivity(t,e,n){const i={type:"create",activity_type:t,initial_context:e};return this.isOverrideTypeDefinition(n)?i.types_override={owner_type:{type:n.owner.type,name:n.owner.name,configuration:n.owner},helper_types:n.helpers&&n.helpers.map((t=>({type:t.type,name:t.name,configuration:t})))}:i.configuration=n&&n.map((t=>({type:t.type,name:t.name,configuration:t}))),this.sendCreateAndMapResultingMessagesToPromise(i,on,((t,e)=>t.request_id===e),en,((t,e,n)=>t.activity_id===n.activity_id),nn,((t,e,n)=>t.activity_id===n.activity_id),(t=>t.activity_id),null).then((e=>"trackMyTypeAndInitiatedFromMe"!==this._config.mode||this._activityTypesInitiatedFromMe[t]?e:(this._activityTypesInitiatedFromMe[t]=!0,this._gw3Session.send({type:"subscribe",activity_types:[t]}).then((()=>e)))))}stopActivity(t){return this._gw3Session.send({type:"destroy",activity_id:t.id,reason_uri:"com.tick42.glue.activity.constants.destroyReason.general",reason:"Destroying activity"}).then((t=>!0))}updateActivityContext(t,e,n,i){if(n)return this._contexts.set(t.id,e);i=i||[];for(const t of i)e[t]=null;return this._contexts.update(t.id,e)}announceWindow(t,e){throw new Error("Invalid operation 'announceWindow' for GW3 protocol")}registerWindow(t,e,n){let i=void 0!==this._connection.gatewayToken;const o=this._connection.peerId;if("undefined"!=typeof window){const t=window.glue42gd;t&&(i=void 0!==t.activityInfo)}return i&&this._gw3Session.send({type:"ready"}),this.invokeCallbacks(this._activityWindowChangeCallbacks,new Le(new Ze(o,e,t,void 0,this.getAgmInstance(o),n,this.generateWindowGetter(o),void 0),new De(qe.Added)),"register window"),Promise.resolve(o)}onActivityWindowChange(t){this._activityWindowChangeCallbacks.push(t)}createWindow(t,e){e.layout||(e.left||e.width||e.height||e.top)&&(e.layout={mode:"pixels",cellSize:1});const n=n=>{if(t)return this.joinActivity(t,n,e.name).then((()=>n))};return this.sendCreateAndMapResultingMessagesToPromise({type:"create-peer",peer_type:e.type,peer_name:e.name||e.type,configuration:e,activity_id:t},void 0,void 0,ln,((t,e)=>t.request_id===e),void 0,void 0,(t=>t.created_id),n).then(n)}closeWindow(t){return this._gw3Session.send({type:"destroy-peer",destroy_peer_id:t}).then((t=>{}))}getAnnouncementInfo(){let t=this._config.activityId||this._config.announcementInfo&&this._config.announcementInfo.activityId,e=this._config.announcementInfo&&this._config.announcementInfo.activityWindowType,n=this._config.announcementInfo&&this._config.announcementInfo.activityWindowIndependent,i=this._config.announcementInfo&&this._config.announcementInfo.activityWindowName;if("undefined"!=typeof window&&void 0!==window.location&&window.location.search&&"function"==typeof URLSearchParams){const o=new URLSearchParams(location.search.slice(1));e=e||o.get("t42PeerType"),e=e||o.get("t42ActivityWindowType"),void 0===n&&(n=o.get("t42ActivityWindowIndependent")),i=i||o.get("t42ActivityWindowName"),t=t||o.get("t42ActivityId")}return e=e||"unknown",n=n||!1,i=i||this._connection.peerId,{activityWindowId:void 0,activityId:t,activityWindowType:e,activityWindowIndependent:n,activityWindowName:i}}joinActivity(t,e,n){const i=n&&{name:n}||{};return this._gw3Session.send({type:"join-activity",target_id:e,activity_id:t,...i}).then((()=>{this.invokeCallbacks(this._activityWindowChangeCallbacks,new Le(new Ze(e,void 0,void 0,t,this.getAgmInstance(e),void 0,this.generateWindowGetter(e),void 0),new De(qe.ActivityWindowJoinedActivity)),"activity joined - ActivityWindow"),this.invokeCallbacks(this._activityChangeCallbacks,new Le(new ze(t,void 0,new Xe("created",void 0,void 0),void 0,void 0),new De(qe.Updated)),"activity joined - Activity")}))}leaveActivity(t,e){return this._gw3Session.send({type:"leave-activity",target_id:e,activity_id:t}).then((()=>{this.invokeCallbacks(this._activityWindowChangeCallbacks,new Le(new Ze(e,void 0,void 0,null,this.getAgmInstance(e),void 0,this.generateWindowGetter(e),void 0),new De(qe.ActivityWindowLeftActivity)),"activity left - ActivityWindow"),this.invokeCallbacks(this._activityChangeCallbacks,new Le(new ze(t,void 0,new Xe("created",void 0,void 0),void 0,void 0),new De(qe.Updated)),"activity left - Activity")}))}getActivityTypes(){return Promise.resolve([])}getWindowTypes(){return Promise.resolve([])}getActivities(){return Promise.resolve([])}getActivityWindows(){return Promise.resolve([])}createStackedWindows(t,e,n){}getWindowBounds(t){}setWindowBounds(t,e){}activateWindow(t,e){}setWindowVisibility(t,e){}cloneActivity(t,e){}attachActivities(t,e,n){return this._gw3Session.send({type:"merge",into:e,merge:t})}detachActivities(t,e){return this._gw3Session.send({type:"split",from:t}).then((()=>""))}onActivitiesAttached(t){}onActivitiesDetached(t){}onActivityAttachedDescriptorsRefreshed(t){}getAttachedDescriptors(){return Promise.resolve([])}getRandomRequestId(){return this._connection.peerId+":"+Math.floor(1e9*Math.random())}forwardAddedAndRemovedMessagesToEventHandler(t,e,n,i){const o=t=>e=>new Le(e,new De(t?qe.Added:qe.Removed));return[t&&this.forwardMessageToEventHandler(t,(t=>n(t,!0)),o(!0),i),e&&this.forwardMessageToEventHandler(e,(t=>n(t,!1)),o(!1),i)].filter((t=>t))}forwardMessageToEventHandler(t,e,n,i){return this.subscribe(t,(t=>{e(t).forEach((e=>i.forEach((i=>i(n(e,t))))))}))}sendCreateAndMapResultingMessagesToPromise(t,e,n,i,o,r,s,a,c){const d=this.getRandomRequestId();let u,h;const l=new Promise(((t,e)=>{u=t,h=e}));let p,g,f,y,m=null;const v=()=>{this.dropSubscription(p),c||this.dropSubscription(g),this.dropSubscription(f),this.dropSubscription(y)};p=e&&this.subscribe(e,(t=>{n(t,d)&&(m=t,this.dropSubscription(p))}));let w=!1;g=this.subscribe(i,(t=>{o(t,d,m)&&(w?c&&c(a(t)):(w=!0,u(a(t))))})),f=r&&this.subscribe(r,(t=>{s(t,d,m)&&h(t)})),y=r&&this.subscribe(Ye,(t=>{t.request_id===d&&h(t)})),t.request_id=d;const b=this._gw3Session.send(t).then((()=>l));return b.then(v,v),b}peerFactoryIdAndOwnerIdToWindowType(t,e){const n=this._peerIdAndFactoryIdToPeerType[e+":"+t];return n?new Fe(n,void 0):null}subscribe(t,e){const n=this._connection.on(t,(t=>e.bind(this)(t)));return this._gw3Subscriptions.push(n),n}dropSubscription(t){t&&(this._connection.off(t),delete this._gw3Subscriptions[this._gw3Subscriptions.indexOf(t)])}invokeCallbacks(t,e,n){t.forEach((t=>{try{t(e)}catch(t){this._logger.error(`Error in ${n||e.context.type} callback: `+JSON.stringify(t))}}))}handleActivityCreatedMessage(t){t.context_id?this._contextSubscriptions[t.activity_id]||this.subscribeToContext(t):this._logger.error("Activity created with unknown context_id: "+t.activity_id)}async subscribeToContext(t){const e=t.activity_id;this._contextSubscriptions[e]=await this._contexts.subscribe(e,((t,n,i)=>{const o=new Le(new ze(e,void 0,void 0,t,void 0),new Be(t,n,i));this.invokeCallbacks(this._activityChangeCallbacks,o,"context updated")}))}handleActivityDestroyedMessage(t){const e=this._contextSubscriptions[t.activity_id];"function"==typeof e&&e(),delete this._contextSubscriptions[t.activity_id]}handlePeerFactoriesAdded(t){t.factories.forEach((e=>{this._peerIdAndFactoryIdToPeerType[t.owner_id+":"+e.id]=e.peer_type}))}handlePeerFactoriesRemoved(t){t.factory_ids.forEach((e=>{delete this._peerIdAndFactoryIdToPeerType[t.owner_id+":"+e]}))}forwardActivityTypeMessagesToStatusEventHandlers(){this.forwardAddedAndRemovedMessagesToEventHandler("types-added","types-removed",((t,e)=>e?t.types.map((t=>pn.activityTypeGwMessageEntityToActivityType(t,void 0))):t.types.map((t=>new We(t.name,void 0,void 0,void 0)))),this._activityTypeStatusChangeCallbacks)}forwardActivityCreatedAndJoinedActivityToActivityWindowEventHandlers(){for(const t of[en,rn,cn])this.forwardMessageToEventHandler(t,(t=>[t.owner||{...t,type:t.peer_type,name:t.peer_name,peer_id:t.owner_id}].concat(t.participants||[]).map((e=>new Ze(e.peer_id,e.name,e.type,t.activity_id,this.getAgmInstance(e.peer_id),void 0,this.generateWindowGetter(e.peer_id),void 0)))),((t,e)=>new Le(t,new De(qe.ActivityWindowJoinedActivity))),this._activityWindowChangeCallbacks)}forwardActivityMessagesToStatusEventHandlers(){for(const t of[en,rn])this.forwardMessageToEventHandler(t,(t=>[pn.activityGwMessageToActivity(t,new Xe("started","",new Date))]),((t,e)=>pn.activityToActivityStatusChangeEvent(t)),this._activityChangeCallbacks);this.forwardMessageToEventHandler(nn,(t=>[pn.activityGwMessageToActivity(t,new Xe("destroyed",t.reason,new Date))]),((t,e)=>pn.activityToActivityStatusChangeEvent(t)),this._activityChangeCallbacks),this.forwardMessageToEventHandler(on,(t=>[pn.activityGwMessageToActivity(t,new Xe("created","",new Date))]),((t,e)=>pn.activityToActivityStatusChangeEvent(t)),this._activityChangeCallbacks),this.forwardMessageToEventHandler(cn,(t=>[pn.activityGwMessageToActivity(t,new Xe("created","",new Date))]),((t,e)=>pn.activityToActivityStatusChangeEvent(t)),this._activityChangeCallbacks)}forwardPeerFactoryMessagesToStatusEventHandlers(){this.forwardAddedAndRemovedMessagesToEventHandler(un,hn,((t,e)=>e?t.factories.map(pn.peerFactoryGwMessageEntityToWindowType):t.factory_ids.map((e=>this.peerFactoryIdAndOwnerIdToWindowType(e,t.owner_id))).filter((t=>null!=t))),this._windowTypeStatusChangeCallbacks)}forwardPeerFactoryMessagesToPeerFactoryRequests(){this.subscribe("peer-requested",(t=>{const e=this._peerFactoriesRegisteredByUs[t.peer_factory];if(e)try{const n=t.configuration||{};n.gateway_token=n.gateway_token||t.gateway_token,n.peer_factory=n.peer_factory||t.peer_factory;const i=e({activityId:t.activity&&t.activity.id,activityType:t.activity&&t.activity.type,type:t.configuration&&t.configuration.type,gwToken:n.gateway_token,configuration:n});i&&i.then&&i.catch&&i.catch((e=>this._gw3Session.send({type:Ye,request_id:t.request_id,reason:e&&(e.message||JSON.stringify(e))})))}catch(e){this._gw3Session.send({type:Ye,request_id:t.request_id,reason:e&&(e.message||JSON.stringify(e))})}else this._gw3Session.send({type:Ye,request_id:t.request_id,reason:`Unknown peer factory ${t.peer_factory}`})}))}forwardActivityWindowMessagesToEventHandlers(){for(const t of[sn,rn])this.subscribe(t,(e=>{const n=t===sn?e.joined_id:e.peer_id,i=t===sn?e.joined_type:e.peer_type,o=t===sn?e.joined_name:e.peer_name,r=new Ze(n,o,i,e.activity_id,this.getAgmInstance(n),void 0,this.generateWindowGetter(n),void 0);this._contextSubscriptions[e.activity_id]?t===rn&&this._activityJoinedPromiseResolve({}):this.subscribeToContext(e).then((()=>{t===rn&&this._activityJoinedPromiseResolve({})})),this.invokeCallbacks(this._activityWindowChangeCallbacks,new Le(r,new De(qe.ActivityWindowJoinedActivity)),t)}));this.subscribe(an,(t=>{const e=new Ze(t.left_id,void 0,void 0,null,this.getAgmInstance(t.left_id),void 0,this.generateWindowGetter(t.left_id),void 0);this.invokeCallbacks(this._activityWindowChangeCallbacks,new Le(e,new De(qe.ActivityWindowLeftActivity)),an)})),this.forwardAddedAndRemovedMessagesToEventHandler(ln,void 0,(t=>[new Ze(t.created_id,void 0,void 0,void 0,void 0,void 0,this.generateWindowGetter(t.created_id),void 0)]),this._activityWindowChangeCallbacks)}getAgmInstance(t){return this._config.agm.servers().find((e=>e.peerId===t||e.windowId===t))}generateWindowGetter(t){return()=>{const e=this.getAgmInstance(t);if(!e)return;const n=e.windowId;return this._config.windows.list().filter((t=>t.id===n))[0]}}isOverrideTypeDefinition(t){return void 0!==t&&!!t.owner}}class gn{constructor(t,e){this._myAttached=[],this._myDetached=[],this._myAttachedTo=[],this._myDetachedFrom=[],this._myActivityFrameColorChanged=[],this._myActivityJoinedCallbacks=[],this._myActivityRemovedCallbacks=[],this._myContextUpdateCallbacks=[],this._logger=Qe.Get(this),this._m=t,t.ready().then((t=>{t.subscribeActivityContextChanged(this._subscribeMyContextChanged.bind(this)),t.subscribeWindowEvents(this._subscribeMyWindowEvent.bind(this)),t.subscribeActivitiesAttached(this._subscribeActivitiesAttached.bind(this)),t.subscribeActivitiesDetached(this._subscribeActivitiesDetached.bind(this)),e&&e.onWindowFrameColorChanged(this._subscribeWindowFrameColorChanged.bind(this))}))}get window(){if(Me(this._w)){const t=this._m.announcedWindows;t.length>0&&(this._w=t[0])}return this._w}get activity(){const t=this.window;if(!Me(t))return t.activity}createWindow(t){return this._m.createWindow(this.activity,t)}createStackedWindows(t,e){return this._m.createStackedWindows(this.activity,t,e)}get context(){const t=this.activity;return Pe(t)?{}:t.context}updateContext(t,e){const n=this.activity;return Pe(n)?new Promise(((t,e)=>{e("Not in activity")})):n.updateContext(t,e)}setContext(t,e){const n=this.activity;return Pe(n)?new Promise(((t,e)=>{e("Not in activity")})):n.setContext(t,e)}onActivityJoined(t){this._myActivityJoinedCallbacks.push(t);const e=this.window;Me(e)||Me(e.activity)||t(e.activity)}onActivityLeft(t){this._myActivityRemovedCallbacks.push(t)}onContextChanged(t){this._myContextUpdateCallbacks.push(t);const e=this.window;if(Me(e))return;const n=e.activity;Me(n)||t(n.context,n.context,[],n)}clone(t,e){const n=this.activity;return this._m.clone(n,t,e)}attach(t,e){let n;return n="string"==typeof t?t:t.id,this._m.attachActivities(n,this.activity.id,e)}onActivityAttached(t){this._myAttached.push(t)}onActivityDetached(t){this._myDetached.push(t)}onAttachedToActivity(t){this._myAttachedTo.push(t)}onDetachedFromActivity(t){this._myDetachedFrom.push(t)}get attached(){return this.activity?this.activity.attached:[]}setFrameColor(t,e){return this.activity?this.activity.setFrameColor(t,e):Promise.resolve(null)}getFrameColor(){return this.activity?this.activity.getFrameColor():""}onFrameColorChanged(t){this._myActivityFrameColorChanged.push(t)}_subscribeMyContextChanged(t,e,n,i){const o=this.window;if(Me(o))return;const r=o.activity;Me(r)||t.id===r.id&&this._notifyMyContextChanged(t,e,n,i)}_subscribeMyWindowEvent(t,e,n){Me(this.window)||this.window.id===e.id&&(n===qe.ActivityWindowJoinedActivity?(this._notifyMyWindowEvent(t,this._myActivityJoinedCallbacks),this._notifyMyContextChanged(t,t.context,null,null)):n===qe.ActivityWindowLeftActivity&&this._notifyMyWindowEvent(t,this._myActivityRemovedCallbacks))}_notifyMyWindowEvent(t,e){e.forEach((e=>{try{e(t,event)}catch(t){this._logger.warn("error in user callback "+t)}}))}_notifyMyContextChanged(t,e,n,i){n=n||{},i=i||[],this._myContextUpdateCallbacks.forEach((o=>{try{o(e,n,i,t)}catch(t){this._logger.warn("error in user callback "+t)}}))}_notifyAttached(t){this._myAttached.forEach((e=>{try{e(t)}catch(t){this._logger.warn("error in user callback "+t)}}))}_notifyDetached(t){this._myDetached.forEach((e=>{try{e(t)}catch(t){this._logger.warn("error in user callback "+t)}}))}_notifyAttachedTo(t){this._myAttachedTo.forEach((e=>{try{e(this.activity,t)}catch(t){this._logger.warn("error in user callback "+t)}}))}_notifyDetachedFrom(t,e,n){this._myDetachedFrom.forEach((i=>{try{i(t,e,n)}catch(t){this._logger.warn("error in user callback "+t)}}))}_subscribeActivitiesAttached(t,e){const n=this.window;if(Me(n))return;const i=n.activity;Me(i)||t.id===i.id&&(e.windowIds.indexOf(n.id)>=0?this._notifyAttachedTo(e):this._notifyAttached(e))}_subscribeActivitiesDetached(t,e,n){const i=this.window;if(Me(i))return;const o=i.activity;Me(o)||(e.id===o.id&&this._notifyDetached(n),t.id===o.id&&this._notifyDetachedFrom(t,e,n))}_subscribeWindowFrameColorChanged(t){const e=this.activity;e&&e.owner&&e.owner.underlyingWindow.id===t.id&&this._myActivityFrameColorChanged.forEach((e=>{e(t.frameColor)}))}}class fn{constructor(t,e){if(this._logger=Qe.Get("ReadyMarker ["+t+"]"),this._logger.debug("Initializing ready marker for '"+t+"' with "+e+" signals to wait"),e<=0)throw new Error("Invalid signal number. Should be > 0");this._signals=e,this._callbacks=[],this._name=t}setCallback(t){this.isSet()?t(void 0):this.isError()?t(this._error):this._callbacks.push(t)}signal(t){if(this._logger.debug("Signaled - "+t+" - 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((t=>{t(void 0)}))}error(t){this._error=t,this._callbacks.forEach((e=>{e(t)}))}isSet(){return!this.isError()&&0===this._signals}isError(){return!Pe(this._error)}getError(){return this._error}}class yn{constructor(t){this._items={},this._listeners=[],this._processNew=t}addOne(t){this.add([t])}add(t){t.forEach((t=>{this.process(new Le(t,new De(qe.Added)))}))}process(t){const e=t.context,n=e.type,i=t.entity;if(n===qe.StatusChange&&!e.oldStatus){const t=this._items[i.id];t&&(e.oldStatus=t.status)}n===qe.StatusChange&&e.oldStatus&&e.newStatus&&e.oldStatus.state===e.newStatus.state&&(e.type=qe.Updated),"undefined"==typeof htmlContainer&&(n===qe.ActivityWindowJoinedActivity&&this._items[i.id]&&this._items[i.id].activity&&(e.type=qe.Updated),n===qe.ActivityWindowLeftActivity&&this._items[i.id]&&!this._items[i.id].activity&&(e.type=qe.Updated));const o=this._updateInternalCollections(i,n,e);return this._notifyListeners(o,e),o}get(){const t=[];for(const e in this._items)if(this._items.hasOwnProperty(e)){const n=this._items[e];t.push(n)}return t}getByName(t){for(const e in this._items)if(e===t)return this._items[e]}getOrWait(t){return new Promise((e=>{const n=i=>{i.id===t&&(e(i),this.unsubscribe(n))};this.subscribe(n);const i=this.getByName(t);if(i)return this.unsubscribe(n),void e(i)}))}subscribe(t){return this._listeners.push(t),Object.keys(this._items).forEach((e=>{const n=this._items[e];t(n,new De(qe.Added.toString()))})),()=>{this.unsubscribe(t)}}unsubscribe(t){const e=this._listeners.indexOf(t);-1!==e&&this._listeners.splice(e,1)}_notifyListeners(t,e){this._listeners.forEach((n=>{try{n(t,e)}catch(t){return}}))}_updateInternalCollections(t,e,n){const i=t,o=e===qe.StatusChange&&i.status&&i.status.state===Ue.Destroyed||e===qe.StatusChange&&n&&n.newStatus&&n.newStatus.state===Ue.Destroyed,r=e===qe.Closed;if(e===qe.Removed&&void 0===i.isIndependent||r||o){const e=this._items[t.id];return delete this._items[t.id],this._processNew(t),e&&t._beforeDelete(e),t}{const e=t.id;this._items.hasOwnProperty(e)?this._items[t.id]._update(t):(this._processNew(t),this._items[t.id]=t)}return this._items[t.id]}}class mn{get usingHc(){return"HC"===this._bridge.bridgeType}get announcedWindows(){return this._announcedWindows}set announcedWindows(t){throw new Error("not allowed")}constructor(t,e,n){this._logger=Qe.Get("activityManager"),this._announcedWindows=[],this._attachedCallbacks=[],this._detachedCallbacks=[],this._frameColorChangesCallbacks=[],this._windowHandlers=[],this._bridge=t,this._activityTypes=new yn((t=>this._grabEntity(t))),this._windowTypes=new yn((t=>this._grabEntity(t))),this._activities=new yn((t=>this._grabEntity(t))),this._windows=new yn((t=>this._grabEntity(t))),this._dataReadyMarker=new fn("Activity Manager Data",4),this._descriptorsMarker=new fn("Attached Activities Descriptors",1),e?(this._readyMarker=new fn("Activity Manager Announce",1),this._dataReadyMarker.setCallback((t=>{t&&this._readyMarker.error(t),this._descriptorsMarker.setCallback((t=>{t&&this._readyMarker.error(t),this._logger.debug("Auto announcing window"),this.announceWindow().then((t=>{this._announcedWindows.push(t),this._readyMarker.signal("Successfully announced window with id '"+t.id+"'")})).catch((t=>{this._logger.debug("Will not announce window - "+t),this._readyMarker.signal()}))})),this.refreshDescriptors()}))):this._readyMarker=this._dataReadyMarker,this._bridge.onActivitiesAttached((t=>{this._handleActivitiesAttached(t)})),this._bridge.onActivitiesDetached((t=>{this._handleActivitiesDetached(t)})),this._bridge.onActivityAttachedDescriptorsRefreshed((t=>{this._handleActivityDescriptorsRefreshed(t)})),n&&n.onWindowFrameColorChanged(this._handleWindowFrameColorChanged.bind(this)),this._bridge.init(),this._subscribeForData(),this._bridge.initReady().then((t=>{this._getInitialData()})).catch((t=>{console.log(t)}))}ready(t){const e=new Promise(((t,e)=>{this._readyMarker.setCallback((n=>{n?e(this._readyMarker.getError()):t(this)}))}));return Ve(Promise.all([this._bridge.ready(),e]).then((()=>this)),t)}getActivityTypes(){return this._activityTypes.get()}getActivityType(t){return this._activityTypes.getByName(t)}registerActivityType(t,e,n,i,o,r){return Ve(new Promise(((r,s)=>{if(Me(t))return void s("activityTypeName argument can not be undefined");if(!ke(t))return void s("activityTypeName should be string");if(!Me(this.getActivityType(t)))return void s("Activity type '"+t+"' already exists");let a;if(Pe(e))return void s("Owner window type can not be undefined");a=ke(e)?{type:e,name:"",isIndependent:!1,arguments:{}}:e;const c=[];if(!Pe(n)&&Ee(n))for(const t in n){const e=n[t];if(ke(e)){const t={type:e,name:"",isIndependent:!1,arguments:{},relativeTo:"",relativeDirection:"",windowStyleAttributes:{}};c.push(t)}else c.push(e)}this._bridge.registerActivityType(t,a,c,i,o).then((t=>{this._grabEntity(t),r(t)})).catch((t=>{s(t)}))})),r)}unregisterActivityType(t,e){return Ve(new Promise(((e,n)=>{const i=this.getActivityType(t);Pe(i)?n("Activity type '"+t+"' does not exists"):this._bridge.unregisterActivityType(t).then((()=>e(i)),n)})),e)}initiate(t,e,n,i){return Ve(new Promise(((n,o)=>{Pe(this.getActivityType(t))?o("Activity type '"+t+"' does not exists"):this._bridge.initiateActivity(t,e,i).then((t=>{this._activities.getOrWait(t).then((t=>{n(t)})).catch((t=>o(t)))})).catch((t=>{o(t)}))})),n)}subscribeActivityTypeEvents(t){this._activityTypes.subscribe(((e,n)=>{t(e,n.type)}))}getWindowTypes(){return this._windowTypes.get()}getWindowType(t){return this._windowTypes.getByName(t)}registerWindowFactory(t,e,n){return Ve(new Promise(((n,i)=>{if(Me(t))i("no windowType specified");else{if(Te(t))t=t.getName();else if(!ke(t))return void i("windowType should be string or object that has getName method");this._bridge.registerWindowFactory(t,e).then((t=>{n(t)})).catch((t=>{i(t)}))}})),n)}unregisterWindowFactory(t,e){return Ve(new Promise(((e,n)=>{Me(t)?n("no windowType specified"):ke(t)?this._bridge.unregisterWindowFactory(t).then((t=>{e(t)})).catch((t=>{n(t)})):n("windowType should be a string")})),e)}getActivities(t){let e=this._activities.get();if(e=e.filter((t=>t._ownerId)),!t)return e;let n=t;if(ke(t))n=[t];else if(t instanceof We)n=[t.name];else if(!(t instanceof Array))throw new Error("Invalid input argument 'activityType' = "+t);return e.filter((t=>{const e=t.type;return function(t,e){for(let n=0;n<t.length;n++)if(e(t[n],n))return!0;return!1}(n,(t=>e.id===t.id))}))}getActivityById(t){return this._activities.getByName(t)}announceWindow(t,e){return new Promise(((n,i)=>{const o=this._bridge.getAnnouncementInfo();if(Pe(t)&&(t=o.activityWindowId),Pe(e)&&(e=o.activityWindowType),Me(e))throw new Error("Can not announce - unknown windowType");const r=o&&o.activityId;if(Me(t))this._logger.debug("Registering window with type:'"+e+"', name:'"+o.activityWindowName+"', ind.:'"+o.activityWindowIndependent+"'"),this._bridge.registerWindow(e,o.activityWindowName,o.activityWindowIndependent).then(this._windows.getOrWait.bind(this._windows)).then((t=>r?this._activities.getOrWait(r).then((e=>t)):t)).then((t=>{n(t)})).catch((t=>{this._logger.error(t)}));else{this._logger.debug("Announcing window with id '"+t+"' and type '"+e+"'");const o=this._windows.getByName(t);if(!Me(o))return this._logger.debug("Window with id '"+t+"' already announced - reusing the window"),void n(o);const r=(e,o,s)=>{if(t===o.id&&s===qe.ActivityWindowJoinedActivity){Pe(o.activity)&&i("UNDEFINED ACTIVITY"),this._logger.trace("Got joined event for id '"+t+"'"),n(o),this.unsubscribeWindowEvents(r)}};this.subscribeWindowEvents(r),this._logger.trace("Waiting for joined event for id '"+t+"'"),this._bridge.announceWindow(e,t)}}))}subscribeWindowTypeEvents(t){this._windowTypes.subscribe(((e,n)=>{t(e,n.type)}))}subscribeActivityEvents(t){return this._activities.subscribe(((e,n)=>{if(n.type===qe.StatusChange){const i=n;t(e,i.newStatus,i.oldStatus)}if(n.type===qe.Removed||n.type===qe.StatusChange&&n.newStatus.getState()===Ue.Destroyed)for(const t of this._windows.get())t.activity&&t.activity.id===e.id&&this._windows.process(new Le(t,new De(qe.ActivityWindowLeftActivity)))}))}subscribeWindowEvents(t){const e=(e,n)=>{let i=n.type;i===qe.Added&&(i="opened"),t(e.activity,e,i)};return this._windowHandlers.push([t,e]),this._windows.subscribe(e)}unsubscribeWindowEvents(t){const e=this._windowHandlers.find((e=>e[0]===t));e&&(this._windowHandlers.splice(this._windowHandlers.indexOf(e),1),this._windows.unsubscribe(e[1]))}createWindow(t,e,n){return Ve(new Promise(((n,i)=>{let o,r;if(Me(e)&&i("windowType is undefined"),ke(e))o={type:e,name:"",isIndependent:!1,arguments:{}};else if(e instanceof Fe)o={type:e.type||e.id,name:e.name||e.type||e.id,isIndependent:!1};else{const t=["url"],n={};Object.keys(e).forEach((i=>{-1===t.indexOf(i)&&(n[i]=e[i])})),o=n}if(!Me(o.relativeTo))if(r=o.relativeTo,"string"==typeof r){const t=this.getWindows({type:r});!Me(t)&&t.length>0&&(o.relativeTo=t[0].id)}else if(Me(r.type))Me(r.windowId)||(o.relativeTo=r.windowId);else{const t=this.getWindows({type:r.type});!Me(t)&&t.length>0&&(o.relativeTo=t[0].id)}this._bridge.createWindow(t&&t.id,o).then((e=>{this._logger.debug("Window created, waiting for window entity with id "+e);const i=(o,r)=>{o.id!==e||t&&!o.activity||(this._logger.debug("Got entity window with id "+e),n(o),this._windows.unsubscribe(i))};this._windows.subscribe(i)})).catch((t=>{i(t)}))})),n)}createStackedWindows(t,e,n,i){return Ve(new Promise(((i,o)=>{Me(t)&&o("activity is undefined"),Me(e)&&o("relativeWindowTypes is undefined"),Array.isArray(e)||o("relativeWindowTypes has to be an array"),Me(n)&&(n=2e4);const r=[];e.forEach((t=>{let e,i;if(e=ke(t)?{type:t,name:"",isIndependent:!1,arguments:{}}:t,e.stackedWindow=!0,e.timeout=n,!Me(e.relativeTo))if(i=e.relativeTo,Me(i.type)){if(!Me(i.windowId)){const t=this.getWindows({id:i.windowId});!Me(t)&&t.length>0&&(e.relativeTo=t[0].type.name)}}else e.relativeTo=i.type;r.push(e)}));const s=[];r.forEach((e=>s.push(this.createWindow(t,e)))),Promise.all(s).then(i).catch(o)})),i)}addWindowToActivity(t,e,n){const i=this._bridge.joinActivity(t.id,e.id).then((()=>e));return Ve(i,n),i}leaveWindowFromActivity(t,e,n){const i=this._bridge.leaveActivity(t.id,e.id).then((()=>e));return Ve(i,n),i}setActivityContext(t,e,n){return Ve(new Promise(((n,i)=>{Me(t)&&i("activity can not be null"),this._bridge.updateActivityContext(t,e,!0).then((e=>{n(t)})).catch((t=>{i(t)}))})),n)}updateActivityContext(t,e,n){return Ve(new Promise(((n,i)=>{Me(t)&&i("activity can not be null");const o=[];for(const t in e)e.hasOwnProperty(t)&&null===e[t]&&o.push(t);for(const t of o)delete e[t];this._bridge.updateActivityContext(t,e,!1,o).then((e=>{n(t)})).catch((t=>{i(t)}))})),n)}subscribeActivityContextChanged(t){this._activities.subscribe(((e,n)=>{if(n.type===qe.ActivityContextChange){const i=n;t(e,i.context,i.updated,i.removed)}}))}stopActivity(t,e){return Ve(this._bridge.stopActivity(t),e)}getWindows(t){if(Pe(t))return this._windows.get();if(!Pe(t.id))return[this._windows.getByName(t.id)];return this._windows.get().filter((e=>{if(!Pe(t.type)&&e.type.id!==t.type)return!1;if(!Pe(t.name)&&e.name!==t.name)return!1;if(!Pe(t.activityId)){if(Me(e.activity))return!1;if(e.activity.id!==t.activityId)return!1}return!0}))}getWindowBounds(t){return this._bridge.getWindowBounds(t)}setWindowBounds(t,e,n){return Ve(new Promise(((n,i)=>{this._bridge.setWindowBounds(t,e).then((()=>n())).catch((t=>i(t)))})),n)}closeWindow(t){return this._bridge.closeWindow(t)}activateWindow(t,e){return this._bridge.activateWindow(t,e)}setWindowVisibility(t,e){return this._bridge.setWindowVisibility(t,e)}clone(t,e,n){return Ve(new Promise(((n,i)=>{t||i("activity can not be null"),this._bridge.cloneActivity(t.id,e).then((t=>{this._activities.getOrWait(t).then((t=>{n(t)})).catch((t=>i(t)))})).catch((t=>i(t)))})),n)}attachActivities(t,e,n,i){n=n||{};return Ve(new Promise(((i,o)=>{if(!this._activities.getByName(t))return void o("can not find activity with id "+t);if(this._activities.getByName(e))return this._bridge.attachActivities(t,e,n).then((t=>{const e=t.to,n=t.descriptor,o=t.descriptors;this._activities.getOrWait(e).then((t=>{t._updateDescriptors(o);const e=t.attached.filter((t=>t.ownerId===n.ownerId))[0];i(e)}))})).catch((t=>{o(t)}));o("can not find activity with id "+e)})),i)}detachActivities(t,e,n){return Ve(new Promise(((n,i)=>this._bridge.detachActivities(t,e).then((()=>{this._activities.getOrWait(undefined).then((t=>{t._updateDescriptors(undefined),this._activities.getOrWait(undefined).then((t=>{n(t)}))})).catch((t=>i(t)))})).catch((t=>{i(t)})))),n)}subscribeActivitiesAttached(t){this._attachedCallbacks.push(t)}subscribeActivitiesDetached(t){this._detachedCallbacks.push(t)}subscribeActivityFrameColorChanged(t){this._frameColorChangesCallbacks.push(t)}_grabEntity(t){t._manager=this}_getInitialData(){this._logger.debug("Request initial data..."),this._bridge.getActivityTypes().then((t=>{this._activityTypes.add(t),this._dataReadyMarker.signal("Got act types")})).catch((t=>{this._logger.error(t),this._dataReadyMarker.error("Can not initialize ActivityManager - error getting activity types -"+t)})),this._bridge.getWindowTypes().then((t=>{this._windowTypes.add(t),this._dataReadyMarker.signal("Got window types")})).catch((t=>{this._logger.error(t),this._dataReadyMarker.error("Can not initialize ActivityManager - error getting window types "+t)})),this._bridge.getActivities().then((t=>{this._activities.add(t),this._dataReadyMarker.signal("Got activities")})).catch((t=>{this._logger.error(t),this._dataReadyMarker.error("Can not initialize ActivityManager - error getting activity instances -"+t)})),this._bridge.getActivityWindows().then((t=>{this._windows.add(t),this._dataReadyMarker.signal("Got windows")})).catch((t=>{this._logger.error(t),this._dataReadyMarker.error("Can not initialize ActivityManager - error getting activity windows -"+t)}))}_subscribeForData(){this._logger.debug("Subscribe for data..."),this._bridge.onActivityTypeStatusChange((t=>{this._activityTypes.process(t)})),this._bridge.onWindowTypeStatusChange((t=>{this._windowTypes.process(t)})),this._bridge.onActivityWindowChange((t=>{this._windows.process(t)})),this._bridge.onActivityStatusChange((t=>{this._activities.process(t)}))}_handleActivitiesAttached(t){const e=t.to,n=t.descriptor,i=t.descriptors;this._activities.getOrWait(e).then((t=>{t._updateDescriptors(i);const e=t.attached.filter((t=>t.ownerId===n.ownerId))[0];this._attachedCallbacks.forEach((n=>{try{n(t,e)}catch(t){return}}))}))}_handleActivitiesDetached(t){const e=t.oldActivityId,n=t.newActivityId,i=t.descriptors,o=t.descriptor;this._activities.getOrWait(e).then((t=>{t._updateDescriptors(i),this._activities.getOrWait(n).then((e=>{this._detachedCallbacks.forEach((n=>{try{n(e,t,o)}catch(t){return}}))}))}))}_handleActivityDescriptorsRefreshed(t){const e=t.id,n=t.descriptors,i=this._activities.getByName(e);i&&i._updateDescriptors(n)}refreshDescriptors(){this._bridge.getAttachedDescriptors().then((t=>{t&&Object.keys(t).forEach((e=>{const n=e,i=t[e],o=this._activities.getByName(n);o&&o._updateDescriptors(i)})),this._descriptorsMarker.signal("Successfully got descriptors")})).catch((t=>{this._descriptorsMarker.error("failed to get descriptors - "+t)}))}_handleWindowFrameColorChanged(t){if(!t.activityId)return;const e=this._activities.getByName(t.activityId);e&&e.owner&&e.owner.underlyingWindow.id===t.id&&this._frameColorChangesCallbacks.forEach((n=>{try{n(e,t.frameColor)}catch(t){return}}))}}class vn{constructor(t,e){this._m=t,this._my=e,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(t){this._m.subscribeActivitiesAttached(t)}onDetached(t){this._m.subscribeActivitiesDetached(t)}onActivityFrameColorChanged(t){this._m.subscribeActivityFrameColorChanged(t)}_getActivityTypesWrapper(t){return Pe(t)?this._m.getActivityTypes():this._m.getActivityType(t)}_getWindowTypesWrapper(t){return Pe(t)?this._m.getWindowTypes():this._m.getWindowType(t)}}class wn{constructor(t,e){this._mgr=t,this._my=e,this.all=new vn(t,e)}ready(t){return Ve(new Promise(((t,e)=>{this._mgr.ready().then((()=>{t(this)})).catch((t=>{e(t)}))})),t)}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 He(null)}getAvailableFrameColors(){return[]}}class bn{static checkIsUsingGW3Implementation(t){return 3===t.protocolVersion}get api(){return this._api}set api(t){this._api=t}constructor(t){if(!t)throw new Error("config can not be null");let e;if(Pe(t.logLevel)||(Qe.Level=t.logLevel),Me(t.logger)||(Qe.GlueLogger=t.logger),this._isUsingHCImplementation=2===t.gdMajorVersion,this._isUsingGW3Implementation=bn.checkIsUsingGW3Implementation(t.connection),this._isUsingHCImplementation)throw new Error("GD2 not supported");if(!this._isUsingGW3Implementation)throw new Error("Unable to instantiate activity bridge implementation");if(e=new pn(t),!e)throw new Error("A bridge to native activity is needed to create activity lib.");He.AGM=t.agm;const n=new mn(e,!t.disableAutoAnnounce,t.windows),i=new gn(n,t.windows);this._api=new wn(n,i),this._readyPromise=n.ready().then((t=>this))}get isUsingHCImplementation(){return this._isUsingHCImplementation}get isUsingGW3Implementation(){return this._isUsingGW3Implementation}ready(t){return Ve(this._readyPromise,t)}}const _n="T42.ACS.GetFunctionalEntitlement",In="T42.ACS.CanI",Cn="T42.ACS.OnEvent",An="T42.ACS.GetApplications";function Sn(t){if(t&&t.errorHandling&&"function"!=typeof t.errorHandling&&"log"!==t.errorHandling&&"silent"!==t.errorHandling&&"throw"!==t.errorHandling)throw new Error('Invalid options passed to createRegistry. Prop errorHandling should be ["log" | "silent" | "throw" | (err) => void], but '+typeof t.errorHandling+" was passed");var e=t&&"function"==typeof t.errorHandling&&t.errorHandling,n={};function i(n,i){var o=n instanceof Error?n:new Error(n);if(e)e(o);else{var r='[ERROR] callback-registry: User callback for key "'+i+'" failed: '+o.stack;if(t)switch(t.errorHandling){case"log":return console.error(r);case"silent":return;case"throw":throw new Error(r)}console.error(r)}}return{add:function(t,e,o){var r=n[t];return r||(r=[],n[t]=r),r.push(e),o&&setTimeout((function(){o.forEach((function(o){var r;if(null===(r=n[t])||void 0===r?void 0:r.includes(e))try{Array.isArray(o)?e.apply(void 0,o):e.apply(void 0,[o])}catch(e){i(e,t)}}))}),0),function(){var i=n[t];i&&(0===(i=i.reduce((function(t,n,i){return n===e&&t.length===i||t.push(n),t}),[])).length?delete n[t]:n[t]=i)}},execute:function(t){for(var e=[],o=1;o<arguments.length;o++)e[o-1]=arguments[o];var r=n[t];if(!r||0===r.length)return[];var s=[];return r.forEach((function(n){try{var o=n.apply(void 0,e);s.push(o)}catch(e){s.push(void 0),i(e,t)}})),s},clear:function(){n={}},clearKey:function(t){n[t]&&delete n[t]}}}Sn.default=Sn;var xn=Sn;function kn(t){return t?Object.keys(t).map((e=>t[e])):[]}function Tn(t){let e;try{e=JSON.parse(JSON.stringify(t||{}))}catch(t){e={}}return e}function En(t,e){if(e.throwErrors&&"function"!=typeof t)throw new Error("Please provide the callback as a function!")}class Pn{constructor(t,e,n,i){this._appManager=t,this._name=e,this._agm=n,this._configuration=i,this._registry=xn(),t.onInstanceStarted((t=>{t.application&&t.application.name!==this._name||this._registry.execute("instanceStarted",t)})),t.onInstanceStopped((t=>{t.application&&t.application.name!==this._name||this._registry.execute("instanceStopped",t)})),t.onAppRemoved((t=>{t.name===this._name&&this._registry.execute("appRemoved",t)})),t.onAppChanged((t=>{t.name===this._name&&this._registry.execute("appChanged",t)})),t.onAppAvailable((t=>{t.name===this._name&&(this._props.IsReady=!0,this._registry.execute("appAvailable",t))})),t.onAppUnavailable((t=>{t.name===this._name&&(this._props.IsReady=!1,this._registry.execute("appUnavailable",t))}))}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?Tn(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?Tn(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((t=>t.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 t=this._props.WindowStyleAttributes;if(t){t=t.split(" ").join("");const e='mode:"',n=t.indexOf(e);if(-1!==n){const i=n+e.length,o=t.indexOf('"',i),r=t.substr(i,o-i);if(r&&"string"==typeof r)return r.toLowerCase()}}return"flat"}async getConfiguration(){return(await this._agm.invoke(An,{v2:{apps:[this._name]}})).returned.applications[0]}updateFromProps(t){this._props||(this._props={Name:t.Name}),Object.keys(t).forEach((e=>{this._props[e]=t[e]}))}start(t,e){return new Promise((async(n,i)=>{var o,r,s,a,c;const d=this._name;let u=6e4;if(Me(t))t={};else if((null===(o=this._configuration())||void 0===o?void 0:o.throwErrors)&&"object"!=typeof t||Array.isArray(t))return i(new Error('Invalid "context" parameter - must be an object.'));if(Me(e))e={};else if((null===(r=this._configuration())||void 0===r?void 0:r.throwErrors)&&"object"!=typeof e)return i(new Error('Invalid "options" parameter - must be an object.'));let h=null===(a=null!==(s=e.awaitInterop)&&void 0!==s?s:e.waitForAGMReady)||void 0===a||a;const l=t=>{let e;const o=setTimeout((()=>{e&&e(),i(`timed out while waiting for instance id ${t} for app ${this.name}`)}),u),r=i=>{i.id===t&&(e&&(e(),e=void 0),clearTimeout(o),n(i))};e=h?this._appManager.onInstanceAgmServerReady(r):this._appManager.onInstanceStarted(r)};try{const i=(await this._agm.invoke("T42.ACS.StartApplication",{Name:d,Context:t,Options:e},"best",{methodResponseTimeoutMs:u})).returned;if(void 0!==i.timeout&&(u=1e3*i.timeout),void 0!==i.waitForInterop&&void 0===e.waitForAGMReady&&void 0===e.awaitInterop&&(h=i.waitForInterop),i&&i.Id)if("startOnly"===this._appManager.mode){const t=this._appManager.handleInstanceStarted({ActivityId:void 0,IsActivityOwner:void 0,Context:void 0,Title:void 0,AgmServers:void 0,Id:i.Id,Name:i.Name});n(t)}else l(i.Id);else n(void 0)}catch(t){i(null!==(c=t.message)&&void 0!==c?c:t)}}))}onInstanceStarted(t){return En(t,this._configuration()),this._registry.add("instanceStarted",t)}onInstanceStopped(t){return En(t,this._configuration()),this._registry.add("instanceStopped",t)}onAvailable(t){return En(t,this._configuration()),this._props.IsReady&&setTimeout((()=>{this._registry.execute("appAvailable",this)}),0),this._registry.add("appAvailable",t)}onUnavailable(t){return En(t,this._configuration()),!1===this._props.IsReady&&setTimeout((()=>{this._registry.execute("appUnavailable",this)}),0),this._registry.add("appUnavailable",t)}onChanged(t){En(t,this._configuration()),this._registry.add("appChanged",t)}onRemoved(t){En(t,this._configuration()),this._registry.add("appRemoved",t)}}class Mn{constructor(t,e,n,i,o,r,s,a){this._id=t,this._appName=e,this._appManager=n,this._agm=i,this._activities=o,this._windows=r,this._configuration=a,this._registry=xn(),s||(this._unsubscribeInstanceStopped=this._appManager.onInstanceStopped((t=>{t.id===this._id&&this._registry.execute("stopped",t)})),this._unsubscribeInstanceAgmServerReady=this._appManager.onInstanceAgmServerReady((t=>{t.id===this._id&&this._registry.execute("agmReady",t)})))}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((t=>t.id===this._activityId))[0]}get isActivityOwner(){return this._isActivityOwner}get activityInstances(){return this._appManager.instances().filter((t=>"activity"!==t.application.type&&t.activityId&&t.activityId===this._activityId))}get activityOwnerInstance(){if(this._activityId)return this.activityInstances.filter((t=>null==t?void 0:t.isActivityOwner))[0]}get window(){if(!this._windows)throw new Error("This method requires glue.windows library to be enabled.");let t=this._windows.list().filter((t=>t.id===this._id))[0];return!t&&this._activities&&this.activity&&this.activityOwnerInstance&&(t=this.activityOwnerInstance.window),t}get context(){var t,e,n;return null!==(n=null!==(t=this._startUpContext)&&void 0!==t?t:null===(e=this.window)||void 0===e?void 0:e.context)&&void 0!==n?n:{}}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(t){return En(t,this._configuration()),this._agmInstance&&setTimeout((()=>{this._registry.execute("agmReady",this)}),0),this._registry.add("agmReady",t)}onAgmReady(t){return this.onInteropReady(t)}onStopped(t){return En(t,this._configuration()),this._registry.add("stopped",t)}getWindow(){return new Promise(((t,e)=>{const n=this.window;if(n)return void t(n);const i=(n,i)=>{n&&e(n),i&&t(i),setTimeout((()=>{clearTimeout(o),r()}),0)},o=setTimeout((()=>{i(new Error(`can not find a window with id ${this._id}`))}),3e4),r=this._windows.onWindowAdded((t=>{t.id===this._id&&i(void 0,t)}))}))}updateFromProps(t){this._startUpContext=t.Context,this._title=t.Title,this._isActivityInstance=!1,t.ActivityId&&""!==t.ActivityId&&(this._activityId=t.ActivityId,this._isActivityInstance=!0),this._isActivityOwner=t.IsActivityOwner,!this._activityId&&this._startUpContext&&this._startUpContext.activityId&&(this._activityId=this._startUpContext.activityId),this._inActivity=Boolean(this._activityId),this.updateAgmInstanceFromProps(t)}updateAgmInstanceFromProps(t){if(!t.AgmServers)return;const e=t.AgmServers;e&&e.length>0&&!Me(e[0])&&(this._agmInstance=e[0])}stop(){return new Promise(((t,e)=>{let n=this._id;this.isActivityOwner&&(n=this.activityId);const i=this._appManager.onInstanceStopped((e=>{e.id===n&&(i(),t())}));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}),t())})).catch((t=>e(t)))}))}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)}}class Rn{constructor(t,e,n,i,o,r,s){this.mode=t,this._agm=e,this._activities=n,this._windows=i,this._logger=o,this._gdMajorVersion=r,this._configuration=s,this._apps={},this._instances=[],this._registry=xn(),this.getConfigurations=async t=>{const e={v2:{apps:void 0}};Array.isArray(t)&&(e.v2={apps:t});return(await this._agm.invoke(An,e)).returned.applications},this.application=t=>{var e;if((null===(e=this._configuration())||void 0===e?void 0:e.throwErrors)&&"string"!=typeof t)throw new Error('"name" must be string');return this._apps[t]},this.applications=()=>Object.keys(this._apps).map((t=>this._apps[t])),this.instances=()=>this._instances.map((t=>t)),this.getMyInstance=()=>{const t="undefined"!=typeof window&&window.glue42gd;if(!t){const t=this._agm.instance.instance;return this._instances.find((e=>e.id===t))}if(this._gdMajorVersion>=3){const e=t.appInstanceId;return this._instances.find((t=>t.id===e))}},this.getMyApplication=()=>{if(this._agm.instance)return this.application(this._agm.instance.application)},this.handleSnapshotAppsAdded=t=>{const e=this.applications();e.length>0&&e.forEach((e=>{const n=e.name;t.find((t=>t.Name===e.name))||this.handleAppRemoved({Name:n})})),t.forEach((t=>{e.find((e=>e.name===t.Name))||this.handleAppAdded(t)}))},this.handleSnapshotInstanceStarted=t=>{const e=this.instances();e.length>0&&e.forEach((e=>{const n=e.id;t.find((t=>t.Id===n))||this.handleInstanceStopped({Name:e.application.name,Id:n})})),t.forEach((t=>{e.find((e=>e.id===t.Id))||this.handleInstanceStarted(t)}))},this.handleAppAdded=t=>{const e=this._getAppId(t);this._logger.trace(`adding app ${e}`),this._apps[e]=new Pn(this,e,this._agm,this._configuration);const n=this._updateAppFromProps(t);this._registry.execute("appAdded",n),this._registry.execute("appAvailable",n)},this.handleAppUpdated=t=>{const e=this._updateAppFromProps(t);this._registry.execute("appChanged",e)},this.handleAppRemoved=t=>{const e=this._getAppId(t);this._logger.trace(`removing app ${e}`);const n=this.application(e);this._instances=this._instances.filter((t=>t.application.name!==n.name)),delete this._apps[e],this._registry.execute("appRemoved",n)},this.handleAppReady=t=>{const e=this._getAppId(t),n=this._getAppOrThrow(e);n.updateFromProps(t),n.available?this._registry.execute("appAvailable",n):this._registry.execute("appUnavailable",n)},this.handleInstanceStarted=t=>{this._logger.trace(`started app ${t.Name} ${t.Id}`);const e=this._getInstanceId(t),n=this._getInstanceAppName(t),i=new Mn(e,n,this,this._agm,this._activities,this._windows,!1,this._configuration);return this._updateInstanceFromProps(i,t),this._instances.push(i),this._registry.execute("instanceStarted",i),i},this.handleInstanceStopped=t=>{this._logger.trace(`failed to start app ${t.Name} ${t.Id}`);const e=this._getInstanceId(t),n=this._getInstanceAppName(t),i=this._getInstanceOrThrow(e,n);this._instances=this._instances.filter((t=>!this._matchInstance(t,e,n))),this._registry.execute("instanceStopped",i),i.done()},this.handleInstanceAgmServerReady=t=>{const e=this._getInstanceId(t),n=this._getInstanceAppName(t),i=this._getInstanceOrThrow(e,n);i.updateAgmInstanceFromProps(t),this._registry.execute("instanceAgmServerReady",i)},this.handleInstanceStartFailed=t=>{const e=this._getInstanceId(t),n=this._getInstanceAppName(t),i=new Mn(e,n,void 0,void 0,void 0,void 0,!0,this._configuration);this._updateInstanceFromProps(i,t),this._registry.execute("instanceStartFailed",i)},this.handleInstanceUpdated=t=>{const e=this._getInstanceId(t),n=this._getInstanceAppName(t),i=this._getInstanceOrThrow(e,n);this._updateInstanceFromProps(i,t)},this.onInstanceStarted=t=>(En(t,this._configuration()),this._registry.add("instanceStarted",t,this._instances)),this.onInstanceStartFailed=t=>(En(t,this._configuration()),this._registry.add("instanceStartFailed",t)),this.onInstanceStopped=t=>(En(t,this._configuration()),this._registry.add("instanceStopped",t)),this.onInstanceUpdated=t=>(En(t,this._configuration()),this._registry.add("instanceChanged",t)),this.onInstanceAgmServerReady=t=>(En(t,this._configuration()),this._registry.add("instanceAgmServerReady",t)),this.onAppAdded=t=>(En(t,this._configuration()),this._registry.add("appAdded",t,Object.values(this._apps))),this.onAppRemoved=t=>(En(t,this._configuration()),this._registry.add("appRemoved",t)),this.onAppAvailable=t=>(En(t,this._configuration()),this._registry.add("appAvailable",t)),this.onAppUnavailable=t=>(En(t,this._configuration()),this._registry.add("appUnavailable",t)),this.onAppChanged=t=>(En(t,this._configuration()),this._registry.add("appChanged",t))}_getAppOrThrow(t){const e=this.application(t);if(!e)throw Error(`app with id ${t} not found`);return e}_getAppId(t){return t.Name}_matchInstance(t,e,n){return t.id===e&&t.application.name===n}_getInstanceByIdAndName(t,e){return this._instances.filter((n=>this._matchInstance(n,t,e)))[0]}_getInstanceOrThrow(t,e){const n=this._getInstanceByIdAndName(t,e);if(!n)throw Error(`instance with id ${t} not found`);return n}_getInstanceId(t){return t.Id}_getInstanceAppName(t){return t.Name}_updateAppFromProps(t){const e=this._getAppId(t);this._logger.trace(`updating app with + ${e}, ${JSON.stringify(t)}`);const n=this._getAppOrThrow(e);return n.updateFromProps(t),n}_updateInstanceFromProps(t,e){this._logger.trace("updating instance with "+this._getInstanceId(e)+" for app "+this._getInstanceAppName(e)),t.updateFromProps(e)}}function Nn(t,e,n){const i=t=>!!(t&&t.constructor&&t.call&&t.apply);return i(e)||i(n)?(i(e)?i(n)||(n=()=>{}):e=()=>{},t.then(e,n)):t}class jn{constructor(t){this._agm=t,this._registry=xn(),this._isMethodRegistered=!1,this.handleBranchModified=t=>{this._registry.execute("branchChanged",t)},this.handleBranchesModified=t=>{this._registry.execute("branchesChanged",t)},this.getRegion=(t,e)=>Nn(this._agmInvoke("T42.ACS.GetConfigurationRegion",(t=>t.returned.Region)),t,e),this.getBranches=(t,e)=>Nn(this._agmInvoke("T42.ACS.GetBranches",(t=>{const e=t.returned.Branches;return Object.keys(e).map((t=>e[t]))})),t,e),this.getCurrentBranch=(t,e)=>Nn(this._agmInvoke("T42.ACS.GetCurrentBranch",(t=>t.returned.Branch),void 0),t,e),this.setRegion=(t,e,n)=>Nn(this._agmInvoke("T42.ACS.SetConfigurationRegion",(t=>t.returned.ResultMessage),{Region:t}),e,n),this.setCurrentBranch=(t,e,n)=>Nn(this._agmInvoke("T42.ACS.SetCurrentBranch",(t=>t.returned.ResultMessage),{Branch:t}),e,n),this.currentUser=(t,e)=>Nn(this._agmInvoke("T42.ACS.GetUser"),t,e),this.getFunctionalEntitlement=(t,e,n)=>Nn(this._agmInvoke(_n,(t=>t.returned.Entitlement),{Function:t}),e,n),this.getFunctionalEntitlementBranch=(t,e,n,i)=>Nn(this._agmInvoke(_n,(t=>t.returned.Entitlement),{Function:t,Branch:e}),n,i),this.canI=(t,e,n)=>Nn(this._agmInvoke(In,(t=>t.returned.Result),{Function:t}),e,n),this.canIBranch=(t,e,n,i)=>Nn(this._agmInvoke(In,(t=>t.returned.Result),{Function:t,Branch:e}),n,i),this.onBranchesChanged=t=>this._registry.add("branchesChanged",t),this.onBranchChanged=t=>this._registry.add("branchChanged",t),this.exit=t=>this._agmInvoke("T42.ACS.Shutdown",null,t),this.onShuttingDown=t=>(this.registerMethod(),this._registry.add("onShuttingDown",t)),this.restart=t=>this._agmInvoke("T42.ACS.Restart",null,t),this._agmInvoke=(t,e,n)=>(n=n||{},new Promise(((i,o)=>{this._agm.invoke(t,n).then((t=>{e||(e=t=>t.returned),i(e(t))})).catch((t=>o(t)))})))}registerMethod(){this._isMethodRegistered||(this._agm.register("T42.ACS.OnGDShutdown",(async t=>{try{const e=await Promise.all(this._registry.execute("onShuttingDown",t));return{prevent:e.some((t=>t.prevent))}}catch(t){}})),this._isMethodRegistered=!0)}}const On="T42.ACS.InMemoryStoreCommand";class Wn{constructor(t){this.interop=t}import(t,e){if(!t||!Array.isArray(t))return Promise.reject("invalid apps argument - should be an array of application definitions");if(e&&"replace"!==e&&"merge"!==e)return Promise.reject("invalid mode argument - should be 'replace' or 'merge'");const n={command:"import",args:{apps:t,mode:e=null!=e?e:"replace"}};return this.interop.invoke(On,n).then((t=>t.returned))}export(){return this.interop.invoke(On,{command:"export"}).then((t=>t.returned.apps))}remove(t){if(!t||"string"!=typeof t)return Promise.reject("invalid app name, should be a string value");const e={command:"remove",args:{apps:[t]}};return this.interop.invoke(On,e).then((t=>t.returned))}clear(){return this.interop.invoke(On,{command:"clear"}).then((t=>t.returned))}createAppDef(t,e){return e||(e="https://google.com"),{name:t,type:"window",title:t,details:{url:e}}}}var Fn=t=>{if(!t)throw Error("config not set");if(!t.agm)throw Error("config.agm is missing");const e="startOnly",n="skipIcons",i=t.mode||e;if(i!==e&&i!==n&&"full"!==i)throw new Error(`Invalid mode for appManager lib - ${i} is not supported`);const o=t.activities,r=t.agm,s=t.logger,a=t.windows;let c={};const d=new Rn(i,r,o,a,s.subLogger("applications"),t.gdMajorVersion,(()=>c)),u=new jn(r);let h;if(i===e)h=function(t,e){return new Promise(((n,i)=>{t.invoke(An,{skipIcon:!0}).then((t=>{var i;const o=t.returned,r=null!==(i=t.returned.configuration)&&void 0!==i?i:{};o||n(r);const s=o.applications;s||n(r),kn(s).map((t=>e.handleAppAdded(t))),n(r)})).catch((t=>i(`Error getting application snapshot: ${t.message}`)))}))}(r,d);else{const t=function(t,e,n,i){let o,r=!1;return{start:()=>{let s,a;const c=new Promise(((t,e)=>{s=t,a=e}));return t.subscribe(Cn,{arguments:{skipIcon:i},waitTimeoutMs:1e4}).then((i=>{o=i,o.onData((i=>{var o;const a=i.data,c=null!==(o=a.configuration)&&void 0!==o?o:{},d=kn(a.OnApplicationAdded);i.data.isSnapshot?e.handleSnapshotAppsAdded(d):d.forEach((t=>e.handleAppAdded(t))),kn(a.OnApplicationChanged).forEach((t=>e.handleAppUpdated(t))),kn(a.OnApplicationRemoved).forEach((t=>e.handleAppRemoved(t))),kn(a.OnApplicationReady).forEach((t=>e.handleAppReady(t)));const u=kn(a.OnApplicationStarted);if(i.data.isSnapshot?e.handleSnapshotInstanceStarted(u):u.forEach((t=>e.handleInstanceStarted(t))),kn(a.OnApplicationStartFailed).forEach((t=>e.handleInstanceStartFailed(t))),kn(a.OnApplicationStopped).forEach((t=>e.handleInstanceStopped(t))),kn(a.OnApplicationUpdated).forEach((t=>e.handleInstanceUpdated(t))),kn(a.OnApplicationAgmServerReady).forEach((t=>e.handleInstanceAgmServerReady(t))),kn(a.OnBranchChanged).forEach((t=>n.handleBranchModified(t))),kn(a.OnBranchesModified).forEach((t=>n.handleBranchesModified(t))),!r){r=!0;const n=d.some((e=>e.Name===t.instance.application)),i=u.some((e=>e.Id===t.instance.instance));if(n)if(i)s(c);else{const n=e.onInstanceStarted((e=>{e.id===t.instance.instance&&(n(),s(c))}))}else s(c)}})),o.onFailed((t=>a(t)))})).catch((t=>{var e;return a(`Error subscribing for ${Cn} stream. Err: ${null!==(e=t.message)&&void 0!==e?e:JSON.stringify(t)}`)})),c},stop:()=>{o&&o.close()}}}(r,d,u,i===n);h=t.start()}return{ready:()=>h.then((t=>{c=t})),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:u.getRegion,getBranches:u.getBranches,getCurrentBranch:u.getCurrentBranch,getFunctionalEntitlement:u.getFunctionalEntitlement,getFunctionalEntitlementBranch:u.getFunctionalEntitlementBranch,setCurrentBranch:u.setCurrentBranch,setRegion:u.setRegion,currentUser:u.currentUser,canI:u.canI,canIBranch:u.canIBranch,onBranchesChanged:u.onBranchesChanged,exit:u.exit,restart:u.restart,onShuttingDown:u.onShuttingDown,inMemory:new Wn(r)}};var Ln=1;var Dn,Gn,Bn,qn={nextValue:function(){return(Ln=(9301*Ln+49297)%233280)/233280},seed:function(t){Ln=t}},Un="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-";function Hn(){Bn=!1}function $n(t){if(t){if(t!==Dn){if(t.length!==Un.length)throw new Error("Custom alphabet for shortid must be "+Un.length+" unique characters. You submitted "+t.length+" characters: "+t);var e=t.split("").filter((function(t,e,n){return e!==n.lastIndexOf(t)}));if(e.length)throw new Error("Custom alphabet for shortid must be "+Un.length+" unique characters. These characters were not unique: "+e.join(", "));Dn=t,Hn()}}else Dn!==Un&&(Dn=Un,Hn())}function Jn(){return Bn||(Bn=function(){Dn||$n(Un);for(var t,e=Dn.split(""),n=[],i=qn.nextValue();e.length>0;)i=qn.nextValue(),t=Math.floor(i*e.length),n.push(e.splice(t,1)[0]);return n.join("")}())}var Vn={characters:function(t){return $n(t),Dn},seed:function(t){qn.seed(t),Gn!==t&&(Hn(),Gn=t)},lookup:function(t){return Jn()[t]},shuffled:Jn},zn="object"==typeof window&&(window.crypto||window.msCrypto);var Kn=function(){if(!zn||!zn.getRandomValues)return 48&Math.floor(256*Math.random());var t=new Uint8Array(1);return zn.getRandomValues(t),48&t[0]};var Qn=function(t,e){for(var n,i=0,o="";!n;)o+=t(e>>4*i&15|Kn()),n=e<Math.pow(16,i+1),i++;return o};var Zn,Xn,Yn=function(t){var e=Vn.shuffled();return{version:15&e.indexOf(t.substr(0,1)),worker:15&e.indexOf(t.substr(1,1))}};var ti=function(t){var e="",n=Math.floor(.001*(Date.now()-1459707606518));return n===Xn?Zn++:(Zn=0,Xn=n),e+=Qn(Vn.lookup,6),e+=Qn(Vn.lookup,t),Zn>0&&(e+=Qn(Vn.lookup,Zn)),e+=Qn(Vn.lookup,n)};var ei=function(t){if(!t||"string"!=typeof t||t.length<6)return!1;for(var e=Vn.characters(),n=t.length,i=0;i<n;i++)if(-1===e.indexOf(t[i]))return!1;return!0},ni=function(t,e){return t(e={exports:{}},e.exports),e.exports}((function(t){var e=0;function n(){return ti(e)}t.exports=n,t.exports.generate=n,t.exports.seed=function(e){return Vn.seed(e),t.exports},t.exports.worker=function(n){return e=n,t.exports},t.exports.characters=function(t){return void 0!==t&&Vn.characters(t),Vn.shuffled()},t.exports.decode=Yn,t.exports.isValid=ei}));ni.generate,ni.seed,ni.worker,ni.characters,ni.decode,ni.isValid;var ii=ni;const oi="T42.JumpList.Action";var ri=new class{constructor(){this._groupActionCallbacks=new Map,this._registered=!1}init(t,e,n){this._executor=t,this._agm=e,this._logger=n,this.registerCallbackMethod()}setEnabled(t,e){const n={enabled:e};return this._executor.updateJumpList(t,n)}createCategory(t,e,n){this.validateActions(e,n);const i={category:{title:e,operation:"create",actions:this.toUpdateActions(t,"create",e,n)}};return this._executor.updateJumpList(t,i)}removeCategory(t,e){const n={category:{title:e,operation:"remove",actions:[]}};return this.manageActionCallback(t,n.category.operation,e),this._executor.updateJumpList(t,n)}createActions(t,e,n){this.validateActions(e,n);const i={category:{title:e,operation:"update",actions:this.toUpdateActions(t,"create",e,n)}};return this._executor.updateJumpList(t,i)}removeActions(t,e,n){const i={category:{title:e,operation:"update",actions:this.toUpdateActions(t,"remove",e,n)}};return this._executor.updateJumpList(t,i)}async getActions(t,e){const n=[],i=(await this.getJumpListSettings(t)).categories.find((t=>t.title===e));return i&&i.actions.forEach((t=>{const e=this.getActionCallback(t.callbackId);e&&(t.callback=e.callback),n.push({icon:t.icon,callback:t.callback,singleInstanceTitle:t.singleInstanceTitle,multiInstanceTitle:t.multiInstanceTitle})})),Promise.resolve(n)}getJumpListSettings(t){return this._executor.getJumpList(t)}toUpdateActions(t,e,n,i){return i.map((i=>{const o={icon:i.icon,callback:i.callback,callbackId:ii.generate(),singleInstanceTitle:i.singleInstanceTitle,multiInstanceTitle:i.multiInstanceTitle,operation:e};return this.manageActionCallback(t,e,n,o),o}))}manageActionCallback(t,e,n,i){var o;const r=`${n}-${t}`;if("create"===e){this._groupActionCallbacks.has(r)||this._groupActionCallbacks.set(r,[]);this._groupActionCallbacks.get(r).push({callbackId:i.callbackId,callback:i.callback})}else if("remove"===e)if(i){let t=null!==(o=this._groupActionCallbacks.get(r))&&void 0!==o?o:[];t=t.filter((t=>t.callbackId!==i.callbackId)),0===t.length?this._groupActionCallbacks.delete(r):this._groupActionCallbacks.set(r,t)}else this._groupActionCallbacks.delete(r)}registerCallbackMethod(){if(!this._registered){this._registered=!0;try{this._agm.register(oi,((t,e)=>{const n=this.getActionCallback(t.callbackId);if(n)try{n.callback()}catch(t){this._logger.error("Unable to execute user callback for jump list action!",t)}}))}catch(t){return this._logger.error(`Unable to register method ${oi} for invoking jump list action callbacks!`,t),Promise.reject(t)}}}getActionCallback(t){let e;return[...this._groupActionCallbacks.values()].forEach((n=>{const i=n.find((e=>e.callbackId===t));i&&(e=i)})),e}validateActions(t,e){if(!(e&&e.length>0))throw new Error(`Category '${t}' doesn't contain any actions!`);e.forEach((e=>{if(!e.singleInstanceTitle)throw new Error(`Category '${t}' contains an action with undefined singleInstanceTitle!`);if(!e.multiInstanceTitle)throw new Error(`Category '${t}' contains an action with undefined multiInstanceTitle!`);if(!e.callback)throw new Error(`Category '${t}' contains an action with undefined callback function!`)}))}};var si=new class{constructor(){this.waitForTimeoutInMilliseconds=6e4,this._windows={},this._pendingWindows={},this._pendingWindowsStates={},this._registry=xn()}init(t){this._logger=t}get(t){return this._windows[t]||this._pendingWindows[t]}getIfReady(t){return this._windows[t]}get list(){return this._windows}add(t){if(!!this._pendingWindows[t.API.id])return void this._logger.error(`trying to add window with id ${t.API.id} from windowStore, which already exists`);const e="remote"===t.API.windowType;this._pendingWindows[t.API.id]=t,this._pendingWindowsStates[t.API.id]={ready:!1,urlChanged:e},this._registry.execute("on-added",t)}remove(t){delete this._windows[t.API.id],delete this._pendingWindows[t.API.id],delete this._pendingWindowsStates[t.API.id],this._registry.execute("on-removed",t)}setReadyState(t){const e=this._pendingWindowsStates[t];void 0!==e&&(e.ready=!0,e.urlChanged&&this.markReadyToShow(t))}setUrlChangedState(t){const e=this._pendingWindowsStates[t];void 0!==e&&(e.urlChanged=!0,e.ready&&this.markReadyToShow(t))}setCompositionChangedState(t,e){void 0!==this._pendingWindowsStates[t]&&!1===e&&this.markReadyToShow(t)}waitFor(t){return new Promise(((e,n)=>{let i;const o=setTimeout((()=>{i(),n("waitFor timed out.")}),this.waitForTimeoutInMilliseconds),r=this._windows[t];r?(clearTimeout(o),e(r)):i=this.onReadyWindow((n=>{n.API.id===t&&(clearTimeout(o),i(),e(n))}))}))}onReadyWindow(t){return this._registry.add("on-ready",t)}onAdded(t){return this._registry.add("on-added",t)}onRemoved(t){return this._registry.add("on-removed",t)}markReadyToShow(t){this._pendingWindows[t]&&(this._windows[t]=this._pendingWindows[t],delete this._pendingWindows[t],delete this._pendingWindowsStates[t]),this._registry.execute("on-ready",this._windows[t])}};class ai{static getGDMajorVersion(){if("undefined"==typeof window)return-1;if(!window.glueDesktop)return-1;if(!window.glueDesktop.version)return-1;const t=Number(window.glueDesktop.version.substr(0,1));return isNaN(t)?-1:t}static callbackifyPromise(t,e,n){const i=t=>{let e=t;if(t instanceof Error&&(e=t.message),"function"!=typeof n)return Promise.reject(e);n(e)};try{return t().then((t=>("function"==typeof e&&e(t),t))).catch((t=>i(t)))}catch(t){return i(t)}}static getMonitor(t,e){return e.map((e=>{const{left:n,top:i,workingAreaWidth:o,workingAreaHeight:r}=e;return{monitor:e,totalOverlap:this.calculateTotalOverlap({left:n,top:i,width:o,height:r},t)}})).sort(((t,e)=>e.totalOverlap-t.totalOverlap))[0].monitor}static getDisplayCenterOfScreen(t,e,n){const i=t.width/e.scaleFactor,o=t.height/e.scaleFactor,r=e.workArea.left/n.scaleFactor,s=e.workArea.top/n.scaleFactor,a=e.workArea.width/e.scaleFactor,c=e.workArea.height/e.scaleFactor,d=Math.max((a-i)/2,0),u=Math.max((c-o)/2,0),h=Math.floor(r+d),l=Math.floor(s+u);return{left:h*n.scaleFactor,top:l*n.scaleFactor,width:t.width,height:t.height}}static isNode(){if(void 0!==ai._isNode)return ai._isNode;if("undefined"!=typeof window)return ai._isNode=!1,!1;try{ai._isNode="[object process]"===Object.prototype.toString.call(global.process)}catch(t){ai._isNode=!1}return ai._isNode}static calculateTotalOverlap(t,e){const n=t.left,i=t.top,o=n+t.width,r=i+t.height,s=e.left,a=e.top,c=s+e.width,d=a+e.height;return Math.max(0,Math.min(o,c)-Math.max(n,s))*Math.max(0,Math.min(r,d)-Math.max(i,a))}}class ci{constructor(t,e){this.windowId=t,this._categoryTitle=e.title}list(){return ri.getActions(this.windowId,this._categoryTitle)}create(t){return ri.createActions(this.windowId,this._categoryTitle,t)}remove(t){return ri.removeActions(this.windowId,this._categoryTitle,t)}}class di{constructor(t){this.windowId=t}list(){return this.getCategories()}create(t,e){return ri.createCategory(this.windowId,t,e)}remove(t){return ri.removeCategory(this.windowId,t)}async find(t){return(await this.getCategories()).find((e=>e.title===t))}async getCategories(){const t=[];return(await ri.getJumpListSettings(this.windowId)).categories.forEach((e=>{t.push({title:e.title,actions:new ci(this.windowId,e)})})),t}}class ui{constructor(t){this.windowId=t,this._categories=new di(t)}get categories(){return this._categories}async isEnabled(){return(await ri.getJumpListSettings(this.windowId)).enabled}setEnabled(t){return ri.setEnabled(this.windowId,t)}}var hi=(t,e,n,i,o,r,s,a)=>{var c,d,u,h;const l=xn(),p=()=>{const t=s();if(!t)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 t},g=t,f=e.name,y=e.mode;let m=e.bounds,v=e.url,w=e.title,b=null!==(c=e.context)&&void 0!==c?c:{},_=e.frameColor,I=e.focus,C=null!==(d=e.neighbours)&&void 0!==d?d:{},A=e.groupId,S=e.isGroupHeaderVisible,x=e.isTabHeaderVisible,k=null!==(u=e.isTabSelected)&&void 0!==u&&u,T=e.settings;const E=e.applicationName;let P,M=e.isVisible,R=e.isSticky,N=e.isCollapsed,j=e.state,O=e.tabGroupId,W=e.tabIndex,F=e.frameId,L=e.isLocked,D=null!==(h=e.frameButtons)&&void 0!==h?h:[],G=e.zoomFactor,B=e.placementSettings;const q=new ui(t);function U(t,e,i){return ai.callbackifyPromise((()=>{if(Me(t))throw new Error("The properties of `bounds` cannot be null or undefined.");return n.moveResize(Q,t)}),e,i)}function H(t,e,i){return ai.callbackifyPromise((()=>n.setVisible(Q,t)),e,i)}function $(t){return J("group-changed",t)}function J(t,e,n){if(!je(e))throw new Error("callback must be a function");return l.add(t,e,n)}function V(t){const e=C[t];if(void 0!==e)return e.reduce(((t,e)=>{const n=si.get(e);return n&&t.push(n.API),t}),[])}function z(){var e;if(E)return E;if(b._APPLICATION_NAME)return b._APPLICATION_NAME;if(b&&b._t42&&b._t42.application)return b._t42.application;const n=K();if(n&&n.applicationName)return n.applicationName;const i=o();if(i){const n=i.instances().find((e=>t===e.id));if(n)return null===(e=n.application)||void 0===e?void 0:e.name}}function K(){if("undefined"!=typeof window&&window.glue42gd&&window.glue42gd.getWindowInfo){const e=window.glue42gd.getWindowInfo(t);return e||void 0}}const Q={get id(){return g},get name(){return f},get application(){const t=o(),e=z();if(e&&t)return t.application(e)},get hostInstance(){return n.hostInstance},get interopInstance(){const t=a.servers().find((t=>t.windowId===this.id));if(t)return t;{const t=z();if(t)return{application:t}}},get agmInstance(){return Q.interopInstance},get url(){return v},get title(){return w},get windowStyleAttributes(){return T},get settings(){return T},get tabGroupId(){return"tab"===y.toLowerCase()?O:void 0},get tabIndex(){return"tab"===y.toLowerCase()?W:void 0},get frameId(){return F},get frameButtons(){return D.sort(((t,e)=>t.order-e.order))},get mode(){return y},get state(){return j},get isCollapsed(){return N},get isVisible(){return M},get isLocked(){return L},get context(){return b},get bounds(){return m},get minHeight(){return T.minHeight},get maxHeight(){return T.maxHeight},get minWidth(){return T.minWidth},get maxWidth(){return T.maxWidth},get isFocused(){return I},get frameColor(){return _},get opened(){return void 0!==Q.id},get group(){return P},get groupId(){return A},get isSticky(){return R},get topNeighbours(){return V("top")},get leftNeighbours(){return V("left")},get rightNeighbours(){return V("right")},get bottomNeighbours(){return V("bottom")},get isGroupHeaderVisible(){return S},get activityId(){if(b._t42)return b._t42.activityId;const t=K();return t?t.activityId:void 0},get activityWindowId(){if(b._t42)return b._t42.activityWindowId;const t=K();return t?t.activityWindowId:void 0},get windowType(){return e.windowType||"electron"},get zoomFactor(){return G},get screen(){if("undefined"!=typeof window&&window.glue42gd)return ai.getMonitor(Q.bounds,window.glue42gd.monitors)},get placementSettings(){return Object.assign({},B)},get jumpList(){return q},maximize:function(t,e){return ai.callbackifyPromise((()=>"maximized"===j?Promise.resolve(Q):n.maximize(Q)),t,e)},restore:function(t,e){return ai.callbackifyPromise((()=>"normal"===j?Promise.resolve(Q):n.restore(Q)),t,e)},minimize:function(t,e){return ai.callbackifyPromise((()=>"minimized"===j?Promise.resolve(Q):n.minimize(Q)),t,e)},maximizeRestore:function(t,e){return ai.callbackifyPromise((()=>n.maximizeRestore(Q)),t,e)},collapse:function(t,e){return ai.callbackifyPromise((()=>N?Promise.resolve(Q):n.collapse(Q)),t,e)},expand:function(t,e){return ai.callbackifyPromise((()=>N?n.expand(Q):Promise.resolve(Q)),t,e)},toggleCollapse:function(t,e){return ai.callbackifyPromise((()=>n.toggleCollapse(Q)),t,e)},focus:function(t,e){return ai.callbackifyPromise((()=>I?Promise.resolve(Q):n.focus(Q)),t,e)},activate:function(t,e){return ai.callbackifyPromise((()=>I?Promise.resolve(Q):n.activate(Q)),t,e)},moveResize:U,setTitle:function(t,e,i){return ai.callbackifyPromise((()=>{if(Me(t))throw new Error("`newTitle` must not be null or undefined.");return t===w?Promise.resolve(Q):n.setTitle(Q,t)}),e,i)},setStyle:function(t,e,i){return ai.callbackifyPromise((()=>{if(!t||0===Object.keys(t).length||Object.keys(t).every((t=>!t)))throw new Error("Invalid style arguments: "+JSON.stringify(t));if(t&&void 0!==t.focus){if("boolean"!=typeof t.focus)throw new Error("Focus must be a boolean value. Currently, only `focus: true` is supported.");!1===t.focus&&console.warn("`focus: false` is not supported!")}if(t&&void 0!==t.hidden&&"boolean"!=typeof t.hidden)throw new Error("The `hidden` property must hold a boolean value.");for(const e of["minHeight","maxHeight","minWidth","maxWidth"]){const n=t,i=n[e];if(e in t){if(Me(i)){delete n[e];continue}if(!xe(n[e]))throw new Error(`"${e}" must be a number`)}}return n.setStyle(Q,t)}),e,i)},setOnTop:function(t,e,i){return ai.callbackifyPromise((()=>{if("string"==typeof t){if("always"!==t)throw new Error("`onTop` must hold a `always` value.")}else if("boolean"!=typeof t)throw new Error("`onTop` must hold a boolean or `always` value.");return n.setOnTop(Q,t)}),e,i)},resetButtons:function(t,e,i){return ai.callbackifyPromise((()=>n.resetButtons(Q,t)),e,i)},getButtons:function(){return n.getButtons(Q)},setSizeConstraints:function(t,e,i){return ai.callbackifyPromise((()=>{if(!t||Object.keys(t).every((t=>void 0===t)))throw new Error("The properties of `constraints` cannot be null or undefined.");return n.setSizeConstraints(Q,t)}),e,i)},getSizeConstraints:function(){return n.getSizeConstraints(Q)},navigate:function(t,e,i){if("function"==typeof e)return ai.callbackifyPromise((()=>{if(Re(t))throw new Error("The new URL must be a non-empty string.");return n.navigate(Q,t)}),e,i);if(Re(t))throw new Error("The new URL must be a non-empty string.");return n.navigate(Q,t,e)},addFrameButton:function(t,e,i){return ai.callbackifyPromise((()=>{if(void 0===t||0===Object.keys(t).length)throw new Error("Button info is not available.");if(Re(t.buttonId))throw new Error("`buttonId` must not be null or undefined.");if(Re(t.imageBase64))throw new Error("`imageBase64` must not be null or undefined.");return n.addFrameButton(Q,t)}),e,i)},removeFrameButton:function(t,e,i){return ai.callbackifyPromise((()=>{if(Re(t))throw new Error("`buttonId` must not be null or undefined.");return n.removeFrameButton(Q,t)}),e,i)},setVisible:H,show:()=>H(!0),hide:()=>H(!1),center:async function(t){return t&&function(t){if("object"!=typeof t)throw Error("display argument must be a valid display object");if(!t.workArea||!t.scaleFactor)throw Error("display argument is not a valid display object")}(t),n.center(Q,t)},close:function(e,i){return void 0===e||"function"==typeof e?ai.callbackifyPromise((()=>{if(!t)throw new Error("The window is already closed.");return n.close(Q)}),e,i):n.close(Q,e)},snap:function(t,e,i,o){return ai.callbackifyPromise((()=>{if(Me(t))throw new Error(`A target window is not specified - ${"string"==typeof t?t:JSON.stringify(t)}`);if("string"==typeof t){const e=si.get(t);if(!e)throw new Error(`Invalid "target" parameter or no such window. Invoked with: ${t}`);t=e.API}return"string"==typeof e&&(e={direction:e,autoAlign:!0}),n.snap(Q,t,e)}),i,o)},showLoader:function(t){return n.showLoader(Q,t)},hideLoader:function(){return n.hideLoader(Q)},updateContext:function(t,e,i){return ai.callbackifyPromise((()=>{if(Me(t))throw new Error('"context" must not be null or undefined.');return n.updateContext(Q,t,!1)}),e,i)},lock:function(t,e){return ai.callbackifyPromise((()=>n.lock(Q)),t,e)},unlock:function(t,e){return ai.callbackifyPromise((()=>n.unlock(Q)),t,e)},getIcon:function(t,e){return ai.callbackifyPromise((()=>n.getIcon(Q)),t,e)},setIcon:function(t,e,i){return ai.callbackifyPromise((()=>{if(Re(t))throw new Error('"base64Image" must be a non-empty string.');return n.setIcon(Q,t)}),e,i)},setFrameColor:function(t,e,i){return ai.callbackifyPromise((()=>{if(Re(t))throw new Error('"frameColor" must be a non-empty string');return n.setFrameColor(Q,t)}),e,i)},setTabTooltip:async function(t){if(Re(t))throw new Error(`"${t}" must not be null or undefined`);return n.setTabTooltip(Q,t)},getTabTooltip:async function(){return n.getTabTooltip(Q)},attachTab:function(t,e,i,o){return ai.callbackifyPromise((()=>{var i;const o='Invalid "tab" parameter - must be an object with an "id" property or a string. Invoked for source window with ID:';if(Me(t)){const e=`${o} ${"string"==typeof t?t:JSON.stringify(t)}`;throw new Error(e)}let r;if("string"==typeof t){if(r=null===(i=si.get(t))||void 0===i?void 0:i.API,Me(r)){const t=`${o} ${"string"==typeof r?r:JSON.stringify(r)}`;throw new Error(t)}}else{if(Me(t.id))throw new Error(o);r=t}const s={};return Me(e)||("number"==typeof e?s.index=e:(s.selected=e.selected,s.index=e.index)),n.attachTab(Q,r,s)}),i,o)},detachTab:function(t={},e,i){return ai.callbackifyPromise((()=>{const e={};return void 0!==t.relativeTo?("string"==typeof t.relativeTo?e.relativeTo=t.relativeTo:Me(t.relativeTo.id)||(e.relativeTo=t.relativeTo.id),Me(t.relativeDirection)||(e.relativeDirection=t.relativeDirection),Me(t.width)||(e.width=t.width),Me(t.height)||(e.height=t.height)):Me(t.bounds)||(e.bounds=t.bounds),Me(t.hideTabHeader)||(e.hideTabHeader=t.hideTabHeader),n.detachTab(Q,e)}),e,i)},setTabHeaderVisible:function(t,e,i){return ai.callbackifyPromise((()=>{if("boolean"!=typeof t)throw new Error('"toBeTabHeaderVisible" must hold a boolean value.');return n.setTabHeaderVisible(Q,t)}),e,i)},showPopup:function(t){return n.showPopup(Q,t)},createFlydown:function(t){return n.createFlydown(Q.id,t)},setModalState:function(t){return n.setModalState(Q.id,t||!1)},setZoomFactor:function(t,e,i){return ai.callbackifyPromise((()=>{if(isNaN(t))throw new Error("zoomFactor is not a number");return n.setZoomFactor(Q,t)}),e,i)},zoomIn:function(t,e){return ai.callbackifyPromise((()=>n.zoomIn(Q)),t,e)},zoomOut:function(t,e){return ai.callbackifyPromise((()=>n.zoomOut(Q)),t,e)},showDevTools:function(){return n.showDevTools(Q)},capture:function(t){return n.capture(Q,t)},flash:function(t,e){const i={shouldFlash:!0,mode:"auto"};return"boolean"==typeof t&&(i.shouldFlash=t),void 0!==e&&(i.mode=e),n.flash(Q,i)},flashTab:function(t){const e={shouldFlash:!0};return"boolean"==typeof t&&(e.shouldFlash=t),n.flashTab(Q,e)},setSticky:function(t,e,i){return ai.callbackifyPromise((()=>{if("boolean"!=typeof t)throw new Error("`isSticky` must hold a boolean value.");return n.setSticky(Q,t)}),e,i)},print:function(t){return n.print(Q,t)},printToPDF:function(t){return n.printToPDF(Q,t)},place:function(t){return n.place(Q,t)},ungroup:function(e){return new Promise(((i,o)=>{const r=$(((e,n,o)=>{t===e.id&&(r(),i(Q))}));n.ungroup(Q,e).catch((t=>{r(),o(t)}))}))},refresh:function(t){return n.refresh(Q,t)},goBack:function(){return n.goBack(Q)},goForward:function(){return n.goForward(Q)},download:function(t,e){return n.download(Q,t,e)},configure:function(t){return n.configureWindow(Q,t)},getConfiguration:function(){return n.getWindowConfiguration(Q)},getChannel:async()=>{var t;return null===(t=(await p().getWindowsWithChannels({windowIds:[g]}))[0])||void 0===t?void 0:t.channel},startDrag:function(t){return n.startDrag(Q,t)},showDialog:function(t){if((null==t?void 0:t.timerDuration)&&isNaN(null==t?void 0:t.timerDuration))throw new Error("timerDuration must be a number");if((null==t?void 0:t.showTimer)&&"boolean"!=typeof(null==t?void 0:t.showTimer))throw new Error("showTimer must be a boolean");return n.showDialog(Q,t)},onClose:function(e){if(!je(e))throw new Error("callback should be a function");return void 0===t&&e(Q),l.add("onClose",e)},onUrlChanged:function(t){return J("onUrlChanged",t)},onTitleChanged:function(t){if(!je(t))throw new Error("callback should be a function");return t(Q.title,Q),J("onTitleChanged",t)},onFrameButtonAdded:function(t){return J("onFrameButtonAdded",t)},onFrameButtonRemoved:function(t){return J("onFrameButtonRemoved",t)},onFrameButtonClicked:function(t){return J("onFrameButtonClicked",t)},onCollapsed:function(t){if(!je(t))throw new Error("callback should be a function");return N&&t(Q),l.add("collapsed",t)},onExpanded:function(t){if(!je(t))throw new Error("callback should be a function");return N||t(Q),l.add("expanded",t)},onMinimized:function(t){return"minimized"===j?J("minimized",t,[Q]):J("minimized",t)},onMaximized:function(t){return"maximized"===j?J("maximized",t,[Q]):J("maximized",t)},onNormal:function(t){return"normal"===j?J("normal",t,[Q]):J("normal",t)},onAttached:function(t){return J("attached",t)},onDetached:function(t){return J("detached",t)},onVisibilityChanged:function(t){return J("visibility-changed",t)},onContextUpdated:function(t){return J("context-updated",t)},onLockingChanged:function(t){return J("lock-changed",t)},onBoundsChanged:function(t){return J("bounds-changed",t)},onFrameColorChanged:function(t){return J("frame-color-changed",t)},onFocusChanged:function(t){return J("focus-changed",t)},onStickyChanged:function(t){return J("sticky-changed",t)},onGroupChanged:$,onWindowAttached:function(t){return J("window-attached",t)},onWindowDetached:function(t){return J("window-detached",t)},onTabSelectionChanged:function(t){return J("tab-selection-changed",t)},onTabHeaderVisibilityChanged:function(t){return J("tab-header-visibility-changed",t)},onClosing:function(t){if(!je(t))throw new Error("callback must be a function");return n.onClosing(((e,n,i)=>{const o=t(i);(null==o?void 0:o.then)?o.then(e).catch(n):e()}),Q)},onRefreshing:function(t){if(!je(t))throw new Error("callback must be a function");return n.onRefreshing(((e,n,i)=>{const o=t(i);(null==o?void 0:o.then)?o.then(e).catch(n):e()}),Q)},onZoomFactorChanged:function(t){return J("zoom-factor-changed",t)},onPlacementSettingsChanged:function(t){return J("placementSettingsChanged",t)},onNeighboursChanged:function(t){return J("neighbours-changed",t)},onNavigating:function(t){if(!je(t))throw new Error("callback must be a function");return n.onNavigating(((e,n,i,o)=>{const r=t(o);(null==r?void 0:r.then)?r.then(e).catch(n):e()}),Q)},get tabs(){return function(){const t=si.list;return"tab"!==y.toLowerCase()?[]:Object.keys(t).reduce(((e,n)=>{const i=t[n];return i&&i.API.tabGroupId&&void 0!==i.API.tabGroupId&&void 0!==Q.tabGroupId&&i.API.tabGroupId===Q.tabGroupId&&e.push(i.API),e}),[]).sort(((t,e)=>{if(t.tabIndex!==e.tabIndex){if(-1===t.tabIndex)return Number.MAX_SAFE_INTEGER;if(-1===e.tabIndex)return Number.MIN_SAFE_INTEGER}return t.tabIndex-e.tabIndex}))}()},get isTabHeaderVisible(){return x},get isTabSelected(){return k},getURL:()=>Promise.resolve(v),getTitle:()=>Promise.resolve(w),getBounds:()=>Promise.resolve(m),getContext:()=>Promise.resolve(b),setContext(t){if(Me(t))throw new Error('"context" must not be null or undefined, set to empty object if you want to clear it out.');return n.updateContext(Q,t,!0)},getDisplay:()=>r().getByWindowId(t),resizeTo:(t,e)=>U({width:t,height:e}),moveTo:(t,e)=>U({top:t,left:e}),async getParentWindow(){var t;const e=T.parentInstanceId;if(e)return null===(t=si.list[e])||void 0===t?void 0:t.API},getChildWindows:async()=>Object.keys(si.list).map((t=>si.list[t].API)).filter((e=>e.settings.parentInstanceId===t)),joinChannel:e=>p().join(e,t),leaveChannel:()=>p().leave(t)};return{API:Q,Events:{handleUpdate:function(t){v=t.url,w=t.title,b=t.context||{},m=t.bounds,_=t.frameColor,I=t.focus,C=t.neighbours||{},A=t.groupId,S=t.isGroupHeaderVisible,x=t.isTabHeaderVisible,k=t.isTabSelected,T=t.settings,M=t.isVisible,R=t.isSticky,N=t.isCollapsed,j=t.state,O=t.tabGroupId,F=t.frameId,L=t.isLocked,G=t.zoomFactor,B=t.placementSettings},handleWindowClose:function(){void 0!==t&&(l.execute("onClose",Q),t=void 0)},handleWindowChangeState:async function(t){"collapsed"===t?N=!0:"expanded"===t?N=!1:j=t,await n.finished,l.execute(t,Q)},handleTitleChanged:function(t){w=t,n.finished.finally((()=>{l.execute("onTitleChanged",t,Q)}))},handleVisibilityChanged:function(t){t!==M&&(M=t,l.execute("visibility-changed",Q))},handleUrlChanged:function(t){v=t,l.execute("onUrlChanged",t,Q)},handleWindowSettingsChanged:function(t){T=t,l.execute("settings-changed",Q)},handleContextUpdated:function(t){b=t,l.execute("context-updated",b,Q)},handleFrameIsLockedChanged:function(t){L=t,l.execute("lock-changed",Q)},handleBoundsChanged:function(t){m.top===t.top&&m.left===t.left&&m.width===t.width&&m.height===t.height||(m=t,l.execute("bounds-changed",Q))},handleFocusChanged:function(t){I=t,l.execute("focus-changed",Q)},handleFrameButtonAdded:function(t){const e=["buttonId","imageBase64","order","tooltip"].reduce(((e,n)=>(e[n]=t[n],e)),{});-1===D.map((t=>t.buttonId)).indexOf(t.buttonId)&&D.push(e),l.execute("onFrameButtonAdded",e,Q)},handleFrameButtonRemoved:function(t){let e;D=D.reduce(((n,i)=>(i.buttonId===t?e=i:n.push(i),n)),[]),void 0!==e&&l.execute("onFrameButtonRemoved",e,Q)},handleFrameButtonClicked:function(t){const e=D.filter((e=>e.buttonId===t.buttonId));e.length>0&&l.execute("onFrameButtonClicked",e[0],Q)},handleFrameColorChanged:function(t){_=t,l.execute("frame-color-changed",Q)},handleFrameAttached:function(t,e,n){O=t,F=e,x=n,l.execute("frame-attached",Q)},handleFrameSelectionChanged:async function(e,i){let o;e===t?(k=!0,o=Q):(k=!1,o=si.get(e)?si.get(e).API:void 0);const r=si.get(i)?si.get(i).API:void 0;await n.finished,l.execute("tab-selection-changed",o,r,Q)},handleCompositionChanged:function(t){C=t.neighbors||{},W=t.index,l.execute("neighbours-changed",C,Q)},handleGroupHeaderVisibilityChanged:function(t){S=t},handleTabHeaderVisibilityChanged:function(t){x!==t&&(x=t,l.execute("tab-header-visibility-changed",Q))},handleGroupChanged:function(t,e){P=t,A=null==t?void 0:t.id,Me(t)||Me(e)||l.execute("group-changed",Q,t,e)},handleAttached:async function(t,e,i,o,r){O=t,x=i,F=e,void 0!==o&&(L=o),await n.finished,r.forEach((t=>{t.Events.handleWindowAttached(Q)})),l.execute("attached",Q)},handleDetached:async function(t,e){O=void 0,k=!1,void 0!==t&&(L=t),await n.finished,e.forEach((t=>{t.Events.handleWindowDetached(Q)})),l.execute("detached",Q)},handleWindowAttached:function(t){l.execute("window-attached",t)},handleWindowDetached:function(t){l.execute("window-detached",t)},handleZoomFactorChanged:function(t){G=t,l.execute("zoom-factor-changed",Q)},handleIsStickyChanged:function(t){R=t,l.execute("sticky-changed",t,Q)},handlePlacementSettingsChanged:function(t){let e;const n=t;if(n.display){const t=r();if(t){const i=n.display-1;e=new Promise(((e,n)=>{t.all().then((t=>{const n=t.find((t=>t.index===i));e(n)})).catch(n)}))}else e=Promise.resolve(void 0)}else e=Promise.resolve(void 0);e.then((t=>{n.display=t,B=n,l.execute("placementSettingsChanged",Q)}))}}}};function li(t,e){const n=si.list;return Object.keys(n).reduce(((i,o)=>{const r=n[o];return r.API.tabGroupId===e&&r.API.id!==t&&i.push(r),i}),[])}function pi(t){return!(t&&!Object.keys(t).every((e=>void 0===t[e])))}var gi=new class{constructor(){this.GroupMethodName="T42.Group.Execute",this.WndMethodName="T42.Wnd.Execute",this._registry=xn(),this._finished=Promise.resolve(),this.unsubCallbacks={}}get hostInstance(){return this.agmTarget}get finished(){return this._finished}init(t,e,n){this.agm=t,this.agmTarget=e,this._configuration=n,this._registry.add("event",(t=>{if("Closed"===t.type){Object.keys(this.unsubCallbacks).forEach((e=>{e.startsWith(t.windowId)&&delete this.unsubCallbacks[e]}))}}))}handleEvent(t){this._registry.execute("event",t)}async open(t){let e;this._finished=new Promise((t=>{e=t}));try{const e=await this.agm.invoke("T42.Wnd.Create",t,this.agmTarget);if(void 0===e.returned)throw new Error("failed to execute T42.Wnd.Create - unknown reason");const n=e.returned.id,i=await si.waitFor(n);return this._configuration&&!this._configuration.windowAvailableOnURLChanged||setTimeout((()=>{"electron"===i.API.windowType&&i.Events.handleUrlChanged(i.API.url)}),0),i.API}catch(t){throw t}finally{e()}}async close(t,e){const n=await this.execute("close",{windowId:t.id,options:e},"Closed");return e?n.closed:t}async navigate(t,e,n){return await this.execute("navigate",{windowId:t.id,options:{url:e,urlLoadOptions:n}},"UrlChanged"),t}async setStyle(t,e){var n;const i=[],o=t=>i.push(t);if(Me(e.focus)||t.isFocused||o(t.focus()),!Me(e.hidden)){const n=!e.hidden;o(t.setVisible(n))}if(Me(e.onTop)||o(t.setOnTop(e.onTop)),!Re(e.tabTooltip)||!Re(e.tabToolTip)){const i=null!==(n=e.tabTooltip)&&void 0!==n?n:e.tabToolTip;o(t.setTabTooltip(i))}Re(e.tabTitle)||o(this.execute("setTabTitle",{windowId:t.id,options:{tabTitle:e.tabTitle}}));const r={minHeight:e.minHeight,minWidth:e.minWidth,maxHeight:e.maxHeight,maxWidth:e.maxWidth};!pi(r)&&o(t.setSizeConstraints(r));const s={allowClose:e.allowClose,allowCollapse:e.allowCollapse,allowLockUnlock:e.allowLockUnlock,allowMaximize:e.allowMaximize,allowMinimize:e.allowMinimize};return!pi(s)&&o(t.resetButtons(s)),await Promise.all(i),t}async setSizeConstraints(t,e){return await this.execute("setSizeConstraints",{windowId:t.id,options:e}),t}async getSizeConstraints(t){return await this.execute("getSizeConstraints",{windowId:t.id})}async setTabTooltip(t,e){return await this.execute("setTabTooltip",{windowId:t.id,options:{tabTooltip:e}}),t}async getTabTooltip(t){return(await this.execute("getTabTooltip",{windowId:t.id})).tabTooltip}async resetButtons(t,e){return await this.execute("resetButtons",{windowId:t.id,options:e}),t}async getButtons(t){return await this.execute("getButtons",{windowId:t.id})}async setOnTop(t,e){return await this.execute("setOnTop",{windowId:t.id,options:{onTop:e}}),t}async setTitle(t,e){const n={windowId:t.id,options:{title:e}};return await this.execute("setTitle",n,"TitleChanged"),t}async setSticky(t,e){const n={windowId:t.id,options:{isSticky:e}};return await this.execute("setSticky",n),t}async moveResize(t,e){return"undefined"!=typeof window&&window.glueDesktop.versionNum<31200?new Promise((async(n,i)=>{const o=this.areBoundsEqual(e,t);let r=!1;const s=()=>{r||(r=!0,c&&(c(),c=void 0),n(t),a&&(clearTimeout(a),a=void 0))};let a,c;o||(c=t.onBoundsChanged((t=>{this.areBoundsEqual(e,t)&&s()})));try{await this.execute("moveResize",{windowId:t.id,options:{bounds:e}})}catch(t){return void i(t)}o?s():a=setTimeout((()=>{s()}),1e3)})):(await this.execute("moveResize",{windowId:t.id,options:{bounds:e}}),t)}async addFrameButton(t,e){return await this.execute("addButton",{windowId:t.id,options:e},"ButtonAdded"),t}async removeFrameButton(t,e){return await this.execute("removeButton",{windowId:t.id,options:e},"ButtonRemoved"),t}async activate(t){let e;try{const n=new Promise(((n,i)=>{e=t.onFocusChanged((()=>{n()}))}));return await Promise.all([this.execute("activate",{windowId:t.id},"FocusChanged"),n]),t}catch(t){throw t}finally{e&&e()}}async focus(t){let e;try{const n=new Promise(((n,i)=>{e=t.onFocusChanged((()=>{n()}))}));return await Promise.all([this.execute("focus",{windowId:t.id},"FocusChanged"),n]),t}catch(t){throw t}finally{e&&e()}}async maximizeRestore(t){return await this.execute("maximizeRestore",{windowId:t.id},"StateChanged"),t}async maximize(t){return await this.execute("maximize",{windowId:t.id},"StateChanged"),t}async restore(t){return await this.execute("restore",{windowId:t.id},"StateChanged"),t}async minimize(t){return await this.execute("minimize",{windowId:t.id},"StateChanged"),t}async collapse(t){return await this.execute("collapse",{windowId:t.id},"StateChanged"),t}async expand(t){return await this.execute("expand",{windowId:t.id},"StateChanged"),t}async toggleCollapse(t){return await this.execute("toggleCollapse",{windowId:t.id},"StateChanged"),t}async snap(t,e,n){const i={targetWindowId:e.id};return i.snappingEdge=n.direction,i.autoAlign=n.autoAlign,await this.execute("snap",{windowId:t.id,options:i},"CompositionChanged",`CompositionChanged-${e.id}`),t}async attachTab(t,e,n){return await this.execute("attachTab",{windowId:t.id,options:{index:n,sourceWindowId:e.id,targetWindowId:t.id}},`WindowFrameAdded-${e.id}`,`WindowFrameRemoved-${e.id}`),t}async detachTab(t,e){const n=["WindowFrameRemoved","WindowFrameAdded"];return Me(null==e?void 0:e.relativeTo)?n.push("BoundsChanged"):(n.push("CompositionChanged"),n.push(`CompositionChanged-${e.relativeTo}`)),await this.execute("detachTab",{windowId:t.id,options:e},...n),t}async setVisible(t,e=!0){let n;return n=e?"show":"hide",await this.execute(n,{windowId:t.id},"VisibilityChanged"),t}async center(t,e){return await this.execute("center",{windowId:t.id,options:e}),t}async showLoader(t,e){return await this.execute("showLoadingAnimation",{windowId:t.id,options:e}),t}async hideLoader(t){return await this.execute("hideLoadingAnimation",{windowId:t.id}),t}async updateContext(t,e,n){let i;try{const o=this.swapUndefinedToNull(e),r=new Promise(((e,n)=>{i=t.onContextUpdated((()=>{e()}))}));return await Promise.all([this.execute("updateContext",{windowId:t.id,context:o,replace:n}),r]),t}catch(t){throw t}finally{i&&i()}}async lock(t){return await this.execute("lockUnlock",{windowId:t.id,options:{lock:!0}},"FrameIsLockedChanged"),t}async unlock(t){return await this.execute("lockUnlock",{windowId:t.id,options:{lock:!1}},"FrameIsLockedChanged"),t}async getIcon(t){return(await this.execute("getIcon",{windowId:t.id,options:{}})).icon}async setIcon(t,e){return await this.execute("setIcon",{windowId:t.id,options:{dataURL:e}}),t}async setFrameColor(t,e){return await this.execute("setFrameColor",{windowId:t.id,options:{frameColor:e}},"FrameColorChanged"),t}async setTabHeaderVisible(t,e){return await this.execute("setTabHeaderVisible",{windowId:t.id,options:{toShow:e}},"TabHeaderVisibilityChanged"),t}async showPopup(t,e){if(!e)throw new Error("The options object is not valid!");const n={...e};n.targetLocation||(n.targetLocation="bottom");const i={...n,popupBounds:n.size,targetId:t.id,popupId:n.windowId};return await this.execute("showPopupWindow",{windowId:t.id,options:i}),t}async createFlydown(t,e){if(!e)throw new Error("The options object is not valid!");const n={...e};n.horizontalOffset||(n.horizontalOffset=0),n.verticalOffset||(n.verticalOffset=0);const i=this.reformatFlydownOptions(t,n);return this.execute("setFlydownArea",{windowId:t,options:i}).then((()=>{const t=i.zones.map((t=>t.id));return i.zones.forEach((t=>{let n="function"==typeof t.flydownSize?t.flydownSize:()=>t.flydownSize;e.size instanceof Function&&t.flydownSize&&(n=async(n,i)=>{let o;return e.size instanceof Function&&(o=await e.size(n,i)),t.flydownSize instanceof Function&&t.flydownSize!==e.size?await t.flydownSize(n,i)||o:o||t.flydownSize}),this._registry.clearKey(`${i.targetId}_${t.id}`),this._registry.add(`${i.targetId}_${t.id}`,n)})),{destroy:()=>this.clearFlydownArea(i.targetId,t),options:n}}))}async setModalState(t,e){return this.execute("setModalState",{windowId:t,options:{isModal:e}})}async handleFlydownBoundsRequested(t,e){const n={zoneId:e.flydownId,flydownWindowBounds:e.flydownWindowBounds,flydownWindowId:e.flydownWindowId},i=await Promise.all(this._registry.execute(`${t}_${e.flydownId}`,n,(()=>e.cancel=!0)));if(1===i.length){const t={height:0,width:0,top:0,left:0},n="object"!=typeof i[0]||Array.isArray(i[0])?t:i[0];return{...e,flydownWindowBounds:n}}}async handleOnEventRequested(t,e){var n;const i=null!==(n=this.unsubCallbacks[t])&&void 0!==n?n:[];let o=!1;const r=[];return await Promise.all(i.map((t=>new Promise(((n,i)=>{t((()=>{n()}),(()=>{i()}),(t=>{o=!0,r.push(t)}),e)}))))),{prevented:o,preventArgs:r}}async zoomIn(t){return await this.execute("zoomIn",{windowId:t.id}),t}async zoomOut(t){return await this.execute("zoomOut",{windowId:t.id}),t}async setZoomFactor(t,e){return await this.execute("setZoomFactor",{windowId:t.id,options:{zoomFactor:e}}),t}async showDevTools(t){return await this.execute("showDevTools",{windowId:t.id}),t}async capture(t,e){return(await this.execute("captureScreenshot",{windowId:t.id,options:{...e}})).data}async captureGroup(t,e){return(await this.execute("captureGroupScreenshot",{windowId:t[0],options:{groupWindowIds:t,...e}})).data}async flash(t,e){return await this.execute("flash",{windowId:t.id,options:{...e}}),t}async flashTab(t,e){return await this.execute("flashTab",{windowId:t.id,options:{...e}}),t}async configure(t,e){return this.execute("configure",{windowId:t,options:{...e}})}async print(t,e){return await this.execute("print",{windowId:t.id,options:{...e}}),t}async printToPDF(t,e){return(await this.execute("printToPDF",{windowId:t.id,options:{...e}})).filePath}async place(t,e){const n={...e};return e.display&&"current"!==e.display||(n.display=await t.getDisplay()),n.display&&"string"!=typeof n.display&&"number"!=typeof n.display&&(n.display=n.display.index+1),this.execute("place",{windowId:t.id,options:{...n}})}async refresh(t,e){return await this.execute("refresh",{windowId:t.id,options:{ignoreCache:e}}),t}async download(t,e,n={}){n.enableDownloadBar=!n.silent;const i=await this.execute("downloadURL",{windowId:t.id,options:{url:e,options:n}});return{url:e,path:i.fullPath,size:i.fileSize}}async configureWindow(t,e){return await this.execute("configureWindow",{windowId:t.id,options:e}),t}async getWindowConfiguration(t){return await this.execute("getWindowConfiguration",{windowId:t.id})}async startDrag(t,e){return await this.execute("startDrag",{windowId:t.id,options:e}),t}showDialog(t,e){return new Promise(((n,i)=>{const o=ii.generate(),r=this._registry.add("event",(e=>{if("DialogResult"===e.type&&e.windowId===t.id&&e.data.token===o){r();const t=e.data;"status"in t&&("failed"===t.status?i(t.message):"successful"===t.status&&n(t.result))}}));this.execute("showDialog",{windowId:t.id,options:Object.assign({},{...e},{token:o})})}))}async execute(t,e,...n){return this.executeCore(this.WndMethodName,t,e,...n)}async executeGroup(t,e,...n){return this.executeCore(this.GroupMethodName,t,e,...n)}async ungroup(t,e){const n={windowId:t.id,options:e};return await this.execute("ungroup",n),t}async updateJumpList(t,e){const n={windowId:t,options:e};await this.execute("updateJumplist",n)}async getJumpList(t){const e={windowId:t};return await this.execute("getJumplist",e)}onClosing(t,e){const n="undefined"!=typeof window&&window.glue42gd;return n&&"electron"===e.windowType?n.addCloseHandler(t,e.id):this.nonWindowHandlers(t,e.id,"OnClosing")}onRefreshing(t,e){const n="undefined"!=typeof window&&window.glue42gd;return n&&"electron"===e.windowType?n.addRefreshHandler(t,e.id):this.nonWindowHandlers(t,e.id,"OnRefreshing")}onNavigating(t,e){const n="undefined"!=typeof window&&window.glue42gd;return n&&"electron"===e.windowType?n.addWillNavigateHandler(t,e.id):this.nonWindowHandlers(t,e.id,"OnNavigating")}async goBack(t){await this.execute("goBack",{windowId:t.id})}async goForward(t){await this.execute("goForward",{windowId:t.id})}nonWindowHandlers(t,e,n){const i=`${e}-${n}`,o=()=>{if(this.unsubCallbacks[i]){const e=this.unsubCallbacks[i];this.unsubCallbacks[i]=e.filter((e=>e!==t))}0===this.unsubCallbacks[i].length&&this.execute(n,{windowId:e,options:{unsubscribe:!0}})};if(this.unsubCallbacks[i])return this.unsubCallbacks[i].push(t),o;this.unsubCallbacks[i]=[t];const r={windowId:e};return this.execute(n,r),o}reformatFlydownOptions(t,e){const n=(t,n)=>{if(e[n]&&(void 0===t[n]||null===t[n])){const i=e[n];t[n]=i}},i=e.zones.map((t=>(n(t,"windowId"),n(t,"targetLocation"),!e.size||void 0!==t.flydownSize&&null!==t.flydownSize||(t.flydownSize=e.size),t.flydownBounds=t.flydownSize,t.flydownId=t.windowId,t.targetLocation||(t.targetLocation="bottom"),t)));return{...e,zones:i,targetId:t,flydownBounds:e.size,flydownActiveArea:e.activeArea}}clearFlydownArea(t,e){return this.execute("clearFlydownWindowArea",{windowId:t,options:{}}).then((()=>{e.forEach((e=>{this._registry.clearKey(`${t}_${e}`)}))}))}executeWithoutToken(t,...e){const n=[],i=null==e?void 0:e.filter((t=>!Me(t))).map((e=>new Promise((i=>{const[o,r=t.windowId]=e.split("-");n.push(this._registry.add("event",(t=>{t.type===o&&t.windowId===r&&i()})))})))),o=new Promise(((e,n)=>{this.agm.invoke("T42.Wnd.Execute",t,this.agmTarget).then((t=>{t.returned&&t.returned.errorMsg?n(t):e(t.returned)})).catch((t=>n(t)))}));return Promise.all([o,...i]).then((t=>t[0])).finally((()=>{n.forEach((t=>t()))}))}async executeCore(t,e,n,...i){const o={...n,command:e};let r;this._finished=new Promise((t=>{r=t}));try{return"undefined"!=typeof window&&window.glueDesktop.versionNum<31200?await this.executeWithoutToken(o,...i):await this.executeWithToken(t,o)}finally{r()}}async executeWithToken(t,e){let n;try{const i=ii.generate(),o=new Promise((t=>{n=this._registry.add("event",(e=>{e.token===i&&t()}))})),r=new Promise(((n,o)=>{e.token=i,this.agm.invoke(t,e,this.agmTarget).then((t=>{t.returned&&t.returned.errorMsg?o(t):n(t.returned)})).catch((t=>{o(t)}))}));return(await Promise.all([r,o]))[0]}catch(t){throw t}finally{n&&n()}}areBoundsEqual(t,e){const n=e.bounds,i=e.settings;let o=t.height,r=t.width;t.height<i.minHeight&&(o=i.minHeight),t.height>i.maxHeight&&(o=i.maxHeight),t.width<i.minWidth&&(r=i.minWidth),t.width>i.maxWidth&&(r=i.maxWidth);const s=!o||n.height===o,a=!r||n.width===r,c=!t.left||n.left===t.left,d=!t.top||n.top===t.top;return s&&a&&c&&d}swapUndefinedToNull(t){try{const e={};for(const n of Object.keys(t)){let i=t[n];void 0===i&&(i=null),e[n]=i}return e}catch{return t}}};class fi{constructor(t,e,n,i,o,r){this._registry=xn(),this._waitTimeout=1e4,this._agm=t,this._logger=e.subLogger("gd-env"),this._windowId=r,this._appManagerGetter=n,this._displayAPIGetter=i,this._channelsAPIGetter=o}init(){return new Promise(((t,e)=>{this._agm.register("T42.Wnd.OnEventWithResponse",((t,e)=>this.respondToEvent(t))),new Promise(((n,i)=>{this._agm.subscribe("T42.Wnd.OnEvent",{waitTimeoutMs:this._waitTimeout,target:"best",arguments:{withConfig:!0},onData:e=>{"Configuration"!==e.data.type?(this.updateWindow(e.data,t),gi.handleEvent(e.data),gi.init(this._agm,this._agmInstance,this._configuration)):this._configuration=e.data},onConnected:t=>{this._agmInstance=t,gi.init(this._agm,this._agmInstance)}}).catch((t=>{var n;const i=`${null===(n=null==t?void 0:t.method)||void 0===n?void 0:n.name} - ${JSON.stringify(null==t?void 0:t.called_with)} - ${null==t?void 0:t.message}`;e(new Error(i))}))}))}))}get executor(){return gi}open(t,e,n){n=n||{};const i={...n};return void 0!==i.relativeTo&&"string"!=typeof i.relativeTo&&(i.relativeTo=i.relativeTo.id||""),i.name=t,i.url=e,i.windowState=n.windowState||n.state,delete i.state,this.executor.open(i)}createFlydown(t,e){return this.executor.createFlydown(t,e)}async showPopup(t,e){const n=si.get(t);await this.executor.showPopup(n.API,e)}tabAttached(t){return this._registry.add("tab-attached",t)}tabDetached(t){return this._registry.add("tab-detached",t)}onWindowFrameColorChanged(t){return this._registry.add("frame-color-changed",t)}onEvent(t){return this._registry.add("window-event",t)}my(){return this._windowId}execute(t,e,n){return this._agm.invoke("T42.Wnd.Execute",{command:t,options:n,windowId:e})}onCompositionChanged(t){return this._registry.add("composition-changed",t)}onGroupHeaderVisibilityChanged(t){return this._registry.add("group-header-changed",t)}onGroupVisibilityChanged(t){return this._registry.add("group-visibility-changed",t)}onGroupStateChanged(t){return this._registry.add("group-state-changed",t)}onWindowGotFocus(t){return this._registry.add("got-focus",t)}onWindowLostFocus(t){return this._registry.add("lost-focus",t)}respondToEvent(t){return"ShowFlydownBoundsRequested"===t.type?this.executor.handleFlydownBoundsRequested(t.data.windowId,t.data):"OnClosing"===t.type||"OnRefreshing"===t.type||"OnNavigating"===t.type?this.executor.handleOnEventRequested(t.data.callbackId,t.data.args):Promise.reject(`There isn't a handler for ${t.type}`)}updateWindow(t,e){var n;const i=this.getExtendedStreamEvent(t);if("Snapshot"===t.type){return t.windows.forEach((t=>{const e=si.get(t.id);if(e)e.Events.handleUpdate(this.mapToWindowConstructorOptions(t));else{const e=this.createWindow(t.id,t);si.markReadyToShow(e.API.id)}this._registry.execute("window-event",i)})),void e(this)}if("CommandExecuted"===t.type)return void this._registry.execute("window-event",i);if("Created"===t.type){const e=t,n=this.createWindow(e.windowId,e.data||{});return si.setReadyState(n.API.id),void this._registry.execute("window-event",i)}if("OnGroupVisibilityChanged"===t.type){const e=t;return this._registry.execute("group-visibility-changed",e.data),void this._registry.execute("window-event",t)}if("OnGroupStateChanged"===t.type){const e=t;return this._registry.execute("group-state-changed",e.data),void this._registry.execute("window-event",t)}const o=si.get(t.windowId);if(!o)return void this._logger.error(`received update for unknown window. Stream:', ${JSON.stringify(t,null,4)}`);const r=o.API,s=o.Events;if("BoundsChanged"===t.type){const e=t;s.handleBoundsChanged(e.data)}if("UrlChanged"===t.type){const e=t;si.setUrlChangedState(e.windowId),s.handleUrlChanged(e.data)}if("TitleChanged"===t.type){const e=t;s.handleTitleChanged(e.data)}if("IsStickyChanged"===t.type){const e=t;s.handleIsStickyChanged(e.data)}if("VisibilityChanged"===t.type&&s.handleVisibilityChanged(t.data),"ContextChanged"===t.type&&s.handleContextUpdated(t.data),"StateChanged"===t.type&&s.handleWindowChangeState(t.data),"FrameColorChanged"===t.type&&(s.handleFrameColorChanged(t.data),this._registry.execute("frame-color-changed",r)),"CompositionChanged"===t.type){const e=t;s.handleCompositionChanged(e.data),si.setCompositionChangedState(e.data.windowId,null===(n=this._configuration)||void 0===n?void 0:n.windowAvailableOnURLChanged),this._registry.execute("composition-changed",e.data)}if("GroupHeaderVisibilityChanged"===t.type){const e=t;s.handleGroupHeaderVisibilityChanged(e.data.groupHeaderVisible),this._registry.execute("group-header-changed",e.data)}if("FocusChanged"===t.type){const e=t;this.focusChanged(s,r,e.data)}if("WindowFrameChanged"===t.type&&(s.handleFrameAttached(t.data.frameId,t.data.frameId,t.data.isTabHeaderVisible),this._registry.execute("frame-changed")),"WindowFrameAdded"===t.type){const e=li(r.id,t.data.frameId),n=t.data;s.handleAttached(n.frameId,n.frameId,n.isTabHeaderVisible,n.isLocked,e).then((async()=>{e.length>0&&(await gi.finished,this._registry.execute("tab-attached",r,t.data.frameId,t.data.isTabHeaderVisible))}))}if("WindowFrameRemoved"===t.type){const e=r.tabGroupId,n=li(r.id,e);s.handleDetached(t.data.isLocked,n).then((async()=>{n.length>0&&(await gi.finished,this._registry.execute("tab-detached",r,t.data.frameId,r.tabGroupId))}))}"TabHeaderVisibilityChanged"===t.type&&s.handleTabHeaderVisibilityChanged(t.data.isTabHeaderVisible),"FrameSelectionChanged"===t.type&&s.handleFrameSelectionChanged(t.data.newWindowId,t.data.prevWindowId),"ButtonClicked"===t.type&&s.handleFrameButtonClicked(t.data),"ButtonAdded"===t.type&&s.handleFrameButtonAdded(t.data),"ButtonRemoved"===t.type&&s.handleFrameButtonRemoved(t.data),"WindowZoomFactorChanged"===t.type&&s.handleZoomFactorChanged(t.data),"Closed"===t.type&&(si.remove(o),s.handleWindowClose()),"FrameIsLockedChanged"===t.type&&s.handleFrameIsLockedChanged(t.data),"PlacementSettingsChanged"===t.type&&s.handlePlacementSettingsChanged(t.data),this._registry.execute("window-event",i)}createWindow(t,e){const n=hi(t,this.mapToWindowConstructorOptions(e),gi,this._logger,this._appManagerGetter,this._displayAPIGetter,this._channelsAPIGetter,this._agm);return si.add(n),n}async focusChanged(t,e,n){t.handleFocusChanged(n),await si.waitFor(e.id),n?this._registry.execute("got-focus",e):this._registry.execute("lost-focus",e)}mapToWindowConstructorOptions(t){return{name:t.name,context:t.context,bounds:t.bounds,url:t.url,title:t.title,isVisible:t.isVisible,focus:t.isFocused,state:t.state,frameColor:t.frameColor,groupId:t.groupId,neighbours:t.neighbors,isFocused:t.isFocused,isGroupHeaderVisible:t.groupHeaderVisible,isCollapsed:t.isCollapsed,tabGroupId:t.frameId,frameId:t.frameId,mode:t.mode,isTabHeaderVisible:t.isTabHeaderVisible,isTabSelected:t.isActiveTab,settings:t.settings,windowType:t.windowType,zoomFactor:t.zoomFactor,isLocked:t.isLocked,placementSettings:t.placementSettings,isSticky:t.isSticky,tabIndex:t.tabIndex,frameButtons:t.frameButtons,jumpListOptions:t.jumpList,applicationName:t.applicationName}}getExtendedStreamEvent(t){try{if(!t.windowId)return t;const e=si.get(t.windowId);if(!e)return t;const n={state:t.type,windowName:e.API.name,...t};return"WindowFrameAdded"===n.state&&(n.state="TabAttached"),"StateChanged"===n.state&&(n.state=n.data.charAt(0).toUpperCase()+n.data.slice(1)),"ButtonAdded"===n.state&&(n.state="FrameButtonAdded"),"ButtonRemoved"===n.state&&(n.state="FrameButtonRemoved"),n}catch(e){return t}}}var yi=(t,e)=>{const n=xn(),i=[];let o=!1,r=!0;async function s(t,n,...i){return await e.execute(t,n,...i),d}function a(){const t=[];return i.forEach((e=>{const n=c(e);void 0!==n&&t.push(n)})),t}function c(t){return si.get(t)?si.get(t).API:void 0}const d={id:t,get windows(){return function(t){const e=a();return"function"==typeof t&&t(e),e}()},find:function(t,e,n){let i;"string"==typeof t?i=t:Me(t)||(i=t.id);const o=c(i);if(o)return"function"==typeof e&&e(o),o;"function"==typeof n&&n(`No window with ID: ${i}`)},get isHeaderVisible(){return void 0===a().find((t=>!t.isGroupHeaderVisible))},get isHibernated(){return o},get isVisible(){return r},showHeader:(t,e)=>ai.callbackifyPromise((()=>s("setGroupHeaderVisibility",{windowId:i[0],options:{toShow:!0}},...i.map((t=>`GroupHeaderVisibilityChanged-${t}`)))),t,e),hideHeader:(t,e)=>ai.callbackifyPromise((()=>s("setGroupHeaderVisibility",{windowId:i[0],options:{toShow:!1}},...i.map((t=>`GroupHeaderVisibilityChanged-${t}`)))),t,e),getTitle:async()=>(await e.execute("getGroupTitle",{windowId:i[0]})).title,setTitle:async t=>{if(Re(t))throw new Error("`title` must not be null or undefined.");return s("setGroupTitle",{windowId:i[0],options:{title:t}})},capture:t=>e.captureGroup(i,t),maximize:(t,e)=>ai.callbackifyPromise((()=>s("maximizeGroup",{windowId:i[0]},...i.map((t=>`StateChanged-${t}`)))),t,e),restore:(t,e)=>ai.callbackifyPromise((()=>s("restoreGroup",{windowId:i[0]},...i.map((t=>`StateChanged-${t}`)))),t,e),show:n=>{if(!Me(n)&&!Ne(n))throw new Error("Activate flag must be a boolean!");return n=!!Me(n)||n,e.executeGroup("showGroup",{groupId:t,options:{activate:n}})},hide:()=>e.executeGroup("hideGroup",{groupId:t}),onHeaderVisibilityChanged:function(t){return n.add("header-visibility-changed",t)},onWindowAdded:function(t){return n.add("window-added",t)},onWindowRemoved:function(t){return n.add("window-removed",t)},onVisibilityChanged:function(t){if(!t)throw new Error("Callback argument is required");if(t&&"function"!=typeof t)throw new Error("Callback argument must be a function");return n.add("group-visibility-changed",t)}};return{groupAPI:d,groupInternal:{get windows(){return i},addWindow:async function(t){if(-1===i.indexOf(t)){i.push(t);const o=si.get(t);o.Events.handleGroupChanged(d,void 0),await e.finished,n.execute("window-added",d,o.API)}},removeWindow:async function(t){const o=i.indexOf(t.API.id);-1!==o&&(i.splice(o,1),t.Events.handleGroupChanged(void 0,d),await e.finished,n.execute("window-removed",d,t.API))},handleGroupHeaderVisibilityChanged:function(t){n.execute("header-visibility-changed",d)},handleGroupVisibilityChanged:function(t){r=t,n.execute("group-visibility-changed",d)},handleGroupHibernateChanged:function(t){o=t}}}},mi=(t,e)=>{const n=xn(),i={};let o=-1;const r=si.list;function s(t,e,n){let o;"string"==typeof t?o=t:Me(t)||(o=t.id);const r=Object.values(i).find((t=>t.groupAPI.windows.filter((t=>t.id===o)).length));if(r)return"function"==typeof e&&e(r.groupAPI),r.groupAPI;"function"==typeof n&&n("Cannot find the group of the window.")}function a(t){return n.add("group-added",t)}function c(e,o){const r=function(e){if(i.hasOwnProperty(e))return i[e];{const o=yi(e,t.executor);i[e]=o;const r=o.groupAPI;return n.execute("group-added",r),o}}(e);return r.groupInternal.addWindow(o),r}function d(t,e){t&&(t.groupInternal.removeWindow(e),function(t){const e=t.groupAPI;0===e.windows.length&&(delete i[e.id],n.execute("group-removed",e))}(t))}function u(t){let e;return"string"==typeof t?e=t:Me(t)||(e=t.id),Object.values(i).find((t=>t.groupInternal.windows.filter((t=>t===e)).length))}Object.keys(r).forEach((t=>{const e=r[t],n=e.API.groupId,i=e.API.id;Re(n)||c(n,i)})),si.onRemoved((t=>{d(u(t.API),t)})),t.onCompositionChanged((t=>{!function(t){const e=t.groupId,o=t.windowId,r=si.get(o);if(!r)return;const s=u(r.API);if(Me(e))return void d(s,r);if(Me(s)&&!Me(e))return void c(e,r.API.id);s.groupAPI.id!==e&&function(t,e,o){const r=t.API.id,s=i[e];d(s,t);const a=c(o,r);t.Events.handleGroupChanged(a.groupAPI,s.groupAPI),n.execute("window-moved",r,e,o)}(r,s.groupAPI.id,e)}(t)})),t.onGroupHeaderVisibilityChanged((t=>{const e=s(t.windowId);if(void 0!==e){const n=i[e.id];-1===o&&(o=e.windows.length),o--,0===o&&(o=-1,n.groupInternal.handleGroupHeaderVisibilityChanged(t))}})),t.onGroupVisibilityChanged((t=>{const e=i[t.groupId];e&&e.groupInternal.handleGroupVisibilityChanged(t.visible)})),t.onGroupStateChanged((t=>{const e=i[t.groupId];"hibernated"===t.state?(e&&e.groupAPI&&e.groupInternal.handleGroupHibernateChanged(!0),n.execute("group-hibernated",t.groupId)):"resumed"===t.state&&(e&&e.groupAPI&&e.groupInternal.handleGroupHibernateChanged(!1),n.execute("group-resumed",e.groupAPI))}));return{groupsAPI:{get my(){return s(t.my())},list:function(t){const e=Object.keys(i).map((t=>{if(i[t])return i[t].groupAPI}));return"function"==typeof t&&t(e),e},findGroupByWindow:s,waitForGroup:function(t){return t?new Promise(((e,n)=>{const o=i[t];if(o)e(o.groupAPI);else{const n=a((i=>{i.id===t&&(n(),e(i))}))}})):Promise.reject("groupId must be defined")},onGroupAdded:a,onGroupRemoved:function(t){return n.add("group-removed",t)},hibernate:async function(t){return await gi.executeGroup("hibernateGroup",{groupId:t}),t},resume:async function(t,e){if(!Me(e)&&!Ne(e))throw new Error("Activate flag must be a boolean!");e=!!Me(e)||e,await gi.executeGroup("resumeGroup",{groupId:t,options:{activate:e}})},onHibernated:function(t){if(!t)throw new Error("Callback argument is required");if(t&&"function"!=typeof t)throw new Error("Callback argument must be a function");return n.add("group-hibernated",t)},onResumed:function(t){if(!t)throw new Error("Callback argument is required");if(t&&"function"!=typeof t)throw new Error("Callback argument must be a function");return n.add("group-resumed",t)}},groupsEvents:{onWindowMoved:function(t){return n.add("window-moved",t)}}}},vi=(t,e,n,i,o,r)=>{const s=xn(),a=e;let c,d;si.init(a);const u=new Promise(((e,s)=>{((t,e,n,i,o,r)=>{const s=e;if(2===r)throw s.trace("running in HC"),new Error("GD2 not supported");return r>=3?(s.trace("running in GD 3"),new fi(t,s,n,i,o,window.glue42gd.windowId).init()):new fi(t,s,n,i,o).init()})(t,a,n,i,o,r).then((n=>{d=n,c=mi(n),ri.init(n.executor,t,a),e()})).catch((t=>{const e=`Timed out waiting for connection to Glue42 Enterprise: Error: ${t.message}`;a.error(e,t),s(new Error(e))}))}));function h(){const t=si.getIfReady(d.my());return t?t.API:void 0}function l(t){return s.add("window-added",t)}function p(t){return s.add("window-removed",t)}return si.onReadyWindow((function(t){s.execute("window-added",t.API)})),si.onRemoved((function(t){s.execute("window-removed",t.API)})),{my:h,open:function(t,e,n,i,o){return ai.callbackifyPromise((()=>{if(Re(t))throw new Error("The window name is missing.");if(Re(e))throw new Error("The window URL is missing.");if(!Me(n)){const t=n;for(const e of["minHeight","maxHeight","minWidth","maxWidth","width","height","top","left"])if(e in t){const n=t[e];if(Me(n)){delete t[e];continue}if(!xe(n)){throw new Error(`${e} must be a number`)}if(("width"===t[e]||"height"===t[e])&&n<=0){throw new Error(`${e} must be a positive number`)}}}return d.open(t,e,n)}),i,o)},find:function(t,e,n){const i=si.list,o=Object.keys(i).reduce(((e,n)=>{var o;const r=i[n];return(null===(o=null==r?void 0:r.API)||void 0===o?void 0:o.name)===t&&e.push(r.API),e}),[]);if(o[0])return"function"==typeof e&&e(o[0]),o[0];"function"==typeof n&&n("There is no window with name:"+t)},findById:function(t,e,n){const i=si.list,o=Object.keys(i).reduce(((e,n)=>{const o=i[n];return void 0!==o&&o.API.id===t&&e.push(o.API),e}),[]);if(o[0])return"function"==typeof e&&e(o[0]),o[0];"function"==typeof n&&n("There is no window with such id:"+t)},list:function(t){const e=si.list,n=Object.keys(e).map((t=>e[t].API));if("function"!=typeof t)return n;t(n)},ready:function(){return u},onWindowAdded:l,windowAdded:l,onWindowRemoved:p,windowRemoved:p,onTabAttached:function(t){let e,n=!1;return u.then((()=>{n||(e=d.tabAttached(t))})),()=>{n=!0,e&&e()}},onTabDetached:function(t){let e,n=!1;return u.then((()=>{n||(e=d.tabDetached(t))})),()=>{n=!0,e&&e()}},onWindowFrameColorChanged:function(t){let e,n=!1;return u.then((()=>{n||(e=d.onWindowFrameColorChanged(t))})),()=>{n=!0,e&&e()}},get groups(){return c.groupsAPI},onWindowGotFocus:function(t){let e,n=!1;return u.then((()=>{n||(e=d.onWindowGotFocus(t))})),()=>{n=!0,e&&e()}},onWindowLostFocus:function(t){let e,n=!1;return u.then((()=>{n||(e=d.onWindowLostFocus(t))})),()=>{n=!0,e&&e()}},onEvent:function(t){let e,n=!1;return u.then((()=>{n||(e=d.onEvent(t))})),()=>{n=!0,e&&e()}},createFlydown:function(t,e){return d.createFlydown(t,e)},showPopup:function(t,e){return d.showPopup(t,e)},configure:function(t){const e=h(),n=e?e.id:"";return gi.configure(n,t)}}};var wi=new class{constructor(){this.layouts=[]}removeWhere(t){this.layouts=this.layouts.filter(t)}removeAll(){this.layouts=[]}add(t){this.layouts.push(t)}get all(){return this.layouts}where(t){return this.layouts.filter(t)}first(t){return this.where(t)[0]}};class bi{constructor(t,e,n,i){this.config=t,this.activitiesGetter=e,this.callbacks=n,this.logger=i,this.interop=t.agm,this.registerRequestMethods()}onSaveRequested(t){return this.callbacks.add("saveRequested",t)}isActivityOwner(){if("undefined"!=typeof htmlContainer){const t=htmlContainer.getContext();return t&&t._t42&&t._t42.activityIsOwner}const t=this.activitiesGetter();if(!t)return!1;if(!t.inActivity)return!1;const e=t.my.window,n=t.my.activity;return!(!n&&!e)&&n.owner.id===e.id}registerRequestMethods(){this.interop.register("T42.HC.GetSaveContext",(t=>{const e=this.callbacks.execute("saveRequested",t);(null==e?void 0:e.length)>1&&this.logger.warn('Multiple subscriptions for "glue.layouts.onSaveRequested" - only the first one will be used');const n=e[0],i=this.config.autoSaveWindowContext;if("boolean"==typeof i&&i)return{autoSaveWindowContext:i};if(Array.isArray(i)&&i.length>0)return{autoSaveWindowContext:i};const o={windowContext:null==n?void 0:n.windowContext,activityContext:void 0};return this.isActivityOwner()&&(o.activityContext=null==n?void 0:n.activityContext),o}))}}function _i(t){if(!t)return t;if(Array.isArray(t))return t.map((t=>_i(t)));if("string"==typeof t||"number"==typeof t||"boolean"==typeof t)return t;return Object.keys(t).reduce(((e,n)=>{var i;const o=_i(t[n]);let r=n;return(null===(i=n[0])||void 0===i?void 0:i.toLowerCase())!==n[0]&&(r=n[0].toLowerCase()+n.substr(1)),e[r]=o,e}),{})}class Ii{constructor(t){this.name=t.name,this.type=t.type,this.components=t.components,this.context=t.context,this.metadata=t.metadata,this.version=t.version,this.displays=t.displays}}const Ci="T42.ACS.Command";class Ai{constructor(t,e,n,i){this.config=t,this.stream=e,this.callbacks=n,this.isRegisterMethodForLayoutModified=!1,this.appManager=t.appManager,this.provider=new bi(t,t.activityGetter,n,i),e.subscribe()}async setDefaultGlobal(t){await this.invokeMethodCore("SelectDefaultLayout",{name:t})}async clearDefaultGlobal(){this.invokeMethodCore("DeselectDefaultLayout")}async getDefaultGlobal(){const t=(await this.invokeMethodCore("GetDefaultLayout")).returned;if(t)return this.isSlimMode()?t:this.list().find((e=>e.name===t.name&&"Global"===e.type))}ready(){return"fullWaitSnapshot"===this.config.mode?this.stream.gotSnapshot:this.stream.ready}save(t){return new Promise(((e,n)=>{var i,o;if(this.verifyNotSlimMode(),Me(t))return n(new Error("layout is required"));if(Re(t.name))return n(new Error("layout.name argument is required"));Re(t.type)&&(t.type="Global"),Re(t.activityId)||(t.type="Activity");const r={name:t.name,type:t.type,context:null!==(i=t.context)&&void 0!==i?i:{},metadata:null!==(o=t.metadata)&&void 0!==o?o:{},options:{}};if("Activity"===t.type){let e=t.activityId;if(!e){if(!this.appManager.myInstance.inActivity)return n(new Error("Current application is not in activity. Cannot save activity layout for it."));e=this.appManager.myInstance.activityId}r.activityId=e}else{if("Global"!==t.type)return n(new Error(`layout type ${t.type} is not supported`));Array.isArray(t.ignoreInstances)&&(r.options.ignoreInstances=t.ignoreInstances),Array.isArray(t.instances)&&(r.options.instances=t.instances)}this.invokeMethodAndTrack("SaveLayout",r,e,n)}))}restore(t){return new Promise(((e,n)=>{var i,o,r;if(this.verifyNotSlimMode(),Me(t))return n(new Error("options argument is required"));if(Re(t.name))return n(new Error("options.name argument is required"));if(Re(t.type)&&(t.type="Global"),Re(t.activityIdToJoin)||(t.type="Activity"),"Activity"===t.type){if(Me(t.setActivityContext)&&(t.setActivityContext=!0),"boolean"!=typeof t.setActivityContext)return n(new Error("`setActivityContext` must hold a boolean value."));t.activityIdToJoin=null!==(i=t.activityIdToJoin)&&void 0!==i?i:this.appManager.myInstance.activityId}if(Me(t.closeRunningInstance)||(t.closeRunningInstances=t.closeRunningInstance),Me(t.closeRunningInstances)&&(t.closeRunningInstances=!0),!Ne(t.closeRunningInstances))return n(new Error("`closeRunningInstances` must hold a boolean value."));if(Me(t.closeMe)&&(t.closeMe=t.closeRunningInstances),!Ne(t.closeMe))return n(new Error("`closeMe` must hold a boolean value."));if(!Me(t.context)&&!Te(t.context))return n(new Error("`context` must hold an object value."));if(!Me(t.timeout)&&"number"!=typeof t.timeout)return n(new Error("`timeout` must hold an number value."));t.context=null!==(o=t.context)&&void 0!==o?o:{};const s={activityToJoin:t.activityIdToJoin,setActivityContext:t.setActivityContext,ignoreActivityWindowTypes:t.ignoreActivityWindowTypes,reuseExistingWindows:t.reuseWindows,closeRunningInstances:t.closeRunningInstances,excludeFromClosing:t.closeMe?[]:[null===(r=this.appManager.myInstance)||void 0===r?void 0:r.id]},a={type:t.type,name:t.name,context:t.context,options:s};t.timeout&&(a.timeout=t.timeout),this.invokeMethodAndTrack("RestoreLayout",a,e,n,!0)}))}remove(t,e){return new Promise(((n,i)=>{if(this.verifyNotSlimMode(),!e)return i(new Error("name argument is required"));if(!t)return i(new Error("type argument is required"));const o={type:t,name:e};this.invokeMethodAndTrack("RemoveLayout",o,n,i)}))}list(){return this.verifyNotSlimMode(),wi.all}import(t,e){return new Promise(((n,i)=>{if(this.verifyNotSlimMode(),!Me(e)&&"merge"!==e&&"replace"!==e)return i(new Error(`${e} is not supported - only "merge" and "replace"`));if(!Array.isArray(t))return i(new Error("layouts arguments is not an array"));const o={mode:e||"replace",layouts:t};this.invokeMethodAndTrack("ImportLayouts",o,n,i,!0)}))}export(t){return new Promise(((e,n)=>{this.invokeMethodAndTrack("ExportLayouts",{},(n=>{let i=this.getObjectValues(n.Layouts).map((t=>new Ii(_i(t))));t&&(i=i.filter((e=>e.type===t))),e(i)}),n,!0)}))}rename(t,e){return new Promise(((n,i)=>{if(this.verifyNotSlimMode(),!t)return i(new Error("layout argument is required"));if(!t.name)return i(new Error("name argument is required"));if(!t.type)return i(new Error("type argument is required"));const o={type:t.type,oldName:t.name,newName:e};this.invokeMethodAndTrack("RenameLayout",o,n,i)}))}updateMetadata(t){return new Promise(((e,n)=>{if(!t)return n(new Error("layout argument is required"));if(!t.name)return n(new Error("name argument is required"));if(!t.type)return n(new Error("type argument is required"));if(!t.metadata)return n(new Error("metadata argument is required"));const i={name:t.name,type:t.type,metadata:t.metadata};this.invokeMethodAndTrack("UpdateMetadata",i,e,n,!0)}))}hibernate(t,e){return new Promise(((n,i)=>{if(!t)return i(new Error("name cannot be empty"));const o={name:t,type:"Global",context:(e=e||{}).context||{},metadata:e.metadata||{}};this.invokeMethodAndTrack("HibernateLayout",o,n,i,!0)}))}resume(t,e,n){return new Promise(((i,o)=>{if(!t)return o(new Error("name cannot be empty"));const r={name:t,type:"Global",context:e,...n};this.invokeMethodAndTrack("ResumeLayout",r,i,o,!0)}))}async getCurrentLayout(){let t=(await this.invokeMethodCore("GetCurrentLayout")).returned.layout;if(t)return this.isSlimMode()||(t=this.list().find((e=>e.name===t.name&&e.type===t.type))),t}onAdded(t){const e=this.callbacks.add("added",t);return wi.all.length>0&&wi.all.forEach((e=>{try{t(e)}catch(t){}})),e}onRemoved(t){return this.callbacks.add("removed",t)}onChanged(t){return this.callbacks.add("changed",t)}onRestored(t){return this.callbacks.add("restored",t)}onRenamed(t){return this.callbacks.add("renamed",t)}onEvent(t){return this.stream.onEvent(t)}onSaveRequested(t){return this.provider.onSaveRequested(t)}onLayoutModified(t){return!1===this.isRegisterMethodForLayoutModified&&(this.isRegisterMethodForLayoutModified=!0,this.registerMethodForLayoutModified()),this.callbacks.add("layout-modified",t)}updateAppContextInCurrent(t){return new Promise(((e,n)=>{if(t&&"object"!=typeof t)return n(new Error("context must be an object"));const i={context:t=null!=t?t:{}};this.invokeMethodAndTrack("UpdateLayoutComponentContext",i,e,n,!0)}))}updateDefaultContext(t){return new Promise(((e,n)=>{if(t&&"object"!=typeof t)return n(new Error("context must be an object"));const i={context:t=null!=t?t:{}};this.invokeMethodAndTrack("UpdateDefaultContext",i,e,n,!0)}))}async get(t,e){const n=this.list().find((n=>n.name===t&&n.type===e));if(!n)throw new Error(`cannot find layout with name=${t} and type=${e}`);return n}async getAll(t){return this.list().filter((e=>t===e.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",((t,e)=>{this.callbacks.execute("layout-modified",t)}))}invokeMethodAndTrack(t,e,n,i,o){let r,s=o;const a=ii();e.token=a;const c=()=>{s&&r&&n(r)},d=12e4;o||this.stream.waitFor(a,d).then((()=>{s=!0,c()})).catch((t=>{i(t)}));this.invokeMethodCore(t,e,"best",{methodResponseTimeoutMs:d}).then((e=>{if(!e.returned)return i(new Error("No result from method "+t));if(e.returned.status&&"Success"!==e.returned.status&&"PartialSuccess"!==e.returned.status){if("string"==typeof e.returned)return i(new Error(e.returned));if("object"==typeof e.returned)return e.returned.status&&e.returned.failed?i(new Error(`${e.returned.status}: ${JSON.stringify(e.returned.failed)}`)):i(new Error(e.returned))}r=e.returned,c()})).catch((t=>i(t)))}async invokeMethodCore(t,e,n,i){return this.isCommandMethodPresent()?await this.config.agm.invoke(Ci,{command:t,data:e},n,i):await this.config.agm.invoke(`T42.ACS.${t}`,e,n,i)}getObjectValues(t){return t?Object.keys(t).map((e=>t[e])):[]}isCommandMethodPresent(){return this.config.agm.methods().some((t=>t.name===Ci))}}class Si{constructor(t,e){this.agm=t,this.callbacks=e,this.StreamName="T42.ACS.OnLayoutEvent",this.ready=new Promise(((t,e)=>{this.resolveReady=t,this.rejectReady=e})),this.gotSnapshot=new Promise(((t,e)=>{this.resolveGotSnapshot=t,this.rejectGotSnapshot=e}))}subscribe(t){const e=t=>this.getObjectValues(t).map((t=>_i(t)));this.checkForLayoutEventMethod()?this.agm.subscribe(this.StreamName,{waitTimeoutMs:1e4}).then((t=>{t.onData((t=>{const n=t.data;n.IsSnapshot&&this.resolveGotSnapshot(),this.addLayouts(e(n.OnLayoutAdded),n.IsSnapshot),this.removeLayouts(e(n.OnLayoutRemoved)),this.changeLayouts(e(n.OnLayoutChanged)),this.renameLayouts(e(n.OnLayoutRenamed)),this.restoredLayout(e(n.OnLayoutRestored)),this.callbacks.execute("streamEvent",n)})),t.onFailed((t=>{const e=`Can not subscribe to "${this.StreamName}" stream - ${JSON.stringify(t)}`;this.rejectReady(e),this.rejectGotSnapshot(e)})),this.resolveReady()})).catch((t=>{const e=`Error subscribing to "${this.StreamName}" stream - ${JSON.stringify(t)}`;this.rejectReady(e),this.rejectGotSnapshot(e)})):(t&&this.resolveReady(),setTimeout((()=>{this.subscribe(!0)}),500))}onEvent(t){return this.callbacks.add("streamEvent",t)}waitFor(t,e){return e||(e=3e4),new Promise(((n,i)=>{let o=!1;const r=this.onEvent((e=>{e.Token===t&&(o=!0,r(),n())}));setTimeout((()=>{o||i("timed out")}),e)}))}checkForLayoutEventMethod(){try{return-1!==this.agm.methods().map((t=>t.name)).indexOf(this.StreamName)}catch(t){return!1}}addLayouts(t,e){if(!t)return;const n=t=>{const e=new Ii(t);wi.add(e),this.callbacks.execute("added",e)};t.forEach((t=>{if(e){wi.first((e=>this.compareLayouts(e,t)))||n(t)}else n(t)}))}removeLayouts(t){t&&t.forEach((t=>{wi.removeWhere((e=>!this.compareLayouts(e,t))),this.callbacks.execute("removed",t)}))}changeLayouts(t){t&&t.forEach((t=>{wi.removeWhere((e=>!this.compareLayouts(e,t))),wi.add(new Ii(t)),this.callbacks.execute("changed",t)}))}renameLayouts(t){t&&t.forEach((t=>{const e=wi.first((e=>this.compareLayouts(e,{type:t.type,name:t.oldName})));if(!e)throw Error(`received rename event for unknown layout with type ${t.type} and name ${t.oldName}`);e.name=t.newName,this.callbacks.execute("renamed",e)}))}compareLayouts(t,e){return t.name===e.name&&t.type===e.type}getObjectValues(t){return t?Object.keys(t).map((e=>t[e])):[]}restoredLayout(t){t&&t.forEach((t=>{const e=wi.first((e=>this.compareLayouts(e,{type:t.type,name:t.name})));this.callbacks.execute("restored",e)}))}}function xi(t){if(!t.agm)throw Error("config.agm is required");if(!t.logger)throw Error("config.logger is required");t.mode=t.mode||"slim";const e=t.logger,n=xn();let i;return t.mode,i=new Si(t.agm,n),new Ai(t,i,n,e)}class ki{constructor(t,e){this._agm=t,this._logger=e,this._registry=xn(),this._registered=!1,this.all=async()=>(await this.callGD(Ti.GetAll,{})).map(this.decorateDisplay),this.get=async t=>{const e=await this.callGD(Ti.Get,{id:t});return this.decorateDisplay(e)},this.getPrimary=async()=>(await this.all()).find((t=>t.isPrimary)),this.capture=async t=>await this.callGD(Ti.Capture,{...t}),this.captureAll=async t=>await this.callGD(Ti.CaptureAll,{...t}),this.getMousePosition=async()=>await this.callGD(Ti.GetMousePosition),this.callGD=async(t,e)=>(await this._agm.invoke("T42.Displays.Command",{options:{...e},command:t})).returned.data,this.decorateDisplay=t=>{const e={...t,capture:e=>this.capture({id:t.id,size:e})},n=e.workArea;return n.x=n.left,n.y=e.workArea.top,e}}getByWindowId(t){return this.callGD(Ti.GetByWindowId,{id:t})}onDisplayChanged(t){return this.register(),this._registry.add("on-display-changed",t)}register(){this._registered||(this._registered=!0,this._agm.register("T42.Displays.OnEvent",((t,e)=>{const n=t.event,i=t.data;if("display-changed"===n)this._registry.execute("on-display-changed",i.displays.map(this.decorateDisplay));else this._logger.warn(`unknown event - ${n}`)})))}}var Ti;let Ei,Pi;!function(t){t.Capture="capture",t.CaptureAll="captureAll",t.GetAll="getAll",t.Get="get",t.GetByWindowId="getByWindowId",t.GetMousePosition="getMousePosition"}(Ti||(Ti={}));const Mi="T42.Channels.Announce";async function Ri(t,e){Ei.invoke("T42.Channels.Announce",{swId:null!=e?e:Pi,command:"switchChannel",data:{newChannel:t}})}async function Ni(t,e,n){await Ei.invoke(Mi,{command:t,data:{id:e,color:n}})}const ji="___channel___",Oi="latest_fdc3_type";class Wi{constructor(t){this.contexts=t}subscribe(t){this.callback=t}subscribeFor(t,e){if(!this.isChannel(t))return Promise.reject(new Error(`Channel with name: ${t} doesn't exist!`));const n=this.createContextName(t);return this.contexts.subscribe(n,((t,n,i,o,r)=>{e(t.data,t,null==r?void 0:r.updaterId)}))}async switchChannel(t){this.unsubscribe();const e=this.createContextName(t);this.unsubscribeFunc=await this.contexts.subscribe(e,((t,e,n,i,o)=>{this.callback&&this.callback(t.data,t,null==o?void 0:o.updaterId)}))}leave(){this.callback&&this.callback({},void 0),this.unsubscribe()}all(){return this.contexts.all().filter((t=>t.startsWith(ji))).map((t=>t.substr(13)))}async getContextData(t){if(!this.isChannel(t))throw new Error(`A channel with name: ${t} doesn't exist!`);const e=this.createContextName(t),n=await this.contexts.get(e);if(n[Oi]){const{latest_fdc3_type:t,...e}=n;return e}return n}updateChannel(t,e){const n=this.createContextName(t);return this.contexts.update(n,e)}updateData(t,e){const n=this.createContextName(t),i=this.getFDC3Type(e);if(this.contexts.setPathSupported){const t=Object.keys(e).map((t=>({path:"data."+t,value:e[t]})));return i&&t.push({path:Oi,value:i}),this.contexts.setPaths(n,t)}return i&&(e[Oi]=i),this.contexts.update(n,{data:e})}isChannel(t){return this.all().some((e=>e===t))}async remove(t){if(!this.isChannel(t))throw new Error(`A channel with name: ${t} doesn't exist!`);const e=this.createContextName(t);await this.contexts.destroy(e)}unsubscribe(){this.unsubscribeFunc&&this.unsubscribeFunc()}createContextName(t){return ji+t}getFDC3Type(t){const e=Object.keys(t).filter((t=>0===t.indexOf("fdc3_")));if(0!==e.length){if(e.length>1)throw new Error("FDC3 does not support updating of multiple context keys");return e[0].split("_").slice(1).join("_")}}}class Fi{constructor(t,e,n,i){this.shared=t,this.interop=e,this.getWindows=n,this.logger=i,this.subsKey="subs",this.changedKey="changed",this.isInitialJoin=!0,this.registry=xn(),this.pendingReplays={},this.shared.subscribe(this.handler.bind(this)),"undefined"!=typeof window&&void 0!==window.glue42gd&&(this.currentContext=window.glue42gd.initialChannel,this.currentContext&&this.joinNoSelectorSwitch(this.currentContext))}subscribe(t){if("function"!=typeof t)throw new Error("Please provide the callback as a function!");const e=ii();if(this.pendingReplays[e]=!0,this.lastUpdate){let n=Object.assign({},this.lastUpdate);setTimeout((()=>{this.pendingReplays[e]&&(this.lastUpdate&&(n=this.lastUpdate),t(n.context.data,n.context,n.updaterId)),delete this.pendingReplays[e]}),0)}const n=this.registry.add(this.subsKey,t);return()=>{this.pendingReplays[e]=!1,n()}}async subscribeFor(t,e){if("string"!=typeof t)throw new Error("Please provide the name as a string!");if("function"!=typeof e)throw new Error("Please provide the callback as a function!");return await this.shared.subscribeFor(t,e)}async publish(t,e){if("object"!=typeof t)throw new Error("Please provide the data as an object!");if(e){if("string"!=typeof e)throw new Error("Please provide the name as a string!");return this.shared.isChannel(e)?this.shared.updateData(e,t):Promise.reject(new Error(`A channel with name: ${e} doesn't exist!`))}if(!this.currentContext)throw new Error("Not joined to any channel!");return this.shared.updateData(this.currentContext,t)}all(){const t=this.shared.all();return Promise.resolve(t)}async list(){const t=await this.all();return await Promise.all(t.map((t=>this.get(t))))}get(t){return"string"!=typeof t?Promise.reject(new Error("Please provide the channel name as a string!")):this.shared.getContextData(t)}getMy(){return this.currentContext?this.get(this.currentContext):Promise.resolve(void 0)}async join(t,e){return e?Ri(t,e):this.joinCore(t)}async joinNoSelectorSwitch(t){return this.joinCore(t,!1)}leave(t){return t?Ri(void 0,t):this.leaveCore()}leaveNoSelectorSwitch(){return this.leaveCore(!1)}current(){return this.currentContext}my(){return this.current()}changed(t){if("function"!=typeof t)throw new Error("Please provide the callback as a function!");return this.current()&&setTimeout((()=>{t(this.current())}),0),this.registry.add(this.changedKey,t)}onChanged(t){return this.changed(t)}async add(t){if("object"!=typeof t)throw new Error("Please provide the info as an object!");if(void 0===t.name)throw new Error("info.name is missing!");if("string"!=typeof t.name)throw new Error("Please provide the info.name as a string!");if(void 0===t.meta)throw new Error("info.meta is missing!");if("object"!=typeof t.meta)throw new Error("Please provide the info.meta as an object!");if(void 0===t.meta.color)throw new Error("info.meta.color is missing!");if("string"!=typeof t.meta.color)throw new Error("Please provide the info.meta.color as a string!");const e={name:t.name,meta:t.meta||{},data:t.data||{}};return await this.shared.updateChannel(t.name,e),await Ni("addChannel",t.name,t.meta.color),e}async remove(t){if("string"!=typeof t)throw new Error("Please provide the channel name as a string!");await this.shared.remove(t),await Ni("removeChannel",t)}async getWindowsOnChannel(t){if("string"!=typeof t)throw new Error("Please provide the channel name as a string!");return(await this.getWindowsWithChannels({channels:[t]})).map((t=>t.window))}async getWindowsWithChannels(t){try{const e=await async function(t){return(await Ei.invoke(Mi,{command:"getChannelsInfo",data:{filter:t}})).returned}(t),n=this.getWindows();if(null==e?void 0:e.windows)return e.windows.map((t=>({window:n.findById(t.windowId),channel:t.channel,application:t.application})))}catch(t){this.logger.error("Error getting all channel enabled windows. This method is available since Glue42 3.12",t)}return[]}handler(t,e,n){e||n?(this.lastUpdate={context:e,updaterId:n},this.pendingReplays={},this.registry.execute(this.subsKey,t,e,n)):this.lastUpdate=void 0}async joinCore(t,e=!0){if("string"!=typeof t)throw new Error("Please provide the channel name as a string!");if(!this.isInitialJoin&&t===this.currentContext)return;this.isInitialJoin=!1;const n=t=>this.shared.all().includes(t);if(!n(t)){const e=new Promise(((e,i)=>{const o=setInterval((()=>{n(t)&&(clearTimeout(r),clearInterval(o),e())}),100),r=setTimeout((()=>(clearInterval(o),i(new Error(`A channel with name: ${t} doesn't exist!`)))),3e3)}));await e}this.currentContext=t,this.lastUpdate=void 0,await this.shared.switchChannel(t),e&&Ri(t),this.registry.execute(this.changedKey,t)}leaveCore(t=!0){return this.currentContext=void 0,this.registry.execute(this.changedKey,void 0),this.shared.leave(),t&&Ri(),Promise.resolve()}}function Li(t,e,n,i){const o=new Wi(t),r=new Fi(o,e,n,i),s=async function(t,e){Ei=t,"undefined"!=typeof window&&window.glue42gd&&(Pi=window.glue42gd.windowId),Pi&&(await Ei.register("T42.Channels.Command",(t=>{const n=t.command;if(!n)throw new Error("missing command argument");if("join"!==n){if("leave"!==n){if("get"===n)return{id:e.current()};throw new Error(`unknown command ${n}`)}e.leaveNoSelectorSwitch()}else{const n=t.channel;if(!n)throw new Error("missing argument id");e.joinNoSelectorSwitch(n)}})),await Ei.invoke("T42.Channels.Announce",{swId:Pi,instance:Ei.instance.instance}))}(e,r);return{subscribe:r.subscribe.bind(r),subscribeFor:r.subscribeFor.bind(r),publish:r.publish.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),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([t.ready(),s])}}}const Di="T42.Hotkeys.Command";class Gi{constructor(t){this.agm=t,this.registry=xn(),this.firstHotkey=!0,this.hotkeys=new Map}async register(t,e){if(void 0===t)throw new Error("Hotkey parameter missing");if("string"==typeof t)t={hotkey:t};else{if(!t.hotkey)throw new Error("Info's hotkey parameter missing");t={hotkey:t.hotkey,description:t.description}}const n=this.formatHotkey(t.hotkey);if(this.hotkeys.has(n))throw new Error(`Shortcut for ${n} already registered`);this.firstHotkey&&(this.firstHotkey=!1,await this.registerInvokeAGMMethod()),this.registry.add(n,e),await this.agm.invoke(Di,{command:"register",hotkey:n,description:t.description}),this.hotkeys.set(n,t)}async unregister(t){if(void 0===t)throw new Error("hotkey parameter missing");if("string"!=typeof t)throw new Error("hotkey parameter must be string");const e=this.formatHotkey(t);await this.agm.invoke(Di,{command:"unregister",hotkey:e}),this.hotkeys.delete(e),this.registry.clearKey(e)}async unregisterAll(){await this.agm.invoke(Di,{command:"unregisterAll"}),this.hotkeys.clear(),this.registry.clear()}isRegistered(t){const e=this.formatHotkey(t);return this.hotkeys.has(e)}registerInvokeAGMMethod(){return this.agm.register("T42.Hotkeys.Invoke",(t=>{const e=t.key.toLowerCase(),n=this.hotkeys.get(e);this.registry.execute(e,n)}))}formatHotkey(t){if(t)return t.replace(/\s/g,"").toLowerCase()}}var Bi="6.0.0",qi=t=>{function e(t,e,i){if("boolean"==typeof t&&!t)return;const o=n(t,e,i);return void 0!==o?"object"==typeof t?(t.mode=o,t):{mode:o}:void 0}function n(t,e,i){return"object"==typeof t?n(t.mode,e,i).toString():void 0===t?"boolean"!=typeof e||e?"boolean"==typeof e&&e?void 0===i?e:i:void 0===e?void 0:e:void 0:"boolean"==typeof t?t?void 0===i?e:i:void 0:t}const i=!ai.isNode()&&"trackMyTypeAndInitiatedFromMe",o="slim",r=o,s="boolean"==typeof t.exposeAPI||"boolean"==typeof t.exposeGlue;return{layouts:e(t.layouts,o,r),activities:e(t.activities,i,"trackMyTypeAndInitiatedFromMe"),appManager:e(t.appManager,!0,"startOnly"),windows:e(t.windows,!0,!0),channels:e(t.channels,!1,!0),displays:e(t.displays,!0,!0),exposeAPI:s||!0}};class Ui{constructor(t){this.options=t,this.callbacks=xn(),this.actions=t.actions,this.body=t.body,this.badge=t.badge,this.data=t.data,this.dir=t.dir,this.icon=t.icon,this.image=t.image,this.lang=t.lang,this.renotify=t.renotify,this.requireInteraction=t.requireInteraction,this.silent=t.silent,this.tag=t.tag,this.timestamp=t.timestamp,this.title=t.title}close(){throw new Error("Method not implemented.")}addEventListener(t,e,n){this.callbacks.add(t,e)}removeEventListener(t,e,n){}dispatchEvent(t){return this.callbacks.execute(t.type,t),!0}}class Hi{constructor(t,e){this.interop=t,this.onStreamEvent=e}onVisibilityChanged(t){return this.onStreamEvent("on-panel-visibility-changed",t)}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 $i{constructor(t,e){this.interop=t,this.logger=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-"+ii(),this.nextId=0,this.notifications={},this.registry=xn(),this.subscribedForNotifications=!1,this.subscribedCounterStream=!1,this.subscriptionsCountForNotifications=0,this.subscriptionsCountForCounter=0,this._panel=new Hi(t,this.onStreamEventCore.bind(this)),this.subscribeInternalEvents()}get maxActions(){return 2}get panel(){return this._panel.toAPI()}async raise(t){var e,n,i;if(this.validate(t),!this.methodsRegistered){const t=[];for(let e=0;e<this.maxActions;e++)t.push(this.interop.register(`${this.methodNameRoot}_${e}`,this.handleNotificationEvent.bind(this)));this.methodsRegistered=!0,await Promise.all(t)}const o=String(this.nextId++),r=null!==(e=t.type)&&void 0!==e?e:"Notification",s={title:t.title,type:r,severity:null!==(n=t.severity)&&void 0!==n?n:"None",description:t.body,glueRoutingDetailMethodName:`${this.methodNameRoot}_0`,actions:[],sourceId:o,source:t.source,publishExtraEvents:!0,clickInterop:t.clickInterop};t.actions&&this.handleActions(t,o,s),this.handleOptions(t,s);const a=new Ui(t);this.notifications[o]=a;try{const t=await this.interop.invoke(this.RaiseNotificationMethodName,{notification:s});a.id=null===(i=t.returned)||void 0===i?void 0:i.id}catch(t){const e=t.message;setTimeout((()=>{this.handleNotificationErrorEvent(a,e)}),1)}return a}async setFilter(t){return(await this.interop.invoke("T42.Notifications.Filter",t)).returned}async getFilter(){return(await this.interop.invoke("T42.Notifications.Filter")).returned}async configure(t){var e,n,i,o;if(!t||Array.isArray(t))throw new Error("Invalid options - should be an object.");if(0===Object.values(t).length)throw new Error("The argument must be a non-empty object.");if(void 0!==t.enable&&"boolean"!=typeof t.enable)throw new Error("Expected type of enabled - boolean.");if(void 0!==t.enableToasts&&"boolean"!=typeof t.enableToasts)throw new Error("Expected type of enableToasts - boolean.");if(void 0!==t.toastExpiry&&"number"!=typeof t.toastExpiry)throw new Error("Expected type of toastExpiry - number.");if(t.sourceFilter&&"object"!=typeof t.sourceFilter)throw new Error("Expected type of sourceFilter - object.");if((null===(e=t.sourceFilter)||void 0===e?void 0:e.allowed)&&!Array.isArray(null===(n=t.sourceFilter)||void 0===n?void 0:n.allowed))throw new Error("Expected type of sourceFilter.allowed - array.");if((null===(i=t.sourceFilter)||void 0===i?void 0:i.blocked)&&!Array.isArray(null===(o=t.sourceFilter)||void 0===o?void 0:o.blocked))throw new Error("Expected type of sourceFilter.blocked - array.");return(await this.interop.invoke(this.NOTIFICATIONS_CONFIGURE_METHOD_NAME,t)).returned}async getConfiguration(){return(await this.interop.invoke(this.NotificationsExecuteMethod,{command:"getConfiguration"})).returned}async list(){return(await this.interop.invoke(this.NotificationsExecuteMethod,{command:"list"})).returned.notifications}onRaised(t){return this.onStreamEventCore("on-notification-raised",t)}onStateChanged(t){return this.onStreamEventCore("on-state-changed",t)}onClosed(t){return this.onStreamEventCore("on-notification-closed",t)}onConfigurationChanged(t){if("function"!=typeof t)throw new Error("Please provide the callback as a function!");this.subscribe();const e=this.registry.add("on-configuration-changed",t);return()=>{e(),this.closeStreamSubscriptionIfNoNeeded()}}onCounterChanged(t){if("function"!=typeof t)throw new Error("Please provide the callback as a function!");this.subscribeForCounterStream();const e=this.registry.add("on-counter-changed",t);return()=>{e(),this.closeStreamCounterSubscriptionIfNoNeeded()}}async clearAll(){await this.interop.invoke(this.NotificationsExecuteMethod,{command:"clearAll"})}async clearOld(){await this.interop.invoke(this.NotificationsExecuteMethod,{command:"clearAllOld"})}async clear(t){if(!t)throw new Error("The 'id' argument cannot be null or undefined");if("string"!=typeof t)throw new Error("The 'id' argument must be a string");await this.interop.invoke(this.NotificationsExecuteMethod,{command:"clear",data:{id:t}})}async click(t,e){await this.interop.invoke(this.NotificationsExecuteMethod,{command:"click",data:{id:t,action:e}})}async setState(t,e){if(!t)throw new Error("The 'id' argument cannot be null or undefined");if("string"!=typeof t)throw new Error("The 'id' argument must be a string");if(!e)throw new Error("The 'state' argument cannot be null or undefined");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!`);await this.interop.invoke(this.NotificationsExecuteMethod,{command:"updateState",data:{id:t,state:e}})}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),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)}}onStreamEventCore(t,e){if("function"!=typeof e)throw new Error("Please provide the callback as a function!");this.subscribe();const n=this.registry.add(t,e);return()=>{n(),this.closeStreamSubscriptionIfNoNeeded()}}handleOptions(t,e){if(t.icon&&(e.attributes=e.attributes||[],e.attributes.push({key:"icon",value:{stringValue:t.icon}})),t.data){e.attributes=e.attributes||[];const n=JSON.stringify(t.data);e.attributes.push({key:"data",value:{stringValue:n}})}"number"==typeof t.panelExpiry&&(e.attributes=e.attributes||[],e.attributes.push({key:"panelExpiry",value:{stringValue:t.panelExpiry.toString()}})),"number"==typeof t.toastExpiry&&(e.attributes=e.attributes||[],e.attributes.push({key:"toastExpiry",value:{stringValue:t.toastExpiry.toString()}}))}handleActions(t,e,n){var i,o,r;const s=t.actions.slice(0,this.maxActions);let a=0;for(const t of s){const s={g42notificationId:e,g42action:t.action,g42interopMethod:null===(i=t.interop)||void 0===i?void 0:i.method,g42interopTarget:null===(o=t.interop)||void 0===o?void 0:o.target,g42interopArguments:JSON.stringify(null===(r=t.interop)||void 0===r?void 0:r.arguments)},c=Object.keys(s).map((t=>({name:t,value:{stringValue:s[t]}}))),d={name:`${this.methodNameRoot}_${a}`,description:t.title,displayName:t.title,parameters:c};n.actions.push(d),a++}}validate(t){if(!t)throw new Error("invalid options - should be an object");if("object"!=typeof t)throw new Error("invalid options - should be an object");if(!t.title)throw new Error("invalid options - should have a title");if("string"!=typeof t.title)throw new Error("invalid options - title should be a string");if(t.severity&&"string"!=typeof t.severity)throw new Error("invalid options - severity should be a string");if(t.panelExpiry&&"number"!=typeof t.panelExpiry)throw new Error("invalid options - panelExpiry should be a number");if(t.toastExpiry&&"number"!=typeof t.toastExpiry)throw new Error("invalid options - toastExpiry should be a number")}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}}).then((t=>{this.subscriptionForNotifications=t,this.logger.info(`Successfully subscribed to "${this.NotificationsSubscribeStream}".`),t.onData((({data:t})=>{this.handleData(t)})),t.onClosed(((...t)=>{this.subscribedForNotifications=!1,this.logger.info(`Stream subscription Closed - ${JSON.stringify(t)}`)})),t.onFailed(((...t)=>{this.subscribedForNotifications=!1,this.logger.warn(`Stream subscription Failed - ${JSON.stringify(t)}`)}))})).catch((t=>{this.subscribedForNotifications=!1,this.logger.error(`Unable to subscribe to "${this.NotificationsSubscribeStream}"`,t)})))}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((t=>{this.subscriptionForCounter=t,this.logger.info(`Successfully subscribed to "${this.NotificationsCounterStream}".`),t.onData((({data:t})=>{this.registry.execute("on-counter-changed",{count:t.count})})),t.onClosed(((...t)=>{this.subscribedCounterStream=!1,this.logger.info(`Stream subscription Closed - ${JSON.stringify(t)}`)})),t.onFailed(((...t)=>{this.subscribedCounterStream=!1,this.logger.warn(`Stream subscription Failed - ${JSON.stringify(t)}`)}))})).catch((t=>{this.subscribedCounterStream=!1,this.logger.error(`Unable to subscribe to "${this.NotificationsCounterStream}"`,t)})))}subscribeInternalEvents(){this.registry.add("on-notification-closed",(t=>{this.handleOnClosed(t)})),this.registry.add("on-notification-raised",(t=>{this.handleOnShow(t.id)}))}handleData(t){var e;try{"items"in t&&Array.isArray(t.items)?this.handleItemsData(t):"deltas"in t&&Array.isArray(t.deltas)&&this.handleDeltas(t),"configuration"in t&&"object"==typeof t.configuration&&(this.logger.info(`Received configuration ${JSON.stringify(t.configuration)} from the stream`),this.registry.execute("on-configuration-changed",t.configuration,t.configuration.allApplications)),"command"in t&&"string"==typeof t.command&&(this.logger.info(`Received command "${null!==(e=t.command)&&void 0!==e?e:JSON.stringify(t)}" from the stream`),"showPanel"!==t.command&&"hidePanel"!==t.command||this.registry.execute("on-panel-visibility-changed","showPanel"===t.command))}catch(t){this.logger.error("Failed to parse data from the stream",t)}}handleItemsData(t){const e=t.items;this.logger.info(`Received ${e.length} notifications from the stream`);const n=e;if(t.isSnapshot)n.forEach((t=>{this.registry.execute("on-notification-raised",t)}));else{const t=n[0];"Closed"===t.state?this.registry.execute("on-notification-closed",{id:t.id}):"Active"===t.state&&this.registry.execute("on-notification-raised",t)}}handleDeltas(t){t.deltas.forEach((t=>{const e=t.id,n=t.delta;"Closed"===n.state?this.registry.execute("on-notification-closed",{id:e}):this.registry.execute("on-state-changed",{id:e},n.state)}))}handleOnClosed(t){const{notification:e,key:n}=this.getNotification(t);e&&(this.handleEvent(e,"close"),delete this.notifications[n])}handleOnShow(t){const{notification:e}=this.getNotification(t);e&&this.handleEvent(e,"show")}getNotification(t){let e,n;for(const i in this.notifications)if(this.notifications[i].id===t){e=this.notifications[i],n=i;break}return{notification:e,key:n}}handleNotificationEvent(t){const e=this.getGnsNotificationArgs(t);if("unknown"===e.event)return;const n=this.notifications[e.notificationId];n&&this.handleNotificationEventCore(n,e)}handleNotificationEventCore(t,e){switch(e.event){case"action":return this.handleNotificationActionEvent(t,e.notificationActionPayload);case"click":return this.handleNotificationClickEvent(t);case"close":return this.handleEvent(t,"close");case"error":return this.handleNotificationErrorEvent(t,e.error);case"show":return this.handleEvent(t,"show")}}handleNotificationActionEvent(t,e){const n={type:"onaction",action:e.g42action};t.onaction&&t.onaction(n),t.dispatchEvent(n)}handleNotificationClickEvent(t){const e={type:"onclick"};t.onclick&&t.onclick(e),t.dispatchEvent(e)}handleEvent(t,e){var n;const i={type:e};null===(n=t[`on${e}`])||void 0===n||n.call(t,i),t.dispatchEvent(i)}handleNotificationErrorEvent(t,e){const n={type:"onerror",error:e};t.onerror&&t.onerror(n),t.dispatchEvent(n)}getGnsNotificationArgs(t){var e;let n;const i=null===(e=t.notification)||void 0===e?void 0:e.event;return n=i?{event:i,notificationId:t.notification.sourceNotificationId,notificationActionPayload:t}:this.getBackwardGnsNotificationArgs(t),n}getBackwardGnsNotificationArgs(t){var e;let n;return n=t.g42notificationId?{event:"action",notificationId:t.g42notificationId,notificationActionPayload:t}:(null===(e=t.notification)||void 0===e?void 0:e.sourceNotificationId)?{event:"click",notificationId:t.notification.sourceNotificationId,notificationActionPayload:t}:{event:"unknown",notificationId:void 0,notificationActionPayload:t},n}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)}}class Ji{constructor(t,e){this.contexts=t,this.interop=e,this.registry=xn(),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 t=await this.getAll();return t.returned.all.find((e=>e.name===t.returned.selected))}async select(t){if(await this.getConfiguration(),!this.setMethodName)throw new Error("not supported");await this.interop.invoke(this.setMethodName,{theme:t})}onChanged(t){return this.subscribe(),this.registry.add("changed",t)}async getConfiguration(){try{if(this.sharedContextName)return;const t=await this.interop.invoke("T42.Themes.Configuration");this.sharedContextName=t.returned.sharedContextName,this.getMethodName=t.returned.getThemesMethodName,this.setMethodName=t.returned.setThemesMethodName}catch(t){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,(t=>{t&&t.all&&t.selected&&this.registry.execute("changed",t.all.find((e=>e.name===t.selected)))})))}}const Vi="Tick42.FDC3.Intents.",zi=["applicationName","type"],Ki=(t,e,n)=>new Promise(((i,o)=>{let r=!0;const s=setTimeout((()=>{if(!r)return;r=!1;o(n||`Promise timeout hit: ${e}`)}),e);t().then((t=>{r&&(r=!1,clearTimeout(s),i(t))})).catch((t=>{r&&(r=!1,clearTimeout(s),o(t))}))}));class Qi{constructor(t,e,n,i,o){this.interop=t,this.windows=e,this.logger=n,this.appManager=o,this.myIntents=new Set,this.intentsResolverResponsePromises={},this.useIntentsResolverUI=!0,this.unregisterIntentPromises=[],this.checkIfIntentsResolverIsEnabled(i,o)}async find(t){await Promise.all(this.unregisterIntentPromises);let e=await this.all();if(void 0===t)return e;if("string"==typeof t)return e.filter((e=>e.name===t));if("object"!=typeof t)throw new Error("Please provide the intentFilter as a string or an object!");if(t.contextType){const n=t.contextType.toLowerCase();e=e.filter((t=>t.handlers.some((t=>{var e;return null===(e=t.contextTypes)||void 0===e?void 0:e.some((t=>t.toLowerCase()===n))}))))}if(t.resultType){const n=t.resultType.toLowerCase();e=e.filter((t=>t.handlers.some((t=>{var e;return(null===(e=t.resultType)||void 0===e?void 0:e.toLowerCase())===n}))))}return t.name&&(e=e.filter((e=>e.name===t.name))),e}async raise(t){if("string"!=typeof t&&"object"!=typeof t||"object"==typeof t&&"string"!=typeof t.intent)throw new Error("Please provide the intent as a string or an object with an intent property!");"string"==typeof t&&(t={intent:t}),this.validateIntentRequest(t),await Promise.all(this.unregisterIntentPromises);const e=t.timeout||9e4,n={},i=this.coreRaiseIntent.bind(this,{request:t,resolverInstance:n,timeout:e});if(t.waitUserResponseIndefinitely)return i();const o=Ki(i,e,`Timeout of ${e}ms hit for intent request ${JSON.stringify(t)}`);return o.catch((()=>this.handleRaiseOnError(n.instanceId))),o}async all(){let t;await Promise.all(this.unregisterIntentPromises);try{const e=await this.interop.invoke("T42.ACS.GetApplications",{withIntentsInfo:!0});t=e.returned.applications}catch(t){return this.logger.error("Failed to get the applications!",t),[]}const e={},n=t.filter((t=>t.intents&&t.intents.length>0));for(const t of n)for(const n of t.intents){let i=e[n.name];i||(i={name:n.name,handlers:[]},e[n.name]=i);const o={applicationName:t.name,applicationTitle:t.title||"",applicationDescription:t.caption,displayName:n.displayName,contextTypes:n.contexts,applicationIcon:t.icon,type:"app",resultType:n.resultType};i.handlers.push(o)}const i=this.interop.servers(),o=i.map((t=>t.windowId)).filter((t=>void 0!==t)),r="T42.Wnd.GetInfo";let s;if(this.interop.methods().some((t=>t.name===r)))try{const t=await this.interop.invoke(r,{ids:o});s=t.returned.windows}catch(t){}for(const n of i)await Promise.all(n.getMethods().filter((t=>t.name.startsWith(Vi))).map((async i=>{const o=i.name.replace(Vi,"");let r=e[o];r||(r={name:o,handlers:[]},e[o]=r);const a=i.flags.intent,c=t.find((t=>t.name===n.application));let d;c&&c.intents&&(d=c.intents.find((t=>t.name===o)));const u=await this.windowsIdToTitle(n.windowId,s),h={instanceId:n.instance,applicationName:n.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:u,type:"instance",resultType:(null==d?void 0:d.resultType)||a.resultType};r.handlers.push(h)})));return Object.values(e)}addIntentListener(t,e){if("string"!=typeof t&&"object"!=typeof t||"object"==typeof t&&"string"!=typeof t.intent)throw new Error("Please provide the intent as a string or an object with an intent property!");if("function"!=typeof e)throw new Error("Please provide the handler as a function!");const n="string"==typeof t?t:t.intent,i=`${Vi}${n}`;let o,r={};if(this.myIntents.has(n))throw new Error(`Intent listener for intent ${n} already registered!`);this.myIntents.add(n);const s={unsubscribe:()=>{this.myIntents.delete(n),o.then((()=>this.interop.unregister(i))).catch((t=>this.logger.trace(`Unregistration of a method with name ${i} failed with reason: ${JSON.stringify(t)}`)))}};if("object"==typeof t){const{intent:e,...n}=t;r=n}return o=this.interop.register({name:i,flags:{intent:r}},(t=>{if(this.myIntents.has(n))return e(t)})),o.catch((t=>{this.myIntents.delete(n),this.logger.warn(`Registration of a method with name ${i} failed with reason: ${JSON.stringify(t)}`)})),s}async register(t,e){if("string"!=typeof t&&"object"!=typeof t||"object"==typeof t&&"string"!=typeof t.intent)throw new Error("Please provide the intent as a string or an object with an intent property!");if("function"!=typeof e)throw new Error("Please provide the handler as a function!");await Promise.all(this.unregisterIntentPromises);const n="string"==typeof t?t:t.intent,i=this.buildInteropMethodName(n);let o={};if(this.myIntents.has(n))throw new Error(`Intent listener for intent ${n} already registered!`);if(this.myIntents.add(n),"object"==typeof t){const{intent:e,...n}=t;o=n}try{await this.interop.register({name:i,flags:{intent:o}},(t=>{if(this.myIntents.has(n))return e(t)}))}catch(t){throw this.myIntents.delete(n),new Error(`Registration of a method with name ${i} failed with reason: ${JSON.stringify(t)}`)}return{unsubscribe:()=>this.unsubscribeIntent(n)}}async coreRaiseIntent({request:t,resolverInstance:e,timeout:n}){var i,o;const r=await this.get(t.intent);if(void 0===r)throw new Error(`Intent ${t.intent} not found.`);const{open:s,reason:a}=this.checkIfResolverShouldBeOpened(r,t);if(!s)return this.logger.trace(`Intent Resolver UI won't be used. Reason: ${a}`),t.waitUserResponseIndefinitely?Ki((()=>this.raiseIntent(t,n)),n,`Timeout of ${n}ms hit for raise to resolve`):this.raiseIntent(t,n);const c=await this.startResolverApp(t,e);if(null===(i=this.logger)||void 0===i||i.trace(`Raising intent to target handler: ${JSON.stringify(c)} with timeout of ${n}`),t.waitUserResponseIndefinitely)return Ki((()=>this.raiseIntentToTargetHandler(t,c,n)),n,`Timeout of ${n}ms hit for raise to resolve`);const d=await this.raiseIntentToTargetHandler(t,c,n);return null===(o=this.logger)||void 0===o||o.trace(`Result from raise() method for intent ${JSON.stringify(t.intent)}: ${JSON.stringify(d)}`),d}async get(t){return(await this.all()).find((e=>e.name===t))}async raiseIntent(t,e){const n=t.intent,i=await this.get(n);if(void 0===i)throw new Error(`Intent ${n} not found.`);const o=t.handlers?this.findHandlerByFilter(t.handlers,{type:"app"}):this.findHandlerByFilter(i.handlers,{type:"app"}),r=t.handlers?this.findHandlerByFilter(t.handlers,{type:"instance"}):this.findHandlerByFilter(i.handlers,{type:"instance"});let s;if(t.target&&"reuse"!==t.target||(s=r||o),"startNew"===t.target&&(s=o),"object"==typeof t.target&&t.target.app&&(s=this.findHandlerByFilter(i.handlers,{app:t.target.app})),"object"==typeof t.target&&t.target.instance&&(s=this.findHandlerByFilter(i.handlers,{instance:t.target.instance,app:t.target.app})),!s)throw new Error(`Can not raise intent for request ${JSON.stringify(t)} - can not find intent handler!`);return await this.raiseIntentToTargetHandler(t,s,e)}async raiseIntentToTargetHandler(t,e,n){var i,o;null===(i=this.logger)||void 0===i||i.trace(`Raising intent to target handler:${JSON.stringify(e)}`),e.instanceId||(e.instanceId=await this.invokeStartApp(e.applicationName,t.context,t.options));const r=`${Vi}${t.intent}`,s={methodResponseTimeoutMs:n?n+1e3:6e4,waitTimeoutMs:n?n+1e3:6e4},a=await this.interop.invoke(r,t.context,{instance:e.instanceId},s);return null===(o=this.logger)||void 0===o||o.trace(`raiseIntent command completed. Returning result: ${JSON.stringify(a)}`),{request:t,handler:{...e,type:"instance"},result:a.returned}}async startResolverApp(t,e){var n,i,o,r;null===(n=this.logger)||void 0===n||n.trace(`Intents Resolver UI with app name ${this.intentsResolverAppName} will be used`);const s=await this.registerIntentResolverMethod();null===(i=this.logger)||void 0===i||i.trace(`Registered interop method ${s}`);const a=this.buildStartContext(t,s),c=await this.buildStartOptions();null===(o=this.logger)||void 0===o||o.trace(`Starting Intents Resolver UI with context: ${JSON.stringify(a)} and options: ${JSON.stringify(c)}`);const d=await this.appManager.application(this.intentsResolverAppName).start(a,c);e&&(e.instanceId=d.id),null===(r=this.logger)||void 0===r||r.trace(`Intents Resolver instance with id ${d.id} opened`),this.subscribeOnInstanceStopped(d),this.createResponsePromise(t,d.id,s);return await this.handleInstanceResponse(d.id)}async windowsIdToTitle(t,e){var n,i;if(void 0!==e)return null===(n=e.find((e=>e.id===t)))||void 0===n?void 0:n.title;const o=null===(i=this.windows)||void 0===i?void 0:i.findById(t);return await(null==o?void 0:o.getTitle())}async handleInstanceResponse(t){var e;try{const{handler:n,intent:i}=await this.intentsResolverResponsePromises[t].promise;return null===(e=this.logger)||void 0===e||e.trace(`Intent handler chosen for intent ${i}: ${JSON.stringify(n)}`),this.stopResolverInstance(t),n}catch(e){throw this.stopResolverInstance(t),new Error(e)}}async registerIntentResolverMethod(){const t="T42.Intents.Resolver.Control"+ii();return await this.interop.register(t,this.resolverResponseHandler.bind(this)),t}resolverResponseHandler(t,e){const{instance:n}=e,i=this.validateIntentsResolverResponse(t);i||(this.logger.trace(`Intent Resolver sent invalid response. Error: ${i.error}`),this.intentsResolverResponsePromises[n].reject(i.error),this.stopResolverInstance(n));const o=i.ok;this.intentsResolverResponsePromises[n].resolve(o),this.cleanUpIntentResolverPromise(n)}buildStartContext(t,e){return{intent:t,callerId:this.interop.instance.instance,methodName:e}}async buildStartOptions(){const t=this.windows.my();if(!t)return;const e=await t.getBounds();return{top:(e.height-440)/2+e.top,left:(e.width-400)/2+e.left}}createResponsePromise(t,e,n){let i,o;const r=t.waitUserResponseIndefinitely?2147483647:this.intentsResolverResponseTimeout,s=((t,e,n)=>new Promise(((i,o)=>{const r=setTimeout((()=>{o(n||`Promise timeout hit: ${e}`)}),e);new Promise(t).then((t=>{clearTimeout(r),i(t)})).catch((t=>{clearTimeout(r),o(t)}))})))(((t,e)=>{i=t,o=e}),r,`Timeout of ${r}ms hit waiting for the user to choose a handler for intent ${t.intent}`);this.intentsResolverResponsePromises[e]={intent:t.intent,resolve:i,reject:o,promise:s,methodName:n}}async invokeStartApp(t,e,n){return(await this.interop.invoke("T42.ACS.StartApplication",{Name:t,options:n})).returned.Id}subscribeOnInstanceStopped(t){const e=t.onStopped((t=>{const n=this.intentsResolverResponsePromises[t.id];if(!n)return e();n.reject(`Cannot resolve raise intent ${n.intent} - User closed ${this.intentsResolverAppName} app without choosing an intent handler`),this.cleanUpIntentResolverPromise(t.id),e()}))}async cleanUpIntentResolverPromise(t){const e=this.intentsResolverResponsePromises[t];if(!e)return;this.interop.unregister(e.methodName).catch((t=>this.logger.warn(t))),delete this.intentsResolverResponsePromises[t]}validateIntentsResolverResponse(t){if(Object.keys(t).some((t=>"intent"!==t&&"handler"!==t)))return{isValid:!1,error:"Response is not a valid object. Expected { intent: string, handler: IntentHandler }"};if("string"!=typeof t.intent)return{isValid:!1,error:"Response object has invalid 'intent' key. Expected a string, got "+typeof t.intent};if("object"!=typeof t.handler)return{isValid:!1,error:"Response object has invalid 'handler' key. Expected an object, got "+typeof t.handler};const e=zi.filter((e=>!(e in t.handler)));return e.length?{isValid:!1,error:`Handler in Response object does not provide compulsory keys: ${e.join(", ")}`}:{isValid:!0,ok:{intent:t.intent,handler:{...t.handler}}}}handleRaiseOnError(t){t&&this.stopResolverInstance(t)}stopResolverInstance(t){const e=this.windows.findById(t);null==e||e.close().catch((t=>this.logger.error(t)))}checkIfIntentsResolverIsEnabled(t,e){var n,i,o,r,s;e?(this.useIntentsResolverUI="boolean"!=typeof(null===(n=t.intents)||void 0===n?void 0:n.enableIntentsResolverUI)||t.intents.enableIntentsResolverUI,this.intentsResolverAppName=null!==(o=null===(i=t.intents)||void 0===i?void 0:i.intentsResolverAppName)&&void 0!==o?o:"intentsResolver",this.intentsResolverResponseTimeout=null!==(s=null===(r=t.intents)||void 0===r?void 0:r.methodResponseTimeoutMs)&&void 0!==s?s:6e4):this.useIntentsResolverUI=!1}checkIfResolverShouldBeOpened(t,e){if(!this.useIntentsResolverUI)return{open:!1,reason:"Intent Resolver is disabled. Raising intent to first found handler"};if(!this.appManager.application(this.intentsResolverAppName))return{open:!1,reason:`Intent Resolver Application with name ${this.intentsResolverAppName} not found.`};return this.checkIfIntentHasMoreThanOneHandler(t,e)?{open:!0}:{open:!1,reason:`Raised intent ${t.name} has only one handler`}}checkIfIntentHasMoreThanOneHandler(t,e){return e.target?"reuse"===e.target?e.handlers?e.handlers.filter((t=>"instance"===t.type&&t.instanceId)).length>1||e.handlers.filter((t=>"app"===t.type)).length>1:t.handlers.filter((t=>"instance"===t.type&&t.instanceId)).length>1||t.handlers.filter((t=>"app"===t.type)).length>1:"startNew"===e.target?e.handlers?e.handlers.filter((t=>"app"===t.type)).length>1:t.handlers.filter((t=>"app"===t.type)).length>1:(e.target,!1):e.handlers?e.handlers.length>1:t.handlers.length>1}buildInteropMethodName(t){return`${Vi}${t}`}clearUnregistrationPromise(t){this.unregisterIntentPromises=this.unregisterIntentPromises.filter((e=>e!==t))}unsubscribeIntent(t){this.myIntents.delete(t);const e=this.buildInteropMethodName(t),n=this.interop.unregister(e);this.unregisterIntentPromises.push(n),n.then((()=>{this.clearUnregistrationPromise(n)})).catch((t=>{this.logger.error(`Unregistration of a method with name ${e} failed with reason: `,t),this.clearUnregistrationPromise(n)}))}validateIntentRequest(t){this.validateIntentRequestContext(t.context),this.validateIntentRequestTarget(t.target),this.validateIntentRequestTimeout(t.timeout),this.validateWaitUserResponseIndefinitely(t.waitUserResponseIndefinitely),t.handlers&&t.handlers.forEach((t=>this.validateIntentRequestHandler(t)))}validateIntentRequestTarget(t){if(t&&"string"!=typeof t&&"object"!=typeof t)throw new Error('Please provide the intent target as one of the valid values: "reuse", "startNew", { app: string }, { instance: string } ')}validateIntentRequestContext(t){if(t){if("object"!=typeof t)throw new Error("Please provide the intent context as an object");if(t.type&&"string"!=typeof t.type)throw new Error("Please provide the intent context as an object with 'type' property as string");if(t.data&&"object"!=typeof t.data)throw new Error("Please provide the intent context as an object with 'data' property as object")}}validateIntentRequestHandler(t){if(!t.applicationName)throw new Error(`Please provide applicationName for handler ${JSON.stringify(t)}`);if(!t.type)throw new Error(`Please provide type for handler ${JSON.stringify(t)}`);if("instance"===t.type&&!t.instanceId)throw new Error(`Please provide instanceId for handler ${JSON.stringify(t)}`)}validateIntentRequestTimeout(t){if(t){if("number"!=typeof t)throw new Error("Please provide the timeout as a number");if(t<=0)throw new Error("Please provide the timeout as a positive number")}}validateWaitUserResponseIndefinitely(t){if(t&&"boolean"!=typeof t)throw new Error("Please provide waitUserResponseIndefinitely as a boolean")}findHandlerByFilter(t,e){return e.type?t.find((t=>t.type===e.type)):e.instance?t.find((t=>e.app?t.applicationName===e.app&&t.instanceId===e.instance:t.instanceId===e.instance)):e.app?t.find((t=>t.applicationName===e.app)):void 0}}class Zi{constructor(t,e){this.appName=t,this.interop=e,this.registry=xn(),this.interopMethodRegistered=!1}async get(t){return(await this.interop.invoke("T42.Prefs.Get",{app:null!=t?t:this.appName})).returned}async set(t,e){var n;this.verifyDataObject(t),await this.interop.invoke("T42.Prefs.Set",{app:null!==(n=null==e?void 0:e.app)&&void 0!==n?n:this.appName,data:t,merge:!1})}async setFor(t,e){return this.verifyApp(t),this.verifyDataObject(e),this.set(e,{app:t})}async update(t,e){var n;this.verifyDataObject(t),await this.interop.invoke("T42.Prefs.Set",{app:null!==(n=null==e?void 0:e.app)&&void 0!==n?n:this.appName,data:t,merge:!0})}async updateFor(t,e){return this.verifyApp(t),this.verifyDataObject(e),this.update(e,{app:t})}async clear(t){await this.interop.invoke("T42.Prefs.Set",{app:null!=t?t:this.appName,clear:!0})}async clearFor(t){this.verifyApp(t),await this.interop.invoke("T42.Prefs.Set",{app:t,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(t){return this.verifyCallback(t),this.subscribeFor(this.appName,t)}subscribeFor(t,e){this.verifyApp(t),this.verifyCallback(e);const n=this.registry.add(t,e);return this.registerInteropIfNeeded().then((()=>{this.interop.invoke("T42.Prefs.Get",{app:t,subscribe:!0})})),()=>{n()}}async registerInteropIfNeeded(){this.interopMethodRegistered||(this.interopMethodRegistered=!0,await this.interop.register("T42.Prefs.Update",(t=>{this.registry.execute(t.app,t)})))}verifyApp(t){if(!t)throw new Error("app should be defined");if(!ke(t))throw new Error("app should be a string")}verifyDataObject(t){if(!t)throw new Error("data should be defined");if(!Te(t))throw new Error("data should be an object")}verifyCallback(t){if(!je(t))throw new Error("callback should be defined")}}class Xi{constructor(t,e){this.methodName=t,this.interop=e}async get(t){return(await this.invoke("get-cookies",{filter:t})).returned.cookies}async set(t){this.verifyCookieObject(t),await this.invoke("set-cookie",t)}async remove(t,e){if(!ke(t))throw new Error("url should be a string");if(!ke(e))throw new Error("name should be a string");await this.invoke("remove-cookie",{url:t,name:e})}invoke(t,e){return this.interop.invoke(this.methodName,{command:t,args:e})}verifyCookieObject(t){if(!t)throw new Error("cookie should be defined");if(!Te(t))throw new Error("cookie should be an object")}}class Yi{constructor(t){this.config=t,this.glue42EventName="Glue42",this.events={notifyStarted:{name:"notifyStarted",handle:this.handleNotifyStarted.bind(this)},requestGlue:{name:"requestGlue",handle:this.handleRequestGlue.bind(this)}}}start(t){ai.isNode()||(this.glue=t,this.wireCustomEventListener(),this.announceStarted())}wireCustomEventListener(){window.addEventListener(this.glue42EventName,(t=>{const e=t.detail;if(!e||!e.glue42)return;const n=e.glue42.event,i=this.events[n];i&&i.handle(e.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(t,e){const n={glue42:{event:t,message:e}},i=new CustomEvent(this.glue42EventName,{detail:n});window.dispatchEvent(i)}}const to=new class{constructor(){this.initialized=!1,this.details=[],this.reject=()=>{},this.resolve=()=>{}}init(t){this.initialized=!0,this.addCall(t),this.promise=new Promise(((t,e)=>{this.resolve=t,this.reject=e}))}addCall(t){this.details.push({date:new Date,config:t})}done(t){this.resolve(t)}error(t){this.reject(t)}},eo=async t=>{let e=!1;to.initialized||(e=!0,to.init(t));const n="undefined"!=typeof window&&window.glue42gd;if(n&&!e)return to.addCall(t),to.promise;const i=await no(t,n);return to.resolve(i),i},no=async(t,e)=>{const n=ai.getGDMajorVersion(),i=qi(t=t||{});let o,r,s,a,c;t.gateway=t.gateway||{};const d=new Yi(i);function u(t,e,n){const i=e.subLogger(t);if(n&&n.logger){const t=n.logger;t.console&&i.consoleLevel(t.console),t.publish&&i.publishLevel(t.publish)}return i}const h={libs:[{name:"windows",create:function(t){if(i.windows){const e=u("windows",t.logger,i.windows);return s=vi(t.agm,e,(()=>o),(()=>a),(()=>c),n),p(s),s}}},{name:"activities",create:function(t){var a;if(i.activities&&bn.checkIsUsingGW3Implementation&&bn.checkIsUsingGW3Implementation(t.connection)){const c=u("activity",t.logger,i.activities);return r=new bn({connection:t.connection,contexts:t.contexts,agm:t.agm,logger:c,logLevel:"info",disableAutoAnnounce:!1,disposeRequestHandling:"exit",announcementInfo:null,windows:s,appManagerGetter:()=>o,mode:i.activities.mode,typesToTrack:i.activities.typesToTrack,activityId:null===(a=null==e?void 0:e.activityInfo)||void 0===a?void 0:a.activityId,gdMajorVersion:n}).api,p(r),r}}},{name:"appManager",create:function(t){if(!i.appManager)return;const e=u("appManager",t.logger,i.appManager);return o=Fn({agm:t.agm,windows:s,logger:e,activities:r,mode:i.appManager.mode,gdMajorVersion:n}),p(o),o}},{name:"layouts",create:function(t){var e;if(!i.layouts)return;const s=u("layouts",t.logger,i.layouts),a=i.layouts,c=xi({agm:t.agm,appManager:o,activityGetter:()=>r,logger:s,mode:a.mode,autoSaveWindowContext:null!==(e=a.autoSaveWindowContext)&&void 0!==e&&e,gdMajorVersion:n});return p(c),c}},{name:"channels",create:function(t){if(!i.channels)return;if(!t.contexts)return;const e=u("channels",t.logger,i.channels);return c=Li(t.contexts,t.agm,(()=>s),e),p(c),c}},{name:"hotkeys",create:function(t){const e=function(t){const e=new Gi(t);return{register:e.register.bind(e),unregister:e.unregister.bind(e),unregisterAll:e.unregisterAll.bind(e),isRegistered:e.isRegistered.bind(e),ready:()=>Promise.resolve()}}(t.agm);return p(e),e}},{name:"displays",create:function(t){if(i.displays){const e=u("displays",t.logger,i.displays);return a=new ki(t.agm,e),p(a),a}}},{name:"intents",create:function(e){const n=new Qi(e.agm,s,e.logger.subLogger("intents"),t,o);return p(n),n}},{name:"notifications",create:function(t){const e=new $i(t.interop,t.logger).toAPI();return p(e),e}},{name:"themes",create:function(t){if(!t.contexts)return;const e=function(t,e){const n=new Ji(t,e);return{list:n.list.bind(n),getCurrent:n.getCurrent.bind(n),select:n.select.bind(n),onChanged:n.onChanged.bind(n),ready:()=>Promise.resolve()}}(t.contexts,t.interop);return p(e),e}},{name:"prefs",create:function(n){var i,o;const r=null!==(o=null!==(i=t.application)&&void 0!==i?i:null==e?void 0:e.application)&&void 0!==o?o:n.interop.instance.application,s=new Zi(r,n.interop);return p(s),s}},{name:"cookies",create:function(t){const e=function(t,e){const n=new Xi(e,t);return{get:n.get.bind(n),remove:n.remove.bind(n),set:n.set.bind(n),ready:()=>Promise.resolve()}}(t.interop,"T42.GD.Execute");return p(e),e}}],version:Bi,enrichGlue:t=>{t.config.activities=i.activities,t.config.windows=i.windows,t.config.appManager=i.appManager,t.config.layouts=i.layouts,t.config.channels=i.channels,t.config.displays=i.displays}},l=[];function p(t){l.push(t)}"undefined"!=typeof window&&(window.glueFactoryLog||(window.glueFactoryLog=[]),window.glueFactoryLog.push(l));const g=await Ae(t,h);return Array.isArray(null==t?void 0:t.libraries)&&t.libraries.length&&await Promise.all(t.libraries.map((e=>e(g,t)))),d.start(g),g};var io;eo.coreVersion=Ae.version,eo.version=Bi,eo.calls=to;let oo=eo,ro=!0;if("undefined"!=typeof window){const t=window,e=null!==(io=t.iodesktop)&&void 0!==io?io:t.glue42gd;e&&e.autoInjected&&(oo=t.IODesktop,ro=!1),ro&&(t.Glue=oo,t.IODesktop=oo),delete t.IOBrowser,delete t.GlueCore}return oo.default=oo,oo}));
2
+ //# sourceMappingURL=desktop.umd.min.js.map