@interopio/browser 3.4.8 → 3.5.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.
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):((e="undefined"!=typeof globalThis?globalThis:e||self).browser=e.browser||{},e.browser.min=t())}(this,(function(){"use strict";const e={logger:"info",gateway:{webPlatform:{}},libraries:[],exposeAPI:!0},t={name:"platformUnload"},n={name:"transportSwitchRequest"},i={name:"transportSwitchResponse"},s={name:"getCurrentTransport"},r={name:"getCurrentTransportResponse"},o={name:"checkPreferredLogic"},a={name:"checkPreferredConnection"},c={name:"checkPreferredLogicResponse"},d={name:"checkPreferredConnectionResponse"},l="web-platform",h="latest_fdc3_type",u=new MessageChannel,p=e=>"string"==typeof e?e:e?.message?"string"==typeof e.message?e.message:JSON.stringify(e.message):JSON.stringify(e),g=(e,t)=>{try{return e.runWithException(t)}catch(e){return m.raiseError(e,!0)}};const m=new class{raiseError(e,t){const n=p(e);if(u.port1.postMessage(n),t)throw e;throw new Error(n)}};var f=function(e){return{ok:!0,result:e}},b=function(e){return{ok:!1,error:e}},w=function(e,t,n){return!1===t.ok?t:!1===n.ok?n:f(e(t.result,n.result))},y=function(e,t){return!0===t.ok?t:b(e(t.error))},v=function(){return v=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++)for(var s in t=arguments[n])Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s]);return e},v.apply(this,arguments)};function C(e,t){if(e===t)return!0;if(null===e&&null===t)return!0;if(typeof e!=typeof t)return!1;if("object"==typeof e){if(Array.isArray(e)){if(!Array.isArray(t))return!1;if(e.length!==t.length)return!1;for(var n=0;n<e.length;n++)if(!C(e[n],t[n]))return!1;return!0}var i=Object.keys(e);if(i.length!==Object.keys(t).length)return!1;for(n=0;n<i.length;n++){if(!t.hasOwnProperty(i[n]))return!1;if(!C(e[i[n]],t[i[n]]))return!1}return!0}}var I=function(e){return Array.isArray(e)},S=function(e){return"object"==typeof e&&null!==e&&!I(e)},_=function(e,t){return"expected "+e+", got "+function(e){switch(typeof e){case"string":return"a string";case"number":return"a number";case"boolean":return"a boolean";case"undefined":return"undefined";case"object":return e instanceof Array?"an array":null===e?"null":"an object";default:return JSON.stringify(e)}}(t)},x=function(e){return e.map((function(e){return"string"==typeof e?"."+e:"["+e+"]"})).join("")},k=function(e,t){var n=t.at,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(i=Object.getOwnPropertySymbols(e);s<i.length;s++)t.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(e,i[s])&&(n[i[s]]=e[i[s]])}return n}(t,["at"]);return v({at:e+(n||"")},i)},T=function(){function e(t){var n=this;this.decode=t,this.run=function(e){return y((function(t){return{kind:"DecoderError",input:e,at:"input"+(t.at||""),message:t.message||""}}),n.decode(e))},this.runPromise=function(e){return!0===(t=n.run(e)).ok?Promise.resolve(t.result):Promise.reject(t.error);var t},this.runWithException=function(e){return function(e){if(!0===e.ok)return e.result;throw e.error}(n.run(e))},this.map=function(t){return new e((function(e){return function(e,t){return!0===t.ok?f(e(t.result)):t}(t,n.decode(e))}))},this.andThen=function(t){return new e((function(e){return function(e,t){return!0===t.ok?e(t.result):t}((function(n){return t(n).decode(e)}),n.decode(e))}))},this.where=function(t,i){return n.andThen((function(n){return t(n)?e.succeed(n):e.fail(i)}))}}return e.string=function(){return new e((function(e){return"string"==typeof e?f(e):b({message:_("a string",e)})}))},e.number=function(){return new e((function(e){return"number"==typeof e?f(e):b({message:_("a number",e)})}))},e.boolean=function(){return new e((function(e){return"boolean"==typeof e?f(e):b({message:_("a boolean",e)})}))},e.constant=function(t){return new e((function(e){return C(e,t)?f(t):b({message:"expected "+JSON.stringify(t)+", got "+JSON.stringify(e)})}))},e.object=function(t){return new e((function(e){if(S(e)&&t){var n={};for(var i in t)if(t.hasOwnProperty(i)){var s=t[i].decode(e[i]);if(!0!==s.ok)return void 0===e[i]?b({message:"the key '"+i+"' is required but was not present"}):b(k("."+i,s.error));void 0!==s.result&&(n[i]=s.result)}return f(n)}return S(e)?f(e):b({message:_("an object",e)})}))},e.array=function(t){return new e((function(e){if(I(e)&&t){return e.reduce((function(e,n,i){return w((function(e,t){return e.concat([t])}),e,function(e,n){return y((function(e){return k("["+n+"]",e)}),t.decode(e))}(n,i))}),f([]))}return I(e)?f(e):b({message:_("an array",e)})}))},e.tuple=function(t){return new e((function(e){if(I(e)){if(e.length!==t.length)return b({message:"expected a tuple of length "+t.length+", got one of length "+e.length});for(var n=[],i=0;i<t.length;i++){var s=t[i].decode(e[i]);if(!s.ok)return b(k("["+i+"]",s.error));n[i]=s.result}return f(n)}return b({message:_("a tuple of length "+t.length,e)})}))},e.union=function(t,n){for(var i=[],s=2;s<arguments.length;s++)i[s-2]=arguments[s];return e.oneOf.apply(e,[t,n].concat(i))},e.intersection=function(t,n){for(var i=[],s=2;s<arguments.length;s++)i[s-2]=arguments[s];return new e((function(e){return[t,n].concat(i).reduce((function(t,n){return w(Object.assign,t,n.decode(e))}),f({}))}))},e.anyJson=function(){return new e((function(e){return f(e)}))},e.unknownJson=function(){return new e((function(e){return f(e)}))},e.dict=function(t){return new e((function(e){if(S(e)){var n={};for(var i in e)if(e.hasOwnProperty(i)){var s=t.decode(e[i]);if(!0!==s.ok)return b(k("."+i,s.error));n[i]=s.result}return f(n)}return b({message:_("an object",e)})}))},e.optional=function(t){return new e((function(e){return null==e?f(void 0):t.decode(e)}))},e.oneOf=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return new e((function(e){for(var n=[],i=0;i<t.length;i++){var s=t[i].decode(e);if(!0===s.ok)return s;n[i]=s.error}var r=n.map((function(e){return"at error"+(e.at||"")+": "+e.message})).join('", "');return b({message:'expected a value matching one of the decoders, got the errors ["'+r+'"]'})}))},e.withDefault=function(t,n){return new e((function(e){return f(function(e,t){return!0===t.ok?t.result:e}(t,n.decode(e)))}))},e.valueAt=function(t,n){return new e((function(e){for(var i=e,s=0;s<t.length;s++){if(void 0===i)return b({at:x(t.slice(0,s+1)),message:"path does not exist"});if("string"==typeof t[s]&&!S(i))return b({at:x(t.slice(0,s+1)),message:_("an object",i)});if("number"==typeof t[s]&&!I(i))return b({at:x(t.slice(0,s+1)),message:_("an array",i)});i=i[t[s]]}return y((function(e){return void 0===i?{at:x(t),message:"path does not exist"}:k(x(t),e)}),n.decode(i))}))},e.succeed=function(t){return new e((function(e){return f(t)}))},e.fail=function(t){return new e((function(e){return b({message:t})}))},e.lazy=function(t){return new e((function(e){return t().decode(e)}))},e}(),P=T.string,R=T.number,A=T.boolean,M=T.anyJson;T.unknownJson;var E=T.constant,O=T.object,D=T.array;T.tuple,T.dict;var j=T.optional,N=T.oneOf;T.union,T.intersection,T.withDefault,T.valueAt,T.succeed,T.fail;var L=T.lazy;const F=["name","title","version","customProperties","icon","caption","type"],$=["appId","name","type","details","version","title","tooltip","lang","description","categories","icons","screenshots","contactEmail","moreInfo","publisher","customConfig","hostManifests","interop","localizedVersions"];var W=function(e){return{ok:!0,result:e}},q=function(e){return{ok:!1,error:e}},G=function(e,t,n){return!1===t.ok?t:!1===n.ok?n:W(e(t.result,n.result))},B=function(e,t){return!0===t.ok?t:q(e(t.error))},U=function(){return U=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++)for(var s in t=arguments[n])Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s]);return e},U.apply(this,arguments)};function H(e,t){if(e===t)return!0;if(null===e&&null===t)return!0;if(typeof e!=typeof t)return!1;if("object"==typeof e){if(Array.isArray(e)){if(!Array.isArray(t))return!1;if(e.length!==t.length)return!1;for(var n=0;n<e.length;n++)if(!H(e[n],t[n]))return!1;return!0}var i=Object.keys(e);if(i.length!==Object.keys(t).length)return!1;for(n=0;n<i.length;n++){if(!t.hasOwnProperty(i[n]))return!1;if(!H(e[i[n]],t[i[n]]))return!1}return!0}}var J=function(e){return Array.isArray(e)},K=function(e){return"object"==typeof e&&null!==e&&!J(e)},z=function(e,t){return"expected "+e+", got "+function(e){switch(typeof e){case"string":return"a string";case"number":return"a number";case"boolean":return"a boolean";case"undefined":return"undefined";case"object":return e instanceof Array?"an array":null===e?"null":"an object";default:return JSON.stringify(e)}}(t)},V=function(e){return e.map((function(e){return"string"==typeof e?"."+e:"["+e+"]"})).join("")},Q=function(e,t){var n=t.at,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(i=Object.getOwnPropertySymbols(e);s<i.length;s++)t.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(e,i[s])&&(n[i[s]]=e[i[s]])}return n}(t,["at"]);return U({at:e+(n||"")},i)},X=function(){function e(t){var n=this;this.decode=t,this.run=function(e){return B((function(t){return{kind:"DecoderError",input:e,at:"input"+(t.at||""),message:t.message||""}}),n.decode(e))},this.runPromise=function(e){return!0===(t=n.run(e)).ok?Promise.resolve(t.result):Promise.reject(t.error);var t},this.runWithException=function(e){return function(e){if(!0===e.ok)return e.result;throw e.error}(n.run(e))},this.map=function(t){return new e((function(e){return function(e,t){return!0===t.ok?W(e(t.result)):t}(t,n.decode(e))}))},this.andThen=function(t){return new e((function(e){return function(e,t){return!0===t.ok?e(t.result):t}((function(n){return t(n).decode(e)}),n.decode(e))}))},this.where=function(t,i){return n.andThen((function(n){return t(n)?e.succeed(n):e.fail(i)}))}}return e.string=function(){return new e((function(e){return"string"==typeof e?W(e):q({message:z("a string",e)})}))},e.number=function(){return new e((function(e){return"number"==typeof e?W(e):q({message:z("a number",e)})}))},e.boolean=function(){return new e((function(e){return"boolean"==typeof e?W(e):q({message:z("a boolean",e)})}))},e.constant=function(t){return new e((function(e){return H(e,t)?W(t):q({message:"expected "+JSON.stringify(t)+", got "+JSON.stringify(e)})}))},e.object=function(t){return new e((function(e){if(K(e)&&t){var n={};for(var i in t)if(t.hasOwnProperty(i)){var s=t[i].decode(e[i]);if(!0!==s.ok)return void 0===e[i]?q({message:"the key '"+i+"' is required but was not present"}):q(Q("."+i,s.error));void 0!==s.result&&(n[i]=s.result)}return W(n)}return K(e)?W(e):q({message:z("an object",e)})}))},e.array=function(t){return new e((function(e){if(J(e)&&t){return e.reduce((function(e,n,i){return G((function(e,t){return e.concat([t])}),e,function(e,n){return B((function(e){return Q("["+n+"]",e)}),t.decode(e))}(n,i))}),W([]))}return J(e)?W(e):q({message:z("an array",e)})}))},e.tuple=function(t){return new e((function(e){if(J(e)){if(e.length!==t.length)return q({message:"expected a tuple of length "+t.length+", got one of length "+e.length});for(var n=[],i=0;i<t.length;i++){var s=t[i].decode(e[i]);if(!s.ok)return q(Q("["+i+"]",s.error));n[i]=s.result}return W(n)}return q({message:z("a tuple of length "+t.length,e)})}))},e.union=function(t,n){for(var i=[],s=2;s<arguments.length;s++)i[s-2]=arguments[s];return e.oneOf.apply(e,[t,n].concat(i))},e.intersection=function(t,n){for(var i=[],s=2;s<arguments.length;s++)i[s-2]=arguments[s];return new e((function(e){return[t,n].concat(i).reduce((function(t,n){return G(Object.assign,t,n.decode(e))}),W({}))}))},e.anyJson=function(){return new e((function(e){return W(e)}))},e.unknownJson=function(){return new e((function(e){return W(e)}))},e.dict=function(t){return new e((function(e){if(K(e)){var n={};for(var i in e)if(e.hasOwnProperty(i)){var s=t.decode(e[i]);if(!0!==s.ok)return q(Q("."+i,s.error));n[i]=s.result}return W(n)}return q({message:z("an object",e)})}))},e.optional=function(t){return new e((function(e){return null==e?W(void 0):t.decode(e)}))},e.oneOf=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return new e((function(e){for(var n=[],i=0;i<t.length;i++){var s=t[i].decode(e);if(!0===s.ok)return s;n[i]=s.error}var r=n.map((function(e){return"at error"+(e.at||"")+": "+e.message})).join('", "');return q({message:'expected a value matching one of the decoders, got the errors ["'+r+'"]'})}))},e.withDefault=function(t,n){return new e((function(e){return W(function(e,t){return!0===t.ok?t.result:e}(t,n.decode(e)))}))},e.valueAt=function(t,n){return new e((function(e){for(var i=e,s=0;s<t.length;s++){if(void 0===i)return q({at:V(t.slice(0,s+1)),message:"path does not exist"});if("string"==typeof t[s]&&!K(i))return q({at:V(t.slice(0,s+1)),message:z("an object",i)});if("number"==typeof t[s]&&!J(i))return q({at:V(t.slice(0,s+1)),message:z("an array",i)});i=i[t[s]]}return B((function(e){return void 0===i?{at:V(t),message:"path does not exist"}:Q(V(t),e)}),n.decode(i))}))},e.succeed=function(t){return new e((function(e){return W(t)}))},e.fail=function(t){return new e((function(e){return q({message:t})}))},e.lazy=function(t){return new e((function(e){return t().decode(e)}))},e}(),Y=X.string,Z=X.number,ee=X.boolean,te=X.anyJson;X.unknownJson;var ne=X.constant,ie=X.object,se=X.array;X.tuple;var re=X.dict,oe=X.optional,ae=X.oneOf;X.union,X.intersection,X.withDefault,X.valueAt,X.succeed,X.fail,X.lazy;const ce=Y().where((e=>e.length>0),"Expected a non-empty string"),de=Z().where((e=>e>=0),"Expected a non-negative number"),le=ie({name:ce,displayName:oe(Y()),contexts:oe(se(Y())),customConfig:oe(ie())}),he=ae(ne("web"),ne("native"),ne("citrix"),ne("onlineNative"),ne("other")),ue=ie({url:ce}),pe=ie({src:ce,size:oe(ce),type:oe(ce)}),ge=ie({src:ce,size:oe(ce),type:oe(ce),label:oe(ce)}),me=ie({contexts:se(ce),displayName:oe(ce),resultType:oe(ce),customConfig:oe(te())}),fe=ie({listensFor:oe(re(me)),raises:oe(re(se(ce)))}),be=ie({broadcasts:oe(se(ce)),listensFor:oe(se(ce))}),we=ie({name:ce,description:oe(ce),broadcasts:oe(se(ce)),listensFor:oe(se(ce))}),ye=ie({intents:oe(fe),userChannels:oe(be),appChannels:oe(se(we))}),ve=ie({url:oe(ce),top:oe(Z()),left:oe(Z()),width:oe(de),height:oe(de)}),Ce=ie({name:oe(ce),type:oe(ce.where((e=>"window"===e),"Expected a value of window")),title:oe(ce),version:oe(ce),customProperties:oe(te()),icon:oe(Y()),caption:oe(Y()),details:oe(ve),intents:oe(se(le)),hidden:oe(ee())}),Ie=ie({name:ce,appId:ce,title:oe(ce),version:oe(ce),manifest:ce,manifestType:ce,tooltip:oe(ce),description:oe(ce),contactEmail:oe(ce),supportEmail:oe(ce),publisher:oe(ce),images:oe(se(ie({url:oe(ce)}))),icons:oe(se(ie({icon:oe(ce)}))),customConfig:te(),intents:oe(se(le))}),Se=ie({appId:oe(ce),name:oe(ce),details:oe(ue),version:oe(ce),title:oe(ce),tooltip:oe(ce),lang:oe(ce),description:oe(ce),categories:oe(se(ce)),icons:oe(se(pe)),screenshots:oe(se(ge)),contactEmail:oe(ce),supportEmail:oe(ce),moreInfo:oe(ce),publisher:oe(ce),customConfig:oe(se(te())),hostManifests:oe(te()),interop:oe(ye)}),_e=ie({appId:ce,name:ce,type:he,details:ue,version:oe(ce),title:oe(ce),tooltip:oe(ce),lang:oe(ce),description:oe(ce),categories:oe(se(ce)),icons:oe(se(pe)),screenshots:oe(se(ge)),contactEmail:oe(ce),supportEmail:oe(ce),moreInfo:oe(ce),publisher:oe(ce),customConfig:oe(se(te())),hostManifests:oe(te()),interop:oe(ye),localizedVersions:oe(re(Se))}),xe=ae(Ie,_e),ke=e=>`${e.kind} at ${e.at}: ${JSON.stringify(e.input)}. Reason - ${e.message}`;class Te{fdc3ToDesktopDefinitionType={web:"window",native:"exe",citrix:"citrix",onlineNative:"clickonce",other:"window"};toApi(){return{isFdc3Definition:this.isFdc3Definition.bind(this),parseToBrowserBaseAppData:this.parseToBrowserBaseAppData.bind(this),parseToDesktopAppConfig:this.parseToDesktopAppConfig.bind(this)}}isFdc3Definition(e){const t=xe.run(e);return t.ok?e.appId&&e.details?{isFdc3:!0,version:"2.0"}:e.manifest?{isFdc3:!0,version:"1.2"}:{isFdc3:!1,reason:"The passed definition is not FDC3"}:{isFdc3:!1,reason:ke(t.error)}}parseToBrowserBaseAppData(e){const{isFdc3:t,version:n}=this.isFdc3Definition(e);if(!t)throw new Error("The passed definition is not FDC3");const i=xe.run(e);if(!i.ok)throw new Error(`Invalid FDC3 ${n} definition. Error: ${ke(i.error)}`);const s=this.getUserPropertiesFromDefinition(e,n),r={url:this.getUrl(e,n)},o={name:e.appId,type:"window",createOptions:r,userProperties:{...s,intents:"1.2"===n?s.intents:this.getIntentsFromV2AppDefinition(e),details:r},title:e.title,version:e.version,icon:this.getIconFromDefinition(e,n),caption:e.description,fdc3:"2.0"===n?{...e,definitionVersion:"2.0"}:void 0},a=e.hostManifests?.ioConnect||e.hostManifests?.Glue42;if(!a)return o;const c=Ce.run(a);if(!c.ok)throw new Error(`Invalid FDC3 ${n} definition. Error: ${ke(c.error)}`);return Object.keys(c.result).length?this.mergeBaseAppDataWithGlueManifest(o,c.result):o}parseToDesktopAppConfig(e){const{isFdc3:t,version:n}=this.isFdc3Definition(e);if(!t)throw new Error("The passed definition is not FDC3");const i=xe.run(e);if(!i.ok)throw new Error(`Invalid FDC3 ${n} definition. Error: ${ke(i.error)}`);if("1.2"===n){const t=e;return{name:t.appId,type:"window",details:{url:this.getUrl(e,n)},version:t.version,title:t.title,tooltip:t.tooltip,caption:t.description,icon:t.icons?.[0].icon,intents:t.intents,customProperties:{manifestType:t.manifestType,images:t.images,contactEmail:t.contactEmail,supportEmail:t.supportEmail,publisher:t.publisher,icons:t.icons,customConfig:t.customConfig}}}const s=e,r={name:s.appId,type:this.fdc3ToDesktopDefinitionType[s.type],details:s.details,version:s.version,title:s.title,tooltip:s.tooltip,caption:s.description,icon:this.getIconFromDefinition(s,"2.0"),intents:this.getIntentsFromV2AppDefinition(s),fdc3:{...s,definitionVersion:"2.0"}},o=e.hostManifests?.ioConnect||e.hostManifests?.Glue42;if(!o)return r;if("object"!=typeof o||Array.isArray(o))throw new Error(`Invalid '${e.hostManifests.ioConnect?"hostManifests.ioConnect":"hostManifests['Glue42']"}' key`);return this.mergeDesktopConfigWithGlueManifest(r,o)}getUserPropertiesFromDefinition(e,t){return"1.2"===t?Object.fromEntries(Object.entries(e).filter((([e])=>!F.includes(e)))):Object.fromEntries(Object.entries(e).filter((([e])=>!F.includes(e)&&!$.includes(e))))}getUrl(e,t){let n;if("1.2"===t){const t=JSON.parse(e.manifest);n=t.details?.url||t.url}else n=e.details?.url;if(!n||"string"!=typeof n)throw new Error(`Invalid FDC3 ${t} definition. Provide valid 'url' under '${"1.2"===t?"manifest":"details"}' key`);return n}getIntentsFromV2AppDefinition(e){const t=e.interop?.intents?.listensFor;if(!t)return;return Object.entries(t).map((e=>{const[t,n]=e;return{name:t,...n}}))}getIconFromDefinition(e,t){return"1.2"===t?e.icons?.find((e=>e.icon))?.icon||void 0:e.icons?.find((e=>e.src))?.src||void 0}mergeBaseAppDataWithGlueManifest(e,t){let n=e;if(t.details){const i={...e.createOptions,...t.details};n.createOptions=i,n.userProperties.details=i}return Array.isArray(t.intents)&&(n.userProperties.intents=(n.userProperties.intents||[]).concat(t.intents)),n={...n,...t},delete n.details,delete n.intents,n}mergeDesktopConfigWithGlueManifest(e,t){const n=Object.assign({},e,t,{details:{...e.details,...t.details}});return Array.isArray(t.intents)&&(n.intents=(e.intents||[]).concat(t.intents)),n}}const Pe={common:{nonEmptyStringDecoder:ce,nonNegativeNumberDecoder:de},fdc3:{allDefinitionsDecoder:xe,v1DefinitionDecoder:Ie,v2DefinitionDecoder:_e}};var Re;!function(e){e.USER_CANCELLED="User Closed Intents Resolver UI without choosing a handler",e.CALLER_NOT_DEFINED="Caller Id is not defined",e.TIMEOUT_HIT="Timeout hit",e.INTENT_NOT_FOUND="Cannot find Intent",e.HANDLER_NOT_FOUND="Cannot find Intent Handler",e.TARGET_INSTANCE_UNAVAILABLE="Cannot start Target Instance",e.INTENT_DELIVERY_FAILED="Target Instance did not add a listener",e.RESOLVER_UNAVAILABLE="Intents Resolver UI unavailable",e.RESOLVER_TIMEOUT="User did not choose a handler",e.INVALID_RESOLVER_RESPONSE="Intents Resolver UI returned invalid response",e.INTENT_HANDLER_REJECTION="Intent Handler function processing the raised intent threw an error or rejected the promise it returned"}(Re||(Re={}));const Ae=new class{_fdc3;_decoders=Pe;_errors={intents:Re};get fdc3(){return this._fdc3||(this._fdc3=(new Te).toApi()),this._fdc3}get decoders(){return this._decoders}get errors(){return this._errors}};Ae.fdc3;const Me=Ae.decoders;Ae.errors;const Ee=P().where((e=>e.length>0),"Expected a non-empty string"),Oe=R().where((e=>e>=0),"Expected a non-negative number"),De=j(Ee),je=N(E("system"),E("windows"),E("appManager"),E("layouts"),E("intents"),E("notifications"),E("channels"),E("extension"),E("themes"),E("prefs")),Ne=N(E("openWindow"),E("windowHello"),E("windowAdded"),E("windowRemoved"),E("getBounds"),E("getFrameBounds"),E("getUrl"),E("moveResize"),E("focus"),E("close"),E("getTitle"),E("setTitle"),E("focusChange"),E("getChannel"),E("notifyChannelsChanged")),Le=N(E("appHello"),E("appDirectoryStateChange"),E("instanceStarted"),E("instanceStopped"),E("applicationStart"),E("instanceStop"),E("clear")),Fe=N(E("layoutAdded"),E("layoutChanged"),E("layoutRemoved"),E("layoutRenamed"),E("get"),E("getAll"),E("export"),E("import"),E("remove"),E("rename"),E("clientSaveRequest"),E("getGlobalPermissionState"),E("checkGlobalActivated"),E("requestGlobalPermission"),E("getDefaultGlobal"),E("setDefaultGlobal"),E("clearDefaultGlobal"),E("updateMetadata")),$e=N(E("raiseNotification"),E("requestPermission"),E("notificationShow"),E("notificationClick"),E("getPermission"),E("list"),E("notificationRaised"),E("notificationClosed"),E("click"),E("clear"),E("clearAll"),E("configure"),E("getConfiguration"),E("configurationChanged"),E("setState"),E("clearOld"),E("activeCountChange"),E("stateChange")),We=N(E("getEnvironment"),E("getBase"),E("platformShutdown"),E("isFdc3DataWrappingSupported"),E("clientError"),E("systemHello")),qe=N(E("top"),E("left"),E("right"),E("bottom")),Ge=O({top:R(),left:R(),width:Oe,height:Oe}),Be=j(O({top:j(R()),left:j(R()),width:j(Oe),height:j(Oe),context:j(M()),relativeTo:j(Ee),relativeDirection:j(qe),windowId:j(Ee),layoutComponentId:j(Ee)})),Ue=O({name:Ee,url:Ee,options:Be}),He=O({windowId:j(Ee)}),Je=O({windowId:Ee,name:Ee}),Ke=O({windowId:Ee}),ze=O({windows:D(Je),isWorkspaceFrame:A()}),Ve=O({windowId:Ee,title:P()}),Qe=O({windowId:Ee,hasFocus:A()}),Xe=O({windowId:Ee,top:j(R()),left:j(R()),width:j(Oe),height:j(Oe),relative:j(A())}),Ye=O({windowId:Ee,bounds:O({top:R(),left:R(),width:Oe,height:Oe})}),Ze=O({bounds:O({top:R(),left:R(),width:Oe,height:Oe})}),et=O({windowId:Ee,url:Ee}),tt=M(),nt=O({top:j(R()),left:j(R()),width:j(Oe),height:j(Oe)}),it=O({id:Ee,applicationName:Ee}),st=O({flags:P()}),rt=O({flags:P()}),ot=O({windowId:Ee,channelsNames:D(Ee)}),at=O({enabled:A()}),ct=O({url:Ee,top:j(R()),left:j(R()),width:j(Oe),height:j(Oe),workspacesSandbox:j(rt),channelSelector:j(at),iframePermissionsPolicy:j(st)}),dt=O({name:Ee,displayName:j(P()),contexts:j(D(P())),customConfig:j(O())});O({name:Ee,title:j(Ee),version:j(Ee),appId:j(Ee),manifest:Ee,manifestType:Ee,tooltip:j(Ee),description:j(Ee),contactEmail:j(Ee),supportEmail:j(Ee),publisher:j(Ee),images:j(D(O({url:j(Ee)}))),icons:j(D(O({icon:j(Ee)}))),customConfig:M(),intents:j(D(dt))});const lt=O({name:Ee,type:Ee.where((e=>"window"===e),"Expected a value of window"),title:j(Ee),version:j(Ee),customProperties:j(M()),icon:j(P()),caption:j(P()),details:ct,intents:j(D(dt)),hidden:j(A()),fdc3:j(Me.fdc3.v2DefinitionDecoder)}),ht=N(lt,Me.fdc3.v2DefinitionDecoder,Me.fdc3.v1DefinitionDecoder);O({definitions:D(ht),mode:N(E("replace"),E("merge"))});const ut=O({name:Ee}),pt=O({definitions:D(lt)}),gt=O({name:Ee,type:Ee.where((e=>"window"===e),"Expected a value of window"),instances:D(it),userProperties:j(M()),title:j(Ee),version:j(Ee),icon:j(Ee),caption:j(Ee)}),mt=O({name:Ee,type:Ee.where((e=>"window"===e),"Expected a value of window"),userProperties:M(),title:j(Ee),version:j(Ee),icon:j(Ee),caption:j(Ee)}),ft=O({appsAdded:D(mt),appsChanged:D(mt),appsRemoved:D(mt)}),bt=O({apps:D(gt),initialChannelId:j(Ee)}),wt=O({id:Ee}),yt=O({name:Ee,waitForAGMReady:A(),id:j(Ee),context:j(M()),top:j(R()),left:j(R()),width:j(Oe),height:j(Oe),relativeTo:j(Ee),relativeDirection:j(qe),forceChromeTab:j(A()),layoutComponentId:j(Ee),channelId:j(Ee)}),vt=N(E("Global"),E("Activity"),E("ApplicationDefault"),E("Swimlane"),E("Workspace")),Ct=N(E("application"),E("activity")),It=O({context:j(M()),bounds:Ge,createArgs:O({name:j(Ee),url:j(Ee),context:j(M())}),windowState:j(Ee),restoreState:j(Ee),instanceId:Ee,isCollapsed:j(A()),isSticky:j(A()),restoreSettings:O({groupId:j(Ee),groupZOrder:j(R())})}),St=O({type:E("window"),componentType:j(Ct),application:Ee,state:It}),_t=O({type:E("window"),config:O({appName:Ee,url:j(Ee),title:j(P()),allowExtract:j(A()),allowReorder:j(A()),showCloseButton:j(A()),isMaximized:j(A())})}),xt=O({type:E("group"),config:M(),children:D(N(_t))}),kt=O({type:E("column"),config:M(),children:D(N(xt,_t,L((()=>kt)),L((()=>Tt))))}),Tt=O({type:E("row"),config:M(),children:D(N(kt,xt,_t,L((()=>Tt))))}),Pt=O({config:M(),context:M(),children:D(N(Tt,kt,xt,_t))}),Rt=O({type:E("Workspace"),application:j(Ee),state:Pt}),At=O({bounds:Ge,instanceId:Ee,selectedWorkspace:Oe,workspaces:D(Pt),windowState:j(Ee),restoreState:j(Ee),context:j(M())}),Mt=O({type:E("workspaceFrame"),application:Ee,componentType:j(Ct),state:At}),Et=O({name:Ee,type:vt,components:D(N(St,Rt,Mt)),context:j(M()),metadata:j(M()),version:j(R())}),Ot=O({name:Ee,context:j(M()),metadata:j(M()),instances:j(D(Ee)),ignoreInstances:j(D(Ee))}),Dt=O({name:Ee,context:j(M()),closeRunningInstance:j(A()),closeMe:j(A()),timeout:j(Oe)}),jt=O({name:Ee,type:vt,context:j(M()),metadata:j(M())}),Nt=O({name:Ee,type:vt}),Lt=O({layout:Ot}),Ft=O({layout:Et,newName:Ee}),$t=O({status:Ee}),Wt=O({layout:Et}),qt=O({layout:Dt}),Gt=O({type:vt}),Bt=O({layouts:D(Et)}),Ut=N(E("replace"),E("merge")),Ht=O({layouts:D(Et),mode:Ut,skipManagerRequest:j(A())}),Jt=O({summaries:D(jt)}),Kt=O({layout:Et}),zt=O({layout:j(Et)}),Vt=O({name:Ee}),Qt=N(E("findIntent"),E("getIntents"),E("raiseIntent"),E("raise"),E("filterHandlers")),Xt=O({applicationName:Ee,applicationTitle:j(P()),applicationDescription:j(P()),applicationIcon:j(P()),type:N(E("app"),E("instance")),displayName:j(P()),contextTypes:j(D(Ee)),instanceId:j(P()),instanceTitle:j(P()),resultType:j(P())});O({applicationName:P(),applicationIcon:j(P()),instanceId:j(P())});const Yt=O({intent:Ee,handler:Xt}),Zt=O({name:Ee,handlers:D(Xt)}),en=N(E("startNew"),E("reuse"),O({app:j(Ee),instance:j(Ee)})),tn=O({type:j(Ee),data:j(M())}),nn=D(Zt),sn=O({intents:nn}),rn=O({name:j(Ee),contextType:j(Ee),resultType:j(Ee)}),on=N(Ee,rn),an=O({filter:j(rn)}),cn=O({intent:Ee,target:j(en),context:j(tn),options:j(Be),handlers:j(D(Xt)),timeout:j(Oe),waitUserResponseIndefinitely:j(A()),clearSavedHandler:j(A())}),dn=N(Ee,cn),ln=O({enabled:A(),appName:Ee,waitResponseTimeout:R()}),hn=O({intentRequest:cn,resolverConfig:ln}),un=O({request:cn,handler:Xt,result:M()}),pn=O({title:j(Ee),openResolver:j(A()),timeout:j(Oe),intent:j(Ee),contextTypes:j(D(Ee)),resultType:j(Ee),applicationNames:j(D(Ee))}),gn=O({handlers:D(Xt)}),mn=O({filterHandlersRequest:pn,resolverConfig:ln}),fn=O({intent:Ee,contextTypes:j(D(Ee)),displayName:j(P()),icon:j(P()),description:j(P()),resultType:j(P())}),bn=N(Ee,fn),wn=O({intent:Ee,contextTypes:j(D(Ee)),description:j(Ee),displayName:j(Ee),icon:j(Ee),resultType:j(Ee)}),yn=O({intents:D(wn)}),vn=e=>Ee.where((t=>e.includes(t)),"Expected a valid channel name"),Cn=O({contextType:j(Ee)}),In=j(N(Ee,O({name:j(Ee),fdc3:j(A())}))),Sn=O({windowId:De,channel:De}),_n=M().where((e=>"string"==typeof e.type),"Expected a valid FDC3 Context with compulsory 'type' field"),xn=O({method:Ee,arguments:j(M()),target:j(N(E("all"),E("best")))}),kn=O({action:P(),title:Ee,icon:j(P()),interop:j(xn)}),Tn=N(E("Active"),E("Acknowledged"),E("Seen"),E("Closed"),E("Stale"),E("Snoozed"),E("Processing")),Pn=O({count:R()}),Rn=O({badge:j(P()),body:j(P()),data:j(M()),dir:j(N(E("auto"),E("ltr"),E("rtl"))),icon:j(P()),image:j(P()),lang:j(P()),renotify:j(A()),requireInteraction:j(A()),silent:j(A()),tag:j(P()),timestamp:j(Oe),vibrate:j(D(R()))}),An=O({title:Ee,clickInterop:j(xn),actions:j(D(kn)),focusPlatformOnDefaultClick:j(A()),badge:j(P()),body:j(P()),data:j(M()),dir:j(N(E("auto"),E("ltr"),E("rtl"))),icon:j(P()),image:j(P()),lang:j(P()),renotify:j(A()),requireInteraction:j(A()),silent:j(A()),tag:j(P()),timestamp:j(Oe),vibrate:j(D(R())),severity:j(N(E("Low"),E("None"),E("Medium"),E("High"),E("Critical"))),showToast:j(A()),showInPanel:j(A()),state:j(Tn)}),Mn=O({id:Ee,state:Tn});O().where((e=>!e.fdc3||"string"==typeof e.fdc3.type),"Expected a valid FDC3 Context with compulsory 'type' field");const En=O({name:Ee,meta:O({color:Ee}),data:j(O())}),On=O({name:Ee}),Dn=O({name:Ee,read:A(),write:A(),windowId:j(Ee)}),jn=O({name:Ee,read:A(),write:A(),windowId:Ee}),Nn=O({config:jn}),Ln=O({channels:D(Dn)}),Fn=O({windowId:Ee}),$n=O({read:A(),write:A(),windowId:j(Ee)}),Wn=O({restrictions:$n}),qn=O({settings:An,id:Ee}),Gn=O({settings:An}),Bn=O({permissionGranted:A()}),Un=O({permission:N(E("default"),E("granted"),E("denied"))}),Hn=O({definition:Rn,action:j(P()),id:j(Ee)}),Jn=O({allowed:j(D(Ee)),blocked:j(D(Ee))}),Kn=O({enable:j(A()),enableToasts:j(A()),sourceFilter:j(Jn)}),zn=O({configuration:Kn}),Vn=O({configuration:O({enable:A(),enableToasts:A(),sourceFilter:O({allowed:D(Ee),blocked:D(Ee)})})}),Qn=O({layoutType:N(E("Global"),E("Workspace")),layoutName:Ee,context:j(M())}),Xn=O({windowContext:j(M())}),Yn=O({state:N(E("prompt"),E("denied"),E("granted"))}),Zn=O({isAvailable:A()}),ei=O({itemId:Ee}),ti=O({isSupported:A()}),ni=O({operation:Ee}),ii=O({bounds:Ge}),si=O({displayName:Ee,name:Ee}),ri=O({theme:si}),oi=O({themes:D(si)}),ai=O({name:Ee}),ci=O({id:Ee,title:Ee,clickInterop:j(xn),actions:j(D(kn)),focusPlatformOnDefaultClick:j(A()),badge:j(P()),body:j(P()),data:j(M()),dir:j(N(E("auto"),E("ltr"),E("rtl"))),icon:j(P()),image:j(P()),lang:j(P()),renotify:j(A()),requireInteraction:j(A()),silent:j(A()),tag:j(P()),timestamp:j(Oe),vibrate:j(D(R())),severity:j(N(E("Low"),E("None"),E("Medium"),E("High"),E("Critical"))),showToast:j(A()),showInPanel:j(A()),state:j(Tn)}),di=O({notification:ci}),li=O({notifications:D(ci)}),hi=O({id:Ee}),ui=O({channel:Ee}),pi=O({windowIds:D(Ee)}),gi=N(E("addChannel"),E("getMyChannel"),E("getWindowIdsOnChannel"),E("getWindowIdsWithChannels"),E("joinChannel"),E("restrict"),E("getRestrictions"),E("restrictAll"),E("notifyChannelsChanged"),E("leaveChannel")),mi=O({channel:j(Ee)}),fi=O({application:j(Ee),channels:j(D(Ee)),windowIds:j(D(Ee))}),bi=O({filter:j(fi)}),wi=O({windowIdsWithChannels:D(O({application:Ee,channel:j(Ee),windowId:Ee}))}),yi=j(M()),vi=j(O({top:j(R()),left:j(R()),width:j(Oe),height:j(Oe),relativeTo:j(Ee),relativeDirection:j(qe),waitForAGMReady:j(A()),channelId:j(Ee),reuseId:j(Ee)})),Ci=O({channel:Ee,windowId:Ee}),Ii=O({windowId:Ee,channelName:j(Ee)}),Si=O({windowId:Ee,channelNames:D(Ee)}),_i=O({channel:j(Ee)}),xi=N(E("clear"),E("clearAll"),E("get"),E("getAll"),E("set"),E("update"),E("prefsChanged"),E("prefsHello")),ki=O({app:Ee,data:O(),lastUpdate:j(Ee)}),Ti=O({app:Ee}),Pi=O({prefs:ki}),Ri=O({all:D(ki)}),Ai=O({app:Ee,data:O()}),Mi=O({platform:O({app:Ee}),validNonExistentApps:j(D(Ee))}),Ei=O({message:Ee}),Oi=O({isClientErrorOperationSupported:A()}),Di={openWindow:{name:"openWindow",dataDecoder:Ue,resultDecoder:Je},windowHello:{name:"windowHello",dataDecoder:He,resultDecoder:ze},windowAdded:{name:"windowAdded",dataDecoder:Je},windowRemoved:{name:"windowRemoved",dataDecoder:Ke},getBounds:{name:"getBounds",dataDecoder:Ke,resultDecoder:Ye},getFrameBounds:{name:"getFrameBounds",dataDecoder:Ke,resultDecoder:Ze},getUrl:{name:"getUrl",dataDecoder:Ke,resultDecoder:et},moveResize:{name:"moveResize",dataDecoder:Xe},focus:{name:"focus",dataDecoder:Ke},close:{name:"close",dataDecoder:Ke},getTitle:{name:"getTitle",dataDecoder:Ke,resultDecoder:Ve},setTitle:{name:"setTitle",dataDecoder:Ve},focusChange:{name:"focusChange",dataDecoder:Qe},getChannel:{name:"getChannel",dataDecoder:Ke,resultDecoder:_i},notifyChannelsChanged:{name:"notifyChannelsChanged",dataDecoder:Si}};function ji(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Ni(e){if(e&&e.errorHandling&&"function"!=typeof e.errorHandling&&"log"!==e.errorHandling&&"silent"!==e.errorHandling&&"throw"!==e.errorHandling)throw new Error('Invalid options passed to createRegistry. Prop errorHandling should be ["log" | "silent" | "throw" | (err) => void], but '+typeof e.errorHandling+" was passed");var t=e&&"function"==typeof e.errorHandling&&e.errorHandling,n={};function i(n,i){var s=n instanceof Error?n:new Error(n);if(t)t(s);else{var r='[ERROR] callback-registry: User callback for key "'+i+'" failed: '+s.stack;if(e)switch(e.errorHandling){case"log":return console.error(r);case"silent":return;case"throw":throw new Error(r)}console.error(r)}}return{add:function(e,t,s){var r=n[e];return r||(r=[],n[e]=r),r.push(t),s&&setTimeout((function(){s.forEach((function(s){var r;if(null===(r=n[e])||void 0===r?void 0:r.includes(t))try{Array.isArray(s)?t.apply(void 0,s):t.apply(void 0,[s])}catch(t){i(t,e)}}))}),0),function(){var i=n[e];i&&(0===(i=i.reduce((function(e,n,i){return n===t&&e.length===i||e.push(n),e}),[])).length?delete n[e]:n[e]=i)}},execute:function(e){for(var t=[],s=1;s<arguments.length;s++)t[s-1]=arguments[s];var r=n[e];if(!r||0===r.length)return[];var o=[];return r.forEach((function(n){try{var s=n.apply(void 0,t);o.push(s)}catch(t){o.push(void 0),i(t,e)}})),o},clear:function(){n={}},clearKey:function(e){n[e]&&delete n[e]}}}Ni.default=Ni;var Li=ji(Ni);class Fi{_id;_name;_bridge;registry=Li();myCtxKey;ctxUnsubscribe;me;constructor(e,t,n){this._id=e,this._name=t,this._bridge=n,this.myCtxKey=`___window___${this.id}`}get id(){return this._id.slice()}get name(){return this._name.slice()}clean(){this.ctxUnsubscribe&&this.ctxUnsubscribe()}processSelfFocusEvent(e){this.me.isFocused=e,this.registry.execute("focus-change",this.me)}processChannelsChangedEvent(e){this.registry.execute("channels-changed",e)}async toApi(){return this.ctxUnsubscribe=await this._bridge.contextLib.subscribe(this.myCtxKey,(e=>this.registry.execute("context-updated",e))),this.me={id:this.id,name:this.name,isFocused:!1,getURL:this.getURL.bind(this),moveResize:this.moveResize.bind(this),resizeTo:this.resizeTo.bind(this),moveTo:this.moveTo.bind(this),focus:this.focus.bind(this),close:this.close.bind(this),getTitle:this.getTitle.bind(this),setTitle:this.setTitle.bind(this),getBounds:this.getBounds.bind(this),getContext:this.getContext.bind(this),updateContext:this.updateContext.bind(this),setContext:this.setContext.bind(this),onContextUpdated:this.onContextUpdated.bind(this),onFocusChanged:this.onFocusChanged.bind(this),getChannel:this.getChannel.bind(this),onChannelsChanged:this.onChannelsChanged.bind(this)},this.me}async getURL(){return(await this._bridge.send("windows",Di.getUrl,{windowId:this.id})).url}onFocusChanged(e){return"function"!=typeof e?m.raiseError("Cannot subscribe to context changes, because the provided callback is not a function!"):this.registry.add("focus-change",e)}async moveResize(e){const t=g(nt,e),n=Object.assign({},t,{windowId:this.id,relative:!1});return await this._bridge.send("windows",Di.moveResize,n),this.me}async resizeTo(e,t){if(void 0===e&&void 0===t)return this.me;void 0!==e&&g(Oe,e),void 0!==t&&g(Oe,t);const n=Object.assign({},{width:e,height:t},{windowId:this.id,relative:!0});return await this._bridge.send("windows",Di.moveResize,n),this.me}async moveTo(e,t){if(void 0===e&&void 0===t)return this.me;void 0!==e&&g(R(),e),void 0!==t&&g(R(),t);const n=Object.assign({},{top:e,left:t},{windowId:this.id,relative:!0});return await this._bridge.send("windows",Di.moveResize,n),this.me}async focus(){return"Platform"===this.name?window.open(void 0,this.id):await this._bridge.send("windows",Di.focus,{windowId:this.id}),this.me}async close(){return await this._bridge.send("windows",Di.close,{windowId:this.id}),this.me}async getTitle(){return(await this._bridge.send("windows",Di.getTitle,{windowId:this.id})).title}async setTitle(e){const t=g(Ee,e);return await this._bridge.send("windows",Di.setTitle,{windowId:this.id,title:t}),this.me}async getBounds(){return(await this._bridge.send("windows",Di.getBounds,{windowId:this.id})).bounds}async getContext(){const e=await this._bridge.contextLib.get(this.myCtxKey),{___io___:t,...n}=e;return n}async updateContext(e){const t=g(tt,e);return await this._bridge.contextLib.update(this.myCtxKey,t),this.me}async setContext(e){const t=g(tt,e),n=await this._bridge.contextLib.get(this.myCtxKey),i=n.___io___?{...t,___io___:n.___io___}:t;return await this._bridge.contextLib.set(this.myCtxKey,i),this.me}onContextUpdated(e){if("function"!=typeof e)return m.raiseError("Cannot subscribe to context changes, because the provided callback is not a function!");return this.registry.add("context-updated",(t=>{const{___io___:n,...i}=t;e(i,this.me)}))}async getChannel(){return(await this._bridge.send("windows",Di.getChannel,{windowId:this.id},void 0,{includeOperationCheck:!0})).channel}onChannelsChanged(e){return this.registry.add("channels-changed",e)}}const $i={operationCheck:{name:"operationCheck",dataDecoder:ni,resultDecoder:ti},getWorkspaceWindowFrameBounds:{name:"getWorkspaceWindowFrameBounds",resultDecoder:ii,dataDecoder:ei}},Wi=(e,t,n)=>new Promise(((i,s)=>{const r=setTimeout((()=>{s(n||`Promise timeout hit: ${t}`)}),t);new Promise(e).then((e=>{clearTimeout(r),i(e)})).catch((e=>{clearTimeout(r),s(e)}))}));class qi{focusEventHandler;registry=Li();platformRegistration;ioc;bridge;publicWindowId;allWindowProjections=[];me;logger;isWorkspaceFrame;instanceId;channelsController;async start(e,t){this.logger=e.logger.subLogger("windows.controller.web"),this.logger.trace("starting the web windows controller"),this.publicWindowId=t.publicWindowId,this.addWindowOperationExecutors(),this.ioc=t,this.bridge=t.bridge,this.instanceId=e.interop.instance.instance,this.channelsController=t.channelsController,this.logger.trace(`set the public window id: ${this.publicWindowId}, set the bridge operations and ioc, registering with the platform now`),this.platformRegistration=this.registerWithPlatform(),await this.platformRegistration,await this.initializeFocusTracking(),this.logger.trace("registration with the platform successful, attaching the windows property to glue and returning");const n=this.toApi();e.windows=n}handlePlatformShutdown(){this.registry.clear(),this.allWindowProjections=[],this.focusEventHandler&&(document.removeEventListener("visibilityChange",this.focusEventHandler),window.removeEventListener("focus",this.focusEventHandler),window.removeEventListener("blur",this.focusEventHandler))}async handleBridgeMessage(e){await this.platformRegistration;const t=g(Ne,e.operation),n=Di[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=g(n.dataDecoder,e.data)),await n.execute(i)}async open(e,t,n){g(Ee,e),g(Ee,t);const i=g(Be,n),s=await this.bridge.send("windows",Di.openWindow,{name:e,url:t,options:i});return this.waitForWindowAdded(s.windowId)}list(){return this.allWindowProjections.map((e=>e.api))}findById(e){return g(Ee,e),this.allWindowProjections.find((t=>t.id===e))?.api}toApi(){return{open:this.open.bind(this),my:this.my.bind(this),list:this.list.bind(this),findById:this.findById.bind(this),onWindowAdded:this.onWindowAdded.bind(this),onWindowRemoved:this.onWindowRemoved.bind(this),onWindowGotFocus:this.onWindowGotFocus.bind(this),onWindowLostFocus:this.onWindowLostFocus.bind(this)}}addWindowOperationExecutors(){Di.focusChange.execute=this.handleFocusChangeEvent.bind(this),Di.windowAdded.execute=this.handleWindowAdded.bind(this),Di.windowRemoved.execute=this.handleWindowRemoved.bind(this),Di.getBounds.execute=this.handleGetBounds.bind(this),Di.getFrameBounds.execute=this.handleGetBounds.bind(this),Di.getTitle.execute=this.handleGetTitle.bind(this),Di.getUrl.execute=this.handleGetUrl.bind(this),Di.moveResize.execute=this.handleMoveResize.bind(this),Di.setTitle.execute=this.handleSetTitle.bind(this),Di.getChannel.execute=this.handleGetChannel.bind(this),Di.notifyChannelsChanged.execute=this.handleChannelsChanged.bind(this)}my(){return Object.assign({},this.me)}onWindowAdded(e){return"function"!=typeof e?m.raiseError("Cannot subscribe to window added, because the provided callback is not a function!"):this.registry.add("window-added",e)}onWindowRemoved(e){return"function"!=typeof e?m.raiseError("Cannot subscribe to window removed, because the provided callback is not a function!"):this.registry.add("window-removed",e)}onWindowGotFocus(e){return"function"!=typeof e?m.raiseError("Cannot subscribe to onWindowGotFocus, because the provided callback is not a function!"):this.registry.add("window-got-focus",e)}onWindowLostFocus(e){return"function"!=typeof e?m.raiseError("Cannot subscribe to onWindowLostFocus, because the provided callback is not a function!"):this.registry.add("window-lost-focus",e)}async sayHello(){return await this.bridge.send("windows",Di.windowHello,{windowId:this.publicWindowId})}async registerWithPlatform(){const{windows:e,isWorkspaceFrame:t}=await this.sayHello();if(this.isWorkspaceFrame=t,this.logger.trace("the platform responded to the hello message"),!this.isWorkspaceFrame&&this.publicWindowId){this.logger.trace("i am not treated as a workspace frame, setting my window");const t=e.find((e=>e.windowId===this.publicWindowId));if(!t)return m.raiseError("Cannot initialize the window library, because I received no information about me from the platform");const n=await this.ioc.buildWebWindow(this.publicWindowId,t.name);this.me=n.api,this.allWindowProjections.push(n)}const n=await Promise.all(e.filter((e=>e.windowId!==this.publicWindowId)).map((e=>this.ioc.buildWebWindow(e.windowId,e.name))));this.logger.trace("all windows projections are completed, building the list collection"),this.allWindowProjections.push(...n)}async handleFocusChangeEvent(e){const t=this.allWindowProjections.find((t=>t.id===e.windowId));if(!t)return;t.model.processSelfFocusEvent(e.hasFocus);const n=e.hasFocus?"window-got-focus":"window-lost-focus";this.registry.execute(n,t.api)}async handleWindowAdded(e){if(this.allWindowProjections.some((t=>t.id===e.windowId)))return;const t=await this.ioc.buildWebWindow(e.windowId,e.name);this.allWindowProjections.push(t),this.registry.execute("window-added",t.api)}async handleWindowRemoved(e){const t=this.allWindowProjections.find((t=>t.id===e.windowId));t&&(this.allWindowProjections=this.allWindowProjections.filter((t=>t.id!==e.windowId)),t.model.clean(),this.registry.execute("window-removed",t.api))}async handleGetBounds(){return this.me||this.isWorkspaceFrame?{windowId:this.isWorkspaceFrame?"noop":this.me.id,bounds:{top:window.screenTop,left:window.screenLeft,width:window.innerWidth,height:window.innerHeight}}:m.raiseError("This window cannot report it's bounds, because it is not a Glue Window, most likely because it is an iframe")}async handleGetTitle(){return this.me?{windowId:this.me.id,title:document.title}:m.raiseError("This window cannot report it's title, because it is not a Glue Window, most likely because it is an iframe")}async handleGetUrl(){return this.me?{windowId:this.me.id,url:window.location.href}:m.raiseError("This window cannot report it's url, because it is not a Glue Window, most likely because it is an iframe")}async handleMoveResize(e){const t="number"==typeof e.top?e.top:e.relative?0:window.screenTop,n="number"==typeof e.left?e.left:e.relative?0:window.screenLeft,i="number"==typeof e.height?e.height:e.relative?0:window.innerHeight,s="number"==typeof e.width?e.width:e.relative?0:window.innerWidth,r=e.relative?window.moveBy:window.moveTo,o=e.relative?window.resizeBy:window.resizeTo;r(n,t),o(s,i)}async handleSetTitle(e){document.title=e.title}async initializeFocusTracking(){if(this.isWorkspaceFrame)return void this.logger.trace("Ignoring the focus tracking, because this client is a workspace frame");try{await this.bridge.send("windows",$i.operationCheck,{operation:"focusChange"})}catch(e){return void this.logger.warn("The platform of this client is outdated and does not support focus tracking, disabling focus events for this client.")}const e=document.hasFocus();await this.transmitFocusChange(!0),e||await this.transmitFocusChange(!1),this.defineEventListeners()}processFocusEvent(){const e=document.hasFocus();this.transmitFocusChange(e)}waitForWindowAdded(e){const t=this.allWindowProjections.find((t=>t.id===e));return t?Promise.resolve(t.api):Wi((t=>{const n=this.onWindowAdded((i=>{i.id===e&&(n(),t(i))}))}),3e4,`Timed out waiting for ${e} to be announced`)}async transmitFocusChange(e){const t={windowId:this.me?.id||`iframe-${this.instanceId}`,hasFocus:e};this.me&&(this.me.isFocused=e),await this.bridge.send("windows",Di.focusChange,t)}defineEventListeners(){this.focusEventHandler=this.processFocusEvent.bind(this),document.addEventListener("visibilityChange",this.focusEventHandler),window.addEventListener("focus",this.focusEventHandler),window.addEventListener("blur",this.focusEventHandler)}async handleGetChannel(){if(!this.me)return m.raiseError("This window cannot report it's channel, because it is not a Glue Window, most likely because it is an iframe");const e=this.channelsController.my();return{...e?{channel:e}:{}}}async handleChannelsChanged(e){const t=this.allWindowProjections.find((t=>t.id===e.windowId));t?.model.processChannelsChangedEvent(e.channelNames)}}const Gi="T42.Web.Platform.Control",Bi="T42.Web.Platform.Stream",Ui="T42.Web.Client.Control",Hi="T42.Core.Plus.Themes.Stream";class Ji{coreGlue;communicationId;platformMethodTimeoutMs=1e4;controllers;sub;running;constructor(e,t){this.coreGlue=e,this.communicationId=t}get contextLib(){return this.coreGlue.contexts}get interopInstance(){return this.coreGlue.interop.instance.instance}async stop(){this.running=!1,this.sub.close(),await this.coreGlue.interop.unregister(Ui)}async start(e){this.running=!0,this.controllers=e,await Promise.all([this.checkWaitMethod(Gi),this.checkWaitMethod(Bi)]);const t=this.communicationId,[n]=await Promise.all([this.coreGlue.interop.subscribe(Bi,t?{target:{instance:this.communicationId}}:void 0),this.coreGlue.interop.registerAsync(Ui,((e,t,n,i)=>this.passMessageController(e,n,i)))]);this.sub=n,this.sub.onData((e=>this.passMessageController(e.data)))}getInteropInstance(e){const t=this.coreGlue.interop.servers().find((t=>t.windowId&&t.windowId===e));return{application:t?.application,applicationName:t?.applicationName,peerId:t?.peerId,instance:t?.instance,windowId:t?.windowId}}async send(e,t,n,i,s){if(t.dataDecoder)try{t.dataDecoder.runWithException(n)}catch(e){return m.raiseError(`Unexpected Web->Platform outgoing validation error: ${e.message}, for operation: ${t.name} and input: ${JSON.stringify(e.input)}`)}if(!(!s?.includeOperationCheck||(await this.checkOperationSupported(e,t)).isSupported))return m.raiseError(`Cannot complete operation: ${t.name} for domain: ${e} because this client is connected to a platform which does not support it`);try{const s=await this.transmitMessage(e,t,n,i);return t.resultDecoder&&t.resultDecoder.runWithException(s),s}catch(e){return e?.kind?m.raiseError(`Unexpected Web<-Platform incoming validation error: ${e.message}, for operation: ${t.name} and input: ${JSON.stringify(e.input)}`):m.raiseError(e)}}async createNotificationsSteam(){return this.coreGlue.interop.methods().some((e=>e.name===Hi))?this.coreGlue.interop.subscribe(Hi,this.communicationId?{target:{instance:this.communicationId}}:void 0):m.raiseError("Cannot subscribe to theme changes, because the underlying interop stream does not exist. Most likely this is the case when this client is not connected to Core Plus.")}async checkOperationSupported(e,t){try{return await this.send(e,$i.operationCheck,{operation:t.name})}catch(e){return{isSupported:!1}}}checkWaitMethod(e){return Wi((t=>{if(this.coreGlue.interop.methods().some((t=>{const n=t.name===e,i=!this.communicationId||t.getServers().some((e=>e.instance===this.communicationId));return n&&i})))return t();const n=this.coreGlue.interop.serverMethodAdded((i=>{const s=i.method,r=i.server,o=!this.communicationId||r.instance===this.communicationId;s.name===e&&o&&(n(),t())}))}),this.platformMethodTimeoutMs,`Cannot initiate Glue Web, because a system method's discovery timed out: ${e}`)}passMessageController(e,t,n){const i=je.run(e.domain);if(!i.ok)return void(n&&n(`Cannot execute this client control, because of domain validation error: ${JSON.stringify(i.error)}`));const s=i.result;this.controllers[s].handleBridgeMessage(e).then((e=>{t&&t(e)})).catch((e=>{n&&n(e),console.warn(e)}))}async transmitMessage(e,t,n,i){const s={domain:e,data:n,operation:t.name};let r;const o=`Internal Platform Communication Error. Attempted operation: ${JSON.stringify(t.name)} with data: ${JSON.stringify(n)}. `,a=this.communicationId;try{if(!this.running)throw new Error("Cannot send a control message, because the platform shut down");if(r=await this.coreGlue.interop.invoke(Gi,s,a?{instance:this.communicationId}:void 0,i),!r)throw new Error("Received unsupported result from the platform - empty result");if(!Array.isArray(r.all_return_values)||0===r.all_return_values.length)throw new Error("Received unsupported result from the platform - empty values collection")}catch(e){if(e&&e.all_errors&&e.all_errors.length){const t=e.all_errors[0].message;throw new Error(`${o} -> Inner message: ${t}`)}throw new Error(`${o} -> Inner message: ${e.message}`)}return r.all_return_values[0].returned}}const Ki={appHello:{name:"appHello",dataDecoder:He,resultDecoder:bt},appDirectoryStateChange:{name:"appDirectoryStateChange",dataDecoder:ft},instanceStarted:{name:"instanceStarted",dataDecoder:it},instanceStopped:{name:"instanceStopped",dataDecoder:it},applicationStart:{name:"applicationStart",dataDecoder:yt,resultDecoder:it},instanceStop:{name:"instanceStop",dataDecoder:wt},import:{name:"import"},remove:{name:"remove",dataDecoder:ut},export:{name:"export",resultDecoder:pt},clear:{name:"clear"}};class zi{me;baseApplicationsTimeoutMS=6e4;appImportTimeoutMS=20;registry=Li();ioc;bridge;publicWindowId;applications=[];instances=[];platformRegistration;logger;channelsController;sessionController;handlePlatformShutdown(){this.registry.clear(),this.applications=[],this.instances=[],delete this.me}async start(e,t){this.logger=e.logger.subLogger("appManger.controller.web"),this.logger.trace("starting the web appManager controller"),this.publicWindowId=t.publicWindowId,this.addOperationsExecutors(),this.ioc=t,this.bridge=t.bridge,this.channelsController=t.channelsController,this.sessionController=t.sessionController,this.platformRegistration=this.registerWithPlatform(),await this.platformRegistration,this.logger.trace("registration with the platform successful, attaching the appManager property to glue and returning");const n=this.toApi();e.appManager=n}async handleBridgeMessage(e){await this.platformRegistration;const t=g(Le,e.operation),n=Ki[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=g(n.dataDecoder,e.data)),await n.execute(i)}onInstanceStarted(e){return"function"!=typeof e?m.raiseError("onInstanceStarted requires a single argument of type function"):this.registry.add("instance-started",e,this.instances)}onInstanceStopped(e){return"function"!=typeof e?m.raiseError("onInstanceStopped requires a single argument of type function"):this.registry.add("instance-stopped",e)}async startApplication(e,t,n){const i=await this.channelsController.all();if(n?.channelId&&!i.includes(n.channelId))return m.raiseError(`The channel with name "${n.channelId}" doesn't exist!`);const s={name:e,waitForAGMReady:n?.waitForAGMReady??!0,context:t,top:n?.top,left:n?.left,width:n?.width,height:n?.height,relativeTo:n?.relativeTo,relativeDirection:n?.relativeDirection,id:n?.reuseId,forceChromeTab:n?.forceTab,layoutComponentId:n?.layoutComponentId,channelId:n?.channelId},r=await this.bridge.send("appManager",Ki.applicationStart,s),o=this.applications.find((e=>e.name===r.applicationName));return this.ioc.buildInstance(r,o)}getApplication(e){const t=g(Ee,e);return this.applications.find((e=>e.name===t))}getInstances(){return this.instances.slice()}toApi(){return{myInstance:this.me,inMemory:{import:this.import.bind(this),remove:this.remove.bind(this),export:this.export.bind(this),clear:this.clear.bind(this)},application:this.getApplication.bind(this),applications:this.getApplications.bind(this),instances:this.getInstances.bind(this),onAppAdded:this.onAppAdded.bind(this),onAppChanged:this.onAppChanged.bind(this),onAppRemoved:this.onAppRemoved.bind(this),onInstanceStarted:this.onInstanceStarted.bind(this),onInstanceStopped:this.onInstanceStopped.bind(this)}}addOperationsExecutors(){Ki.appDirectoryStateChange.execute=this.handleAppDirectoryStateChange.bind(this),Ki.instanceStarted.execute=this.handleInstanceStartedMessage.bind(this),Ki.instanceStopped.execute=this.handleInstanceStoppedMessage.bind(this)}async handleAppDirectoryStateChange(e){e.appsAdded.forEach(this.handleApplicationAddedMessage.bind(this)),e.appsChanged.forEach(this.handleApplicationChangedMessage.bind(this)),e.appsRemoved.forEach(this.handleApplicationRemovedMessage.bind(this))}onAppAdded(e){return"function"!=typeof e?m.raiseError("onAppAdded requires a single argument of type function"):this.registry.add("application-added",e,this.applications)}onAppRemoved(e){return"function"!=typeof e?m.raiseError("onAppRemoved requires a single argument of type function"):this.registry.add("application-removed",e)}onAppChanged(e){return"function"!=typeof e?m.raiseError("onAppChanged requires a single argument of type function"):this.registry.add("application-changed",e)}async handleApplicationAddedMessage(e){if(this.applications.some((t=>t.name===e.name)))return;const t=await this.ioc.buildApplication(e,[]),n=this.instances.filter((e=>e.application.name===t.name));t.instances.push(...n),this.applications.push(t),this.registry.execute("application-added",t)}async handleApplicationRemovedMessage(e){const t=this.applications.findIndex((t=>t.name===e.name));if(t<0)return;const n=this.applications[t];this.applications.splice(t,1),this.registry.execute("application-removed",n)}async handleApplicationChangedMessage(e){const t=this.applications.find((t=>t.name===e.name));if(!t)return this.handleApplicationAddedMessage(e);t.title=e.title,t.version=e.version,t.icon=e.icon,t.caption=e.caption,t.userProperties=e.userProperties,this.registry.execute("application-changed",t)}async handleInstanceStartedMessage(e){if(this.instances.some((t=>t.id===e.id)))return;const t=this.applications.find((t=>t.name===e.applicationName));if(!t)return m.raiseError(`Cannot add instance: ${e.id}, because there is no application definition associated with it`);const n=this.ioc.buildInstance(e,t);this.instances.push(n),t.instances.push(n),this.registry.execute("instance-started",n)}async handleInstanceStoppedMessage(e){const t=this.instances.find((t=>t.id===e.id));if(t){const t=this.instances.findIndex((t=>t.id===e.id));this.instances.splice(t,1)}const n=this.applications.find((t=>t.instances.some((t=>t.id===e.id))));if(n){const t=n.instances.findIndex((t=>t.id===e.id));n.instances.splice(t,1)}t&&this.registry.execute("instance-stopped",t)}async import(e,t="replace"){if(g(Ut,t),!Array.isArray(e))return m.raiseError("Import must be called with an array of definitions");if(e.length>1e4)return m.raiseError("Cannot import more than 10000 app definitions in Glue42 Core.");const n=e.reduce(((e,t)=>{const n=ht.run(t);return n.ok?e.valid.push(t):e.invalid.push({app:t?.name,error:JSON.stringify(n.error)}),e}),{valid:[],invalid:[]}),i=this.baseApplicationsTimeoutMS+this.appImportTimeoutMS*n.valid.length;return await this.bridge.send("appManager",Ki.import,{definitions:n.valid,mode:t},{methodResponseTimeoutMs:i}),{imported:n.valid.map((e=>e.name)),errors:n.invalid}}async remove(e){g(Ee,e),await this.bridge.send("appManager",Ki.remove,{name:e},{methodResponseTimeoutMs:this.baseApplicationsTimeoutMS})}async clear(){await this.bridge.send("appManager",Ki.clear,void 0,{methodResponseTimeoutMs:this.baseApplicationsTimeoutMS})}async export(){return(await this.bridge.send("appManager",Ki.export,void 0,{methodResponseTimeoutMs:this.baseApplicationsTimeoutMS})).definitions}getApplications(){return this.applications.slice()}async joinInitialChannel(e){try{await this.channelsController.join(e)}catch(t){this.logger.warn(`Application instance ${this.me} was unable to join the ${e} channel. Reason: ${JSON.stringify(t)}`)}}async registerWithPlatform(){const e=await this.bridge.send("appManager",Ki.appHello,{windowId:this.publicWindowId},{methodResponseTimeoutMs:this.baseApplicationsTimeoutMS});this.logger.trace("the platform responded to the hello message with a full list of apps"),this.applications=await Promise.all(e.apps.map((e=>this.ioc.buildApplication(e,e.instances)))),this.instances=this.applications.reduce(((e,t)=>(e.push(...t.instances),e)),[]),this.me=this.findMyInstance(),this.logger.trace(`all applications were parsed and saved. I am ${this.me?"NOT a":"a"} valid instance`);const{channels:t}=this.sessionController.getWindowData(),n=t?t.currentName:e.initialChannelId;n&&await this.joinInitialChannel(n)}findMyInstance(){for(const e of this.applications){const t=e.instances.find((e=>e.id===this.publicWindowId));if(t)return t}}}class Vi{data;bridge;application;me;myCtxKey;constructor(e,t,n){this.data=e,this.bridge=t,this.application=n,this.myCtxKey=`___instance___${this.data.id}`}toApi(){const e=this.bridge.getInteropInstance(this.data.id),t={id:this.data.id,agm:e,application:this.application,stop:this.stop.bind(this),getContext:this.getContext.bind(this)};return this.me=Object.freeze(t),this.me}async getContext(){return this.bridge.contextLib.get(this.myCtxKey)}async stop(){await this.bridge.send("appManager",Ki.instanceStop,{id:this.data.id})}}class Qi{data;instances;controller;me;constructor(e,t,n){this.data=e,this.instances=t,this.controller=n}toApi(){const e={name:this.data.name,title:this.data.title,version:this.data.version,icon:this.data.icon,caption:this.data.caption,userProperties:this.data.userProperties,instances:this.instances,start:this.start.bind(this),onInstanceStarted:this.onInstanceStarted.bind(this),onInstanceStopped:this.onInstanceStopped.bind(this)};return this.me=e,this.me}onInstanceStarted(e){return"function"!=typeof e?m.raiseError("OnInstanceStarted requires a single argument of type function"):this.controller.onInstanceStarted((t=>{t.application.name===this.data.name&&e(t)}))}onInstanceStopped(e){return"function"!=typeof e?m.raiseError("OnInstanceStarted requires a single argument of type function"):this.controller.onInstanceStopped((t=>{t.application.name===this.data.name&&e(t)}))}async start(e,t){const n=g(yi,e),i=g(vi,t);return this.controller.startApplication(this.data.name,n,i)}}const Xi={layoutAdded:{name:"layoutAdded",dataDecoder:Et},layoutChanged:{name:"layoutChanged",dataDecoder:Et},layoutRemoved:{name:"layoutRemoved",dataDecoder:Et},layoutRenamed:{name:"layoutRenamed",dataDecoder:Et},get:{name:"get",dataDecoder:Nt,resultDecoder:zt},getAll:{name:"getAll",dataDecoder:Gt,resultDecoder:Jt},export:{name:"export",dataDecoder:Gt,resultDecoder:Bt},import:{name:"import",dataDecoder:Ht},remove:{name:"remove",dataDecoder:Nt},rename:{name:"rename",dataDecoder:Ft,resultDecoder:$t},save:{name:"save",dataDecoder:Lt,resultDecoder:Kt},restore:{name:"restore",dataDecoder:qt},clientSaveRequest:{name:"clientSaveRequest",dataDecoder:Qn,resultDecoder:Xn},getGlobalPermissionState:{name:"getGlobalPermissionState",resultDecoder:Yn},requestGlobalPermission:{name:"requestGlobalPermission",resultDecoder:Zn},checkGlobalActivated:{name:"checkGlobalActivated",resultDecoder:Zn},getDefaultGlobal:{name:"getDefaultGlobal",resultDecoder:zt},setDefaultGlobal:{name:"setDefaultGlobal",dataDecoder:Vt},clearDefaultGlobal:{name:"clearDefaultGlobal"},updateMetadata:{name:"updateMetadata",dataDecoder:Wt}};class Yi{defaultLayoutRestoreTimeoutMS=12e4;registry=Li();bridge;logger;windowsController;saveRequestSubscription;handlePlatformShutdown(){this.registry.clear()}async start(e,t){this.logger=e.logger.subLogger("layouts.controller.web"),this.logger.trace("starting the web layouts controller"),this.bridge=t.bridge,this.windowsController=t.windowsController,this.addOperationsExecutors();const n=this.toApi();this.logger.trace("no need for platform registration, attaching the layouts property to glue and returning"),e.layouts=n}async handleBridgeMessage(e){const t=g(Fe,e.operation),n=Xi[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=g(n.dataDecoder,e.data)),await n.execute(i)}toApi(){const e={get:this.get.bind(this),getAll:this.getAll.bind(this),export:this.export.bind(this),import:this.import.bind(this),save:this.save.bind(this),restore:this.restore.bind(this),remove:this.remove.bind(this),onAdded:this.onAdded.bind(this),onChanged:this.onChanged.bind(this),onRemoved:this.onRemoved.bind(this),onSaveRequested:this.subscribeOnSaveRequested.bind(this),getMultiScreenPermissionState:this.getGlobalPermissionState.bind(this),requestMultiScreenPermission:this.requestGlobalPermission.bind(this),getGlobalTypeState:this.checkGlobalActivated.bind(this),getDefaultGlobal:this.getDefaultGlobal.bind(this),setDefaultGlobal:this.setDefaultGlobal.bind(this),clearDefaultGlobal:this.clearDefaultGlobal.bind(this),rename:this.rename.bind(this),onRenamed:this.onRenamed.bind(this),updateMetadata:this.updateMetadata.bind(this)};return Object.freeze(e)}addOperationsExecutors(){Xi.layoutAdded.execute=this.handleOnAdded.bind(this),Xi.layoutChanged.execute=this.handleOnChanged.bind(this),Xi.layoutRemoved.execute=this.handleOnRemoved.bind(this),Xi.layoutRenamed.execute=this.handleOnRenamed.bind(this),Xi.clientSaveRequest.execute=this.handleSaveRequest.bind(this)}async get(e,t){g(Ee,e),g(vt,t);return(await this.bridge.send("layouts",Xi.get,{name:e,type:t})).layout}async getAll(e){g(vt,e);return(await this.bridge.send("layouts",Xi.getAll,{type:e})).summaries}async export(e){g(vt,e);return(await this.bridge.send("layouts",Xi.export,{type:e})).layouts}async import(e,t="replace"){if(g(Ut,t),!Array.isArray(e))return m.raiseError("Import must be called with an array of layouts");if(e.length>1e3)return m.raiseError("Cannot import more than 1000 layouts at once in Glue42 Core.");const n=e.reduce(((e,t)=>{const n=Et.run(t);return n.ok?e.valid.push(t):this.logger.warn(`A layout with name: ${t.name} was not imported, because of error: ${JSON.stringify(n.error)}`),e}),{valid:[]}),i=e.filter((e=>n.valid.some((t=>t.name===e.name))));await this.bridge.send("layouts",Xi.import,{layouts:i,mode:t})}async save(e){g(Ot,e);return(await this.bridge.send("layouts",Xi.save,{layout:e})).layout}async restore(e){g(Dt,e);const t=e.timeout?2*e.timeout:this.defaultLayoutRestoreTimeoutMS;await this.bridge.send("layouts",Xi.restore,{layout:e},{methodResponseTimeoutMs:t})}async remove(e,t){g(vt,e),g(Ee,t),await this.bridge.send("layouts",Xi.remove,{type:e,name:t})}async handleSaveRequest(e){const t={};if(this.saveRequestSubscription)try{const n=this.saveRequestSubscription(e);t.windowContext=n?.windowContext}catch(e){this.logger.warn(`An error was thrown by the onSaveRequested callback, ignoring the callback: ${JSON.stringify(e)}`)}return t}async getGlobalPermissionState(){return await this.bridge.send("layouts",Xi.getGlobalPermissionState,void 0)}async requestGlobalPermission(){const e=(await this.getGlobalPermissionState()).state;if("denied"===e)return{permissionGranted:!1};if("granted"===e)return{permissionGranted:!0};const t=this.windowsController.my(),n=(window.glue42core||window.iobrowser).isPlatformFrame;if("Platform"!==t.name&&!n)return m.raiseError("Cannot request permission for multi-window placement from any app other than the Platform.");return{permissionGranted:(await this.bridge.send("layouts",Xi.requestGlobalPermission,void 0,{methodResponseTimeoutMs:18e4})).isAvailable}}async checkGlobalActivated(){return{activated:(await this.bridge.send("layouts",Xi.checkGlobalActivated,void 0)).isAvailable}}async getDefaultGlobal(){return(await this.bridge.send("layouts",Xi.getDefaultGlobal,void 0,void 0,{includeOperationCheck:!0})).layout}async setDefaultGlobal(e){g(Ee,e),await this.bridge.send("layouts",Xi.setDefaultGlobal,{name:e},void 0,{includeOperationCheck:!0})}async clearDefaultGlobal(){await this.bridge.send("layouts",Xi.clearDefaultGlobal,void 0,void 0,{includeOperationCheck:!0})}async rename(e,t){g(Et,e),g(Ee,t);return await this.bridge.send("layouts",Xi.rename,{layout:e,newName:t},void 0,{includeOperationCheck:!0})}async updateMetadata(e){g(Et,e),await this.bridge.send("layouts",Xi.updateMetadata,{layout:e},void 0,{includeOperationCheck:!0})}onAdded(e){return this.export("Global").then((t=>t.forEach((t=>e(t))))).catch((()=>{})),this.export("Workspace").then((t=>t.forEach((t=>e(t))))).catch((()=>{})),this.registry.add(Xi.layoutAdded.name,e)}onChanged(e){return this.registry.add(Xi.layoutChanged.name,e)}onRemoved(e){return this.registry.add(Xi.layoutRemoved.name,e)}onRenamed(e){return"function"!=typeof e?m.raiseError("Cannot subscribe to onRenamed, because the provided callback is not a function!"):this.registry.add(Xi.layoutRenamed.name,e)}subscribeOnSaveRequested(e){return"function"!=typeof e?m.raiseError("Cannot subscribe to onSaveRequested, because the provided argument is not a valid callback function."):this.saveRequestSubscription?m.raiseError("Cannot subscribe to onSaveRequested, because this client has already subscribed and only one subscription is supported. Consider unsubscribing from the initial one."):(this.saveRequestSubscription=e,()=>{delete this.saveRequestSubscription})}async handleOnAdded(e){this.registry.execute(Xi.layoutAdded.name,e)}async handleOnChanged(e){this.registry.execute(Xi.layoutChanged.name,e)}async handleOnRemoved(e){this.registry.execute(Xi.layoutRemoved.name,e)}async handleOnRenamed(e){this.registry.execute(Xi.layoutRenamed.name,e)}}const Zi={raiseNotification:{name:"raiseNotification",dataDecoder:qn,resultDecoder:Gn},requestPermission:{name:"requestPermission",resultDecoder:Bn},notificationShow:{name:"notificationShow",dataDecoder:Hn},notificationClick:{name:"notificationClick",dataDecoder:Hn},getPermission:{name:"getPermission",resultDecoder:Un},list:{name:"list",resultDecoder:li},notificationRaised:{name:"notificationRaised",dataDecoder:di},notificationClosed:{name:"notificationClosed",dataDecoder:hi},click:{name:"click"},clear:{name:"clear"},clearAll:{name:"clearAll"},clearOld:{name:"clearOld"},configure:{name:"configure",dataDecoder:zn},getConfiguration:{name:"getConfiguration",resultDecoder:Vn},configurationChanged:{name:"configurationChanged",resultDecoder:Vn},setState:{name:"setState",dataDecoder:Mn},activeCountChange:{name:"activeCountChange",resultDecoder:Pn},stateChange:{name:"stateChange",resultDecoder:Mn}};let es=(e=21)=>{let t="",n=e;for(;n--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return t};class ts{registry=Li();logger;bridge;notificationsSettings;notifications={};coreGlue;buildNotificationFunc;handlePlatformShutdown(){this.notifications={},this.registry.clear()}async start(e,t){this.logger=e.logger.subLogger("notifications.controller.web"),this.logger.trace("starting the web notifications controller"),this.bridge=t.bridge,this.coreGlue=e,this.notificationsSettings=t.config.notifications,this.buildNotificationFunc=t.buildNotification;const n=this.toApi();this.addOperationExecutors(),e.notifications=n,this.logger.trace("notifications are ready")}async handleBridgeMessage(e){const t=g($e,e.operation),n=Zi[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=g(n.dataDecoder,e.data)),await n.execute(i)}toApi(){const e={raise:this.raise.bind(this),requestPermission:this.requestPermission.bind(this),getPermission:this.getPermission.bind(this),list:this.list.bind(this),onRaised:this.onRaised.bind(this),onClosed:this.onClosed.bind(this),click:this.click.bind(this),clear:this.clear.bind(this),clearAll:this.clearAll.bind(this),clearOld:this.clearOld.bind(this),configure:this.configure.bind(this),getConfiguration:this.getConfiguration.bind(this),getFilter:this.getFilter.bind(this),setFilter:this.setFilter.bind(this),setState:this.setState.bind(this),onConfigurationChanged:this.onConfigurationChanged.bind(this),onActiveCountChanged:this.onActiveCountChanged.bind(this),onStateChanged:this.onStateChanged.bind(this)};return Object.freeze(e)}async getPermission(){return(await this.bridge.send("notifications",Zi.getPermission,void 0)).permission}async requestPermission(){return(await this.bridge.send("notifications",Zi.requestPermission,void 0)).permissionGranted}async raise(e){const t=g(An,e);t.showToast="boolean"!=typeof t.showToast||t.showToast,t.showInPanel="boolean"!=typeof t.showInPanel||t.showInPanel;if(!await this.requestPermission())return m.raiseError("Cannot raise the notification, because the user has declined the permission request");const n=es(10),i=await this.bridge.send("notifications",Zi.raiseNotification,{settings:t,id:n}),s=this.buildNotificationFunc(i.settings,n);return this.notifications[n]=s,s}async list(){return(await this.bridge.send("notifications",Zi.list,void 0,void 0,{includeOperationCheck:!0})).notifications}onRaised(e){return"function"!=typeof e?m.raiseError("onRaised expects a callback of type function"):this.registry.add("notification-raised",e)}onClosed(e){return"function"!=typeof e?m.raiseError("onClosed expects a callback of type function"):this.registry.add("notification-closed",e)}async click(e,t){g(Ee,e),t&&g(Ee,t),await this.bridge.send("notifications",Zi.click,{id:e,action:t},void 0,{includeOperationCheck:!0})}async clear(e){g(Ee,e),await this.bridge.send("notifications",Zi.clear,{id:e},void 0,{includeOperationCheck:!0})}async clearAll(){await this.bridge.send("notifications",Zi.clearAll,void 0,void 0,{includeOperationCheck:!0})}async clearOld(){await this.bridge.send("notifications",Zi.clearOld,void 0,void 0,{includeOperationCheck:!0})}async configure(e){const t=g(Kn,e);await this.bridge.send("notifications",Zi.configure,{configuration:t},void 0,{includeOperationCheck:!0})}async getConfiguration(){return(await this.bridge.send("notifications",Zi.getConfiguration,void 0,void 0,{includeOperationCheck:!0})).configuration}async getFilter(){return(await this.bridge.send("notifications",Zi.getConfiguration,void 0,void 0,{includeOperationCheck:!0})).configuration.sourceFilter}async setFilter(e){const t=g(Jn,e);return await this.bridge.send("notifications",Zi.configure,{configuration:{sourceFilter:t}},void 0,{includeOperationCheck:!0}),t}async setState(e,t){g(Ee,e),g(Tn,t),await this.bridge.send("notifications",Zi.setState,{id:e,state:t},void 0,{includeOperationCheck:!0})}onConfigurationChanged(e){return"function"!=typeof e?m.raiseError("Cannot subscribe to configuration changed, because the provided callback is not a function!"):this.registry.add("notifications-config-changed",e)}onActiveCountChanged(e){return"function"!=typeof e?m.raiseError("Cannot subscribe to onActiveCountChanged changed, because the provided callback is not a function!"):this.registry.add("notifications-active-count-changed",e)}onStateChanged(e){return"function"!=typeof e?m.raiseError("Cannot subscribe to onStateChanged changed, because the provided callback is not a function!"):this.registry.add("notification-state-changed",e)}addOperationExecutors(){Zi.notificationShow.execute=this.handleNotificationShow.bind(this),Zi.notificationClick.execute=this.handleNotificationClick.bind(this),Zi.notificationRaised.execute=this.handleNotificationRaised.bind(this),Zi.notificationClosed.execute=this.handleNotificationClosed.bind(this),Zi.configurationChanged.execute=this.handleConfigurationChanged.bind(this),Zi.activeCountChange.execute=this.handleActiveCountChanged.bind(this),Zi.stateChange.execute=this.handleNotificationStateChanged.bind(this)}async handleConfigurationChanged(e){this.registry.execute("notifications-config-changed",e.configuration)}async handleActiveCountChanged(e){this.registry.execute("notifications-active-count-changed",e)}async handleNotificationStateChanged(e){this.registry.execute("notification-state-changed",{id:e.id},e.state)}async handleNotificationShow(e){if(!e.id)return;const t=this.notifications[e.id];t&&t.onshow&&t.onshow()}async handleNotificationClick(e){if(!e.action&&this.notificationsSettings?.defaultClick&&this.notificationsSettings.defaultClick(this.coreGlue,e.definition),e.action&&this.notificationsSettings?.actionClicks?.some((t=>t.action===e.action))){const t=this.notificationsSettings?.actionClicks?.find((t=>t.action===e.action));t.handler(this.coreGlue,e.definition)}if(!e.id)return;const t=this.notifications[e.id];t&&t.onclick&&(t.onclick(),delete this.notifications[e.id])}async handleNotificationRaised(e){this.registry.execute("notification-raised",e.notification)}async handleNotificationClosed(e){this.registry.execute("notification-closed",e)}}const ns={getIntents:{name:"getIntents",resultDecoder:sn},findIntent:{name:"findIntent",dataDecoder:an,resultDecoder:sn},raiseIntent:{name:"raiseIntent",dataDecoder:cn,resultDecoder:un},raise:{name:"raise",dataDecoder:hn,resultDecoder:un},filterHandlers:{name:"filterHandlers",dataDecoder:mn,resultDecoder:gn},getIntentsByHandler:{name:"getIntentsByHandler",dataDecoder:Xt,resultDecoder:yn}},is=2147483647,ss=9e4;class rs{bridge;logger;interop;legacyIntentsController;myIntents=new Set;prefsController;useIntentsResolverUI=!0;intentsResolverAppName;intentResolverResponseTimeout;unregisterIntentPromises=[];async start(e,t){this.logger=e.logger.subLogger("intents.controller.web"),this.logger.trace("starting the web intents controller"),this.bridge=t.bridge,this.interop=e.interop,this.legacyIntentsController=t.legacyIntentsHelper,this.prefsController=t.prefsController,this.checkIfIntentsResolverIsEnabled(t.config);const n=this.toApi();this.logger.trace("no need for platform registration, attaching the intents property to glue and returning"),e.intents=n}handlePlatformShutdown(){this.myIntents=new Set,this.unregisterIntentPromises=[]}async handleBridgeMessage(e){const t=g(Qt,e.operation),n=ns[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=g(n.dataDecoder,e.data)),await n.execute(i)}toApi(){return{raise:this.raise.bind(this),all:this.all.bind(this),addIntentListener:this.addIntentListener.bind(this),register:this.register.bind(this),find:this.find.bind(this),filterHandlers:this.filterHandlers.bind(this),getIntents:this.getIntentsByHandler.bind(this),clearSavedHandlers:this.clearSavedHandlers.bind(this)}}async raise(e){const t=g(dn,e),n="string"==typeof t?{intent:t}:t;await Promise.all(this.unregisterIntentPromises),n.clearSavedHandler&&(this.logger.trace(`User removes saved handler for intent ${n.intent}`),await this.removeRememberedHandler(n.intent));const i=await this.checkHandleRaiseWithRememberedHandler(n);if(i)return i;const s={intentRequest:n,resolverConfig:this.getResolverConfigByRequest({intentRequest:n})},r=await this.isRaiseOperationSupported();if(!r.supported)return this.logger.warn(`${r.reason}. Invoking legacy raise method`),this.legacyIntentsController.raise(s,this.find.bind(this));this.logger.trace(`Sending raise request to the platform: ${JSON.stringify(e)} and method response timeout of ${this.intentResolverResponseTimeout}ms`);const o=n.waitUserResponseIndefinitely?is:(n.timeout||this.intentResolverResponseTimeout)+3e4;return await this.bridge.send("intents",ns.raise,s,{methodResponseTimeoutMs:o,waitTimeoutMs:o})}getResolverConfigByRequest(e){if(e.handlerFilter)return{enabled:"boolean"==typeof e.handlerFilter?.openResolver?e.handlerFilter?.openResolver:this.useIntentsResolverUI,appName:this.intentsResolverAppName,waitResponseTimeout:e.handlerFilter?.timeout||ss};const t=e.intentRequest?.waitUserResponseIndefinitely?is:this.intentResolverResponseTimeout;return{enabled:this.useIntentsResolverUI,appName:this.intentsResolverAppName,waitResponseTimeout:t}}async isRaiseOperationSupported(){try{const{isSupported:e}=await this.bridge.send("intents",$i.operationCheck,{operation:"raise"});return{supported:e,reason:e?"":'The platform of this client is outdated and does not support "raise" operation'}}catch(e){return{supported:!1,reason:'The platform of this client is outdated and does not support "operationCheck" command'}}}async all(){await Promise.all(this.unregisterIntentPromises);return(await this.bridge.send("intents",ns.getIntents,void 0)).intents}addIntentListener(e,t){if(g(bn,e),"function"!=typeof t)return m.raiseError("Cannot add intent listener, because the provided handler is not a function!");let n;const i="string"==typeof e?e:e.intent,s=this.buildInteropMethodName(i);if(this.myIntents.has(i))return m.raiseError(`Intent listener for intent ${i} already registered!`);this.myIntents.add(i);const r={unsubscribe:()=>{this.myIntents.delete(i),n.then((()=>this.interop.unregister(s))).catch((e=>this.logger.trace(`Unregistration of a method with name ${s} failed with reason: ${e}`)))}};let o={};if("object"==typeof e){const{intent:t,...n}=e;o=n}return n=this.interop.register({name:s,flags:{intent:o}},(e=>{if(this.myIntents.has(i)){const{_initialCallerId:n,...i}=e;return t(i)}})),n.catch((e=>{this.myIntents.delete(i),this.logger.warn(`Registration of a method with name ${s} failed with reason: ${e}`)})),r}async register(e,t){if(g(bn,e),"function"!=typeof t)return m.raiseError("Cannot add intent listener, because the provided handler is not a function!");await Promise.all(this.unregisterIntentPromises);const n="string"==typeof e?e:e.intent,i=this.buildInteropMethodName(n);if(this.myIntents.has(n))return m.raiseError(`Intent listener for intent ${n} already registered!`);this.myIntents.add(n);let s={};if("object"==typeof e){const{intent:t,...n}=e;s=n}try{await this.interop.register({name:i,flags:{intent:s}},(e=>{if(this.myIntents.has(n)){const{_initialCallerId:n,...i}=e,s=this.interop.servers().find((e=>e.instance===n));return t(i,s)}}))}catch(e){return this.myIntents.delete(n),m.raiseError(`Registration of a method with name ${i} failed with reason: ${JSON.stringify(e)}`)}return{unsubscribe:()=>this.unsubscribeIntent(n)}}async find(e){let t;if(void 0!==e){const n=g(on,e);"string"==typeof n?t={filter:{name:n}}:"object"==typeof n&&(t={filter:n})}await Promise.all(this.unregisterIntentPromises);return(await this.bridge.send("intents",ns.findIntent,t)).intents}async clearSavedHandlers(){this.logger.trace("Removing all saved handlers from prefs storage for current app"),await this.prefsController.update({intents:void 0})}checkIfIntentsResolverIsEnabled(e){this.useIntentsResolverUI="boolean"!=typeof e.intents?.enableIntentsResolverUI||e.intents.enableIntentsResolverUI,this.intentsResolverAppName=e.intents?.intentsResolverAppName??"intentsResolver",this.intentResolverResponseTimeout=e.intents?.methodResponseTimeoutMs??6e4}clearUnregistrationPromise(e){this.unregisterIntentPromises=this.unregisterIntentPromises.filter((t=>t!==e))}buildInteropMethodName(e){return`Tick42.FDC3.Intents.${e}`}unsubscribeIntent(e){this.myIntents.delete(e);const t=this.buildInteropMethodName(e),n=this.interop.unregister(t);this.unregisterIntentPromises.push(n),n.then((()=>{this.clearUnregistrationPromise(n)})).catch((e=>{this.logger.error(`Unregistration of a method with name ${t} failed with reason: ${e}`),this.clearUnregistrationPromise(n)}))}async filterHandlers(e){if(g(pn,e),this.checkIfAtLeastOneFilterIsPresent(e),e.openResolver&&!this.useIntentsResolverUI)return m.raiseError("Cannot resolve 'filterHandlers' request using Intents Resolver UI because it's globally disabled");const t=(e.timeout||ss)+3e4,n={filterHandlersRequest:e,resolverConfig:this.getResolverConfigByRequest({handlerFilter:e})};return await this.bridge.send("intents",ns.filterHandlers,n,{methodResponseTimeoutMs:t,waitTimeoutMs:t},{includeOperationCheck:!0})}checkIfAtLeastOneFilterIsPresent(e){const t="Provide at least one filter criteria of the following: 'intent' | 'contextTypes' | 'resultType' | 'applicationNames'";if(!Object.keys(e).length)return m.raiseError(t);const{intent:n,resultType:i,contextTypes:s,applicationNames:r}=e,o=s?.length,a=r?.length;return n||i||o||a?void 0:m.raiseError(t)}async getIntentsByHandler(e){g(Xt,e);return await this.bridge.send("intents",ns.getIntentsByHandler,e,void 0,{includeOperationCheck:!0})}async removeRememberedHandler(e){this.logger.trace(`Removing saved handler from prefs storage for intent ${e}`);const t=await this.prefsController.get(),n=t.data?.intents;if(!n)return void this.logger.trace("No app prefs found for current app");delete n[e];const i={...t.data,intents:n};await this.prefsController.update(i),this.logger.trace(`Handler saved choice for intent ${e} removed successfully`)}async checkForRememberedHandler(e){const t=await this.prefsController.get(),n=t.data?.intents?.[e.intent];return n?.handler}async checkHandleRaiseWithRememberedHandler(e){if(e.target)return;const t=await this.checkForRememberedHandler(e);if(!t)return;const n={intentRequest:{...e,target:{app:t.applicationName,instance:t.instanceId}},resolverConfig:{enabled:!1,appName:this.intentsResolverAppName,waitResponseTimeout:e.timeout||ss}};try{return await this.bridge.send("intents",ns.raise,n)}catch(t){this.logger.trace("Could not raise intent to remembered handler. Removing it from Prefs store"),await this.removeRememberedHandler(e.intent)}}}const os={addChannel:{name:"addChannel",dataDecoder:En},removeChannel:{name:"removeChannel",dataDecoder:On},getMyChannel:{name:"getMyChannel",resultDecoder:mi},getWindowIdsOnChannel:{name:"getWindowIdsOnChannel",dataDecoder:ui,resultDecoder:pi},getWindowIdsWithChannels:{name:"getWindowIdsWithChannels",dataDecoder:bi,resultDecoder:wi},joinChannel:{name:"joinChannel",dataDecoder:Ci},restrict:{name:"restrict",dataDecoder:Nn},getRestrictions:{name:"getRestrictions",dataDecoder:Fn,resultDecoder:Ln},restrictAll:{name:"restrictAll",dataDecoder:Wn},notifyChannelsChanged:{name:"notifyChannelsChanged",dataDecoder:Si},leaveChannel:{name:"leaveChannel",dataDecoder:Ii},requestChannelSelector:{name:"requestChannelSelector",dataDecoder:ot}};class as{registry=Li();logger;contexts;bridge;currentChannelName;windowsController;sessionController;unsubscribeFunc;GlueWebChannelsPrefix="___channel___";SubsKey="subs";ChangedKey="changed";handlePlatformShutdown(){this.registry.clear()}addOperationsExecutors(){os.getMyChannel.execute=this.handleGetMyChannel.bind(this),os.joinChannel.execute=this.handleJoinChannel.bind(this),os.leaveChannel.execute=this.handleLeaveChannel.bind(this),os.restrict.execute=({config:e})=>this.restrict(e),os.getRestrictions.execute=({windowId:e})=>this.getRestrictions(e),os.restrictAll.execute=({restrictions:e})=>this.restrictAll(e)}async start(e,t){this.logger=e.logger.subLogger("channels.controller.web"),this.logger.trace("starting the web channels controller"),this.contexts=e.contexts,this.addOperationsExecutors(),this.bridge=t.bridge,this.windowsController=t.windowsController,this.sessionController=t.sessionController,this.logger.trace("no need for platform registration, attaching the channels property to glue and returning");const n=this.toApi();e.channels=n}async postStart(e,t){try{await this.requestChannelSelector(e.appManager.myInstance)}catch(e){this.logger.warn(`Failed to display channel selector: ${p(e)}`)}}async handleBridgeMessage(e){const t=g(gi,e.operation),n=os[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=g(n.dataDecoder,e.data)),await n.execute(i)}async list(){const e=this.getAllChannelNames();return await Promise.all(e.map((e=>this.get(e))))}my(){return this.current()}async handleGetMyChannel(){const e=this.my();return e?{channel:e}:{}}async join(e,t){const n=this.getAllChannelNames();g(vn(n),e),g(De,t),t&&t!==this.windowsController.my().id?await this.bridge.send("channels",os.joinChannel,{channel:e,windowId:t},void 0,{includeOperationCheck:!0}):await this.switchToChannel(e)}handleJoinChannel({channel:e,windowId:t}){return this.join(e,t)}onChanged(e){return this.changed(e)}async leave(e={}){if(g(Sn,e),!e.windowId||e.windowId===this.windowsController.my().id)return void await this.switchToChannel();const t={windowId:e.windowId,channelName:e.channel};await this.bridge.send("channels",os.leaveChannel,t,void 0,{includeOperationCheck:!0})}handleLeaveChannel(e){return this.leave({channel:e.channelName})}toApi(){const e={subscribe:this.subscribe.bind(this),subscribeFor:this.subscribeFor.bind(this),publish:this.publish.bind(this),all:this.all.bind(this),list:this.list.bind(this),get:this.get.bind(this),join:this.join.bind(this),leave:this.leave.bind(this),current:this.current.bind(this),my:this.my.bind(this),changed:this.changed.bind(this),onChanged:this.onChanged.bind(this),add:this.add.bind(this),remove:this.remove.bind(this),getMy:this.getMy.bind(this),getWindowsOnChannel:this.getWindowsOnChannel.bind(this),getWindowsWithChannels:this.getWindowsWithChannels.bind(this),restrict:this.restrict.bind(this),getRestrictions:this.getRestrictions.bind(this),restrictAll:this.restrictAll.bind(this)};return Object.freeze(e)}createContextName(e){return`${this.GlueWebChannelsPrefix}${e}`}getAllChannelNames(){return this.contexts.all().filter((e=>e.startsWith(this.GlueWebChannelsPrefix))).map((e=>e.replace(this.GlueWebChannelsPrefix,"")))}unsubscribe(){this.unsubscribeFunc&&(this.unsubscribeFunc(),this.unsubscribeFunc=void 0)}async switchToChannel(e){if(this.unsubscribe(),this.currentChannelName=e,void 0!==e){const t=this.createContextName(e);this.unsubscribeFunc=await this.contexts.subscribe(t,((e,t,n,i,s)=>{this.registry.execute(this.SubsKey,e.data,e,s?.updaterId)}))}this.registry.execute(this.ChangedKey,e),this.sessionController.setWindowData({currentName:e},"channels");const t=this.windowsController.my().id;if(!t)return;const n=this.currentChannelName?[this.currentChannelName]:[];try{await this.bridge.send("channels",os.notifyChannelsChanged,{channelNames:n,windowId:t},void 0,{includeOperationCheck:!0})}catch(e){this.logger.warn(`Failed to notify channel changed: ${p(e)}`)}}async updateData(e,t){const n=this.createContextName(e),i=this.getFDC3Type(t);if(this.contexts.setPathSupported){const e=Object.keys(t).map((e=>({path:`data.${e}`,value:t[e]})));i&&e.push({path:h,value:i}),await this.contexts.setPaths(n,e)}else i&&(t[h]=i),await this.contexts.update(n,{data:t})}getFDC3Type(e){const t=Object.keys(e).filter((e=>0===e.indexOf("fdc3_")));if(0!==t.length)return t.length>1?m.raiseError("FDC3 does not support updating of multiple context keys"):t[0].split("_").slice(1).join("_")}subscribe(e,t){if("function"!=typeof e)return m.raiseError("Cannot subscribe to channels, because the provided callback is not a function!");t&&g(Cn,t);const n=this.current(),i=t?.contextType?this.getWrappedSubscribeCallbackWithFdc3Type(e,t.contextType):this.getWrappedSubscribeCallback(e);return n&&this.replaySubscribe(i,n),this.registry.add(this.SubsKey,i)}async subscribeFor(e,t,n){const i=this.getAllChannelNames();if(g(vn(i),e),"function"!=typeof t)return m.raiseError(`Cannot subscribe to channel ${e}, because the provided callback is not a function!`);n&&g(Cn,n);const s=this.createContextName(e),r=n?.contextType?this.getWrappedSubscribeCallbackWithFdc3Type(t,n.contextType):this.getWrappedSubscribeCallback(t);return this.contexts.subscribe(s,((e,t,n,i,s)=>{r(e.data,e,s?.updaterId)}))}async publish(e,t){if("object"!=typeof e)return m.raiseError("Cannot publish to channel, because the provided data is not an object!");if(g(In,t),"object"==typeof t)return this.publishWithOptions(e,t);if("string"==typeof t){const e=this.getAllChannelNames();g(vn(e),t)}const n="string"==typeof t?t:this.currentChannelName;if(!n)return m.raiseError("Cannot publish to channel, because not joined to a channel!");return this.isAllowedByRestrictions(n,"write")?this.updateData(n,e):m.raiseError(`Cannot publish on channel ${n} due to restrictions`)}async all(){return this.getAllChannelNames()}async get(e,t){const n=this.getAllChannelNames();g(vn(n),e),t&&g(Cn,t);const i=this.createContextName(e),s=await this.contexts.get(i);return t?.contextType?this.getContextForFdc3Type(s,t.contextType):s.latest_fdc3_type?this.getContextWithFdc3Data(s):s}getContextForFdc3Type(e,t){const n=`fdc3_${t.split(".").join("&")}`;if(!e.data[n])return{name:e.name,meta:e.meta,data:{}};const i={type:t,...e.data[n]};return{name:e.name,meta:e.meta,data:{fdc3:i}}}getContextWithFdc3Data(e){const{latest_fdc3_type:t,...n}=e,i={type:t.split("&").join("."),...n.data[`fdc3_${t}`]};delete n.data[`fdc3_${t}`];return{name:e.name,meta:e.meta,data:{...n.data,fdc3:i}}}current(){return this.currentChannelName}changed(e){return"function"!=typeof e?m.raiseError("Cannot subscribe to channel changed, because the provided callback is not a function!"):this.registry.add(this.ChangedKey,e)}async add(e){const t=g(En,e);return this.getAllChannelNames().includes(t.name)?m.raiseError("There's an already existing channel with such name"):(await this.bridge.send("channels",os.addChannel,t),{name:t.name,meta:t.meta,data:t.data||{}})}async remove(e){g(Ee,e);if(!this.getAllChannelNames().includes(e))return m.raiseError("There's no channel with such name");await this.bridge.send("channels",os.removeChannel,{name:e},void 0,{includeOperationCheck:!0})}replaySubscribe=(e,t)=>{this.get(t).then((t=>{if("object"==typeof t.data&&Object.keys(t.data).length){const n=this.createContextName(t.name);return this.contexts.subscribe(n,((t,n,i,s,r)=>{e(t.data,t,r?.updaterId)}))}})).then((e=>{e&&"function"==typeof e&&e()})).catch((e=>this.logger.trace(e)))};async getMy(e){if(this.currentChannelName)return e&&g(Cn,e),this.get(this.currentChannelName,e)}async getWindowsOnChannel(e){const t=this.getAllChannelNames();g(vn(t),e);const{windowIds:n}=await this.bridge.send("channels",os.getWindowIdsOnChannel,{channel:e},void 0,{includeOperationCheck:!0});return n.reduce(((e,t)=>{const n=this.windowsController.findById(t);return n?[...e,n]:e}),[])}async getWindowsWithChannels(e){const t=void 0!==e?{filter:g(fi,e)}:{},{windowIdsWithChannels:n}=await this.bridge.send("channels",os.getWindowIdsWithChannels,t,void 0,{includeOperationCheck:!0});return n.reduce(((e,{application:t,channel:n,windowId:i})=>{const s=this.windowsController.findById(i);return s?[...e,{application:t,channel:n,window:s}]:e}),[])}async restrict(e){g(Dn,e);const t=this.getAllChannelNames();g(vn(t),e.name);if(e.windowId&&e.windowId!==this.windowsController.my().id)return this.bridge.send("channels",os.restrict,{config:e},void 0,{includeOperationCheck:!0});const n=this.sessionController.getWindowData(),i=n?.restrictions?{...n.restrictions,[e.name]:e}:{[e.name]:e},s=await this.getMy(),r=this.checkPreviousReadAllowed(s?.name);this.sessionController.setWindowData(i,"restrictions"),s&&!r&&e.read&&s.name===e.name&&this.replaySubscribeCallback(e.name)}async getRestrictions(e){return g(De,e),e&&e!==this.windowsController.my().id?this.bridge.send("channels",os.getRestrictions,{windowId:e},void 0,{includeOperationCheck:!0}):this.getMyRestrictions()}async restrictAll(e){g($n,e);const t=this.getAllChannelNames();if(e.windowId&&e.windowId!==this.windowsController.my().id)return this.bridge.send("channels",os.restrictAll,{restrictions:e},void 0,{includeOperationCheck:!0});const n={};t.forEach((t=>{n[t]={...e,name:t}}));const i=await this.getMy(),s=this.checkPreviousReadAllowed(i?.name);this.sessionController.setWindowData(n,"restrictions"),i&&!s&&e.read&&this.replaySubscribeCallback(i.name)}isAllowedByRestrictions(e,t){const{channels:n}=this.getMyRestrictions();if(!n?.length)return!0;const i=n.find((t=>t.name===e));return!i||i[t]}getMyRestrictions(){const e=this.sessionController.getWindowData();return{channels:Object.values(e?.restrictions||{})}}replaySubscribeCallback(e){const t=this.createContextName(e);this.contexts.subscribe(t,((e,t,n,i,s)=>{this.registry.execute(this.SubsKey,e.data,e,s?.updaterId)})).then((e=>{e&&"function"==typeof e&&e()})).catch((e=>this.logger.error(e)))}checkPreviousReadAllowed(e){if(!e)return!0;const t=this.sessionController.getWindowData().restrictions;return!t?.[e]||t[e].read}async publishWithOptions(e,t){if(t.name){const e=this.getAllChannelNames();g(vn(e),t.name)}const n=t.name||this.currentChannelName;if(!n)return m.raiseError("Cannot publish to channel, because not joined to a channel!");return this.isAllowedByRestrictions(n,"write")?t.fdc3?this.publishFdc3Data(n,e):this.updateData(n,e):m.raiseError(`Cannot publish on channel ${n} due to restrictions`)}async publishFdc3Data(e,t){g(_n,t);const{type:n,...i}=t,s={[`fdc3_${n.split(".").join("&")}`]:i};return this.updateData(e,s)}getWrappedSubscribeCallback(e){return(t,n,i)=>{if(!this.isAllowedByRestrictions(n.name,"read"))return;const{data:s,latest_fdc3_type:r}=n;if(!r)return void e(t,n,i);const o=r.split("&").join("."),a=`fdc3_${r}`,c={type:o,...s[a]},{[a]:d,...l}=t;e({...l,fdc3:c},n,i)}}getWrappedSubscribeCallbackWithFdc3Type(e,t){const n={replayed:!1};return(i,s,r)=>{if(!this.isAllowedByRestrictions(s.name,"read"))return;const{data:o,latest_fdc3_type:a}=s,c=`fdc3_${t.split(".").join("&")}`;if(!o[c])return;if(n.replayed)return this.parseDataAndInvokeSubscribeCallback({latestFdc3TypeEncoded:a,searchedType:t,callback:e,context:s,updaterId:r});const d={type:t,...o[c]};e({fdc3:d},s,r),n.replayed=!0}}parseDataAndInvokeSubscribeCallback(e){const{latestFdc3TypeEncoded:t,searchedType:n,callback:i,context:s,updaterId:r}=e;if(t.split("&").join(".")!==n)return;i({fdc3:{type:n,...s.data[`fdc3_${t}`]}},s,r)}async requestChannelSelector(e){if(!e)return;const t=e.application,n=t.userProperties?.details;if(!n)return;if(!n?.channelSelector?.enabled)return;const{channels:i}=this.sessionController.getWindowData(),s=i?.currentName,r={windowId:e.id,channelsNames:s?[s]:[]};await this.bridge.send("channels",os.requestChannelSelector,r,void 0,{includeOperationCheck:!0})}}const cs={getEnvironment:{name:"getEnvironment",resultDecoder:tt},getBase:{name:"getBase",resultDecoder:tt},platformShutdown:{name:"platformShutdown"},isFdc3DataWrappingSupported:{name:"isFdc3DataWrappingSupported"},clientError:{name:"clientError",dataDecoder:Ei},systemHello:{name:"systemHello",resultDecoder:Oi}};class ds{bridge;ioc;logger;errorPort=u.port2;async start(e,t){this.logger=e.logger.subLogger("system.controller.web"),this.logger.trace("starting the web system controller"),this.bridge=t.bridge,this.ioc=t,this.addOperationsExecutors();let n=!1;try{const e=await this.bridge.send("system",cs.systemHello,void 0,void 0,{includeOperationCheck:!0});n=e.isClientErrorOperationSupported}catch(e){this.logger.warn("The platform of this client is outdated and does not support some system operations.")}this.errorPort.onmessage=async e=>{n&&await this.bridge.send("system",cs.clientError,{message:e.data},void 0,{includeOperationCheck:!0})},await this.setEnvironment()}async handleBridgeMessage(e){const t=g(We,e.operation),n=cs[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=g(n.dataDecoder,e.data)),await n.execute(i)}async processPlatformShutdown(){Object.values(this.ioc.controllers).forEach((e=>e.handlePlatformShutdown?e.handlePlatformShutdown():null)),this.ioc.preferredConnectionController.stop(),this.ioc.eventsDispatcher.stop(),await this.bridge.stop()}async setEnvironment(){const e=await this.bridge.send("system",cs.getEnvironment,void 0),t=await this.bridge.send("system",cs.getBase,void 0),n=window.glue42core||window.iobrowser,i=window.glue42core?"glue42core":"iobrowser",s=Object.assign({},n,t,{environment:e});window[i]=Object.freeze(s)}addOperationsExecutors(){cs.platformShutdown.execute=this.processPlatformShutdown.bind(this),cs.isFdc3DataWrappingSupported.execute=this.handleIsFdc3DataWrappingSupported.bind(this)}async handleIsFdc3DataWrappingSupported(){return{isSupported:!0}}}class ls{onclick=()=>{};onshow=()=>{};id;title;badge;body;data;dir;icon;image;lang;renotify;requireInteraction;silent;tag;timestamp;vibrate;clickInterop;actions;focusPlatformOnDefaultClick;severity;showToast;showInPanel;state;constructor(e,t){this.id=t,this.badge=e.badge,this.body=e.body,this.data=e.data,this.dir=e.dir,this.icon=e.icon,this.image=e.image,this.lang=e.lang,this.renotify=e.renotify,this.requireInteraction=e.requireInteraction,this.silent=e.silent,this.tag=e.tag,this.timestamp=e.timestamp,this.vibrate=e.vibrate,this.title=e.title,this.clickInterop=e.clickInterop,this.actions=e.actions,this.focusPlatformOnDefaultClick=e.focusPlatformOnDefaultClick,this.severity=e.severity,this.showToast=e.showToast,this.showInPanel=e.showInPanel,this.state=e.state}}N(E("clientHello"));const hs={clientHello:{name:"clientHello",resultDecoder:O({widget:O({inject:A()})})}};class us{windowId;logger;bridge;eventsDispatcher;channelsController;config;channels=[];unsubFuncs=[];contentCommands={widgetVisualizationPermission:{name:"widgetVisualizationPermission",handle:this.handleWidgetVisualizationPermission.bind(this)},changeChannel:{name:"changeChannel",handle:this.handleChangeChannel.bind(this)}};handlePlatformShutdown(){this.unsubFuncs.forEach((e=>e())),this.channels=[],this.unsubFuncs=[]}async start(e,t){this.logger=e.logger.subLogger("extension.controller.web"),this.windowId=t.publicWindowId,this.logger.trace("starting the extension web controller"),this.bridge=t.bridge,this.channelsController=t.channelsController,this.eventsDispatcher=t.eventsDispatcher;try{await this.registerWithPlatform()}catch(e){return}this.channels=await this.channelsController.list();const n=this.eventsDispatcher.onContentMessage(this.handleContentMessage.bind(this)),i=this.channelsController.onChanged((e=>{this.eventsDispatcher.sendContentMessage({command:"channelChange",newChannel:e})}));this.unsubFuncs.push(n),this.unsubFuncs.push(i)}async handleBridgeMessage(e){}handleContentMessage(e){if(!e||"string"!=typeof e.command)return;const t=this.contentCommands[e.command];t&&t.handle(e)}async registerWithPlatform(){this.logger.trace("registering with the platform"),this.config=await this.bridge.send("extension",hs.clientHello,{windowId:this.windowId}),this.logger.trace("the platform responded to the hello message with a valid extension config")}async handleWidgetVisualizationPermission(){if(!this.config?.widget.inject)return this.eventsDispatcher.sendContentMessage({command:"permissionResponse",allowed:!1});const e=this.channels.find((e=>e.name===this.channelsController.my()));this.eventsDispatcher.sendContentMessage({command:"permissionResponse",allowed:!0,channels:this.channels,currentChannel:e})}async handleChangeChannel(e){"no-channel"!==e.name?await this.channelsController.join(e.name):await this.channelsController.leave()}}class ps{config;glue;registry=Li();glue42EventName="Glue42";_handleMessage;constructor(e){this.config=e}events={notifyStarted:{name:"notifyStarted",handle:this.handleNotifyStarted.bind(this)},contentInc:{name:"contentInc",handle:this.handleContentInc.bind(this)},requestGlue:{name:"requestGlue",handle:this.handleRequestGlue.bind(this)}};stop(){window.removeEventListener(this.glue42EventName,this._handleMessage)}start(e){this.glue=e,this.wireCustomEventListener(),this.announceStarted()}sendContentMessage(e){this.send("contentOut","glue42core",e)}onContentMessage(e){return this.registry.add("content-inc",e)}wireCustomEventListener(){this._handleMessage=this.handleMessage.bind(this),window.addEventListener(this.glue42EventName,this._handleMessage)}handleMessage(e){const t=e.detail,n=t?.glue42??t?.glue42core;if(!n)return;const i=n.event,s=this.events[i];s&&s.handle(n.message)}announceStarted(){this.send("start","glue42")}handleRequestGlue(){this.config.exposeAPI?this.send("requestGlueResponse","glue42",{glue:this.glue}):this.send("requestGlueResponse","glue42",{error:"Will not give access to the underlying Glue API, because it was explicitly denied upon initialization."})}handleNotifyStarted(){this.announceStarted()}handleContentInc(e){this.registry.execute("content-inc",e)}send(e,t,n){const i={};i[t]={event:e,message:n};const s=new CustomEvent(this.glue42EventName,{detail:i});window.dispatchEvent(s)}}class gs{coreGlue;transactionTimeout=15e3;transactionLocks={};webPlatformTransport;webPlatformMessagesUnsubscribe;reconnectCounter=0;logger;constructor(e){this.coreGlue=e,this.logger=this.coreGlue.logger.subLogger("web.preferred.connection.controller")}stop(){this.webPlatformMessagesUnsubscribe&&this.webPlatformMessagesUnsubscribe()}async start(e){if(e.isPlatformInternal)return void this.logger.trace("This is an internal client to the platform, skipping all client preferred communication logic.");if(!(this.coreGlue.connection.transport.name()===l))return m.raiseError("Cannot initiate the Glue Web Bridge, because the initial connection was not handled by a Web Platform transport.");if(!this.coreGlue.connection.transport.isPreferredActivated)return void this.logger.trace("The platform of this client was configured without a preferred connection, skipping the rest of the initialization.");this.webPlatformTransport=this.coreGlue.connection.transport,this.webPlatformMessagesUnsubscribe=this.webPlatformTransport.onMessage(this.handleWebPlatformMessage.bind(this));const t=await this.getCurrentPlatformTransportState();await this.checkSwitchTransport(t)}handleWebPlatformMessage(e){if("string"==typeof e)return;const i=this.coreGlue.connection.transport.name()===l,s=e.type,c=e.args,d=e.transactionId;return s===n.name?this.handleTransportSwitchRequest(c,d):s!==t.name||i?s===r.name?this.handleGetCurrentTransportResponse(c,d):s===o.name?this.handleCheckPreferredLogic(d):s===a.name?this.handleCheckPreferredConnection(c,d):void 0:this.handlePlatformUnload()}async reEstablishPlatformPort(){try{await this.webPlatformTransport.connect()}catch(e){if(this.logger.trace(`Error when re-establishing port connection to the platform: ${JSON.stringify(e)}`),--this.reconnectCounter,this.reconnectCounter>0)return this.reEstablishPlatformPort();this.logger.warn("This client lost connection to the platform while connected to a preferred GW and was not able to re-connect to the platform.")}this.logger.trace("The connection to the platform was re-established, closing the connection to the web gateway."),this.reconnectCounter=0,this.webPlatformTransport.close();const e=await this.getCurrentPlatformTransportState();await this.checkSwitchTransport(e)}async checkSwitchTransport(e){const t=this.coreGlue.connection.transport.name();if(t===e.transportName)return void this.logger.trace("A check switch was requested, but the platform transport and my transport are identical, no switch is necessary");this.logger.trace(`A check switch was requested and a transport switch is necessary, because this client is now on ${t}, but it should reconnect to ${JSON.stringify(e)}`);const n=await this.coreGlue.connection.switchTransport(e);this.setConnected(),this.logger.trace(`The transport switch was completed with result: ${JSON.stringify(n)}`)}async getCurrentPlatformTransportState(){this.logger.trace("Requesting the current transport state of the platform.");const e=this.setTransaction(s.name);this.sendPlatformMessage(s.name,e.id);const t=await e.lock;return this.logger.trace(`The platform responded with transport state: ${JSON.stringify(t)}`),t}setTransaction(e){const t={},n=es(10),i=new Promise(((i,s)=>{let r=!0;t.lift=e=>{r=!1,delete this.transactionLocks[n],i(e)},t.fail=e=>{r=!1,delete this.transactionLocks[n],s(e)},setTimeout((()=>{r&&(r=!1,this.logger.warn(`Transaction for operation: ${e} timed out.`),delete this.transactionLocks[n],s(`Transaction for operation: ${e} timed out.`))}),this.transactionTimeout)}));return t.lock=i,t.id=n,this.transactionLocks[n]=t,t}sendPlatformMessage(e,t,n){this.logger.trace(`Sending a platform message of type: ${e}, id: ${t} and args: ${JSON.stringify(n)}`),this.webPlatformTransport.sendObject({glue42core:{type:e,args:n,transactionId:t}})}handleTransportSwitchRequest(e,t){this.logger.trace(`Received a transport switch request with id: ${t} and data: ${JSON.stringify(e)}`),this.coreGlue.connection.switchTransport(e.switchSettings).then((e=>{this.logger.trace(`The transport switch was completed with result: ${JSON.stringify(e)}`),this.setConnected(),this.sendPlatformMessage(i.name,t,{success:e.success})})).catch((e=>{this.logger.error(e),this.sendPlatformMessage(i.name,t,{success:!1})}))}handlePlatformUnload(){this.reconnectCounter=5,this.logger.trace("The platform was unloaded while I am connected to a preferred connection, re-establishing the port connection."),this.reEstablishPlatformPort()}handleGetCurrentTransportResponse(e,t){this.logger.trace(`Got a current transport response from the platform with id: ${t} and data: ${JSON.stringify(e)}`);const n=e.transportState,i=this.transactionLocks[t];i?.lift(n)}handleCheckPreferredLogic(e){setTimeout((()=>this.sendPlatformMessage(c.name,e)),0)}handleCheckPreferredConnection(e,t){const n=e.url;this.logger.trace(`Testing the possible connection to: ${n}`),this.checkPreferredConnection(n).then((e=>{this.logger.trace(`The connection to ${n} is possible`),this.sendPlatformMessage(d.name,t,e)})).catch((e=>{this.logger.trace(`The connection to ${n} is not possible`),this.sendPlatformMessage(d.name,t,{error:e})}))}checkPreferredConnection(e){return new Promise((t=>{const n=new WebSocket(e);n.onerror=()=>t({live:!1}),n.onopen=()=>{n.close(),t({live:!0})}}))}setConnected(){this.webPlatformTransport.manualSetReadyState()}}class ms{bridge;interop;appManagerController;windowsController;logger;intentsResolverResponsePromises={};constructor(e,t,n,i,s){this.bridge=t,this.interop=n,this.appManagerController=i,this.windowsController=s,this.logger=this.configureLogger(e)}async raise(e,t){const{intentRequest:n,resolverConfig:i}=e,s=(await t(n.intent)).find((e=>e.name===n.intent));if(!s)return m.raiseError(`Intent with name ${n.intent} not found`);const{open:r,reason:o}=this.checkIfResolverShouldBeOpened(s,n,i);if(!r)return this.logger?.trace(`Intent Resolver UI won't be used. Reason: ${o}`),this.invokeRaiseIntent(n);return await this.raiseIntentWithResolverApp(e)}configureLogger(e){return e.subLogger("intents.legacy.helper.web")}async raiseIntentWithResolverApp(e){const{intentRequest:t,resolverConfig:n}=e;this.logger.trace(`Intents Resolver UI with app name ${n.appName} will be used`);const i=await this.registerResponseMethod();this.logger.trace(`Registered interop method ${i}`);const s=await this.openIntentResolverApplication(e,i);this.logger.trace(`Intents Resolver Instance with id ${s.id} opened`);const r=await this.handleInstanceResponse(s.id),o="app"===r.type?{app:r.applicationName}:{instance:r.instanceId};this.logger.trace(`Intent handler chosen by the user: ${JSON.stringify(o)}`);return await this.invokeRaiseIntent({...t,target:o})}async handleInstanceResponse(e){try{const{handler:t,intent:n}=await this.intentsResolverResponsePromises[e].promise;return this.logger?.trace(`Intent handler chosen for intent ${n}: ${JSON.stringify(t)}`),this.stopResolverInstance(e),t}catch(t){return this.stopResolverInstance(e),m.raiseError(t)}}invokeRaiseIntent(e){return this.bridge.send("intents",ns.raiseIntent,e)}async registerResponseMethod(){const e="T42.Intents.Resolver.Control."+es(10);return await this.interop.register(e,this.resolverResponseHandler.bind(this)),e}async openIntentResolverApplication(e,t){const{intentRequest:n,resolverConfig:i}=e,s=this.buildStartContext(n,t),r=await this.buildStartOptions();this.logger.trace(`Starting Intents Resolver UI with context: ${JSON.stringify(s)} and options: ${r}`);const o=await this.appManagerController.getApplication(i.appName).start(s,r);return this.logger.trace(`Intents Resolver instance with id ${o.id} opened`),this.subscribeOnInstanceStopped(o),this.createResponsePromise(n.intent,o.id,t,i.waitResponseTimeout),o}async cleanUpIntentResolverPromise(e){const t=this.intentsResolverResponsePromises[e];if(!t)return;this.interop.unregister(t.methodName).catch((e=>this.logger.warn(e))),delete this.intentsResolverResponsePromises[e]}buildStartContext(e,t){return{intent:e,callerId:this.interop.instance.instance,methodName:t}}async buildStartOptions(){const e=await this.getTargetBounds();return{top:(e.height-440)/2+e.top,left:(e.width-400)/2+e.left,width:400,height:440}}async getTargetBounds(){const e=await this.tryGetWindowBasedBounds()||await this.tryGetWorkspaceBasedBounds();if(e)return this.logger.trace(`Opening Intents Resolver UI with bounds: ${JSON.stringify(e)}`),e;const t={top:window.screen.availTop||0,left:window.screen.availLeft||0,width:window.screen.width,height:window.screen.height};return this.logger.trace(`Opening Intents Resolver UI relative to my screen bounds: ${JSON.stringify(t)}`),t}async tryGetWindowBasedBounds(){try{const e=await this.windowsController.my().getBounds();return this.logger.trace(`Opening the resolver UI relative to my window bounds: ${JSON.stringify(e)}`),e}catch(e){this.logger.trace(`Failure to get my window bounds: ${JSON.stringify(e)}`)}}async tryGetWorkspaceBasedBounds(){try{await this.bridge.send("workspaces",$i.operationCheck,{operation:"getWorkspaceWindowFrameBounds"});const e=(await this.bridge.send("workspaces",$i.getWorkspaceWindowFrameBounds,{itemId:this.windowsController.my().id})).bounds;return this.logger.trace(`Opening the resolver UI relative to my workspace frame window bounds: ${JSON.stringify(e)}`),e}catch(e){this.logger.trace(`Failure to get my workspace frame window bounds: ${JSON.stringify(e)}`)}}subscribeOnInstanceStopped(e){const{application:t}=e,n=t.onInstanceStopped((i=>{if(i.id!==e.id)return;const s=this.intentsResolverResponsePromises[i.id];if(!s)return n();s.reject(`Cannot resolve raised intent "${s.intent}" - User closed ${t.name} app without choosing an intent handler`),this.cleanUpIntentResolverPromise(i.id),n()}))}createResponsePromise(e,t,n,i){let s=()=>{},r=()=>{};const o=Wi(((e,t)=>{s=e,r=t}),i,`Timeout of ${i}ms hit waiting for the user to choose a handler for intent ${e}`);this.intentsResolverResponsePromises[t]={intent:e,resolve:s,reject:r,promise:o,methodName:n}}resolverResponseHandler(e,t){const n=Yt.run(e),i=t.instance;if(n.ok)return this.logger.trace(`Intent Resolver instance with id ${i} send a valid response: ${JSON.stringify(n.result)}`),this.intentsResolverResponsePromises[i].resolve(n.result);this.logger.trace(`Intent Resolver instance with id ${i} sent an invalid response. Error: ${JSON.stringify(n.error)}`),this.intentsResolverResponsePromises[i].reject(n.error.message),this.stopResolverInstance(i)}stopResolverInstance(e){const t=this.appManagerController.getInstances().find((t=>t.id===e));t&&t.stop().catch((e=>this.logger.error(e)))}checkIfIntentHasMoreThanOneHandler(e,t){return"object"!=typeof t.target&&(t.handlers?t.handlers.length>1:e.handlers.length>1)}checkIfResolverShouldBeOpened(e,t,n){if(!n.enabled)return{open:!1,reason:"Intent Resolver is disabled. Raising intent to first found handler"};if(!this.appManagerController.getApplication(n.appName))return{open:!1,reason:`Application with name ${n.appName} not found`};return this.checkIfIntentHasMoreThanOneHandler(e,t)?{open:!0}:{open:!1,reason:"Raised intent has only one handler"}}}const fs={getCurrent:{name:"getCurrent",resultDecoder:ri},list:{name:"list",resultDecoder:oi},select:{name:"select",dataDecoder:ai}};class bs{logger;bridge;registry=Li();themesSubscription;activeThemeSubs=0;async start(e,t){this.logger=e.logger.subLogger("themes.controller.web"),this.logger.trace("starting the web themes controller"),this.bridge=t.bridge;const n=this.toApi();e.themes=n,this.logger.trace("themes are ready")}handlePlatformShutdown(){this.registry.clear(),this.activeThemeSubs=0,this.themesSubscription?.close(),delete this.themesSubscription}async handleBridgeMessage(){}toApi(){const e={getCurrent:this.getCurrent.bind(this),list:this.list.bind(this),select:this.select.bind(this),onChanged:this.onChanged.bind(this)};return Object.freeze(e)}async getCurrent(){return(await this.bridge.send("themes",fs.getCurrent,void 0,void 0,{includeOperationCheck:!0})).theme}async list(){return(await this.bridge.send("themes",fs.list,void 0,void 0,{includeOperationCheck:!0})).themes}async select(e){g(Ee,e),await this.bridge.send("themes",fs.select,{name:e},void 0,{includeOperationCheck:!0})}async onChanged(e){if("function"!=typeof e)return m.raiseError("onChanged requires a callback of type function");const t=this.themesSubscription?Promise.resolve():this.configureThemeSubscription();await t,++this.activeThemeSubs;const n=this.registry.add("on-theme-change",e);return()=>this.themeUnsub(n)}async configureThemeSubscription(){this.themesSubscription||(this.themesSubscription=await this.bridge.createNotificationsSteam(),this.themesSubscription.onData((e=>{const t=e.data,n=ri.run(t);if(!n.ok)return void this.logger.warn(`Received invalid theme data on the theme event stream: ${JSON.stringify(n.error)}`);const i=n.result;this.registry.execute("on-theme-change",i.theme)})),this.themesSubscription.onClosed((()=>{this.logger.warn("The Themes interop stream was closed, no theme changes notifications will be received"),this.registry.clear(),this.activeThemeSubs=0,delete this.themesSubscription})))}themeUnsub(e){e(),--this.activeThemeSubs,this.activeThemeSubs||(this.themesSubscription?.close(),delete this.themesSubscription)}}class ws{sessionStorage=window.sessionStorage;windowId;get allNamespaces(){return[{namespace:this.windowNamespace,defaultValue:{}}]}configure(e){this.windowId=e.windowId,this.allNamespaces.forEach((({namespace:e,defaultValue:t})=>{this.sessionStorage.getItem(e)||this.sessionStorage.setItem(e,JSON.stringify(t))}))}get windowNamespace(){return`io_connect_window_${this.windowId}`}getWindowData(){return JSON.parse(this.sessionStorage.getItem(this.windowNamespace))}setWindowData(e,t){const n=this.getWindowData();n[t]=e,this.sessionStorage.setItem(this.windowNamespace,JSON.stringify(n))}}const ys={clear:{name:"clear",dataDecoder:Ti},clearAll:{name:"clearAll"},get:{name:"get",dataDecoder:Ti,resultDecoder:Pi},getAll:{name:"getAll",resultDecoder:Ri},set:{name:"set",dataDecoder:Ai},update:{name:"update",dataDecoder:Ai},prefsChanged:{name:"prefsChanged",dataDecoder:Pi},prefsHello:{name:"prefsHello",resultDecoder:Mi}};class vs{bridge;config;logger;appManagerController;platformAppName;registry=Li();validNonExistentApps;handlePlatformShutdown(){this.registry.clear()}async start(e,t){this.logger=e.logger.subLogger("prefs.controller.web"),this.logger.trace("starting the web prefs controller"),this.addOperationsExecutors(),this.bridge=t.bridge,this.config=t.config,this.appManagerController=t.appManagerController;try{const e=await this.bridge.send("prefs",ys.prefsHello,void 0,void 0,{includeOperationCheck:!0});this.platformAppName=e.platform.app,this.validNonExistentApps=e.validNonExistentApps??[]}catch(e){return void this.logger.warn("The platform of this client is outdated and does not support Prefs API.")}this.logger.trace("no need for platform registration, attaching the prefs property to glue and returning");const n=this.toApi();e.prefs=n}async handleBridgeMessage(e){const t=g(xi,e.operation),n=ys[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=g(n.dataDecoder,e.data)),await n.execute(i)}async get(e){const t=null==e?this.getMyAppName():g(Ee,e),{prefs:n}=await this.bridge.send("prefs",ys.get,{app:t},void 0,{includeOperationCheck:!0});return n}async update(e,t){const n=g(j(Ti),t),i=n?.app??this.getMyAppName();await this.updateFor(i,e)}addOperationsExecutors(){ys.prefsChanged.execute=this.handleOnChanged.bind(this)}toApi(){return{clear:this.clear.bind(this),clearAll:this.clearAll.bind(this),clearFor:this.clearFor.bind(this),get:this.get.bind(this),getAll:this.getAll.bind(this),set:this.set.bind(this),setFor:this.setFor.bind(this),subscribe:this.subscribe.bind(this),subscribeFor:this.subscribeFor.bind(this),update:this.update.bind(this),updateFor:this.updateFor.bind(this)}}async clear(){const e=this.getMyAppName();await this.clearFor(e)}async clearAll(){await this.bridge.send("prefs",ys.clearAll,void 0,void 0,{includeOperationCheck:!0})}async clearFor(e){const t=g(Ee,e);await this.bridge.send("prefs",ys.clear,{app:t},void 0,{includeOperationCheck:!0})}async getAll(){return await this.bridge.send("prefs",ys.getAll,void 0,void 0,{includeOperationCheck:!0})}async set(e,t){const n=g(j(Ti),t),i=n?.app??this.getMyAppName();await this.setFor(i,e)}async setFor(e,t){const n=g(Ee,e),i=g(O(),t);await this.bridge.send("prefs",ys.set,{app:n,data:i},void 0,{includeOperationCheck:!0})}subscribe(e){const t=this.getMyAppName();return this.subscribeFor(t,e)}subscribeFor(e,t){const n=g(Ee,e),i=this.appManagerController.getApplications();if(!(n===this.platformAppName||i.some((e=>e.name===n))||this.validNonExistentApps.includes(n)))return m.raiseError(`The provided app name "${e}" is not valid.`);if("function"!=typeof t)return m.raiseError("Cannot subscribe to prefs, because the provided callback is not a function!");const s=this.getSubscriptionKey(n);return this.get(n).then(t),this.registry.add(s,t)}async updateFor(e,t){const n=g(Ee,e),i=g(O(),t);await this.bridge.send("prefs",ys.update,{app:n,data:i},void 0,{includeOperationCheck:!0})}getMyAppName(){const e=this.config.isPlatformInternal?this.platformAppName:this.appManagerController.me?.application.name;return e||m.raiseError("App Preferences operations can not be executed for windows that do not have app!")}getSubscriptionKey(e){return`prefs-changed-${e}`}async handleOnChanged({prefs:e}){const t=this.getSubscriptionKey(e.app);this.registry.execute(t,e)}}class Cs{_coreGlue;_communicationId;_publicWindowId;_webConfig;_windowsControllerInstance;_appManagerControllerInstance;_layoutsControllerInstance;_notificationsControllerInstance;_intentsControllerInstance;_legacyIntentsHelperInstance;_channelsControllerInstance;_themesControllerInstance;_extensionController;_systemControllerInstance;_bridgeInstance;_eventsDispatcher;_preferredConnectionController;_sessionController;_prefsControllerInstance;controllers={windows:this.windowsController,appManager:this.appManagerController,layouts:this.layoutsController,notifications:this.notificationsController,intents:this.intentsController,channels:this.channelsController,system:this.systemController,extension:this.extensionController,themes:this.themesController,prefs:this.prefsController};get communicationId(){return this._communicationId}get publicWindowId(){return this._publicWindowId}get windowsController(){return this._windowsControllerInstance||(this._windowsControllerInstance=new qi),this._windowsControllerInstance}get appManagerController(){return this._appManagerControllerInstance||(this._appManagerControllerInstance=new zi),this._appManagerControllerInstance}get layoutsController(){return this._layoutsControllerInstance||(this._layoutsControllerInstance=new Yi),this._layoutsControllerInstance}get themesController(){return this._themesControllerInstance||(this._themesControllerInstance=new bs),this._themesControllerInstance}get notificationsController(){return this._notificationsControllerInstance||(this._notificationsControllerInstance=new ts),this._notificationsControllerInstance}get intentsController(){return this._intentsControllerInstance||(this._intentsControllerInstance=new rs),this._intentsControllerInstance}get legacyIntentsHelper(){return this._legacyIntentsHelperInstance||(this._legacyIntentsHelperInstance=new ms(this._coreGlue.logger,this.bridge,this._coreGlue.interop,this.appManagerController,this.windowsController)),this._legacyIntentsHelperInstance}get systemController(){return this._systemControllerInstance||(this._systemControllerInstance=new ds),this._systemControllerInstance}get channelsController(){return this._channelsControllerInstance||(this._channelsControllerInstance=new as),this._channelsControllerInstance}get prefsController(){return this._prefsControllerInstance||(this._prefsControllerInstance=new vs),this._prefsControllerInstance}get extensionController(){return this._extensionController||(this._extensionController=new us),this._extensionController}get eventsDispatcher(){return this._eventsDispatcher||(this._eventsDispatcher=new ps(this.config)),this._eventsDispatcher}get bridge(){return this._bridgeInstance||(this._bridgeInstance=new Ji(this._coreGlue,this.communicationId)),this._bridgeInstance}get preferredConnectionController(){return this._preferredConnectionController||(this._preferredConnectionController=new gs(this._coreGlue)),this._preferredConnectionController}get sessionController(){return this._sessionController||(this._sessionController=new ws),this._sessionController}get config(){return this._webConfig}defineGlue(e){this._coreGlue=e,this._publicWindowId=e.connection.transport.publicWindowId;const t=window.glue42core||window.iobrowser;this._communicationId=e.connection.transport.communicationId||t.communicationId}defineConfig(e){this._webConfig=e}async buildWebWindow(e,t){const n=new Fi(e,t,this.bridge),i=await n.toApi();return{id:e,model:n,api:i}}buildNotification(e,t){return new ls(e,t)}async buildApplication(e,t){const n=new Qi(e,[],this.appManagerController).toApi(),i=t.map((e=>this.buildInstance(e,n)));return n.instances.push(...i),n}buildInstance(e,t){return new Vi(e,this.bridge,t).toApi()}}var Is="3.4.8";var Ss={STRING:1,NUMBER:2,TIMESTAMP:3,OBJECT:4};function _s(e){return e.type===Ss.TIMESTAMP?"timestamp":e.type===Ss.NUMBER?"number":e.type===Ss.STRING?"string":e.type===Ss.OBJECT?"object":"unknown"}function xs(e){return e.constructor===Date?"timestamp":"number"==typeof e?"number":"string"==typeof e?"string":"object"==typeof e?"object":"string"}function ks(e){const t={},n=_s(e);if("object"===n){const n=Object.keys(e.value).reduce(((t,n)=>{const i=xs(e.value[n]);if("object"===i){const i=Ts(e.value[n]);t[n]={type:"object",description:"",context:{},composite:i}}else t[n]={type:i,description:"",context:{}};return t}),{});t.composite=n}return t.name=Ps(e.path.join("/")+"/"+e.name),t.type=n,t.description=e.description,t.context={},t}function Ts(e){return Object.keys(e).reduce(((t,n)=>{const i=xs(e[n]);return t[n]="object"===i?{type:"object",description:"",context:{},composite:Ts(e[n])}:{type:i,description:"",context:{}},t}),{})}function Ps(e){return void 0!==e&&e.length>0&&"/"!==e[0]?"/"+e:e}function Rs(e){return"timestamp"===_s(e)?Date.now():As(e.value)}function As(e){return"object"!=typeof e?e:Object.keys(e).reduce(((t,n)=>{const i=e[n];return"object"==typeof i&&i.constructor!==Date?t[n]=As(i):i.constructor===Date?t[n]=new Date(i).getTime():i.constructor===Boolean?t[n]=i.toString():t[n]=i,t}),{})}function Ms(e){return e.reduce(((e,t)=>e.concat(Array.isArray(t)?Ms(t):t)),[])}function Es(e){const t=Ms(e.root.getAggregateState()),n=t.sort(((e,t)=>e.state?t.state?t.state-e.state:-1:1))[0];const i=function(e){let t="";return e.forEach(((e,n,i)=>{const s=e.path.join(".");n===i.length-1?t+=s+"."+e.name+": "+e.description:t+=s+"."+e.name+": "+e.description+","})),t.length>100?t.slice(0,100)+"...":t}(t);return{description:i,value:n.state}}var Os=(e,t,n)=>{if(null===e||"object"!=typeof e)throw new Error("Missing definition");if(null===t||"object"!=typeof t)throw new Error("Missing parent");if(null===n||"object"!=typeof n)throw new Error("Missing transport")};class Ds{definition;system;transport;value;type;path=[];name;description;get repo(){return this.system?.repo}get id(){return`${this.system.path}/${name}`}constructor(e,t,n,i,s){this.definition=e,this.system=t,this.transport=n,this.value=i,this.type=s,Os(e,t,n),this.path=t.path.slice(0),this.path.push(t.name),this.name=e.name,this.description=e.description,n.createMetric(this)}update(e){return this.value=e,this.transport.updateMetric(this)}}class js extends Ds{constructor(e,t,n,i){super(e,t,n,i,Ss.NUMBER)}incrementBy(e){this.update(this.value+e)}increment(){this.incrementBy(1)}decrement(){this.incrementBy(-1)}decrementBy(e){this.incrementBy(-1*e)}}class Ns extends Ds{constructor(e,t,n,i){super(e,t,n,i,Ss.OBJECT)}update(e){return this.mergeValues(e),this.transport.updateMetric(this)}mergeValues(e){return Object.keys(this.value).forEach((t=>{void 0!==e[t]&&(this.value[t]=e[t])}))}}class Ls extends Ds{constructor(e,t,n,i){super(e,t,n,i,Ss.STRING)}}class Fs extends Ds{constructor(e,t,n,i){super(e,t,n,i,Ss.TIMESTAMP)}now(){this.update(new Date)}}function $s(e,t,n,i,s){if(!t)throw new Error("Repository is required");if(!n)throw new Error("Transport is required");const r=n,o=e,a=s||"",c=t,d=i,l=function e(t){if(!t||!t.parent)return[];const n=e(t.parent);return n.push(t.name),n}(i);let h={};const u=(g="/",((p=l)&&p.length>0?p.join(g):"")+e);var p,g;const m=t.root,f=[],b=[];function w(e,t,n,i){let s={name:""};s="string"==typeof e?{name:e}:e;const r=b.filter((e=>e.name===s.name));if(r.length>0){const e=r[0];if(e.type!==t)throw new Error(`A metric named ${s.name} is already defined with different type.`);return void 0!==n&&e.update(n).catch((()=>{})),e}const o=i(s);return b.push(o),o}const y={get name(){return o},get description(){return a},get repo(){return c},get parent(){return d},path:l,id:u,root:m,get subSystems(){return f},get metrics(){return b},subSystem:function(e,t){if(!e||0===e.length)throw new Error("name is required");const n=f.filter((t=>t.name===e));if(n.length>0)return n[0];const i=$s(e,c,r,y,t);return f.push(i),i},getState:()=>h,setState:function(e,t){h={state:e,description:t},r.updateSystem(y,h)},stringMetric:function(e,t){return w(e,Ss.STRING,t,(e=>new Ls(e,y,r,t)))},timestampMetric:function(e,t){return w(e,Ss.TIMESTAMP,t,(e=>new Fs(e,y,r,t)))},objectMetric:function(e,t){return w(e,Ss.OBJECT,t,(e=>new Ns(e,y,r,t)))},numberMetric:function(e,t){return w(e,Ss.NUMBER,t,(e=>new js(e,y,r,t)))},getAggregateState:function(){const e=[];return Object.keys(h).length>0&&e.push({name:o,path:l,state:h.state,description:h.description}),f.forEach((t=>{const n=t.getAggregateState();n.length>0&&e.push(...n)})),e}};return r.createSystem(y),y}class Ws{root;constructor(e,t){t.init(this),this.root=$s("",this,t),this.addSystemMetrics(this.root,e.clickStream||void 0===e.clickStream)}addSystemMetrics(e,t){if("undefined"!=typeof navigator&&e.stringMetric("UserAgent",navigator.userAgent),t&&"undefined"!=typeof document){const t=e.subSystem("ClickStream"),n=e=>{if(!e.target)return;const n=e.target,i=n?n.getAttribute("class")??"":"";t.objectMetric("LastBrowserEvent",{type:"click",timestamp:new Date,target:{className:i,id:n.id,type:"<"+n.tagName.toLowerCase()+">",href:n.href||""}})};t.objectMetric("Page",{title:document.title,page:window.location.href}),document.addEventListener?document.addEventListener("click",n):document.attachEvent("onclick",n)}e.stringMetric("StartTime",(new Date).toString());const n=e.stringMetric("StartURL",""),i=e.stringMetric("AppName","");if("undefined"!=typeof window){if(void 0!==window.location){const e=window.location.href;n.update(e)}void 0!==window.glue42gd&&i.update(window.glue42gd.appName)}}}class qs{init(e){}createSystem(e){return Promise.resolve()}updateSystem(e,t){return Promise.resolve()}createMetric(e){return Promise.resolve()}updateMetric(e){return Promise.resolve()}}class Gs{api;lastCount=0;initialPublishTimeout=1e4;publishInterval=6e4;system;constructor(e,t,n){this.api=e,this.initialPublishTimeout=t??this.initialPublishTimeout,this.publishInterval=n??this.publishInterval,this.scheduleCollection(),this.system=this.api.subSystem("performance","Performance data published by the web application")}scheduleCollection(){setTimeout((()=>{this.collect(),setInterval((()=>{this.collect()}),this.publishInterval)}),this.initialPublishTimeout)}collect(){try{this.collectMemory(),this.collectEntries()}catch{}}collectMemory(){const e=window.performance.memory;this.system.stringMetric("memory",JSON.stringify({totalJSHeapSize:e.totalJSHeapSize,usedJSHeapSize:e.usedJSHeapSize}))}collectEntries(){const e=window.performance.getEntries();if(e.length<=this.lastCount)return;this.lastCount=e.length;const t=e.map((e=>e.toJSON()));this.system.stringMetric("entries",JSON.stringify(t))}}var Bs=e=>{let t;t=e.connection&&"object"==typeof e.connection?function(e,t){if(!e||"object"!=typeof e)throw new Error("Connection is required parameter");let n,i;const s=e=>{r(e.root)},r=e=>{o(e),e.metrics.forEach((e=>{a(e)})),e.subSystems.forEach((e=>{r(e)}))},o=async e=>{if(void 0===e.parent)return;await n;const t={type:"define",metrics:[{name:Ps(e.path.join("/")+"/"+e.name+"/State"),type:"object",composite:{Description:{type:"string",description:""},Value:{type:"number",description:""}},description:"System state",context:{}}]};i.send(t)},a=async e=>{const t=d(e);await n;const s={type:"define",metrics:[ks(t)]};i.send(s),void 0!==t.value&&c(t)},c=e=>{if(l()){const t=Rs(e),n={type:"publish",values:[{name:Ps(e.path.join("/")+"/"+e.name),value:t,timestamp:Date.now()}]};return i.sendFireAndForget(n)}return Promise.resolve()},d=e=>{const t={...e};return"object"==typeof e.value&&null!==e.value&&(t.value={...e.value}),t},l=()=>{try{return(t.canUpdateMetric??(()=>!0))()}catch{return!0}};return{init:r=>{let o;n=new Promise((e=>{o=e})),i=e.domain("metrics"),i.onJoined((e=>{!e&&o&&(o(),o=void 0);const t={type:"define",metrics:[{name:"/State",type:"object",composite:{Description:{type:"string",description:""},Value:{type:"number",description:""}},description:"System state",context:{}}]};i.send(t),e&&s(r)})),i.join({system:t.system,service:t.service,instance:t.instance})},createSystem:o,updateSystem:async(t,s)=>{await n;const r={type:"publish",values:[{name:Ps(t.path.join("/")+"/"+t.name+"/State"),value:{Description:s.description,Value:s.state},timestamp:Date.now()}]};i.send(r);const o=Es(t),a={type:"publish",peer_id:e.peerId,values:[{name:"/State",value:{Description:o.description,Value:o.value},timestamp:Date.now()}]};i.send(a)},createMetric:a,updateMetric:async e=>{const t=d(e);await n,c(t)}}}(e.connection,e):new qs;let n=new Ws(e,t).root;e.disableAutoAppSystem||(n=n.subSystem("App"));const i=function(e){const t=e.subSystem("reporting"),n={name:"features"};let i;const s=(e,s,r)=>{if(void 0===e||""===e)throw new Error("name is mandatory");if(void 0===s||""===s)throw new Error("action is mandatory");if(void 0===r||""===r)throw new Error("payload is mandatory");i?i.update({name:e,action:s,payload:r}):i=t.objectMetric(n,{name:e,action:s,payload:r})};return e.featureMetric=s,e}(n);return function(e,t){if("undefined"==typeof window)return;const n=window?.glue42gd?.metrics?.pagePerformanceMetrics;n&&(t=n);t?.enabled&&new Gs(e,t.initialPublishTimeout,t.publishInterval)}(i,e.pagePerformanceMetrics),i};var Us="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Hs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Js(e){if(e&&e.errorHandling&&"function"!=typeof e.errorHandling&&"log"!==e.errorHandling&&"silent"!==e.errorHandling&&"throw"!==e.errorHandling)throw new Error('Invalid options passed to createRegistry. Prop errorHandling should be ["log" | "silent" | "throw" | (err) => void], but '+typeof e.errorHandling+" was passed");var t=e&&"function"==typeof e.errorHandling&&e.errorHandling,n={};function i(n,i){var s=n instanceof Error?n:new Error(n);if(t)t(s);else{var r='[ERROR] callback-registry: User callback for key "'+i+'" failed: '+s.stack;if(e)switch(e.errorHandling){case"log":return console.error(r);case"silent":return;case"throw":throw new Error(r)}console.error(r)}}return{add:function(e,t,s){var r=n[e];return r||(r=[],n[e]=r),r.push(t),s&&setTimeout((function(){s.forEach((function(s){var r;if(null===(r=n[e])||void 0===r?void 0:r.includes(t))try{Array.isArray(s)?t.apply(void 0,s):t.apply(void 0,[s])}catch(t){i(t,e)}}))}),0),function(){var i=n[e];i&&(0===(i=i.reduce((function(e,n,i){return n===t&&e.length===i||e.push(n),e}),[])).length?delete n[e]:n[e]=i)}},execute:function(e){for(var t=[],s=1;s<arguments.length;s++)t[s-1]=arguments[s];var r=n[e];if(!r||0===r.length)return[];var o=[];return r.forEach((function(n){try{var s=n.apply(void 0,t);o.push(s)}catch(t){o.push(void 0),i(t,e)}})),o},clear:function(){n={}},clearKey:function(e){n[e]&&delete n[e]}}}Js.default=Js;var Ks=Hs(Js);class zs{gw;registry=Ks();client;constructor(e,t){this.gw=e.facade,this.gw.connect(((e,t)=>{this.messageHandler(t)})).then((e=>{this.client=e}))}get isObjectBasedTransport(){return!0}sendObject(e){return this.client?(this.client.send(e),Promise.resolve(void 0)):Promise.reject("not connected")}send(e){return Promise.reject("not supported")}onMessage(e){return this.registry.add("onMessage",e)}onConnectedChanged(e){return e(!0),()=>{}}close(){return Promise.resolve()}open(){return Promise.resolve()}name(){return"in-memory"}reconnect(){return Promise.resolve()}messageHandler(e){this.registry.execute("onMessage",e)}}class Vs{logger;worker;registry=Ks();constructor(e,t){this.logger=t,this.worker=new SharedWorker(e),this.worker.port.onmessage=e=>{this.messageHandler(e.data)}}get isObjectBasedTransport(){return!0}sendObject(e){return this.worker.port.postMessage(e),Promise.resolve()}send(e){return Promise.reject("not supported")}onMessage(e){return this.registry.add("onMessage",e)}onConnectedChanged(e){return e(!0),()=>{}}close(){return Promise.resolve()}open(){return Promise.resolve()}name(){return"shared-worker"}reconnect(){return Promise.resolve()}messageHandler(e){this.registry.execute("onMessage",e)}}class Qs{static isNode(){if(void 0!==Qs._isNode)return Qs._isNode;if("undefined"!=typeof window)return Qs._isNode=!1,!1;try{Qs._isNode="[object process]"===Object.prototype.toString.call(global.process)}catch(e){Qs._isNode=!1}return Qs._isNode}static _isNode}class Xs{static delay(e){return new Promise((t=>setTimeout(t,e)))}resolve;reject;promise;rejected=!1;resolved=!1;get ended(){return this.rejected||this.resolved}constructor(){this.promise=new Promise(((e,t)=>{this.resolve=t=>{this.resolved=!0,e(t)},this.reject=e=>{this.rejected=!0,t(e)}}))}}const Ys={};function Zs(e){const t=Ys[e];if(t)return t;const n=[];function i(){return(new Date).getTime()}const s=i();let r,o;function a(e,t){const s=t??i();let r=0;n.length>0&&(r=s-n[n.length-1].time),n.push({name:e,time:s,diff:r})}a("start",s);const c={get startTime(){return s},get endTime(){return r},get period(){return o},stop:function(){return r=i(),a("end",r),o=r-s,o},mark:a,marks:n};return Ys[e]=c,c}const er=Qs.isNode()?null:window.WebSocket;class tr{ws;logger;settings;startupTimer=Zs("connection");_running=!0;_registry=Ks();wsRequests=[];constructor(e,t){if(this.settings=e,this.logger=t,!this.settings.ws)throw new Error("ws is missing")}onMessage(e){return this._registry.add("onMessage",e)}send(e,t){return new Promise(((t,n)=>{this.waitForSocketConnection((()=>{try{this.ws?.send(e),t()}catch(e){n(e)}}),n)}))}open(){return this.logger.info("opening ws..."),this._running=!0,new Promise(((e,t)=>{this.waitForSocketConnection(e,t)}))}close(){return this._running=!1,this.ws&&this.ws.close(),Promise.resolve()}onConnectedChanged(e){return this._registry.add("onConnectedChanged",e)}name(){return this.settings.ws}reconnect(){this.ws?.close();const e=new Xs;return this.waitForSocketConnection((()=>{e.resolve()})),e.promise}waitForSocketConnection(e,t){t=t??(()=>{}),this._running?1!==this.ws?.readyState?(this.wsRequests.push({callback:e,failed:t}),this.wsRequests.length>1||this.openSocket()):e():t(`wait for socket on ${this.settings.ws} failed - socket closed by user`)}async openSocket(e,t){if(this.logger.info(`opening ws to ${this.settings.ws}, retryInterval: ${e}, retriesLeft: ${t}...`),this.startupTimer.mark("opening-socket"),void 0===e&&(e=this.settings.reconnectInterval),void 0===t&&(t=this.settings.reconnectAttempts),void 0!==t){if(0===t)return void this.notifyForSocketState(`wait for socket on ${this.settings.ws} failed - no more retries left`);this.logger.debug(`will retry ${t} more times (every ${e} ms)`)}try{await this.initiateSocket(),this.startupTimer.mark("socket-initiated"),this.notifyForSocketState()}catch{setTimeout((()=>{const n=void 0===t?void 0:t-1;this.openSocket(e,n)}),e)}}initiateSocket(){const e=new Xs;return this.logger.debug(`initiating ws to ${this.settings.ws}...`),this.ws=new er(this.settings.ws??""),this.ws.onerror=t=>{let n="";try{n=JSON.stringify(t)}catch(e){const i=new WeakSet,s=(e,t)=>{if("object"==typeof t&&null!==t){if(i.has(t))return;i.add(t)}return t};n=JSON.stringify(t,s)}this.logger.info(`ws error - reason: ${n}`),e.reject("error"),this.notifyStatusChanged(!1,n)},this.ws.onclose=t=>{this.logger.info(`ws closed - code: ${t?.code} reason: ${t?.reason}`),e.reject("closed"),this.notifyStatusChanged(!1)},this.ws.onopen=()=>{this.startupTimer.mark("ws-opened"),this.logger.info(`ws opened ${this.settings.identity?.application}`),e.resolve(),this.notifyStatusChanged(!0)},this.ws.onmessage=e=>{this._registry.execute("onMessage",e.data)},e.promise}notifyForSocketState(e){this.wsRequests.forEach((t=>{e?t.failed&&t.failed(e):t.callback()})),this.wsRequests=[]}notifyStatusChanged(e,t){this._registry.execute("onConnectedChanged",e,t)}}class nr{specs;specsNames=[];messages={};isDone;subs={};subsRefCount={};connection;constructor(e){this.specs={};for(const t of e)this.specs[t.name]=t,this.specsNames.push(t.name)}init(e){this.connection=e;for(const t of this.specsNames)for(const n of this.specs[t].types){let t=this.subsRefCount[n];if(t||(t=0),t+=1,this.subsRefCount[n]=t,t>1)continue;const i=e.on(n,(e=>this.processMessage(n,e)));this.subs[n]=i}}processMessage(e,t){if(!this.isDone&&t)for(const n of this.specsNames)if(-1!==this.specs[n].types.indexOf(e)){const e=this.messages[n]||[];this.messages[n]=e,e.push(t)}}drain(e,t){t&&(this.messages[e]||[]).forEach(t),delete this.messages[e];for(const t of this.specs[e].types)this.subsRefCount[t]-=1,this.subsRefCount[t]<=0&&(this.connection?.off(this.subs[t]),delete this.subs[t],delete this.subsRefCount[t]);delete this.specs[e],this.specs.length||(this.isDone=!0)}}let ir=(e=21)=>{let t="",n=e;for(;n--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return t};const sr=(e,t,n)=>new Promise(((i,s)=>{const r=setTimeout((()=>{s(n||`Promise timeout hit: ${t}`)}),t);new Promise(e).then((e=>{clearTimeout(r),i(e)})).catch((e=>{clearTimeout(r),s(e)}))}));class rr{settings;logger;identity;isPreferredActivated;_communicationId;publicWindowId;selfAssignedWindowId;iAmConnected=!1;parentReady=!1;rejected=!1;parentPingResolve;parentPingInterval;connectionResolve;extConnectionResolve;extConnectionReject;connectionReject;port;myClientId;children=[];extContentAvailable=!1;extContentConnecting=!1;extContentConnected=!1;parentWindowId;parentInExtMode=!1;webNamespace="g42_core_web";parent;parentType;parentPingTimeout=5e3;connectionRequestTimeout=7e3;defaultTargetString="*";registry=Ks();messages={connectionAccepted:{name:"connectionAccepted",handle:this.handleConnectionAccepted.bind(this)},connectionRejected:{name:"connectionRejected",handle:this.handleConnectionRejected.bind(this)},connectionRequest:{name:"connectionRequest",handle:this.handleConnectionRequest.bind(this)},parentReady:{name:"parentReady",handle:()=>{}},parentPing:{name:"parentPing",handle:this.handleParentPing.bind(this)},platformPing:{name:"platformPing",handle:this.handlePlatformPing.bind(this)},platformReady:{name:"platformReady",handle:this.handlePlatformReady.bind(this)},clientUnload:{name:"clientUnload",handle:this.handleClientUnload.bind(this)},manualUnload:{name:"manualUnload",handle:this.handleManualUnload.bind(this)},extConnectionResponse:{name:"extConnectionResponse",handle:this.handleExtConnectionResponse.bind(this)},extSetupRequest:{name:"extSetupRequest",handle:this.handleExtSetupRequest.bind(this)},gatewayDisconnect:{name:"gatewayDisconnect",handle:this.handleGatewayDisconnect.bind(this)},gatewayInternalConnect:{name:"gatewayInternalConnect",handle:this.handleGatewayInternalConnect.bind(this)}};constructor(e,t,n){this.settings=e,this.logger=t,this.identity=n,this.extContentAvailable=!!window.glue42ext,this.setUpMessageListener(),this.setUpUnload(),this.setupPlatformUnloadListener(),this.parentType=window.name.includes("#wsp")?"workspace":void 0}manualSetReadyState(){this.iAmConnected=!0,this.parentReady=!0}get transportWindowId(){return this.publicWindowId}get communicationId(){return this._communicationId}async sendObject(e){if(this.extContentConnected)return window.postMessage({glue42ExtOut:e},this.defaultTargetString);if(!this.port)throw new Error("Cannot send message, because the port was not opened yet");this.port.postMessage(e)}get isObjectBasedTransport(){return!0}onMessage(e){return this.registry.add("onMessage",e)}send(){return Promise.reject("not supported")}onConnectedChanged(e){return this.registry.add("onConnectedChanged",e)}async open(){this.logger.debug("opening a connection to the web platform gateway."),await this.connect(),this.notifyStatusChanged(!0)}close(){const e={glue42core:{type:this.messages.gatewayDisconnect.name,data:{clientId:this.myClientId,ownWindowId:this.identity?.windowId}}};return this.port?.postMessage(e),this.parentReady=!1,this.notifyStatusChanged(!1,"manual reconnection"),Promise.resolve()}name(){return"web-platform"}async reconnect(){return await this.close(),Promise.resolve()}initiateInternalConnection(){return new Promise(((e,t)=>{this.logger.debug("opening an internal web platform connection"),this.port=this.settings.port,this.iAmConnected?this.logger.warn("cannot open a new connection, because this client is currently connected"):(this.port.onmessage=n=>{if(this.iAmConnected&&!n.data?.glue42core)return void this.registry.execute("onMessage",n.data);const i=n.data?.glue42core;i&&(i.type===this.messages.gatewayInternalConnect.name&&i.success&&(this.publicWindowId=this.settings.windowId,this.identity&&this.publicWindowId&&(this.identity.windowId=this.publicWindowId,this.identity.instance=this.publicWindowId),e()),i.type===this.messages.gatewayInternalConnect.name&&i.error&&t(i.error))},this.port.postMessage({glue42core:{type:this.messages.gatewayInternalConnect.name}}))}))}initiateRemoteConnection(e){return sr(((t,n)=>{this.connectionResolve=t,this.connectionReject=n,this.myClientId=this.myClientId??ir(10);const i=this.getMyWindowId()||ir(10),s={glue42core:{type:this.messages.connectionRequest.name,clientId:this.myClientId,clientType:"child",bridgeInstanceId:i,selfAssignedWindowId:this.selfAssignedWindowId}};if(this.logger.debug("sending connection request"),this.extContentConnecting)return s.glue42core.clientType="child",s.glue42core.bridgeInstanceId=this.myClientId,s.glue42core.parentWindowId=this.parentWindowId,window.postMessage(s,this.defaultTargetString);if(!e)throw new Error("Cannot send a connection request, because no glue target was specified!");e.postMessage(s,this.defaultTargetString)}),this.connectionRequestTimeout,"The connection to the target glue window timed out")}async isParentCheckSuccess(e){try{return await e,{success:!0}}catch(e){return{success:!1}}}setUpMessageListener(){this.settings.port?this.logger.debug("skipping generic message listener, because this is an internal client"):window.addEventListener("message",(e=>{const t=e.data?.glue42core;if(!t||this.rejected)return;const n=this.settings.allowedOrigins||[];if(n.length&&!n.includes(e.origin))return void this.logger.warn(`received a message from an origin which is not in the allowed list: ${e.origin}`);if(!this.checkMessageTypeValid(t.type))return void this.logger.error(`cannot handle the incoming glue42 core message, because the type is invalid: ${t.type}`);const i=t.type;this.logger.debug(`received valid glue42core message of type: ${i}`),this.messages[i].handle(e)}))}setUpUnload(){this.settings.port?this.logger.debug("skipping unload event listener, because this is an internal client"):window.addEventListener("beforeunload",(()=>{if(this.extContentConnected)return;const e={glue42core:{type:this.messages.clientUnload.name,data:{clientId:this.myClientId,ownWindowId:this.identity?.windowId}}};this.parent&&this.parent.postMessage(e,this.defaultTargetString),this.port?.postMessage(e)}))}handlePlatformReady(e){this.logger.debug("the web platform gave the ready signal"),this.parentReady=!0,this.parentPingResolve&&(this.parentPingResolve(),delete this.parentPingResolve),this.parentPingInterval&&(clearInterval(this.parentPingInterval),delete this.parentPingInterval),this.parent=e.source,this.parentType=window.name.includes("#wsp")?"workspace":"window"}handleConnectionAccepted(e){const t=e.data?.glue42core;return this.myClientId===t.clientId?this.handleAcceptanceOfMyRequest(t):this.handleAcceptanceOfGrandChildRequest(t,e)}handleAcceptanceOfMyRequest(e){if(this.logger.debug("handling a connection accepted signal targeted at me."),this.isPreferredActivated=e.isPreferredActivated,this.extContentConnecting)return this.processExtContentConnection(e);if(e.port){if(this.publicWindowId=this.getMyWindowId(),this.identity&&(this.identity.windowId=this.publicWindowId,this.identity.instance=this.identity.instance?this.identity.instance:this.publicWindowId||ir(10)),this.identity&&e.appName&&(this.identity.application=e.appName,this.identity.applicationName=e.appName),this._communicationId=e.communicationId,this.port=e.port,this.port.onmessage=e=>this.registry.execute("onMessage",e.data),this.connectionResolve)return this.logger.debug("my connection is set up, calling the connection resolve."),this.connectionResolve(),void delete this.connectionResolve;this.logger.error("unable to call the connection resolve, because no connection promise was found")}else this.logger.error("cannot set up my connection, because I was not provided with a port")}processExtContentConnection(e){if(this.logger.debug("handling a connection accepted signal targeted at me for extension content connection."),this.extContentConnecting=!1,this.extContentConnected=!0,this.publicWindowId=this.parentWindowId||this.myClientId,this.extContentConnecting&&this.identity&&(this.identity.windowId=this.publicWindowId),this.identity&&e.appName&&(this.identity.application=e.appName,this.identity.applicationName=e.appName),window.addEventListener("message",(e=>{const t=e.data?.glue42ExtInc;if(!t)return;const n=this.settings.allowedOrigins||[];!n.length||n.includes(e.origin)?this.registry.execute("onMessage",t):this.logger.warn(`received a message from an origin which is not in the allowed list: ${e.origin}`)})),this.connectionResolve)return this.logger.debug("my connection is set up, calling the connection resolve."),this.connectionResolve(),void delete this.connectionResolve}handleAcceptanceOfGrandChildRequest(e,t){if(this.extContentConnecting||this.extContentConnected)return void this.logger.debug("cannot process acceptance of a grandchild, because I am connected to a content script");this.logger.debug(`handling a connection accepted signal targeted at a grandchild: ${e.clientId}`);const n=this.children.find((t=>t.grandChildId===e.clientId));n?(n.connected=!0,this.logger.debug(`the grandchild connection for ${e.clientId} is set up, forwarding the success message and the gateway port`),e.parentWindowId=this.publicWindowId,n.source.postMessage(t.data,n.origin,[e.port])):this.logger.error(`cannot handle connection accepted for grandchild: ${e.clientId}, because there is no grandchild with this id`)}handleConnectionRejected(){this.logger.debug("handling a connection rejection. Most likely the reason is that this window was not created by a glue API call"),this.connectionReject&&(this.connectionReject("The platform connection was rejected. Most likely because this window was not created by a glue API call"),delete this.connectionReject)}handleConnectionRequest(e){if(this.extContentConnecting)return void this.logger.debug("This connection request event is targeted at the extension content");const t=e.source,n=e.data.glue42core;return n.clientType&&"grandChild"===n.clientType?n.clientId?this.parent?(this.logger.debug(`handling a connection request for a grandchild: ${n.clientId}`),this.children.push({grandChildId:n.clientId,source:t,connected:!1,origin:e.origin}),this.logger.debug(`grandchild: ${n.clientId} is prepared, forwarding connection request to the platform`),void this.parent.postMessage(e.data,this.defaultTargetString)):this.rejectConnectionRequest(t,e.origin,"Cannot forward the connection request, because no direct connection to the platform was found"):this.rejectConnectionRequest(t,e.origin,"rejecting a connection request, because the source did not provide a valid id"):this.rejectConnectionRequest(t,e.origin,"rejecting a connection request, because the source was not opened by a glue API call")}handleParentPing(e){if(!this.parentReady)return void this.logger.debug("my parent is not ready, I am ignoring the parent ping");if(!this.iAmConnected)return void this.logger.debug("i am not fully connected yet, I am ignoring the parent ping");const t={glue42core:{type:this.messages.parentReady.name}};this.extContentConnected&&(t.glue42core.extMode={windowId:this.myClientId});const n=e.source;this.logger.debug("responding to a parent ping with a ready message"),n.postMessage(t,e.origin)}setupPlatformUnloadListener(){this.onMessage((e=>{"platformUnload"===e.type&&(this.logger.debug("detected a web platform unload"),this.parentReady=!1,this.notifyStatusChanged(!1,"Gateway unloaded"))}))}handleManualUnload(){const e={glue42core:{type:this.messages.clientUnload.name,data:{clientId:this.myClientId,ownWindowId:this.identity?.windowId}}};if(this.extContentConnected)return window.postMessage({glue42ExtOut:e},this.defaultTargetString);this.port?.postMessage(e)}handleClientUnload(e){const t=e.data.glue42core,n=t?.data.clientId;if(!n)return void this.logger.warn("cannot process grand child unload, because the provided id was not valid");this.children.find((e=>e.grandChildId===n))?(this.logger.debug(`handling grandchild unload for id: ${n}`),this.children=this.children.filter((e=>e.grandChildId!==n))):this.logger.warn("cannot process grand child unload, because this client is unaware of this grandchild")}handlePlatformPing(){}notifyStatusChanged(e,t){this.iAmConnected=e,this.registry.execute("onConnectedChanged",e,t)}checkMessageTypeValid(e){return"string"==typeof e&&!!this.messages[e]}rejectConnectionRequest(e,t,n){this.rejected=!0,this.logger.error(n);const i={glue42core:{type:this.messages.connectionRejected.name}};e.postMessage(i,t)}requestConnectionPermissionFromExt(){return this.waitForContentScript().then((()=>sr(((e,t)=>{this.extConnectionResolve=e,this.extConnectionReject=t;this.logger.debug("permission request to the extension content script was sent"),window.postMessage({glue42core:{type:"extSetupRequest"}},this.defaultTargetString)}),this.parentPingTimeout,"Cannot initialize glue, because this app was not opened or created by a Glue Client and the request for extension connection timed out")))}handleExtConnectionResponse(e){const t=e.data?.glue42core;if(!t.approved)return this.extConnectionReject?this.extConnectionReject("Cannot initialize glue, because this app was not opened or created by a Glue Client and the request for extension connection was rejected"):void 0;this.extConnectionResolve&&(this.extConnectionResolve(),delete this.extConnectionResolve),this.extContentConnecting=!0,this.parentType="extension",this.logger.debug("The extension connection was approved, proceeding.")}handleExtSetupRequest(){}handleGatewayDisconnect(){}handleGatewayInternalConnect(){}waitForContentScript(){return!!window.glue42ext?.content?Promise.resolve():sr((e=>{window.addEventListener("Glue42EXTReady",(()=>{e()}))}),this.connectionRequestTimeout,"The content script was available, but was never heard to be ready")}async connect(){if(this.settings.port)return await this.initiateInternalConnection(),void this.logger.debug("internal web platform connection completed");this.logger.debug("opening a client web platform connection"),await this.findParent(),await this.initiateRemoteConnection(this.parent),this.logger.debug("the client is connected")}async findParent(){const e="Cannot initiate glue, because this window was not opened or created by a glue client",t=this.getPossibleParentsInWindow(window),n=this.getPossibleParentsOutsideWindow(window.top?.opener,window.top),i=new Set([...t,...n]);if(!i.size&&!this.extContentAvailable)throw new Error(e);if(!i.size&&this.extContentAvailable)return void await this.requestConnectionPermissionFromExt();if((await this.isParentCheckSuccess(this.confirmParent(Array.from(i)))).success)this.logger.debug("The default parent was found!");else{if(!this.extContentAvailable)throw new Error(e);await this.requestConnectionPermissionFromExt()}}getPossibleParentsInWindow(e){return e&&e!==e.top?[e.parent,...this.getPossibleParentsInWindow(e.parent)]:[]}getPossibleParentsOutsideWindow(e,t){return e&&t&&e!==t?[e,...this.getPossibleParentsInWindow(e),...this.getPossibleParentsOutsideWindow(e.opener,e)]:[]}confirmParent(e){const t=sr((t=>{this.parentPingResolve=t;const n={glue42core:{type:this.messages.platformPing.name}};this.parentPingInterval=setInterval((()=>{e.forEach((e=>{e.postMessage(n,this.defaultTargetString)}))}),1e3)}),this.parentPingTimeout,"Cannot initiate glue, because this window was not opened or created by a glue client");return t.catch((()=>{this.parentPingInterval&&(clearInterval(this.parentPingInterval),delete this.parentPingInterval)})),t}getMyWindowId(){return"workspace"===this.parentType?window.name.substring(0,window.name.indexOf("#wsp")):window===window.top?window.name?.includes("g42")?window.name:(this.selfAssignedWindowId=this.selfAssignedWindowId||`g42-${ir(10)}`,this.selfAssignedWindowId):void 0}}class or{minSequenceInterval;queue=[];isExecutingQueue=!1;constructor(e=0){this.minSequenceInterval=e}enqueue(e){return new Promise(((t,n)=>{this.queue.push({action:e,resolve:t,reject:n}),this.executeQueue()}))}async executeQueue(){if(!this.isExecutingQueue){for(this.isExecutingQueue=!0;this.queue.length;){const e=this.queue.shift();if(!e)return void(this.isExecutingQueue=!1);try{const t=await e.action();e.resolve(t)}catch(t){e.reject(t)}await this.intervalBreak()}this.isExecutingQueue=!1}}intervalBreak(){return new Promise((e=>setTimeout(e,this.minSequenceInterval)))}}function ar(e,t,n,i,s){null==e&&(e="global"),i=i??["success"],s=s??["error"];let r,o="global"===e,a=!1,c=!1;const d=Ks();t.disconnected((function(){c=!1,n.debug("connection is down"),o=!1,a=!0,d.execute("onLeft",{disconnected:!0})})),t.loggedIn((function(){c=!0,a&&(n.debug("connection is now up - trying to reconnect..."),h(r))})),t.on("success",(e=>g(e))),t.on("error",(e=>p(e))),t.on("result",(e=>g(e))),i&&i.forEach((e=>{t.on(e,(e=>g(e)))})),s&&s.forEach((e=>{t.on(e,(e=>p(e)))}));const l={};function h(t){return r=t,new Promise(((i,s)=>{if(o)return void i({});let r;if("global"===e)r=c?Promise.resolve({}):Promise.reject("not connected to gateway");else{n.debug(`joining domain ${e}`);r=b({type:"join",destination:e,domain:"global",options:t})}r.then((()=>{!function(){n.debug("did join "+e),o=!0;const t=a;a=!1,d.execute("onJoined",t)}(),i({})})).catch((t=>{n.debug("error joining "+e+" domain: "+JSON.stringify(t)),s(t)}))}))}function u(e){return o&&e(!1),d.add("onJoined",e)}function p(t){if(e!==t.domain)return;const n=t.request_id;if(!n)return;const i=l[n];i&&i.error(t)}function g(t){if(t.domain!==e)return;const n=t.request_id;if(!n)return;const i=l[n];i&&i.success(t)}function m(){return ir(10)}let f=[];function b(i,s,r){if(i.type&&-1===["hello","join"].indexOf(i.type)&&!o){console.warn(`trying to send a message (${i.domain} ${i.type}) but not connected, will queue`);const e=new Xs;if(f.push({msg:i,tag:s,options:r,pw:e}),1===f.length){const e=u((()=>{n.info(`joined - will now send queued messages (${f.length} -> [${f.map((e=>e.msg.type))}])`),f.forEach((e=>{b(e.msg,e.tag,e.options).then((t=>e.pw.resolve(t))).catch((t=>e.pw.reject(t)))})),f=[],e()}))}return e.promise}r=r??{},i.request_id=i.request_id??m(),i.domain=i.domain??e,r.skipPeerId||(i.peer_id=t.peerId);const a=i.request_id;return new Promise(((e,o)=>{l[a]={success:t=>{delete l[a],t._tag=s,e(t)},error:e=>{n.warn(`Gateway error - ${JSON.stringify(e)}`),delete l[a],e._tag=s,o(e)}},t.send(i,r).catch((e=>{l[a].error({err:e})}))}))}return{join:h,leave:function(){return"global"===e?Promise.resolve():(n.debug("stopping session "+e+"..."),a=!1,b({type:"leave",destination:e,domain:"global"}).then((()=>{o=!1,d.execute("onLeft")})).catch((()=>{o=!1,d.execute("onLeft")})))},onJoined:u,onLeft:function(e){return o||e(),d.add("onLeft",e)},send:b,sendFireAndForget:function(n){return n.request_id=n.request_id?n.request_id:m(),n.domain=n.domain??e,n.peer_id=t.peerId,t.send(n)},on:(i,s)=>{t.on(i,(t=>{if(t.domain===e)try{s(t)}catch(e){n.error(`Callback failed: ${e} \n ${e.stack} \n msg was: ${JSON.stringify(t)}`,e)}}))},loggedIn:e=>t.loggedIn(e),connected:e=>t.connected(e),disconnected:e=>t.disconnected(e),get peerId(){return t.peerId},get domain(){return e}}}class cr{settings;logger;protocolVersion=3;peerId;token;info;resolvedIdentity;availableDomains;gatewayToken;replayer;messageHandlers={};ids=1;registry=Ks();_connected=!1;isTrace=!1;transport;_defaultTransport;_defaultAuth;_targetTransport;_targetAuth;_swapTransport=!1;_switchInProgress=!1;_transportSubscriptions=[];datePrefix="#T42_DATE#";datePrefixLen=this.datePrefix.length;dateMinLen=this.datePrefixLen+1;datePrefixFirstChar=this.datePrefix[0];_sequelizer=new or;_isLoggedIn=!1;shouldTryLogin=!0;pingTimer;sessions=[];globalDomain;initialLogin=!0;initialLoginAttempts=3;loginConfig;constructor(e,t){if(this.settings=e,this.logger=t,(e=e||{}).reconnectAttempts=e.reconnectAttempts??10,e.reconnectInterval=e.reconnectInterval??1e3,e.inproc)this.transport=new zs(e.inproc,t.subLogger("inMemory"));else if(e.sharedWorker)this.transport=new Vs(e.sharedWorker,t.subLogger("shared-worker"));else if(e.webPlatform)this.transport=new rr(e.webPlatform,t.subLogger("web-platform"),e.identity);else{if(void 0===e.ws)throw new Error("No connection information specified");this.transport=new tr(e,t.subLogger("ws"))}this.isTrace=t.canPublish("trace"),t.debug(`starting with ${this.transport.name()} transport`);const 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,this.ping()}async switchTransport(e){return this._sequelizer.enqueue((async()=>{if(!e||"object"!=typeof e)throw new Error("Cannot switch transports, because the settings are missing or invalid.");if(void 0===e.type)throw new Error("Cannot switch the transport, because the type is not defined");this.logger.trace(`Starting transport switch with settings: ${JSON.stringify(e)}`);const t="secondary"===e.type?this.getNewSecondaryTransport(e):this._defaultTransport;this._targetTransport=t,this._targetAuth="secondary"===e.type?this.getNewSecondaryAuth(e):this._defaultAuth;const n=this.verifyConnection();this._swapTransport=!0,this._switchInProgress=!0,this.logger.trace("The new transport has been set, closing the current transport"),await this.transport.close();try{await n;const e=this.transport===t;return this.logger.info(`The reconnection after the switch was completed. Was the switch a success: ${e}`),this._switchInProgress=!1,{success:e}}catch(e){return this.logger.info("The reconnection after the switch timed out, reverting back to the default transport."),this.switchTransport({type:"default"}),this._switchInProgress=!1,{success:!1}}}))}onLibReAnnounced(e){return this.registry.add("libReAnnounced",e)}setLibReAnnounced(e){this.registry.execute("libReAnnounced",e)}send(e,t){if(this.transport.sendObject&&this.transport.isObjectBasedTransport){const n=this.createObjectMessage(e);return this.isTrace&&this.logger.trace(`>> ${JSON.stringify(n)}`),this.transport.sendObject(n,t)}{const n=this.createStringMessage(e);return this.isTrace&&this.logger.trace(`>> ${n}`),this.transport.send(n,t)}}on(e,t){e=e.toLowerCase(),void 0===this.messageHandlers[e]&&(this.messageHandlers[e]={});const n=this.ids++;return this.messageHandlers[e][n]=t,{type:e,id:n}}off(e){delete this.messageHandlers[e.type.toLowerCase()][e.id]}get isConnected(){return this._isLoggedIn}connected(e){return this.loggedIn((()=>{const t=this.transport.name();e(t)}))}disconnected(e){return this.registry.add("disconnected",e)}async login(e,t){if(this._defaultAuth||(this._defaultAuth=e),this._swapTransport){this.logger.trace("Detected a transport swap, swapping transports");e=this.transportSwap()??e}this.logger.trace(`Starting login for transport: ${this.transport.name()} and auth ${JSON.stringify(e)}`);try{await this.transport.open(),this.logger.trace(`Transport: ${this.transport.name()} opened, logging in`),Zs("connection").mark("transport-opened");const n=await this.loginCore(e,t);return this.logger.trace(`Logged in with identity: ${JSON.stringify(n)}`),Zs("connection").mark("protocol-logged-in"),n}catch(e){throw this._switchInProgress&&(this.logger.trace("An error while logging in after a transport swap, preparing a default swap."),this.prepareDefaultSwap()),new Error(e)}}async logout(){await this.logoutCore(),await this.transport.close()}loggedIn(e){return this._isLoggedIn&&e(),this.registry.add("onLoggedIn",e)}domain(e,t,n){let i=this.sessions.find((t=>t.domain===e));return i||(i=ar(e,this,this.logger.subLogger(`domain=${e}`),t,n),this.sessions.push(i)),i}authToken(){return this.globalDomain?this.globalDomain.send({domain:"global",type:"create-token"}).then((e=>e.token)):Promise.reject(new Error("no global domain session"))}reconnect(){return this.transport.reconnect()}setLoggedIn(e){this._isLoggedIn=e,this._isLoggedIn&&this.registry.execute("onLoggedIn")}distributeMessage(e,t){const n=this.messageHandlers[t.toLowerCase()];void 0!==n&&Object.keys(n).forEach((t=>{const i=n[t];if(void 0!==i)try{i(e)}catch(e){try{this.logger.error(`Message handler failed with ${e.stack}`,e)}catch(t){console.log("Message handler failed",e)}}}))}handleConnectionChanged(e){this._connected!==e&&(this._connected=e,e?(this.settings?.replaySpecs?.length&&(this.replayer=new nr(this.settings.replaySpecs),this.replayer.init(this)),this.registry.execute("connected")):(this.handleDisconnected(),this.registry.execute("disconnected")))}handleDisconnected(){this.setLoggedIn(!1);if(this.shouldTryLogin&&this.initialLogin){if(this.initialLoginAttempts<=0)return;this.initialLoginAttempts--}if(this.logger.debug("disconnected - will try new login?"+this.shouldTryLogin),this.shouldTryLogin){if(!this.loginConfig)throw new Error("no login info");this.login(this.loginConfig,!0).catch((()=>{setTimeout(this.handleDisconnected.bind(this),this.settings.reconnectInterval||1e3)}))}}handleTransportMessage(e){let t;t="string"==typeof e?this.processStringMessage(e):this.processObjectMessage(e),this.isTrace&&this.logger.trace(`<< ${JSON.stringify(t)}`),this.distributeMessage(t.msg,t.msgType)}verifyConnection(){return sr((e=>{let t;const n=((e,t)=>{let n=e;return()=>{n--,0===n&&t()}})(2,(()=>{t&&t(),e()}));t=this.onLibReAnnounced((e=>"interop"===e.name||"contexts"===e.name?n():void 0))}),1e4,"Transport switch timed out waiting for all libraries to be re-announced")}getNewSecondaryTransport(e){if(!e.transportConfig?.url)throw new Error("Missing secondary transport URL.");return new tr(Object.assign({},this.settings,{ws:e.transportConfig.url,reconnectAttempts:1}),this.logger.subLogger("ws-secondary"))}getNewSecondaryAuth(e){if(!e.transportConfig?.auth)throw new Error("Missing secondary transport auth information.");return e.transportConfig.auth}transportSwap(){if(this._swapTransport=!1,!this._targetTransport||!this._targetAuth)return void this.logger.warn(`Error while switching transports - either the target transport or auth is not defined: transport defined -> ${!!this._defaultTransport}, auth defined -> ${!!this._targetAuth}. Staying on the current one.`);this._transportSubscriptions.forEach((e=>e())),this._transportSubscriptions=[],this.transport=this._targetTransport;const e=this.transport.onConnectedChanged(this.handleConnectionChanged.bind(this)),t=this.transport.onMessage(this.handleTransportMessage.bind(this));return this._transportSubscriptions.push(e),this._transportSubscriptions.push(t),this._targetAuth}prepareDefaultSwap(){this._transportSubscriptions.forEach((e=>e())),this._transportSubscriptions=[],this.transport.close().catch((e=>this.logger.warn(`Error closing the ${this.transport.name()} transport after a failed connection attempt: ${JSON.stringify(e)}`))),this._targetTransport=this._defaultTransport,this._targetAuth=this._defaultAuth,this._swapTransport=!0}processStringMessage(e){const t=JSON.parse(e,((e,t)=>{if("string"!=typeof t)return t;if(t.length<this.dateMinLen)return t;if(!t.startsWith(this.datePrefixFirstChar))return t;if(t.substring(0,this.datePrefixLen)!==this.datePrefix)return t;try{const e=parseInt(t.substring(this.datePrefixLen,t.length),10);return isNaN(e)?t:new Date(e)}catch(e){return t}}));return{msg:t,msgType:t.type}}createStringMessage(e){const t=Date.prototype.toJSON;try{const t=this.datePrefix;Date.prototype.toJSON=function(){return t+this.getTime()};return JSON.stringify(e)}finally{Date.prototype.toJSON=t}}processObjectMessage(e){if(!e.type)throw new Error("Object should have type property");return{msg:e,msgType:e.type}}createObjectMessage(e){return e}async loginCore(e,t){this.logger.info("logging in..."),this.loginConfig=e,this.loginConfig||(this.loginConfig={username:"",password:""}),this.shouldTryLogin=!0;const n=await this.setupAuthConfig(e,t),i={type:"hello",identity:this.settings.identity,authentication:n};e.sessionId&&(i.request_id=e.sessionId),this.globalDomain=ar("global",this,this.logger.subLogger("global-domain"),["welcome","token","authentication-request"]);const s={skipPeerId:!0};this.initialLogin&&(s.retryInterval=this.settings.reconnectInterval,s.maxRetries=this.settings.reconnectAttempts);try{const t=await this.tryAuthenticate(this.globalDomain,i,s,e);return this.initialLogin=!1,this.logger.info("login successful with peerId "+t.peer_id),this.peerId=t.peer_id,this.resolvedIdentity=t.resolved_identity,this.availableDomains=t.available_domains,t.options&&(this.token=t.options.access_token,this.info=t.options.info),this.setLoggedIn(!0),t.resolved_identity}catch(e){throw this.logger.error("error sending hello message - "+(e.message||e.msg||e.reason||e),e),e}finally{e?.flowCallback&&e.sessionId&&e.flowCallback(e.sessionId,null)}}async tryAuthenticate(e,t,n,i){let s;for(;;){const r=await e.send(t,void 0,n);if("authentication-request"!==r.type){if("welcome"===r.type){s=r;break}throw"error"===r.type?new Error("Authentication failed: "+r.reason):new Error("Unexpected message type during authentication: "+r.type)}{const e=Buffer.from(r.authentication.token,"base64");i.flowCallback&&i.sessionId&&(t.authentication.token=(await i.flowCallback(i.sessionId,e)).data.toString("base64")),t.request_id=i.sessionId}}return s}async setupAuthConfig(e,t){const n={};if(this.gatewayToken=e.gatewayToken,e.gatewayToken){if(t)try{e.gatewayToken=await this.getNewGWToken()}catch(e){this.logger.warn(`failed to get GW token when reconnecting ${e?.message||e}`)}n.method="gateway-token",n.token=e.gatewayToken,this.gatewayToken=e.gatewayToken}else if("sspi"===e.flowName){if(n.provider="win",n.method="access-token",!e.flowCallback||!e.sessionId)throw new Error("Invalid SSPI config");n.token=(await e.flowCallback(e.sessionId,null)).data.toString("base64")}else if(e.token)n.method="access-token",n.token=e.token;else if(e.username)n.method="secret",n.login=e.username,n.secret=e.password;else{if(!e.provider)throw new Error("invalid auth message"+JSON.stringify(e));n.provider=e.provider,n.providerContext=e.providerContext}return n}async logoutCore(){this.logger.debug("logging out..."),this.shouldTryLogin=!1,this.pingTimer&&clearTimeout(this.pingTimer);const e=this.sessions.map((e=>{e.leave()}));await Promise.all(e)}getNewGWToken(){if("undefined"!=typeof window){const e=window.glue42gd;if(e)return e.getGWToken()}return Promise.reject(new Error("not running in GD"))}ping(){this.shouldTryLogin&&(this._isLoggedIn&&this.send({type:"ping"}),this.pingTimer=setTimeout((()=>{this.ping()}),3e4))}}const dr=["trace","debug","info","warn","error","off"];class lr{name;parent;static Interop;static InteropMethodName="T42.AppLogger.Log";static Instance;path;subLoggers=[];_consoleLevel;_publishLevel;loggerFullName;includeTimeAndLevel;logFn=console;customLogFn=!1;constructor(e,t,n){this.name=e,this.parent=t,this.name=e,this.path=t?`${t.path}.${e}`:e,this.loggerFullName=`[${this.path}]`,this.includeTimeAndLevel=!n,n&&(this.logFn=n,this.customLogFn=!0)}subLogger(e){const t=this.subLoggers.filter((t=>t.name===e))[0];if(void 0!==t)return t;Object.keys(this).forEach((t=>{if(t===e)throw new Error("This sub logger name is not allowed.")}));const n=new lr(e,this,this.customLogFn?this.logFn:void 0);return this.subLoggers.push(n),n}publishLevel(e){return e&&(this._publishLevel=e),this._publishLevel||this.parent?.publishLevel()}consoleLevel(e){return e&&(this._consoleLevel=e),this._consoleLevel||this.parent?.consoleLevel()}log(e,t,n){this.publishMessage(t||"info",e,n)}trace(e){this.log(e,"trace")}debug(e){this.log(e,"debug")}info(e){this.log(e,"info")}warn(e){this.log(e,"warn")}error(e,t){this.log(e,"error")}canPublish(e,t){return dr.indexOf(e)>=dr.indexOf(t||this.consoleLevel()||"trace")}publishMessage(e,t,n){const i=this.loggerFullName;if("error"===e&&!n){const e=new Error;e.stack&&(t=t+"\n"+e.stack.split("\n").slice(3).join("\n"))}if(this.canPublish(e,this.publishLevel())){const n=lr.Interop;if(n)try{n.methods({name:lr.InteropMethodName}).length>0&&n.invoke(lr.InteropMethodName,{msg:`${t}`,logger:i,level:e})}catch{}}if(this.canPublish(e)){let s="";if(this.includeTimeAndLevel){const t=new Date;s=`[${`${t.getHours()}:${t.getMinutes()}:${t.getSeconds()}:${t.getMilliseconds()}`}] [${e}] `}const r=`${s}${i}: ${t}`;switch(e){case"trace":this.logFn.debug(r);break;case"debug":this.logFn.debug?this.logFn.debug(r):this.logFn.log(r);break;case"info":this.logFn.info(r);break;case"warn":this.logFn.warn(r);break;case"error":this.logFn.error(r,n)}}}}const hr="create-context",ur="created",pr="destroyed",gr="context-created",mr="context-added",fr="subscribe-context",br="subscribed-context",wr="unsubscribe-context",yr="destroy-context",vr="context-destroyed",Cr="update-context",Ir="context-updated",Sr="joined",_r={get name(){return"context"},get types(){return[hr,ur,pr,gr,mr,fr,br,wr,yr,vr,Cr,Ir,Sr]}};var xr="6.4.2";class kr{name;contextId;context;isAnnounced;joinedActivity;updateCallbacks={};activityId;sentExplicitSubscription;hasReceivedSnapshot;constructor(e,t,n,i){this.contextId=e,this.name=t,this.isAnnounced=n,this.activityId=i,this.context={}}hasCallbacks(){return Object.keys(this.updateCallbacks).length>0}getState(){return this.isAnnounced&&this.hasCallbacks()?3:this.isAnnounced?2:this.hasCallbacks()?1:0}}var Tr={exports:{}};!function(e,t){var n="__lodash_hash_undefined__",i=9007199254740991,s="[object Arguments]",r="[object Boolean]",o="[object Date]",a="[object Function]",c="[object GeneratorFunction]",d="[object Map]",l="[object Number]",h="[object Object]",u="[object Promise]",p="[object RegExp]",g="[object Set]",m="[object String]",f="[object Symbol]",b="[object WeakMap]",w="[object ArrayBuffer]",y="[object DataView]",v="[object Float32Array]",C="[object Float64Array]",I="[object Int8Array]",S="[object Int16Array]",_="[object Int32Array]",x="[object Uint8Array]",k="[object Uint8ClampedArray]",T="[object Uint16Array]",P="[object Uint32Array]",R=/\w*$/,A=/^\[object .+?Constructor\]$/,M=/^(?:0|[1-9]\d*)$/,E={};E[s]=E["[object Array]"]=E[w]=E[y]=E[r]=E[o]=E[v]=E[C]=E[I]=E[S]=E[_]=E[d]=E[l]=E[h]=E[p]=E[g]=E[m]=E[f]=E[x]=E[k]=E[T]=E[P]=!0,E["[object Error]"]=E[a]=E[b]=!1;var O="object"==typeof Us&&Us&&Us.Object===Object&&Us,D="object"==typeof self&&self&&self.Object===Object&&self,j=O||D||Function("return this")(),N=t&&!t.nodeType&&t,L=N&&e&&!e.nodeType&&e,F=L&&L.exports===N;function $(e,t){return e.set(t[0],t[1]),e}function W(e,t){return e.add(t),e}function q(e,t,n,i){for(var s=-1,r=e?e.length:0;++s<r;)n=t(n,e[s],s,e);return n}function G(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(e){}return t}function B(e){var t=-1,n=Array(e.size);return e.forEach((function(e,i){n[++t]=[i,e]})),n}function U(e,t){return function(n){return e(t(n))}}function H(e){var t=-1,n=Array(e.size);return e.forEach((function(e){n[++t]=e})),n}var J,K=Array.prototype,z=Function.prototype,V=Object.prototype,Q=j["__core-js_shared__"],X=(J=/[^.]+$/.exec(Q&&Q.keys&&Q.keys.IE_PROTO||""))?"Symbol(src)_1."+J:"",Y=z.toString,Z=V.hasOwnProperty,ee=V.toString,te=RegExp("^"+Y.call(Z).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),ne=F?j.Buffer:void 0,ie=j.Symbol,se=j.Uint8Array,re=U(Object.getPrototypeOf,Object),oe=Object.create,ae=V.propertyIsEnumerable,ce=K.splice,de=Object.getOwnPropertySymbols,le=ne?ne.isBuffer:void 0,he=U(Object.keys,Object),ue=Le(j,"DataView"),pe=Le(j,"Map"),ge=Le(j,"Promise"),me=Le(j,"Set"),fe=Le(j,"WeakMap"),be=Le(Object,"create"),we=Ge(ue),ye=Ge(pe),ve=Ge(ge),Ce=Ge(me),Ie=Ge(fe),Se=ie?ie.prototype:void 0,_e=Se?Se.valueOf:void 0;function xe(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var i=e[t];this.set(i[0],i[1])}}function ke(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var i=e[t];this.set(i[0],i[1])}}function Te(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var i=e[t];this.set(i[0],i[1])}}function Pe(e){this.__data__=new ke(e)}function Re(e,t){var n=Ue(e)||function(e){return function(e){return function(e){return!!e&&"object"==typeof e}(e)&&He(e)}(e)&&Z.call(e,"callee")&&(!ae.call(e,"callee")||ee.call(e)==s)}(e)?function(e,t){for(var n=-1,i=Array(e);++n<e;)i[n]=t(n);return i}(e.length,String):[],i=n.length,r=!!i;for(var o in e)!Z.call(e,o)||r&&("length"==o||We(o,i))||n.push(o);return n}function Ae(e,t,n){var i=e[t];Z.call(e,t)&&Be(i,n)&&(void 0!==n||t in e)||(e[t]=n)}function Me(e,t){for(var n=e.length;n--;)if(Be(e[n][0],t))return n;return-1}function Ee(e,t,n,i,u,b,A){var M;if(i&&(M=b?i(e,u,b,A):i(e)),void 0!==M)return M;if(!ze(e))return e;var O=Ue(e);if(O){if(M=function(e){var t=e.length,n=e.constructor(t);t&&"string"==typeof e[0]&&Z.call(e,"index")&&(n.index=e.index,n.input=e.input);return n}(e),!t)return function(e,t){var n=-1,i=e.length;t||(t=Array(i));for(;++n<i;)t[n]=e[n];return t}(e,M)}else{var D=$e(e),j=D==a||D==c;if(Je(e))return function(e,t){if(t)return e.slice();var n=new e.constructor(e.length);return e.copy(n),n}(e,t);if(D==h||D==s||j&&!b){if(G(e))return b?e:{};if(M=function(e){return"function"!=typeof e.constructor||qe(e)?{}:(t=re(e),ze(t)?oe(t):{});var t}(j?{}:e),!t)return function(e,t){return je(e,Fe(e),t)}(e,function(e,t){return e&&je(t,Ve(t),e)}(M,e))}else{if(!E[D])return b?e:{};M=function(e,t,n,i){var s=e.constructor;switch(t){case w:return De(e);case r:case o:return new s(+e);case y:return function(e,t){var n=t?De(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.byteLength)}(e,i);case v:case C:case I:case S:case _:case x:case k:case T:case P:return function(e,t){var n=t?De(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.length)}(e,i);case d:return function(e,t,n){var i=t?n(B(e),!0):B(e);return q(i,$,new e.constructor)}(e,i,n);case l:case m:return new s(e);case p:return function(e){var t=new e.constructor(e.source,R.exec(e));return t.lastIndex=e.lastIndex,t}(e);case g:return function(e,t,n){var i=t?n(H(e),!0):H(e);return q(i,W,new e.constructor)}(e,i,n);case f:return a=e,_e?Object(_e.call(a)):{}}var a}(e,D,Ee,t)}}A||(A=new Pe);var N=A.get(e);if(N)return N;if(A.set(e,M),!O)var L=n?function(e){return function(e,t,n){var i=t(e);return Ue(e)?i:function(e,t){for(var n=-1,i=t.length,s=e.length;++n<i;)e[s+n]=t[n];return e}(i,n(e))}(e,Ve,Fe)}(e):Ve(e);return function(e,t){for(var n=-1,i=e?e.length:0;++n<i&&!1!==t(e[n],n,e););}(L||e,(function(s,r){L&&(s=e[r=s]),Ae(M,r,Ee(s,t,n,i,r,e,A))})),M}function Oe(e){return!(!ze(e)||(t=e,X&&X in t))&&(Ke(e)||G(e)?te:A).test(Ge(e));var t}function De(e){var t=new e.constructor(e.byteLength);return new se(t).set(new se(e)),t}function je(e,t,n,i){n||(n={});for(var s=-1,r=t.length;++s<r;){var o=t[s];Ae(n,o,e[o])}return n}function Ne(e,t){var n,i,s=e.__data__;return("string"==(i=typeof(n=t))||"number"==i||"symbol"==i||"boolean"==i?"__proto__"!==n:null===n)?s["string"==typeof t?"string":"hash"]:s.map}function Le(e,t){var n=function(e,t){return null==e?void 0:e[t]}(e,t);return Oe(n)?n:void 0}xe.prototype.clear=function(){this.__data__=be?be(null):{}},xe.prototype.delete=function(e){return this.has(e)&&delete this.__data__[e]},xe.prototype.get=function(e){var t=this.__data__;if(be){var i=t[e];return i===n?void 0:i}return Z.call(t,e)?t[e]:void 0},xe.prototype.has=function(e){var t=this.__data__;return be?void 0!==t[e]:Z.call(t,e)},xe.prototype.set=function(e,t){return this.__data__[e]=be&&void 0===t?n:t,this},ke.prototype.clear=function(){this.__data__=[]},ke.prototype.delete=function(e){var t=this.__data__,n=Me(t,e);return!(n<0)&&(n==t.length-1?t.pop():ce.call(t,n,1),!0)},ke.prototype.get=function(e){var t=this.__data__,n=Me(t,e);return n<0?void 0:t[n][1]},ke.prototype.has=function(e){return Me(this.__data__,e)>-1},ke.prototype.set=function(e,t){var n=this.__data__,i=Me(n,e);return i<0?n.push([e,t]):n[i][1]=t,this},Te.prototype.clear=function(){this.__data__={hash:new xe,map:new(pe||ke),string:new xe}},Te.prototype.delete=function(e){return Ne(this,e).delete(e)},Te.prototype.get=function(e){return Ne(this,e).get(e)},Te.prototype.has=function(e){return Ne(this,e).has(e)},Te.prototype.set=function(e,t){return Ne(this,e).set(e,t),this},Pe.prototype.clear=function(){this.__data__=new ke},Pe.prototype.delete=function(e){return this.__data__.delete(e)},Pe.prototype.get=function(e){return this.__data__.get(e)},Pe.prototype.has=function(e){return this.__data__.has(e)},Pe.prototype.set=function(e,t){var n=this.__data__;if(n instanceof ke){var i=n.__data__;if(!pe||i.length<199)return i.push([e,t]),this;n=this.__data__=new Te(i)}return n.set(e,t),this};var Fe=de?U(de,Object):function(){return[]},$e=function(e){return ee.call(e)};function We(e,t){return!!(t=null==t?i:t)&&("number"==typeof e||M.test(e))&&e>-1&&e%1==0&&e<t}function qe(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||V)}function Ge(e){if(null!=e){try{return Y.call(e)}catch(e){}try{return e+""}catch(e){}}return""}function Be(e,t){return e===t||e!=e&&t!=t}(ue&&$e(new ue(new ArrayBuffer(1)))!=y||pe&&$e(new pe)!=d||ge&&$e(ge.resolve())!=u||me&&$e(new me)!=g||fe&&$e(new fe)!=b)&&($e=function(e){var t=ee.call(e),n=t==h?e.constructor:void 0,i=n?Ge(n):void 0;if(i)switch(i){case we:return y;case ye:return d;case ve:return u;case Ce:return g;case Ie:return b}return t});var Ue=Array.isArray;function He(e){return null!=e&&function(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=i}(e.length)&&!Ke(e)}var Je=le||function(){return!1};function Ke(e){var t=ze(e)?ee.call(e):"";return t==a||t==c}function ze(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function Ve(e){return He(e)?Re(e):function(e){if(!qe(e))return he(e);var t=[];for(var n in Object(e))Z.call(e,n)&&"constructor"!=n&&t.push(n);return t}(e)}e.exports=function(e){return Ee(e,!0,!0)}}(Tr,Tr.exports);var Pr=Hs(Tr.exports);function Rr(e,t,n){try{if(n?.canPublish("trace")&&n?.trace(`applying context delta ${JSON.stringify(t)} on context ${JSON.stringify(e)}`),!t)return e;if(t.reset)return e={...t.reset};if(e=Ar(e,void 0),t.commands){for(const n of t.commands)"remove"===n.type?jr(e,n.path):"set"===n.type&&Or(e,n.value,n.path);return e}const i=t.added,s=t.updated,r=t.removed;return i&&Object.keys(i).forEach((t=>{e[t]=i[t]})),s&&Object.keys(s).forEach((t=>{Mr(t,e,s)})),r&&r.forEach((t=>{delete e[t]})),e}catch(i){return n?.error(`error applying context delta ${JSON.stringify(t)} on context ${JSON.stringify(e)}`,i),e}}function Ar(e,t){return Pr(e)}const Mr=(e,t,n)=>{const i=n[e];if(void 0===i)return t;const s=t[e];return s&&i?"string"==typeof s||"number"==typeof s||"boolean"==typeof s||"string"==typeof i||"number"==typeof i||"boolean"==typeof i||Array.isArray(s)||Array.isArray(i)?(t[e]=i,t):(t[e]=Object.assign({},s,i),t):(t[e]=i,t)};function Er(e,t){if(e===t)return!0;if(!(e instanceof Object&&t instanceof Object))return!1;if(e.constructor!==t.constructor)return!1;for(const n in e)if(e.hasOwnProperty(n)){if(!t.hasOwnProperty(n))return!1;if(e[n]!==t[n]){if("object"!=typeof e[n])return!1;if(!Er(e[n],t[n]))return!1}}for(const n in t)if(t.hasOwnProperty(n)&&!e.hasOwnProperty(n))return!1;return!0}function Or(e,t,n){const i=n.split(".");let s;for(s=0;s<i.length-1;s++)e[i[s]]||(e[i[s]]={}),"object"!=typeof e[i[s]]&&(e[i[s]]={}),e=e[i[s]];e[i[s]]=t}function Dr(e,t){return Object.keys(t).every((n=>"object"==typeof t[n]?Dr(e?.[n]||{},t[n]||{}):t[n]===e?.[n]))}function jr(e,t){const n=t.split(".");let i;for(i=0;i<n.length-1;i++){if(!e[n[i]])return;e=e[n[i]]}delete e[n[i]]}class Nr{_logger;_connection;_trackAllContexts;_reAnnounceKnownContexts;_gw3Session;_contextNameToData={};_gw3Subscriptions=[];_nextCallbackSubscriptionNumber=0;_creationPromises={};_contextNameToId={};_contextIdToName={};_protocolVersion=void 0;_contextsTempCache={};_contextsSubscriptionsCache=[];_systemContextsSubKey;get protocolVersion(){if(!this._protocolVersion){const e=this._connection.availableDomains.find((e=>"context"===e.uri));this._protocolVersion=e?.version??1}return this._protocolVersion}get setPathSupported(){return this.protocolVersion>=2}constructor(e){this._connection=e.connection,this._logger=e.logger,this._trackAllContexts=e.trackAllContexts,this._reAnnounceKnownContexts=e.reAnnounceKnownContexts,this._gw3Session=this._connection.domain("global",[gr,br,vr,Ir]),this._gw3Session.disconnected(this.resetState.bind(this)),this._gw3Session.onJoined((e=>{if(e)return this._reAnnounceKnownContexts?void this.reInitiateState().then((()=>this._connection.setLibReAnnounced({name:"contexts"}))):this._connection.setLibReAnnounced({name:"contexts"})})),this.subscribeToContextCreatedMessages(),this.subscribeToContextUpdatedMessages(),this.subscribeToContextDestroyedMessages(),this._connection.replayer?.drain(_r.name,(e=>{const t=e.type;t&&(t===gr||t===mr||t===ur?this.handleContextCreatedMessage(e):t===br||t===Ir||t===Sr?this.handleContextUpdatedMessage(e):t!==vr&&t!==pr||this.handleContextDestroyedMessage(e))}))}dispose(){for(const e of this._gw3Subscriptions)this._connection.off(e);this._gw3Subscriptions.length=0;for(const e in this._contextNameToData)this._contextNameToId.hasOwnProperty(e)&&delete this._contextNameToData[e]}createContext(e,t){return e in this._creationPromises||(this._creationPromises[e]=this._gw3Session.send({type:hr,domain:"global",name:e,data:t,lifetime:"retained"}).then((n=>{this._contextNameToId[e]=n.context_id,this._contextIdToName[n.context_id]=e;const i=this._contextNameToData[e]||new kr(n.context_id,e,!0,void 0);return i.isAnnounced=!0,i.name=e,i.contextId=n.context_id,i.context=n.data||Ar(t),i.hasReceivedSnapshot=!0,this._contextNameToData[e]=i,delete this._creationPromises[e],n.context_id}))),this._creationPromises[e]}all(){return Object.keys(this._contextNameToData).filter((e=>this._contextNameToData[e].isAnnounced))}async update(e,t){t&&(t=Ar(t)),e in this._creationPromises&&await this._creationPromises[e];const n=this._contextNameToData[e];if(!n||!n.isAnnounced)return this.createContext(e,t);let i=n.context;n.hasCallbacks()||(i=await this.get(n.name));const s=this.setPathSupported?this.calculateContextDeltaV2(i,t):this.calculateContextDeltaV1(i,t);return Object.keys(s.added).length||Object.keys(s.updated).length||s.removed.length||s.commands?.length?this._gw3Session.send({type:Cr,domain:"global",context_id:n.contextId,delta:s},{},{skipPeerId:!1}).then((e=>{this.handleUpdated(n,s,{updaterId:e.peer_id})})):Promise.resolve()}async set(e,t){t&&(t=Ar(t)),e in this._creationPromises&&await this._creationPromises[e];const n=this._contextNameToData[e];return n&&n.isAnnounced?this._gw3Session.send({type:Cr,domain:"global",context_id:n.contextId,delta:{reset:t}},{},{skipPeerId:!1}).then((e=>{this.handleUpdated(n,{reset:t,added:{},removed:[],updated:{}},{updaterId:e.peer_id})})):this.createContext(e,t)}setPath(e,t,n){return this.setPathSupported?this.setPaths(e,[{path:t,value:n}]):Promise.reject("glue.contexts.setPath operation is not supported, use Glue42 3.10 or later")}async setPaths(e,t){if(!this.setPathSupported)return Promise.reject("glue.contexts.setPaths operation is not supported, use Glue42 3.10 or later");t&&(t=Ar(t)),e in this._creationPromises&&await this._creationPromises[e];const n=this._contextNameToData[e];if(!n||!n.isAnnounced){const n={};for(const e of t)Or(n,e.value,e.path);return this.createContext(e,n)}const i=[];for(const e of t)null===e.value?i.push({type:"remove",path:e.path}):i.push({type:"set",path:e.path,value:e.value});return this._gw3Session.send({type:Cr,domain:"global",context_id:n.contextId,delta:{commands:i}},{},{skipPeerId:!1}).then((e=>{this.handleUpdated(n,{added:{},removed:[],updated:{},commands:i},{updaterId:e.peer_id})}))}async get(e){e in this._creationPromises&&await this._creationPromises[e];const t=this._contextNameToData[e];if(!t||!t.isAnnounced)return Promise.resolve({});if(t&&(!t.hasCallbacks()||!t.hasReceivedSnapshot))return new Promise((t=>{this.subscribe(e,((e,n,i,s)=>{this.unsubscribe(s),t(e)}))}));const n=t?.context??{};return Promise.resolve(Ar(n))}async subscribe(e,t,n){e in this._creationPromises&&await this._creationPromises[e];const i=void 0===n?this._nextCallbackSubscriptionNumber:n;void 0===n&&(this._nextCallbackSubscriptionNumber+=1),this._contextsSubscriptionsCache.every((e=>e.subKey!==this._nextCallbackSubscriptionNumber))&&this._contextsSubscriptionsCache.push({contextName:e,subKey:i,callback:t});let s=this._contextNameToData[e];if(!s||!s.isAnnounced)return s=s||new kr(void 0,e,!1,void 0),this._contextNameToData[e]=s,s.updateCallbacks[i]=t,Promise.resolve(i);const r=s.hasCallbacks();if(s.updateCallbacks[i]=t,r){if(s.hasReceivedSnapshot){const e=Ar(s.context);t(e,e,[],i)}return Promise.resolve(i)}if(s.joinedActivity){if(s.hasReceivedSnapshot){const e=Ar(s.context);t(e,e,[],i)}return Promise.resolve(i)}if(s.context&&s.sentExplicitSubscription){if(s.hasReceivedSnapshot){const e=Ar(s.context);t(e,e,[],i)}return Promise.resolve(i)}return this.sendSubscribe(s).then((()=>i))}unsubscribe(e){this._contextsSubscriptionsCache=this._contextsSubscriptionsCache.filter((t=>t.subKey!==e));for(const t of Object.keys(this._contextNameToData)){const n=this._contextNameToData[t];if(!n)return;const i=n.hasCallbacks();delete n.updateCallbacks[e],n.isAnnounced&&i&&!n.hasCallbacks()&&n.sentExplicitSubscription&&this.sendUnsubscribe(n).catch((()=>{})),n.isAnnounced||n.hasCallbacks()||delete this._contextNameToData[t]}}async destroy(e){e in this._creationPromises&&await this._creationPromises[e];const t=this._contextNameToData[e];return t?this._gw3Session.send({type:yr,domain:"global",context_id:t.contextId}).then((e=>{})):Promise.reject(`context with ${e} does not exist`)}handleUpdated(e,t,n){const i=e.context;e.context=Rr(e.context,t,this._logger),e.hasReceivedSnapshot=!0,this._contextNameToData[e.name]!==e||Er(i,e.context)||this.invokeUpdateCallbacks(e,t,n)}subscribeToContextCreatedMessages(){const e=[mr,gr,ur];for(const t of e){const e=this._connection.on(t,this.handleContextCreatedMessage.bind(this));this._gw3Subscriptions.push(e)}}handleContextCreatedMessage(e){const t=e.type;t===ur?(this._contextNameToId[e.activity_id]=e.context_id,this._contextIdToName[e.context_id]=e.activity_id):t===mr&&(this._contextNameToId[e.name]=e.context_id,this._contextIdToName[e.context_id]=e.name);const n=this._contextIdToName[e.context_id];if(!n)throw new Error("Received created event for context with unknown name: "+e.context_id);if(!this._contextNameToId[n])throw new Error("Received created event for context with unknown id: "+e.context_id);let i=this._contextNameToData[n];if(i){if(i.isAnnounced)return;if(!i.hasCallbacks())throw new Error("Assertion failure: contextData.hasCallbacks()");i.isAnnounced=!0,i.contextId=e.context_id,i.activityId=e.activity_id,i.sentExplicitSubscription||this.sendSubscribe(i)}else this._contextNameToData[n]=i=new kr(e.context_id,n,!0,e.activity_id),this._trackAllContexts&&this.subscribe(n,(()=>{})).then((e=>this._systemContextsSubKey=e))}subscribeToContextUpdatedMessages(){const e=[Ir,br,Sr];for(const t of e){const e=this._connection.on(t,this.handleContextUpdatedMessage.bind(this));this._gw3Subscriptions.push(e)}}handleContextUpdatedMessage(e){const t=e.type,n=e.context_id;let i=this._contextNameToData[this._contextIdToName[n]];const s=!i||!i.isAnnounced;if(t===Sr)i||(i=this._contextNameToData[e.activity_id]||new kr(n,e.activity_id,!0,e.activity_id)),this._contextNameToData[e.activity_id]=i,this._contextIdToName[n]=e.activity_id,this._contextNameToId[e.activity_id]=n,i.contextId=n,i.isAnnounced=!0,i.activityId=e.activity_id,i.joinedActivity=!0;else if(!i||!i.isAnnounced)return void(t===br?(i=i||new kr(n,e.name,!0,void 0),i.sentExplicitSubscription=!0,this._contextNameToData[e.name]=i,this._contextIdToName[n]=e.name,this._contextNameToId[e.name]=n):this._logger.error(`Received 'update' for unknown context: ${n}`));const r=i.context;if(i.hasReceivedSnapshot=!0,t===br)i.context=e.data||{};else if(t===Sr)i.context=e.context_snapshot||{};else{if(t!==Ir)throw new Error("Unrecognized context update message "+t);i.context=Rr(i.context,e.delta,this._logger)}!s&&Er(i.context,r)&&t!==br||this.invokeUpdateCallbacks(i,e.delta,{updaterId:e.updater_id})}invokeUpdateCallbacks(e,t,n){if((t=t||{added:{},updated:{},reset:{},removed:[]}).commands){t.added=t.updated=t.reset={},t.removed=[];for(const e of t.commands)"remove"===e.type?(-1===e.path.indexOf(".")&&t.removed.push(e.path),Or(t.updated,null,e.path)):"set"===e.type&&Or(t.updated,e.value,e.path)}for(const i in e.updateCallbacks)if(e.updateCallbacks.hasOwnProperty(i))try{(0,e.updateCallbacks[i])(Ar(e.context),Ar(Object.assign({},t.added||{},t.updated||{},t.reset||{})),t.removed,parseInt(i,10),n)}catch(e){this._logger.debug("callback error: "+JSON.stringify(e))}}subscribeToContextDestroyedMessages(){const e=[vr,pr];for(const t of e){const e=this._connection.on(t,this.handleContextDestroyedMessage.bind(this));this._gw3Subscriptions.push(e)}}handleContextDestroyedMessage(e){let t,n;if(e.type===pr){if(n=e.activity_id,t=this._contextNameToId[n],!t)return void this._logger.error(`Received 'destroyed' for unknown activity: ${e.activity_id}`)}else if(t=e.context_id,n=this._contextIdToName[t],!n)return void this._logger.error(`Received 'destroyed' for unknown context: ${e.context_id}`);delete this._contextIdToName[t],delete this._contextNameToId[n];const i=this._contextNameToData[n];delete this._contextNameToData[n],i&&i.isAnnounced||this._logger.error(`Received 'destroyed' for unknown context: ${t}`)}sendSubscribe(e){return e.sentExplicitSubscription=!0,this._gw3Session.send({type:fr,domain:"global",context_id:e.contextId}).then((e=>{}))}sendUnsubscribe(e){return e.sentExplicitSubscription=!1,this._gw3Session.send({type:wr,domain:"global",context_id:e.contextId}).then((e=>{}))}calculateContextDeltaV1(e,t){const n={added:{},updated:{},removed:[],reset:void 0};if(e)for(const i of Object.keys(e))-1===Object.keys(t).indexOf(i)||null===t[i]||Er(e[i],t[i])||(n.updated[i]=t[i]);for(const i of Object.keys(t))e&&-1!==Object.keys(e).indexOf(i)?null===t[i]&&n.removed.push(i):null!==t[i]&&(n.added[i]=t[i]);return n}calculateContextDeltaV2(e,t){const n={added:{},updated:{},removed:[],reset:void 0,commands:[]};for(const i of Object.keys(t))if(null!==t[i]){Er(e?e[i]:null,t[i])||n.commands?.push({type:"set",path:i,value:t[i]})}else n.commands?.push({type:"remove",path:i});return n}resetState(){for(const e of this._gw3Subscriptions)this._connection.off(e);this._systemContextsSubKey&&(this.unsubscribe(this._systemContextsSubKey),delete this._systemContextsSubKey),this._gw3Subscriptions=[],this._contextNameToId={},this._contextIdToName={},delete this._protocolVersion,this._contextsTempCache=Object.keys(this._contextNameToData).reduce(((e,t)=>(e[t]=this._contextNameToData[t].context,e)),{}),this._contextNameToData={}}async reInitiateState(){this.subscribeToContextCreatedMessages(),this.subscribeToContextUpdatedMessages(),this.subscribeToContextDestroyedMessages(),this._connection.replayer?.drain(_r.name,(e=>{const t=e.type;t&&(t===gr||t===mr||t===ur?this.handleContextCreatedMessage(e):t===br||t===Ir||t===Sr?this.handleContextUpdatedMessage(e):t!==vr&&t!==pr||this.handleContextDestroyedMessage(e))})),await Promise.all(this._contextsSubscriptionsCache.map((e=>this.subscribe(e.contextName,e.callback,e.subKey)))),await this.flushQueue();for(const e in this._contextsTempCache){if("object"!=typeof this._contextsTempCache[e]||0===Object.keys(this._contextsTempCache[e]).length)continue;const t=this._contextsTempCache[e];this._logger.info(`Re-announcing known context: ${e}`),await this.flushQueue(),await this.update(e,t)}this._contextsTempCache={},this._logger.info("Contexts are re-announced")}flushQueue(){return new Promise((e=>setTimeout((()=>e()),0)))}}class Lr{initTime;initStartTime;initEndTime;_bridge;constructor(e){this._bridge=new Nr(e)}all(){return this._bridge.all()}update(e,t){return this.checkName(e),this.checkData(t),this._bridge.update(e,t)}set(e,t){return this.checkName(e),this.checkData(t),this._bridge.set(e,t)}setPath(e,t,n){this.checkName(e),this.checkPath(t);return""===t?(this.checkData(n),this.set(e,n)):this._bridge.setPath(e,t,n)}setPaths(e,t){if(this.checkName(e),!Array.isArray(t))throw new Error("Please provide the paths as an array of PathValues!");for(const{path:e,value:n}of t){this.checkPath(e);""===e&&this.checkData(n)}return this._bridge.setPaths(e,t)}subscribe(e,t){if(this.checkName(e),"function"!=typeof t)throw new Error("Please provide the callback as a function!");return this._bridge.subscribe(e,((e,n,i,s,r)=>t(e,n,i,(()=>this._bridge.unsubscribe(s)),r))).then((e=>()=>{this._bridge.unsubscribe(e)}))}get(e){return this.checkName(e),this._bridge.get(e)}ready(){return Promise.resolve(this)}destroy(e){return this.checkName(e),this._bridge.destroy(e)}get setPathSupported(){return this._bridge.setPathSupported}checkName(e){if("string"!=typeof e||""===e)throw new Error("Please provide the name as a non-empty string!")}checkPath(e){if("string"!=typeof e)throw new Error("Please provide the path as a dot delimited string!")}checkData(e){if("object"!=typeof e)throw new Error("Please provide the data as an object!")}}function Fr(e,t,n){return"function"!=typeof t&&"function"!=typeof n?e:("function"!=typeof t?t=()=>{}:"function"!=typeof n&&(n=()=>{}),e.then(t,n))}function $r(e=0,t,n){let i;const s=()=>{i&&clearTimeout(i)};return t.then((()=>{s()})).catch((()=>{s()})),new Promise(((t,s)=>{i=setTimeout((()=>s(n)),e)}))}var Wr;!function(e){e[e.Success=0]="Success",e[e.Error=1]="Error"}(Wr||(Wr={}));class qr{protocol;repo;instance;configuration;constructor(e,t,n,i){this.protocol=e,this.repo=t,this.instance=n,this.configuration=i}subscribe(e,t,n,i,s){const r=(e,n,i,r)=>{t.methodResponseTimeout=t.methodResponseTimeout??t.waitTimeoutMs,this.protocol.client.subscribe(n,t,e,i,r,s)},o=new Promise(((n,i)=>{const s=e=>{n(e)},o=e=>{i(e)};if(!e)return void i("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");let a;if(a="string"==typeof e?{name:e}:e,!a.name)return void i("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");void 0===t&&(t={});let c=t.target;if(void 0===c&&(c="best"),"string"==typeof c&&"all"!==c&&"best"!==c)return void i(new Error(`"${c}" is not a valid target. Valid targets are "all", "best", or an instance.`));void 0===t.methodResponseTimeout&&(t.methodResponseTimeout=t.method_response_timeout,void 0===t.methodResponseTimeout&&(t.methodResponseTimeout=this.configuration.methodResponseTimeout)),void 0===t.waitTimeoutMs&&(t.waitTimeoutMs=t.wait_for_method_timeout,void 0===t.waitTimeoutMs&&(t.waitTimeoutMs=this.configuration.waitTimeoutMs));let d=0,l=this.getServerMethodsByFilterAndTarget(a,c);if(l.length>0)r(l,l[0].methods[0],s,o);else{const n=()=>{if(c&&t.waitTimeoutMs)if(d+=500,l=this.getServerMethodsByFilterAndTarget(a,c),l.length>0){const e=l[0].methods[0];r(l,e,s,o)}else if(d>=t.waitTimeoutMs){r(l,"string"==typeof e?{name:e}:e,s,o)}else setTimeout(n,500)};setTimeout(n,500)}}));return Fr(o,n,i)}servers(e){const t=void 0===e?void 0:{...e};return this.getServers(t).map((e=>e.server.instance))}methods(e){return e="string"==typeof e?{name:e}:{...e},this.getMethods(e)}methodsForInstance(e){return this.getMethodsForInstance(e)}methodAdded(e){return this.repo.onMethodAdded(e)}methodRemoved(e){return this.repo.onMethodRemoved(e)}serverAdded(e){return this.repo.onServerAdded(e)}serverRemoved(e){return this.repo.onServerRemoved(((t,n)=>{e(t,n)}))}serverMethodAdded(e){return this.repo.onServerMethodAdded(((t,n)=>{e({server:t,method:n})}))}serverMethodRemoved(e){return this.repo.onServerMethodRemoved(((t,n)=>{e({server:t,method:n})}))}async invoke(e,t,n,i,s,r){return Fr((async()=>{let s;if(s="string"==typeof e?{name:e}:{...e},!s.name)return Promise.reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");if(t||(t={}),n||(n="best"),"string"==typeof n&&"all"!==n&&"best"!==n&&"skipMine"!==n)return Promise.reject(new Error(`"${n}" is not a valid target. Valid targets are "all" and "best".`));if(i||(i={}),void 0===i.methodResponseTimeoutMs&&(i.methodResponseTimeoutMs=i.method_response_timeout,void 0===i.methodResponseTimeoutMs&&(i.methodResponseTimeoutMs=this.configuration.methodResponseTimeout)),void 0===i.waitTimeoutMs&&(i.waitTimeoutMs=i.wait_for_method_timeout,void 0===i.waitTimeoutMs&&(i.waitTimeoutMs=this.configuration.waitTimeoutMs)),void 0!==i.waitTimeoutMs&&"number"!=typeof i.waitTimeoutMs)return Promise.reject(new Error(`"${i.waitTimeoutMs}" is not a valid number for "waitTimeoutMs" `));if("object"!=typeof t)return Promise.reject(new Error(`The method arguments must be an object. method: ${s.name}`));let r=this.getServerMethodsByFilterAndTarget(s,n);if(0===r.length)try{r=await this.tryToAwaitForMethods(s,n,i)}catch(i){const r={method:{...s,getServers:()=>[],supportsStreaming:!1,objectTypes:s.objectTypes??[],flags:s.flags?.metadata??{}},called_with:t,message:`Can not find a method matching ${JSON.stringify(e)} with server filter ${JSON.stringify(n)}`,executed_by:void 0,returned:void 0,status:void 0};return Promise.reject(r)}const o=i.methodResponseTimeoutMs,a=i,c=r.map((e=>{const n=ir(10),i=e.methods[0],s=e.server,r=this.protocol.client.invoke(n,i,t,s,a);return Promise.race([r,$r(o,r,{invocationId:n,message:`Invocation timeout (${o} ms) reached for method name: ${i?.name}, target instance: ${JSON.stringify(s.instance)}, options: ${JSON.stringify(a)}`,status:Wr.Error})])})),d=await Promise.all(c),l=this.getInvocationResultObj(d,s,t);return d.every((e=>e.status===Wr.Error))?Promise.reject(l):l})(),s,r)}getInvocationResultObj(e,t,n){const i=e.filter((e=>e.status===Wr.Success)).reduce(((e,i)=>e=[...e,{executed_by:i.instance,returned:i.result,called_with:n,method:t,message:i.message,status:i.status}]),[]),s=e.filter((e=>e.status===Wr.Error)).reduce(((e,i)=>e=[...e,{executed_by:i.instance,called_with:n,name:t.name,message:i.message}]),[]),r=e[0];return{method:t,called_with:n,returned:r.result,executed_by:r.instance,all_return_values:i,all_errors:s,message:r.message,status:r.status}}tryToAwaitForMethods(e,t,n){return new Promise(((i,s)=>{if(0===n.waitTimeoutMs)return void s();let r=0;const o=setInterval((()=>{r+=500;const a=this.getServerMethodsByFilterAndTarget(e,t);if(a.length>0)clearInterval(o),i(a);else if(r>=(n.waitTimeoutMs||1e4))return clearInterval(o),void s()}),500)}))}filterByTarget(e,t){if("string"!=typeof e){let n;n=Array.isArray(e)?e:[e];return n.reduce(((e,n)=>{const i=t.filter((e=>this.instanceMatch(n,e.server.instance)));return e.concat(i)}),[])}if("all"===e)return[...t];if("best"===e){const e=t.find((e=>e.server.instance.isLocal));if(e)return[e];if(void 0!==t[0])return[t[0]]}else if("skipMine"===e)return t.filter((({server:e})=>e.instance.peerId!==this.instance.peerId));return[]}instanceMatch(e,t){return e?.peerId&&e?.instance&&delete(e={...e}).peerId,this.containsProps(e,t)}methodMatch(e,t){return this.containsProps(e,t)}containsProps(e,t){return Object.keys(e).filter((t=>void 0!==e[t]&&null!==e[t]&&"function"!=typeof e[t]&&"object_types"!==t&&"display_name"!==t&&"id"!==t&&"gatewayId"!==t&&"identifier"!==t&&"_"!==t[0])).every((n=>{let i;const s=e[n],r=t[n];switch(n){case"objectTypes":i=(s||[]).every((e=>(r||[]).includes(e)));break;case"flags":i=Dr(r||{},s||{});break;default:i=String(s).toLowerCase()===String(r).toLowerCase()}return i}))}getMethods(e){if(void 0===e)return this.repo.getMethods();return this.repo.getMethods().filter((t=>this.methodMatch(e,t)))}getMethodsForInstance(e){const t=this.repo.getServers().filter((t=>this.instanceMatch(e,t.instance)));if(0===t.length)return[];let n={};return 1===t.length?n=t[0].methods:t.forEach((e=>{Object.keys(e.methods).forEach((t=>{const i=e.methods[t];n[i.identifier]=i}))})),Object.keys(n).map((e=>n[e]))}getServers(e){const t=this.repo.getServers();return void 0===e?t.map((e=>({server:e,methods:[]}))):t.reduce(((t,n)=>{const i=Object.values(n.methods).filter((t=>this.methodMatch(e,t)));return i.length>0&&t.push({server:n,methods:i}),t}),[])}getServerMethodsByFilterAndTarget(e,t){const n=this.getServers(e);return this.filterByTarget(t,n)}}class Gr{protocol;repoMethod;subscription;constructor(e,t,n){this.protocol=e,this.repoMethod=t,this.subscription=n}get stream(){if(!this.repoMethod.stream)throw new Error("no stream");return this.repoMethod.stream}get arguments(){return this.subscription.arguments||{}}get branchKey(){return this.subscription.branchKey}get instance(){if(!this.subscription.instance)throw new Error("no instance");return this.subscription.instance}close(){this.protocol.server.closeSingleSubscription(this.repoMethod,this.subscription)}push(e){this.protocol.server.pushDataToSingle(this.repoMethod,this.subscription,e)}}class Br{protocol;repoMethod;requestContext;arguments;instance;constructor(e,t,n){this.protocol=e,this.repoMethod=t,this.requestContext=n,this.arguments=n.arguments,this.instance=n.instance}accept(){this.protocol.server.acceptRequestOnBranch(this.requestContext,this.repoMethod,"")}acceptOnBranch(e){this.protocol.server.acceptRequestOnBranch(this.requestContext,this.repoMethod,e)}reject(e){this.protocol.server.rejectRequest(this.requestContext,this.repoMethod,e)}}class Ur{key;protocol;repoMethod;constructor(e,t,n){this.key=e,this.protocol=t,this.repoMethod=n}subscriptions(){return this.protocol.server.getSubscriptionList(this.repoMethod,this.key).map((e=>new Gr(this.protocol,this.repoMethod,e)))}close(){this.protocol.server.closeAllSubscriptions(this.repoMethod,this.key)}push(e){this.protocol.server.pushData(this.repoMethod,e,[this.key])}}class Hr{_protocol;_repoMethod;_server;name;constructor(e,t,n){this._protocol=e,this._repoMethod=t,this._server=n,this.name=this._repoMethod.definition.name}branches(e){const t=this._protocol.server.getBranchList(this._repoMethod);return e?t.indexOf(e)>-1?new Ur(e,this._protocol,this._repoMethod):void 0:t.map((e=>new Ur(e,this._protocol,this._repoMethod)))}branch(e){return this.branches(e)}subscriptions(){return this._protocol.server.getSubscriptionList(this._repoMethod).map((e=>new Gr(this._protocol,this._repoMethod,e)))}get definition(){const e=this._repoMethod.definition;return{accepts:e.accepts,description:e.description,displayName:e.displayName,name:e.name,objectTypes:e.objectTypes,returns:e.returns,supportsStreaming:e.supportsStreaming,flags:e.flags?.metadata}}close(){this._protocol.server.closeAllSubscriptions(this._repoMethod),this._server.unregister(this._repoMethod.definition,!0)}push(e,t){if("string"!=typeof t&&!Array.isArray(t)&&void 0!==t)throw new Error("invalid branches should be string or string array");if("object"!=typeof e)throw new Error("Invalid arguments. Data must be an object.");this._protocol.server.pushData(this._repoMethod,e,t)}updateRepoMethod(e){this._repoMethod=e}}class Jr{protocol;serverRepository;streaming;invocations=0;currentlyUnregistering={};constructor(e,t){this.protocol=e,this.serverRepository=t,this.streaming=new class{protocol;server;constructor(e,t){this.protocol=e,this.server=t,e.server.onSubRequest(((e,t)=>this.handleSubRequest(e,t))),e.server.onSubAdded(((e,t)=>this.handleSubAdded(e,t))),e.server.onSubRemoved(((e,t)=>this.handleSubRemoved(e,t)))}handleSubRequest(e,t){if(!t||!t.streamCallbacks||"function"!=typeof t.streamCallbacks.subscriptionRequestHandler)return;const n=new Br(this.protocol,t,e);t.streamCallbacks.subscriptionRequestHandler(n)}handleSubAdded(e,t){if(!t||!t.streamCallbacks||"function"!=typeof t.streamCallbacks.subscriptionAddedHandler)return;const n=new Gr(this.protocol,t,e);t.streamCallbacks.subscriptionAddedHandler(n)}handleSubRemoved(e,t){if(!t||!t.streamCallbacks||"function"!=typeof t.streamCallbacks.subscriptionRemovedHandler)return;const n=new Gr(this.protocol,t,e);t.streamCallbacks.subscriptionRemovedHandler(n)}}(e,this),this.protocol.server.onInvoked(this.onMethodInvoked.bind(this))}createStream(e,t,n,i,s){const r=new Promise(((n,i)=>{if(!e)return void i("The stream name must be unique! Please, provide either a unique string for a stream name to “glue.interop.createStream()” or a “methodDefinition” object with a unique “name” property for the stream.");let r;if(r="string"==typeof e?{name:""+e}:{...e},!r.name)return i(`The “name” property is required for the “streamDefinition” object and must be unique. Stream definition: ${JSON.stringify(r)}`);if(this.serverRepository.getList().some((e=>e.definition.name===r.name)))return i(`A stream with the name "${r.name}" already exists! Please, provide a unique name for the stream.`);r.supportsStreaming=!0,t||(t={}),"function"!=typeof t.subscriptionRequestHandler&&(t.subscriptionRequestHandler=e=>{e.accept()});const o=this.serverRepository.add({definition:r,streamCallbacks:t,protocolState:{}});this.protocol.server.createStream(o).then((()=>{let e;s?(e=s,s.updateRepoMethod(o)):e=new Hr(this.protocol,o,this),o.stream=e,n(e)})).catch((e=>{o.repoId&&this.serverRepository.remove(o.repoId),i(e)}))}));return Fr(r,n,i)}register(e,t){if(!e)return Promise.reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");if("function"!=typeof t)return Promise.reject(`The second parameter must be a callback function. Method: ${"string"==typeof e?e:e.name}`);const n=async(e,n)=>{try{const i=t(e.args,e.instance);if(i&&"function"==typeof i.then){n(void 0,await i)}else n(void 0,i)}catch(e){n(e??"",e??"")}};return n.userCallback=t,this.registerCore(e,n)}registerAsync(e,t){if(!e)return Promise.reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");if("function"!=typeof t)return Promise.reject(`The second parameter must be a callback function. Method: ${"string"==typeof e?e:e.name}`);const n=async(e,n)=>{try{let i=!1;const s=e=>{i||n(void 0,e),i=!0},r=e=>{i||(e||(e=""),n(e,e)),i=!0},o=t(e.args,e.instance,s,r);o&&"function"==typeof o.then&&o.then(s).catch(r)}catch(e){n(e,void 0)}};return n.userCallbackAsync=t,this.registerCore(e,n)}async unregister(e,t=!1){if(void 0===e)return Promise.reject("Please, provide either a unique string for a name or an object containing a “name” property.");if("function"==typeof e)return void await this.unregisterWithPredicate(e,t);let n;if(n="string"==typeof e?{name:e}:e,void 0===n.name)return Promise.reject("Method name is required. Cannot find a method if the method name is undefined!");const i=this.serverRepository.getList().find((e=>e.definition.name===n.name&&(e.definition.supportsStreaming||!1)===t));if(!i)return Promise.reject(`Method with a name "${n.name}" does not exist or is not registered by your application!`);await this.removeMethodsOrStreams([i])}async unregisterWithPredicate(e,t){const n=this.serverRepository.getList().filter((t=>e(t.definition))).filter((e=>(e.definition.supportsStreaming||!1)===t));if(!n||0===n.length)return Promise.reject(`Could not find a ${t?"stream":"method"} matching the specified condition!`);await this.removeMethodsOrStreams(n)}removeMethodsOrStreams(e){const t=[];return e.forEach((e=>{const n=this.protocol.server.unregister(e).then((()=>{e.repoId&&this.serverRepository.remove(e.repoId)}));t.push(n),this.addAsCurrentlyUnregistering(e.definition.name,n)})),Promise.all(t)}async addAsCurrentlyUnregistering(e,t){const n=new Promise((e=>setTimeout(e,5e3)));this.currentlyUnregistering[e]=Promise.race([t,n]).then((()=>{delete this.currentlyUnregistering[e]}))}async registerCore(e,t){let n;if(n="string"==typeof e?{name:""+e}:{...e},!n.name)return Promise.reject(`Please, provide a (unique) string value for the “name” property in the “methodDefinition” object: ${JSON.stringify(e)}`);const i=this.currentlyUnregistering[n.name];void 0!==i&&await i;if(this.serverRepository.getList().some((e=>e.definition.name===n.name)))return Promise.reject(`A method with the name "${n.name}" already exists! Please, provide a unique name for the method.`);if(n.supportsStreaming)return Promise.reject(`When you create methods with “glue.interop.register()” or “glue.interop.registerAsync()” the property “supportsStreaming” cannot be “true”. If you want “${n.name}” to be a stream, please use the “glue.interop.createStream()” method.`);const s=this.serverRepository.add({definition:n,theFunction:t,protocolState:{}});return this.protocol.server.register(s).catch((e=>{throw s?.repoId&&this.serverRepository.remove(s.repoId),e}))}onMethodInvoked(e,t,n){e&&e.theFunction&&e.theFunction(n,((n,i)=>{if(null!=n)if(n.message&&"string"==typeof n.message)n=n.message;else if("string"!=typeof n)try{n=JSON.stringify(n)}catch(e){n=`un-stringifyable error in onMethodInvoked! Top level prop names: ${Object.keys(n)}`}i?("object"!=typeof i||Array.isArray(i))&&(i={_value:i}):i={},this.protocol.server.methodInvocationResult(e,t,n,i)}))}}class Kr{wrapped={};constructor(e,t,n){this.wrapped.getMethods=function(){return e.methodsForInstance(this)},this.wrapped.getStreams=function(){return e.methodsForInstance(this).filter((e=>e.supportsStreaming))},t&&this.refreshWrappedObject(t),n&&(n.loggedIn((()=>{this.refresh(n)})),this.refresh(n))}unwrap(){return this.wrapped}refresh(e){if(!e)return;const t=e?.resolvedIdentity,n=Object.assign({},t??{},{peerId:e?.peerId});this.refreshWrappedObject(n)}refreshWrappedObject(e){Object.keys(e).forEach((t=>{this.wrapped[t]=e[t]})),this.wrapped.user=e.user,this.wrapped.instance=e.instance,this.wrapped.application=e.application??ir(10),this.wrapped.applicationName=e.applicationName,this.wrapped.pid=e.pid??e.process??Math.floor(1e10*Math.random()),this.wrapped.machine=e.machine,this.wrapped.environment=e.environment,this.wrapped.region=e.region,this.wrapped.windowId=e.windowId,this.wrapped.isLocal=e.isLocal??!0,this.wrapped.api=e.api,this.wrapped.service=e.service,this.wrapped.peerId=e.peerId}}const zr=e=>({...e,flags:e.flags.metadata||{}});class Vr{logger;API;servers={};myServer;methodsCount={};callbacks=Ks();constructor(e,t){this.logger=e,this.API=t;const n=this.API.instance.peerId;this.myServer={id:n,methods:{},instance:this.API.instance,wrapper:this.API.unwrappedInstance},this.servers[n]=this.myServer}addServer(e,t){this.logger.debug(`adding server ${t}`);const n=this.servers[t];if(n)return n.id;const i=new Kr(this.API,e),s={id:t,methods:{},instance:i.unwrap(),wrapper:i};return this.servers[t]=s,this.callbacks.execute("onServerAdded",s.instance),t}removeServerById(e,t){const n=this.servers[e];n?(this.logger.debug(`removing server ${e}`),Object.keys(n.methods).forEach((t=>{this.removeServerMethod(e,t)})),delete this.servers[e],this.callbacks.execute("onServerRemoved",n.instance,t)):this.logger.warn(`not aware of server ${e}, my state ${JSON.stringify(Object.keys(this.servers))}`)}addServerMethod(e,t){const n=this.servers[e];if(!n)throw new Error("server does not exists");if(n.methods[t.id])return;const i=this.createMethodIdentifier(t),s=this,r={identifier:i,gatewayId:t.id,name:t.name,displayName:t.display_name,description:t.description,version:t.version,objectTypes:t.object_types||[],accepts:t.input_signature,returns:t.result_signature,supportsStreaming:void 0!==t.flags&&t.flags.streaming,flags:t.flags??{},getServers:()=>s.getServersByMethod(i)};r.object_types=r.objectTypes,r.display_name=r.displayName,r.version=r.version,n.methods[t.id]=r;const o=zr(r);return this.methodsCount[i]||(this.methodsCount[i]=0,this.callbacks.execute("onMethodAdded",o)),this.methodsCount[i]=this.methodsCount[i]+1,this.callbacks.execute("onServerMethodAdded",n.instance,o),r}removeServerMethod(e,t){const n=this.servers[e];if(!n)throw new Error("server does not exists");const i=n.methods[t];delete n.methods[t];const s=zr(i);this.methodsCount[i.identifier]=this.methodsCount[i.identifier]-1,0===this.methodsCount[i.identifier]&&this.callbacks.execute("onMethodRemoved",s),this.callbacks.execute("onServerMethodRemoved",n.instance,s)}getMethods(){return this.extractMethodsFromServers(Object.values(this.servers)).map(zr)}getServers(){return Object.values(this.servers).map(this.hideServerMethodSystemFlags)}onServerAdded(e){const t=this.callbacks.add("onServerAdded",e),n=this.getServers().map((e=>e.instance));return this.returnUnsubWithDelayedReplay(t,n,e)}onMethodAdded(e){const t=this.callbacks.add("onMethodAdded",e),n=this.getMethods();return this.returnUnsubWithDelayedReplay(t,n,e)}onServerMethodAdded(e){const t=this.callbacks.add("onServerMethodAdded",e);let n=!1;const i=this.getServers();return setTimeout((()=>{i.forEach((t=>{const i=t.methods;Object.keys(i).forEach((s=>{n||e(t.instance,i[s])}))}))}),0),()=>{n=!0,t()}}onMethodRemoved(e){return this.callbacks.add("onMethodRemoved",e)}onServerRemoved(e){return this.callbacks.add("onServerRemoved",e)}onServerMethodRemoved(e){return this.callbacks.add("onServerMethodRemoved",e)}getServerById(e){if(this.servers[e])return this.hideServerMethodSystemFlags(this.servers[e])}reset(){Object.keys(this.servers).forEach((e=>{this.removeServerById(e,"reset")})),this.servers={[this.myServer.id]:this.myServer},this.methodsCount={}}createMethodIdentifier(e){const t=e.input_signature??"",n=e.result_signature??"";return(e.name+t+n).toLowerCase()}getServersByMethod(e){const t=[];return Object.values(this.servers).forEach((n=>{Object.values(n.methods).forEach((i=>{i.identifier===e&&t.push(n.instance)}))})),t}returnUnsubWithDelayedReplay(e,t,n){let i=!1;return setTimeout((()=>{t.forEach((e=>{i||n(e)}))}),0),()=>{i=!0,e()}}hideServerMethodSystemFlags(e){const t={};return Object.entries(e.methods).forEach((([e,n])=>{t[e]=zr(n)})),{...e,methods:t}}extractMethodsFromServers(e){return Object.values(e).reduce(((e,t)=>[...e,...Object.values(t.methods)]),[])}}class Qr{nextId=0;methods=[];add(e){return e.repoId=String(this.nextId),this.nextId+=1,this.methods.push(e),e}remove(e){if("string"!=typeof e)return new TypeError("Expecting a string");this.methods=this.methods.filter((t=>t.repoId!==e))}getById(e){if("string"==typeof e)return this.methods.find((t=>t.repoId===e))}getList(){return this.methods.map((e=>e))}length(){return this.methods.length}reset(){this.methods=[]}}const Xr="onSubscriptionRequest",Yr="onSubscriptionAdded",Zr="onSubscriptionRemoved";class eo{session;repository;serverRepository;ERR_URI_SUBSCRIPTION_FAILED="com.tick42.agm.errors.subscription.failure";callbacks=Ks();nextStreamId=0;constructor(e,t,n){this.session=e,this.repository=t,this.serverRepository=n,e.on("add-interest",(e=>{this.handleAddInterest(e)})),e.on("remove-interest",(e=>{this.handleRemoveInterest(e)}))}acceptRequestOnBranch(e,t,n){if("string"!=typeof n&&(n=""),"object"!=typeof t.protocolState.subscriptionsMap)throw new TypeError("The streaming method is missing its subscriptions.");if(!Array.isArray(t.protocolState.branchKeyToStreamIdMap))throw new TypeError("The streaming method is missing its branches.");const i=this.getStreamId(t,n),s=e.msg.subscription_id,r={id:s,arguments:e.arguments,instance:e.instance,branchKey:n,streamId:i,subscribeMsg:e.msg};t.protocolState.subscriptionsMap[s]=r,this.session.sendFireAndForget({type:"accepted",subscription_id:s,stream_id:i}),this.callbacks.execute(Yr,r,t)}rejectRequest(e,t,n){"string"!=typeof n&&(n=""),this.sendSubscriptionFailed("Subscription rejected by user. "+n,e.msg.subscription_id)}pushData(e,t,n){if("object"!=typeof e||!Array.isArray(e.protocolState.branchKeyToStreamIdMap))return;if("object"!=typeof t)throw new Error("Invalid arguments. Data must be an object.");"string"==typeof n?n=[n]:(!Array.isArray(n)||n.length<=0)&&(n=[]);e.protocolState.branchKeyToStreamIdMap.filter((e=>!n||0===n.length||n.indexOf(e.key)>=0)).map((e=>e.streamId)).forEach((e=>{const n={type:"publish",stream_id:e,data:t};this.session.sendFireAndForget(n)}))}pushDataToSingle(e,t,n){if("object"!=typeof n)throw new Error("Invalid arguments. Data must be an object.");const i={type:"post",subscription_id:t.id,data:n};this.session.sendFireAndForget(i)}closeSingleSubscription(e,t){e.protocolState.subscriptionsMap&&delete e.protocolState.subscriptionsMap[t.id];const n={type:"drop-subscription",subscription_id:t.id,reason:"Server dropping a single subscription"};this.session.sendFireAndForget(n),t.instance,this.callbacks.execute(Zr,t,e)}closeMultipleSubscriptions(e,t){if("object"!=typeof e||"object"!=typeof e.protocolState.subscriptionsMap)return;if(!e.protocolState.subscriptionsMap)return;const n=e.protocolState.subscriptionsMap;let i=Object.keys(n).map((e=>n[e]));"string"==typeof t&&(i=i.filter((e=>e.branchKey===t))),i.forEach((e=>{delete n[e.id];const t={type:"drop-subscription",subscription_id:e.id,reason:"Server dropping all subscriptions on stream_id: "+e.streamId};this.session.sendFireAndForget(t)}))}getSubscriptionList(e,t){if("object"!=typeof e)return[];let n=[];if(!e.protocolState.subscriptionsMap)return[];const i=e.protocolState.subscriptionsMap,s=Object.keys(i).map((e=>i[e]));return n="string"!=typeof t?s:s.filter((e=>e.branchKey===t)),n}getBranchList(e){if("object"!=typeof e)return[];if(!e.protocolState.subscriptionsMap)return[];const t=e.protocolState.subscriptionsMap,n=Object.keys(t).map((e=>t[e])),i=[];return n.forEach((e=>{let t="";"object"==typeof e&&"string"==typeof e.branchKey&&(t=e.branchKey),-1===i.indexOf(t)&&i.push(t)})),i}onSubAdded(e){this.onSubscriptionLifetimeEvent(Yr,e)}onSubRequest(e){this.onSubscriptionLifetimeEvent(Xr,e)}onSubRemoved(e){this.onSubscriptionLifetimeEvent(Zr,e)}handleRemoveInterest(e){const t=this.serverRepository.getById(e.method_id);if("string"!=typeof e.subscription_id||"object"!=typeof t)return;if(!t.protocolState.subscriptionsMap)return;if("object"!=typeof t.protocolState.subscriptionsMap[e.subscription_id])return;const n=t.protocolState.subscriptionsMap[e.subscription_id];delete t.protocolState.subscriptionsMap[e.subscription_id],this.callbacks.execute(Zr,n,t)}onSubscriptionLifetimeEvent(e,t){this.callbacks.add(e,t)}getNextStreamId(){return this.nextStreamId+++""}handleAddInterest(e){const t=this.repository.getServerById(e.caller_id),n=t?.instance??{},i={msg:e,arguments:e.arguments_kv||{},instance:n},s=this.serverRepository.getById(e.method_id);if(void 0!==s)s.protocolState.subscriptionsMap&&s.protocolState.subscriptionsMap[e.subscription_id]?this.sendSubscriptionFailed("A subscription with id "+e.subscription_id+" already exists.",e.subscription_id):this.callbacks.execute(Xr,i,s);else{const t="No method with id "+e.method_id+" on this server.";this.sendSubscriptionFailed(t,e.subscription_id)}}sendSubscriptionFailed(e,t){const n={type:"error",reason_uri:this.ERR_URI_SUBSCRIPTION_FAILED,reason:e,request_id:t};this.session.sendFireAndForget(n)}getStreamId(e,t){if("string"!=typeof t&&(t=""),!e.protocolState.branchKeyToStreamIdMap)throw new Error(`streaming ${e.definition.name} method without protocol state`);const n=e.protocolState.branchKeyToStreamIdMap.filter((e=>e.key===t))[0];let i=n?n.streamId:void 0;return"string"==typeof i&&""!==i||(i=this.getNextStreamId(),e.protocolState.branchKeyToStreamIdMap.push({key:t,streamId:i})),i}}class to{session;clientRepository;serverRepository;logger;callbacks=Ks();streaming;constructor(e,t,n,i){this.session=e,this.clientRepository=t,this.serverRepository=n,this.logger=i,this.streaming=new eo(e,t,n),this.session.on("invoke",(e=>this.handleInvokeMessage(e)))}createStream(e){return e.protocolState.subscriptionsMap={},e.protocolState.branchKeyToStreamIdMap=[],this.register(e,!0)}register(e,t){const n=e.definition,i=Object.assign({},{metadata:n.flags??{}},{streaming:t||!1}),s={type:"register",methods:[{id:e.repoId,name:n.name,display_name:n.displayName,description:n.description,version:n.version,flags:i,object_types:n.objectTypes||n.object_types,input_signature:n.accepts,result_signature:n.returns,restrictions:void 0}]};return this.session.send(s,{methodId:e.repoId}).then((()=>{this.logger.debug("registered method "+e.definition.name+" with id "+e.repoId)})).catch((t=>{throw this.logger.warn(`failed to register method ${e.definition.name} with id ${e.repoId} - ${JSON.stringify(t)}`),t}))}onInvoked(e){this.callbacks.add("onInvoked",e)}methodInvocationResult(e,t,n,i){let s;s=n||""===n?{type:"error",request_id:t,reason_uri:"agm.errors.client_error",reason:n,context:i,peer_id:void 0}:{type:"yield",invocation_id:t,peer_id:this.session.peerId,result:i,request_id:void 0},this.session.sendFireAndForget(s)}async unregister(e){const t={type:"unregister",methods:[e.repoId]};await this.session.send(t)}getBranchList(e){return this.streaming.getBranchList(e)}getSubscriptionList(e,t){return this.streaming.getSubscriptionList(e,t)}closeAllSubscriptions(e,t){this.streaming.closeMultipleSubscriptions(e,t)}pushData(e,t,n){this.streaming.pushData(e,t,n)}pushDataToSingle(e,t,n){this.streaming.pushDataToSingle(e,t,n)}closeSingleSubscription(e,t){this.streaming.closeSingleSubscription(e,t)}acceptRequestOnBranch(e,t,n){this.streaming.acceptRequestOnBranch(e,t,n)}rejectRequest(e,t,n){this.streaming.rejectRequest(e,t,n)}onSubRequest(e){this.streaming.onSubRequest(e)}onSubAdded(e){this.streaming.onSubAdded(e)}onSubRemoved(e){this.streaming.onSubRemoved(e)}handleInvokeMessage(e){const t=e.invocation_id,n=e.caller_id,i=e.method_id,s=e.arguments_kv,r=this.serverRepository.getList().filter((e=>e.repoId===i))[0];if(void 0===r)return;const o=this.clientRepository.getServerById(n)?.instance,a={args:s,instance:o};this.callbacks.execute("onInvoked",r,t,a)}}class no{repository;subscriptionData;get requestArguments(){return this.subscriptionData.params.arguments||{}}get servers(){return this.subscriptionData.trackedServers.reduce(((e,t)=>{if(t.subscriptionId){const n=this.repository.getServerById(t.serverId)?.instance;n&&e.push(n)}return e}),[])}get serverInstance(){return this.servers[0]}get stream(){return this.subscriptionData.method}constructor(e,t){this.repository=e,this.subscriptionData=t}onData(e){if("function"!=typeof e)throw new TypeError("The data callback must be a function.");this.subscriptionData.handlers.onData.push(e),1===this.subscriptionData.handlers.onData.length&&this.subscriptionData.queued.data.length>0&&this.subscriptionData.queued.data.forEach((t=>{e(t)}))}onClosed(e){if("function"!=typeof e)throw new TypeError("The callback must be a function.");this.subscriptionData.handlers.onClosed.push(e)}onFailed(e){}onConnected(e){if("function"!=typeof e)throw new TypeError("The callback must be a function.");this.subscriptionData.handlers.onConnected.push(e)}close(){this.subscriptionData.close()}setNewSubscription(e){this.subscriptionData=e}}class io{config;cache=[];timeoutIds=[];constructor(e){this.config=e}add(e){const t=ir(10);this.cache.push({id:t,element:e});const n=setTimeout((()=>{const e=this.cache.findIndex((e=>e.id===t));e<0||this.cache.splice(e,1)}),this.config.ELEMENT_TTL_MS);this.timeoutIds.push(n)}flush(){const e=this.cache.map((e=>e.element));return this.timeoutIds.forEach((e=>clearInterval(e))),this.cache=[],this.timeoutIds=[],e}}const so="awaitingAccept",ro="subscribed",oo="Subscription failed.",ao="ClientInitiated";class co{session;repository;logger;subscriptionsList={};timedCache=new io({ELEMENT_TTL_MS:1e4});subscriptionIdToLocalKeyMap={};nextSubLocalKey=0;constructor(e,t,n){this.session=e,this.repository=t,this.logger=n,e.on("subscribed",this.handleSubscribed),e.on("event",this.handleEventData),e.on("subscription-cancelled",this.handleSubscriptionCancelled)}subscribe(e,t,n,i,s,r){if(0===n.length)return void s({method:e,called_with:t.arguments,message:oo+" No available servers matched the target params."});const o=this.getNextSubscriptionLocalKey(),a=this.registerSubscription(o,e,t,i,s,t.methodResponseTimeout||1e4,r);"object"==typeof a?n.forEach((n=>{const i=n.server.id,s=n.methods.find((t=>t.name===e.name));if(!s)return void this.logger.error(`can not find method ${e.name} for target ${n.server.id}`);a.trackedServers.push({serverId:i,subscriptionId:void 0});const r={type:"subscribe",server_id:i,method_id:s.gatewayId,arguments_kv:t.arguments};this.session.send(r,{serverId:i,subLocalKey:o}).then((e=>this.handleSubscribed(e))).catch((e=>this.handleErrorSubscribing(e)))})):s({method:e,called_with:t.arguments,message:oo+" Unable to register the user callbacks."})}drainSubscriptions(){const e=Object.values(this.subscriptionsList);return this.subscriptionsList={},this.subscriptionIdToLocalKeyMap={},e}drainSubscriptionsCache(){return this.timedCache.flush()}getNextSubscriptionLocalKey(){const e=this.nextSubLocalKey;return this.nextSubLocalKey+=1,e}registerSubscription(e,t,n,i,s,r,o){const a={localKey:e,status:so,method:t,params:n,success:i,error:s,trackedServers:[],handlers:{onData:o?.handlers.onData||[],onClosed:o?.handlers.onClosed||[],onConnected:o?.handlers.onConnected||[]},queued:{data:[],closers:[]},timeoutId:void 0,close:()=>this.closeSubscription(e),subscription:o?.subscription};return o||(n.onData&&a.handlers.onData.push(n.onData),n.onClosed&&a.handlers.onClosed.push(n.onClosed),n.onConnected&&a.handlers.onConnected.push(n.onConnected)),this.subscriptionsList[e]=a,a.timeoutId=setTimeout((()=>{if(void 0===this.subscriptionsList[e])return;const i=this.subscriptionsList[e];i.status===so?(s({method:t,called_with:n.arguments,message:oo+" Subscription attempt timed out after "+r+" ms."}),delete this.subscriptionsList[e]):i.status===ro&&i.trackedServers.length>0&&(i.trackedServers=i.trackedServers.filter((e=>void 0!==e.subscriptionId)),delete i.timeoutId,i.trackedServers.length<=0&&(this.callOnClosedHandlers(i),delete this.subscriptionsList[e]))}),r),a}handleErrorSubscribing=e=>{const t=e._tag,n=t.subLocalKey,i=this.subscriptionsList[n];if("object"==typeof i&&(i.trackedServers=i.trackedServers.filter((e=>e.serverId!==t.serverId)),i.trackedServers.length<=0)){if(clearTimeout(i.timeoutId),i.status===so){const t="string"==typeof e.reason&&""!==e.reason?' Publisher said "'+e.reason+'".':" No reason given.",n="object"==typeof i.params.arguments?JSON.stringify(i.params.arguments):"{}";i.error({message:"Subscription rejected."+t+" Called with:"+n,called_with:i.params.arguments,method:i.method})}else i.status===ro&&this.callOnClosedHandlers(i);delete this.subscriptionsList[n]}};handleSubscribed=e=>{const t=e._tag.subLocalKey,n=this.subscriptionsList[t];if("object"!=typeof n)return;const i=e._tag.serverId,s=n.trackedServers.filter((e=>e.serverId===i))[0];if("object"!=typeof s)return;s.subscriptionId=e.subscription_id,this.subscriptionIdToLocalKeyMap[e.subscription_id]=t;const r=n.status===so;if(n.status=ro,r){let e=!1,t=n.subscription;t?(t.setNewSubscription(n),n.success(t),e=!0):(t=new no(this.repository,n),n.subscription=t,n.success(t));for(const i of n.handlers.onConnected)try{i(t.serverInstance,e)}catch(e){}}};handleEventData=e=>{const t=this.subscriptionIdToLocalKeyMap[e.subscription_id];if(void 0===t)return;const n=this.subscriptionsList[t];if("object"!=typeof n)return;const i=n.trackedServers.filter((t=>t.subscriptionId===e.subscription_id));if(1!==i.length)return;const s=e.oob,r=i[0].serverId,o=this.repository.getServerById(r),a=()=>({data:e.data,server:o?.instance??{},requestArguments:n.params.arguments,message:void 0,private:s}),c=n.handlers.onData,d=n.queued.data;c.length>0?c.forEach((e=>{"function"==typeof e&&e(a())})):d.push(a())};handleSubscriptionCancelled=e=>{const t=this.subscriptionIdToLocalKeyMap[e.subscription_id];if(void 0===t)return;const n=this.subscriptionsList[t];if("object"!=typeof n)return;const i=n.trackedServers.length-1;n.trackedServers=n.trackedServers.filter((t=>t.subscriptionId!==e.subscription_id||(n.queued.closers.push(t.serverId),!1))),n.trackedServers.length===i&&(n.trackedServers.length<=0&&(this.timedCache.add(n),clearTimeout(n.timeoutId),this.callOnClosedHandlers(n),delete this.subscriptionsList[t]),delete this.subscriptionIdToLocalKeyMap[e.subscription_id])};callOnClosedHandlers(e,t){const n=e.queued.closers.length,i=n>0?e.queued.closers[n-1]:null;let s;void 0!==i&&"string"==typeof i&&(s=this.repository.getServerById(i)?.instance??{}),e.handlers.onClosed.forEach((n=>{"function"==typeof n&&n({message:t||"ServerInitiated",requestArguments:e.params.arguments||{},server:s,stream:e.method})}))}closeSubscription(e){const t=this.subscriptionsList[e];"object"==typeof t&&(t.trackedServers.forEach((e=>{void 0!==e.subscriptionId&&(t.queued.closers.push(e.serverId),this.session.sendFireAndForget({type:"unsubscribe",subscription_id:e.subscriptionId,reason_uri:"",reason:ao}),delete this.subscriptionIdToLocalKeyMap[e.subscriptionId])})),t.trackedServers=[],this.callOnClosedHandlers(t,ao),delete this.subscriptionsList[e])}}class lo{session;repository;logger;streaming;constructor(e,t,n){this.session=e,this.repository=t,this.logger=n,e.on("peer-added",(e=>this.handlePeerAdded(e))),e.on("peer-removed",(e=>this.handlePeerRemoved(e))),e.on("methods-added",(e=>this.handleMethodsAddedMessage(e))),e.on("methods-removed",(e=>this.handleMethodsRemovedMessage(e))),this.streaming=new co(e,t,n)}subscribe(e,t,n,i,s,r){this.streaming.subscribe(e,t,n,i,s,r)}invoke(e,t,n,i){const s=i.id,r={type:"call",server_id:s,method_id:t.gatewayId,arguments_kv:n};return this.session.send(r,{invocationId:e,serverId:s}).then((e=>this.handleResultMessage(e))).catch((e=>this.handleInvocationError(e)))}drainSubscriptions(){return this.streaming.drainSubscriptions()}drainSubscriptionsCache(){return this.streaming.drainSubscriptionsCache()}handlePeerAdded(e){const t=e.new_peer_id,n=e.identity,i=!e.meta||e.meta.local,s=Number(n.process),r={machine:n.machine,pid:isNaN(s)?n.process:s,instance:n.instance,application:n.application,applicationName:n.applicationName,environment:n.environment,region:n.region,user:n.user,windowId:n.windowId,peerId:t,api:n.api,isLocal:i};this.repository.addServer(r,t)}handlePeerRemoved(e){const t=e.removed_id,n=e.reason;this.repository.removeServerById(t,n)}handleMethodsAddedMessage(e){const t=e.server_id;e.methods.forEach((e=>{this.repository.addServerMethod(t,e)}))}handleMethodsRemovedMessage(e){const t=e.server_id,n=e.methods,i=this.repository.getServerById(t);if(i){Object.keys(i.methods).forEach((e=>{const s=i.methods[e];n.indexOf(s.gatewayId)>-1&&this.repository.removeServerMethod(t,e)}))}}handleResultMessage(e){const t=e._tag.invocationId,n=e.result,i=e._tag.serverId,s=this.repository.getServerById(i);return{invocationId:t,result:n,instance:s?.instance,status:Wr.Success,message:""}}handleInvocationError(e){if(this.logger.debug(`handle invocation error ${JSON.stringify(e)}`),"_tag"in e){const t=e._tag.invocationId,n=e._tag.serverId,i=this.repository.getServerById(n),s=e.reason;return{invocationId:t,result:e.context,instance:i?.instance,status:Wr.Error,message:s}}return{invocationId:"",message:e.message,status:Wr.Error,error:e}}}function ho(e,t,n,i,s,r){const o=s.logger.subLogger("gw3-protocol");let a;const c=new Promise((e=>{a=e})),d=t.domain("agm",["subscribed"]),l=new to(d,n,i,o.subLogger("server")),h=new lo(d,n,o.subLogger("client"));return d.onJoined((s=>{n.addServer(e,t.peerId),s?async function(){o.info("reconnected - will replay registered methods and subscriptions"),h.drainSubscriptionsCache().forEach((e=>{const t=e.method,n=Object.assign({},e.params);o.info(`trying to soft-re-subscribe to method ${t.name}, with params: ${JSON.stringify(n)}`),r.client.subscribe(t,n,void 0,void 0,e).then((()=>o.info(`soft-subscribing to method ${t.name} DONE`))).catch((e=>o.warn(`subscribing to method ${t.name} failed: ${JSON.stringify(e)}}`)))}));const e=[],t=h.drainSubscriptions();for(const n of t){const t=n.method,i=Object.assign({},n.params);o.info(`trying to re-subscribe to method ${t.name}, with params: ${JSON.stringify(i)}`),e.push(r.client.subscribe(t,i,void 0,void 0,n).then((()=>o.info(`subscribing to method ${t.name} DONE`))))}const n=i.getList();i.reset();for(const t of n){const n=t.definition;t.stream?e.push(r.server.createStream(n,t.streamCallbacks,void 0,void 0,t.stream).then((()=>o.info(`subscribing to method ${n.name} DONE`))).catch((()=>o.warn(`subscribing to method ${n.name} FAILED`)))):t?.theFunction?.userCallback?e.push(r.register(n,t.theFunction.userCallback).then((()=>o.info(`registering method ${n.name} DONE`))).catch((()=>o.warn(`registering method ${n.name} FAILED`)))):t?.theFunction?.userCallbackAsync&&e.push(r.registerAsync(n,t.theFunction.userCallbackAsync).then((()=>o.info(`registering method ${n.name} DONE`))).catch((()=>o.warn(`registering method ${n.name} FAILED`))))}await Promise.all(e),o.info("Interop is re-announced")}().then((()=>t.setLibReAnnounced({name:"interop"}))).catch((e=>o.warn(`Error while re-announcing interop: ${JSON.stringify(e)}`))):a&&(a({client:h,server:l}),a=void 0)})),d.onLeft((()=>{n.reset()})),d.join(),c}class uo{instance;readyPromise;client;server;unwrappedInstance;protocol;clientRepository;serverRepository;constructor(e){if(void 0===e)throw new Error("configuration is required");if(void 0===e.connection)throw new Error("configuration.connections is required");const t=e.connection;let n;if("number"!=typeof e.methodResponseTimeout&&(e.methodResponseTimeout=3e4),"number"!=typeof e.waitTimeoutMs&&(e.waitTimeoutMs=3e4),this.unwrappedInstance=new Kr(this,void 0,t),this.instance=this.unwrappedInstance.unwrap(),this.clientRepository=new Vr(e.logger.subLogger("cRep"),this),this.serverRepository=new Qr,3!==t.protocolVersion)throw new Error(`protocol ${t.protocolVersion} not supported`);n=ho(this.instance,t,this.clientRepository,this.serverRepository,e,this),this.readyPromise=n.then((t=>(this.protocol=t,this.client=new qr(this.protocol,this.clientRepository,this.instance,e),this.server=new Jr(this.protocol,this.serverRepository),this)))}ready(){return this.readyPromise}serverRemoved(e){return this.client.serverRemoved(e)}serverAdded(e){return this.client.serverAdded(e)}serverMethodRemoved(e){return this.client.serverMethodRemoved(e)}serverMethodAdded(e){return this.client.serverMethodAdded(e)}methodRemoved(e){return this.client.methodRemoved(e)}methodAdded(e){return this.client.methodAdded(e)}methodsForInstance(e){return this.client.methodsForInstance(e)}methods(e){return this.client.methods(e)}servers(e){return this.client.servers(e)}subscribe(e,t,n,i){return this.client.subscribe(e,t,n,i)}createStream(e,t,n,i){return this.server.createStream(e,t,n,i)}unregister(e){return this.server.unregister(e)}registerAsync(e,t){return this.server.registerAsync(e,t)}register(e,t){return this.server.register(e,t)}invoke(e,t,n,i,s,r){return this.client.invoke(e,t,n,i,s,r)}waitForMethod(e){const t=new Xs,n=this.client.methodAdded((i=>{i.name===e&&(n(),t.resolve(i))}));return t.promise}}const po=["subscribed","success"];class go{connection;logger;peerId;session;subscriptions;readyPromise;constructor(e,t){this.connection=e,this.logger=t,this.peerId=e.peerId,this.subscriptions=[],this.session=e.domain("bus",po),this.readyPromise=this.session.join(),this.readyPromise.then((()=>{this.watchOnEvent()}))}ready(){return this.readyPromise}publish=(e,t,n)=>{const{routingKey:i,target:s}=n||{},r=this.removeEmptyValues({type:"publish",topic:e,data:t,peer_id:this.peerId,routing_key:i,target_identity:s});this.session.send(r)};subscribe=(e,t,n)=>new Promise(((i,s)=>{const{routingKey:r,target:o}=n||{},a=this.removeEmptyValues({type:"subscribe",topic:e,peer_id:this.peerId,routing_key:r,source:o});this.session.send(a).then((n=>{const{subscription_id:s}=n;this.subscriptions.push({subscription_id:s,topic:e,callback:t,source:o}),i({unsubscribe:()=>(this.session.send({type:"unsubscribe",subscription_id:s,peer_id:this.peerId}),this.subscriptions=this.subscriptions.filter((e=>e.subscription_id!==s)),Promise.resolve())})})).catch((e=>s(e)))}));watchOnEvent=()=>{this.session.on("event",(e=>{const{data:t,subscription_id:n}=e,i=e["publisher-identity"],s=this.subscriptions.find((e=>e.subscription_id===n));s&&(s.source?this.keysMatch(s.source,i)&&s.callback(t,s.topic,i):s.callback(t,s.topic,i))}))};removeEmptyValues(e){const t={};return Object.keys(e).forEach((n=>{void 0!==e[n]&&null!==e[n]&&(t[n]=e[n])})),t}keysMatch(e,t){const n=Object.keys(e);let i=!0;return n.forEach((n=>{e[n]!==t[n]&&(i=!1)})),i}}const mo=(e,t)=>{const n="object"==typeof window?window.iodesktop??window.glue42gd:void 0,i="object"==typeof window?window.gdPreloadPromise??Promise.resolve():Promise.resolve(),s=Zs("glue"),r=function(e,t,n){let i;if(Qs.isNode()){const e=process.env._GD_STARTING_CONTEXT_;if(e)try{i=JSON.parse(e)}catch{}}function s(){if(e.application)return e.application;if(n)return n.applicationName;if("undefined"!=typeof window&&void 0!==window.glue42electron)return window.glue42electron.application;const t=ir(10);return Qs.isNode()?i?i.applicationConfig.name:"NodeJS"+t:"undefined"!=typeof window&&"undefined"!=typeof document?document.title+` (${t})`:t}const r=function(){const r=e.gateway,o=r?.protocolVersion??3,a=r?.reconnectInterval,c=r?.reconnectAttempts;let d=r?.ws;const l=r?.sharedWorker,h=r?.inproc,u=r?.webPlatform??void 0;let p,g,m,f,b;n&&(d=n.gwURL),Qs.isNode()&&i&&i.gwURL&&(d=i.gwURL),d||l||h||(d="ws://localhost:8385");const w=s();let y=w;void 0!==n?(g=n.windowId,m=n.pid,n.env&&(f=n.env.env,b=n.env.region),y=n.application??"glue-app",p=n.appInstanceId):Qs.isNode()?(m=process.pid,i&&(f=i.env,b=i.region,p=i.instanceId)):void 0!==window?.glue42electron&&(g=window?.glue42electron.instanceId,m=window?.glue42electron.pid,f=window?.glue42electron.env,b=window?.glue42electron.region,y=window?.glue42electron.application??"glue-app",p=window?.glue42electron.instanceId);const v=e.gateway?.replaySpecs??[];v.push(_r);let C={application:y,applicationName:w,windowId:g,instance:p,process:m,region:b,environment:f,api:t.version||xr};return e.identity&&(C=Object.assign(C,e.identity)),{identity:C,reconnectInterval:a,ws:d,sharedWorker:l,webPlatform:u,inproc:h,protocolVersion:o,reconnectAttempts:c,replaySpecs:v}}();let o=s();if("undefined"!=typeof window){const e=window,t=e.htmlContainer?`${e.htmlContainer.containerName}.${e.htmlContainer.application}`:e?.glue42gd?.application;t&&(o=t)}return{bus:e.bus??!1,application:o,auth:"string"==typeof e.auth?{token:e.auth}:e.auth?e.auth:Qs.isNode()&&i&&i.gwToken?{gatewayToken:i.gwToken}:e.gateway?.webPlatform||e.gateway?.inproc||e.gateway?.sharedWorker?{username:"glue42",password:"glue42"}:void 0,logger:function(){let t=e.logger;const i="warn";let s;return t||(t=i),n&&(s=n.consoleLogLevel),"string"==typeof t?{console:s??t,publish:i}:{console:s??t.console??i,publish:t.publish??i}}(),connection:r,metrics:e.metrics??!0,contexts:void 0===e.contexts||"boolean"==typeof e.contexts&&e.contexts?{reAnnounceKnownContexts:!0}:"object"==typeof e.contexts&&Object.assign({},{reAnnounceKnownContexts:!0},e.contexts),version:t.version||xr,libs:t.libs??[],customLogger:e.customLogger}}(e=e||{},t=t||{},n);let o,a,c,d,l,h,u;const p={};function g(e,t,n){u=c.canPublish("trace"),u&&c.trace(`registering ${e} module`);const i=()=>{t.initTime=n.stop(),t.initEndTime=n.endTime,t.marks=n.marks,u&&c.trace(`${e} is ready - ${n.endTime-n.startTime}`)};t.initStartTime=n.startTime,t.ready?t.ready().then((()=>{i()})):i(),Array.isArray(e)||(e=[e]),e.forEach((e=>{p[e]=t,mo[e]=t}))}function m(){const e=Zs("metrics"),t=r.metrics,i=n?.getMetricsPublishingEnabled,s=r.connection.identity,a=i||(()=>!0),l=("boolean"!=typeof t&&t.disableAutoAppSystem)??!1;return d=Bs({connection:t?o:void 0,logger:c.subLogger("metrics"),canUpdateMetric:a,system:"Glue42",service:s?.service??n?.applicationName??r.application,instance:s?.instance??s?.windowId??ir(10),disableAutoAppSystem:l,pagePerformanceMetrics:"boolean"!=typeof t?t?.pagePerformanceMetrics:void 0}),g("metrics",d,e),Promise.resolve()}function f(){const e=Zs("interop"),t={connection:o,logger:c.subLogger("interop")};return a=new uo(t),lr.Interop=a,g(["interop","agm"],a,e),Promise.resolve()}function b(){const e=r.activities&&3===o.protocolVersion;if(r.contexts||e){const e=Zs("contexts");return l=new Lr({connection:o,logger:c.subLogger("contexts"),trackAllContexts:"object"==typeof r.contexts&&r.contexts.trackAllContexts,reAnnounceKnownContexts:"object"==typeof r.contexts&&r.contexts.reAnnounceKnownContexts}),g("contexts",l,e),l}{const e=o.replayer;e&&e.drain(_r.name)}}async function w(){if(!r.bus)return Promise.resolve();const e=Zs("bus");return h=new go(o,c.subLogger("bus")),g("bus",h,e),Promise.resolve()}function y(e){try{return e.forEach((e=>{!function(e,t){const n=Zs(e),i=t(p);i&&g(e,i,n)}(e.name,e.create)})),Promise.resolve()}catch(e){return Promise.reject(e)}}return i.then((function(){const e=Zs("logger");return c=new lr(`${r.connection.identity?.application}`,void 0,r.customLogger),c.consoleLevel(r.logger.console),c.publishLevel(r.logger.publish),c.canPublish("debug")&&c.debug("initializing glue..."),g("logger",c,e),Promise.resolve(void 0)})).then((function(){const e=Zs("connection");o=new cr(r.connection,c.subLogger("connection"));let t=Promise.resolve(r.auth);return r.connection&&!r.auth&&(n?t=n.getGWToken().then((e=>({gatewayToken:e}))):"undefined"!=typeof window&&window?.glue42electron?"string"==typeof window.glue42electron.gwToken&&(t=Promise.resolve({gatewayToken:window.glue42electron.gwToken})):t=Promise.reject("You need to provide auth information")),t.then((t=>{let n;if(e.mark("auth-promise-resolved"),"[object Object]"!==Object.prototype.toString.call(t))throw new Error("Invalid auth object - "+JSON.stringify(t));return n=t,o.login(n)})).then((()=>(g("connection",o,e),r))).catch((e=>{throw o&&o.logout(),e}))})).then((()=>Promise.all([m(),f(),b(),w()]))).then((()=>a.readyPromise)).then((()=>async function(){const t="T42.ACS.RegisterInstance";if(Qs.isNode()&&void 0===process.env._GD_STARTING_CONTEXT_&&void 0!==e?.application&&a.methods({name:t}).length>0)try{await a.invoke(t,{appName:e?.application,pid:process.pid})}catch(e){const t=e;c.error(`Cannot register as an instance: ${JSON.stringify(t.message)}`)}}())).then((()=>y(r.libs||[]))).then((function(){const e=Object.keys(p).map((e=>{const t=p[e];return t.ready?t.ready():Promise.resolve()}));return Promise.all(e)})).then((function(){const i={coreVersion:xr,version:r.version};s.stop();const u={feedback:e=>{a&&a.invoke("T42.ACS.Feedback",e,"best")},info:i,logger:c,interop:a,agm:a,connection:o,metrics:d,contexts:l,bus:h,version:r.version,userConfig:e,done:()=>(c?.info("done called by user..."),o.logout())};if(u.performance={get glueVer(){return r.version},get glueConfig(){return JSON.stringify(e)},get browser(){return window.performance.timing.toJSON()},get memory(){return window.performance.memory},get initTimes(){const e=Ys;return Object.keys(e).map((t=>{const n=e[t];return{name:t,duration:n.endTime-n.startTime,marks:n.marks,startTime:n.startTime,endTime:n.endTime}}))}},Object.keys(p).forEach((e=>{const t=p[e];u[e]=t})),u.config={},Object.keys(r).forEach((e=>{u.config[e]=r[e]})),t&&t.extOptions&&Object.keys(t.extOptions).forEach((e=>{u.config[e]=t?.extOptions[e]})),t?.enrichGlue&&t.enrichGlue(u),n&&n.updatePerfData&&n.updatePerfData(u.performance),u.agm){const e=(e,t,n)=>function(){return u.logger.warn(`glue.js - 'glue.agm.${t}' method is deprecated, use 'glue.interop.${n}' instead.`),e.apply(u.agm,arguments)},t=u.agm;t.method_added=e(u.agm.methodAdded,"method_added","methodAdded"),t.method_removed=e(u.agm.methodRemoved,"method_removed","methodRemoved"),t.server_added=e(u.agm.serverAdded,"server_added","serverAdded"),t.server_method_aded=e(u.agm.serverMethodAdded,"server_method_aded","serverMethodAdded"),t.server_method_removed=e(u.agm.serverMethodRemoved,"server_method_removed","serverMethodRemoved")}return u})).catch((e=>Promise.reject({err:e,libs:p})))};"undefined"!=typeof window&&(window.IOConnectCore=mo),mo.version=xr,mo.default=mo;const fo=(t=>{let n;const i=async e=>{const n=new Cs,i=await(s=()=>t(e,{version:Is}),r=3e4,o="Glue Web initialization timed out, because core didn't resolve",new Promise(((e,t)=>{let n=!0;const i=setTimeout((()=>{n&&(n=!1,t(o))}),r);s().then((t=>{n&&(n=!1,clearTimeout(i),e(t))})).catch((e=>{n&&(n=!1,clearTimeout(i),t(e))}))})));var s,r,o;const a=i.logger.subLogger("web.main.controller");n.defineGlue(i),n.sessionController.configure({windowId:i.interop.instance.instance}),await n.preferredConnectionController.start(e),await n.bridge.start(n.controllers),n.defineConfig(e),a.trace("the bridge has been started, initializing all controllers"),await Promise.all(Object.values(n.controllers).map((e=>e.start(i,n)))),a.trace("all controllers reported started, starting all additional libraries");try{return await Promise.all(e.libraries.map((t=>t(i,e)))),a.trace("all libraries were started"),n.eventsDispatcher.start(i),a.trace("start event dispatched, glue is ready, returning it"),await Promise.all(Object.values(n.controllers).map((e=>e.postStart?e.postStart(i,n):Promise.resolve()))),i}catch(e){return m.raiseError(e,!0)}};return t=>{if(window.glue42gd||window.iodesktop)return(e=>{const t={windows:!0,layouts:"full",appManager:"full",channels:!0,libraries:e?.libraries??[],logger:e?.systemLogger?.level??"warn"};return(window.IODesktop||window.Glue)(t)})(t);const s=(t=>{const n=!!t?.gateway?.webPlatform?.port,i=Object.assign({},e,t,{isPlatformInternal:n});return i.systemLogger&&(i.logger=i.systemLogger.level??"info"),i})(t);try{(()=>{const e=window.glue42core||window.iobrowser;if(e&&e.webStarted)return m.raiseError("IoConnect Browser has already been started for this application.");e?e.webStarted=!0:window.iobrowser={webStarted:!0}})()}catch(e){return void 0===n?Promise.reject(new Error(e)):n}const r=i(s);return n=t?.memoizeAPI?r:void 0,r}})(mo);if("undefined"!=typeof window){const e=window;e.IOBrowser=fo,delete e.GlueCore,delete e.IOConnectCore}const bo=window.glue42gd||window.glue42core,wo=window.iodesktop||window.iobrowser;return bo||wo||(window.iobrowser={webStarted:!1}),fo.version=Is,fo}));
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):((e="undefined"!=typeof globalThis?globalThis:e||self).browser=e.browser||{},e.browser.min=t())}(this,(function(){"use strict";const e={logger:"info",gateway:{webPlatform:{}},libraries:[],exposeAPI:!0},t={awaitFactory:!0,timeout:5e3},n={name:"platformUnload"},i={name:"transportSwitchRequest"},s={name:"transportSwitchResponse"},r={name:"getCurrentTransport"},o={name:"getCurrentTransportResponse"},a={name:"checkPreferredLogic"},c={name:"checkPreferredConnection"},d={name:"checkPreferredLogicResponse"},l={name:"checkPreferredConnectionResponse"},h="web-platform",u="latest_fdc3_type",p=new MessageChannel,g=e=>"string"==typeof e?e:e?.message?"string"==typeof e.message?e.message:JSON.stringify(e.message):JSON.stringify(e),m=(e,t)=>{try{return e.runWithException(t)}catch(e){return f.raiseError(e,!0)}};const f=new class{raiseError(e,t){const n=g(e);if(p.port1.postMessage(n),t)throw e;throw new Error(n)}};var w=function(e){return{ok:!0,result:e}},b=function(e){return{ok:!1,error:e}},y=function(e,t,n){return!1===t.ok?t:!1===n.ok?n:w(e(t.result,n.result))},v=function(e,t){return!0===t.ok?t:b(e(t.error))},C=function(){return C=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++)for(var s in t=arguments[n])Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s]);return e},C.apply(this,arguments)};function I(e,t){if(e===t)return!0;if(null===e&&null===t)return!0;if(typeof e!=typeof t)return!1;if("object"==typeof e){if(Array.isArray(e)){if(!Array.isArray(t))return!1;if(e.length!==t.length)return!1;for(var n=0;n<e.length;n++)if(!I(e[n],t[n]))return!1;return!0}var i=Object.keys(e);if(i.length!==Object.keys(t).length)return!1;for(n=0;n<i.length;n++){if(!t.hasOwnProperty(i[n]))return!1;if(!I(e[i[n]],t[i[n]]))return!1}return!0}}var S=function(e){return Array.isArray(e)},_=function(e){return"object"==typeof e&&null!==e&&!S(e)},x=function(e,t){return"expected "+e+", got "+function(e){switch(typeof e){case"string":return"a string";case"number":return"a number";case"boolean":return"a boolean";case"undefined":return"undefined";case"object":return e instanceof Array?"an array":null===e?"null":"an object";default:return JSON.stringify(e)}}(t)},k=function(e){return e.map((function(e){return"string"==typeof e?"."+e:"["+e+"]"})).join("")},T=function(e,t){var n=t.at,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(i=Object.getOwnPropertySymbols(e);s<i.length;s++)t.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(e,i[s])&&(n[i[s]]=e[i[s]])}return n}(t,["at"]);return C({at:e+(n||"")},i)},R=function(){function e(t){var n=this;this.decode=t,this.run=function(e){return v((function(t){return{kind:"DecoderError",input:e,at:"input"+(t.at||""),message:t.message||""}}),n.decode(e))},this.runPromise=function(e){return!0===(t=n.run(e)).ok?Promise.resolve(t.result):Promise.reject(t.error);var t},this.runWithException=function(e){return function(e){if(!0===e.ok)return e.result;throw e.error}(n.run(e))},this.map=function(t){return new e((function(e){return function(e,t){return!0===t.ok?w(e(t.result)):t}(t,n.decode(e))}))},this.andThen=function(t){return new e((function(e){return function(e,t){return!0===t.ok?e(t.result):t}((function(n){return t(n).decode(e)}),n.decode(e))}))},this.where=function(t,i){return n.andThen((function(n){return t(n)?e.succeed(n):e.fail(i)}))}}return e.string=function(){return new e((function(e){return"string"==typeof e?w(e):b({message:x("a string",e)})}))},e.number=function(){return new e((function(e){return"number"==typeof e?w(e):b({message:x("a number",e)})}))},e.boolean=function(){return new e((function(e){return"boolean"==typeof e?w(e):b({message:x("a boolean",e)})}))},e.constant=function(t){return new e((function(e){return I(e,t)?w(t):b({message:"expected "+JSON.stringify(t)+", got "+JSON.stringify(e)})}))},e.object=function(t){return new e((function(e){if(_(e)&&t){var n={};for(var i in t)if(t.hasOwnProperty(i)){var s=t[i].decode(e[i]);if(!0!==s.ok)return void 0===e[i]?b({message:"the key '"+i+"' is required but was not present"}):b(T("."+i,s.error));void 0!==s.result&&(n[i]=s.result)}return w(n)}return _(e)?w(e):b({message:x("an object",e)})}))},e.array=function(t){return new e((function(e){if(S(e)&&t){return e.reduce((function(e,n,i){return y((function(e,t){return e.concat([t])}),e,function(e,n){return v((function(e){return T("["+n+"]",e)}),t.decode(e))}(n,i))}),w([]))}return S(e)?w(e):b({message:x("an array",e)})}))},e.tuple=function(t){return new e((function(e){if(S(e)){if(e.length!==t.length)return b({message:"expected a tuple of length "+t.length+", got one of length "+e.length});for(var n=[],i=0;i<t.length;i++){var s=t[i].decode(e[i]);if(!s.ok)return b(T("["+i+"]",s.error));n[i]=s.result}return w(n)}return b({message:x("a tuple of length "+t.length,e)})}))},e.union=function(t,n){for(var i=[],s=2;s<arguments.length;s++)i[s-2]=arguments[s];return e.oneOf.apply(e,[t,n].concat(i))},e.intersection=function(t,n){for(var i=[],s=2;s<arguments.length;s++)i[s-2]=arguments[s];return new e((function(e){return[t,n].concat(i).reduce((function(t,n){return y(Object.assign,t,n.decode(e))}),w({}))}))},e.anyJson=function(){return new e((function(e){return w(e)}))},e.unknownJson=function(){return new e((function(e){return w(e)}))},e.dict=function(t){return new e((function(e){if(_(e)){var n={};for(var i in e)if(e.hasOwnProperty(i)){var s=t.decode(e[i]);if(!0!==s.ok)return b(T("."+i,s.error));n[i]=s.result}return w(n)}return b({message:x("an object",e)})}))},e.optional=function(t){return new e((function(e){return null==e?w(void 0):t.decode(e)}))},e.oneOf=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return new e((function(e){for(var n=[],i=0;i<t.length;i++){var s=t[i].decode(e);if(!0===s.ok)return s;n[i]=s.error}var r=n.map((function(e){return"at error"+(e.at||"")+": "+e.message})).join('", "');return b({message:'expected a value matching one of the decoders, got the errors ["'+r+'"]'})}))},e.withDefault=function(t,n){return new e((function(e){return w(function(e,t){return!0===t.ok?t.result:e}(t,n.decode(e)))}))},e.valueAt=function(t,n){return new e((function(e){for(var i=e,s=0;s<t.length;s++){if(void 0===i)return b({at:k(t.slice(0,s+1)),message:"path does not exist"});if("string"==typeof t[s]&&!_(i))return b({at:k(t.slice(0,s+1)),message:x("an object",i)});if("number"==typeof t[s]&&!S(i))return b({at:k(t.slice(0,s+1)),message:x("an array",i)});i=i[t[s]]}return v((function(e){return void 0===i?{at:k(t),message:"path does not exist"}:T(k(t),e)}),n.decode(i))}))},e.succeed=function(t){return new e((function(e){return w(t)}))},e.fail=function(t){return new e((function(e){return b({message:t})}))},e.lazy=function(t){return new e((function(e){return t().decode(e)}))},e}(),A=R.string,P=R.number,M=R.boolean,O=R.anyJson;R.unknownJson;var E=R.constant,D=R.object,j=R.array;R.tuple,R.dict;var N=R.optional,$=R.oneOf;R.union,R.intersection,R.withDefault,R.valueAt,R.succeed,R.fail;var W=R.lazy;const F=["name","title","version","customProperties","icon","caption","type"],L=["appId","name","type","details","version","title","tooltip","lang","description","categories","icons","screenshots","contactEmail","moreInfo","publisher","customConfig","hostManifests","interop","localizedVersions"];var q=function(e){return{ok:!0,result:e}},G=function(e){return{ok:!1,error:e}},B=function(e,t,n){return!1===t.ok?t:!1===n.ok?n:q(e(t.result,n.result))},U=function(e,t){return!0===t.ok?t:G(e(t.error))},H=function(){return H=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++)for(var s in t=arguments[n])Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s]);return e},H.apply(this,arguments)};function J(e,t){if(e===t)return!0;if(null===e&&null===t)return!0;if(typeof e!=typeof t)return!1;if("object"==typeof e){if(Array.isArray(e)){if(!Array.isArray(t))return!1;if(e.length!==t.length)return!1;for(var n=0;n<e.length;n++)if(!J(e[n],t[n]))return!1;return!0}var i=Object.keys(e);if(i.length!==Object.keys(t).length)return!1;for(n=0;n<i.length;n++){if(!t.hasOwnProperty(i[n]))return!1;if(!J(e[i[n]],t[i[n]]))return!1}return!0}}var K=function(e){return Array.isArray(e)},z=function(e){return"object"==typeof e&&null!==e&&!K(e)},V=function(e,t){return"expected "+e+", got "+function(e){switch(typeof e){case"string":return"a string";case"number":return"a number";case"boolean":return"a boolean";case"undefined":return"undefined";case"object":return e instanceof Array?"an array":null===e?"null":"an object";default:return JSON.stringify(e)}}(t)},Q=function(e){return e.map((function(e){return"string"==typeof e?"."+e:"["+e+"]"})).join("")},X=function(e,t){var n=t.at,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(i=Object.getOwnPropertySymbols(e);s<i.length;s++)t.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(e,i[s])&&(n[i[s]]=e[i[s]])}return n}(t,["at"]);return H({at:e+(n||"")},i)},Y=function(){function e(t){var n=this;this.decode=t,this.run=function(e){return U((function(t){return{kind:"DecoderError",input:e,at:"input"+(t.at||""),message:t.message||""}}),n.decode(e))},this.runPromise=function(e){return!0===(t=n.run(e)).ok?Promise.resolve(t.result):Promise.reject(t.error);var t},this.runWithException=function(e){return function(e){if(!0===e.ok)return e.result;throw e.error}(n.run(e))},this.map=function(t){return new e((function(e){return function(e,t){return!0===t.ok?q(e(t.result)):t}(t,n.decode(e))}))},this.andThen=function(t){return new e((function(e){return function(e,t){return!0===t.ok?e(t.result):t}((function(n){return t(n).decode(e)}),n.decode(e))}))},this.where=function(t,i){return n.andThen((function(n){return t(n)?e.succeed(n):e.fail(i)}))}}return e.string=function(){return new e((function(e){return"string"==typeof e?q(e):G({message:V("a string",e)})}))},e.number=function(){return new e((function(e){return"number"==typeof e?q(e):G({message:V("a number",e)})}))},e.boolean=function(){return new e((function(e){return"boolean"==typeof e?q(e):G({message:V("a boolean",e)})}))},e.constant=function(t){return new e((function(e){return J(e,t)?q(t):G({message:"expected "+JSON.stringify(t)+", got "+JSON.stringify(e)})}))},e.object=function(t){return new e((function(e){if(z(e)&&t){var n={};for(var i in t)if(t.hasOwnProperty(i)){var s=t[i].decode(e[i]);if(!0!==s.ok)return void 0===e[i]?G({message:"the key '"+i+"' is required but was not present"}):G(X("."+i,s.error));void 0!==s.result&&(n[i]=s.result)}return q(n)}return z(e)?q(e):G({message:V("an object",e)})}))},e.array=function(t){return new e((function(e){if(K(e)&&t){return e.reduce((function(e,n,i){return B((function(e,t){return e.concat([t])}),e,function(e,n){return U((function(e){return X("["+n+"]",e)}),t.decode(e))}(n,i))}),q([]))}return K(e)?q(e):G({message:V("an array",e)})}))},e.tuple=function(t){return new e((function(e){if(K(e)){if(e.length!==t.length)return G({message:"expected a tuple of length "+t.length+", got one of length "+e.length});for(var n=[],i=0;i<t.length;i++){var s=t[i].decode(e[i]);if(!s.ok)return G(X("["+i+"]",s.error));n[i]=s.result}return q(n)}return G({message:V("a tuple of length "+t.length,e)})}))},e.union=function(t,n){for(var i=[],s=2;s<arguments.length;s++)i[s-2]=arguments[s];return e.oneOf.apply(e,[t,n].concat(i))},e.intersection=function(t,n){for(var i=[],s=2;s<arguments.length;s++)i[s-2]=arguments[s];return new e((function(e){return[t,n].concat(i).reduce((function(t,n){return B(Object.assign,t,n.decode(e))}),q({}))}))},e.anyJson=function(){return new e((function(e){return q(e)}))},e.unknownJson=function(){return new e((function(e){return q(e)}))},e.dict=function(t){return new e((function(e){if(z(e)){var n={};for(var i in e)if(e.hasOwnProperty(i)){var s=t.decode(e[i]);if(!0!==s.ok)return G(X("."+i,s.error));n[i]=s.result}return q(n)}return G({message:V("an object",e)})}))},e.optional=function(t){return new e((function(e){return null==e?q(void 0):t.decode(e)}))},e.oneOf=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return new e((function(e){for(var n=[],i=0;i<t.length;i++){var s=t[i].decode(e);if(!0===s.ok)return s;n[i]=s.error}var r=n.map((function(e){return"at error"+(e.at||"")+": "+e.message})).join('", "');return G({message:'expected a value matching one of the decoders, got the errors ["'+r+'"]'})}))},e.withDefault=function(t,n){return new e((function(e){return q(function(e,t){return!0===t.ok?t.result:e}(t,n.decode(e)))}))},e.valueAt=function(t,n){return new e((function(e){for(var i=e,s=0;s<t.length;s++){if(void 0===i)return G({at:Q(t.slice(0,s+1)),message:"path does not exist"});if("string"==typeof t[s]&&!z(i))return G({at:Q(t.slice(0,s+1)),message:V("an object",i)});if("number"==typeof t[s]&&!K(i))return G({at:Q(t.slice(0,s+1)),message:V("an array",i)});i=i[t[s]]}return U((function(e){return void 0===i?{at:Q(t),message:"path does not exist"}:X(Q(t),e)}),n.decode(i))}))},e.succeed=function(t){return new e((function(e){return q(t)}))},e.fail=function(t){return new e((function(e){return G({message:t})}))},e.lazy=function(t){return new e((function(e){return t().decode(e)}))},e}(),Z=Y.string,ee=Y.number,te=Y.boolean,ne=Y.anyJson;Y.unknownJson;var ie=Y.constant,se=Y.object,re=Y.array;Y.tuple;var oe=Y.dict,ae=Y.optional,ce=Y.oneOf;Y.union,Y.intersection,Y.withDefault,Y.valueAt,Y.succeed,Y.fail,Y.lazy;const de=Z().where((e=>e.length>0),"Expected a non-empty string"),le=ee().where((e=>e>=0),"Expected a non-negative number"),he=se({name:de,displayName:ae(Z()),contexts:ae(re(Z())),customConfig:ae(se())}),ue=ce(ie("web"),ie("native"),ie("citrix"),ie("onlineNative"),ie("other")),pe=se({url:de}),ge=se({src:de,size:ae(de),type:ae(de)}),me=se({src:de,size:ae(de),type:ae(de),label:ae(de)}),fe=se({contexts:re(de),displayName:ae(de),resultType:ae(de),customConfig:ae(ne())}),we=se({listensFor:ae(oe(fe)),raises:ae(oe(re(de)))}),be=se({broadcasts:ae(re(de)),listensFor:ae(re(de))}),ye=se({name:de,description:ae(de),broadcasts:ae(re(de)),listensFor:ae(re(de))}),ve=se({intents:ae(we),userChannels:ae(be),appChannels:ae(re(ye))}),Ce=se({url:ae(de),top:ae(ee()),left:ae(ee()),width:ae(le),height:ae(le)}),Ie=se({name:ae(de),type:ae(de.where((e=>"window"===e),"Expected a value of window")),title:ae(de),version:ae(de),customProperties:ae(ne()),icon:ae(Z()),caption:ae(Z()),details:ae(Ce),intents:ae(re(he)),hidden:ae(te())}),Se=se({name:de,appId:de,title:ae(de),version:ae(de),manifest:de,manifestType:de,tooltip:ae(de),description:ae(de),contactEmail:ae(de),supportEmail:ae(de),publisher:ae(de),images:ae(re(se({url:ae(de)}))),icons:ae(re(se({icon:ae(de)}))),customConfig:ne(),intents:ae(re(he))}),_e=se({appId:ae(de),name:ae(de),details:ae(pe),version:ae(de),title:ae(de),tooltip:ae(de),lang:ae(de),description:ae(de),categories:ae(re(de)),icons:ae(re(ge)),screenshots:ae(re(me)),contactEmail:ae(de),supportEmail:ae(de),moreInfo:ae(de),publisher:ae(de),customConfig:ae(re(ne())),hostManifests:ae(ne()),interop:ae(ve)}),xe=se({appId:de,name:de,type:ue,details:pe,version:ae(de),title:ae(de),tooltip:ae(de),lang:ae(de),description:ae(de),categories:ae(re(de)),icons:ae(re(ge)),screenshots:ae(re(me)),contactEmail:ae(de),supportEmail:ae(de),moreInfo:ae(de),publisher:ae(de),customConfig:ae(re(ne())),hostManifests:ae(ne()),interop:ae(ve),localizedVersions:ae(oe(_e))}),ke=ce(Se,xe),Te=e=>`${e.kind} at ${e.at}: ${JSON.stringify(e.input)}. Reason - ${e.message}`;class Re{fdc3ToDesktopDefinitionType={web:"window",native:"exe",citrix:"citrix",onlineNative:"clickonce",other:"window"};toApi(){return{isFdc3Definition:this.isFdc3Definition.bind(this),parseToBrowserBaseAppData:this.parseToBrowserBaseAppData.bind(this),parseToDesktopAppConfig:this.parseToDesktopAppConfig.bind(this)}}isFdc3Definition(e){const t=ke.run(e);return t.ok?e.appId&&e.details?{isFdc3:!0,version:"2.0"}:e.manifest?{isFdc3:!0,version:"1.2"}:{isFdc3:!1,reason:"The passed definition is not FDC3"}:{isFdc3:!1,reason:Te(t.error)}}parseToBrowserBaseAppData(e){const{isFdc3:t,version:n}=this.isFdc3Definition(e);if(!t)throw new Error("The passed definition is not FDC3");const i=ke.run(e);if(!i.ok)throw new Error(`Invalid FDC3 ${n} definition. Error: ${Te(i.error)}`);const s=this.getUserPropertiesFromDefinition(e,n),r={url:this.getUrl(e,n)},o={name:e.appId,type:"window",createOptions:r,userProperties:{...s,intents:"1.2"===n?s.intents:this.getIntentsFromV2AppDefinition(e),details:r},title:e.title,version:e.version,icon:this.getIconFromDefinition(e,n),caption:e.description,fdc3:"2.0"===n?{...e,definitionVersion:"2.0"}:void 0},a=e.hostManifests?.ioConnect||e.hostManifests?.Glue42;if(!a)return o;const c=Ie.run(a);if(!c.ok)throw new Error(`Invalid FDC3 ${n} definition. Error: ${Te(c.error)}`);return Object.keys(c.result).length?this.mergeBaseAppDataWithGlueManifest(o,c.result):o}parseToDesktopAppConfig(e){const{isFdc3:t,version:n}=this.isFdc3Definition(e);if(!t)throw new Error("The passed definition is not FDC3");const i=ke.run(e);if(!i.ok)throw new Error(`Invalid FDC3 ${n} definition. Error: ${Te(i.error)}`);if("1.2"===n){const t=e;return{name:t.appId,type:"window",details:{url:this.getUrl(e,n)},version:t.version,title:t.title,tooltip:t.tooltip,caption:t.description,icon:t.icons?.[0].icon,intents:t.intents,customProperties:{manifestType:t.manifestType,images:t.images,contactEmail:t.contactEmail,supportEmail:t.supportEmail,publisher:t.publisher,icons:t.icons,customConfig:t.customConfig}}}const s=e,r={name:s.appId,type:this.fdc3ToDesktopDefinitionType[s.type],details:s.details,version:s.version,title:s.title,tooltip:s.tooltip,caption:s.description,icon:this.getIconFromDefinition(s,"2.0"),intents:this.getIntentsFromV2AppDefinition(s),fdc3:{...s,definitionVersion:"2.0"}},o=e.hostManifests?.ioConnect||e.hostManifests?.Glue42;if(!o)return r;if("object"!=typeof o||Array.isArray(o))throw new Error(`Invalid '${e.hostManifests.ioConnect?"hostManifests.ioConnect":"hostManifests['Glue42']"}' key`);return this.mergeDesktopConfigWithGlueManifest(r,o)}getUserPropertiesFromDefinition(e,t){return"1.2"===t?Object.fromEntries(Object.entries(e).filter((([e])=>!F.includes(e)))):Object.fromEntries(Object.entries(e).filter((([e])=>!F.includes(e)&&!L.includes(e))))}getUrl(e,t){let n;if("1.2"===t){const t=JSON.parse(e.manifest);n=t.details?.url||t.url}else n=e.details?.url;if(!n||"string"!=typeof n)throw new Error(`Invalid FDC3 ${t} definition. Provide valid 'url' under '${"1.2"===t?"manifest":"details"}' key`);return n}getIntentsFromV2AppDefinition(e){const t=e.interop?.intents?.listensFor;if(!t)return;return Object.entries(t).map((e=>{const[t,n]=e;return{name:t,...n}}))}getIconFromDefinition(e,t){return"1.2"===t?e.icons?.find((e=>e.icon))?.icon||void 0:e.icons?.find((e=>e.src))?.src||void 0}mergeBaseAppDataWithGlueManifest(e,t){let n=e;if(t.details){const i={...e.createOptions,...t.details};n.createOptions=i,n.userProperties.details=i}return Array.isArray(t.intents)&&(n.userProperties.intents=(n.userProperties.intents||[]).concat(t.intents)),n={...n,...t},delete n.details,delete n.intents,n}mergeDesktopConfigWithGlueManifest(e,t){const n=Object.assign({},e,t,{details:{...e.details,...t.details}});return Array.isArray(t.intents)&&(n.intents=(e.intents||[]).concat(t.intents)),n}}const Ae={common:{nonEmptyStringDecoder:de,nonNegativeNumberDecoder:le},fdc3:{allDefinitionsDecoder:ke,v1DefinitionDecoder:Se,v2DefinitionDecoder:xe}};var Pe;!function(e){e.USER_CANCELLED="User Closed Intents Resolver UI without choosing a handler",e.CALLER_NOT_DEFINED="Caller Id is not defined",e.TIMEOUT_HIT="Timeout hit",e.INTENT_NOT_FOUND="Cannot find Intent",e.HANDLER_NOT_FOUND="Cannot find Intent Handler",e.TARGET_INSTANCE_UNAVAILABLE="Cannot start Target Instance",e.INTENT_DELIVERY_FAILED="Target Instance did not add a listener",e.RESOLVER_UNAVAILABLE="Intents Resolver UI unavailable",e.RESOLVER_TIMEOUT="User did not choose a handler",e.INVALID_RESOLVER_RESPONSE="Intents Resolver UI returned invalid response",e.INTENT_HANDLER_REJECTION="Intent Handler function processing the raised intent threw an error or rejected the promise it returned"}(Pe||(Pe={}));const Me=new class{_fdc3;_decoders=Ae;_errors={intents:Pe};get fdc3(){return this._fdc3||(this._fdc3=(new Re).toApi()),this._fdc3}get decoders(){return this._decoders}get errors(){return this._errors}};Me.fdc3;const Oe=Me.decoders;Me.errors;const Ee=A().where((e=>e.length>0),"Expected a non-empty string"),De=P().where((e=>e>=0),"Expected a non-negative number"),je=N(Ee),Ne=$(E("system"),E("windows"),E("appManager"),E("layouts"),E("intents"),E("notifications"),E("channels"),E("extension"),E("themes"),E("prefs"),E("ui")),$e=$(E("openWindow"),E("windowHello"),E("windowAdded"),E("windowRemoved"),E("getBounds"),E("getFrameBounds"),E("getUrl"),E("moveResize"),E("focus"),E("close"),E("getTitle"),E("setTitle"),E("focusChange"),E("getChannel"),E("notifyChannelsChanged")),We=$(E("appHello"),E("appDirectoryStateChange"),E("instanceStarted"),E("instanceStopped"),E("applicationStart"),E("instanceStop"),E("clear")),Fe=$(E("layoutAdded"),E("layoutChanged"),E("layoutRemoved"),E("layoutRenamed"),E("get"),E("getAll"),E("export"),E("import"),E("remove"),E("rename"),E("clientSaveRequest"),E("getGlobalPermissionState"),E("checkGlobalActivated"),E("requestGlobalPermission"),E("getDefaultGlobal"),E("setDefaultGlobal"),E("clearDefaultGlobal"),E("updateMetadata")),Le=$(E("raiseNotification"),E("requestPermission"),E("notificationShow"),E("notificationClick"),E("getPermission"),E("list"),E("notificationRaised"),E("notificationClosed"),E("click"),E("clear"),E("clearAll"),E("configure"),E("getConfiguration"),E("configurationChanged"),E("setState"),E("clearOld"),E("activeCountChange"),E("stateChange")),qe=$(E("getEnvironment"),E("getBase"),E("platformShutdown"),E("isFdc3DataWrappingSupported"),E("clientError"),E("systemHello")),Ge=$(E("top"),E("left"),E("right"),E("bottom")),Be=D({top:P(),left:P(),width:De,height:De}),Ue=N(D({top:N(P()),left:N(P()),width:N(De),height:N(De),context:N(O()),relativeTo:N(Ee),relativeDirection:N(Ge),windowId:N(Ee),layoutComponentId:N(Ee)})),He=D({name:Ee,url:Ee,options:Ue}),Je=D({windowId:N(Ee)}),Ke=D({windowId:Ee,name:Ee}),ze=D({windowId:Ee}),Ve=D({windows:j(Ke),isWorkspaceFrame:M()}),Qe=D({windowId:Ee,title:A()}),Xe=D({windowId:Ee,hasFocus:M()}),Ye=D({windowId:Ee,top:N(P()),left:N(P()),width:N(De),height:N(De),relative:N(M())}),Ze=D({windowId:Ee,bounds:D({top:P(),left:P(),width:De,height:De})}),et=D({bounds:D({top:P(),left:P(),width:De,height:De})}),tt=D({windowId:Ee,url:Ee}),nt=O(),it=D({top:N(P()),left:N(P()),width:N(De),height:N(De)}),st=D({id:Ee,applicationName:Ee}),rt=D({flags:A()}),ot=D({flags:A()}),at=D({windowId:Ee,channelsNames:j(Ee)}),ct=D({enabled:M()}),dt=D({url:Ee,top:N(P()),left:N(P()),width:N(De),height:N(De),workspacesSandbox:N(ot),channelSelector:N(ct),iframePermissionsPolicy:N(rt)}),lt=D({name:Ee,displayName:N(A()),contexts:N(j(A())),customConfig:N(D())});D({name:Ee,title:N(Ee),version:N(Ee),appId:N(Ee),manifest:Ee,manifestType:Ee,tooltip:N(Ee),description:N(Ee),contactEmail:N(Ee),supportEmail:N(Ee),publisher:N(Ee),images:N(j(D({url:N(Ee)}))),icons:N(j(D({icon:N(Ee)}))),customConfig:O(),intents:N(j(lt))});const ht=D({name:Ee,type:Ee.where((e=>"window"===e),"Expected a value of window"),title:N(Ee),version:N(Ee),customProperties:N(O()),icon:N(A()),caption:N(A()),details:dt,intents:N(j(lt)),hidden:N(M()),fdc3:N(Oe.fdc3.v2DefinitionDecoder)}),ut=$(ht,Oe.fdc3.v2DefinitionDecoder,Oe.fdc3.v1DefinitionDecoder);D({definitions:j(ut),mode:$(E("replace"),E("merge"))});const pt=D({name:Ee}),gt=D({definitions:j(ht)}),mt=D({name:Ee,type:Ee.where((e=>"window"===e),"Expected a value of window"),instances:j(st),userProperties:N(O()),title:N(Ee),version:N(Ee),icon:N(Ee),caption:N(Ee)}),ft=D({name:Ee,type:Ee.where((e=>"window"===e),"Expected a value of window"),userProperties:O(),title:N(Ee),version:N(Ee),icon:N(Ee),caption:N(Ee)}),wt=D({appsAdded:j(ft),appsChanged:j(ft),appsRemoved:j(ft)}),bt=D({apps:j(mt),initialChannelId:N(Ee)}),yt=D({id:Ee}),vt=D({name:Ee,waitForAGMReady:M(),id:N(Ee),context:N(O()),top:N(P()),left:N(P()),width:N(De),height:N(De),relativeTo:N(Ee),relativeDirection:N(Ge),forceChromeTab:N(M()),layoutComponentId:N(Ee),channelId:N(Ee)}),Ct=$(E("Global"),E("Activity"),E("ApplicationDefault"),E("Swimlane"),E("Workspace")),It=$(E("application"),E("activity")),St=D({context:N(O()),bounds:Be,createArgs:D({name:N(Ee),url:N(Ee),context:N(O())}),windowState:N(Ee),restoreState:N(Ee),instanceId:Ee,isCollapsed:N(M()),isSticky:N(M()),restoreSettings:D({groupId:N(Ee),groupZOrder:N(P())})}),_t=D({type:E("window"),componentType:N(It),application:Ee,state:St}),xt=D({type:E("window"),config:D({appName:Ee,url:N(Ee),title:N(A()),allowExtract:N(M()),allowReorder:N(M()),showCloseButton:N(M()),isMaximized:N(M())})}),kt=D({type:E("group"),config:O(),children:j($(xt))}),Tt=D({type:E("column"),config:O(),children:j($(kt,xt,W((()=>Tt)),W((()=>Rt))))}),Rt=D({type:E("row"),config:O(),children:j($(Tt,kt,xt,W((()=>Rt))))}),At=D({config:O(),context:O(),children:j($(Rt,Tt,kt,xt))}),Pt=D({type:E("Workspace"),application:N(Ee),state:At}),Mt=D({bounds:Be,instanceId:Ee,selectedWorkspace:De,workspaces:j(At),windowState:N(Ee),restoreState:N(Ee),context:N(O())}),Ot=D({type:E("workspaceFrame"),application:Ee,componentType:N(It),state:Mt}),Et=D({name:Ee,type:Ct,components:j($(_t,Pt,Ot)),context:N(O()),metadata:N(O()),version:N(P())}),Dt=D({name:Ee,context:N(O()),metadata:N(O()),instances:N(j(Ee)),ignoreInstances:N(j(Ee))}),jt=D({name:Ee,context:N(O()),closeRunningInstance:N(M()),closeMe:N(M()),timeout:N(De)}),Nt=D({name:Ee,type:Ct,context:N(O()),metadata:N(O())}),$t=D({name:Ee,type:Ct}),Wt=D({layout:Dt}),Ft=D({layout:Et,newName:Ee}),Lt=D({status:Ee}),qt=D({layout:Et}),Gt=D({layout:jt}),Bt=D({type:Ct}),Ut=D({layouts:j(Et)}),Ht=$(E("replace"),E("merge")),Jt=D({layouts:j(Et),mode:Ht,skipManagerRequest:N(M())}),Kt=D({summaries:j(Nt)}),zt=D({layout:Et}),Vt=D({layout:N(Et)}),Qt=D({name:Ee}),Xt=$(E("findIntent"),E("getIntents"),E("raiseIntent"),E("raise"),E("filterHandlers")),Yt=D({applicationName:Ee,applicationTitle:N(A()),applicationDescription:N(A()),applicationIcon:N(A()),type:$(E("app"),E("instance")),displayName:N(A()),contextTypes:N(j(Ee)),instanceId:N(A()),instanceTitle:N(A()),resultType:N(A())});D({applicationName:A(),applicationIcon:N(A()),instanceId:N(A())});const Zt=D({intent:Ee,handler:Yt}),en=D({name:Ee,handlers:j(Yt)}),tn=$(E("startNew"),E("reuse"),D({app:N(Ee),instance:N(Ee)})),nn=D({type:N(Ee),data:N(O())}),sn=j(en),rn=D({intents:sn}),on=D({name:N(Ee),contextType:N(Ee),resultType:N(Ee)}),an=$(Ee,on),cn=D({filter:N(on)}),dn=D({intent:Ee,target:N(tn),context:N(nn),options:N(Ue),handlers:N(j(Yt)),timeout:N(De),waitUserResponseIndefinitely:N(M()),clearSavedHandler:N(M())}),ln=$(Ee,dn),hn=D({enabled:M(),appName:Ee,waitResponseTimeout:P()}),un=D({intentRequest:dn,resolverConfig:hn}),pn=D({request:dn,handler:Yt,result:O()}),gn=D({title:N(Ee),openResolver:N(M()),timeout:N(De),intent:N(Ee),contextTypes:N(j(Ee)),resultType:N(Ee),applicationNames:N(j(Ee))}),mn=D({handlers:j(Yt)}),fn=D({filterHandlersRequest:gn,resolverConfig:hn}),wn=D({intent:Ee,contextTypes:N(j(Ee)),displayName:N(A()),icon:N(A()),description:N(A()),resultType:N(A())}),bn=$(Ee,wn),yn=D({intent:Ee,contextTypes:N(j(Ee)),description:N(Ee),displayName:N(Ee),icon:N(Ee),resultType:N(Ee)}),vn=D({intents:j(yn)}),Cn=e=>Ee.where((t=>e.includes(t)),"Expected a valid channel name"),In=D({contextType:N(Ee)}),Sn=N($(Ee,D({name:N(Ee),fdc3:N(M())}))),_n=D({windowId:je,channel:je}),xn=O().where((e=>"string"==typeof e.type),"Expected a valid FDC3 Context with compulsory 'type' field"),kn=D({method:Ee,arguments:N(O()),target:N($(E("all"),E("best")))}),Tn=D({action:A(),title:Ee,icon:N(A()),interop:N(kn)}),Rn=$(E("Active"),E("Acknowledged"),E("Seen"),E("Closed"),E("Stale"),E("Snoozed"),E("Processing")),An=D({count:P()}),Pn=D({badge:N(A()),body:N(A()),data:N(O()),dir:N($(E("auto"),E("ltr"),E("rtl"))),icon:N(A()),image:N(A()),lang:N(A()),renotify:N(M()),requireInteraction:N(M()),silent:N(M()),tag:N(A()),timestamp:N(De),vibrate:N(j(P()))}),Mn=D({title:Ee,clickInterop:N(kn),actions:N(j(Tn)),focusPlatformOnDefaultClick:N(M()),badge:N(A()),body:N(A()),data:N(O()),dir:N($(E("auto"),E("ltr"),E("rtl"))),icon:N(A()),image:N(A()),lang:N(A()),renotify:N(M()),requireInteraction:N(M()),silent:N(M()),tag:N(A()),timestamp:N(De),vibrate:N(j(P())),severity:N($(E("Low"),E("None"),E("Medium"),E("High"),E("Critical"))),showToast:N(M()),showInPanel:N(M()),state:N(Rn)}),On=D({id:Ee,state:Rn});D().where((e=>!e.fdc3||"string"==typeof e.fdc3.type),"Expected a valid FDC3 Context with compulsory 'type' field");const En=D({color:N(Ee),icon:N(Ee),name:N(Ee),glyph:N(Ee)}),Dn=D({id:Ee,displayMetadata:N(En)}),jn=D({color:Ee,fdc3:N(Dn)}),Nn=D({name:Ee,meta:jn,data:N(D())}),$n=D({name:Ee}),Wn=D({name:Ee,read:M(),write:M(),windowId:N(Ee)}),Fn=D({name:Ee,read:M(),write:M(),windowId:Ee}),Ln=D({config:Fn}),qn=D({channels:j(Wn)}),Gn=D({windowId:Ee}),Bn=D({read:M(),write:M(),windowId:N(Ee)}),Un=D({restrictions:Bn}),Hn=D({settings:Mn,id:Ee}),Jn=D({settings:Mn}),Kn=D({permissionGranted:M()}),zn=D({permission:$(E("default"),E("granted"),E("denied"))}),Vn=D({definition:Pn,action:N(A()),id:N(Ee)}),Qn=D({allowed:N(j(Ee)),blocked:N(j(Ee))}),Xn=D({enable:N(M()),enableToasts:N(M()),sourceFilter:N(Qn)}),Yn=D({configuration:Xn}),Zn=D({configuration:D({enable:M(),enableToasts:M(),sourceFilter:D({allowed:j(Ee),blocked:j(Ee)})})}),ei=D({layoutType:$(E("Global"),E("Workspace")),layoutName:Ee,context:N(O())}),ti=D({windowContext:N(O())}),ni=D({state:$(E("prompt"),E("denied"),E("granted"))}),ii=D({isAvailable:M()}),si=D({itemId:Ee}),ri=D({isSupported:M()}),oi=D({operation:Ee}),ai=D({bounds:Be}),ci=D({displayName:Ee,name:Ee}),di=D({theme:ci}),li=D({themes:j(ci)}),hi=D({name:Ee}),ui=D({id:Ee,title:Ee,clickInterop:N(kn),actions:N(j(Tn)),focusPlatformOnDefaultClick:N(M()),badge:N(A()),body:N(A()),data:N(O()),dir:N($(E("auto"),E("ltr"),E("rtl"))),icon:N(A()),image:N(A()),lang:N(A()),renotify:N(M()),requireInteraction:N(M()),silent:N(M()),tag:N(A()),timestamp:N(De),vibrate:N(j(P())),severity:N($(E("Low"),E("None"),E("Medium"),E("High"),E("Critical"))),showToast:N(M()),showInPanel:N(M()),state:N(Rn)}),pi=D({notification:ui}),gi=D({notifications:j(ui)}),mi=D({id:Ee}),fi=D({channel:Ee}),wi=D({windowIds:j(Ee)}),bi=$(E("addChannel"),E("getMyChannel"),E("getWindowIdsOnChannel"),E("getWindowIdsWithChannels"),E("joinChannel"),E("restrict"),E("getRestrictions"),E("restrictAll"),E("notifyChannelsChanged"),E("leaveChannel"),E("getMode")),yi=D({mode:$(E("single"),E("multi"))}),vi=D({channel:N(Ee)}),Ci=D({application:N(Ee),channels:N(j(Ee)),windowIds:N(j(Ee))}),Ii=D({filter:N(Ci)}),Si=D({windowIdsWithChannels:j(D({application:Ee,channel:N(Ee),windowId:Ee}))}),_i=N(O()),xi=N(D({top:N(P()),left:N(P()),width:N(De),height:N(De),relativeTo:N(Ee),relativeDirection:N(Ge),waitForAGMReady:N(M()),channelId:N(Ee),reuseId:N(Ee)})),ki=D({channel:Ee,windowId:Ee}),Ti=D({windowId:Ee,channelName:N(Ee)}),Ri=D({windowId:Ee,channelNames:j(Ee)}),Ai=D({channel:N(Ee)}),Pi=$(E("clear"),E("clearAll"),E("get"),E("getAll"),E("set"),E("update"),E("prefsChanged"),E("prefsHello")),Mi=D({app:Ee,data:D(),lastUpdate:N(Ee)}),Oi=D({app:Ee}),Ei=D({prefs:Mi}),Di=D({all:j(Mi)}),ji=D({app:Ee,data:D()}),Ni=D({platform:D({app:Ee}),validNonExistentApps:N(j(Ee))}),$i=D({message:Ee}),Wi=D({isClientErrorOperationSupported:M()}),Fi={openWindow:{name:"openWindow",dataDecoder:He,resultDecoder:Ke},windowHello:{name:"windowHello",dataDecoder:Je,resultDecoder:Ve},windowAdded:{name:"windowAdded",dataDecoder:Ke},windowRemoved:{name:"windowRemoved",dataDecoder:ze},getBounds:{name:"getBounds",dataDecoder:ze,resultDecoder:Ze},getFrameBounds:{name:"getFrameBounds",dataDecoder:ze,resultDecoder:et},getUrl:{name:"getUrl",dataDecoder:ze,resultDecoder:tt},moveResize:{name:"moveResize",dataDecoder:Ye},focus:{name:"focus",dataDecoder:ze},close:{name:"close",dataDecoder:ze},getTitle:{name:"getTitle",dataDecoder:ze,resultDecoder:Qe},setTitle:{name:"setTitle",dataDecoder:Qe},focusChange:{name:"focusChange",dataDecoder:Xe},getChannel:{name:"getChannel",dataDecoder:ze,resultDecoder:Ai},notifyChannelsChanged:{name:"notifyChannelsChanged",dataDecoder:Ri}};function Li(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function qi(e){if(e&&e.errorHandling&&"function"!=typeof e.errorHandling&&"log"!==e.errorHandling&&"silent"!==e.errorHandling&&"throw"!==e.errorHandling)throw new Error('Invalid options passed to createRegistry. Prop errorHandling should be ["log" | "silent" | "throw" | (err) => void], but '+typeof e.errorHandling+" was passed");var t=e&&"function"==typeof e.errorHandling&&e.errorHandling,n={};function i(n,i){var s=n instanceof Error?n:new Error(n);if(t)t(s);else{var r='[ERROR] callback-registry: User callback for key "'+i+'" failed: '+s.stack;if(e)switch(e.errorHandling){case"log":return console.error(r);case"silent":return;case"throw":throw new Error(r)}console.error(r)}}return{add:function(e,t,s){var r=n[e];return r||(r=[],n[e]=r),r.push(t),s&&setTimeout((function(){s.forEach((function(s){var r;if(null===(r=n[e])||void 0===r?void 0:r.includes(t))try{Array.isArray(s)?t.apply(void 0,s):t.apply(void 0,[s])}catch(t){i(t,e)}}))}),0),function(){var i=n[e];i&&(0===(i=i.reduce((function(e,n,i){return n===t&&e.length===i||e.push(n),e}),[])).length?delete n[e]:n[e]=i)}},execute:function(e){for(var t=[],s=1;s<arguments.length;s++)t[s-1]=arguments[s];var r=n[e];if(!r||0===r.length)return[];var o=[];return r.forEach((function(n){try{var s=n.apply(void 0,t);o.push(s)}catch(t){o.push(void 0),i(t,e)}})),o},clear:function(){n={}},clearKey:function(e){n[e]&&delete n[e]}}}qi.default=qi;var Gi=Li(qi);class Bi{_id;_name;_bridge;registry=Gi();myCtxKey;ctxUnsubscribe;me;constructor(e,t,n){this._id=e,this._name=t,this._bridge=n,this.myCtxKey=`___window___${this.id}`}get id(){return this._id.slice()}get name(){return this._name.slice()}clean(){this.ctxUnsubscribe&&this.ctxUnsubscribe()}processSelfFocusEvent(e){this.me.isFocused=e,this.registry.execute("focus-change",this.me)}processChannelsChangedEvent(e){this.registry.execute("channels-changed",e)}async toApi(){return this.ctxUnsubscribe=await this._bridge.contextLib.subscribe(this.myCtxKey,(e=>this.registry.execute("context-updated",e))),this.me={id:this.id,name:this.name,isFocused:!1,getURL:this.getURL.bind(this),moveResize:this.moveResize.bind(this),resizeTo:this.resizeTo.bind(this),moveTo:this.moveTo.bind(this),focus:this.focus.bind(this),close:this.close.bind(this),getTitle:this.getTitle.bind(this),setTitle:this.setTitle.bind(this),getBounds:this.getBounds.bind(this),getContext:this.getContext.bind(this),updateContext:this.updateContext.bind(this),setContext:this.setContext.bind(this),onContextUpdated:this.onContextUpdated.bind(this),onFocusChanged:this.onFocusChanged.bind(this),getChannel:this.getChannel.bind(this),onChannelsChanged:this.onChannelsChanged.bind(this)},this.me}async getURL(){return(await this._bridge.send("windows",Fi.getUrl,{windowId:this.id})).url}onFocusChanged(e){return"function"!=typeof e?f.raiseError("Cannot subscribe to context changes, because the provided callback is not a function!"):this.registry.add("focus-change",e)}async moveResize(e){const t=m(it,e),n=Object.assign({},t,{windowId:this.id,relative:!1});return await this._bridge.send("windows",Fi.moveResize,n),this.me}async resizeTo(e,t){if(void 0===e&&void 0===t)return this.me;void 0!==e&&m(De,e),void 0!==t&&m(De,t);const n=Object.assign({},{width:e,height:t},{windowId:this.id,relative:!0});return await this._bridge.send("windows",Fi.moveResize,n),this.me}async moveTo(e,t){if(void 0===e&&void 0===t)return this.me;void 0!==e&&m(P(),e),void 0!==t&&m(P(),t);const n=Object.assign({},{top:e,left:t},{windowId:this.id,relative:!0});return await this._bridge.send("windows",Fi.moveResize,n),this.me}async focus(){return"Platform"===this.name?window.open(void 0,this.id):await this._bridge.send("windows",Fi.focus,{windowId:this.id}),this.me}async close(){return await this._bridge.send("windows",Fi.close,{windowId:this.id}),this.me}async getTitle(){return(await this._bridge.send("windows",Fi.getTitle,{windowId:this.id})).title}async setTitle(e){const t=m(Ee,e);return await this._bridge.send("windows",Fi.setTitle,{windowId:this.id,title:t}),this.me}async getBounds(){return(await this._bridge.send("windows",Fi.getBounds,{windowId:this.id})).bounds}async getContext(){const e=await this._bridge.contextLib.get(this.myCtxKey),{___io___:t,...n}=e;return n}async updateContext(e){const t=m(nt,e);return await this._bridge.contextLib.update(this.myCtxKey,t),this.me}async setContext(e){const t=m(nt,e),n=await this._bridge.contextLib.get(this.myCtxKey),i=n.___io___?{...t,___io___:n.___io___}:t;return await this._bridge.contextLib.set(this.myCtxKey,i),this.me}onContextUpdated(e){if("function"!=typeof e)return f.raiseError("Cannot subscribe to context changes, because the provided callback is not a function!");return this.registry.add("context-updated",(t=>{const{___io___:n,...i}=t;e(i,this.me)}))}async getChannel(){return(await this._bridge.send("windows",Fi.getChannel,{windowId:this.id},void 0,{includeOperationCheck:!0})).channel}onChannelsChanged(e){return this.registry.add("channels-changed",e)}}const Ui={operationCheck:{name:"operationCheck",dataDecoder:oi,resultDecoder:ri},getWorkspaceWindowFrameBounds:{name:"getWorkspaceWindowFrameBounds",resultDecoder:ai,dataDecoder:si}},Hi=(e,t,n)=>new Promise(((i,s)=>{let r=!0;const o=setTimeout((()=>{if(!r)return;r=!1;s(n||`Promise timeout hit: ${t}`)}),t);e().then((e=>{r&&(r=!1,clearTimeout(o),i(e))})).catch((e=>{r&&(r=!1,clearTimeout(o),s(e))}))})),Ji=(e,t,n)=>new Promise(((i,s)=>{const r=setTimeout((()=>{s(n||`Promise timeout hit: ${t}`)}),t);new Promise(e).then((e=>{clearTimeout(r),i(e)})).catch((e=>{clearTimeout(r),s(e)}))}));class Ki{focusEventHandler;registry=Gi();platformRegistration;ioc;bridge;publicWindowId;allWindowProjections=[];me;logger;isWorkspaceFrame;instanceId;channelsController;async start(e,t){this.logger=e.logger.subLogger("windows.controller.web"),this.logger.trace("starting the web windows controller"),this.publicWindowId=t.publicWindowId,this.addWindowOperationExecutors(),this.ioc=t,this.bridge=t.bridge,this.instanceId=e.interop.instance.instance,this.channelsController=t.channelsController,this.logger.trace(`set the public window id: ${this.publicWindowId}, set the bridge operations and ioc, registering with the platform now`),this.platformRegistration=this.registerWithPlatform(),await this.platformRegistration,await this.initializeFocusTracking(),this.logger.trace("registration with the platform successful, attaching the windows property to glue and returning");const n=this.toApi();e.windows=n}handlePlatformShutdown(){this.registry.clear(),this.allWindowProjections=[],this.focusEventHandler&&(document.removeEventListener("visibilityChange",this.focusEventHandler),window.removeEventListener("focus",this.focusEventHandler),window.removeEventListener("blur",this.focusEventHandler))}async handleBridgeMessage(e){await this.platformRegistration;const t=m($e,e.operation),n=Fi[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=m(n.dataDecoder,e.data)),await n.execute(i)}async open(e,t,n){m(Ee,e),m(Ee,t);const i=m(Ue,n),s=await this.bridge.send("windows",Fi.openWindow,{name:e,url:t,options:i});return this.waitForWindowAdded(s.windowId)}list(){return this.allWindowProjections.map((e=>e.api))}findById(e){return m(Ee,e),this.allWindowProjections.find((t=>t.id===e))?.api}toApi(){return{open:this.open.bind(this),my:this.my.bind(this),list:this.list.bind(this),findById:this.findById.bind(this),onWindowAdded:this.onWindowAdded.bind(this),onWindowRemoved:this.onWindowRemoved.bind(this),onWindowGotFocus:this.onWindowGotFocus.bind(this),onWindowLostFocus:this.onWindowLostFocus.bind(this)}}addWindowOperationExecutors(){Fi.focusChange.execute=this.handleFocusChangeEvent.bind(this),Fi.windowAdded.execute=this.handleWindowAdded.bind(this),Fi.windowRemoved.execute=this.handleWindowRemoved.bind(this),Fi.getBounds.execute=this.handleGetBounds.bind(this),Fi.getFrameBounds.execute=this.handleGetBounds.bind(this),Fi.getTitle.execute=this.handleGetTitle.bind(this),Fi.getUrl.execute=this.handleGetUrl.bind(this),Fi.moveResize.execute=this.handleMoveResize.bind(this),Fi.setTitle.execute=this.handleSetTitle.bind(this),Fi.getChannel.execute=this.handleGetChannel.bind(this),Fi.notifyChannelsChanged.execute=this.handleChannelsChanged.bind(this)}my(){return Object.assign({},this.me)}onWindowAdded(e){return"function"!=typeof e?f.raiseError("Cannot subscribe to window added, because the provided callback is not a function!"):this.registry.add("window-added",e)}onWindowRemoved(e){return"function"!=typeof e?f.raiseError("Cannot subscribe to window removed, because the provided callback is not a function!"):this.registry.add("window-removed",e)}onWindowGotFocus(e){return"function"!=typeof e?f.raiseError("Cannot subscribe to onWindowGotFocus, because the provided callback is not a function!"):this.registry.add("window-got-focus",e)}onWindowLostFocus(e){return"function"!=typeof e?f.raiseError("Cannot subscribe to onWindowLostFocus, because the provided callback is not a function!"):this.registry.add("window-lost-focus",e)}async sayHello(){return await this.bridge.send("windows",Fi.windowHello,{windowId:this.publicWindowId})}async registerWithPlatform(){const{windows:e,isWorkspaceFrame:t}=await this.sayHello();if(this.isWorkspaceFrame=t,this.logger.trace("the platform responded to the hello message"),!this.isWorkspaceFrame&&this.publicWindowId){this.logger.trace("i am not treated as a workspace frame, setting my window");const t=e.find((e=>e.windowId===this.publicWindowId));if(!t)return f.raiseError("Cannot initialize the window library, because I received no information about me from the platform");const n=await this.ioc.buildWebWindow(this.publicWindowId,t.name);this.me=n.api,this.allWindowProjections.push(n)}const n=await Promise.all(e.filter((e=>e.windowId!==this.publicWindowId)).map((e=>this.ioc.buildWebWindow(e.windowId,e.name))));this.logger.trace("all windows projections are completed, building the list collection"),this.allWindowProjections.push(...n)}async handleFocusChangeEvent(e){const t=this.allWindowProjections.find((t=>t.id===e.windowId));if(!t)return;t.model.processSelfFocusEvent(e.hasFocus);const n=e.hasFocus?"window-got-focus":"window-lost-focus";this.registry.execute(n,t.api)}async handleWindowAdded(e){if(this.allWindowProjections.some((t=>t.id===e.windowId)))return;const t=await this.ioc.buildWebWindow(e.windowId,e.name);this.allWindowProjections.push(t),this.registry.execute("window-added",t.api)}async handleWindowRemoved(e){const t=this.allWindowProjections.find((t=>t.id===e.windowId));t&&(this.allWindowProjections=this.allWindowProjections.filter((t=>t.id!==e.windowId)),t.model.clean(),this.registry.execute("window-removed",t.api))}async handleGetBounds(){return this.me||this.isWorkspaceFrame?{windowId:this.isWorkspaceFrame?"noop":this.me.id,bounds:{top:window.screenTop,left:window.screenLeft,width:window.innerWidth,height:window.innerHeight}}:f.raiseError("This window cannot report it's bounds, because it is not a Glue Window, most likely because it is an iframe")}async handleGetTitle(){return this.me?{windowId:this.me.id,title:document.title}:f.raiseError("This window cannot report it's title, because it is not a Glue Window, most likely because it is an iframe")}async handleGetUrl(){return this.me?{windowId:this.me.id,url:window.location.href}:f.raiseError("This window cannot report it's url, because it is not a Glue Window, most likely because it is an iframe")}async handleMoveResize(e){const t="number"==typeof e.top?e.top:e.relative?0:window.screenTop,n="number"==typeof e.left?e.left:e.relative?0:window.screenLeft,i="number"==typeof e.height?e.height:e.relative?0:window.innerHeight,s="number"==typeof e.width?e.width:e.relative?0:window.innerWidth,r=e.relative?window.moveBy:window.moveTo,o=e.relative?window.resizeBy:window.resizeTo;r(n,t),o(s,i)}async handleSetTitle(e){document.title=e.title}async initializeFocusTracking(){if(this.isWorkspaceFrame)return void this.logger.trace("Ignoring the focus tracking, because this client is a workspace frame");try{await this.bridge.send("windows",Ui.operationCheck,{operation:"focusChange"})}catch(e){return void this.logger.warn("The platform of this client is outdated and does not support focus tracking, disabling focus events for this client.")}const e=document.hasFocus();await this.transmitFocusChange(!0),e||await this.transmitFocusChange(!1),this.defineEventListeners()}processFocusEvent(){const e=document.hasFocus();this.transmitFocusChange(e)}waitForWindowAdded(e){const t=this.allWindowProjections.find((t=>t.id===e));return t?Promise.resolve(t.api):Ji((t=>{const n=this.onWindowAdded((i=>{i.id===e&&(n(),t(i))}))}),3e4,`Timed out waiting for ${e} to be announced`)}async transmitFocusChange(e){const t={windowId:this.me?.id||`iframe-${this.instanceId}`,hasFocus:e};this.me&&(this.me.isFocused=e),await this.bridge.send("windows",Fi.focusChange,t)}defineEventListeners(){this.focusEventHandler=this.processFocusEvent.bind(this),document.addEventListener("visibilityChange",this.focusEventHandler),window.addEventListener("focus",this.focusEventHandler),window.addEventListener("blur",this.focusEventHandler)}async handleGetChannel(){if(!this.me)return f.raiseError("This window cannot report it's channel, because it is not a Glue Window, most likely because it is an iframe");const e=this.channelsController.my();return{...e?{channel:e}:{}}}async handleChannelsChanged(e){const t=this.allWindowProjections.find((t=>t.id===e.windowId));t?.model.processChannelsChangedEvent(e.channelNames)}}const zi="T42.Web.Platform.Control",Vi="T42.Web.Platform.Stream",Qi="T42.Web.Client.Control",Xi="T42.Core.Plus.Themes.Stream";class Yi{coreGlue;communicationId;platformMethodTimeoutMs=1e4;controllers;sub;running;constructor(e,t){this.coreGlue=e,this.communicationId=t}get contextLib(){return this.coreGlue.contexts}get interopInstance(){return this.coreGlue.interop.instance.instance}async stop(){this.running=!1,this.sub.close(),await this.coreGlue.interop.unregister(Qi)}async start(e){this.running=!0,this.controllers=e,await Promise.all([this.checkWaitMethod(zi),this.checkWaitMethod(Vi)]);const t=this.communicationId,[n]=await Promise.all([this.coreGlue.interop.subscribe(Vi,t?{target:{instance:this.communicationId}}:void 0),this.coreGlue.interop.registerAsync(Qi,((e,t,n,i)=>this.passMessageController(e,n,i)))]);this.sub=n,this.sub.onData((e=>this.passMessageController(e.data)))}getInteropInstance(e){const t=this.coreGlue.interop.servers().find((t=>t.windowId&&t.windowId===e));return{application:t?.application,applicationName:t?.applicationName,peerId:t?.peerId,instance:t?.instance,windowId:t?.windowId}}async send(e,t,n,i,s){if(t.dataDecoder)try{t.dataDecoder.runWithException(n)}catch(e){return f.raiseError(`Unexpected Web->Platform outgoing validation error: ${e.message}, for operation: ${t.name} and input: ${JSON.stringify(e.input)}`)}if(!(!s?.includeOperationCheck||(await this.checkOperationSupported(e,t)).isSupported))return f.raiseError(`Cannot complete operation: ${t.name} for domain: ${e} because this client is connected to a platform which does not support it`);try{const s=await this.transmitMessage(e,t,n,i);return t.resultDecoder&&t.resultDecoder.runWithException(s),s}catch(e){return e?.kind?f.raiseError(`Unexpected Web<-Platform incoming validation error: ${e.message}, for operation: ${t.name} and input: ${JSON.stringify(e.input)}`):f.raiseError(e)}}async createNotificationsSteam(){return this.coreGlue.interop.methods().some((e=>e.name===Xi))?this.coreGlue.interop.subscribe(Xi,this.communicationId?{target:{instance:this.communicationId}}:void 0):f.raiseError("Cannot subscribe to theme changes, because the underlying interop stream does not exist. Most likely this is the case when this client is not connected to Core Plus.")}async checkOperationSupported(e,t){try{return await this.send(e,Ui.operationCheck,{operation:t.name})}catch(e){return{isSupported:!1}}}checkWaitMethod(e){return Ji((t=>{if(this.coreGlue.interop.methods().some((t=>{const n=t.name===e,i=!this.communicationId||t.getServers().some((e=>e.instance===this.communicationId));return n&&i})))return t();const n=this.coreGlue.interop.serverMethodAdded((i=>{const s=i.method,r=i.server,o=!this.communicationId||r.instance===this.communicationId;s.name===e&&o&&(n(),t())}))}),this.platformMethodTimeoutMs,`Cannot initiate Glue Web, because a system method's discovery timed out: ${e}`)}passMessageController(e,t,n){const i=Ne.run(e.domain);if(!i.ok)return void(n&&n(`Cannot execute this client control, because of domain validation error: ${JSON.stringify(i.error)}`));const s=i.result;this.controllers[s].handleBridgeMessage(e).then((e=>{t&&t(e)})).catch((e=>{n&&n(e),console.warn(e)}))}async transmitMessage(e,t,n,i){const s={domain:e,data:n,operation:t.name};let r;const o=`Internal Platform Communication Error. Attempted operation: ${JSON.stringify(t.name)} with data: ${JSON.stringify(n)}. `,a=this.communicationId;try{if(!this.running)throw new Error("Cannot send a control message, because the platform shut down");if(r=await this.coreGlue.interop.invoke(zi,s,a?{instance:this.communicationId}:void 0,i),!r)throw new Error("Received unsupported result from the platform - empty result");if(!Array.isArray(r.all_return_values)||0===r.all_return_values.length)throw new Error("Received unsupported result from the platform - empty values collection")}catch(e){if(e&&e.all_errors&&e.all_errors.length){const t=e.all_errors[0].message;throw new Error(`${o} -> Inner message: ${t}`)}throw new Error(`${o} -> Inner message: ${e.message}`)}return r.all_return_values[0].returned}}const Zi={appHello:{name:"appHello",dataDecoder:Je,resultDecoder:bt},appDirectoryStateChange:{name:"appDirectoryStateChange",dataDecoder:wt},instanceStarted:{name:"instanceStarted",dataDecoder:st},instanceStopped:{name:"instanceStopped",dataDecoder:st},applicationStart:{name:"applicationStart",dataDecoder:vt,resultDecoder:st},instanceStop:{name:"instanceStop",dataDecoder:yt},import:{name:"import"},remove:{name:"remove",dataDecoder:pt},export:{name:"export",resultDecoder:gt},clear:{name:"clear"}};class es{me;baseApplicationsTimeoutMS=6e4;appImportTimeoutMS=20;registry=Gi();ioc;bridge;publicWindowId;applications=[];instances=[];platformRegistration;logger;channelsController;sessionController;handlePlatformShutdown(){this.registry.clear(),this.applications=[],this.instances=[],delete this.me}async start(e,t){this.logger=e.logger.subLogger("appManger.controller.web"),this.logger.trace("starting the web appManager controller"),this.publicWindowId=t.publicWindowId,this.addOperationsExecutors(),this.ioc=t,this.bridge=t.bridge,this.channelsController=t.channelsController,this.sessionController=t.sessionController,this.platformRegistration=this.registerWithPlatform(),await this.platformRegistration,this.logger.trace("registration with the platform successful, attaching the appManager property to glue and returning");const n=this.toApi();e.appManager=n}async handleBridgeMessage(e){await this.platformRegistration;const t=m(We,e.operation),n=Zi[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=m(n.dataDecoder,e.data)),await n.execute(i)}onInstanceStarted(e){return"function"!=typeof e?f.raiseError("onInstanceStarted requires a single argument of type function"):this.registry.add("instance-started",e,this.instances)}onInstanceStopped(e){return"function"!=typeof e?f.raiseError("onInstanceStopped requires a single argument of type function"):this.registry.add("instance-stopped",e)}async startApplication(e,t,n){const i=await this.channelsController.all();if(n?.channelId&&!i.includes(n.channelId))return f.raiseError(`The channel with name "${n.channelId}" doesn't exist!`);const s={name:e,waitForAGMReady:n?.waitForAGMReady??!0,context:t,top:n?.top,left:n?.left,width:n?.width,height:n?.height,relativeTo:n?.relativeTo,relativeDirection:n?.relativeDirection,id:n?.reuseId,forceChromeTab:n?.forceTab,layoutComponentId:n?.layoutComponentId,channelId:n?.channelId},r=await this.bridge.send("appManager",Zi.applicationStart,s),o=this.applications.find((e=>e.name===r.applicationName));return this.ioc.buildInstance(r,o)}getApplication(e){const t=m(Ee,e);return this.applications.find((e=>e.name===t))}getInstances(){return this.instances.slice()}onAppAdded(e){return"function"!=typeof e?f.raiseError("onAppAdded requires a single argument of type function"):this.registry.add("application-added",e,this.applications)}onAppRemoved(e){return"function"!=typeof e?f.raiseError("onAppRemoved requires a single argument of type function"):this.registry.add("application-removed",e)}toApi(){return{myInstance:this.me,inMemory:{import:this.importApps.bind(this),remove:this.remove.bind(this),export:this.exportApps.bind(this),clear:this.clear.bind(this)},application:this.getApplication.bind(this),applications:this.getApplications.bind(this),instances:this.getInstances.bind(this),onAppAdded:this.onAppAdded.bind(this),onAppChanged:this.onAppChanged.bind(this),onAppRemoved:this.onAppRemoved.bind(this),onInstanceStarted:this.onInstanceStarted.bind(this),onInstanceStopped:this.onInstanceStopped.bind(this)}}addOperationsExecutors(){Zi.appDirectoryStateChange.execute=this.handleAppDirectoryStateChange.bind(this),Zi.instanceStarted.execute=this.handleInstanceStartedMessage.bind(this),Zi.instanceStopped.execute=this.handleInstanceStoppedMessage.bind(this)}async handleAppDirectoryStateChange(e){e.appsAdded.forEach(this.handleApplicationAddedMessage.bind(this)),e.appsChanged.forEach(this.handleApplicationChangedMessage.bind(this)),e.appsRemoved.forEach(this.handleApplicationRemovedMessage.bind(this))}onAppChanged(e){return"function"!=typeof e?f.raiseError("onAppChanged requires a single argument of type function"):this.registry.add("application-changed",e)}async handleApplicationAddedMessage(e){if(this.applications.some((t=>t.name===e.name)))return;const t=await this.ioc.buildApplication(e,[]),n=this.instances.filter((e=>e.application.name===t.name));t.instances.push(...n),this.applications.push(t),this.registry.execute("application-added",t)}async handleApplicationRemovedMessage(e){const t=this.applications.findIndex((t=>t.name===e.name));if(t<0)return;const n=this.applications[t];this.applications.splice(t,1),this.registry.execute("application-removed",n)}async handleApplicationChangedMessage(e){const t=this.applications.find((t=>t.name===e.name));if(!t)return this.handleApplicationAddedMessage(e);t.title=e.title,t.version=e.version,t.icon=e.icon,t.caption=e.caption,t.userProperties=e.userProperties,this.registry.execute("application-changed",t)}async handleInstanceStartedMessage(e){if(this.instances.some((t=>t.id===e.id)))return;const t=this.applications.find((t=>t.name===e.applicationName));if(!t)return f.raiseError(`Cannot add instance: ${e.id}, because there is no application definition associated with it`);const n=this.ioc.buildInstance(e,t);this.instances.push(n),t.instances.push(n),this.registry.execute("instance-started",n)}async handleInstanceStoppedMessage(e){const t=this.instances.find((t=>t.id===e.id));if(t){const t=this.instances.findIndex((t=>t.id===e.id));this.instances.splice(t,1)}const n=this.applications.find((t=>t.instances.some((t=>t.id===e.id))));if(n){const t=n.instances.findIndex((t=>t.id===e.id));n.instances.splice(t,1)}t&&this.registry.execute("instance-stopped",t)}async importApps(e,t="replace"){if(m(Ht,t),!Array.isArray(e))return f.raiseError("Import must be called with an array of definitions");if(e.length>1e4)return f.raiseError("Cannot import more than 10000 app definitions in Glue42 Core.");const n=e.reduce(((e,t)=>{const n=ut.run(t);return n.ok?e.valid.push(t):e.invalid.push({app:t?.name,error:JSON.stringify(n.error)}),e}),{valid:[],invalid:[]}),i=this.baseApplicationsTimeoutMS+this.appImportTimeoutMS*n.valid.length;return await this.bridge.send("appManager",Zi.import,{definitions:n.valid,mode:t},{methodResponseTimeoutMs:i}),{imported:n.valid.map((e=>e.name)),errors:n.invalid}}async remove(e){m(Ee,e),await this.bridge.send("appManager",Zi.remove,{name:e},{methodResponseTimeoutMs:this.baseApplicationsTimeoutMS})}async clear(){await this.bridge.send("appManager",Zi.clear,void 0,{methodResponseTimeoutMs:this.baseApplicationsTimeoutMS})}async exportApps(){return(await this.bridge.send("appManager",Zi.export,void 0,{methodResponseTimeoutMs:this.baseApplicationsTimeoutMS})).definitions}getApplications(){return this.applications.slice()}async joinInitialChannel(e){try{await this.channelsController.join(e)}catch(t){this.logger.warn(`Application instance ${this.me} was unable to join the ${e} channel. Reason: ${JSON.stringify(t)}`)}}async registerWithPlatform(){const e=await this.bridge.send("appManager",Zi.appHello,{windowId:this.publicWindowId},{methodResponseTimeoutMs:this.baseApplicationsTimeoutMS});this.logger.trace("the platform responded to the hello message with a full list of apps"),this.applications=await Promise.all(e.apps.map((e=>this.ioc.buildApplication(e,e.instances)))),this.instances=this.applications.reduce(((e,t)=>(e.push(...t.instances),e)),[]),this.me=this.findMyInstance(),this.logger.trace(`all applications were parsed and saved. I am ${this.me?"NOT a":"a"} valid instance`);const{channels:t}=this.sessionController.getWindowData(),n=t?t.currentNames:[e.initialChannelId];n?.length&&await Promise.all(n.map((e=>e?this.joinInitialChannel(e):Promise.resolve())))}findMyInstance(){for(const e of this.applications){const t=e.instances.find((e=>e.id===this.publicWindowId));if(t)return t}}}class ts{data;bridge;application;me;myCtxKey;constructor(e,t,n){this.data=e,this.bridge=t,this.application=n,this.myCtxKey=`___instance___${this.data.id}`}toApi(){const e=this.bridge.getInteropInstance(this.data.id),t={id:this.data.id,agm:e,application:this.application,stop:this.stop.bind(this),getContext:this.getContext.bind(this)};return this.me=Object.freeze(t),this.me}async getContext(){return this.bridge.contextLib.get(this.myCtxKey)}async stop(){await this.bridge.send("appManager",Zi.instanceStop,{id:this.data.id})}}class ns{data;instances;controller;me;constructor(e,t,n){this.data=e,this.instances=t,this.controller=n}toApi(){const e={name:this.data.name,title:this.data.title,version:this.data.version,icon:this.data.icon,caption:this.data.caption,userProperties:this.data.userProperties,instances:this.instances,start:this.start.bind(this),onInstanceStarted:this.onInstanceStarted.bind(this),onInstanceStopped:this.onInstanceStopped.bind(this)};return this.me=e,this.me}onInstanceStarted(e){return"function"!=typeof e?f.raiseError("OnInstanceStarted requires a single argument of type function"):this.controller.onInstanceStarted((t=>{t.application.name===this.data.name&&e(t)}))}onInstanceStopped(e){return"function"!=typeof e?f.raiseError("OnInstanceStarted requires a single argument of type function"):this.controller.onInstanceStopped((t=>{t.application.name===this.data.name&&e(t)}))}async start(e,t){const n=m(_i,e),i=m(xi,t);return this.controller.startApplication(this.data.name,n,i)}}const is={layoutAdded:{name:"layoutAdded",dataDecoder:Et},layoutChanged:{name:"layoutChanged",dataDecoder:Et},layoutRemoved:{name:"layoutRemoved",dataDecoder:Et},layoutRenamed:{name:"layoutRenamed",dataDecoder:Et},get:{name:"get",dataDecoder:$t,resultDecoder:Vt},getAll:{name:"getAll",dataDecoder:Bt,resultDecoder:Kt},export:{name:"export",dataDecoder:Bt,resultDecoder:Ut},import:{name:"import",dataDecoder:Jt},remove:{name:"remove",dataDecoder:$t},rename:{name:"rename",dataDecoder:Ft,resultDecoder:Lt},save:{name:"save",dataDecoder:Wt,resultDecoder:zt},restore:{name:"restore",dataDecoder:Gt},clientSaveRequest:{name:"clientSaveRequest",dataDecoder:ei,resultDecoder:ti},getGlobalPermissionState:{name:"getGlobalPermissionState",resultDecoder:ni},requestGlobalPermission:{name:"requestGlobalPermission",resultDecoder:ii},checkGlobalActivated:{name:"checkGlobalActivated",resultDecoder:ii},getDefaultGlobal:{name:"getDefaultGlobal",resultDecoder:Vt},setDefaultGlobal:{name:"setDefaultGlobal",dataDecoder:Qt},clearDefaultGlobal:{name:"clearDefaultGlobal"},updateMetadata:{name:"updateMetadata",dataDecoder:qt}};class ss{defaultLayoutRestoreTimeoutMS=12e4;registry=Gi();bridge;logger;windowsController;saveRequestSubscription;handlePlatformShutdown(){this.registry.clear()}async start(e,t){this.logger=e.logger.subLogger("layouts.controller.web"),this.logger.trace("starting the web layouts controller"),this.bridge=t.bridge,this.windowsController=t.windowsController,this.addOperationsExecutors();const n=this.toApi();this.logger.trace("no need for platform registration, attaching the layouts property to glue and returning"),e.layouts=n}async handleBridgeMessage(e){const t=m(Fe,e.operation),n=is[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=m(n.dataDecoder,e.data)),await n.execute(i)}toApi(){const e={get:this.get.bind(this),getAll:this.getAll.bind(this),export:this.exportLayouts.bind(this),import:this.importLayouts.bind(this),save:this.save.bind(this),restore:this.restore.bind(this),remove:this.remove.bind(this),onAdded:this.onAdded.bind(this),onChanged:this.onChanged.bind(this),onRemoved:this.onRemoved.bind(this),onSaveRequested:this.subscribeOnSaveRequested.bind(this),getMultiScreenPermissionState:this.getGlobalPermissionState.bind(this),requestMultiScreenPermission:this.requestGlobalPermission.bind(this),getGlobalTypeState:this.checkGlobalActivated.bind(this),getDefaultGlobal:this.getDefaultGlobal.bind(this),setDefaultGlobal:this.setDefaultGlobal.bind(this),clearDefaultGlobal:this.clearDefaultGlobal.bind(this),rename:this.rename.bind(this),onRenamed:this.onRenamed.bind(this),updateMetadata:this.updateMetadata.bind(this)};return Object.freeze(e)}addOperationsExecutors(){is.layoutAdded.execute=this.handleOnAdded.bind(this),is.layoutChanged.execute=this.handleOnChanged.bind(this),is.layoutRemoved.execute=this.handleOnRemoved.bind(this),is.layoutRenamed.execute=this.handleOnRenamed.bind(this),is.clientSaveRequest.execute=this.handleSaveRequest.bind(this)}async get(e,t){m(Ee,e),m(Ct,t);return(await this.bridge.send("layouts",is.get,{name:e,type:t})).layout}async getAll(e){m(Ct,e);return(await this.bridge.send("layouts",is.getAll,{type:e})).summaries}async exportLayouts(e){m(Ct,e);return(await this.bridge.send("layouts",is.export,{type:e})).layouts}async importLayouts(e,t="replace"){if(m(Ht,t),!Array.isArray(e))return f.raiseError("Import must be called with an array of layouts");if(e.length>1e3)return f.raiseError("Cannot import more than 1000 layouts at once in Glue42 Core.");const n=e.reduce(((e,t)=>{const n=Et.run(t);return n.ok?e.valid.push(t):this.logger.warn(`A layout with name: ${t.name} was not imported, because of error: ${JSON.stringify(n.error)}`),e}),{valid:[]}),i=e.filter((e=>n.valid.some((t=>t.name===e.name))));await this.bridge.send("layouts",is.import,{layouts:i,mode:t})}async save(e){m(Dt,e);return(await this.bridge.send("layouts",is.save,{layout:e})).layout}async restore(e){m(jt,e);const t=e.timeout?2*e.timeout:this.defaultLayoutRestoreTimeoutMS;await this.bridge.send("layouts",is.restore,{layout:e},{methodResponseTimeoutMs:t})}async remove(e,t){m(Ct,e),m(Ee,t),await this.bridge.send("layouts",is.remove,{type:e,name:t})}async handleSaveRequest(e){const t={};if(this.saveRequestSubscription)try{const n=this.saveRequestSubscription(e);t.windowContext=n?.windowContext}catch(e){this.logger.warn(`An error was thrown by the onSaveRequested callback, ignoring the callback: ${JSON.stringify(e)}`)}return t}async getGlobalPermissionState(){return await this.bridge.send("layouts",is.getGlobalPermissionState,void 0)}async requestGlobalPermission(){const e=(await this.getGlobalPermissionState()).state;if("denied"===e)return{permissionGranted:!1};if("granted"===e)return{permissionGranted:!0};const t=this.windowsController.my(),n=(window.glue42core||window.iobrowser).isPlatformFrame;if("Platform"!==t.name&&!n)return f.raiseError("Cannot request permission for multi-window placement from any app other than the Platform.");return{permissionGranted:(await this.bridge.send("layouts",is.requestGlobalPermission,void 0,{methodResponseTimeoutMs:18e4})).isAvailable}}async checkGlobalActivated(){return{activated:(await this.bridge.send("layouts",is.checkGlobalActivated,void 0)).isAvailable}}async getDefaultGlobal(){return(await this.bridge.send("layouts",is.getDefaultGlobal,void 0,void 0,{includeOperationCheck:!0})).layout}async setDefaultGlobal(e){m(Ee,e),await this.bridge.send("layouts",is.setDefaultGlobal,{name:e},void 0,{includeOperationCheck:!0})}async clearDefaultGlobal(){await this.bridge.send("layouts",is.clearDefaultGlobal,void 0,void 0,{includeOperationCheck:!0})}async rename(e,t){m(Et,e),m(Ee,t);return await this.bridge.send("layouts",is.rename,{layout:e,newName:t},void 0,{includeOperationCheck:!0})}async updateMetadata(e){m(Et,e),await this.bridge.send("layouts",is.updateMetadata,{layout:e},void 0,{includeOperationCheck:!0})}onAdded(e){return this.exportLayouts("Global").then((t=>t.forEach((t=>e(t))))).catch((()=>{})),this.exportLayouts("Workspace").then((t=>t.forEach((t=>e(t))))).catch((()=>{})),this.registry.add(is.layoutAdded.name,e)}onChanged(e){return this.registry.add(is.layoutChanged.name,e)}onRemoved(e){return this.registry.add(is.layoutRemoved.name,e)}onRenamed(e){return"function"!=typeof e?f.raiseError("Cannot subscribe to onRenamed, because the provided callback is not a function!"):this.registry.add(is.layoutRenamed.name,e)}subscribeOnSaveRequested(e){return"function"!=typeof e?f.raiseError("Cannot subscribe to onSaveRequested, because the provided argument is not a valid callback function."):this.saveRequestSubscription?f.raiseError("Cannot subscribe to onSaveRequested, because this client has already subscribed and only one subscription is supported. Consider unsubscribing from the initial one."):(this.saveRequestSubscription=e,()=>{delete this.saveRequestSubscription})}async handleOnAdded(e){this.registry.execute(is.layoutAdded.name,e)}async handleOnChanged(e){this.registry.execute(is.layoutChanged.name,e)}async handleOnRemoved(e){this.registry.execute(is.layoutRemoved.name,e)}async handleOnRenamed(e){this.registry.execute(is.layoutRenamed.name,e)}}const rs={raiseNotification:{name:"raiseNotification",dataDecoder:Hn,resultDecoder:Jn},requestPermission:{name:"requestPermission",resultDecoder:Kn},notificationShow:{name:"notificationShow",dataDecoder:Vn},notificationClick:{name:"notificationClick",dataDecoder:Vn},getPermission:{name:"getPermission",resultDecoder:zn},list:{name:"list",resultDecoder:gi},notificationRaised:{name:"notificationRaised",dataDecoder:pi},notificationClosed:{name:"notificationClosed",dataDecoder:mi},click:{name:"click"},clear:{name:"clear"},clearAll:{name:"clearAll"},clearOld:{name:"clearOld"},configure:{name:"configure",dataDecoder:Yn},getConfiguration:{name:"getConfiguration",resultDecoder:Zn},configurationChanged:{name:"configurationChanged",resultDecoder:Zn},setState:{name:"setState",dataDecoder:On},activeCountChange:{name:"activeCountChange",resultDecoder:An},stateChange:{name:"stateChange",resultDecoder:On}};let os=(e=21)=>{let t="",n=e;for(;n--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return t};class as{registry=Gi();logger;bridge;notificationsSettings;notifications={};coreGlue;buildNotificationFunc;handlePlatformShutdown(){this.notifications={},this.registry.clear()}async start(e,t){this.logger=e.logger.subLogger("notifications.controller.web"),this.logger.trace("starting the web notifications controller"),this.bridge=t.bridge,this.coreGlue=e,this.notificationsSettings=t.config.notifications,this.buildNotificationFunc=t.buildNotification;const n=this.toApi();this.addOperationExecutors(),e.notifications=n,this.logger.trace("notifications are ready")}async handleBridgeMessage(e){const t=m(Le,e.operation),n=rs[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=m(n.dataDecoder,e.data)),await n.execute(i)}toApi(){const e={raise:this.raise.bind(this),requestPermission:this.requestPermission.bind(this),getPermission:this.getPermission.bind(this),list:this.list.bind(this),onRaised:this.onRaised.bind(this),onClosed:this.onClosed.bind(this),click:this.click.bind(this),clear:this.clear.bind(this),clearAll:this.clearAll.bind(this),clearOld:this.clearOld.bind(this),configure:this.configure.bind(this),getConfiguration:this.getConfiguration.bind(this),getFilter:this.getFilter.bind(this),setFilter:this.setFilter.bind(this),setState:this.setState.bind(this),onConfigurationChanged:this.onConfigurationChanged.bind(this),onActiveCountChanged:this.onActiveCountChanged.bind(this),onStateChanged:this.onStateChanged.bind(this)};return Object.freeze(e)}async getPermission(){return(await this.bridge.send("notifications",rs.getPermission,void 0)).permission}async requestPermission(){return(await this.bridge.send("notifications",rs.requestPermission,void 0)).permissionGranted}async raise(e){const t=m(Mn,e);t.showToast="boolean"!=typeof t.showToast||t.showToast,t.showInPanel="boolean"!=typeof t.showInPanel||t.showInPanel;if(!await this.requestPermission())return f.raiseError("Cannot raise the notification, because the user has declined the permission request");const n=os(10),i=await this.bridge.send("notifications",rs.raiseNotification,{settings:t,id:n}),s=this.buildNotificationFunc(i.settings,n);return this.notifications[n]=s,s}async list(){return(await this.bridge.send("notifications",rs.list,void 0,void 0,{includeOperationCheck:!0})).notifications}onRaised(e){return"function"!=typeof e?f.raiseError("onRaised expects a callback of type function"):this.registry.add("notification-raised",e)}onClosed(e){return"function"!=typeof e?f.raiseError("onClosed expects a callback of type function"):this.registry.add("notification-closed",e)}async click(e,t){m(Ee,e),t&&m(Ee,t),await this.bridge.send("notifications",rs.click,{id:e,action:t},void 0,{includeOperationCheck:!0})}async clear(e){m(Ee,e),await this.bridge.send("notifications",rs.clear,{id:e},void 0,{includeOperationCheck:!0})}async clearAll(){await this.bridge.send("notifications",rs.clearAll,void 0,void 0,{includeOperationCheck:!0})}async clearOld(){await this.bridge.send("notifications",rs.clearOld,void 0,void 0,{includeOperationCheck:!0})}async configure(e){const t=m(Xn,e);await this.bridge.send("notifications",rs.configure,{configuration:t},void 0,{includeOperationCheck:!0})}async getConfiguration(){return(await this.bridge.send("notifications",rs.getConfiguration,void 0,void 0,{includeOperationCheck:!0})).configuration}async getFilter(){return(await this.bridge.send("notifications",rs.getConfiguration,void 0,void 0,{includeOperationCheck:!0})).configuration.sourceFilter}async setFilter(e){const t=m(Qn,e);return await this.bridge.send("notifications",rs.configure,{configuration:{sourceFilter:t}},void 0,{includeOperationCheck:!0}),t}async setState(e,t){m(Ee,e),m(Rn,t),await this.bridge.send("notifications",rs.setState,{id:e,state:t},void 0,{includeOperationCheck:!0})}onConfigurationChanged(e){return"function"!=typeof e?f.raiseError("Cannot subscribe to configuration changed, because the provided callback is not a function!"):this.registry.add("notifications-config-changed",e)}onActiveCountChanged(e){return"function"!=typeof e?f.raiseError("Cannot subscribe to onActiveCountChanged changed, because the provided callback is not a function!"):this.registry.add("notifications-active-count-changed",e)}onStateChanged(e){return"function"!=typeof e?f.raiseError("Cannot subscribe to onStateChanged changed, because the provided callback is not a function!"):this.registry.add("notification-state-changed",e)}addOperationExecutors(){rs.notificationShow.execute=this.handleNotificationShow.bind(this),rs.notificationClick.execute=this.handleNotificationClick.bind(this),rs.notificationRaised.execute=this.handleNotificationRaised.bind(this),rs.notificationClosed.execute=this.handleNotificationClosed.bind(this),rs.configurationChanged.execute=this.handleConfigurationChanged.bind(this),rs.activeCountChange.execute=this.handleActiveCountChanged.bind(this),rs.stateChange.execute=this.handleNotificationStateChanged.bind(this)}async handleConfigurationChanged(e){this.registry.execute("notifications-config-changed",e.configuration)}async handleActiveCountChanged(e){this.registry.execute("notifications-active-count-changed",e)}async handleNotificationStateChanged(e){this.registry.execute("notification-state-changed",{id:e.id},e.state)}async handleNotificationShow(e){if(!e.id)return;const t=this.notifications[e.id];t&&t.onshow&&t.onshow()}async handleNotificationClick(e){if(!e.action&&this.notificationsSettings?.defaultClick&&this.notificationsSettings.defaultClick(this.coreGlue,e.definition),e.action&&this.notificationsSettings?.actionClicks?.some((t=>t.action===e.action))){const t=this.notificationsSettings?.actionClicks?.find((t=>t.action===e.action));t.handler(this.coreGlue,e.definition)}if(!e.id)return;const t=this.notifications[e.id];t&&t.onclick&&(t.onclick(),delete this.notifications[e.id])}async handleNotificationRaised(e){this.registry.execute("notification-raised",e.notification)}async handleNotificationClosed(e){this.registry.execute("notification-closed",e)}}const cs={getIntents:{name:"getIntents",resultDecoder:rn},findIntent:{name:"findIntent",dataDecoder:cn,resultDecoder:rn},raiseIntent:{name:"raiseIntent",dataDecoder:dn,resultDecoder:pn},raise:{name:"raise",dataDecoder:un,resultDecoder:pn},filterHandlers:{name:"filterHandlers",dataDecoder:fn,resultDecoder:mn},getIntentsByHandler:{name:"getIntentsByHandler",dataDecoder:Yt,resultDecoder:vn}},ds="Tick42.FDC3.Intents.",ls=2147483647,hs=9e4;class us{bridge;logger;interop;appManagerController;windowsController;legacyIntentsController;myIntents=new Set;prefsController;registry=Gi();useIntentsResolverUI=!0;intentsResolverAppName;intentResolverResponseTimeout;unregisterIntentPromises=[];async start(e,t){this.logger=e.logger.subLogger("intents.controller.web"),this.logger.trace("starting the web intents controller"),this.bridge=t.bridge,this.interop=e.interop,this.appManagerController=t.appManagerController,this.windowsController=t.windowsController,this.legacyIntentsController=t.legacyIntentsHelper,this.prefsController=t.prefsController,this.checkIfIntentsResolverIsEnabled(t.config);const n=this.toApi();this.logger.trace("no need for platform registration, attaching the intents property to glue and returning"),e.intents=n}handlePlatformShutdown(){this.myIntents=new Set,this.unregisterIntentPromises=[]}async handleBridgeMessage(e){const t=m(Xt,e.operation),n=cs[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=m(n.dataDecoder,e.data)),await n.execute(i)}toApi(){return{raise:this.raise.bind(this),all:this.all.bind(this),addIntentListener:this.addIntentListener.bind(this),register:this.register.bind(this),find:this.find.bind(this),filterHandlers:this.filterHandlers.bind(this),getIntents:this.getIntentsByHandler.bind(this),clearSavedHandlers:this.clearSavedHandlers.bind(this),onHandlerAdded:this.onHandlerAdded.bind(this),onHandlerRemoved:this.onHandlerRemoved.bind(this)}}async raise(e){const t=m(ln,e),n="string"==typeof t?{intent:t}:t;await Promise.all(this.unregisterIntentPromises),n.clearSavedHandler&&(this.logger.trace(`User removes saved handler for intent ${n.intent}`),await this.removeRememberedHandler(n.intent));const i=await this.checkHandleRaiseWithRememberedHandler(n);if(i)return i;const s={intentRequest:n,resolverConfig:this.getResolverConfigByRequest({intentRequest:n})},r=await this.isRaiseOperationSupported();if(!r.supported)return this.logger.warn(`${r.reason}. Invoking legacy raise method`),this.legacyIntentsController.raise(s,this.find.bind(this));this.logger.trace(`Sending raise request to the platform: ${JSON.stringify(e)} and method response timeout of ${this.intentResolverResponseTimeout}ms`);const o=n.waitUserResponseIndefinitely?ls:(n.timeout||this.intentResolverResponseTimeout)+3e4;return await this.bridge.send("intents",cs.raise,s,{methodResponseTimeoutMs:o,waitTimeoutMs:o})}getResolverConfigByRequest(e){if(e.handlerFilter)return{enabled:"boolean"==typeof e.handlerFilter?.openResolver?e.handlerFilter?.openResolver:this.useIntentsResolverUI,appName:this.intentsResolverAppName,waitResponseTimeout:e.handlerFilter?.timeout||hs};const t=e.intentRequest?.waitUserResponseIndefinitely?ls:this.intentResolverResponseTimeout;return{enabled:this.useIntentsResolverUI,appName:this.intentsResolverAppName,waitResponseTimeout:t}}async isRaiseOperationSupported(){try{const{isSupported:e}=await this.bridge.send("intents",Ui.operationCheck,{operation:"raise"});return{supported:e,reason:e?"":'The platform of this client is outdated and does not support "raise" operation'}}catch(e){return{supported:!1,reason:'The platform of this client is outdated and does not support "operationCheck" command'}}}async all(){await Promise.all(this.unregisterIntentPromises);return(await this.bridge.send("intents",cs.getIntents,void 0)).intents}addIntentListener(e,t){if(m(bn,e),"function"!=typeof t)return f.raiseError("Cannot add intent listener, because the provided handler is not a function!");let n;const i="string"==typeof e?e:e.intent,s=this.buildInteropMethodName(i);if(this.myIntents.has(i))return f.raiseError(`Intent listener for intent ${i} already registered!`);this.myIntents.add(i);const r={unsubscribe:()=>{this.myIntents.delete(i),n.then((()=>this.interop.unregister(s))).catch((e=>this.logger.trace(`Unregistration of a method with name ${s} failed with reason: ${e}`)))}};let o={};if("object"==typeof e){const{intent:t,...n}=e;o=n}return n=this.interop.register({name:s,flags:{intent:o}},(e=>{if(this.myIntents.has(i)){const{_initialCallerId:n,...i}=e;return t(i)}})),n.catch((e=>{this.myIntents.delete(i),this.logger.warn(`Registration of a method with name ${s} failed with reason: ${e}`)})),r}async register(e,t){if(m(bn,e),"function"!=typeof t)return f.raiseError("Cannot add intent listener, because the provided handler is not a function!");await Promise.all(this.unregisterIntentPromises);const n="string"==typeof e?e:e.intent,i=this.buildInteropMethodName(n);if(this.myIntents.has(n))return f.raiseError(`Intent listener for intent ${n} already registered!`);this.myIntents.add(n);let s={};if("object"==typeof e){const{intent:t,...n}=e;s=n}try{await this.interop.register({name:i,flags:{intent:s}},(e=>{if(this.myIntents.has(n)){const{_initialCallerId:n,...i}=e,s=this.interop.servers().find((e=>e.instance===n));return t(i,s)}}))}catch(e){return this.myIntents.delete(n),f.raiseError(`Registration of a method with name ${i} failed with reason: ${JSON.stringify(e)}`)}return{unsubscribe:()=>this.unsubscribeIntent(n)}}async find(e){let t;if(void 0!==e){const n=m(an,e);"string"==typeof n?t={filter:{name:n}}:"object"==typeof n&&(t={filter:n})}await Promise.all(this.unregisterIntentPromises);return(await this.bridge.send("intents",cs.findIntent,t)).intents}onHandlerAdded(e){if("function"!=typeof e)return f.raiseError("Cannot subscribe for 'onHandlerAdded' event - callback is not a function!");const t=this.subscribeForAppEvent("onAppAdded",e),n=this.subscribeForServerMethodEvent("serverMethodAdded",e);return()=>{t(),n()}}onHandlerRemoved(e){if("function"!=typeof e)return f.raiseError("Cannot subscribe for 'onHandlerRemoved' event - callback is not a function!");const t=this.subscribeForAppEvent("onAppRemoved",e),n=this.subscribeForServerMethodEvent("serverMethodRemoved",e);return()=>{t(),n()}}subscribeForAppEvent(e,t){return this.appManagerController[e]((e=>{const n=e.userProperties.intents;n?.length&&n.forEach((n=>{const i=this.buildIntentHandlerFromApp(e,n);t(i,n.name)}))}))}subscribeForServerMethodEvent(e,t){return this.interop[e]((async({server:e,method:n})=>{if(!n.name.startsWith(ds))return;const i=n.name.replace(ds,""),s=await this.buildIntentHandlerFromServerMethod(e,n,i);t(s,i)}))}buildIntentHandlerFromApp(e,t){return{applicationName:e.name,type:"app",applicationDescription:e.caption,applicationIcon:e.icon,applicationTitle:e.title,contextTypes:t.contexts,displayName:t.displayName,resultType:t.resultType}}async buildIntentHandlerFromServerMethod(e,t,n){const i=t.flags.intent,s=this.appManagerController.getApplication(e.application||e.applicationName);let r;e.windowId&&(r=await(this.windowsController.findById(e.windowId)?.getTitle()));const o=s?.userProperties?.intents?.find((e=>e.name===n));return{applicationName:e.application||e.applicationName||"",instanceId:e.windowId||e.instance,type:"instance",applicationIcon:i?.icon||s?.icon,applicationTitle:s?.title,applicationDescription:i?.description||s?.caption,contextTypes:i?.contextTypes||o?.contexts,instanceTitle:r,displayName:i?.displayName||o?.displayName,resultType:i?.resultType||o?.resultType}}async clearSavedHandlers(){this.logger.trace("Removing all saved handlers from prefs storage for current app"),await this.prefsController.update({intents:void 0})}checkIfIntentsResolverIsEnabled(e){this.useIntentsResolverUI="boolean"!=typeof e.intents?.enableIntentsResolverUI||e.intents.enableIntentsResolverUI,this.intentsResolverAppName=e.intents?.intentsResolverAppName??"intentsResolver",this.intentResolverResponseTimeout=e.intents?.methodResponseTimeoutMs??6e4}clearUnregistrationPromise(e){this.unregisterIntentPromises=this.unregisterIntentPromises.filter((t=>t!==e))}buildInteropMethodName(e){return`${ds}${e}`}unsubscribeIntent(e){this.myIntents.delete(e);const t=this.buildInteropMethodName(e),n=this.interop.unregister(t);this.unregisterIntentPromises.push(n),n.then((()=>{this.clearUnregistrationPromise(n)})).catch((e=>{this.logger.error(`Unregistration of a method with name ${t} failed with reason: ${e}`),this.clearUnregistrationPromise(n)}))}async filterHandlers(e){if(m(gn,e),this.checkIfAtLeastOneFilterIsPresent(e),e.openResolver&&!this.useIntentsResolverUI)return f.raiseError("Cannot resolve 'filterHandlers' request using Intents Resolver UI because it's globally disabled");const t=(e.timeout||hs)+3e4,n={filterHandlersRequest:e,resolverConfig:this.getResolverConfigByRequest({handlerFilter:e})};return await this.bridge.send("intents",cs.filterHandlers,n,{methodResponseTimeoutMs:t,waitTimeoutMs:t},{includeOperationCheck:!0})}checkIfAtLeastOneFilterIsPresent(e){const t="Provide at least one filter criteria of the following: 'intent' | 'contextTypes' | 'resultType' | 'applicationNames'";if(!Object.keys(e).length)return f.raiseError(t);const{intent:n,resultType:i,contextTypes:s,applicationNames:r}=e,o=s?.length,a=r?.length;return n||i||o||a?void 0:f.raiseError(t)}async getIntentsByHandler(e){m(Yt,e);return await this.bridge.send("intents",cs.getIntentsByHandler,e,void 0,{includeOperationCheck:!0})}async removeRememberedHandler(e){let t;this.logger.trace(`Removing saved handler from prefs storage for intent ${e}`);try{t=await this.prefsController.get()}catch(e){return void this.logger.warn(`prefs.get() threw the following error: ${e}`)}const n=t.data?.intents;if(!n)return void this.logger.trace("No app prefs found for current app");delete n[e];const i={...t.data,intents:n};try{await this.prefsController.update(i)}catch(e){return void this.logger.warn(`prefs.update() threw the following error: ${e}`)}this.logger.trace(`Handler saved choice for intent ${e} removed successfully`)}async checkForRememberedHandler(e){let t;try{t=await this.prefsController.get()}catch(e){return void this.logger.warn(`prefs.get() threw the following error: ${e}`)}const n=t.data?.intents?.[e.intent];return n?.handler}async checkHandleRaiseWithRememberedHandler(e){if(e.target)return;const t=await this.checkForRememberedHandler(e);if(!t)return;const n={intentRequest:{...e,target:{app:t.applicationName,instance:t.instanceId}},resolverConfig:{enabled:!1,appName:this.intentsResolverAppName,waitResponseTimeout:e.timeout||hs}};try{return await this.bridge.send("intents",cs.raise,n)}catch(t){this.logger.trace("Could not raise intent to remembered handler. Removing it from Prefs store"),await this.removeRememberedHandler(e.intent)}}}const ps={addChannel:{name:"addChannel",dataDecoder:Nn},removeChannel:{name:"removeChannel",dataDecoder:$n},getMyChannel:{name:"getMyChannel",resultDecoder:vi},getWindowIdsOnChannel:{name:"getWindowIdsOnChannel",dataDecoder:fi,resultDecoder:wi},getWindowIdsWithChannels:{name:"getWindowIdsWithChannels",dataDecoder:Ii,resultDecoder:Si},joinChannel:{name:"joinChannel",dataDecoder:ki},restrict:{name:"restrict",dataDecoder:Ln},getRestrictions:{name:"getRestrictions",dataDecoder:Gn,resultDecoder:qn},restrictAll:{name:"restrictAll",dataDecoder:Un},notifyChannelsChanged:{name:"notifyChannelsChanged",dataDecoder:Ri},leaveChannel:{name:"leaveChannel",dataDecoder:Ti},requestChannelSelector:{name:"requestChannelSelector",dataDecoder:at},getMode:{name:"getMode",resultDecoder:yi}},gs="___channel___",ms="subs",fs="changed",ws="channels_changed";class bs{registry=Gi();logger;contexts;bridge;windowsController;sessionController;_mode;currentChannels=[];unsubscribeDict={};handlePlatformShutdown(){this.registry.clear()}addOperationsExecutors(){ps.getMyChannel.execute=this.handleGetMyChannel.bind(this),ps.joinChannel.execute=this.handleJoinChannel.bind(this),ps.leaveChannel.execute=this.handleLeaveChannel.bind(this),ps.restrict.execute=({config:e})=>this.restrict(e),ps.getRestrictions.execute=({windowId:e})=>this.getRestrictions(e),ps.restrictAll.execute=({restrictions:e})=>this.restrictAll(e)}async start(e,t){this.logger=e.logger.subLogger("channels.controller.web"),this.logger.trace("starting the web channels controller"),this.contexts=e.contexts,this.addOperationsExecutors(),this.bridge=t.bridge,this.windowsController=t.windowsController,this.sessionController=t.sessionController,this.logger.trace("no need for platform registration, attaching the channels property to glue and returning"),this._mode=await this.getPlatformChannelsMode();const n=this.toApi();e.channels=n}async postStart(e,t){try{await this.requestChannelSelector(e.appManager.myInstance)}catch(e){this.logger.warn(`Failed to display channel selector: ${g(e)}`)}}async handleBridgeMessage(e){const t=m(bi,e.operation),n=ps[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=m(n.dataDecoder,e.data)),await n.execute(i)}async list(){const e=this.getAllChannelNames();return await Promise.all(e.map((e=>this.get(e))))}my(){return this.current()}async handleGetMyChannel(){const e=this.my();return e?{channel:e}:{}}async join(e,t){const n=this.getAllChannelNames();m(Cn(n),e),m(je,t);return t&&t!==this.windowsController.my().id?await this.bridge.send("channels",ps.joinChannel,{channel:e,windowId:t},void 0,{includeOperationCheck:!0}):"single"===this._mode?this.switchToChannel(e):this.joinAdditionalChannel(e)}handleJoinChannel({channel:e,windowId:t}){return this.join(e,t)}onChanged(e){return this.changed(e)}async leave(e={}){if(m(_n,e),e.channel){const t=this.getAllChannelNames();m(Cn(t),e.channel)}if(e.windowId&&e.windowId!==this.windowsController.my().id){const t={windowId:e.windowId,channelName:e.channel};return void await this.bridge.send("channels",ps.leaveChannel,t,void 0,{includeOperationCheck:!0})}const t=e.channel?[e.channel]:this.currentChannels;t.forEach((e=>this.unsubscribe(e))),this.currentChannels=this.currentChannels.filter((e=>!t.includes(e))),this.sessionController.setWindowData({currentNames:this.currentChannels},"channels"),this.executeChangedEvents(),await this.notifyChannelsChanged()}handleLeaveChannel(e){return this.leave({channel:e.channelName})}toApi(){const e={mode:this._mode,subscribe:this.subscribe.bind(this),subscribeFor:this.subscribeFor.bind(this),publish:this.publish.bind(this),all:this.all.bind(this),list:this.list.bind(this),get:this.get.bind(this),getMyChannels:this.getMyChannels.bind(this),myChannels:this.myChannels.bind(this),onChannelsChanged:this.onChannelsChanged.bind(this),join:this.join.bind(this),leave:this.leave.bind(this),current:this.current.bind(this),my:this.my.bind(this),changed:this.changed.bind(this),onChanged:this.onChanged.bind(this),add:this.add.bind(this),remove:this.remove.bind(this),getMy:this.getMy.bind(this),getWindowsOnChannel:this.getWindowsOnChannel.bind(this),getWindowsWithChannels:this.getWindowsWithChannels.bind(this),restrict:this.restrict.bind(this),getRestrictions:this.getRestrictions.bind(this),restrictAll:this.restrictAll.bind(this)};return Object.freeze(e)}createContextName(e){return`${gs}${e}`}getAllChannelNames(){return this.contexts.all().filter((e=>e.startsWith(gs))).map((e=>e.replace(gs,"")))}async joinAdditionalChannel(e){if(this.currentChannels.includes(e))return;this.currentChannels=[...this.currentChannels,e];const t=this.createContextName(e),n=await this.contexts.subscribe(t,((e,t,n,i,s)=>{this.registry.execute(ms,e.data,e,s?.updaterId)}));this.unsubscribeDict[e]=n,this.executeChangedEvents(e),this.sessionController.setWindowData({currentNames:this.currentChannels},"channels"),await this.notifyChannelsChanged()}async switchToChannel(e){const t=this.currentChannels[0];if(e===t)return;this.unsubscribe(t),this.currentChannels=[e];const n=this.createContextName(e),i=await this.contexts.subscribe(n,((e,t,n,i,s)=>{this.registry.execute(ms,e.data,e,s?.updaterId)}));this.unsubscribeDict[e]=i,this.executeChangedEvents(e),this.sessionController.setWindowData({currentNames:this.currentChannels},"channels"),await this.notifyChannelsChanged()}unsubscribe(e){if(e)return this.unsubscribeDict[e]?.(),void delete this.unsubscribeDict[e];Object.values(this.unsubscribeDict).forEach((e=>e())),this.unsubscribeDict={}}executeChangedEvents(e){this.registry.execute(fs,e),this.registry.execute(ws,this.currentChannels)}async notifyChannelsChanged(){const e=this.windowsController.my().id;if(e)try{await this.bridge.send("channels",ps.notifyChannelsChanged,{channelNames:this.currentChannels,windowId:e},void 0,{includeOperationCheck:!0})}catch(e){this.logger.warn(`Failed to notify channel changed: ${g(e)}`)}}async updateData(e,t){const n=this.createContextName(e),i=this.getFDC3Type(t);if(this.contexts.setPathSupported){const e=Object.keys(t).map((e=>({path:`data.${e}`,value:t[e]})));i&&e.push({path:u,value:i}),await this.contexts.setPaths(n,e)}else i&&(t[u]=i),await this.contexts.update(n,{data:t})}getFDC3Type(e){const t=Object.keys(e).filter((e=>0===e.indexOf("fdc3_")));if(0!==t.length)return t.length>1?f.raiseError("FDC3 does not support updating of multiple context keys"):t[0].split("_").slice(1).join("_")}subscribe(e,t){if("function"!=typeof e)return f.raiseError("Cannot subscribe to channels, because the provided callback is not a function!");t&&m(In,t);const n=this.current(),i=t?.contextType?this.getWrappedSubscribeCallbackWithFdc3Type(e,t.contextType):this.getWrappedSubscribeCallback(e);return n&&this.replaySubscribe(i,n),this.registry.add(ms,i)}async subscribeFor(e,t,n){const i=this.getAllChannelNames();if(m(Cn(i),e),"function"!=typeof t)return f.raiseError(`Cannot subscribe to channel ${e}, because the provided callback is not a function!`);n&&m(In,n);const s=this.createContextName(e),r=n?.contextType?this.getWrappedSubscribeCallbackWithFdc3Type(t,n.contextType):this.getWrappedSubscribeCallback(t);return this.contexts.subscribe(s,((e,t,n,i,s)=>{r(e.data,e,s?.updaterId)}))}async publish(e,t){if("object"!=typeof e)return f.raiseError("Cannot publish to channel, because the provided data is not an object!");if(m(Sn,t),"object"==typeof t)return this.publishWithOptions(e,t);if("string"==typeof t){const e=this.getAllChannelNames();m(Cn(e),t)}if(!t&&this.currentChannels.length>1)return this.publishOnMultipleChannels(e);const n="string"==typeof t?t:this.currentChannels[0];if(!n)return f.raiseError("Cannot publish to channel, because not joined to a channel!");return this.isAllowedByRestrictions(n,"write")?this.updateData(n,e):f.raiseError(`Cannot publish on channel ${n} due to restrictions`)}async all(){return this.getAllChannelNames()}async get(e,t){const n=this.getAllChannelNames();m(Cn(n),e),t&&m(In,t);const i=this.createContextName(e),s=await this.contexts.get(i);return t?.contextType?this.getContextForFdc3Type(s,t.contextType):s.latest_fdc3_type?this.getContextWithFdc3Data(s):s}async getMyChannels(){return Promise.all(this.currentChannels.map((e=>{const t=this.createContextName(e);return this.contexts.get(t)})))}myChannels(){return this.currentChannels}getContextForFdc3Type(e,t){const n=`fdc3_${t.split(".").join("&")}`;if(!e.data[n])return{name:e.name,meta:e.meta,data:{}};const i={type:t,...e.data[n]};return{name:e.name,meta:e.meta,data:{fdc3:i}}}getContextWithFdc3Data(e){const{latest_fdc3_type:t,...n}=e,i={type:t.split("&").join("."),...n.data[`fdc3_${t}`]};delete n.data[`fdc3_${t}`];return{name:e.name,meta:e.meta,data:{...n.data,fdc3:i}}}current(){return this.currentChannels[0]}changed(e){return"function"!=typeof e?f.raiseError("Cannot subscribe to channel changed, because the provided callback is not a function!"):this.registry.add(fs,e)}async add(e){const t=m(Nn,e);return this.getAllChannelNames().includes(t.name)?f.raiseError("There's an already existing channel with such name"):(await this.bridge.send("channels",ps.addChannel,t),{name:t.name,meta:t.meta,data:t.data||{}})}async remove(e){m(Ee,e);if(!this.getAllChannelNames().includes(e))return f.raiseError("There's no channel with such name");await this.bridge.send("channels",ps.removeChannel,{name:e},void 0,{includeOperationCheck:!0})}replaySubscribe=(e,t)=>{this.get(t).then((t=>{if("object"==typeof t.data&&Object.keys(t.data).length){const n=this.createContextName(t.name);return this.contexts.subscribe(n,((t,n,i,s,r)=>{e(t.data,t,r?.updaterId)}))}})).then((e=>{e&&"function"==typeof e&&e()})).catch((e=>this.logger.trace(e)))};async getMy(e){if(this.currentChannels.length)return e&&m(In,e),this.get(this.currentChannels[this.currentChannels.length-1],e)}async getWindowsOnChannel(e){const t=this.getAllChannelNames();m(Cn(t),e);const{windowIds:n}=await this.bridge.send("channels",ps.getWindowIdsOnChannel,{channel:e},void 0,{includeOperationCheck:!0});return n.reduce(((e,t)=>{const n=this.windowsController.findById(t);return n?[...e,n]:e}),[])}async getWindowsWithChannels(e){const t=void 0!==e?{filter:m(Ci,e)}:{},{windowIdsWithChannels:n}=await this.bridge.send("channels",ps.getWindowIdsWithChannels,t,void 0,{includeOperationCheck:!0});return n.reduce(((e,{application:t,channel:n,windowId:i})=>{const s=this.windowsController.findById(i);return s?[...e,{application:t,channel:n,window:s}]:e}),[])}async restrict(e){m(Wn,e);const t=this.getAllChannelNames();m(Cn(t),e.name);if(e.windowId&&e.windowId!==this.windowsController.my().id)return this.bridge.send("channels",ps.restrict,{config:e},void 0,{includeOperationCheck:!0});const n=this.sessionController.getWindowData(),i=n?.restrictions?{...n.restrictions,[e.name]:e}:{[e.name]:e},s=await this.getMy(),r=this.checkPreviousReadAllowed(s?.name);this.sessionController.setWindowData(i,"restrictions"),s&&!r&&e.read&&s.name===e.name&&this.replaySubscribeCallback(e.name)}async getRestrictions(e){return m(je,e),e&&e!==this.windowsController.my().id?this.bridge.send("channels",ps.getRestrictions,{windowId:e},void 0,{includeOperationCheck:!0}):this.getMyRestrictions()}async restrictAll(e){m(Bn,e);const t=this.getAllChannelNames();if(e.windowId&&e.windowId!==this.windowsController.my().id)return this.bridge.send("channels",ps.restrictAll,{restrictions:e},void 0,{includeOperationCheck:!0});const n={};t.forEach((t=>{n[t]={...e,name:t}}));const i=await this.getMy(),s=this.checkPreviousReadAllowed(i?.name);this.sessionController.setWindowData(n,"restrictions"),i&&!s&&e.read&&this.replaySubscribeCallback(i.name)}isAllowedByRestrictions(e,t){const{channels:n}=this.getMyRestrictions();if(!n?.length)return!0;const i=n.find((t=>t.name===e));return!i||i[t]}getMyRestrictions(){const e=this.sessionController.getWindowData();return{channels:Object.values(e?.restrictions||{})}}replaySubscribeCallback(e){const t=this.createContextName(e);this.contexts.subscribe(t,((e,t,n,i,s)=>{this.registry.execute(ms,e.data,e,s?.updaterId)})).then((e=>{e&&"function"==typeof e&&e()})).catch((e=>this.logger.error(e)))}checkPreviousReadAllowed(e){if(!e)return!0;const t=this.sessionController.getWindowData().restrictions;return!t?.[e]||t[e].read}async publishWithOptions(e,t){if(t.name){const e=this.getAllChannelNames();m(Cn(e),t.name)}if(!t.name&&this.currentChannels.length>1)return this.publishOnMultipleChannels(e,t.fdc3);const n=t.name||this.currentChannels[0];if(!n)return f.raiseError("Cannot publish to channel, because not joined to a channel!");return this.isAllowedByRestrictions(n,"write")?t.fdc3?this.publishFdc3Data(n,e):this.updateData(n,e):f.raiseError(`Cannot publish on channel ${n} due to restrictions`)}async publishOnMultipleChannels(e,t){const n=this.currentChannels.map((e=>this.isAllowedByRestrictions(e,"write")?void 0:e)).filter((e=>!!e));if(n.length)return f.raiseError(`Cannot complete publish operation due to write restrictions on channel${n.length>1?"s":""}: ${n.join(", ")}`);const i=t?this.publishFdc3Data.bind(this):this.updateData.bind(this);await Promise.all(this.currentChannels.map((t=>i(t,e))))}async publishFdc3Data(e,t){m(xn,t);const{type:n,...i}=t,s={[`fdc3_${n.split(".").join("&")}`]:i};return this.updateData(e,s)}getWrappedSubscribeCallback(e){return(t,n,i)=>{if(!this.isAllowedByRestrictions(n.name,"read"))return;const{data:s,latest_fdc3_type:r}=n;if(!r)return void e(t,n,i);const o=r.split("&").join("."),a=`fdc3_${r}`,c={type:o,...s[a]},{[a]:d,...l}=t;e({...l,fdc3:c},n,i)}}getWrappedSubscribeCallbackWithFdc3Type(e,t){const n={replayed:!1};return(i,s,r)=>{if(!this.isAllowedByRestrictions(s.name,"read"))return;const{data:o,latest_fdc3_type:a}=s,c=`fdc3_${t.split(".").join("&")}`;if(!o[c])return;if(n.replayed)return this.parseDataAndInvokeSubscribeCallback({latestFdc3TypeEncoded:a,searchedType:t,callback:e,context:s,updaterId:r});const d={type:t,...o[c]};e({fdc3:d},s,r),n.replayed=!0}}parseDataAndInvokeSubscribeCallback(e){const{latestFdc3TypeEncoded:t,searchedType:n,callback:i,context:s,updaterId:r}=e;if(t.split("&").join(".")!==n)return;i({fdc3:{type:n,...s.data[`fdc3_${t}`]}},s,r)}async requestChannelSelector(e){if(!e)return;const t=e.application,n=t.userProperties?.details;if(!n)return;if(!n?.channelSelector?.enabled)return;const{channels:i}=this.sessionController.getWindowData(),s={windowId:e.id,channelsNames:i?.currentNames||[]};await this.bridge.send("channels",ps.requestChannelSelector,s,void 0,{includeOperationCheck:!0})}async getPlatformChannelsMode(){try{return(await this.bridge.send("channels",ps.getMode,{},void 0,{includeOperationCheck:!0})).mode}catch(e){return this.logger.warn(e?.message||JSON.stringify(e)),"single"}}onChannelsChanged(e){return"function"!=typeof e?f.raiseError("Cannot subscribe to channels changed, because the provided callback is not a function"):this.registry.add(ws,e)}}const ys={getEnvironment:{name:"getEnvironment",resultDecoder:nt},getBase:{name:"getBase",resultDecoder:nt},platformShutdown:{name:"platformShutdown"},isFdc3DataWrappingSupported:{name:"isFdc3DataWrappingSupported"},clientError:{name:"clientError",dataDecoder:$i},systemHello:{name:"systemHello",resultDecoder:Wi}};class vs{bridge;ioc;logger;errorPort=p.port2;async start(e,t){this.logger=e.logger.subLogger("system.controller.web"),this.logger.trace("starting the web system controller"),this.bridge=t.bridge,this.ioc=t,this.addOperationsExecutors();let n=!1;try{const e=await this.bridge.send("system",ys.systemHello,void 0,void 0,{includeOperationCheck:!0});n=e.isClientErrorOperationSupported}catch(e){this.logger.warn("The platform of this client is outdated and does not support some system operations.")}this.errorPort.onmessage=async e=>{n&&await this.bridge.send("system",ys.clientError,{message:e.data},void 0,{includeOperationCheck:!0})},await this.setEnvironment()}async handleBridgeMessage(e){const t=m(qe,e.operation),n=ys[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=m(n.dataDecoder,e.data)),await n.execute(i)}async processPlatformShutdown(){Object.values(this.ioc.controllers).forEach((e=>e.handlePlatformShutdown?e.handlePlatformShutdown():null)),this.ioc.preferredConnectionController.stop(),this.ioc.eventsDispatcher.stop(),await this.bridge.stop()}async setEnvironment(){const e=await this.bridge.send("system",ys.getEnvironment,void 0),t=await this.bridge.send("system",ys.getBase,void 0),n=window.glue42core||window.iobrowser,i=window.glue42core?"glue42core":"iobrowser",s=Object.assign({},n,t,{environment:e});window[i]=Object.freeze(s)}addOperationsExecutors(){ys.platformShutdown.execute=this.processPlatformShutdown.bind(this),ys.isFdc3DataWrappingSupported.execute=this.handleIsFdc3DataWrappingSupported.bind(this)}async handleIsFdc3DataWrappingSupported(){return{isSupported:!0}}}class Cs{onclick=()=>{};onshow=()=>{};id;title;badge;body;data;dir;icon;image;lang;renotify;requireInteraction;silent;tag;timestamp;vibrate;clickInterop;actions;focusPlatformOnDefaultClick;severity;showToast;showInPanel;state;constructor(e,t){this.id=t,this.badge=e.badge,this.body=e.body,this.data=e.data,this.dir=e.dir,this.icon=e.icon,this.image=e.image,this.lang=e.lang,this.renotify=e.renotify,this.requireInteraction=e.requireInteraction,this.silent=e.silent,this.tag=e.tag,this.timestamp=e.timestamp,this.vibrate=e.vibrate,this.title=e.title,this.clickInterop=e.clickInterop,this.actions=e.actions,this.focusPlatformOnDefaultClick=e.focusPlatformOnDefaultClick,this.severity=e.severity,this.showToast=e.showToast,this.showInPanel=e.showInPanel,this.state=e.state}}$(E("clientHello"));const Is={clientHello:{name:"clientHello",resultDecoder:D({widget:D({inject:M()})})}};class Ss{windowId;logger;bridge;eventsDispatcher;channelsController;config;channels=[];unsubFuncs=[];contentCommands={widgetVisualizationPermission:{name:"widgetVisualizationPermission",handle:this.handleWidgetVisualizationPermission.bind(this)},changeChannel:{name:"changeChannel",handle:this.handleChangeChannel.bind(this)}};handlePlatformShutdown(){this.unsubFuncs.forEach((e=>e())),this.channels=[],this.unsubFuncs=[]}async start(e,t){this.logger=e.logger.subLogger("extension.controller.web"),this.windowId=t.publicWindowId,this.logger.trace("starting the extension web controller"),this.bridge=t.bridge,this.channelsController=t.channelsController,this.eventsDispatcher=t.eventsDispatcher;try{await this.registerWithPlatform()}catch(e){return}this.channels=await this.channelsController.list();const n=this.eventsDispatcher.onContentMessage(this.handleContentMessage.bind(this)),i=this.channelsController.onChanged((e=>{this.eventsDispatcher.sendContentMessage({command:"channelChange",newChannel:e})}));this.unsubFuncs.push(n),this.unsubFuncs.push(i)}async handleBridgeMessage(e){}handleContentMessage(e){if(!e||"string"!=typeof e.command)return;const t=this.contentCommands[e.command];t&&t.handle(e)}async registerWithPlatform(){this.logger.trace("registering with the platform"),this.config=await this.bridge.send("extension",Is.clientHello,{windowId:this.windowId}),this.logger.trace("the platform responded to the hello message with a valid extension config")}async handleWidgetVisualizationPermission(){if(!this.config?.widget.inject)return this.eventsDispatcher.sendContentMessage({command:"permissionResponse",allowed:!1});const e=this.channels.find((e=>e.name===this.channelsController.my()));this.eventsDispatcher.sendContentMessage({command:"permissionResponse",allowed:!0,channels:this.channels,currentChannel:e})}async handleChangeChannel(e){"no-channel"!==e.name?await this.channelsController.join(e.name):await this.channelsController.leave()}}class _s{config;glue;registry=Gi();glue42EventName="Glue42";_handleMessage;_resolveWidgetReadyPromise;constructor(e){this.config=e}events={notifyStarted:{name:"notifyStarted",handle:this.handleNotifyStarted.bind(this)},contentInc:{name:"contentInc",handle:this.handleContentInc.bind(this)},requestGlue:{name:"requestGlue",handle:this.handleRequestGlue.bind(this)},widgetFactoryReady:{name:"widgetFactoryReady",handle:this.handleWidgetReady.bind(this)}};stop(){window.removeEventListener(this.glue42EventName,this._handleMessage)}start(e){this.glue=e,this.wireCustomEventListener(),this.announceStarted()}sendContentMessage(e){this.send("contentOut","glue42core",e)}onContentMessage(e){return this.registry.add("content-inc",e)}async widgetReady(e){const t=Hi((()=>new Promise((e=>{this._resolveWidgetReadyPromise=e}))),e,`Timeout of ${e}ms hit waiting for IOBrowserWidget to be ready`);return this.requestWidgetReady(),t}wireCustomEventListener(){this._handleMessage=this.handleMessage.bind(this),window.addEventListener(this.glue42EventName,this._handleMessage)}handleMessage(e){const t=e.detail,n=t?.glue42??t?.glue42core;if(!n)return;const i=n.event,s=this.events[i];s&&s.handle(n.message)}announceStarted(){this.send("start","glue42")}handleRequestGlue(){this.config.exposeAPI?this.send("requestGlueResponse","glue42",{glue:this.glue}):this.send("requestGlueResponse","glue42",{error:"Will not give access to the underlying Glue API, because it was explicitly denied upon initialization."})}handleNotifyStarted(){this.announceStarted()}handleContentInc(e){this.registry.execute("content-inc",e)}requestWidgetReady(){this.send("requestWidgetFactoryReady","glue42")}handleWidgetReady(){this._resolveWidgetReadyPromise?.()}send(e,t,n){const i={};i[t]={event:e,message:n};const s=new CustomEvent(this.glue42EventName,{detail:i});window.dispatchEvent(s)}}class xs{coreGlue;transactionTimeout=15e3;transactionLocks={};webPlatformTransport;webPlatformMessagesUnsubscribe;reconnectCounter=0;logger;constructor(e){this.coreGlue=e,this.logger=this.coreGlue.logger.subLogger("web.preferred.connection.controller")}stop(){this.webPlatformMessagesUnsubscribe&&this.webPlatformMessagesUnsubscribe()}async start(e){if(e.isPlatformInternal)return void this.logger.trace("This is an internal client to the platform, skipping all client preferred communication logic.");if(!(this.coreGlue.connection.transport.name()===h))return f.raiseError("Cannot initiate the Glue Web Bridge, because the initial connection was not handled by a Web Platform transport.");if(!this.coreGlue.connection.transport.isPreferredActivated)return void this.logger.trace("The platform of this client was configured without a preferred connection, skipping the rest of the initialization.");this.webPlatformTransport=this.coreGlue.connection.transport,this.webPlatformMessagesUnsubscribe=this.webPlatformTransport.onMessage(this.handleWebPlatformMessage.bind(this));const t=await this.getCurrentPlatformTransportState();await this.checkSwitchTransport(t)}handleWebPlatformMessage(e){if("string"==typeof e)return;const t=this.coreGlue.connection.transport.name()===h,s=e.type,r=e.args,d=e.transactionId;return s===i.name?this.handleTransportSwitchRequest(r,d):s!==n.name||t?s===o.name?this.handleGetCurrentTransportResponse(r,d):s===a.name?this.handleCheckPreferredLogic(d):s===c.name?this.handleCheckPreferredConnection(r,d):void 0:this.handlePlatformUnload()}async reEstablishPlatformPort(){try{await this.webPlatformTransport.connect()}catch(e){if(this.logger.trace(`Error when re-establishing port connection to the platform: ${JSON.stringify(e)}`),--this.reconnectCounter,this.reconnectCounter>0)return this.reEstablishPlatformPort();this.logger.warn("This client lost connection to the platform while connected to a preferred GW and was not able to re-connect to the platform.")}this.logger.trace("The connection to the platform was re-established, closing the connection to the web gateway."),this.reconnectCounter=0,this.webPlatformTransport.close();const e=await this.getCurrentPlatformTransportState();await this.checkSwitchTransport(e)}async checkSwitchTransport(e){const t=this.coreGlue.connection.transport.name();if(t===e.transportName)return void this.logger.trace("A check switch was requested, but the platform transport and my transport are identical, no switch is necessary");this.logger.trace(`A check switch was requested and a transport switch is necessary, because this client is now on ${t}, but it should reconnect to ${JSON.stringify(e)}`);const n=await this.coreGlue.connection.switchTransport(e);this.setConnected(),this.logger.trace(`The transport switch was completed with result: ${JSON.stringify(n)}`)}async getCurrentPlatformTransportState(){this.logger.trace("Requesting the current transport state of the platform.");const e=this.setTransaction(r.name);this.sendPlatformMessage(r.name,e.id);const t=await e.lock;return this.logger.trace(`The platform responded with transport state: ${JSON.stringify(t)}`),t}setTransaction(e){const t={},n=os(10),i=new Promise(((i,s)=>{let r=!0;t.lift=e=>{r=!1,delete this.transactionLocks[n],i(e)},t.fail=e=>{r=!1,delete this.transactionLocks[n],s(e)},setTimeout((()=>{r&&(r=!1,this.logger.warn(`Transaction for operation: ${e} timed out.`),delete this.transactionLocks[n],s(`Transaction for operation: ${e} timed out.`))}),this.transactionTimeout)}));return t.lock=i,t.id=n,this.transactionLocks[n]=t,t}sendPlatformMessage(e,t,n){this.logger.trace(`Sending a platform message of type: ${e}, id: ${t} and args: ${JSON.stringify(n)}`),this.webPlatformTransport.sendObject({glue42core:{type:e,args:n,transactionId:t}})}handleTransportSwitchRequest(e,t){this.logger.trace(`Received a transport switch request with id: ${t} and data: ${JSON.stringify(e)}`),this.coreGlue.connection.switchTransport(e.switchSettings).then((e=>{this.logger.trace(`The transport switch was completed with result: ${JSON.stringify(e)}`),this.setConnected(),this.sendPlatformMessage(s.name,t,{success:e.success})})).catch((e=>{this.logger.error(e),this.sendPlatformMessage(s.name,t,{success:!1})}))}handlePlatformUnload(){this.reconnectCounter=5,this.logger.trace("The platform was unloaded while I am connected to a preferred connection, re-establishing the port connection."),this.reEstablishPlatformPort()}handleGetCurrentTransportResponse(e,t){this.logger.trace(`Got a current transport response from the platform with id: ${t} and data: ${JSON.stringify(e)}`);const n=e.transportState,i=this.transactionLocks[t];i?.lift(n)}handleCheckPreferredLogic(e){setTimeout((()=>this.sendPlatformMessage(d.name,e)),0)}handleCheckPreferredConnection(e,t){const n=e.url;this.logger.trace(`Testing the possible connection to: ${n}`),this.checkPreferredConnection(n).then((e=>{this.logger.trace(`The connection to ${n} is possible`),this.sendPlatformMessage(l.name,t,e)})).catch((e=>{this.logger.trace(`The connection to ${n} is not possible`),this.sendPlatformMessage(l.name,t,{error:e})}))}checkPreferredConnection(e){return new Promise((t=>{const n=new WebSocket(e);n.onerror=()=>t({live:!1}),n.onopen=()=>{n.close(),t({live:!0})}}))}setConnected(){this.webPlatformTransport.manualSetReadyState()}}class ks{bridge;interop;appManagerController;windowsController;logger;intentsResolverResponsePromises={};constructor(e,t,n,i,s){this.bridge=t,this.interop=n,this.appManagerController=i,this.windowsController=s,this.logger=this.configureLogger(e)}async raise(e,t){const{intentRequest:n,resolverConfig:i}=e,s=(await t(n.intent)).find((e=>e.name===n.intent));if(!s)return f.raiseError(`Intent with name ${n.intent} not found`);const{open:r,reason:o}=this.checkIfResolverShouldBeOpened(s,n,i);if(!r)return this.logger?.trace(`Intent Resolver UI won't be used. Reason: ${o}`),this.invokeRaiseIntent(n);return await this.raiseIntentWithResolverApp(e)}configureLogger(e){return e.subLogger("intents.legacy.helper.web")}async raiseIntentWithResolverApp(e){const{intentRequest:t,resolverConfig:n}=e;this.logger.trace(`Intents Resolver UI with app name ${n.appName} will be used`);const i=await this.registerResponseMethod();this.logger.trace(`Registered interop method ${i}`);const s=await this.openIntentResolverApplication(e,i);this.logger.trace(`Intents Resolver Instance with id ${s.id} opened`);const r=await this.handleInstanceResponse(s.id),o="app"===r.type?{app:r.applicationName}:{instance:r.instanceId};this.logger.trace(`Intent handler chosen by the user: ${JSON.stringify(o)}`);return await this.invokeRaiseIntent({...t,target:o})}async handleInstanceResponse(e){try{const{handler:t,intent:n}=await this.intentsResolverResponsePromises[e].promise;return this.logger?.trace(`Intent handler chosen for intent ${n}: ${JSON.stringify(t)}`),this.stopResolverInstance(e),t}catch(t){return this.stopResolverInstance(e),f.raiseError(t)}}invokeRaiseIntent(e){return this.bridge.send("intents",cs.raiseIntent,e)}async registerResponseMethod(){const e="T42.Intents.Resolver.Control."+os(10);return await this.interop.register(e,this.resolverResponseHandler.bind(this)),e}async openIntentResolverApplication(e,t){const{intentRequest:n,resolverConfig:i}=e,s=this.buildStartContext(n,t),r=await this.buildStartOptions();this.logger.trace(`Starting Intents Resolver UI with context: ${JSON.stringify(s)} and options: ${r}`);const o=await this.appManagerController.getApplication(i.appName).start(s,r);return this.logger.trace(`Intents Resolver instance with id ${o.id} opened`),this.subscribeOnInstanceStopped(o),this.createResponsePromise(n.intent,o.id,t,i.waitResponseTimeout),o}async cleanUpIntentResolverPromise(e){const t=this.intentsResolverResponsePromises[e];if(!t)return;this.interop.unregister(t.methodName).catch((e=>this.logger.warn(e))),delete this.intentsResolverResponsePromises[e]}buildStartContext(e,t){return{intent:e,callerId:this.interop.instance.instance,methodName:t}}async buildStartOptions(){const e=await this.getTargetBounds();return{top:(e.height-440)/2+e.top,left:(e.width-400)/2+e.left,width:400,height:440}}async getTargetBounds(){const e=await this.tryGetWindowBasedBounds()||await this.tryGetWorkspaceBasedBounds();if(e)return this.logger.trace(`Opening Intents Resolver UI with bounds: ${JSON.stringify(e)}`),e;const t={top:window.screen.availTop||0,left:window.screen.availLeft||0,width:window.screen.width,height:window.screen.height};return this.logger.trace(`Opening Intents Resolver UI relative to my screen bounds: ${JSON.stringify(t)}`),t}async tryGetWindowBasedBounds(){try{const e=await this.windowsController.my().getBounds();return this.logger.trace(`Opening the resolver UI relative to my window bounds: ${JSON.stringify(e)}`),e}catch(e){this.logger.trace(`Failure to get my window bounds: ${JSON.stringify(e)}`)}}async tryGetWorkspaceBasedBounds(){try{await this.bridge.send("workspaces",Ui.operationCheck,{operation:"getWorkspaceWindowFrameBounds"});const e=(await this.bridge.send("workspaces",Ui.getWorkspaceWindowFrameBounds,{itemId:this.windowsController.my().id})).bounds;return this.logger.trace(`Opening the resolver UI relative to my workspace frame window bounds: ${JSON.stringify(e)}`),e}catch(e){this.logger.trace(`Failure to get my workspace frame window bounds: ${JSON.stringify(e)}`)}}subscribeOnInstanceStopped(e){const{application:t}=e,n=t.onInstanceStopped((i=>{if(i.id!==e.id)return;const s=this.intentsResolverResponsePromises[i.id];if(!s)return n();s.reject(`Cannot resolve raised intent "${s.intent}" - User closed ${t.name} app without choosing an intent handler`),this.cleanUpIntentResolverPromise(i.id),n()}))}createResponsePromise(e,t,n,i){let s=()=>{},r=()=>{};const o=Ji(((e,t)=>{s=e,r=t}),i,`Timeout of ${i}ms hit waiting for the user to choose a handler for intent ${e}`);this.intentsResolverResponsePromises[t]={intent:e,resolve:s,reject:r,promise:o,methodName:n}}resolverResponseHandler(e,t){const n=Zt.run(e),i=t.instance;if(n.ok)return this.logger.trace(`Intent Resolver instance with id ${i} send a valid response: ${JSON.stringify(n.result)}`),this.intentsResolverResponsePromises[i].resolve(n.result);this.logger.trace(`Intent Resolver instance with id ${i} sent an invalid response. Error: ${JSON.stringify(n.error)}`),this.intentsResolverResponsePromises[i].reject(n.error.message),this.stopResolverInstance(i)}stopResolverInstance(e){const t=this.appManagerController.getInstances().find((t=>t.id===e));t&&t.stop().catch((e=>this.logger.error(e)))}checkIfIntentHasMoreThanOneHandler(e,t){return"object"!=typeof t.target&&(t.handlers?t.handlers.length>1:e.handlers.length>1)}checkIfResolverShouldBeOpened(e,t,n){if(!n.enabled)return{open:!1,reason:"Intent Resolver is disabled. Raising intent to first found handler"};if(!this.appManagerController.getApplication(n.appName))return{open:!1,reason:`Application with name ${n.appName} not found`};return this.checkIfIntentHasMoreThanOneHandler(e,t)?{open:!0}:{open:!1,reason:"Raised intent has only one handler"}}}const Ts={getCurrent:{name:"getCurrent",resultDecoder:di},list:{name:"list",resultDecoder:li},select:{name:"select",dataDecoder:hi}};class Rs{logger;bridge;registry=Gi();themesSubscription;activeThemeSubs=0;async start(e,t){this.logger=e.logger.subLogger("themes.controller.web"),this.logger.trace("starting the web themes controller"),this.bridge=t.bridge;const n=this.toApi();e.themes=n,this.logger.trace("themes are ready")}handlePlatformShutdown(){this.registry.clear(),this.activeThemeSubs=0,this.themesSubscription?.close(),delete this.themesSubscription}async handleBridgeMessage(){}toApi(){const e={getCurrent:this.getCurrent.bind(this),list:this.list.bind(this),select:this.select.bind(this),onChanged:this.onChanged.bind(this)};return Object.freeze(e)}async getCurrent(){return(await this.bridge.send("themes",Ts.getCurrent,void 0,void 0,{includeOperationCheck:!0})).theme}async list(){return(await this.bridge.send("themes",Ts.list,void 0,void 0,{includeOperationCheck:!0})).themes}async select(e){m(Ee,e),await this.bridge.send("themes",Ts.select,{name:e},void 0,{includeOperationCheck:!0})}async onChanged(e){if("function"!=typeof e)return f.raiseError("onChanged requires a callback of type function");const t=this.themesSubscription?Promise.resolve():this.configureThemeSubscription();await t,++this.activeThemeSubs;const n=this.registry.add("on-theme-change",e);return()=>this.themeUnsub(n)}async configureThemeSubscription(){this.themesSubscription||(this.themesSubscription=await this.bridge.createNotificationsSteam(),this.themesSubscription.onData((e=>{const t=e.data,n=di.run(t);if(!n.ok)return void this.logger.warn(`Received invalid theme data on the theme event stream: ${JSON.stringify(n.error)}`);const i=n.result;this.registry.execute("on-theme-change",i.theme)})),this.themesSubscription.onClosed((()=>{this.logger.warn("The Themes interop stream was closed, no theme changes notifications will be received"),this.registry.clear(),this.activeThemeSubs=0,delete this.themesSubscription})))}themeUnsub(e){e(),--this.activeThemeSubs,this.activeThemeSubs||(this.themesSubscription?.close(),delete this.themesSubscription)}}class As{sessionStorage=window.sessionStorage;windowId;get allNamespaces(){return[{namespace:this.windowNamespace,defaultValue:{}}]}configure(e){this.windowId=e.windowId,this.allNamespaces.forEach((({namespace:e,defaultValue:t})=>{this.sessionStorage.getItem(e)||this.sessionStorage.setItem(e,JSON.stringify(t))}))}get windowNamespace(){return`io_connect_window_${this.windowId}`}getWindowData(){return JSON.parse(this.sessionStorage.getItem(this.windowNamespace))}setWindowData(e,t){const n=this.getWindowData();n[t]=e,this.sessionStorage.setItem(this.windowNamespace,JSON.stringify(n))}}const Ps={clear:{name:"clear",dataDecoder:Oi},clearAll:{name:"clearAll"},get:{name:"get",dataDecoder:Oi,resultDecoder:Ei},getAll:{name:"getAll",resultDecoder:Di},set:{name:"set",dataDecoder:ji},update:{name:"update",dataDecoder:ji},prefsChanged:{name:"prefsChanged",dataDecoder:Ei},prefsHello:{name:"prefsHello",resultDecoder:Ni}};class Ms{bridge;config;logger;appManagerController;platformAppName;registry=Gi();validNonExistentApps;handlePlatformShutdown(){this.registry.clear()}async start(e,t){this.logger=e.logger.subLogger("prefs.controller.web"),this.logger.trace("starting the web prefs controller"),this.addOperationsExecutors(),this.bridge=t.bridge,this.config=t.config,this.appManagerController=t.appManagerController;try{const e=await this.bridge.send("prefs",Ps.prefsHello,void 0,void 0,{includeOperationCheck:!0});this.platformAppName=e.platform.app,this.validNonExistentApps=e.validNonExistentApps??[]}catch(e){return void this.logger.warn("The platform of this client is outdated and does not support Prefs API.")}this.logger.trace("no need for platform registration, attaching the prefs property to glue and returning");const n=this.toApi();e.prefs=n}async handleBridgeMessage(e){const t=m(Pi,e.operation),n=Ps[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=m(n.dataDecoder,e.data)),await n.execute(i)}async get(e){const t=null==e?this.getMyAppName():m(Ee,e),{prefs:n}=await this.bridge.send("prefs",Ps.get,{app:t},void 0,{includeOperationCheck:!0});return n}async update(e,t){const n=m(N(Oi),t),i=n?.app??this.getMyAppName();await this.updateFor(i,e)}addOperationsExecutors(){Ps.prefsChanged.execute=this.handleOnChanged.bind(this)}toApi(){return{clear:this.clear.bind(this),clearAll:this.clearAll.bind(this),clearFor:this.clearFor.bind(this),get:this.get.bind(this),getAll:this.getAll.bind(this),set:this.set.bind(this),setFor:this.setFor.bind(this),subscribe:this.subscribe.bind(this),subscribeFor:this.subscribeFor.bind(this),update:this.update.bind(this),updateFor:this.updateFor.bind(this)}}async clear(){const e=this.getMyAppName();await this.clearFor(e)}async clearAll(){await this.bridge.send("prefs",Ps.clearAll,void 0,void 0,{includeOperationCheck:!0})}async clearFor(e){const t=m(Ee,e);await this.bridge.send("prefs",Ps.clear,{app:t},void 0,{includeOperationCheck:!0})}async getAll(){return await this.bridge.send("prefs",Ps.getAll,void 0,void 0,{includeOperationCheck:!0})}async set(e,t){const n=m(N(Oi),t),i=n?.app??this.getMyAppName();await this.setFor(i,e)}async setFor(e,t){const n=m(Ee,e),i=m(D(),t);await this.bridge.send("prefs",Ps.set,{app:n,data:i},void 0,{includeOperationCheck:!0})}subscribe(e){const t=this.getMyAppName();return this.subscribeFor(t,e)}subscribeFor(e,t){const n=m(Ee,e),i=this.appManagerController.getApplications();if(!(n===this.platformAppName||i.some((e=>e.name===n))||this.validNonExistentApps.includes(n)))return f.raiseError(`The provided app name "${e}" is not valid.`);if("function"!=typeof t)return f.raiseError("Cannot subscribe to prefs, because the provided callback is not a function!");const s=this.getSubscriptionKey(n);return this.get(n).then(t),this.registry.add(s,t)}async updateFor(e,t){const n=m(Ee,e),i=m(D(),t);await this.bridge.send("prefs",Ps.update,{app:n,data:i},void 0,{includeOperationCheck:!0})}getMyAppName(){const e=this.config.isPlatformInternal?this.platformAppName:this.appManagerController.me?.application.name;return e||f.raiseError("App Preferences operations can not be executed for windows that do not have app!")}getSubscriptionKey(e){return`prefs-changed-${e}`}async handleOnChanged({prefs:e}){const t=this.getSubscriptionKey(e.app);this.registry.execute(t,e)}}var Os=function(e){return function(e){return!!e&&"object"==typeof e}(e)&&!function(e){var t=Object.prototype.toString.call(e);return"[object RegExp]"===t||"[object Date]"===t||function(e){return e.$$typeof===Es}(e)}(e)};var Es="function"==typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function Ds(e,t){return!1!==t.clone&&t.isMergeableObject(e)?Fs((n=e,Array.isArray(n)?[]:{}),e,t):e;var n}function js(e,t,n){return e.concat(t).map((function(e){return Ds(e,n)}))}function Ns(e){return Object.keys(e).concat(function(e){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(e).filter((function(t){return Object.propertyIsEnumerable.call(e,t)})):[]}(e))}function $s(e,t){try{return t in e}catch(e){return!1}}function Ws(e,t,n){var i={};return n.isMergeableObject(e)&&Ns(e).forEach((function(t){i[t]=Ds(e[t],n)})),Ns(t).forEach((function(s){(function(e,t){return $s(e,t)&&!(Object.hasOwnProperty.call(e,t)&&Object.propertyIsEnumerable.call(e,t))})(e,s)||($s(e,s)&&n.isMergeableObject(t[s])?i[s]=function(e,t){if(!t.customMerge)return Fs;var n=t.customMerge(e);return"function"==typeof n?n:Fs}(s,n)(e[s],t[s],n):i[s]=Ds(t[s],n))})),i}function Fs(e,t,n){(n=n||{}).arrayMerge=n.arrayMerge||js,n.isMergeableObject=n.isMergeableObject||Os,n.cloneUnlessOtherwiseSpecified=Ds;var i=Array.isArray(t);return i===Array.isArray(e)?i?n.arrayMerge(e,t,n):Ws(e,t,n):Ds(t,n)}Fs.all=function(e,t){if(!Array.isArray(e))throw new Error("first argument should be an array");return e.reduce((function(e,n){return Fs(e,n,t)}),{})};var Ls=Li(Fs);const qs=D({bundle:Ee,styles:j(Ee)}),Gs=$(E("directional"),E("default")),Bs=D({type:N(Gs),enable:N(M())}),Us=$(E("top"),E("bottom"),E("left"),E("right")),Hs=$(E("default"),E("compact")),Js=$(E("all"),E("fdc3")),Ks=D({selector:N(Bs),displayMode:N(Js)}),zs=D({channels:N(Ks),position:N(Us),mode:N(Hs),displayInWorkspace:N(M())}),Vs=D({enable:M(),awaitFactory:N(M()),timeout:N(P()),channelSelector:N(Bs),position:N(Us),mode:N(Hs),displayInWorkspace:N(M())}),Qs=$(E("getResources"),E("operationCheck")),Xs=D({origin:Ee}),Ys=D({blockedOrigin:M(),config:N(zs),sources:N(qs)}),Zs=D({widget:N(Ys)}),er={getResources:{name:"getResources",dataDecoder:Xs,resultDecoder:D({resources:Zs})},operationCheck:{name:"operationCheck",dataDecoder:oi,resultDecoder:ri}};class tr{ioc;logger;bridge;config;resources;displayWidget=!1;constructor(e){this.ioc=e}async start(e,t){if(this.logger=e.logger.subLogger("ui.controller.web"),this.logger.trace("starting the ui controller"),this.bridge=t.bridge,this.config=t.config,this.resources=await this.getResources(),!this.resources)return void this.logger.trace("No UI elements to display - platform is not initialized with any UI resources");this.logger.trace(`Received UI resources from platform: ${JSON.stringify(this.resources)}`),this.setDisplayFlags();this.displayWidget?this.displayWidget&&await this.loadWidget():this.logger.trace("No UI elements to display.")}async handleBridgeMessage(e){const t=m(Qs,e.operation),n=er[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=m(n.dataDecoder,e.data)),await n.execute(i)}async showComponents(e){const t=this.displayWidget?this.invokeWidgetFactory(e):Promise.resolve();this.config?.widget?.awaitFactory&&await t}async getResources(){const e={origin:window.origin};try{return(await this.bridge.send("ui",er.getResources,e,void 0,{includeOperationCheck:!0})).resources}catch(e){this.logger.warn(e?.message||JSON.stringify(e))}}async loadWidget(){if(this.logger.trace(`Client is initialized with widget config: ${JSON.stringify(this.config?.widget)}`),!this.resources?.widget?.config||!this.resources.widget.sources)return void f.raiseError("Cannot load widget because sources are not provided");const e=document.createElement("script");e.src=this.resources?.widget.sources.bundle,document.head.appendChild(e),this.resources?.widget?.sources?.styles.forEach((e=>{const t=document.createElement("link");t.rel="stylesheet",t.href=e,document.head.appendChild(t)}))}async invokeWidgetFactory(e){const t=this.config?.widget?.timeout||5e3;await this.ioc.eventsDispatcher.widgetReady(t);const n=Ls({...this.resources?.widget?.config,enable:!0},this.config?.widget||{});this.logger.trace(`IOBrowserWidget factory is available. Invoking it with config: ${JSON.stringify(n)}`),await window.IOBrowserWidget(e,n)}setDisplayFlags(){this.setDisplayWidgetFlag()}setDisplayWidgetFlag(){const e="Widget won't be displayed. Reason: ";if(!this.config?.widget)return void this.logger.trace(`${e} Client is not initialized with 'widget' config`);if(!this.config.widget.enable)return void this.logger.trace(`${e} Client initialized with 'widget: { enable: false }' config`);if(!this.resources?.widget)return void this.logger.trace(`${e} Platform did not provide resources`);if(this.resources.widget.blockedOrigin)return void this.logger.warn(`${e} Platform has blocked client's origin ('${window.location.toString()}')`);if(!this.resources.widget.sources||!this.resources.widget.config)return void this.logger.warn(`${e} Platform did not provide widget sources`);const t=Vs.run(this.config.widget);t.ok?this.displayWidget=!0:this.logger.warn(`${e} invalid widget config. Error: ${t.error}`)}}class nr{_coreGlue;_communicationId;_publicWindowId;_webConfig;_windowsControllerInstance;_appManagerControllerInstance;_layoutsControllerInstance;_notificationsControllerInstance;_intentsControllerInstance;_legacyIntentsHelperInstance;_channelsControllerInstance;_themesControllerInstance;_extensionController;_systemControllerInstance;_bridgeInstance;_eventsDispatcher;_preferredConnectionController;_sessionController;_prefsControllerInstance;_uiController;controllers={windows:this.windowsController,appManager:this.appManagerController,layouts:this.layoutsController,notifications:this.notificationsController,intents:this.intentsController,channels:this.channelsController,system:this.systemController,extension:this.extensionController,themes:this.themesController,prefs:this.prefsController,ui:this.uiController};get communicationId(){return this._communicationId}get publicWindowId(){return this._publicWindowId}get windowsController(){return this._windowsControllerInstance||(this._windowsControllerInstance=new Ki),this._windowsControllerInstance}get uiController(){return this._uiController||(this._uiController=new tr(this)),this._uiController}get appManagerController(){return this._appManagerControllerInstance||(this._appManagerControllerInstance=new es),this._appManagerControllerInstance}get layoutsController(){return this._layoutsControllerInstance||(this._layoutsControllerInstance=new ss),this._layoutsControllerInstance}get themesController(){return this._themesControllerInstance||(this._themesControllerInstance=new Rs),this._themesControllerInstance}get notificationsController(){return this._notificationsControllerInstance||(this._notificationsControllerInstance=new as),this._notificationsControllerInstance}get intentsController(){return this._intentsControllerInstance||(this._intentsControllerInstance=new us),this._intentsControllerInstance}get legacyIntentsHelper(){return this._legacyIntentsHelperInstance||(this._legacyIntentsHelperInstance=new ks(this._coreGlue.logger,this.bridge,this._coreGlue.interop,this.appManagerController,this.windowsController)),this._legacyIntentsHelperInstance}get systemController(){return this._systemControllerInstance||(this._systemControllerInstance=new vs),this._systemControllerInstance}get channelsController(){return this._channelsControllerInstance||(this._channelsControllerInstance=new bs),this._channelsControllerInstance}get prefsController(){return this._prefsControllerInstance||(this._prefsControllerInstance=new Ms),this._prefsControllerInstance}get extensionController(){return this._extensionController||(this._extensionController=new Ss),this._extensionController}get eventsDispatcher(){return this._eventsDispatcher||(this._eventsDispatcher=new _s(this.config)),this._eventsDispatcher}get bridge(){return this._bridgeInstance||(this._bridgeInstance=new Yi(this._coreGlue,this.communicationId)),this._bridgeInstance}get preferredConnectionController(){return this._preferredConnectionController||(this._preferredConnectionController=new xs(this._coreGlue)),this._preferredConnectionController}get sessionController(){return this._sessionController||(this._sessionController=new As),this._sessionController}get config(){return this._webConfig}defineGlue(e){this._coreGlue=e,this._publicWindowId=e.connection.transport.publicWindowId;const t=window.glue42core||window.iobrowser;this._communicationId=e.connection.transport.communicationId||t.communicationId}defineConfig(e){this._webConfig=e}async buildWebWindow(e,t){const n=new Bi(e,t,this.bridge),i=await n.toApi();return{id:e,model:n,api:i}}buildNotification(e,t){return new Cs(e,t)}async buildApplication(e,t){const n=new ns(e,[],this.appManagerController).toApi(),i=t.map((e=>this.buildInstance(e,n)));return n.instances.push(...i),n}buildInstance(e,t){return new ts(e,this.bridge,t).toApi()}}var ir="3.5.0";var sr={STRING:1,NUMBER:2,TIMESTAMP:3,OBJECT:4};function rr(e){return e.type===sr.TIMESTAMP?"timestamp":e.type===sr.NUMBER?"number":e.type===sr.STRING?"string":e.type===sr.OBJECT?"object":"unknown"}function or(e){return e.constructor===Date?"timestamp":"number"==typeof e?"number":"string"==typeof e?"string":"object"==typeof e?"object":"string"}function ar(e){const t={},n=rr(e);if("object"===n){const n=Object.keys(e.value).reduce(((t,n)=>{const i=or(e.value[n]);if("object"===i){const i=cr(e.value[n]);t[n]={type:"object",description:"",context:{},composite:i}}else t[n]={type:i,description:"",context:{}};return t}),{});t.composite=n}return t.name=dr(e.path.join("/")+"/"+e.name),t.type=n,t.description=e.description,t.context={},t}function cr(e){return Object.keys(e).reduce(((t,n)=>{const i=or(e[n]);return t[n]="object"===i?{type:"object",description:"",context:{},composite:cr(e[n])}:{type:i,description:"",context:{}},t}),{})}function dr(e){return void 0!==e&&e.length>0&&"/"!==e[0]?"/"+e:e}function lr(e){return"timestamp"===rr(e)?Date.now():hr(e.value)}function hr(e){return"object"!=typeof e?e:Object.keys(e).reduce(((t,n)=>{const i=e[n];return"object"==typeof i&&i.constructor!==Date?t[n]=hr(i):i.constructor===Date?t[n]=new Date(i).getTime():i.constructor===Boolean?t[n]=i.toString():t[n]=i,t}),{})}function ur(e){return e.reduce(((e,t)=>e.concat(Array.isArray(t)?ur(t):t)),[])}function pr(e){const t=ur(e.root.getAggregateState()),n=t.sort(((e,t)=>e.state?t.state?t.state-e.state:-1:1))[0];const i=function(e){let t="";return e.forEach(((e,n,i)=>{const s=e.path.join(".");n===i.length-1?t+=s+"."+e.name+": "+e.description:t+=s+"."+e.name+": "+e.description+","})),t.length>100?t.slice(0,100)+"...":t}(t);return{description:i,value:n.state}}var gr=(e,t,n)=>{if(null===e||"object"!=typeof e)throw new Error("Missing definition");if(null===t||"object"!=typeof t)throw new Error("Missing parent");if(null===n||"object"!=typeof n)throw new Error("Missing transport")};class mr{definition;system;transport;value;type;path=[];name;description;get repo(){return this.system?.repo}get id(){return`${this.system.path}/${name}`}constructor(e,t,n,i,s){this.definition=e,this.system=t,this.transport=n,this.value=i,this.type=s,gr(e,t,n),this.path=t.path.slice(0),this.path.push(t.name),this.name=e.name,this.description=e.description,n.createMetric(this)}update(e){return this.value=e,this.transport.updateMetric(this)}}class fr extends mr{constructor(e,t,n,i){super(e,t,n,i,sr.NUMBER)}incrementBy(e){this.update(this.value+e)}increment(){this.incrementBy(1)}decrement(){this.incrementBy(-1)}decrementBy(e){this.incrementBy(-1*e)}}class wr extends mr{constructor(e,t,n,i){super(e,t,n,i,sr.OBJECT)}update(e){return this.mergeValues(e),this.transport.updateMetric(this)}mergeValues(e){return Object.keys(this.value).forEach((t=>{void 0!==e[t]&&(this.value[t]=e[t])}))}}class br extends mr{constructor(e,t,n,i){super(e,t,n,i,sr.STRING)}}class yr extends mr{constructor(e,t,n,i){super(e,t,n,i,sr.TIMESTAMP)}now(){this.update(new Date)}}function vr(e,t,n,i,s){if(!t)throw new Error("Repository is required");if(!n)throw new Error("Transport is required");const r=n,o=e,a=s||"",c=t,d=i,l=function e(t){if(!t||!t.parent)return[];const n=e(t.parent);return n.push(t.name),n}(i);let h={};const u=(g="/",((p=l)&&p.length>0?p.join(g):"")+e);var p,g;const m=t.root,f=[],w=[];function b(e,t,n,i){let s={name:""};s="string"==typeof e?{name:e}:e;const r=w.filter((e=>e.name===s.name));if(r.length>0){const e=r[0];if(e.type!==t)throw new Error(`A metric named ${s.name} is already defined with different type.`);return void 0!==n&&e.update(n).catch((()=>{})),e}const o=i(s);return w.push(o),o}const y={get name(){return o},get description(){return a},get repo(){return c},get parent(){return d},path:l,id:u,root:m,get subSystems(){return f},get metrics(){return w},subSystem:function(e,t){if(!e||0===e.length)throw new Error("name is required");const n=f.filter((t=>t.name===e));if(n.length>0)return n[0];const i=vr(e,c,r,y,t);return f.push(i),i},getState:()=>h,setState:function(e,t){h={state:e,description:t},r.updateSystem(y,h)},stringMetric:function(e,t){return b(e,sr.STRING,t,(e=>new br(e,y,r,t)))},timestampMetric:function(e,t){return b(e,sr.TIMESTAMP,t,(e=>new yr(e,y,r,t)))},objectMetric:function(e,t){return b(e,sr.OBJECT,t,(e=>new wr(e,y,r,t)))},numberMetric:function(e,t){return b(e,sr.NUMBER,t,(e=>new fr(e,y,r,t)))},getAggregateState:function(){const e=[];return Object.keys(h).length>0&&e.push({name:o,path:l,state:h.state,description:h.description}),f.forEach((t=>{const n=t.getAggregateState();n.length>0&&e.push(...n)})),e}};return r.createSystem(y),y}class Cr{root;constructor(e,t){t.init(this),this.root=vr("",this,t),this.addSystemMetrics(this.root,e.clickStream||void 0===e.clickStream)}addSystemMetrics(e,t){if("undefined"!=typeof navigator&&e.stringMetric("UserAgent",navigator.userAgent),t&&"undefined"!=typeof document){const t=e.subSystem("ClickStream"),n=e=>{if(!e.target)return;const n=e.target,i=n?n.getAttribute("class")??"":"";t.objectMetric("LastBrowserEvent",{type:"click",timestamp:new Date,target:{className:i,id:n.id,type:"<"+n.tagName.toLowerCase()+">",href:n.href||""}})};t.objectMetric("Page",{title:document.title,page:window.location.href}),document.addEventListener?document.addEventListener("click",n):document.attachEvent("onclick",n)}e.stringMetric("StartTime",(new Date).toString());const n=e.stringMetric("StartURL",""),i=e.stringMetric("AppName","");if("undefined"!=typeof window){if(void 0!==window.location){const e=window.location.href;n.update(e)}void 0!==window.glue42gd&&i.update(window.glue42gd.appName)}}}class Ir{init(e){}createSystem(e){return Promise.resolve()}updateSystem(e,t){return Promise.resolve()}createMetric(e){return Promise.resolve()}updateMetric(e){return Promise.resolve()}}class Sr{api;lastCount=0;initialPublishTimeout=1e4;publishInterval=6e4;system;constructor(e,t,n){this.api=e,this.initialPublishTimeout=t??this.initialPublishTimeout,this.publishInterval=n??this.publishInterval,this.scheduleCollection(),this.system=this.api.subSystem("performance","Performance data published by the web application")}scheduleCollection(){setTimeout((()=>{this.collect(),setInterval((()=>{this.collect()}),this.publishInterval)}),this.initialPublishTimeout)}collect(){try{this.collectMemory(),this.collectEntries()}catch{}}collectMemory(){const e=window.performance.memory;this.system.stringMetric("memory",JSON.stringify({totalJSHeapSize:e.totalJSHeapSize,usedJSHeapSize:e.usedJSHeapSize}))}collectEntries(){const e=window.performance.getEntries();if(e.length<=this.lastCount)return;this.lastCount=e.length;const t=e.map((e=>e.toJSON()));this.system.stringMetric("entries",JSON.stringify(t))}}var _r=e=>{let t;t=e.connection&&"object"==typeof e.connection?function(e,t){if(!e||"object"!=typeof e)throw new Error("Connection is required parameter");let n,i;const s=e=>{r(e.root)},r=e=>{o(e),e.metrics.forEach((e=>{a(e)})),e.subSystems.forEach((e=>{r(e)}))},o=async e=>{if(void 0===e.parent)return;await n;const t={type:"define",metrics:[{name:dr(e.path.join("/")+"/"+e.name+"/State"),type:"object",composite:{Description:{type:"string",description:""},Value:{type:"number",description:""}},description:"System state",context:{}}]};i.send(t)},a=async e=>{const t=d(e);await n;const s={type:"define",metrics:[ar(t)]};i.send(s),void 0!==t.value&&c(t)},c=e=>{if(l()){const t=lr(e),n={type:"publish",values:[{name:dr(e.path.join("/")+"/"+e.name),value:t,timestamp:Date.now()}]};return i.sendFireAndForget(n)}return Promise.resolve()},d=e=>{const t={...e};return"object"==typeof e.value&&null!==e.value&&(t.value={...e.value}),t},l=()=>{try{return(t.canUpdateMetric??(()=>!0))()}catch{return!0}};return{init:r=>{let o;n=new Promise((e=>{o=e})),i=e.domain("metrics"),i.onJoined((e=>{!e&&o&&(o(),o=void 0);const t={type:"define",metrics:[{name:"/State",type:"object",composite:{Description:{type:"string",description:""},Value:{type:"number",description:""}},description:"System state",context:{}}]};i.send(t),e&&s(r)})),i.join({system:t.system,service:t.service,instance:t.instance})},createSystem:o,updateSystem:async(t,s)=>{await n;const r={type:"publish",values:[{name:dr(t.path.join("/")+"/"+t.name+"/State"),value:{Description:s.description,Value:s.state},timestamp:Date.now()}]};i.send(r);const o=pr(t),a={type:"publish",peer_id:e.peerId,values:[{name:"/State",value:{Description:o.description,Value:o.value},timestamp:Date.now()}]};i.send(a)},createMetric:a,updateMetric:async e=>{const t=d(e);await n,c(t)}}}(e.connection,e):new Ir;let n=new Cr(e,t).root;e.disableAutoAppSystem||(n=n.subSystem("App"));const i=function(e){const t=e.subSystem("reporting"),n={name:"features"};let i;const s=(e,s,r)=>{if(void 0===e||""===e)throw new Error("name is mandatory");if(void 0===s||""===s)throw new Error("action is mandatory");if(void 0===r||""===r)throw new Error("payload is mandatory");i?i.update({name:e,action:s,payload:r}):i=t.objectMetric(n,{name:e,action:s,payload:r})};return e.featureMetric=s,e}(n);return function(e,t){if("undefined"==typeof window)return;const n=window?.glue42gd?.metrics?.pagePerformanceMetrics;n&&(t=n);t?.enabled&&new Sr(e,t.initialPublishTimeout,t.publishInterval)}(i,e.pagePerformanceMetrics),i};var xr="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function kr(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Tr(e){if(e&&e.errorHandling&&"function"!=typeof e.errorHandling&&"log"!==e.errorHandling&&"silent"!==e.errorHandling&&"throw"!==e.errorHandling)throw new Error('Invalid options passed to createRegistry. Prop errorHandling should be ["log" | "silent" | "throw" | (err) => void], but '+typeof e.errorHandling+" was passed");var t=e&&"function"==typeof e.errorHandling&&e.errorHandling,n={};function i(n,i){var s=n instanceof Error?n:new Error(n);if(t)t(s);else{var r='[ERROR] callback-registry: User callback for key "'+i+'" failed: '+s.stack;if(e)switch(e.errorHandling){case"log":return console.error(r);case"silent":return;case"throw":throw new Error(r)}console.error(r)}}return{add:function(e,t,s){var r=n[e];return r||(r=[],n[e]=r),r.push(t),s&&setTimeout((function(){s.forEach((function(s){var r;if(null===(r=n[e])||void 0===r?void 0:r.includes(t))try{Array.isArray(s)?t.apply(void 0,s):t.apply(void 0,[s])}catch(t){i(t,e)}}))}),0),function(){var i=n[e];i&&(0===(i=i.reduce((function(e,n,i){return n===t&&e.length===i||e.push(n),e}),[])).length?delete n[e]:n[e]=i)}},execute:function(e){for(var t=[],s=1;s<arguments.length;s++)t[s-1]=arguments[s];var r=n[e];if(!r||0===r.length)return[];var o=[];return r.forEach((function(n){try{var s=n.apply(void 0,t);o.push(s)}catch(t){o.push(void 0),i(t,e)}})),o},clear:function(){n={}},clearKey:function(e){n[e]&&delete n[e]}}}Tr.default=Tr;var Rr=kr(Tr);class Ar{gw;registry=Rr();client;constructor(e,t){this.gw=e.facade,this.gw.connect(((e,t)=>{this.messageHandler(t)})).then((e=>{this.client=e}))}get isObjectBasedTransport(){return!0}sendObject(e){return this.client?(this.client.send(e),Promise.resolve(void 0)):Promise.reject("not connected")}send(e){return Promise.reject("not supported")}onMessage(e){return this.registry.add("onMessage",e)}onConnectedChanged(e){return e(!0),()=>{}}close(){return Promise.resolve()}open(){return Promise.resolve()}name(){return"in-memory"}reconnect(){return Promise.resolve()}messageHandler(e){this.registry.execute("onMessage",e)}}class Pr{logger;worker;registry=Rr();constructor(e,t){this.logger=t,this.worker=new SharedWorker(e),this.worker.port.onmessage=e=>{this.messageHandler(e.data)}}get isObjectBasedTransport(){return!0}sendObject(e){return this.worker.port.postMessage(e),Promise.resolve()}send(e){return Promise.reject("not supported")}onMessage(e){return this.registry.add("onMessage",e)}onConnectedChanged(e){return e(!0),()=>{}}close(){return Promise.resolve()}open(){return Promise.resolve()}name(){return"shared-worker"}reconnect(){return Promise.resolve()}messageHandler(e){this.registry.execute("onMessage",e)}}class Mr{static isNode(){if(void 0!==Mr._isNode)return Mr._isNode;if("undefined"!=typeof window)return Mr._isNode=!1,!1;try{Mr._isNode="[object process]"===Object.prototype.toString.call(global.process)}catch(e){Mr._isNode=!1}return Mr._isNode}static _isNode}class Or{static delay(e){return new Promise((t=>setTimeout(t,e)))}resolve;reject;promise;rejected=!1;resolved=!1;get ended(){return this.rejected||this.resolved}constructor(){this.promise=new Promise(((e,t)=>{this.resolve=t=>{this.resolved=!0,e(t)},this.reject=e=>{this.rejected=!0,t(e)}}))}}const Er={};function Dr(e){const t=Er[e];if(t)return t;const n=[];function i(){return(new Date).getTime()}const s=i();let r,o;function a(e,t){const s=t??i();let r=0;n.length>0&&(r=s-n[n.length-1].time),n.push({name:e,time:s,diff:r})}a("start",s);const c={get startTime(){return s},get endTime(){return r},get period(){return o},stop:function(){return r=i(),a("end",r),o=r-s,o},mark:a,marks:n};return Er[e]=c,c}const jr=Mr.isNode()?null:window.WebSocket;class Nr{ws;logger;settings;startupTimer=Dr("connection");_running=!0;_registry=Rr();wsRequests=[];constructor(e,t){if(this.settings=e,this.logger=t,!this.settings.ws)throw new Error("ws is missing")}onMessage(e){return this._registry.add("onMessage",e)}send(e,t){return new Promise(((t,n)=>{this.waitForSocketConnection((()=>{try{this.ws?.send(e),t()}catch(e){n(e)}}),n)}))}open(){return this.logger.info("opening ws..."),this._running=!0,new Promise(((e,t)=>{this.waitForSocketConnection(e,t)}))}close(){return this._running=!1,this.ws&&this.ws.close(),Promise.resolve()}onConnectedChanged(e){return this._registry.add("onConnectedChanged",e)}name(){return this.settings.ws}reconnect(){this.ws?.close();const e=new Or;return this.waitForSocketConnection((()=>{e.resolve()})),e.promise}waitForSocketConnection(e,t){t=t??(()=>{}),this._running?1!==this.ws?.readyState?(this.wsRequests.push({callback:e,failed:t}),this.wsRequests.length>1||this.openSocket()):e():t(`wait for socket on ${this.settings.ws} failed - socket closed by user`)}async openSocket(e,t){if(this.logger.info(`opening ws to ${this.settings.ws}, retryInterval: ${e}, retriesLeft: ${t}...`),this.startupTimer.mark("opening-socket"),void 0===e&&(e=this.settings.reconnectInterval),void 0===t&&(t=this.settings.reconnectAttempts),void 0!==t){if(0===t)return void this.notifyForSocketState(`wait for socket on ${this.settings.ws} failed - no more retries left`);this.logger.debug(`will retry ${t} more times (every ${e} ms)`)}try{await this.initiateSocket(),this.startupTimer.mark("socket-initiated"),this.notifyForSocketState()}catch{setTimeout((()=>{const n=void 0===t?void 0:t-1;this.openSocket(e,n)}),e)}}initiateSocket(){const e=new Or;return this.logger.debug(`initiating ws to ${this.settings.ws}...`),this.ws=new jr(this.settings.ws??""),this.ws.onerror=t=>{let n="";try{n=JSON.stringify(t)}catch(e){const i=new WeakSet,s=(e,t)=>{if("object"==typeof t&&null!==t){if(i.has(t))return;i.add(t)}return t};n=JSON.stringify(t,s)}this.logger.info(`ws error - reason: ${n}`),e.reject("error"),this.notifyStatusChanged(!1,n)},this.ws.onclose=t=>{this.logger.info(`ws closed - code: ${t?.code} reason: ${t?.reason}`),e.reject("closed"),this.notifyStatusChanged(!1)},this.ws.onopen=()=>{this.startupTimer.mark("ws-opened"),this.logger.info(`ws opened ${this.settings.identity?.application}`),e.resolve(),this.notifyStatusChanged(!0)},this.ws.onmessage=e=>{this._registry.execute("onMessage",e.data)},e.promise}notifyForSocketState(e){this.wsRequests.forEach((t=>{e?t.failed&&t.failed(e):t.callback()})),this.wsRequests=[]}notifyStatusChanged(e,t){this._registry.execute("onConnectedChanged",e,t)}}class $r{specs;specsNames=[];messages={};isDone;subs={};subsRefCount={};connection;constructor(e){this.specs={};for(const t of e)this.specs[t.name]=t,this.specsNames.push(t.name)}init(e){this.connection=e;for(const t of this.specsNames)for(const n of this.specs[t].types){let t=this.subsRefCount[n];if(t||(t=0),t+=1,this.subsRefCount[n]=t,t>1)continue;const i=e.on(n,(e=>this.processMessage(n,e)));this.subs[n]=i}}processMessage(e,t){if(!this.isDone&&t)for(const n of this.specsNames)if(-1!==this.specs[n].types.indexOf(e)){const e=this.messages[n]||[];this.messages[n]=e,e.push(t)}}drain(e,t){t&&(this.messages[e]||[]).forEach(t),delete this.messages[e];for(const t of this.specs[e].types)this.subsRefCount[t]-=1,this.subsRefCount[t]<=0&&(this.connection?.off(this.subs[t]),delete this.subs[t],delete this.subsRefCount[t]);delete this.specs[e],this.specs.length||(this.isDone=!0)}}let Wr=(e=21)=>{let t="",n=e;for(;n--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return t};const Fr=(e,t,n)=>new Promise(((i,s)=>{const r=setTimeout((()=>{s(n||`Promise timeout hit: ${t}`)}),t);new Promise(e).then((e=>{clearTimeout(r),i(e)})).catch((e=>{clearTimeout(r),s(e)}))}));class Lr{settings;logger;identity;isPreferredActivated;_communicationId;publicWindowId;selfAssignedWindowId;iAmConnected=!1;parentReady=!1;rejected=!1;parentPingResolve;parentPingInterval;connectionResolve;extConnectionResolve;extConnectionReject;connectionReject;port;myClientId;children=[];extContentAvailable=!1;extContentConnecting=!1;extContentConnected=!1;parentWindowId;parentInExtMode=!1;webNamespace="g42_core_web";parent;parentType;parentPingTimeout=5e3;connectionRequestTimeout=7e3;defaultTargetString="*";registry=Rr();messages={connectionAccepted:{name:"connectionAccepted",handle:this.handleConnectionAccepted.bind(this)},connectionRejected:{name:"connectionRejected",handle:this.handleConnectionRejected.bind(this)},connectionRequest:{name:"connectionRequest",handle:this.handleConnectionRequest.bind(this)},parentReady:{name:"parentReady",handle:()=>{}},parentPing:{name:"parentPing",handle:this.handleParentPing.bind(this)},platformPing:{name:"platformPing",handle:this.handlePlatformPing.bind(this)},platformReady:{name:"platformReady",handle:this.handlePlatformReady.bind(this)},clientUnload:{name:"clientUnload",handle:this.handleClientUnload.bind(this)},manualUnload:{name:"manualUnload",handle:this.handleManualUnload.bind(this)},extConnectionResponse:{name:"extConnectionResponse",handle:this.handleExtConnectionResponse.bind(this)},extSetupRequest:{name:"extSetupRequest",handle:this.handleExtSetupRequest.bind(this)},gatewayDisconnect:{name:"gatewayDisconnect",handle:this.handleGatewayDisconnect.bind(this)},gatewayInternalConnect:{name:"gatewayInternalConnect",handle:this.handleGatewayInternalConnect.bind(this)}};constructor(e,t,n){this.settings=e,this.logger=t,this.identity=n,this.extContentAvailable=!!window.glue42ext,this.setUpMessageListener(),this.setUpUnload(),this.setupPlatformUnloadListener(),this.parentType=window.name.includes("#wsp")?"workspace":void 0}manualSetReadyState(){this.iAmConnected=!0,this.parentReady=!0}get transportWindowId(){return this.publicWindowId}get communicationId(){return this._communicationId}async sendObject(e){if(this.extContentConnected)return window.postMessage({glue42ExtOut:e},this.defaultTargetString);if(!this.port)throw new Error("Cannot send message, because the port was not opened yet");this.port.postMessage(e)}get isObjectBasedTransport(){return!0}onMessage(e){return this.registry.add("onMessage",e)}send(){return Promise.reject("not supported")}onConnectedChanged(e){return this.registry.add("onConnectedChanged",e)}async open(){this.logger.debug("opening a connection to the web platform gateway."),await this.connect(),this.notifyStatusChanged(!0)}close(){const e={glue42core:{type:this.messages.gatewayDisconnect.name,data:{clientId:this.myClientId,ownWindowId:this.identity?.windowId}}};return this.port?.postMessage(e),this.parentReady=!1,this.notifyStatusChanged(!1,"manual reconnection"),Promise.resolve()}name(){return"web-platform"}async reconnect(){return await this.close(),Promise.resolve()}initiateInternalConnection(){return new Promise(((e,t)=>{this.logger.debug("opening an internal web platform connection"),this.port=this.settings.port,this.iAmConnected?this.logger.warn("cannot open a new connection, because this client is currently connected"):(this.port.onmessage=n=>{if(this.iAmConnected&&!n.data?.glue42core)return void this.registry.execute("onMessage",n.data);const i=n.data?.glue42core;i&&(i.type===this.messages.gatewayInternalConnect.name&&i.success&&(this.publicWindowId=this.settings.windowId,this.identity&&this.publicWindowId&&(this.identity.windowId=this.publicWindowId,this.identity.instance=this.publicWindowId),e()),i.type===this.messages.gatewayInternalConnect.name&&i.error&&t(i.error))},this.port.postMessage({glue42core:{type:this.messages.gatewayInternalConnect.name}}))}))}initiateRemoteConnection(e){return Fr(((t,n)=>{this.connectionResolve=t,this.connectionReject=n,this.myClientId=this.myClientId??Wr(10);const i=this.getMyWindowId()||Wr(10),s={glue42core:{type:this.messages.connectionRequest.name,clientId:this.myClientId,clientType:"child",bridgeInstanceId:i,selfAssignedWindowId:this.selfAssignedWindowId}};if(this.logger.debug("sending connection request"),this.extContentConnecting)return s.glue42core.clientType="child",s.glue42core.bridgeInstanceId=this.myClientId,s.glue42core.parentWindowId=this.parentWindowId,window.postMessage(s,this.defaultTargetString);if(!e)throw new Error("Cannot send a connection request, because no glue target was specified!");e.postMessage(s,this.defaultTargetString)}),this.connectionRequestTimeout,"The connection to the target glue window timed out")}async isParentCheckSuccess(e){try{return await e,{success:!0}}catch(e){return{success:!1}}}setUpMessageListener(){this.settings.port?this.logger.debug("skipping generic message listener, because this is an internal client"):window.addEventListener("message",(e=>{const t=e.data?.glue42core;if(!t||this.rejected)return;const n=this.settings.allowedOrigins||[];if(n.length&&!n.includes(e.origin))return void this.logger.warn(`received a message from an origin which is not in the allowed list: ${e.origin}`);if(!this.checkMessageTypeValid(t.type))return void this.logger.error(`cannot handle the incoming glue42 core message, because the type is invalid: ${t.type}`);const i=t.type;this.logger.debug(`received valid glue42core message of type: ${i}`),this.messages[i].handle(e)}))}setUpUnload(){this.settings.port?this.logger.debug("skipping unload event listener, because this is an internal client"):window.addEventListener("beforeunload",(()=>{if(this.extContentConnected)return;const e={glue42core:{type:this.messages.clientUnload.name,data:{clientId:this.myClientId,ownWindowId:this.identity?.windowId}}};this.parent&&this.parent.postMessage(e,this.defaultTargetString),this.port?.postMessage(e)}))}handlePlatformReady(e){this.logger.debug("the web platform gave the ready signal"),this.parentReady=!0,this.parentPingResolve&&(this.parentPingResolve(),delete this.parentPingResolve),this.parentPingInterval&&(clearInterval(this.parentPingInterval),delete this.parentPingInterval),this.parent=e.source,this.parentType=window.name.includes("#wsp")?"workspace":"window"}handleConnectionAccepted(e){const t=e.data?.glue42core;return this.myClientId===t.clientId?this.handleAcceptanceOfMyRequest(t):this.handleAcceptanceOfGrandChildRequest(t,e)}handleAcceptanceOfMyRequest(e){if(this.logger.debug("handling a connection accepted signal targeted at me."),this.isPreferredActivated=e.isPreferredActivated,this.extContentConnecting)return this.processExtContentConnection(e);if(e.port){if(this.publicWindowId=this.getMyWindowId(),this.identity&&(this.identity.windowId=this.publicWindowId,this.identity.instance=this.identity.instance?this.identity.instance:this.publicWindowId||Wr(10)),this.identity&&e.appName&&(this.identity.application=e.appName,this.identity.applicationName=e.appName),this._communicationId=e.communicationId,this.port=e.port,this.port.onmessage=e=>this.registry.execute("onMessage",e.data),this.connectionResolve)return this.logger.debug("my connection is set up, calling the connection resolve."),this.connectionResolve(),void delete this.connectionResolve;this.logger.error("unable to call the connection resolve, because no connection promise was found")}else this.logger.error("cannot set up my connection, because I was not provided with a port")}processExtContentConnection(e){if(this.logger.debug("handling a connection accepted signal targeted at me for extension content connection."),this.extContentConnecting=!1,this.extContentConnected=!0,this.publicWindowId=this.parentWindowId||this.myClientId,this.extContentConnecting&&this.identity&&(this.identity.windowId=this.publicWindowId),this.identity&&e.appName&&(this.identity.application=e.appName,this.identity.applicationName=e.appName),window.addEventListener("message",(e=>{const t=e.data?.glue42ExtInc;if(!t)return;const n=this.settings.allowedOrigins||[];!n.length||n.includes(e.origin)?this.registry.execute("onMessage",t):this.logger.warn(`received a message from an origin which is not in the allowed list: ${e.origin}`)})),this.connectionResolve)return this.logger.debug("my connection is set up, calling the connection resolve."),this.connectionResolve(),void delete this.connectionResolve}handleAcceptanceOfGrandChildRequest(e,t){if(this.extContentConnecting||this.extContentConnected)return void this.logger.debug("cannot process acceptance of a grandchild, because I am connected to a content script");this.logger.debug(`handling a connection accepted signal targeted at a grandchild: ${e.clientId}`);const n=this.children.find((t=>t.grandChildId===e.clientId));n?(n.connected=!0,this.logger.debug(`the grandchild connection for ${e.clientId} is set up, forwarding the success message and the gateway port`),e.parentWindowId=this.publicWindowId,n.source.postMessage(t.data,n.origin,[e.port])):this.logger.error(`cannot handle connection accepted for grandchild: ${e.clientId}, because there is no grandchild with this id`)}handleConnectionRejected(e){if(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)return;const t="string"==typeof e.data.glue42core?.error?`Connection was rejected. ${e.data.glue42core?.error}`:"The platform connection was rejected. Most likely because this window was not created by a glue API call";this.connectionReject(t),delete this.connectionReject}handleConnectionRequest(e){if(this.extContentConnecting)return void this.logger.debug("This connection request event is targeted at the extension content");const t=e.source,n=e.data.glue42core;return n.clientType&&"grandChild"===n.clientType?n.clientId?this.parent?(this.logger.debug(`handling a connection request for a grandchild: ${n.clientId}`),this.children.push({grandChildId:n.clientId,source:t,connected:!1,origin:e.origin}),this.logger.debug(`grandchild: ${n.clientId} is prepared, forwarding connection request to the platform`),void this.parent.postMessage(e.data,this.defaultTargetString)):this.rejectConnectionRequest(t,e.origin,"Cannot forward the connection request, because no direct connection to the platform was found"):this.rejectConnectionRequest(t,e.origin,"rejecting a connection request, because the source did not provide a valid id"):this.rejectConnectionRequest(t,e.origin,"rejecting a connection request, because the source was not opened by a glue API call")}handleParentPing(e){if(!this.parentReady)return void this.logger.debug("my parent is not ready, I am ignoring the parent ping");if(!this.iAmConnected)return void this.logger.debug("i am not fully connected yet, I am ignoring the parent ping");const t={glue42core:{type:this.messages.parentReady.name}};this.extContentConnected&&(t.glue42core.extMode={windowId:this.myClientId});const n=e.source;this.logger.debug("responding to a parent ping with a ready message"),n.postMessage(t,e.origin)}setupPlatformUnloadListener(){this.onMessage((e=>{"platformUnload"===e.type&&(this.logger.debug("detected a web platform unload"),this.parentReady=!1,this.notifyStatusChanged(!1,"Gateway unloaded"))}))}handleManualUnload(){const e={glue42core:{type:this.messages.clientUnload.name,data:{clientId:this.myClientId,ownWindowId:this.identity?.windowId}}};if(this.extContentConnected)return window.postMessage({glue42ExtOut:e},this.defaultTargetString);this.port?.postMessage(e)}handleClientUnload(e){const t=e.data.glue42core,n=t?.data.clientId;if(!n)return void this.logger.warn("cannot process grand child unload, because the provided id was not valid");this.children.find((e=>e.grandChildId===n))?(this.logger.debug(`handling grandchild unload for id: ${n}`),this.children=this.children.filter((e=>e.grandChildId!==n))):this.logger.warn("cannot process grand child unload, because this client is unaware of this grandchild")}handlePlatformPing(){}notifyStatusChanged(e,t){this.iAmConnected=e,this.registry.execute("onConnectedChanged",e,t)}checkMessageTypeValid(e){return"string"==typeof e&&!!this.messages[e]}rejectConnectionRequest(e,t,n){this.rejected=!0,this.logger.error(n);const i={glue42core:{type:this.messages.connectionRejected.name}};e.postMessage(i,t)}requestConnectionPermissionFromExt(){return this.waitForContentScript().then((()=>Fr(((e,t)=>{this.extConnectionResolve=e,this.extConnectionReject=t;this.logger.debug("permission request to the extension content script was sent"),window.postMessage({glue42core:{type:"extSetupRequest"}},this.defaultTargetString)}),this.parentPingTimeout,"Cannot initialize glue, because this app was not opened or created by a Glue Client and the request for extension connection timed out")))}handleExtConnectionResponse(e){const t=e.data?.glue42core;if(!t.approved)return this.extConnectionReject?this.extConnectionReject("Cannot initialize glue, because this app was not opened or created by a Glue Client and the request for extension connection was rejected"):void 0;this.extConnectionResolve&&(this.extConnectionResolve(),delete this.extConnectionResolve),this.extContentConnecting=!0,this.parentType="extension",this.logger.debug("The extension connection was approved, proceeding.")}handleExtSetupRequest(){}handleGatewayDisconnect(){}handleGatewayInternalConnect(){}waitForContentScript(){return!!window.glue42ext?.content?Promise.resolve():Fr((e=>{window.addEventListener("Glue42EXTReady",(()=>{e()}))}),this.connectionRequestTimeout,"The content script was available, but was never heard to be ready")}async connect(){if(this.settings.port)return await this.initiateInternalConnection(),void this.logger.debug("internal web platform connection completed");this.logger.debug("opening a client web platform connection"),await this.findParent(),await this.initiateRemoteConnection(this.parent),this.logger.debug("the client is connected")}async findParent(){const e="Cannot initiate glue, because this window was not opened or created by a glue client",t=this.getPossibleParentsInWindow(window),n=this.getPossibleParentsOutsideWindow(window.top?.opener,window.top),i=new Set([...t,...n]);if(!i.size&&!this.extContentAvailable)throw new Error(e);if(!i.size&&this.extContentAvailable)return void await this.requestConnectionPermissionFromExt();if((await this.isParentCheckSuccess(this.confirmParent(Array.from(i)))).success)this.logger.debug("The default parent was found!");else{if(!this.extContentAvailable)throw new Error(e);await this.requestConnectionPermissionFromExt()}}getPossibleParentsInWindow(e){return e?.parent&&e!==e.parent?[e.parent,...this.getPossibleParentsInWindow(e.parent)]:[]}getPossibleParentsOutsideWindow(e,t){return e&&t&&e!==t?[e,...this.getPossibleParentsInWindow(e),...this.getPossibleParentsOutsideWindow(e.opener,e)]:[]}confirmParent(e){const t=Fr((t=>{this.parentPingResolve=t;const n={glue42core:{type:this.messages.platformPing.name}};this.parentPingInterval=setInterval((()=>{e.forEach((e=>{e.postMessage(n,this.defaultTargetString)}))}),1e3)}),this.parentPingTimeout,"Cannot initiate glue, because this window was not opened or created by a glue client");return t.catch((()=>{this.parentPingInterval&&(clearInterval(this.parentPingInterval),delete this.parentPingInterval)})),t}getMyWindowId(){return"workspace"===this.parentType?window.name.substring(0,window.name.indexOf("#wsp")):window===window.top?window.name?.includes("g42")?window.name:(this.selfAssignedWindowId=this.selfAssignedWindowId||`g42-${Wr(10)}`,this.selfAssignedWindowId):void 0}}class qr{minSequenceInterval;queue=[];isExecutingQueue=!1;constructor(e=0){this.minSequenceInterval=e}enqueue(e){return new Promise(((t,n)=>{this.queue.push({action:e,resolve:t,reject:n}),this.executeQueue()}))}async executeQueue(){if(!this.isExecutingQueue){for(this.isExecutingQueue=!0;this.queue.length;){const e=this.queue.shift();if(!e)return void(this.isExecutingQueue=!1);try{const t=await e.action();e.resolve(t)}catch(t){e.reject(t)}await this.intervalBreak()}this.isExecutingQueue=!1}}intervalBreak(){return new Promise((e=>setTimeout(e,this.minSequenceInterval)))}}function Gr(e,t,n,i,s){null==e&&(e="global"),i=i??["success"],s=s??["error"];let r,o="global"===e,a=!1,c=!1;const d=Rr();t.disconnected((function(){c=!1,n.debug("connection is down"),o=!1,a=!0,d.execute("onLeft",{disconnected:!0})})),t.loggedIn((function(){c=!0,a&&(n.debug("connection is now up - trying to reconnect..."),h(r))})),t.on("success",(e=>g(e))),t.on("error",(e=>p(e))),t.on("result",(e=>g(e))),i&&i.forEach((e=>{t.on(e,(e=>g(e)))})),s&&s.forEach((e=>{t.on(e,(e=>p(e)))}));const l={};function h(t){return r=t,new Promise(((i,s)=>{if(o)return void i({});let r;if("global"===e)r=c?Promise.resolve({}):Promise.reject("not connected to gateway");else{n.debug(`joining domain ${e}`);r=w({type:"join",destination:e,domain:"global",options:t})}r.then((()=>{!function(){n.debug("did join "+e),o=!0;const t=a;a=!1,d.execute("onJoined",t)}(),i({})})).catch((t=>{n.debug("error joining "+e+" domain: "+JSON.stringify(t)),s(t)}))}))}function u(e){return o&&e(!1),d.add("onJoined",e)}function p(t){if(e!==t.domain)return;const n=t.request_id;if(!n)return;const i=l[n];i&&i.error(t)}function g(t){if(t.domain!==e)return;const n=t.request_id;if(!n)return;const i=l[n];i&&i.success(t)}function m(){return Wr(10)}let f=[];function w(i,s,r){if(i.type&&-1===["hello","join"].indexOf(i.type)&&!o){console.warn(`trying to send a message (${i.domain} ${i.type}) but not connected, will queue`);const e=new Or;if(f.push({msg:i,tag:s,options:r,pw:e}),1===f.length){const e=u((()=>{n.info(`joined - will now send queued messages (${f.length} -> [${f.map((e=>e.msg.type))}])`),f.forEach((e=>{w(e.msg,e.tag,e.options).then((t=>e.pw.resolve(t))).catch((t=>e.pw.reject(t)))})),f=[],e()}))}return e.promise}r=r??{},i.request_id=i.request_id??m(),i.domain=i.domain??e,r.skipPeerId||(i.peer_id=t.peerId);const a=i.request_id;return new Promise(((e,o)=>{l[a]={success:t=>{delete l[a],t._tag=s,e(t)},error:e=>{n.warn(`Gateway error - ${JSON.stringify(e)}`),delete l[a],e._tag=s,o(e)}},t.send(i,r).catch((e=>{l[a].error({err:e})}))}))}return{join:h,leave:function(){return"global"===e?Promise.resolve():(n.debug("stopping session "+e+"..."),a=!1,w({type:"leave",destination:e,domain:"global"}).then((()=>{o=!1,d.execute("onLeft")})).catch((()=>{o=!1,d.execute("onLeft")})))},onJoined:u,onLeft:function(e){return o||e(),d.add("onLeft",e)},send:w,sendFireAndForget:function(n){return n.request_id=n.request_id?n.request_id:m(),n.domain=n.domain??e,n.peer_id=t.peerId,t.send(n)},on:(i,s)=>{t.on(i,(t=>{if(t.domain===e)try{s(t)}catch(e){n.error(`Callback failed: ${e} \n ${e.stack} \n msg was: ${JSON.stringify(t)}`,e)}}))},loggedIn:e=>t.loggedIn(e),connected:e=>t.connected(e),disconnected:e=>t.disconnected(e),get peerId(){return t.peerId},get domain(){return e}}}class Br{settings;logger;protocolVersion=3;peerId;token;info;resolvedIdentity;availableDomains;gatewayToken;replayer;messageHandlers={};ids=1;registry=Rr();_connected=!1;isTrace=!1;transport;_defaultTransport;_defaultAuth;_targetTransport;_targetAuth;_swapTransport=!1;_switchInProgress=!1;_transportSubscriptions=[];datePrefix="#T42_DATE#";datePrefixLen=this.datePrefix.length;dateMinLen=this.datePrefixLen+1;datePrefixFirstChar=this.datePrefix[0];_sequelizer=new qr;_isLoggedIn=!1;shouldTryLogin=!0;pingTimer;sessions=[];globalDomain;initialLogin=!0;initialLoginAttempts=3;loginConfig;constructor(e,t){if(this.settings=e,this.logger=t,(e=e||{}).reconnectAttempts=e.reconnectAttempts??10,e.reconnectInterval=e.reconnectInterval??1e3,e.inproc)this.transport=new Ar(e.inproc,t.subLogger("inMemory"));else if(e.sharedWorker)this.transport=new Pr(e.sharedWorker,t.subLogger("shared-worker"));else if(e.webPlatform)this.transport=new Lr(e.webPlatform,t.subLogger("web-platform"),e.identity);else{if(void 0===e.ws)throw new Error("No connection information specified");this.transport=new Nr(e,t.subLogger("ws"))}this.isTrace=t.canPublish("trace"),t.debug(`starting with ${this.transport.name()} transport`);const 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,this.ping()}async switchTransport(e){return this._sequelizer.enqueue((async()=>{if(!e||"object"!=typeof e)throw new Error("Cannot switch transports, because the settings are missing or invalid.");if(void 0===e.type)throw new Error("Cannot switch the transport, because the type is not defined");this.logger.trace(`Starting transport switch with settings: ${JSON.stringify(e)}`);const t="secondary"===e.type?this.getNewSecondaryTransport(e):this._defaultTransport;this._targetTransport=t,this._targetAuth="secondary"===e.type?this.getNewSecondaryAuth(e):this._defaultAuth;const n=this.verifyConnection();this._swapTransport=!0,this._switchInProgress=!0,this.logger.trace("The new transport has been set, closing the current transport"),await this.transport.close();try{await n;const e=this.transport===t;return this.logger.info(`The reconnection after the switch was completed. Was the switch a success: ${e}`),this._switchInProgress=!1,{success:e}}catch(e){return this.logger.info("The reconnection after the switch timed out, reverting back to the default transport."),this.switchTransport({type:"default"}),this._switchInProgress=!1,{success:!1}}}))}onLibReAnnounced(e){return this.registry.add("libReAnnounced",e)}setLibReAnnounced(e){this.registry.execute("libReAnnounced",e)}send(e,t){if(this.transport.sendObject&&this.transport.isObjectBasedTransport){const n=this.createObjectMessage(e);return this.isTrace&&this.logger.trace(`>> ${JSON.stringify(n)}`),this.transport.sendObject(n,t)}{const n=this.createStringMessage(e);return this.isTrace&&this.logger.trace(`>> ${n}`),this.transport.send(n,t)}}on(e,t){e=e.toLowerCase(),void 0===this.messageHandlers[e]&&(this.messageHandlers[e]={});const n=this.ids++;return this.messageHandlers[e][n]=t,{type:e,id:n}}off(e){delete this.messageHandlers[e.type.toLowerCase()][e.id]}get isConnected(){return this._isLoggedIn}connected(e){return this.loggedIn((()=>{const t=this.transport.name();e(t)}))}disconnected(e){return this.registry.add("disconnected",e)}async login(e,t){if(this._defaultAuth||(this._defaultAuth=e),this._swapTransport){this.logger.trace("Detected a transport swap, swapping transports");e=this.transportSwap()??e}this.logger.trace(`Starting login for transport: ${this.transport.name()} and auth ${JSON.stringify(e)}`);try{await this.transport.open(),this.logger.trace(`Transport: ${this.transport.name()} opened, logging in`),Dr("connection").mark("transport-opened");const n=await this.loginCore(e,t);return this.logger.trace(`Logged in with identity: ${JSON.stringify(n)}`),Dr("connection").mark("protocol-logged-in"),n}catch(e){throw this._switchInProgress&&(this.logger.trace("An error while logging in after a transport swap, preparing a default swap."),this.prepareDefaultSwap()),new Error(e)}}async logout(){await this.logoutCore(),await this.transport.close()}loggedIn(e){return this._isLoggedIn&&e(),this.registry.add("onLoggedIn",e)}domain(e,t,n){let i=this.sessions.find((t=>t.domain===e));return i||(i=Gr(e,this,this.logger.subLogger(`domain=${e}`),t,n),this.sessions.push(i)),i}authToken(){return this.globalDomain?this.globalDomain.send({domain:"global",type:"create-token"}).then((e=>e.token)):Promise.reject(new Error("no global domain session"))}reconnect(){return this.transport.reconnect()}setLoggedIn(e){this._isLoggedIn=e,this._isLoggedIn&&this.registry.execute("onLoggedIn")}distributeMessage(e,t){const n=this.messageHandlers[t.toLowerCase()];void 0!==n&&Object.keys(n).forEach((t=>{const i=n[t];if(void 0!==i)try{i(e)}catch(e){try{this.logger.error(`Message handler failed with ${e.stack}`,e)}catch(t){console.log("Message handler failed",e)}}}))}handleConnectionChanged(e){this._connected!==e&&(this._connected=e,e?(this.settings?.replaySpecs?.length&&(this.replayer=new $r(this.settings.replaySpecs),this.replayer.init(this)),this.registry.execute("connected")):(this.handleDisconnected(),this.registry.execute("disconnected")))}handleDisconnected(){this.setLoggedIn(!1);if(this.shouldTryLogin&&this.initialLogin){if(this.initialLoginAttempts<=0)return;this.initialLoginAttempts--}if(this.logger.debug("disconnected - will try new login?"+this.shouldTryLogin),this.shouldTryLogin){if(!this.loginConfig)throw new Error("no login info");this.login(this.loginConfig,!0).catch((()=>{setTimeout(this.handleDisconnected.bind(this),this.settings.reconnectInterval||1e3)}))}}handleTransportMessage(e){let t;t="string"==typeof e?this.processStringMessage(e):this.processObjectMessage(e),this.isTrace&&this.logger.trace(`<< ${JSON.stringify(t)}`),this.distributeMessage(t.msg,t.msgType)}verifyConnection(){return Fr((e=>{let t;const n=((e,t)=>{let n=e;return()=>{n--,0===n&&t()}})(2,(()=>{t&&t(),e()}));t=this.onLibReAnnounced((e=>"interop"===e.name||"contexts"===e.name?n():void 0))}),1e4,"Transport switch timed out waiting for all libraries to be re-announced")}getNewSecondaryTransport(e){if(!e.transportConfig?.url)throw new Error("Missing secondary transport URL.");return new Nr(Object.assign({},this.settings,{ws:e.transportConfig.url,reconnectAttempts:1}),this.logger.subLogger("ws-secondary"))}getNewSecondaryAuth(e){if(!e.transportConfig?.auth)throw new Error("Missing secondary transport auth information.");return e.transportConfig.auth}transportSwap(){if(this._swapTransport=!1,!this._targetTransport||!this._targetAuth)return void this.logger.warn(`Error while switching transports - either the target transport or auth is not defined: transport defined -> ${!!this._defaultTransport}, auth defined -> ${!!this._targetAuth}. Staying on the current one.`);this._transportSubscriptions.forEach((e=>e())),this._transportSubscriptions=[],this.transport=this._targetTransport;const e=this.transport.onConnectedChanged(this.handleConnectionChanged.bind(this)),t=this.transport.onMessage(this.handleTransportMessage.bind(this));return this._transportSubscriptions.push(e),this._transportSubscriptions.push(t),this._targetAuth}prepareDefaultSwap(){this._transportSubscriptions.forEach((e=>e())),this._transportSubscriptions=[],this.transport.close().catch((e=>this.logger.warn(`Error closing the ${this.transport.name()} transport after a failed connection attempt: ${JSON.stringify(e)}`))),this._targetTransport=this._defaultTransport,this._targetAuth=this._defaultAuth,this._swapTransport=!0}processStringMessage(e){const t=JSON.parse(e,((e,t)=>{if("string"!=typeof t)return t;if(t.length<this.dateMinLen)return t;if(!t.startsWith(this.datePrefixFirstChar))return t;if(t.substring(0,this.datePrefixLen)!==this.datePrefix)return t;try{const e=parseInt(t.substring(this.datePrefixLen,t.length),10);return isNaN(e)?t:new Date(e)}catch(e){return t}}));return{msg:t,msgType:t.type}}createStringMessage(e){const t=Date.prototype.toJSON;try{const t=this.datePrefix;Date.prototype.toJSON=function(){return t+this.getTime()};return JSON.stringify(e)}finally{Date.prototype.toJSON=t}}processObjectMessage(e){if(!e.type)throw new Error("Object should have type property");return{msg:e,msgType:e.type}}createObjectMessage(e){return e}async loginCore(e,t){this.logger.info("logging in..."),this.loginConfig=e,this.loginConfig||(this.loginConfig={username:"",password:""}),this.shouldTryLogin=!0;const n=await this.setupAuthConfig(e,t),i={type:"hello",identity:this.settings.identity,authentication:n};e.sessionId&&(i.request_id=e.sessionId),this.globalDomain=Gr("global",this,this.logger.subLogger("global-domain"),["welcome","token","authentication-request"]);const s={skipPeerId:!0};this.initialLogin&&(s.retryInterval=this.settings.reconnectInterval,s.maxRetries=this.settings.reconnectAttempts);try{const t=await this.tryAuthenticate(this.globalDomain,i,s,e);return this.initialLogin=!1,this.logger.info("login successful with peerId "+t.peer_id),this.peerId=t.peer_id,this.resolvedIdentity=t.resolved_identity,this.availableDomains=t.available_domains,t.options&&(this.token=t.options.access_token,this.info=t.options.info),this.setLoggedIn(!0),t.resolved_identity}catch(e){throw this.logger.error("error sending hello message - "+(e.message||e.msg||e.reason||e),e),e}finally{e?.flowCallback&&e.sessionId&&e.flowCallback(e.sessionId,null)}}async tryAuthenticate(e,t,n,i){let s;for(;;){const r=await e.send(t,void 0,n);if("authentication-request"!==r.type){if("welcome"===r.type){s=r;break}throw"error"===r.type?new Error("Authentication failed: "+r.reason):new Error("Unexpected message type during authentication: "+r.type)}{const e=Buffer.from(r.authentication.token,"base64");i.flowCallback&&i.sessionId&&(t.authentication.token=(await i.flowCallback(i.sessionId,e)).data.toString("base64")),t.request_id=i.sessionId}}return s}async setupAuthConfig(e,t){const n={};if(this.gatewayToken=e.gatewayToken,e.gatewayToken){if(t)try{e.gatewayToken=await this.getNewGWToken()}catch(e){this.logger.warn(`failed to get GW token when reconnecting ${e?.message||e}`)}n.method="gateway-token",n.token=e.gatewayToken,this.gatewayToken=e.gatewayToken}else if("sspi"===e.flowName){if(n.provider="win",n.method="access-token",!e.flowCallback||!e.sessionId)throw new Error("Invalid SSPI config");n.token=(await e.flowCallback(e.sessionId,null)).data.toString("base64")}else if(e.token)n.method="access-token",n.token=e.token;else if(e.username)n.method="secret",n.login=e.username,n.secret=e.password;else{if(!e.provider)throw new Error("invalid auth message"+JSON.stringify(e));n.provider=e.provider,n.providerContext=e.providerContext}return n}async logoutCore(){this.logger.debug("logging out..."),this.shouldTryLogin=!1,this.pingTimer&&clearTimeout(this.pingTimer);const e=this.sessions.map((e=>{e.leave()}));await Promise.all(e)}getNewGWToken(){if("undefined"!=typeof window){const e=window.glue42gd;if(e)return e.getGWToken()}return Promise.reject(new Error("not running in GD"))}ping(){this.shouldTryLogin&&(this._isLoggedIn&&this.send({type:"ping"}),this.pingTimer=setTimeout((()=>{this.ping()}),3e4))}}const Ur=["trace","debug","info","warn","error","off"];class Hr{name;parent;static Interop;static InteropMethodName="T42.AppLogger.Log";static Instance;path;subLoggers=[];_consoleLevel;_publishLevel;loggerFullName;includeTimeAndLevel;logFn=console;customLogFn=!1;constructor(e,t,n){this.name=e,this.parent=t,this.name=e,this.path=t?`${t.path}.${e}`:e,this.loggerFullName=`[${this.path}]`,this.includeTimeAndLevel=!n,n&&(this.logFn=n,this.customLogFn=!0)}subLogger(e){const t=this.subLoggers.filter((t=>t.name===e))[0];if(void 0!==t)return t;Object.keys(this).forEach((t=>{if(t===e)throw new Error("This sub logger name is not allowed.")}));const n=new Hr(e,this,this.customLogFn?this.logFn:void 0);return this.subLoggers.push(n),n}publishLevel(e){return e&&(this._publishLevel=e),this._publishLevel||this.parent?.publishLevel()}consoleLevel(e){return e&&(this._consoleLevel=e),this._consoleLevel||this.parent?.consoleLevel()}log(e,t,n){this.publishMessage(t||"info",e,n)}trace(e){this.log(e,"trace")}debug(e){this.log(e,"debug")}info(e){this.log(e,"info")}warn(e){this.log(e,"warn")}error(e,t){this.log(e,"error",t)}canPublish(e,t){return Ur.indexOf(e)>=Ur.indexOf(t||this.consoleLevel()||"trace")}publishMessage(e,t,n){const i=this.loggerFullName;if("error"===e&&!n){const e=new Error;e.stack&&(t=t+"\n"+e.stack.split("\n").slice(4).join("\n"))}if(this.canPublish(e,this.publishLevel())){const s=Hr.Interop;if(s)try{if(s.methods({name:Hr.InteropMethodName}).length>0){const r={msg:t,logger:i,level:e};n&&n instanceof Error&&(r.error={message:n.message,stack:n.stack??""}),s.invoke(Hr.InteropMethodName,r)}}catch{}}if(this.canPublish(e)){let s="";if(this.includeTimeAndLevel){const t=new Date;s=`[${`${t.getHours()}:${t.getMinutes()}:${t.getSeconds()}:${t.getMilliseconds()}`}] [${e}] `}const r=`${s}${i}: ${t}`;switch(e){case"trace":this.logFn.debug(r);break;case"debug":this.logFn.debug?this.logFn.debug(r):this.logFn.log(r);break;case"info":this.logFn.info(r);break;case"warn":this.logFn.warn(r);break;case"error":this.logFn.error(r,n)}}}}const Jr="create-context",Kr="created",zr="destroyed",Vr="context-created",Qr="context-added",Xr="subscribe-context",Yr="subscribed-context",Zr="unsubscribe-context",eo="destroy-context",to="context-destroyed",no="update-context",io="context-updated",so="joined",ro={get name(){return"context"},get types(){return[Jr,Kr,zr,Vr,Qr,Xr,Yr,Zr,eo,to,no,io,so]}};var oo="6.5.0";class ao{name;contextId;context;isAnnounced;joinedActivity;updateCallbacks={};activityId;sentExplicitSubscription;hasReceivedSnapshot;constructor(e,t,n,i){this.contextId=e,this.name=t,this.isAnnounced=n,this.activityId=i,this.context={}}hasCallbacks(){return Object.keys(this.updateCallbacks).length>0}getState(){return this.isAnnounced&&this.hasCallbacks()?3:this.isAnnounced?2:this.hasCallbacks()?1:0}}var co={exports:{}};!function(e,t){var n="__lodash_hash_undefined__",i=9007199254740991,s="[object Arguments]",r="[object Boolean]",o="[object Date]",a="[object Function]",c="[object GeneratorFunction]",d="[object Map]",l="[object Number]",h="[object Object]",u="[object Promise]",p="[object RegExp]",g="[object Set]",m="[object String]",f="[object Symbol]",w="[object WeakMap]",b="[object ArrayBuffer]",y="[object DataView]",v="[object Float32Array]",C="[object Float64Array]",I="[object Int8Array]",S="[object Int16Array]",_="[object Int32Array]",x="[object Uint8Array]",k="[object Uint8ClampedArray]",T="[object Uint16Array]",R="[object Uint32Array]",A=/\w*$/,P=/^\[object .+?Constructor\]$/,M=/^(?:0|[1-9]\d*)$/,O={};O[s]=O["[object Array]"]=O[b]=O[y]=O[r]=O[o]=O[v]=O[C]=O[I]=O[S]=O[_]=O[d]=O[l]=O[h]=O[p]=O[g]=O[m]=O[f]=O[x]=O[k]=O[T]=O[R]=!0,O["[object Error]"]=O[a]=O[w]=!1;var E="object"==typeof xr&&xr&&xr.Object===Object&&xr,D="object"==typeof self&&self&&self.Object===Object&&self,j=E||D||Function("return this")(),N=t&&!t.nodeType&&t,$=N&&e&&!e.nodeType&&e,W=$&&$.exports===N;function F(e,t){return e.set(t[0],t[1]),e}function L(e,t){return e.add(t),e}function q(e,t,n,i){for(var s=-1,r=e?e.length:0;++s<r;)n=t(n,e[s],s,e);return n}function G(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(e){}return t}function B(e){var t=-1,n=Array(e.size);return e.forEach((function(e,i){n[++t]=[i,e]})),n}function U(e,t){return function(n){return e(t(n))}}function H(e){var t=-1,n=Array(e.size);return e.forEach((function(e){n[++t]=e})),n}var J,K=Array.prototype,z=Function.prototype,V=Object.prototype,Q=j["__core-js_shared__"],X=(J=/[^.]+$/.exec(Q&&Q.keys&&Q.keys.IE_PROTO||""))?"Symbol(src)_1."+J:"",Y=z.toString,Z=V.hasOwnProperty,ee=V.toString,te=RegExp("^"+Y.call(Z).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),ne=W?j.Buffer:void 0,ie=j.Symbol,se=j.Uint8Array,re=U(Object.getPrototypeOf,Object),oe=Object.create,ae=V.propertyIsEnumerable,ce=K.splice,de=Object.getOwnPropertySymbols,le=ne?ne.isBuffer:void 0,he=U(Object.keys,Object),ue=$e(j,"DataView"),pe=$e(j,"Map"),ge=$e(j,"Promise"),me=$e(j,"Set"),fe=$e(j,"WeakMap"),we=$e(Object,"create"),be=Ge(ue),ye=Ge(pe),ve=Ge(ge),Ce=Ge(me),Ie=Ge(fe),Se=ie?ie.prototype:void 0,_e=Se?Se.valueOf:void 0;function xe(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var i=e[t];this.set(i[0],i[1])}}function ke(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var i=e[t];this.set(i[0],i[1])}}function Te(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var i=e[t];this.set(i[0],i[1])}}function Re(e){this.__data__=new ke(e)}function Ae(e,t){var n=Ue(e)||function(e){return function(e){return function(e){return!!e&&"object"==typeof e}(e)&&He(e)}(e)&&Z.call(e,"callee")&&(!ae.call(e,"callee")||ee.call(e)==s)}(e)?function(e,t){for(var n=-1,i=Array(e);++n<e;)i[n]=t(n);return i}(e.length,String):[],i=n.length,r=!!i;for(var o in e)!Z.call(e,o)||r&&("length"==o||Le(o,i))||n.push(o);return n}function Pe(e,t,n){var i=e[t];Z.call(e,t)&&Be(i,n)&&(void 0!==n||t in e)||(e[t]=n)}function Me(e,t){for(var n=e.length;n--;)if(Be(e[n][0],t))return n;return-1}function Oe(e,t,n,i,u,w,P){var M;if(i&&(M=w?i(e,u,w,P):i(e)),void 0!==M)return M;if(!ze(e))return e;var E=Ue(e);if(E){if(M=function(e){var t=e.length,n=e.constructor(t);t&&"string"==typeof e[0]&&Z.call(e,"index")&&(n.index=e.index,n.input=e.input);return n}(e),!t)return function(e,t){var n=-1,i=e.length;t||(t=Array(i));for(;++n<i;)t[n]=e[n];return t}(e,M)}else{var D=Fe(e),j=D==a||D==c;if(Je(e))return function(e,t){if(t)return e.slice();var n=new e.constructor(e.length);return e.copy(n),n}(e,t);if(D==h||D==s||j&&!w){if(G(e))return w?e:{};if(M=function(e){return"function"!=typeof e.constructor||qe(e)?{}:(t=re(e),ze(t)?oe(t):{});var t}(j?{}:e),!t)return function(e,t){return je(e,We(e),t)}(e,function(e,t){return e&&je(t,Ve(t),e)}(M,e))}else{if(!O[D])return w?e:{};M=function(e,t,n,i){var s=e.constructor;switch(t){case b:return De(e);case r:case o:return new s(+e);case y:return function(e,t){var n=t?De(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.byteLength)}(e,i);case v:case C:case I:case S:case _:case x:case k:case T:case R:return function(e,t){var n=t?De(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.length)}(e,i);case d:return function(e,t,n){var i=t?n(B(e),!0):B(e);return q(i,F,new e.constructor)}(e,i,n);case l:case m:return new s(e);case p:return function(e){var t=new e.constructor(e.source,A.exec(e));return t.lastIndex=e.lastIndex,t}(e);case g:return function(e,t,n){var i=t?n(H(e),!0):H(e);return q(i,L,new e.constructor)}(e,i,n);case f:return a=e,_e?Object(_e.call(a)):{}}var a}(e,D,Oe,t)}}P||(P=new Re);var N=P.get(e);if(N)return N;if(P.set(e,M),!E)var $=n?function(e){return function(e,t,n){var i=t(e);return Ue(e)?i:function(e,t){for(var n=-1,i=t.length,s=e.length;++n<i;)e[s+n]=t[n];return e}(i,n(e))}(e,Ve,We)}(e):Ve(e);return function(e,t){for(var n=-1,i=e?e.length:0;++n<i&&!1!==t(e[n],n,e););}($||e,(function(s,r){$&&(s=e[r=s]),Pe(M,r,Oe(s,t,n,i,r,e,P))})),M}function Ee(e){return!(!ze(e)||(t=e,X&&X in t))&&(Ke(e)||G(e)?te:P).test(Ge(e));var t}function De(e){var t=new e.constructor(e.byteLength);return new se(t).set(new se(e)),t}function je(e,t,n,i){n||(n={});for(var s=-1,r=t.length;++s<r;){var o=t[s];Pe(n,o,e[o])}return n}function Ne(e,t){var n,i,s=e.__data__;return("string"==(i=typeof(n=t))||"number"==i||"symbol"==i||"boolean"==i?"__proto__"!==n:null===n)?s["string"==typeof t?"string":"hash"]:s.map}function $e(e,t){var n=function(e,t){return null==e?void 0:e[t]}(e,t);return Ee(n)?n:void 0}xe.prototype.clear=function(){this.__data__=we?we(null):{}},xe.prototype.delete=function(e){return this.has(e)&&delete this.__data__[e]},xe.prototype.get=function(e){var t=this.__data__;if(we){var i=t[e];return i===n?void 0:i}return Z.call(t,e)?t[e]:void 0},xe.prototype.has=function(e){var t=this.__data__;return we?void 0!==t[e]:Z.call(t,e)},xe.prototype.set=function(e,t){return this.__data__[e]=we&&void 0===t?n:t,this},ke.prototype.clear=function(){this.__data__=[]},ke.prototype.delete=function(e){var t=this.__data__,n=Me(t,e);return!(n<0)&&(n==t.length-1?t.pop():ce.call(t,n,1),!0)},ke.prototype.get=function(e){var t=this.__data__,n=Me(t,e);return n<0?void 0:t[n][1]},ke.prototype.has=function(e){return Me(this.__data__,e)>-1},ke.prototype.set=function(e,t){var n=this.__data__,i=Me(n,e);return i<0?n.push([e,t]):n[i][1]=t,this},Te.prototype.clear=function(){this.__data__={hash:new xe,map:new(pe||ke),string:new xe}},Te.prototype.delete=function(e){return Ne(this,e).delete(e)},Te.prototype.get=function(e){return Ne(this,e).get(e)},Te.prototype.has=function(e){return Ne(this,e).has(e)},Te.prototype.set=function(e,t){return Ne(this,e).set(e,t),this},Re.prototype.clear=function(){this.__data__=new ke},Re.prototype.delete=function(e){return this.__data__.delete(e)},Re.prototype.get=function(e){return this.__data__.get(e)},Re.prototype.has=function(e){return this.__data__.has(e)},Re.prototype.set=function(e,t){var n=this.__data__;if(n instanceof ke){var i=n.__data__;if(!pe||i.length<199)return i.push([e,t]),this;n=this.__data__=new Te(i)}return n.set(e,t),this};var We=de?U(de,Object):function(){return[]},Fe=function(e){return ee.call(e)};function Le(e,t){return!!(t=null==t?i:t)&&("number"==typeof e||M.test(e))&&e>-1&&e%1==0&&e<t}function qe(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||V)}function Ge(e){if(null!=e){try{return Y.call(e)}catch(e){}try{return e+""}catch(e){}}return""}function Be(e,t){return e===t||e!=e&&t!=t}(ue&&Fe(new ue(new ArrayBuffer(1)))!=y||pe&&Fe(new pe)!=d||ge&&Fe(ge.resolve())!=u||me&&Fe(new me)!=g||fe&&Fe(new fe)!=w)&&(Fe=function(e){var t=ee.call(e),n=t==h?e.constructor:void 0,i=n?Ge(n):void 0;if(i)switch(i){case be:return y;case ye:return d;case ve:return u;case Ce:return g;case Ie:return w}return t});var Ue=Array.isArray;function He(e){return null!=e&&function(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=i}(e.length)&&!Ke(e)}var Je=le||function(){return!1};function Ke(e){var t=ze(e)?ee.call(e):"";return t==a||t==c}function ze(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function Ve(e){return He(e)?Ae(e):function(e){if(!qe(e))return he(e);var t=[];for(var n in Object(e))Z.call(e,n)&&"constructor"!=n&&t.push(n);return t}(e)}e.exports=function(e){return Oe(e,!0,!0)}}(co,co.exports);var lo=kr(co.exports);function ho(e,t,n){try{if(n?.canPublish("trace")&&n?.trace(`applying context delta ${JSON.stringify(t)} on context ${JSON.stringify(e)}`),!t)return e;if(t.reset)return e={...t.reset};if(e=uo(e,void 0),t.commands){for(const n of t.commands)"remove"===n.type?wo(e,n.path):"set"===n.type&&mo(e,n.value,n.path);return e}const i=t.added,s=t.updated,r=t.removed;return i&&Object.keys(i).forEach((t=>{e[t]=i[t]})),s&&Object.keys(s).forEach((t=>{po(t,e,s)})),r&&r.forEach((t=>{delete e[t]})),e}catch(i){return n?.error(`error applying context delta ${JSON.stringify(t)} on context ${JSON.stringify(e)}`,i),e}}function uo(e,t){return lo(e)}const po=(e,t,n)=>{const i=n[e];if(void 0===i)return t;const s=t[e];return s&&i?"string"==typeof s||"number"==typeof s||"boolean"==typeof s||"string"==typeof i||"number"==typeof i||"boolean"==typeof i||Array.isArray(s)||Array.isArray(i)?(t[e]=i,t):(t[e]=Object.assign({},s,i),t):(t[e]=i,t)};function go(e,t){if(e===t)return!0;if(!(e instanceof Object&&t instanceof Object))return!1;if(e.constructor!==t.constructor)return!1;for(const n in e)if(e.hasOwnProperty(n)){if(!t.hasOwnProperty(n))return!1;if(e[n]!==t[n]){if("object"!=typeof e[n])return!1;if(!go(e[n],t[n]))return!1}}for(const n in t)if(t.hasOwnProperty(n)&&!e.hasOwnProperty(n))return!1;return!0}function mo(e,t,n){const i=n.split(".");let s;for(s=0;s<i.length-1;s++)e[i[s]]||(e[i[s]]={}),"object"!=typeof e[i[s]]&&(e[i[s]]={}),e=e[i[s]];e[i[s]]=t}function fo(e,t){return Object.keys(t).every((n=>"object"==typeof t[n]?fo(e?.[n]||{},t[n]||{}):t[n]===e?.[n]))}function wo(e,t){const n=t.split(".");let i;for(i=0;i<n.length-1;i++){if(!e[n[i]])return;e=e[n[i]]}delete e[n[i]]}class bo{_logger;_connection;_trackAllContexts;_reAnnounceKnownContexts;_gw3Session;_contextNameToData={};_gw3Subscriptions=[];_nextCallbackSubscriptionNumber=0;_creationPromises={};_contextNameToId={};_contextIdToName={};_protocolVersion=void 0;_contextsTempCache={};_contextsSubscriptionsCache=[];_systemContextsSubKey;get protocolVersion(){if(!this._protocolVersion){const e=this._connection.availableDomains.find((e=>"context"===e.uri));this._protocolVersion=e?.version??1}return this._protocolVersion}get setPathSupported(){return this.protocolVersion>=2}constructor(e){this._connection=e.connection,this._logger=e.logger,this._trackAllContexts=e.trackAllContexts,this._reAnnounceKnownContexts=e.reAnnounceKnownContexts,this._gw3Session=this._connection.domain("global",[Vr,Yr,to,io]),this._gw3Session.disconnected(this.resetState.bind(this)),this._gw3Session.onJoined((e=>{if(e)return this._reAnnounceKnownContexts?void this.reInitiateState().then((()=>this._connection.setLibReAnnounced({name:"contexts"}))):this._connection.setLibReAnnounced({name:"contexts"})})),this.subscribeToContextCreatedMessages(),this.subscribeToContextUpdatedMessages(),this.subscribeToContextDestroyedMessages(),this._connection.replayer?.drain(ro.name,(e=>{const t=e.type;t&&(t===Vr||t===Qr||t===Kr?this.handleContextCreatedMessage(e):t===Yr||t===io||t===so?this.handleContextUpdatedMessage(e):t!==to&&t!==zr||this.handleContextDestroyedMessage(e))}))}dispose(){for(const e of this._gw3Subscriptions)this._connection.off(e);this._gw3Subscriptions.length=0;for(const e in this._contextNameToData)this._contextNameToId.hasOwnProperty(e)&&delete this._contextNameToData[e]}createContext(e,t){return e in this._creationPromises||(this._creationPromises[e]=this._gw3Session.send({type:Jr,domain:"global",name:e,data:t,lifetime:"retained"}).then((n=>{this._contextNameToId[e]=n.context_id,this._contextIdToName[n.context_id]=e;const i=this._contextNameToData[e]||new ao(n.context_id,e,!0,void 0);return i.isAnnounced=!0,i.name=e,i.contextId=n.context_id,i.context=n.data||uo(t),i.hasReceivedSnapshot=!0,this._contextNameToData[e]=i,delete this._creationPromises[e],n.context_id}))),this._creationPromises[e]}all(){return Object.keys(this._contextNameToData).filter((e=>this._contextNameToData[e].isAnnounced))}async update(e,t){t&&(t=uo(t)),e in this._creationPromises&&await this._creationPromises[e];const n=this._contextNameToData[e];if(!n||!n.isAnnounced)return this.createContext(e,t);let i=n.context;n.hasCallbacks()||(i=await this.get(n.name));const s=this.setPathSupported?this.calculateContextDeltaV2(i,t):this.calculateContextDeltaV1(i,t);return Object.keys(s.added).length||Object.keys(s.updated).length||s.removed.length||s.commands?.length?this._gw3Session.send({type:no,domain:"global",context_id:n.contextId,delta:s},{},{skipPeerId:!1}).then((e=>{this.handleUpdated(n,s,{updaterId:e.peer_id})})):Promise.resolve()}async set(e,t){t&&(t=uo(t)),e in this._creationPromises&&await this._creationPromises[e];const n=this._contextNameToData[e];return n&&n.isAnnounced?this._gw3Session.send({type:no,domain:"global",context_id:n.contextId,delta:{reset:t}},{},{skipPeerId:!1}).then((e=>{this.handleUpdated(n,{reset:t,added:{},removed:[],updated:{}},{updaterId:e.peer_id})})):this.createContext(e,t)}setPath(e,t,n){return this.setPathSupported?this.setPaths(e,[{path:t,value:n}]):Promise.reject("glue.contexts.setPath operation is not supported, use Glue42 3.10 or later")}async setPaths(e,t){if(!this.setPathSupported)return Promise.reject("glue.contexts.setPaths operation is not supported, use Glue42 3.10 or later");t&&(t=uo(t)),e in this._creationPromises&&await this._creationPromises[e];const n=this._contextNameToData[e];if(!n||!n.isAnnounced){const n={};for(const e of t)mo(n,e.value,e.path);return this.createContext(e,n)}const i=[];for(const e of t)null===e.value?i.push({type:"remove",path:e.path}):i.push({type:"set",path:e.path,value:e.value});return this._gw3Session.send({type:no,domain:"global",context_id:n.contextId,delta:{commands:i}},{},{skipPeerId:!1}).then((e=>{this.handleUpdated(n,{added:{},removed:[],updated:{},commands:i},{updaterId:e.peer_id})}))}async get(e){e in this._creationPromises&&await this._creationPromises[e];const t=this._contextNameToData[e];if(!t||!t.isAnnounced)return Promise.resolve({});if(t&&(!t.hasCallbacks()||!t.hasReceivedSnapshot))return new Promise((t=>{this.subscribe(e,((e,n,i,s)=>{this.unsubscribe(s),t(e)}))}));const n=t?.context??{};return Promise.resolve(uo(n))}async subscribe(e,t,n){e in this._creationPromises&&await this._creationPromises[e];const i=void 0===n?this._nextCallbackSubscriptionNumber:n;void 0===n&&(this._nextCallbackSubscriptionNumber+=1),this._contextsSubscriptionsCache.every((e=>e.subKey!==this._nextCallbackSubscriptionNumber))&&this._contextsSubscriptionsCache.push({contextName:e,subKey:i,callback:t});let s=this._contextNameToData[e];if(!s||!s.isAnnounced)return s=s||new ao(void 0,e,!1,void 0),this._contextNameToData[e]=s,s.updateCallbacks[i]=t,Promise.resolve(i);const r=s.hasCallbacks();if(s.updateCallbacks[i]=t,r){if(s.hasReceivedSnapshot){const e=uo(s.context);t(e,e,[],i)}return Promise.resolve(i)}if(s.joinedActivity){if(s.hasReceivedSnapshot){const e=uo(s.context);t(e,e,[],i)}return Promise.resolve(i)}if(s.context&&s.sentExplicitSubscription){if(s.hasReceivedSnapshot){const e=uo(s.context);t(e,e,[],i)}return Promise.resolve(i)}return this.sendSubscribe(s).then((()=>i))}unsubscribe(e){this._contextsSubscriptionsCache=this._contextsSubscriptionsCache.filter((t=>t.subKey!==e));for(const t of Object.keys(this._contextNameToData)){const n=this._contextNameToData[t];if(!n)return;const i=n.hasCallbacks();delete n.updateCallbacks[e],n.isAnnounced&&i&&!n.hasCallbacks()&&n.sentExplicitSubscription&&this.sendUnsubscribe(n).catch((()=>{})),n.isAnnounced||n.hasCallbacks()||delete this._contextNameToData[t]}}async destroy(e){e in this._creationPromises&&await this._creationPromises[e];const t=this._contextNameToData[e];return t?this._gw3Session.send({type:eo,domain:"global",context_id:t.contextId}).then((e=>{})):Promise.reject(`context with ${e} does not exist`)}handleUpdated(e,t,n){const i=e.context;e.context=ho(e.context,t,this._logger),e.hasReceivedSnapshot=!0,this._contextNameToData[e.name]!==e||go(i,e.context)||this.invokeUpdateCallbacks(e,t,n)}subscribeToContextCreatedMessages(){const e=[Qr,Vr,Kr];for(const t of e){const e=this._connection.on(t,this.handleContextCreatedMessage.bind(this));this._gw3Subscriptions.push(e)}}handleContextCreatedMessage(e){const t=e.type;t===Kr?(this._contextNameToId[e.activity_id]=e.context_id,this._contextIdToName[e.context_id]=e.activity_id):t===Qr&&(this._contextNameToId[e.name]=e.context_id,this._contextIdToName[e.context_id]=e.name);const n=this._contextIdToName[e.context_id];if(!n)throw new Error("Received created event for context with unknown name: "+e.context_id);if(!this._contextNameToId[n])throw new Error("Received created event for context with unknown id: "+e.context_id);let i=this._contextNameToData[n];if(i){if(i.isAnnounced)return;if(!i.hasCallbacks())throw new Error("Assertion failure: contextData.hasCallbacks()");i.isAnnounced=!0,i.contextId=e.context_id,i.activityId=e.activity_id,i.sentExplicitSubscription||this.sendSubscribe(i)}else this._contextNameToData[n]=i=new ao(e.context_id,n,!0,e.activity_id),this._trackAllContexts&&this.subscribe(n,(()=>{})).then((e=>this._systemContextsSubKey=e))}subscribeToContextUpdatedMessages(){const e=[io,Yr,so];for(const t of e){const e=this._connection.on(t,this.handleContextUpdatedMessage.bind(this));this._gw3Subscriptions.push(e)}}handleContextUpdatedMessage(e){const t=e.type,n=e.context_id;let i=this._contextNameToData[this._contextIdToName[n]];const s=!i||!i.isAnnounced;if(t===so)i||(i=this._contextNameToData[e.activity_id]||new ao(n,e.activity_id,!0,e.activity_id)),this._contextNameToData[e.activity_id]=i,this._contextIdToName[n]=e.activity_id,this._contextNameToId[e.activity_id]=n,i.contextId=n,i.isAnnounced=!0,i.activityId=e.activity_id,i.joinedActivity=!0;else if(!i||!i.isAnnounced)return void(t===Yr?(i=i||new ao(n,e.name,!0,void 0),i.sentExplicitSubscription=!0,this._contextNameToData[e.name]=i,this._contextIdToName[n]=e.name,this._contextNameToId[e.name]=n):this._logger.error(`Received 'update' for unknown context: ${n}`));const r=i.context;if(i.hasReceivedSnapshot=!0,t===Yr)i.context=e.data||{};else if(t===so)i.context=e.context_snapshot||{};else{if(t!==io)throw new Error("Unrecognized context update message "+t);i.context=ho(i.context,e.delta,this._logger)}!s&&go(i.context,r)&&t!==Yr||this.invokeUpdateCallbacks(i,e.delta,{updaterId:e.updater_id})}invokeUpdateCallbacks(e,t,n){if((t=t||{added:{},updated:{},reset:{},removed:[]}).commands){t.added=t.updated=t.reset={},t.removed=[];for(const e of t.commands)"remove"===e.type?(-1===e.path.indexOf(".")&&t.removed.push(e.path),mo(t.updated,null,e.path)):"set"===e.type&&mo(t.updated,e.value,e.path)}for(const i in e.updateCallbacks)if(e.updateCallbacks.hasOwnProperty(i))try{(0,e.updateCallbacks[i])(uo(e.context),uo(Object.assign({},t.added||{},t.updated||{},t.reset||{})),t.removed,parseInt(i,10),n)}catch(e){this._logger.debug("callback error: "+JSON.stringify(e))}}subscribeToContextDestroyedMessages(){const e=[to,zr];for(const t of e){const e=this._connection.on(t,this.handleContextDestroyedMessage.bind(this));this._gw3Subscriptions.push(e)}}handleContextDestroyedMessage(e){let t,n;if(e.type===zr){if(n=e.activity_id,t=this._contextNameToId[n],!t)return void this._logger.error(`Received 'destroyed' for unknown activity: ${e.activity_id}`)}else if(t=e.context_id,n=this._contextIdToName[t],!n)return void this._logger.error(`Received 'destroyed' for unknown context: ${e.context_id}`);delete this._contextIdToName[t],delete this._contextNameToId[n];const i=this._contextNameToData[n];delete this._contextNameToData[n],i&&i.isAnnounced||this._logger.error(`Received 'destroyed' for unknown context: ${t}`)}sendSubscribe(e){return e.sentExplicitSubscription=!0,this._gw3Session.send({type:Xr,domain:"global",context_id:e.contextId}).then((e=>{}))}sendUnsubscribe(e){return e.sentExplicitSubscription=!1,this._gw3Session.send({type:Zr,domain:"global",context_id:e.contextId}).then((e=>{}))}calculateContextDeltaV1(e,t){const n={added:{},updated:{},removed:[],reset:void 0};if(e)for(const i of Object.keys(e))-1===Object.keys(t).indexOf(i)||null===t[i]||go(e[i],t[i])||(n.updated[i]=t[i]);for(const i of Object.keys(t))e&&-1!==Object.keys(e).indexOf(i)?null===t[i]&&n.removed.push(i):null!==t[i]&&(n.added[i]=t[i]);return n}calculateContextDeltaV2(e,t){const n={added:{},updated:{},removed:[],reset:void 0,commands:[]};for(const i of Object.keys(t))if(null!==t[i]){go(e?e[i]:null,t[i])||n.commands?.push({type:"set",path:i,value:t[i]})}else n.commands?.push({type:"remove",path:i});return n}resetState(){for(const e of this._gw3Subscriptions)this._connection.off(e);this._systemContextsSubKey&&(this.unsubscribe(this._systemContextsSubKey),delete this._systemContextsSubKey),this._gw3Subscriptions=[],this._contextNameToId={},this._contextIdToName={},delete this._protocolVersion,this._contextsTempCache=Object.keys(this._contextNameToData).reduce(((e,t)=>(e[t]=this._contextNameToData[t].context,e)),{}),this._contextNameToData={}}async reInitiateState(){this.subscribeToContextCreatedMessages(),this.subscribeToContextUpdatedMessages(),this.subscribeToContextDestroyedMessages(),this._connection.replayer?.drain(ro.name,(e=>{const t=e.type;t&&(t===Vr||t===Qr||t===Kr?this.handleContextCreatedMessage(e):t===Yr||t===io||t===so?this.handleContextUpdatedMessage(e):t!==to&&t!==zr||this.handleContextDestroyedMessage(e))})),await Promise.all(this._contextsSubscriptionsCache.map((e=>this.subscribe(e.contextName,e.callback,e.subKey)))),await this.flushQueue();for(const e in this._contextsTempCache){if("object"!=typeof this._contextsTempCache[e]||0===Object.keys(this._contextsTempCache[e]).length)continue;const t=this._contextsTempCache[e];this._logger.info(`Re-announcing known context: ${e}`),await this.flushQueue(),await this.update(e,t)}this._contextsTempCache={},this._logger.info("Contexts are re-announced")}flushQueue(){return new Promise((e=>setTimeout((()=>e()),0)))}}class yo{initTime;initStartTime;initEndTime;_bridge;constructor(e){this._bridge=new bo(e)}all(){return this._bridge.all()}update(e,t){return this.checkName(e),this.checkData(t),this._bridge.update(e,t)}set(e,t){return this.checkName(e),this.checkData(t),this._bridge.set(e,t)}setPath(e,t,n){this.checkName(e),this.checkPath(t);return""===t?(this.checkData(n),this.set(e,n)):this._bridge.setPath(e,t,n)}setPaths(e,t){if(this.checkName(e),!Array.isArray(t))throw new Error("Please provide the paths as an array of PathValues!");for(const{path:e,value:n}of t){this.checkPath(e);""===e&&this.checkData(n)}return this._bridge.setPaths(e,t)}subscribe(e,t){if(this.checkName(e),"function"!=typeof t)throw new Error("Please provide the callback as a function!");return this._bridge.subscribe(e,((e,n,i,s,r)=>t(e,n,i,(()=>this._bridge.unsubscribe(s)),r))).then((e=>()=>{this._bridge.unsubscribe(e)}))}get(e){return this.checkName(e),this._bridge.get(e)}ready(){return Promise.resolve(this)}destroy(e){return this.checkName(e),this._bridge.destroy(e)}get setPathSupported(){return this._bridge.setPathSupported}checkName(e){if("string"!=typeof e||""===e)throw new Error("Please provide the name as a non-empty string!")}checkPath(e){if("string"!=typeof e)throw new Error("Please provide the path as a dot delimited string!")}checkData(e){if("object"!=typeof e)throw new Error("Please provide the data as an object!")}}function vo(e,t,n){return"function"!=typeof t&&"function"!=typeof n?e:("function"!=typeof t?t=()=>{}:"function"!=typeof n&&(n=()=>{}),e.then(t,n))}function Co(e=0,t,n){let i;const s=()=>{i&&clearTimeout(i)};return t.then((()=>{s()})).catch((()=>{s()})),new Promise(((t,s)=>{i=setTimeout((()=>s(n)),e)}))}var Io;!function(e){e[e.Success=0]="Success",e[e.Error=1]="Error"}(Io||(Io={}));class So{protocol;repo;instance;configuration;constructor(e,t,n,i){this.protocol=e,this.repo=t,this.instance=n,this.configuration=i}subscribe(e,t,n,i,s){const r=(e,n,i,r)=>{t.methodResponseTimeout=t.methodResponseTimeout??t.waitTimeoutMs,this.protocol.client.subscribe(n,t,e,i,r,s)},o=new Promise(((n,i)=>{const s=e=>{n(e)},o=e=>{i(e)};if(!e)return void i("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");let a;if(a="string"==typeof e?{name:e}:e,!a.name)return void i("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");void 0===t&&(t={});let c=t.target;if(void 0===c&&(c="best"),"string"==typeof c&&"all"!==c&&"best"!==c)return void i(new Error(`"${c}" is not a valid target. Valid targets are "all", "best", or an instance.`));void 0===t.methodResponseTimeout&&(t.methodResponseTimeout=t.method_response_timeout,void 0===t.methodResponseTimeout&&(t.methodResponseTimeout=this.configuration.methodResponseTimeout)),void 0===t.waitTimeoutMs&&(t.waitTimeoutMs=t.wait_for_method_timeout,void 0===t.waitTimeoutMs&&(t.waitTimeoutMs=this.configuration.waitTimeoutMs));let d=0,l=this.getServerMethodsByFilterAndTarget(a,c);if(l.length>0)r(l,l[0].methods[0],s,o);else{const n=()=>{if(c&&t.waitTimeoutMs)if(d+=500,l=this.getServerMethodsByFilterAndTarget(a,c),l.length>0){const e=l[0].methods[0];r(l,e,s,o)}else if(d>=t.waitTimeoutMs){r(l,"string"==typeof e?{name:e}:e,s,o)}else setTimeout(n,500)};setTimeout(n,500)}}));return vo(o,n,i)}servers(e){const t=void 0===e?void 0:{...e};return this.getServers(t).map((e=>e.server.instance))}methods(e){return e="string"==typeof e?{name:e}:{...e},this.getMethods(e)}methodsForInstance(e){return this.getMethodsForInstance(e)}methodAdded(e){return this.repo.onMethodAdded(e)}methodRemoved(e){return this.repo.onMethodRemoved(e)}serverAdded(e){return this.repo.onServerAdded(e)}serverRemoved(e){return this.repo.onServerRemoved(((t,n)=>{e(t,n)}))}serverMethodAdded(e){return this.repo.onServerMethodAdded(((t,n)=>{e({server:t,method:n})}))}serverMethodRemoved(e){return this.repo.onServerMethodRemoved(((t,n)=>{e({server:t,method:n})}))}async invoke(e,t,n,i,s,r){return vo((async()=>{let s;if(s="string"==typeof e?{name:e}:{...e},!s.name)return Promise.reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");if(t||(t={}),n||(n="best"),"string"==typeof n&&"all"!==n&&"best"!==n&&"skipMine"!==n)return Promise.reject(new Error(`"${n}" is not a valid target. Valid targets are "all" and "best".`));if(i||(i={}),void 0===i.methodResponseTimeoutMs&&(i.methodResponseTimeoutMs=i.method_response_timeout,void 0===i.methodResponseTimeoutMs&&(i.methodResponseTimeoutMs=this.configuration.methodResponseTimeout)),void 0===i.waitTimeoutMs&&(i.waitTimeoutMs=i.wait_for_method_timeout,void 0===i.waitTimeoutMs&&(i.waitTimeoutMs=this.configuration.waitTimeoutMs)),void 0!==i.waitTimeoutMs&&"number"!=typeof i.waitTimeoutMs)return Promise.reject(new Error(`"${i.waitTimeoutMs}" is not a valid number for "waitTimeoutMs" `));if("object"!=typeof t)return Promise.reject(new Error(`The method arguments must be an object. method: ${s.name}`));let r=this.getServerMethodsByFilterAndTarget(s,n);if(0===r.length)try{r=await this.tryToAwaitForMethods(s,n,i)}catch(i){const r={method:{...s,getServers:()=>[],supportsStreaming:!1,objectTypes:s.objectTypes??[],flags:s.flags?.metadata??{}},called_with:t,message:`Can not find a method matching ${JSON.stringify(e)} with server filter ${JSON.stringify(n)}`,executed_by:void 0,returned:void 0,status:void 0};return Promise.reject(r)}const o=i.methodResponseTimeoutMs,a=i,c=r.map((e=>{const n=Wr(10),i=e.methods[0],s=e.server,r=this.protocol.client.invoke(n,i,t,s,a);return Promise.race([r,Co(o,r,{invocationId:n,message:`Invocation timeout (${o} ms) reached for method name: ${i?.name}, target instance: ${JSON.stringify(s.instance)}, options: ${JSON.stringify(a)}`,status:Io.Error})])})),d=await Promise.all(c),l=this.getInvocationResultObj(d,s,t);return d.every((e=>e.status===Io.Error))?Promise.reject(l):l})(),s,r)}getInvocationResultObj(e,t,n){const i=e.filter((e=>e.status===Io.Success)).reduce(((e,i)=>e=[...e,{executed_by:i.instance,returned:i.result,called_with:n,method:t,message:i.message,status:i.status}]),[]),s=e.filter((e=>e.status===Io.Error)).reduce(((e,i)=>e=[...e,{executed_by:i.instance,called_with:n,name:t.name,message:i.message}]),[]),r=e[0];return{method:t,called_with:n,returned:r.result,executed_by:r.instance,all_return_values:i,all_errors:s,message:r.message,status:r.status}}tryToAwaitForMethods(e,t,n){return new Promise(((i,s)=>{if(0===n.waitTimeoutMs)return void s();let r=0;const o=setInterval((()=>{r+=500;const a=this.getServerMethodsByFilterAndTarget(e,t);if(a.length>0)clearInterval(o),i(a);else if(r>=(n.waitTimeoutMs||1e4))return clearInterval(o),void s()}),500)}))}filterByTarget(e,t){if("string"!=typeof e){let n;n=Array.isArray(e)?e:[e];return n.reduce(((e,n)=>{const i=t.filter((e=>this.instanceMatch(n,e.server.instance)));return e.concat(i)}),[])}if("all"===e)return[...t];if("best"===e){const e=t.find((e=>e.server.instance.isLocal));if(e)return[e];if(void 0!==t[0])return[t[0]]}else if("skipMine"===e)return t.filter((({server:e})=>e.instance.peerId!==this.instance.peerId));return[]}instanceMatch(e,t){return e?.peerId&&e?.instance&&delete(e={...e}).peerId,this.containsProps(e,t)}methodMatch(e,t){return this.containsProps(e,t)}containsProps(e,t){return Object.keys(e).filter((t=>void 0!==e[t]&&null!==e[t]&&"function"!=typeof e[t]&&"object_types"!==t&&"display_name"!==t&&"id"!==t&&"gatewayId"!==t&&"identifier"!==t&&"_"!==t[0])).every((n=>{let i;const s=e[n],r=t[n];switch(n){case"objectTypes":i=(s||[]).every((e=>(r||[]).includes(e)));break;case"flags":i=fo(r||{},s||{});break;default:i=String(s).toLowerCase()===String(r).toLowerCase()}return i}))}getMethods(e){if(void 0===e)return this.repo.getMethods();return this.repo.getMethods().filter((t=>this.methodMatch(e,t)))}getMethodsForInstance(e){const t=this.repo.getServers().filter((t=>this.instanceMatch(e,t.instance)));if(0===t.length)return[];let n={};return 1===t.length?n=t[0].methods:t.forEach((e=>{Object.keys(e.methods).forEach((t=>{const i=e.methods[t];n[i.identifier]=i}))})),Object.keys(n).map((e=>n[e]))}getServers(e){const t=this.repo.getServers();return void 0===e?t.map((e=>({server:e,methods:[]}))):t.reduce(((t,n)=>{const i=Object.values(n.methods).filter((t=>this.methodMatch(e,t)));return i.length>0&&t.push({server:n,methods:i}),t}),[])}getServerMethodsByFilterAndTarget(e,t){const n=this.getServers(e);return this.filterByTarget(t,n)}}class _o{protocol;repoMethod;subscription;constructor(e,t,n){this.protocol=e,this.repoMethod=t,this.subscription=n}get stream(){if(!this.repoMethod.stream)throw new Error("no stream");return this.repoMethod.stream}get arguments(){return this.subscription.arguments||{}}get branchKey(){return this.subscription.branchKey}get instance(){if(!this.subscription.instance)throw new Error("no instance");return this.subscription.instance}close(){this.protocol.server.closeSingleSubscription(this.repoMethod,this.subscription)}push(e){this.protocol.server.pushDataToSingle(this.repoMethod,this.subscription,e)}}class xo{protocol;repoMethod;requestContext;arguments;instance;constructor(e,t,n){this.protocol=e,this.repoMethod=t,this.requestContext=n,this.arguments=n.arguments,this.instance=n.instance}accept(){this.protocol.server.acceptRequestOnBranch(this.requestContext,this.repoMethod,"")}acceptOnBranch(e){this.protocol.server.acceptRequestOnBranch(this.requestContext,this.repoMethod,e)}reject(e){this.protocol.server.rejectRequest(this.requestContext,this.repoMethod,e)}}class ko{key;protocol;repoMethod;constructor(e,t,n){this.key=e,this.protocol=t,this.repoMethod=n}subscriptions(){return this.protocol.server.getSubscriptionList(this.repoMethod,this.key).map((e=>new _o(this.protocol,this.repoMethod,e)))}close(){this.protocol.server.closeAllSubscriptions(this.repoMethod,this.key)}push(e){this.protocol.server.pushData(this.repoMethod,e,[this.key])}}class To{_protocol;_repoMethod;_server;name;constructor(e,t,n){this._protocol=e,this._repoMethod=t,this._server=n,this.name=this._repoMethod.definition.name}branches(e){const t=this._protocol.server.getBranchList(this._repoMethod);return e?t.indexOf(e)>-1?new ko(e,this._protocol,this._repoMethod):void 0:t.map((e=>new ko(e,this._protocol,this._repoMethod)))}branch(e){return this.branches(e)}subscriptions(){return this._protocol.server.getSubscriptionList(this._repoMethod).map((e=>new _o(this._protocol,this._repoMethod,e)))}get definition(){const e=this._repoMethod.definition;return{accepts:e.accepts,description:e.description,displayName:e.displayName,name:e.name,objectTypes:e.objectTypes,returns:e.returns,supportsStreaming:e.supportsStreaming,flags:e.flags?.metadata}}close(){this._protocol.server.closeAllSubscriptions(this._repoMethod),this._server.unregister(this._repoMethod.definition,!0)}push(e,t){if("string"!=typeof t&&!Array.isArray(t)&&void 0!==t)throw new Error("invalid branches should be string or string array");if("object"!=typeof e)throw new Error("Invalid arguments. Data must be an object.");this._protocol.server.pushData(this._repoMethod,e,t)}updateRepoMethod(e){this._repoMethod=e}}class Ro{protocol;serverRepository;streaming;invocations=0;currentlyUnregistering={};constructor(e,t){this.protocol=e,this.serverRepository=t,this.streaming=new class{protocol;server;constructor(e,t){this.protocol=e,this.server=t,e.server.onSubRequest(((e,t)=>this.handleSubRequest(e,t))),e.server.onSubAdded(((e,t)=>this.handleSubAdded(e,t))),e.server.onSubRemoved(((e,t)=>this.handleSubRemoved(e,t)))}handleSubRequest(e,t){if(!t||!t.streamCallbacks||"function"!=typeof t.streamCallbacks.subscriptionRequestHandler)return;const n=new xo(this.protocol,t,e);t.streamCallbacks.subscriptionRequestHandler(n)}handleSubAdded(e,t){if(!t||!t.streamCallbacks||"function"!=typeof t.streamCallbacks.subscriptionAddedHandler)return;const n=new _o(this.protocol,t,e);t.streamCallbacks.subscriptionAddedHandler(n)}handleSubRemoved(e,t){if(!t||!t.streamCallbacks||"function"!=typeof t.streamCallbacks.subscriptionRemovedHandler)return;const n=new _o(this.protocol,t,e);t.streamCallbacks.subscriptionRemovedHandler(n)}}(e,this),this.protocol.server.onInvoked(this.onMethodInvoked.bind(this))}createStream(e,t,n,i,s){const r=new Promise(((n,i)=>{if(!e)return void i("The stream name must be unique! Please, provide either a unique string for a stream name to “glue.interop.createStream()” or a “methodDefinition” object with a unique “name” property for the stream.");let r;if(r="string"==typeof e?{name:""+e}:{...e},!r.name)return i(`The “name” property is required for the “streamDefinition” object and must be unique. Stream definition: ${JSON.stringify(r)}`);if(this.serverRepository.getList().some((e=>e.definition.name===r.name)))return i(`A stream with the name "${r.name}" already exists! Please, provide a unique name for the stream.`);r.supportsStreaming=!0,t||(t={}),"function"!=typeof t.subscriptionRequestHandler&&(t.subscriptionRequestHandler=e=>{e.accept()});const o=this.serverRepository.add({definition:r,streamCallbacks:t,protocolState:{}});this.protocol.server.createStream(o).then((()=>{let e;s?(e=s,s.updateRepoMethod(o)):e=new To(this.protocol,o,this),o.stream=e,n(e)})).catch((e=>{o.repoId&&this.serverRepository.remove(o.repoId),i(e)}))}));return vo(r,n,i)}register(e,t){if(!e)return Promise.reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");if("function"!=typeof t)return Promise.reject(`The second parameter must be a callback function. Method: ${"string"==typeof e?e:e.name}`);const n=async(e,n)=>{try{const i=t(e.args,e.instance);if(i&&"function"==typeof i.then){n(void 0,await i)}else n(void 0,i)}catch(e){n(e??"",e??"")}};return n.userCallback=t,this.registerCore(e,n)}registerAsync(e,t){if(!e)return Promise.reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");if("function"!=typeof t)return Promise.reject(`The second parameter must be a callback function. Method: ${"string"==typeof e?e:e.name}`);const n=async(e,n)=>{try{let i=!1;const s=e=>{i||n(void 0,e),i=!0},r=e=>{i||(e||(e=""),n(e,e)),i=!0},o=t(e.args,e.instance,s,r);o&&"function"==typeof o.then&&o.then(s).catch(r)}catch(e){n(e,void 0)}};return n.userCallbackAsync=t,this.registerCore(e,n)}async unregister(e,t=!1){if(void 0===e)return Promise.reject("Please, provide either a unique string for a name or an object containing a “name” property.");if("function"==typeof e)return void await this.unregisterWithPredicate(e,t);let n;if(n="string"==typeof e?{name:e}:e,void 0===n.name)return Promise.reject("Method name is required. Cannot find a method if the method name is undefined!");const i=this.serverRepository.getList().find((e=>e.definition.name===n.name&&(e.definition.supportsStreaming||!1)===t));if(!i)return Promise.reject(`Method with a name "${n.name}" does not exist or is not registered by your application!`);await this.removeMethodsOrStreams([i])}async unregisterWithPredicate(e,t){const n=this.serverRepository.getList().filter((t=>e(t.definition))).filter((e=>(e.definition.supportsStreaming||!1)===t));if(!n||0===n.length)return Promise.reject(`Could not find a ${t?"stream":"method"} matching the specified condition!`);await this.removeMethodsOrStreams(n)}removeMethodsOrStreams(e){const t=[];return e.forEach((e=>{const n=this.protocol.server.unregister(e).then((()=>{e.repoId&&this.serverRepository.remove(e.repoId)}));t.push(n),this.addAsCurrentlyUnregistering(e.definition.name,n)})),Promise.all(t)}async addAsCurrentlyUnregistering(e,t){const n=new Promise((e=>setTimeout(e,5e3)));this.currentlyUnregistering[e]=Promise.race([t,n]).then((()=>{delete this.currentlyUnregistering[e]}))}async registerCore(e,t){let n;if(n="string"==typeof e?{name:""+e}:{...e},!n.name)return Promise.reject(`Please, provide a (unique) string value for the “name” property in the “methodDefinition” object: ${JSON.stringify(e)}`);const i=this.currentlyUnregistering[n.name];void 0!==i&&await i;if(this.serverRepository.getList().some((e=>e.definition.name===n.name)))return Promise.reject(`A method with the name "${n.name}" already exists! Please, provide a unique name for the method.`);if(n.supportsStreaming)return Promise.reject(`When you create methods with “glue.interop.register()” or “glue.interop.registerAsync()” the property “supportsStreaming” cannot be “true”. If you want “${n.name}” to be a stream, please use the “glue.interop.createStream()” method.`);const s=this.serverRepository.add({definition:n,theFunction:t,protocolState:{}});return this.protocol.server.register(s).catch((e=>{throw s?.repoId&&this.serverRepository.remove(s.repoId),e}))}onMethodInvoked(e,t,n){e&&e.theFunction&&e.theFunction(n,((n,i)=>{if(null!=n)if(n.message&&"string"==typeof n.message)n=n.message;else if("string"!=typeof n)try{n=JSON.stringify(n)}catch(e){n=`un-stringifyable error in onMethodInvoked! Top level prop names: ${Object.keys(n)}`}i?("object"!=typeof i||Array.isArray(i))&&(i={_value:i}):i={},this.protocol.server.methodInvocationResult(e,t,n,i)}))}}class Ao{wrapped={};constructor(e,t,n){this.wrapped.getMethods=function(){return e.methodsForInstance(this)},this.wrapped.getStreams=function(){return e.methodsForInstance(this).filter((e=>e.supportsStreaming))},t&&this.refreshWrappedObject(t),n&&(n.loggedIn((()=>{this.refresh(n)})),this.refresh(n))}unwrap(){return this.wrapped}refresh(e){if(!e)return;const t=e?.resolvedIdentity,n=Object.assign({},t??{},{peerId:e?.peerId});this.refreshWrappedObject(n)}refreshWrappedObject(e){Object.keys(e).forEach((t=>{this.wrapped[t]=e[t]})),this.wrapped.user=e.user,this.wrapped.instance=e.instance,this.wrapped.application=e.application??Wr(10),this.wrapped.applicationName=e.applicationName,this.wrapped.pid=e.pid??e.process??Math.floor(1e10*Math.random()),this.wrapped.machine=e.machine,this.wrapped.environment=e.environment,this.wrapped.region=e.region,this.wrapped.windowId=e.windowId,this.wrapped.isLocal=e.isLocal??!0,this.wrapped.api=e.api,this.wrapped.service=e.service,this.wrapped.peerId=e.peerId}}const Po=e=>({...e,flags:e.flags.metadata||{}});class Mo{logger;API;servers={};myServer;methodsCount={};callbacks=Rr();constructor(e,t){this.logger=e,this.API=t;const n=this.API.instance.peerId;this.myServer={id:n,methods:{},instance:this.API.instance,wrapper:this.API.unwrappedInstance},this.servers[n]=this.myServer}addServer(e,t){this.logger.debug(`adding server ${t}`);const n=this.servers[t];if(n)return n.id;const i=new Ao(this.API,e),s={id:t,methods:{},instance:i.unwrap(),wrapper:i};return this.servers[t]=s,this.callbacks.execute("onServerAdded",s.instance),t}removeServerById(e,t){const n=this.servers[e];n?(this.logger.debug(`removing server ${e}`),Object.keys(n.methods).forEach((t=>{this.removeServerMethod(e,t)})),delete this.servers[e],this.callbacks.execute("onServerRemoved",n.instance,t)):this.logger.warn(`not aware of server ${e}, my state ${JSON.stringify(Object.keys(this.servers))}`)}addServerMethod(e,t){const n=this.servers[e];if(!n)throw new Error("server does not exists");if(n.methods[t.id])return;const i=this.createMethodIdentifier(t),s=this,r={identifier:i,gatewayId:t.id,name:t.name,displayName:t.display_name,description:t.description,version:t.version,objectTypes:t.object_types||[],accepts:t.input_signature,returns:t.result_signature,supportsStreaming:void 0!==t.flags&&t.flags.streaming,flags:t.flags??{},getServers:()=>s.getServersByMethod(i)};r.object_types=r.objectTypes,r.display_name=r.displayName,r.version=r.version,n.methods[t.id]=r;const o=Po(r);return this.methodsCount[i]||(this.methodsCount[i]=0,this.callbacks.execute("onMethodAdded",o)),this.methodsCount[i]=this.methodsCount[i]+1,this.callbacks.execute("onServerMethodAdded",n.instance,o),r}removeServerMethod(e,t){const n=this.servers[e];if(!n)throw new Error("server does not exists");const i=n.methods[t];delete n.methods[t];const s=Po(i);this.methodsCount[i.identifier]=this.methodsCount[i.identifier]-1,0===this.methodsCount[i.identifier]&&this.callbacks.execute("onMethodRemoved",s),this.callbacks.execute("onServerMethodRemoved",n.instance,s)}getMethods(){return this.extractMethodsFromServers(Object.values(this.servers)).map(Po)}getServers(){return Object.values(this.servers).map(this.hideServerMethodSystemFlags)}onServerAdded(e){const t=this.callbacks.add("onServerAdded",e),n=this.getServers().map((e=>e.instance));return this.returnUnsubWithDelayedReplay(t,n,e)}onMethodAdded(e){const t=this.callbacks.add("onMethodAdded",e),n=this.getMethods();return this.returnUnsubWithDelayedReplay(t,n,e)}onServerMethodAdded(e){const t=this.callbacks.add("onServerMethodAdded",e);let n=!1;const i=this.getServers();return setTimeout((()=>{i.forEach((t=>{const i=t.methods;Object.keys(i).forEach((s=>{n||e(t.instance,i[s])}))}))}),0),()=>{n=!0,t()}}onMethodRemoved(e){return this.callbacks.add("onMethodRemoved",e)}onServerRemoved(e){return this.callbacks.add("onServerRemoved",e)}onServerMethodRemoved(e){return this.callbacks.add("onServerMethodRemoved",e)}getServerById(e){if(this.servers[e])return this.hideServerMethodSystemFlags(this.servers[e])}reset(){Object.keys(this.servers).forEach((e=>{this.removeServerById(e,"reset")})),this.servers={[this.myServer.id]:this.myServer},this.methodsCount={}}createMethodIdentifier(e){const t=e.input_signature??"",n=e.result_signature??"";return(e.name+t+n).toLowerCase()}getServersByMethod(e){const t=[];return Object.values(this.servers).forEach((n=>{Object.values(n.methods).forEach((i=>{i.identifier===e&&t.push(n.instance)}))})),t}returnUnsubWithDelayedReplay(e,t,n){let i=!1;return setTimeout((()=>{t.forEach((e=>{i||n(e)}))}),0),()=>{i=!0,e()}}hideServerMethodSystemFlags(e){const t={};return Object.entries(e.methods).forEach((([e,n])=>{t[e]=Po(n)})),{...e,methods:t}}extractMethodsFromServers(e){return Object.values(e).reduce(((e,t)=>[...e,...Object.values(t.methods)]),[])}}class Oo{nextId=0;methods=[];add(e){return e.repoId=String(this.nextId),this.nextId+=1,this.methods.push(e),e}remove(e){if("string"!=typeof e)return new TypeError("Expecting a string");this.methods=this.methods.filter((t=>t.repoId!==e))}getById(e){if("string"==typeof e)return this.methods.find((t=>t.repoId===e))}getList(){return this.methods.map((e=>e))}length(){return this.methods.length}reset(){this.methods=[]}}const Eo="onSubscriptionRequest",Do="onSubscriptionAdded",jo="onSubscriptionRemoved";class No{session;repository;serverRepository;ERR_URI_SUBSCRIPTION_FAILED="com.tick42.agm.errors.subscription.failure";callbacks=Rr();nextStreamId=0;constructor(e,t,n){this.session=e,this.repository=t,this.serverRepository=n,e.on("add-interest",(e=>{this.handleAddInterest(e)})),e.on("remove-interest",(e=>{this.handleRemoveInterest(e)}))}acceptRequestOnBranch(e,t,n){if("string"!=typeof n&&(n=""),"object"!=typeof t.protocolState.subscriptionsMap)throw new TypeError("The streaming method is missing its subscriptions.");if(!Array.isArray(t.protocolState.branchKeyToStreamIdMap))throw new TypeError("The streaming method is missing its branches.");const i=this.getStreamId(t,n),s=e.msg.subscription_id,r={id:s,arguments:e.arguments,instance:e.instance,branchKey:n,streamId:i,subscribeMsg:e.msg};t.protocolState.subscriptionsMap[s]=r,this.session.sendFireAndForget({type:"accepted",subscription_id:s,stream_id:i}),this.callbacks.execute(Do,r,t)}rejectRequest(e,t,n){"string"!=typeof n&&(n=""),this.sendSubscriptionFailed("Subscription rejected by user. "+n,e.msg.subscription_id)}pushData(e,t,n){if("object"!=typeof e||!Array.isArray(e.protocolState.branchKeyToStreamIdMap))return;if("object"!=typeof t)throw new Error("Invalid arguments. Data must be an object.");"string"==typeof n?n=[n]:(!Array.isArray(n)||n.length<=0)&&(n=[]);e.protocolState.branchKeyToStreamIdMap.filter((e=>!n||0===n.length||n.indexOf(e.key)>=0)).map((e=>e.streamId)).forEach((e=>{const n={type:"publish",stream_id:e,data:t};this.session.sendFireAndForget(n)}))}pushDataToSingle(e,t,n){if("object"!=typeof n)throw new Error("Invalid arguments. Data must be an object.");const i={type:"post",subscription_id:t.id,data:n};this.session.sendFireAndForget(i)}closeSingleSubscription(e,t){e.protocolState.subscriptionsMap&&delete e.protocolState.subscriptionsMap[t.id];const n={type:"drop-subscription",subscription_id:t.id,reason:"Server dropping a single subscription"};this.session.sendFireAndForget(n),t.instance,this.callbacks.execute(jo,t,e)}closeMultipleSubscriptions(e,t){if("object"!=typeof e||"object"!=typeof e.protocolState.subscriptionsMap)return;if(!e.protocolState.subscriptionsMap)return;const n=e.protocolState.subscriptionsMap;let i=Object.keys(n).map((e=>n[e]));"string"==typeof t&&(i=i.filter((e=>e.branchKey===t))),i.forEach((e=>{delete n[e.id];const t={type:"drop-subscription",subscription_id:e.id,reason:"Server dropping all subscriptions on stream_id: "+e.streamId};this.session.sendFireAndForget(t)}))}getSubscriptionList(e,t){if("object"!=typeof e)return[];let n=[];if(!e.protocolState.subscriptionsMap)return[];const i=e.protocolState.subscriptionsMap,s=Object.keys(i).map((e=>i[e]));return n="string"!=typeof t?s:s.filter((e=>e.branchKey===t)),n}getBranchList(e){if("object"!=typeof e)return[];if(!e.protocolState.subscriptionsMap)return[];const t=e.protocolState.subscriptionsMap,n=Object.keys(t).map((e=>t[e])),i=[];return n.forEach((e=>{let t="";"object"==typeof e&&"string"==typeof e.branchKey&&(t=e.branchKey),-1===i.indexOf(t)&&i.push(t)})),i}onSubAdded(e){this.onSubscriptionLifetimeEvent(Do,e)}onSubRequest(e){this.onSubscriptionLifetimeEvent(Eo,e)}onSubRemoved(e){this.onSubscriptionLifetimeEvent(jo,e)}handleRemoveInterest(e){const t=this.serverRepository.getById(e.method_id);if("string"!=typeof e.subscription_id||"object"!=typeof t)return;if(!t.protocolState.subscriptionsMap)return;if("object"!=typeof t.protocolState.subscriptionsMap[e.subscription_id])return;const n=t.protocolState.subscriptionsMap[e.subscription_id];delete t.protocolState.subscriptionsMap[e.subscription_id],this.callbacks.execute(jo,n,t)}onSubscriptionLifetimeEvent(e,t){this.callbacks.add(e,t)}getNextStreamId(){return this.nextStreamId+++""}handleAddInterest(e){const t=this.repository.getServerById(e.caller_id),n=t?.instance??{},i={msg:e,arguments:e.arguments_kv||{},instance:n},s=this.serverRepository.getById(e.method_id);if(void 0!==s)s.protocolState.subscriptionsMap&&s.protocolState.subscriptionsMap[e.subscription_id]?this.sendSubscriptionFailed("A subscription with id "+e.subscription_id+" already exists.",e.subscription_id):this.callbacks.execute(Eo,i,s);else{const t="No method with id "+e.method_id+" on this server.";this.sendSubscriptionFailed(t,e.subscription_id)}}sendSubscriptionFailed(e,t){const n={type:"error",reason_uri:this.ERR_URI_SUBSCRIPTION_FAILED,reason:e,request_id:t};this.session.sendFireAndForget(n)}getStreamId(e,t){if("string"!=typeof t&&(t=""),!e.protocolState.branchKeyToStreamIdMap)throw new Error(`streaming ${e.definition.name} method without protocol state`);const n=e.protocolState.branchKeyToStreamIdMap.filter((e=>e.key===t))[0];let i=n?n.streamId:void 0;return"string"==typeof i&&""!==i||(i=this.getNextStreamId(),e.protocolState.branchKeyToStreamIdMap.push({key:t,streamId:i})),i}}class $o{session;clientRepository;serverRepository;logger;callbacks=Rr();streaming;constructor(e,t,n,i){this.session=e,this.clientRepository=t,this.serverRepository=n,this.logger=i,this.streaming=new No(e,t,n),this.session.on("invoke",(e=>this.handleInvokeMessage(e)))}createStream(e){return e.protocolState.subscriptionsMap={},e.protocolState.branchKeyToStreamIdMap=[],this.register(e,!0)}register(e,t){const n=e.definition,i=Object.assign({},{metadata:n.flags??{}},{streaming:t||!1}),s={type:"register",methods:[{id:e.repoId,name:n.name,display_name:n.displayName,description:n.description,version:n.version,flags:i,object_types:n.objectTypes||n.object_types,input_signature:n.accepts,result_signature:n.returns,restrictions:void 0}]};return this.session.send(s,{methodId:e.repoId}).then((()=>{this.logger.debug("registered method "+e.definition.name+" with id "+e.repoId)})).catch((t=>{throw this.logger.warn(`failed to register method ${e.definition.name} with id ${e.repoId} - ${JSON.stringify(t)}`),t}))}onInvoked(e){this.callbacks.add("onInvoked",e)}methodInvocationResult(e,t,n,i){let s;s=n||""===n?{type:"error",request_id:t,reason_uri:"agm.errors.client_error",reason:n,context:i,peer_id:void 0}:{type:"yield",invocation_id:t,peer_id:this.session.peerId,result:i,request_id:void 0},this.session.sendFireAndForget(s)}async unregister(e){const t={type:"unregister",methods:[e.repoId]};await this.session.send(t)}getBranchList(e){return this.streaming.getBranchList(e)}getSubscriptionList(e,t){return this.streaming.getSubscriptionList(e,t)}closeAllSubscriptions(e,t){this.streaming.closeMultipleSubscriptions(e,t)}pushData(e,t,n){this.streaming.pushData(e,t,n)}pushDataToSingle(e,t,n){this.streaming.pushDataToSingle(e,t,n)}closeSingleSubscription(e,t){this.streaming.closeSingleSubscription(e,t)}acceptRequestOnBranch(e,t,n){this.streaming.acceptRequestOnBranch(e,t,n)}rejectRequest(e,t,n){this.streaming.rejectRequest(e,t,n)}onSubRequest(e){this.streaming.onSubRequest(e)}onSubAdded(e){this.streaming.onSubAdded(e)}onSubRemoved(e){this.streaming.onSubRemoved(e)}handleInvokeMessage(e){const t=e.invocation_id,n=e.caller_id,i=e.method_id,s=e.arguments_kv,r=this.serverRepository.getList().filter((e=>e.repoId===i))[0];if(void 0===r)return;const o=this.clientRepository.getServerById(n)?.instance,a={args:s,instance:o};this.callbacks.execute("onInvoked",r,t,a)}}class Wo{repository;subscriptionData;get requestArguments(){return this.subscriptionData.params.arguments||{}}get servers(){return this.subscriptionData.trackedServers.reduce(((e,t)=>{if(t.subscriptionId){const n=this.repository.getServerById(t.serverId)?.instance;n&&e.push(n)}return e}),[])}get serverInstance(){return this.servers[0]}get stream(){return this.subscriptionData.method}constructor(e,t){this.repository=e,this.subscriptionData=t}onData(e){if("function"!=typeof e)throw new TypeError("The data callback must be a function.");this.subscriptionData.handlers.onData.push(e),1===this.subscriptionData.handlers.onData.length&&this.subscriptionData.queued.data.length>0&&this.subscriptionData.queued.data.forEach((t=>{e(t)}))}onClosed(e){if("function"!=typeof e)throw new TypeError("The callback must be a function.");this.subscriptionData.handlers.onClosed.push(e)}onFailed(e){}onConnected(e){if("function"!=typeof e)throw new TypeError("The callback must be a function.");this.subscriptionData.handlers.onConnected.push(e)}close(){this.subscriptionData.close()}setNewSubscription(e){this.subscriptionData=e}}class Fo{config;cache=[];timeoutIds=[];constructor(e){this.config=e}add(e){const t=Wr(10);this.cache.push({id:t,element:e});const n=setTimeout((()=>{const e=this.cache.findIndex((e=>e.id===t));e<0||this.cache.splice(e,1)}),this.config.ELEMENT_TTL_MS);this.timeoutIds.push(n)}flush(){const e=this.cache.map((e=>e.element));return this.timeoutIds.forEach((e=>clearInterval(e))),this.cache=[],this.timeoutIds=[],e}}const Lo="awaitingAccept",qo="subscribed",Go="Subscription failed.",Bo="ClientInitiated";class Uo{session;repository;logger;subscriptionsList={};timedCache=new Fo({ELEMENT_TTL_MS:1e4});subscriptionIdToLocalKeyMap={};nextSubLocalKey=0;constructor(e,t,n){this.session=e,this.repository=t,this.logger=n,e.on("subscribed",this.handleSubscribed),e.on("event",this.handleEventData),e.on("subscription-cancelled",this.handleSubscriptionCancelled)}subscribe(e,t,n,i,s,r){if(0===n.length)return void s({method:e,called_with:t.arguments,message:Go+" No available servers matched the target params."});const o=this.getNextSubscriptionLocalKey(),a=this.registerSubscription(o,e,t,i,s,t.methodResponseTimeout||1e4,r);"object"==typeof a?n.forEach((n=>{const i=n.server.id,s=n.methods.find((t=>t.name===e.name));if(!s)return void this.logger.error(`can not find method ${e.name} for target ${n.server.id}`);a.trackedServers.push({serverId:i,subscriptionId:void 0});const r={type:"subscribe",server_id:i,method_id:s.gatewayId,arguments_kv:t.arguments};this.session.send(r,{serverId:i,subLocalKey:o}).then((e=>this.handleSubscribed(e))).catch((e=>this.handleErrorSubscribing(e)))})):s({method:e,called_with:t.arguments,message:Go+" Unable to register the user callbacks."})}drainSubscriptions(){const e=Object.values(this.subscriptionsList);return this.subscriptionsList={},this.subscriptionIdToLocalKeyMap={},e}drainSubscriptionsCache(){return this.timedCache.flush()}getNextSubscriptionLocalKey(){const e=this.nextSubLocalKey;return this.nextSubLocalKey+=1,e}registerSubscription(e,t,n,i,s,r,o){const a={localKey:e,status:Lo,method:t,params:n,success:i,error:s,trackedServers:[],handlers:{onData:o?.handlers.onData||[],onClosed:o?.handlers.onClosed||[],onConnected:o?.handlers.onConnected||[]},queued:{data:[],closers:[]},timeoutId:void 0,close:()=>this.closeSubscription(e),subscription:o?.subscription};return o||(n.onData&&a.handlers.onData.push(n.onData),n.onClosed&&a.handlers.onClosed.push(n.onClosed),n.onConnected&&a.handlers.onConnected.push(n.onConnected)),this.subscriptionsList[e]=a,a.timeoutId=setTimeout((()=>{if(void 0===this.subscriptionsList[e])return;const i=this.subscriptionsList[e];i.status===Lo?(s({method:t,called_with:n.arguments,message:Go+" Subscription attempt timed out after "+r+" ms."}),delete this.subscriptionsList[e]):i.status===qo&&i.trackedServers.length>0&&(i.trackedServers=i.trackedServers.filter((e=>void 0!==e.subscriptionId)),delete i.timeoutId,i.trackedServers.length<=0&&(this.callOnClosedHandlers(i),delete this.subscriptionsList[e]))}),r),a}handleErrorSubscribing=e=>{const t=e._tag,n=t.subLocalKey,i=this.subscriptionsList[n];if("object"==typeof i&&(i.trackedServers=i.trackedServers.filter((e=>e.serverId!==t.serverId)),i.trackedServers.length<=0)){if(clearTimeout(i.timeoutId),i.status===Lo){const t="string"==typeof e.reason&&""!==e.reason?' Publisher said "'+e.reason+'".':" No reason given.",n="object"==typeof i.params.arguments?JSON.stringify(i.params.arguments):"{}";i.error({message:"Subscription rejected."+t+" Called with:"+n,called_with:i.params.arguments,method:i.method})}else i.status===qo&&this.callOnClosedHandlers(i);delete this.subscriptionsList[n]}};handleSubscribed=e=>{const t=e._tag.subLocalKey,n=this.subscriptionsList[t];if("object"!=typeof n)return;const i=e._tag.serverId,s=n.trackedServers.filter((e=>e.serverId===i))[0];if("object"!=typeof s)return;s.subscriptionId=e.subscription_id,this.subscriptionIdToLocalKeyMap[e.subscription_id]=t;const r=n.status===Lo;if(n.status=qo,r){let e=!1,t=n.subscription;t?(t.setNewSubscription(n),n.success(t),e=!0):(t=new Wo(this.repository,n),n.subscription=t,n.success(t));for(const i of n.handlers.onConnected)try{i(t.serverInstance,e)}catch(e){}}};handleEventData=e=>{const t=this.subscriptionIdToLocalKeyMap[e.subscription_id];if(void 0===t)return;const n=this.subscriptionsList[t];if("object"!=typeof n)return;const i=n.trackedServers.filter((t=>t.subscriptionId===e.subscription_id));if(1!==i.length)return;const s=e.oob,r=i[0].serverId,o=this.repository.getServerById(r),a=()=>({data:e.data,server:o?.instance??{},requestArguments:n.params.arguments,message:void 0,private:s}),c=n.handlers.onData,d=n.queued.data;c.length>0?c.forEach((e=>{"function"==typeof e&&e(a())})):d.push(a())};handleSubscriptionCancelled=e=>{const t=this.subscriptionIdToLocalKeyMap[e.subscription_id];if(void 0===t)return;const n=this.subscriptionsList[t];if("object"!=typeof n)return;const i=n.trackedServers.length-1;n.trackedServers=n.trackedServers.filter((t=>t.subscriptionId!==e.subscription_id||(n.queued.closers.push(t.serverId),!1))),n.trackedServers.length===i&&(n.trackedServers.length<=0&&(this.timedCache.add(n),clearTimeout(n.timeoutId),this.callOnClosedHandlers(n),delete this.subscriptionsList[t]),delete this.subscriptionIdToLocalKeyMap[e.subscription_id])};callOnClosedHandlers(e,t){const n=e.queued.closers.length,i=n>0?e.queued.closers[n-1]:null;let s;void 0!==i&&"string"==typeof i&&(s=this.repository.getServerById(i)?.instance??{}),e.handlers.onClosed.forEach((n=>{"function"==typeof n&&n({message:t||"ServerInitiated",requestArguments:e.params.arguments||{},server:s,stream:e.method})}))}closeSubscription(e){const t=this.subscriptionsList[e];"object"==typeof t&&(t.trackedServers.forEach((e=>{void 0!==e.subscriptionId&&(t.queued.closers.push(e.serverId),this.session.sendFireAndForget({type:"unsubscribe",subscription_id:e.subscriptionId,reason_uri:"",reason:Bo}),delete this.subscriptionIdToLocalKeyMap[e.subscriptionId])})),t.trackedServers=[],this.callOnClosedHandlers(t,Bo),delete this.subscriptionsList[e])}}class Ho{session;repository;logger;streaming;constructor(e,t,n){this.session=e,this.repository=t,this.logger=n,e.on("peer-added",(e=>this.handlePeerAdded(e))),e.on("peer-removed",(e=>this.handlePeerRemoved(e))),e.on("methods-added",(e=>this.handleMethodsAddedMessage(e))),e.on("methods-removed",(e=>this.handleMethodsRemovedMessage(e))),this.streaming=new Uo(e,t,n)}subscribe(e,t,n,i,s,r){this.streaming.subscribe(e,t,n,i,s,r)}invoke(e,t,n,i){const s=i.id,r={type:"call",server_id:s,method_id:t.gatewayId,arguments_kv:n};return this.session.send(r,{invocationId:e,serverId:s}).then((e=>this.handleResultMessage(e))).catch((e=>this.handleInvocationError(e)))}drainSubscriptions(){return this.streaming.drainSubscriptions()}drainSubscriptionsCache(){return this.streaming.drainSubscriptionsCache()}handlePeerAdded(e){const t=e.new_peer_id,n=e.identity,i=!e.meta||e.meta.local,s=Number(n.process),r={machine:n.machine,pid:isNaN(s)?n.process:s,instance:n.instance,application:n.application,applicationName:n.applicationName,environment:n.environment,region:n.region,user:n.user,windowId:n.windowId,peerId:t,api:n.api,isLocal:i};this.repository.addServer(r,t)}handlePeerRemoved(e){const t=e.removed_id,n=e.reason;this.repository.removeServerById(t,n)}handleMethodsAddedMessage(e){const t=e.server_id;e.methods.forEach((e=>{this.repository.addServerMethod(t,e)}))}handleMethodsRemovedMessage(e){const t=e.server_id,n=e.methods,i=this.repository.getServerById(t);if(i){Object.keys(i.methods).forEach((e=>{const s=i.methods[e];n.indexOf(s.gatewayId)>-1&&this.repository.removeServerMethod(t,e)}))}}handleResultMessage(e){const t=e._tag.invocationId,n=e.result,i=e._tag.serverId,s=this.repository.getServerById(i);return{invocationId:t,result:n,instance:s?.instance,status:Io.Success,message:""}}handleInvocationError(e){if(this.logger.debug(`handle invocation error ${JSON.stringify(e)}`),"_tag"in e){const t=e._tag.invocationId,n=e._tag.serverId,i=this.repository.getServerById(n),s=e.reason;return{invocationId:t,result:e.context,instance:i?.instance,status:Io.Error,message:s}}return{invocationId:"",message:e.message,status:Io.Error,error:e}}}function Jo(e,t,n,i,s,r){const o=s.logger.subLogger("gw3-protocol");let a;const c=new Promise((e=>{a=e})),d=t.domain("agm",["subscribed"]),l=new $o(d,n,i,o.subLogger("server")),h=new Ho(d,n,o.subLogger("client"));return d.onJoined((s=>{n.addServer(e,t.peerId),s?async function(){o.info("reconnected - will replay registered methods and subscriptions"),h.drainSubscriptionsCache().forEach((e=>{const t=e.method,n=Object.assign({},e.params);o.info(`trying to soft-re-subscribe to method ${t.name}, with params: ${JSON.stringify(n)}`),r.client.subscribe(t,n,void 0,void 0,e).then((()=>o.info(`soft-subscribing to method ${t.name} DONE`))).catch((e=>o.warn(`subscribing to method ${t.name} failed: ${JSON.stringify(e)}}`)))}));const e=[],t=h.drainSubscriptions();for(const n of t){const t=n.method,i=Object.assign({},n.params);o.info(`trying to re-subscribe to method ${t.name}, with params: ${JSON.stringify(i)}`),e.push(r.client.subscribe(t,i,void 0,void 0,n).then((()=>o.info(`subscribing to method ${t.name} DONE`))))}const n=i.getList();i.reset();for(const t of n){const n=t.definition;t.stream?e.push(r.server.createStream(n,t.streamCallbacks,void 0,void 0,t.stream).then((()=>o.info(`subscribing to method ${n.name} DONE`))).catch((()=>o.warn(`subscribing to method ${n.name} FAILED`)))):t?.theFunction?.userCallback?e.push(r.register(n,t.theFunction.userCallback).then((()=>o.info(`registering method ${n.name} DONE`))).catch((()=>o.warn(`registering method ${n.name} FAILED`)))):t?.theFunction?.userCallbackAsync&&e.push(r.registerAsync(n,t.theFunction.userCallbackAsync).then((()=>o.info(`registering method ${n.name} DONE`))).catch((()=>o.warn(`registering method ${n.name} FAILED`))))}await Promise.all(e),o.info("Interop is re-announced")}().then((()=>t.setLibReAnnounced({name:"interop"}))).catch((e=>o.warn(`Error while re-announcing interop: ${JSON.stringify(e)}`))):a&&(a({client:h,server:l}),a=void 0)})),d.onLeft((()=>{n.reset()})),d.join(),c}class Ko{instance;readyPromise;client;server;unwrappedInstance;protocol;clientRepository;serverRepository;constructor(e){if(void 0===e)throw new Error("configuration is required");if(void 0===e.connection)throw new Error("configuration.connections is required");const t=e.connection;let n;if("number"!=typeof e.methodResponseTimeout&&(e.methodResponseTimeout=3e4),"number"!=typeof e.waitTimeoutMs&&(e.waitTimeoutMs=3e4),this.unwrappedInstance=new Ao(this,void 0,t),this.instance=this.unwrappedInstance.unwrap(),this.clientRepository=new Mo(e.logger.subLogger("cRep"),this),this.serverRepository=new Oo,3!==t.protocolVersion)throw new Error(`protocol ${t.protocolVersion} not supported`);n=Jo(this.instance,t,this.clientRepository,this.serverRepository,e,this),this.readyPromise=n.then((t=>(this.protocol=t,this.client=new So(this.protocol,this.clientRepository,this.instance,e),this.server=new Ro(this.protocol,this.serverRepository),this)))}ready(){return this.readyPromise}serverRemoved(e){return this.client.serverRemoved(e)}serverAdded(e){return this.client.serverAdded(e)}serverMethodRemoved(e){return this.client.serverMethodRemoved(e)}serverMethodAdded(e){return this.client.serverMethodAdded(e)}methodRemoved(e){return this.client.methodRemoved(e)}methodAdded(e){return this.client.methodAdded(e)}methodsForInstance(e){return this.client.methodsForInstance(e)}methods(e){return this.client.methods(e)}servers(e){return this.client.servers(e)}subscribe(e,t,n,i){return this.client.subscribe(e,t,n,i)}createStream(e,t,n,i){return this.server.createStream(e,t,n,i)}unregister(e){return this.server.unregister(e)}registerAsync(e,t){return this.server.registerAsync(e,t)}register(e,t){return this.server.register(e,t)}invoke(e,t,n,i,s,r){return this.client.invoke(e,t,n,i,s,r)}waitForMethod(e){const t=new Or,n=this.client.methodAdded((i=>{i.name===e&&(n(),t.resolve(i))}));return t.promise}}const zo=["subscribed","success"];class Vo{connection;logger;peerId;session;subscriptions;readyPromise;constructor(e,t){this.connection=e,this.logger=t,this.peerId=e.peerId,this.subscriptions=[],this.session=e.domain("bus",zo),this.readyPromise=this.session.join(),this.readyPromise.then((()=>{this.watchOnEvent()}))}ready(){return this.readyPromise}publish=(e,t,n)=>{const{routingKey:i,target:s}=n||{},r=this.removeEmptyValues({type:"publish",topic:e,data:t,peer_id:this.peerId,routing_key:i,target_identity:s});this.session.send(r)};subscribe=(e,t,n)=>new Promise(((i,s)=>{const{routingKey:r,target:o}=n||{},a=this.removeEmptyValues({type:"subscribe",topic:e,peer_id:this.peerId,routing_key:r,source:o});this.session.send(a).then((n=>{const{subscription_id:s}=n;this.subscriptions.push({subscription_id:s,topic:e,callback:t,source:o}),i({unsubscribe:()=>(this.session.send({type:"unsubscribe",subscription_id:s,peer_id:this.peerId}),this.subscriptions=this.subscriptions.filter((e=>e.subscription_id!==s)),Promise.resolve())})})).catch((e=>s(e)))}));watchOnEvent=()=>{this.session.on("event",(e=>{const{data:t,subscription_id:n}=e,i=e["publisher-identity"],s=this.subscriptions.find((e=>e.subscription_id===n));s&&(s.source?this.keysMatch(s.source,i)&&s.callback(t,s.topic,i):s.callback(t,s.topic,i))}))};removeEmptyValues(e){const t={};return Object.keys(e).forEach((n=>{void 0!==e[n]&&null!==e[n]&&(t[n]=e[n])})),t}keysMatch(e,t){const n=Object.keys(e);let i=!0;return n.forEach((n=>{e[n]!==t[n]&&(i=!1)})),i}}const Qo=(e,t)=>{const n="object"==typeof window?window.iodesktop??window.glue42gd:void 0,i="object"==typeof window?window.gdPreloadPromise??Promise.resolve():Promise.resolve(),s=Dr("glue"),r=function(e,t,n){let i;if(Mr.isNode()){const e=process.env._GD_STARTING_CONTEXT_;if(e)try{i=JSON.parse(e)}catch{}}function s(){if(e.application)return e.application;if(n)return n.applicationName;if("undefined"!=typeof window&&void 0!==window.glue42electron)return window.glue42electron.application;const t=Wr(10);return Mr.isNode()?i?i.applicationConfig.name:"NodeJS"+t:"undefined"!=typeof window&&"undefined"!=typeof document?document.title+` (${t})`:t}const r=function(){const r=e.gateway,o=r?.protocolVersion??3,a=r?.reconnectInterval,c=r?.reconnectAttempts;let d=r?.ws;const l=r?.sharedWorker,h=r?.inproc,u=r?.webPlatform??void 0;let p,g,m,f,w;n&&(d=n.gwURL),Mr.isNode()&&i&&i.gwURL&&(d=i.gwURL),d||l||h||(d="ws://localhost:8385");const b=s();let y=b;void 0!==n?(g=n.windowId,m=n.pid,n.env&&(f=n.env.env,w=n.env.region),y=n.application??"glue-app",p=n.appInstanceId):Mr.isNode()?(m=process.pid,i&&(f=i.env,w=i.region,p=i.instanceId)):void 0!==window?.glue42electron&&(g=window?.glue42electron.instanceId,m=window?.glue42electron.pid,f=window?.glue42electron.env,w=window?.glue42electron.region,y=window?.glue42electron.application??"glue-app",p=window?.glue42electron.instanceId);const v=e.gateway?.replaySpecs??[];v.push(ro);let C={application:y,applicationName:b,windowId:g,instance:p,process:m,region:w,environment:f,api:t.version||oo};return e.identity&&(C=Object.assign(C,e.identity)),{identity:C,reconnectInterval:a,ws:d,sharedWorker:l,webPlatform:u,inproc:h,protocolVersion:o,reconnectAttempts:c,replaySpecs:v}}();let o=s();if("undefined"!=typeof window){const e=window,t=e.htmlContainer?`${e.htmlContainer.containerName}.${e.htmlContainer.application}`:e?.glue42gd?.application;t&&(o=t)}return{bus:e.bus??!1,application:o,auth:"string"==typeof e.auth?{token:e.auth}:e.auth?e.auth:Mr.isNode()&&i&&i.gwToken?{gatewayToken:i.gwToken}:e.gateway?.webPlatform||e.gateway?.inproc||e.gateway?.sharedWorker?{username:"glue42",password:"glue42"}:void 0,logger:function(){let t=e.logger;const i="warn";let s;return t||(t=i),n&&(s=n.consoleLogLevel),"string"==typeof t?{console:s??t,publish:i}:{console:s??t.console??i,publish:t.publish??i}}(),connection:r,metrics:e.metrics??!0,contexts:void 0===e.contexts||"boolean"==typeof e.contexts&&e.contexts?{reAnnounceKnownContexts:!0}:"object"==typeof e.contexts&&Object.assign({},{reAnnounceKnownContexts:!0},e.contexts),version:t.version||oo,libs:t.libs??[],customLogger:e.customLogger}}(e=e||{},t=t||{},n);let o,a,c,d,l,h,u;const p={};function g(e,t,n){u=c.canPublish("trace"),u&&c.trace(`registering ${e} module`);const i=()=>{t.initTime=n.stop(),t.initEndTime=n.endTime,t.marks=n.marks,u&&c.trace(`${e} is ready - ${n.endTime-n.startTime}`)};t.initStartTime=n.startTime,t.ready?t.ready().then((()=>{i()})):i(),Array.isArray(e)||(e=[e]),e.forEach((e=>{p[e]=t,Qo[e]=t}))}function m(){const e=Dr("metrics"),t=r.metrics,i=n?.getMetricsPublishingEnabled,s=r.connection.identity,a=i||(()=>!0),l=("boolean"!=typeof t&&t.disableAutoAppSystem)??!1;return d=_r({connection:t?o:void 0,logger:c.subLogger("metrics"),canUpdateMetric:a,system:"Glue42",service:s?.service??n?.applicationName??r.application,instance:s?.instance??s?.windowId??Wr(10),disableAutoAppSystem:l,pagePerformanceMetrics:"boolean"!=typeof t?t?.pagePerformanceMetrics:void 0}),g("metrics",d,e),Promise.resolve()}function f(){const e=Dr("interop"),t={connection:o,logger:c.subLogger("interop")};return a=new Ko(t),Hr.Interop=a,g(["interop","agm"],a,e),Promise.resolve()}function w(){const e=r.activities&&3===o.protocolVersion;if(r.contexts||e){const e=Dr("contexts");return l=new yo({connection:o,logger:c.subLogger("contexts"),trackAllContexts:"object"==typeof r.contexts&&r.contexts.trackAllContexts,reAnnounceKnownContexts:"object"==typeof r.contexts&&r.contexts.reAnnounceKnownContexts}),g("contexts",l,e),l}{const e=o.replayer;e&&e.drain(ro.name)}}async function b(){if(!r.bus)return Promise.resolve();const e=Dr("bus");return h=new Vo(o,c.subLogger("bus")),g("bus",h,e),Promise.resolve()}function y(e){try{return e.forEach((e=>{!function(e,t){const n=Dr(e),i=t(p);i&&g(e,i,n)}(e.name,e.create)})),Promise.resolve()}catch(e){return Promise.reject(e)}}return i.then((function(){const e=Dr("logger");return c=new Hr(`${r.connection.identity?.application}`,void 0,r.customLogger),c.consoleLevel(r.logger.console),c.publishLevel(r.logger.publish),c.canPublish("debug")&&c.debug("initializing glue..."),g("logger",c,e),Promise.resolve(void 0)})).then((function(){const e=Dr("connection");o=new Br(r.connection,c.subLogger("connection"));let t=Promise.resolve(r.auth);return r.connection&&!r.auth&&(n?t=n.getGWToken().then((e=>({gatewayToken:e}))):"undefined"!=typeof window&&window?.glue42electron?"string"==typeof window.glue42electron.gwToken&&(t=Promise.resolve({gatewayToken:window.glue42electron.gwToken})):t=Promise.reject("You need to provide auth information")),t.then((t=>{let n;if(e.mark("auth-promise-resolved"),"[object Object]"!==Object.prototype.toString.call(t))throw new Error("Invalid auth object - "+JSON.stringify(t));return n=t,o.login(n)})).then((()=>(g("connection",o,e),r))).catch((e=>{throw o&&o.logout(),e}))})).then((()=>Promise.all([m(),f(),w(),b()]))).then((()=>a.readyPromise)).then((()=>async function(){const t="T42.ACS.RegisterInstance";if(Mr.isNode()&&void 0===process.env._GD_STARTING_CONTEXT_&&void 0!==e?.application&&a.methods({name:t}).length>0)try{await a.invoke(t,{appName:e?.application,pid:process.pid})}catch(e){const t=e;c.error(`Cannot register as an instance: ${JSON.stringify(t.message)}`)}}())).then((()=>y(r.libs||[]))).then((function(){const e=Object.keys(p).map((e=>{const t=p[e];return t.ready?t.ready():Promise.resolve()}));return Promise.all(e)})).then((function(){const i={coreVersion:oo,version:r.version};s.stop();const u={feedback:e=>{a&&a.invoke("T42.ACS.Feedback",e,"best")},info:i,logger:c,interop:a,agm:a,connection:o,metrics:d,contexts:l,bus:h,version:r.version,userConfig:e,done:()=>(c?.info("done called by user..."),o.logout())};if(u.performance={get glueVer(){return r.version},get glueConfig(){return JSON.stringify(e)},get browser(){return window.performance.timing.toJSON()},get memory(){return window.performance.memory},get initTimes(){const e=Er;return Object.keys(e).map((t=>{const n=e[t];return{name:t,duration:n.endTime-n.startTime,marks:n.marks,startTime:n.startTime,endTime:n.endTime}}))}},Object.keys(p).forEach((e=>{const t=p[e];u[e]=t})),u.config={},Object.keys(r).forEach((e=>{u.config[e]=r[e]})),t&&t.extOptions&&Object.keys(t.extOptions).forEach((e=>{u.config[e]=t?.extOptions[e]})),t?.enrichGlue&&t.enrichGlue(u),n&&n.updatePerfData&&n.updatePerfData(u.performance),u.agm){const e=(e,t,n)=>function(){return u.logger.warn(`glue.js - 'glue.agm.${t}' method is deprecated, use 'glue.interop.${n}' instead.`),e.apply(u.agm,arguments)},t=u.agm;t.method_added=e(u.agm.methodAdded,"method_added","methodAdded"),t.method_removed=e(u.agm.methodRemoved,"method_removed","methodRemoved"),t.server_added=e(u.agm.serverAdded,"server_added","serverAdded"),t.server_method_aded=e(u.agm.serverMethodAdded,"server_method_aded","serverMethodAdded"),t.server_method_removed=e(u.agm.serverMethodRemoved,"server_method_removed","serverMethodRemoved")}return u})).catch((e=>Promise.reject({err:e,libs:p})))};"undefined"!=typeof window&&(window.IOConnectCore=Qo),Qo.version=oo,Qo.default=Qo;const Xo=(n=>{let i;return s=>{if(window.glue42gd||window.iodesktop)return(e=>{const t={windows:!0,layouts:"full",appManager:"full",channels:!0,libraries:e?.libraries??[],logger:e?.systemLogger?.level??"warn"};return(window.IODesktop||window.Glue)(t)})(s);const r=(n=>{const i=!!n?.gateway?.webPlatform?.port,s=Object.assign({},e,n,{isPlatformInternal:i});return s.systemLogger&&(s.logger=s.systemLogger.level??"info"),s.widget&&(s.widget={...t,...s.widget}),s})(s);try{(()=>{const e=window.glue42core||window.iobrowser;if(e&&e.webStarted)return f.raiseError("IoConnect Browser has already been started for this application.");e?e.webStarted=!0:window.iobrowser={webStarted:!0}})()}catch(e){return void 0===i?Promise.reject(new Error(e)):i}const o=(async e=>{const t=new nr,i=await Hi((()=>n(e,{version:ir})),3e4,"Glue Web initialization timed out, because core didn't resolve"),s=i.logger.subLogger("web.main.controller");t.defineGlue(i),t.sessionController.configure({windowId:i.interop.instance.instance}),await t.preferredConnectionController.start(e),await t.bridge.start(t.controllers),t.defineConfig(e),s.trace("the bridge has been started, initializing all controllers"),await Promise.all(Object.values(t.controllers).map((e=>e.start(i,t)))),s.trace("all controllers reported started, starting all additional libraries");try{return await Promise.all(e.libraries.map((t=>t(i,e)))),s.trace("all libraries were started"),t.eventsDispatcher.start(i),s.trace("start event dispatched, glue is ready, returning it"),await t.uiController.showComponents(i).catch((e=>s.warn(e?.message?e.message:JSON.stringify(e)))),await Promise.all(Object.values(t.controllers).map((e=>e.postStart?e.postStart(i,t):Promise.resolve()))),i}catch(e){return f.raiseError(e,!0)}})(r);return i=s?.memoizeAPI?o:void 0,o}})(Qo);if("undefined"!=typeof window){const e=window;e.IOBrowser=Xo,delete e.GlueCore,delete e.IOConnectCore}const Yo=window.glue42gd||window.glue42core,Zo=window.iodesktop||window.iobrowser;return Yo||Zo||(window.iobrowser={webStarted:!1}),Xo.version=ir,Xo}));