@interopio/browser 4.5.0 → 4.6.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.
- package/changelog.md +2 -0
- package/dist/browser.es.js +10 -5
- package/dist/browser.es.js.map +1 -1
- package/dist/browser.umd.js +10 -5
- package/dist/browser.umd.js.map +1 -1
- package/dist/browser.umd.min.js +1 -1
- package/package.json +6 -6
package/dist/browser.umd.min.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
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";function e(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var t=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===n}(e)}(e)};var n="function"==typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function i(e,t){return!1!==t.clone&&t.isMergeableObject(e)?c((n=e,Array.isArray(n)?[]:{}),e,t):e;var n}function r(e,t,n){return e.concat(t).map(function(e){return i(e,n)})}function s(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 o(e,t){try{return t in e}catch(e){return!1}}function a(e,t,n){var r={};return n.isMergeableObject(e)&&s(e).forEach(function(t){r[t]=i(e[t],n)}),s(t).forEach(function(s){(function(e,t){return o(e,t)&&!(Object.hasOwnProperty.call(e,t)&&Object.propertyIsEnumerable.call(e,t))})(e,s)||(o(e,s)&&n.isMergeableObject(t[s])?r[s]=function(e,t){if(!t.customMerge)return c;var n=t.customMerge(e);return"function"==typeof n?n:c}(s,n)(e[s],t[s],n):r[s]=i(t[s],n))}),r}function c(e,n,s){(s=s||{}).arrayMerge=s.arrayMerge||r,s.isMergeableObject=s.isMergeableObject||t,s.cloneUnlessOtherwiseSpecified=i;var o=Array.isArray(n);return o===Array.isArray(e)?o?s.arrayMerge(e,n,s):a(e,n,s):i(n,s)}c.all=function(e,t){if(!Array.isArray(e))throw new Error("first argument should be an array");return e.reduce(function(e,n){return c(e,n,t)},{})};var d=e(c),l=function(e){return{ok:!0,result:e}},h=function(e){return{ok:!1,error:e}},u=function(e,t,n){return!1===t.ok?t:!1===n.ok?n:l(e(t.result,n.result))},p=function(e,t){return!0===t.ok?t:h(e(t.error))},g=function(){return g=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},g.apply(this,arguments)};function f(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(!f(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(!f(e[i[n]],t[i[n]]))return!1}return!0}}var m=function(e){return Array.isArray(e)},b=function(e){return"object"==typeof e&&null!==e&&!m(e)},y=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)},w=function(e){return e.map(function(e){return"string"==typeof e?"."+e:"["+e+"]"}).join("")},v=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 r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(t,["at"]);return g({at:e+(n||"")},i)},C=function(){function e(t){var n=this;this.decode=t,this.run=function(e){return p(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?l(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?l(e):h({message:y("a string",e)})})},e.number=function(){return new e(function(e){return"number"==typeof e?l(e):h({message:y("a number",e)})})},e.boolean=function(){return new e(function(e){return"boolean"==typeof e?l(e):h({message:y("a boolean",e)})})},e.constant=function(t){return new e(function(e){return f(e,t)?l(t):h({message:"expected "+JSON.stringify(t)+", got "+JSON.stringify(e)})})},e.object=function(t){return new e(function(e){if(b(e)&&t){var n={};for(var i in t)if(t.hasOwnProperty(i)){var r=t[i].decode(e[i]);if(!0!==r.ok)return void 0===e[i]?h({message:"the key '"+i+"' is required but was not present"}):h(v("."+i,r.error));void 0!==r.result&&(n[i]=r.result)}return l(n)}return b(e)?l(e):h({message:y("an object",e)})})},e.array=function(t){return new e(function(e){if(m(e)&&t){return e.reduce(function(e,n,i){return u(function(e,t){return e.concat([t])},e,function(e,n){return p(function(e){return v("["+n+"]",e)},t.decode(e))}(n,i))},l([]))}return m(e)?l(e):h({message:y("an array",e)})})},e.tuple=function(t){return new e(function(e){if(m(e)){if(e.length!==t.length)return h({message:"expected a tuple of length "+t.length+", got one of length "+e.length});for(var n=[],i=0;i<t.length;i++){var r=t[i].decode(e[i]);if(!r.ok)return h(v("["+i+"]",r.error));n[i]=r.result}return l(n)}return h({message:y("a tuple of length "+t.length,e)})})},e.union=function(t,n){for(var i=[],r=2;r<arguments.length;r++)i[r-2]=arguments[r];return e.oneOf.apply(e,[t,n].concat(i))},e.intersection=function(t,n){for(var i=[],r=2;r<arguments.length;r++)i[r-2]=arguments[r];return new e(function(e){return[t,n].concat(i).reduce(function(t,n){return u(Object.assign,t,n.decode(e))},l({}))})},e.anyJson=function(){return new e(function(e){return l(e)})},e.unknownJson=function(){return new e(function(e){return l(e)})},e.dict=function(t){return new e(function(e){if(b(e)){var n={};for(var i in e)if(e.hasOwnProperty(i)){var r=t.decode(e[i]);if(!0!==r.ok)return h(v("."+i,r.error));n[i]=r.result}return l(n)}return h({message:y("an object",e)})})},e.optional=function(t){return new e(function(e){return null==e?l(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 r=t[i].decode(e);if(!0===r.ok)return r;n[i]=r.error}var s=n.map(function(e){return"at error"+(e.at||"")+": "+e.message}).join('", "');return h({message:'expected a value matching one of the decoders, got the errors ["'+s+'"]'})})},e.withDefault=function(t,n){return new e(function(e){return l(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,r=0;r<t.length;r++){if(void 0===i)return h({at:w(t.slice(0,r+1)),message:"path does not exist"});if("string"==typeof t[r]&&!b(i))return h({at:w(t.slice(0,r+1)),message:y("an object",i)});if("number"==typeof t[r]&&!m(i))return h({at:w(t.slice(0,r+1)),message:y("an array",i)});i=i[t[r]]}return p(function(e){return void 0===i?{at:w(t),message:"path does not exist"}:v(w(t),e)},n.decode(i))})},e.succeed=function(t){return new e(function(e){return l(t)})},e.fail=function(t){return new e(function(e){return h({message:t})})},e.lazy=function(t){return new e(function(e){return t().decode(e)})},e}(),I=C.string,S=C.number,_=C.boolean,x=C.anyJson;C.unknownJson;var T=C.constant,P=C.object,k=C.array;C.tuple,C.dict;var O=C.optional,R=C.oneOf,A=C.union,M=C.intersection;C.withDefault,C.valueAt,C.succeed,C.fail;var E=C.lazy;const D={gateway:{webPlatform:{}},libraries:[],exposeAPI:!0},j={awaitFactory:!0,enable:!1,timeout:5e3,restoreLastKnownPosition:!0},N={alerts:{enabled:!1},dialogs:{enabled:!1},awaitFactory:!0,timeout:5e3},F={enable:!1,timeout:5e3,awaitFactory:!0},L={name:"platformUnload"},$={name:"transportSwitchRequest"},W={name:"transportSwitchResponse"},H={name:"getCurrentTransport"},U={name:"getCurrentTransportResponse"},q={name:"checkPreferredLogic"},B={name:"checkPreferredConnection"},G={name:"checkPreferredLogicResponse"},J={name:"checkPreferredConnectionResponse"},z="web-platform",V="latest_fdc3_type",K=new MessageChannel,Z=2147483647,Q={configurable:!1,enumerable:!0,writable:!1},Y=e=>"string"==typeof e?e:e?.message?"string"==typeof e.message?e.message:JSON.stringify(e.message):JSON.stringify(e),X=(e,t)=>{try{return e.runWithException(t)}catch(e){return re.raiseError(e,!0)}},ee=e=>Object.keys(e).filter(t=>e[t].execute),te=(e,t)=>({isSupported:e.some(e=>e.toLowerCase()===t.toLowerCase())}),ne=e=>Math.min(e,Z),ie=()=>{let e,t;return{promise:new Promise((n,i)=>{e=n,t=i}),resolve:e,reject:t}};const re=new class{raiseError(e,t){const n=Y(e);if(K.port1.postMessage(n),t)throw e;throw new Error(n)}},se=["name","title","version","customProperties","icon","caption","type"],oe=["appId","name","type","details","version","title","tooltip","lang","description","categories","icons","screenshots","contactEmail","moreInfo","publisher","customConfig","hostManifests","interop","localizedVersions"];var ae=function(e){return{ok:!0,result:e}},ce=function(e){return{ok:!1,error:e}},de=function(e,t,n){return!1===t.ok?t:!1===n.ok?n:ae(e(t.result,n.result))},le=function(e,t){return!0===t.ok?t:ce(e(t.error))},he=function(){return he=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},he.apply(this,arguments)};function ue(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(!ue(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(!ue(e[i[n]],t[i[n]]))return!1}return!0}}var pe=function(e){return Array.isArray(e)},ge=function(e){return"object"==typeof e&&null!==e&&!pe(e)},fe=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)},me=function(e){return e.map(function(e){return"string"==typeof e?"."+e:"["+e+"]"}).join("")},be=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 r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(t,["at"]);return he({at:e+(n||"")},i)},ye=function(){function e(t){var n=this;this.decode=t,this.run=function(e){return le(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?ae(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?ae(e):ce({message:fe("a string",e)})})},e.number=function(){return new e(function(e){return"number"==typeof e?ae(e):ce({message:fe("a number",e)})})},e.boolean=function(){return new e(function(e){return"boolean"==typeof e?ae(e):ce({message:fe("a boolean",e)})})},e.constant=function(t){return new e(function(e){return ue(e,t)?ae(t):ce({message:"expected "+JSON.stringify(t)+", got "+JSON.stringify(e)})})},e.object=function(t){return new e(function(e){if(ge(e)&&t){var n={};for(var i in t)if(t.hasOwnProperty(i)){var r=t[i].decode(e[i]);if(!0!==r.ok)return void 0===e[i]?ce({message:"the key '"+i+"' is required but was not present"}):ce(be("."+i,r.error));void 0!==r.result&&(n[i]=r.result)}return ae(n)}return ge(e)?ae(e):ce({message:fe("an object",e)})})},e.array=function(t){return new e(function(e){if(pe(e)&&t){return e.reduce(function(e,n,i){return de(function(e,t){return e.concat([t])},e,function(e,n){return le(function(e){return be("["+n+"]",e)},t.decode(e))}(n,i))},ae([]))}return pe(e)?ae(e):ce({message:fe("an array",e)})})},e.tuple=function(t){return new e(function(e){if(pe(e)){if(e.length!==t.length)return ce({message:"expected a tuple of length "+t.length+", got one of length "+e.length});for(var n=[],i=0;i<t.length;i++){var r=t[i].decode(e[i]);if(!r.ok)return ce(be("["+i+"]",r.error));n[i]=r.result}return ae(n)}return ce({message:fe("a tuple of length "+t.length,e)})})},e.union=function(t,n){for(var i=[],r=2;r<arguments.length;r++)i[r-2]=arguments[r];return e.oneOf.apply(e,[t,n].concat(i))},e.intersection=function(t,n){for(var i=[],r=2;r<arguments.length;r++)i[r-2]=arguments[r];return new e(function(e){return[t,n].concat(i).reduce(function(t,n){return de(Object.assign,t,n.decode(e))},ae({}))})},e.anyJson=function(){return new e(function(e){return ae(e)})},e.unknownJson=function(){return new e(function(e){return ae(e)})},e.dict=function(t){return new e(function(e){if(ge(e)){var n={};for(var i in e)if(e.hasOwnProperty(i)){var r=t.decode(e[i]);if(!0!==r.ok)return ce(be("."+i,r.error));n[i]=r.result}return ae(n)}return ce({message:fe("an object",e)})})},e.optional=function(t){return new e(function(e){return null==e?ae(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 r=t[i].decode(e);if(!0===r.ok)return r;n[i]=r.error}var s=n.map(function(e){return"at error"+(e.at||"")+": "+e.message}).join('", "');return ce({message:'expected a value matching one of the decoders, got the errors ["'+s+'"]'})})},e.withDefault=function(t,n){return new e(function(e){return ae(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,r=0;r<t.length;r++){if(void 0===i)return ce({at:me(t.slice(0,r+1)),message:"path does not exist"});if("string"==typeof t[r]&&!ge(i))return ce({at:me(t.slice(0,r+1)),message:fe("an object",i)});if("number"==typeof t[r]&&!pe(i))return ce({at:me(t.slice(0,r+1)),message:fe("an array",i)});i=i[t[r]]}return le(function(e){return void 0===i?{at:me(t),message:"path does not exist"}:be(me(t),e)},n.decode(i))})},e.succeed=function(t){return new e(function(e){return ae(t)})},e.fail=function(t){return new e(function(e){return ce({message:t})})},e.lazy=function(t){return new e(function(e){return t().decode(e)})},e}(),we=ye.string,ve=ye.number,Ce=ye.boolean,Ie=ye.anyJson;ye.unknownJson;var Se=ye.constant,_e=ye.object,xe=ye.array;ye.tuple;var Te=ye.dict,Pe=ye.optional,ke=ye.oneOf;ye.union,ye.intersection,ye.withDefault,ye.valueAt,ye.succeed;var Oe=ye.fail;ye.lazy;const Re=we().where(e=>e.length>0,"Expected a non-empty string"),Ae=ve().where(e=>e>=0,"Expected a non-negative number"),Me=Ie().andThen(e=>e instanceof RegExp?Ie():Oe("expected a regex, got a "+typeof e)),Ee=Re.andThen(e=>{try{const{protocol:t}=new URL(e),n=["data:","javascript:","vbscript:"];return n.includes(t)?Oe(`Expected a URL with a safe protocol, got: ${t} (disallowed protocols: ${n.join(", ")})`):Re}catch{return Oe("Expected a valid URL")}}),De=_e({name:Re,displayName:Pe(we()),contexts:Pe(xe(we())),customConfig:Pe(_e())}),je=ke(Se("web"),Se("native"),Se("citrix"),Se("onlineNative"),Se("other")),Ne=_e({url:Ee}),Fe=_e({src:Re,size:Pe(Re),type:Pe(Re)}),Le=_e({src:Re,size:Pe(Re),type:Pe(Re),label:Pe(Re)}),$e=_e({contexts:xe(Re),displayName:Pe(Re),resultType:Pe(Re),customConfig:Pe(Ie())}),We=_e({listensFor:Pe(Te($e)),raises:Pe(Te(xe(Re)))}),He=_e({broadcasts:Pe(xe(Re)),listensFor:Pe(xe(Re))}),Ue=_e({name:Pe(Re),id:Pe(Re),description:Pe(Re),broadcasts:Pe(xe(Re)),listensFor:Pe(xe(Re))}).where(e=>Boolean(e.name||e.id),"Expected at least a name or an id property to be present in the app channel definition"),qe=_e({intents:Pe(We),userChannels:Pe(He),appChannels:Pe(xe(Ue))}),Be=_e({url:Pe(Ee),top:Pe(ve()),left:Pe(ve()),width:Pe(Ae),height:Pe(Ae)}),Ge=_e({name:Pe(Re),type:Pe(Re.where(e=>"window"===e,"Expected a value of window")),title:Pe(Re),version:Pe(Re),customProperties:Pe(Ie()),icon:Pe(we()),caption:Pe(we()),details:Pe(Be),intents:Pe(xe(De)),hidden:Pe(Ce())}),Je=_e({name:Re,appId:Re,title:Pe(Re),version:Pe(Re),manifest:Re,manifestType:Re,tooltip:Pe(Re),description:Pe(Re),contactEmail:Pe(Re),supportEmail:Pe(Re),publisher:Pe(Re),images:Pe(xe(_e({url:Pe(Re)}))),icons:Pe(xe(_e({icon:Pe(Re)}))),customConfig:Ie(),intents:Pe(xe(De))}),ze=_e({appId:Pe(Re),name:Pe(Re),details:Pe(Ne),version:Pe(Re),title:Pe(Re),tooltip:Pe(Re),lang:Pe(Re),description:Pe(Re),categories:Pe(xe(Re)),icons:Pe(xe(Fe)),screenshots:Pe(xe(Le)),contactEmail:Pe(Re),supportEmail:Pe(Re),moreInfo:Pe(Re),publisher:Pe(Re),customConfig:Pe(xe(Ie())),hostManifests:Pe(Ie()),interop:Pe(qe)}),Ve=_e({appId:Re,name:Pe(Re),type:je,details:Ne,version:Pe(Re),title:Pe(Re),tooltip:Pe(Re),lang:Pe(Re),description:Pe(Re),categories:Pe(xe(Re)),icons:Pe(xe(Fe)),screenshots:Pe(xe(Le)),contactEmail:Pe(Re),supportEmail:Pe(Re),moreInfo:Pe(Re),publisher:Pe(Re),customConfig:Pe(xe(Ie())),hostManifests:Pe(Ie()),interop:Pe(qe),localizedVersions:Pe(Te(ze))}),Ke=ke(Je,Ve),Ze=e=>`${e.kind} at ${e.at}: ${JSON.stringify(e.input)}. Reason - ${e.message}`;class Qe{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:Ze(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: ${Ze(i.error)}`);const r=this.getUserPropertiesFromDefinition(e,n),s={url:this.getUrl(e,n)},o={name:e.appId,type:"window",createOptions:s,userProperties:{...r,intents:"1.2"===n?r.intents:this.getIntentsFromV2AppDefinition(e),details:s},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=Ge.run(a);if(!c.ok)throw new Error(`Invalid FDC3 ${n} definition. Error: ${Ze(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: ${Ze(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 r=e,s={name:r.appId,type:this.fdc3ToDesktopDefinitionType[r.type],details:r.details,version:r.version,title:r.title,tooltip:r.tooltip,caption:r.description,icon:this.getIconFromDefinition(r,"2.0"),intents:this.getIntentsFromV2AppDefinition(r),fdc3:{...r,definitionVersion:"2.0"}},o=e.hostManifests?.ioConnect||e.hostManifests?.Glue42;if(!o)return s;if("object"!=typeof o||Array.isArray(o))throw new Error(`Invalid '${e.hostManifests.ioConnect?"hostManifests.ioConnect":"hostManifests['Glue42']"}' key`);return this.mergeDesktopConfigWithGlueManifest(s,o)}getUserPropertiesFromDefinition(e,t){return"1.2"===t?Object.fromEntries(Object.entries(e).filter(([e])=>!se.includes(e))):Object.fromEntries(Object.entries(e).filter(([e])=>!se.includes(e)&&!oe.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.customProperties&&(n.userProperties={...e.userProperties,...t.customProperties}),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 Ye={common:{nonEmptyStringDecoder:Re,nonNegativeNumberDecoder:Ae,regexDecoder:Me,urlDecoder:Ee},fdc3:{allDefinitionsDecoder:Ke,v1DefinitionDecoder:Je,v2DefinitionDecoder:Ve}};var Xe;!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"}(Xe||(Xe={}));const et=new class{_fdc3;_decoders=Ye;_errors={intents:Xe};get fdc3(){return this._fdc3||(this._fdc3=(new Qe).toApi()),this._fdc3}get decoders(){return this._decoders}get errors(){return this._errors}};et.fdc3;const tt=et.decoders;et.errors;const nt=tt.common.nonEmptyStringDecoder,it=tt.common.nonNegativeNumberDecoder,rt=O(nt),st=tt.common.urlDecoder,ot=R(T("system"),T("windows"),T("appManager"),T("layouts"),T("intents"),T("notifications"),T("channels"),T("extension"),T("themes"),T("prefs"),T("ui")),at=R(T("openWindow"),T("windowHello"),T("windowAdded"),T("windowRemoved"),T("getBounds"),T("getFrameBounds"),T("getUrl"),T("moveResize"),T("focus"),T("close"),T("getTitle"),T("setTitle"),T("focusChange"),T("getChannel"),T("notifyChannelsChanged"),T("setZoomFactor"),T("zoomFactorChange"),T("refresh"),T("operationCheck")),ct=R(T("appHello"),T("appDirectoryStateChange"),T("instanceStarted"),T("instanceStopped"),T("applicationStart"),T("instanceStop"),T("clear"),T("operationCheck")),dt=R(T("layoutAdded"),T("layoutChanged"),T("layoutRemoved"),T("layoutRenamed"),T("get"),T("getAll"),T("getLayoutContents"),T("export"),T("import"),T("remove"),T("rename"),T("clientSaveRequest"),T("getGlobalPermissionState"),T("checkGlobalActivated"),T("requestGlobalPermission"),T("getDefaultGlobal"),T("setDefaultGlobal"),T("clearDefaultGlobal"),T("updateMetadata"),T("operationCheck"),T("getCurrent"),T("defaultLayoutChanged"),T("layoutRestored")),lt=R(T("raiseNotification"),T("requestPermission"),T("notificationShow"),T("notificationClick"),T("getPermission"),T("list"),T("notificationRaised"),T("notificationClosed"),T("click"),T("clear"),T("clearAll"),T("configure"),T("getConfiguration"),T("configurationChanged"),T("setState"),T("clearOld"),T("activeCountChange"),T("stateChange"),T("operationCheck"),T("getActiveCount")),ht=R(T("getEnvironment"),T("getBase"),T("platformShutdown"),T("isFdc3DataWrappingSupported"),T("clientError"),T("systemHello"),T("operationCheck")),ut=R(T("top"),T("left"),T("right"),T("bottom")),pt=P({top:S(),left:S(),width:it,height:it}),gt=O(P({top:O(S()),left:O(S()),width:O(it),height:O(it),context:O(x()),relativeTo:O(nt),relativeDirection:O(ut),windowId:O(nt),layoutComponentId:O(nt)})),ft=P({name:nt,url:st,options:gt}),mt=P({windowId:O(nt)}),bt=P({windowId:nt,name:nt}),yt=P({windowId:nt}),wt=P({windows:k(bt),isWorkspaceFrame:_()}),vt=P({windowId:nt,title:I()}),Ct=P({windowId:nt,hasFocus:_()}),It=P({windowId:nt,top:O(S()),left:O(S()),width:O(it),height:O(it),relative:O(_())}),St=P({windowId:nt,bounds:P({top:S(),left:S(),width:it,height:it})}),_t=P({bounds:P({top:S(),left:S(),width:it,height:it})}),xt=P({windowId:nt,url:st}),Tt=P({windowId:nt,factorIndex:it}),Pt=x(),kt=P({top:O(S()),left:O(S()),width:O(it),height:O(it)}),Ot=P({id:nt,applicationName:nt}),Rt=P({flags:I()}),At=P({flags:I()}),Mt=P({flags:I()}),Et=P({windowId:nt,channelsNames:k(nt)}),Dt=P({enabled:_()}),jt=P({url:st,top:O(S()),left:O(S()),width:O(it),height:O(it),workspacesSandbox:O(Mt),channelSelector:O(Dt),iframePermissionsPolicy:O(Rt),iframeSandbox:O(At)}),Nt=P({name:nt,displayName:O(I()),contexts:O(k(I())),customConfig:O(P()),resultType:O(I())}),Ft=P({name:nt,type:nt.where(e=>"window"===e,"Expected a value of window"),title:O(nt),version:O(nt),customProperties:O(x()),icon:O(I()),caption:O(I()),details:jt,intents:O(k(Nt)),hidden:O(_()),fdc3:O(tt.fdc3.v2DefinitionDecoder)}),Lt=P({name:nt}),$t=P({definitions:k(Ft)}),Wt=P({name:nt,type:nt.where(e=>"window"===e,"Expected a value of window"),instances:k(Ot),userProperties:O(x()),title:O(nt),version:O(nt),icon:O(I()),caption:O(nt),fdc3:O(x())}),Ht=P({name:nt,type:nt.where(e=>"window"===e,"Expected a value of window"),userProperties:x(),title:O(nt),version:O(nt),icon:O(I()),caption:O(nt),fdc3:O(x())}),Ut=P({appsAdded:k(Ht),appsChanged:k(Ht),appsRemoved:k(Ht)}),qt=P({apps:k(Wt),initialChannelId:O(nt)}),Bt=P({id:nt}),Gt=R(T("Global"),T("Activity"),T("ApplicationDefault"),T("Swimlane"),T("Workspace")),Jt=R(T("application"),T("activity")),zt=P({context:O(x()),bounds:pt,createArgs:P({name:O(nt),url:O(st),context:O(x())}),windowState:O(nt),restoreState:O(nt),instanceId:nt,isCollapsed:O(_()),isSticky:O(_()),restoreSettings:P({groupId:O(nt),groupZOrder:O(S())}),channelId:O(nt)}),Vt=P({type:T("window"),componentType:O(Jt),application:nt,state:zt}),Kt=P({type:T("window"),config:P({appName:nt,url:O(st),title:O(I()),allowExtract:O(_()),allowReorder:O(_()),showCloseButton:O(_()),isMaximized:O(_()),instanceId:O(nt)})}),Zt=P({type:T("group"),config:x(),children:k(R(Kt))}),Qt=P({type:T("column"),config:x(),children:k(R(Zt,Kt,E(()=>Qt),E(()=>Yt)))}),Yt=P({type:T("row"),config:x(),children:k(R(Qt,Zt,Kt,E(()=>Yt)))}),Xt=P({config:x(),context:x(),children:k(R(Yt,Qt,Zt,Kt))}),en=P({type:T("Workspace"),application:O(nt),state:Xt}),tn=P({bounds:pt,instanceId:nt,selectedWorkspace:it,workspaces:k(Xt),windowState:O(nt),restoreState:O(nt),context:O(x())}),nn=P({type:T("workspaceFrame"),application:nt,componentType:O(Jt),state:tn}),rn=P({name:nt,type:Gt,token:O(nt),components:k(R(Vt,en,nn)),context:O(x()),metadata:O(x()),version:O(S())}),sn=P({name:nt,type:Gt,token:O(nt),components:k(R(Vt,en,nn)),context:O(x()),metadata:O(x()),version:O(S()),prevName:nt}),on=P({name:nt,context:O(x()),metadata:O(x()),instances:O(k(nt)),ignoreInstances:O(k(nt)),setAsCurrent:O(_()),ignoreContexts:O(_()),saveWindowContexts:O(_())}),an=P({name:nt,context:O(x()),closeRunningInstance:O(_()),closeMe:O(_()),timeout:O(it)}),cn=P({name:nt,type:Gt}),dn=P({contents:P({appComponents:k(R(Vt,en,nn)),workspaceComponents:k(Xt),workspaceWindows:k(Kt)})}),ln=P({name:nt,type:Gt,context:O(x()),metadata:O(x())}),hn=P({name:nt,type:Gt}),un=P({layout:on}),pn=P({layout:rn,newName:nt}),gn=P({status:nt}),fn=P({layout:rn}),mn=P({layout:an}),bn=P({type:Gt}),yn=P({layouts:k(rn)}),wn=O(P({name:nt})),vn=R(T("replace"),T("merge")),Cn=P({layouts:k(rn),mode:vn,skipManagerRequest:O(_())}),In=P({summaries:k(ln)}),Sn=P({layout:rn}),_n=P({layout:O(rn)}),xn=P({name:nt}),Tn=R(T("findIntent"),T("getIntents"),T("getIntentsByHandler"),T("raise"),T("filterHandlers")),Pn=P({applicationName:nt,applicationTitle:O(I()),applicationDescription:O(I()),applicationIcon:O(I()),type:R(T("app"),T("instance")),displayName:O(I()),contextTypes:O(k(nt)),instanceId:O(I()),instanceTitle:O(I()),resultType:O(I()),customConfig:O(P())});P({applicationName:I(),applicationIcon:O(I()),instanceId:O(I())}),P({intent:nt,handler:Pn});const kn=P({name:nt,handlers:k(Pn)}),On=R(T("startNew"),T("reuse"),P({app:O(nt),instance:O(nt)})),Rn=P({type:O(nt),data:O(x())}),An=k(kn),Mn=P({intents:An}),En=P({name:O(nt),contextType:O(nt),resultType:O(nt)}),Dn=R(nt,En),jn=P({filter:O(En)}),Nn=P({top:O(S()),left:O(S()),width:O(it),height:O(it),relativeTo:O(nt),relativeDirection:O(ut),waitForAGMReady:O(_()),channelId:O(nt)}),Fn=P({intent:nt,target:O(On),context:O(Rn),options:O(Nn),handlers:O(k(Pn)),timeout:O(it),waitUserResponseIndefinitely:O(_()),clearSavedHandler:O(_())}),Ln=P({interopInstance:nt,name:O(nt)}),$n=P({originApp:Ln,intentRequest:O(Fn)}),Wn=P({name:nt,waitForAGMReady:_(),id:O(nt),context:O(x()),top:O(S()),left:O(S()),width:O(it),height:O(it),relativeTo:O(nt),relativeDirection:O(ut),forceChromeTab:O(_()),layoutComponentId:O(nt),channelId:O(nt),startReason:$n}),Hn=R(nt,Fn),Un=P({enabled:_(),appName:nt,waitResponseTimeout:S()}),qn=R(P({applicationName:nt}),P({instanceId:nt})),Bn=P({title:O(nt),openResolver:O(_()),timeout:O(it),intent:O(nt),contextTypes:O(k(nt)),resultType:O(nt),applicationNames:O(k(nt)),excludeList:O(k(qn))}),Gn=P({enabled:_(),initialCaller:P({instanceId:nt})}),Jn=P({intentRequest:Fn,resolverConfig:Un,embeddedResolverConfig:O(Gn)}),zn=P({request:Fn,handler:Pn,result:x()}),Vn=P({handlers:k(Pn)}),Kn=P({filterHandlersRequest:Bn,resolverConfig:Un,embeddedResolverConfig:O(Gn)}),Zn=P({intent:nt,contextTypes:O(k(nt)),displayName:O(I()),icon:O(I()),description:O(I()),resultType:O(I()),customConfig:O(P())}),Qn=R(nt,Zn),Yn=P({intent:nt,contextTypes:O(k(nt)),description:O(nt),displayName:O(nt),icon:O(nt),resultType:O(nt)}),Xn=P({intents:k(Yn)}),ei=e=>nt.where(t=>e.includes(t),"Expected a valid channel name"),ti=P({contextType:O(nt)}),ni=O(R(nt,P({name:O(nt),fdc3:O(_())}))),ii=R(nt,P({windowId:rt,channel:rt})),ri=x().where(e=>"string"==typeof e.type,"Expected a valid FDC3 Context with compulsory 'type' field"),si=P({method:nt,arguments:O(x()),target:O(R(T("all"),T("best")))}),oi=P({action:I(),title:nt,icon:O(I()),interop:O(si)}),ai=R(T("Active"),T("Acknowledged"),T("Seen"),T("Closed"),T("Stale"),T("Snoozed"),T("Processing")),ci=P({count:S()}),di=P({badge:O(I()),body:O(I()),data:O(x()),dir:O(R(T("auto"),T("ltr"),T("rtl"))),icon:O(I()),image:O(I()),lang:O(I()),renotify:O(_()),requireInteraction:O(_()),silent:O(_()),tag:O(I()),timestamp:O(it),vibrate:O(k(S()))}),li=P({title:nt,clickInterop:O(si),actions:O(k(oi)),focusPlatformOnDefaultClick:O(_()),badge:O(I()),body:O(I()),data:O(x()),dir:O(R(T("auto"),T("ltr"),T("rtl"))),icon:O(I()),image:O(I()),lang:O(I()),renotify:O(_()),requireInteraction:O(_()),silent:O(_()),tag:O(I()),timestamp:O(it),vibrate:O(k(S())),severity:O(R(T("Low"),T("None"),T("Medium"),T("High"),T("Critical"))),showToast:O(_()),showInPanel:O(_()),state:O(ai)}),hi=P({id:nt,state:ai});P().where(e=>!e.fdc3||"string"==typeof e.fdc3.type,"Expected a valid FDC3 Context with compulsory 'type' field");const ui=P({color:O(nt),icon:O(nt),name:O(nt),glyph:O(nt)}),pi=P({id:nt,displayMetadata:O(ui)}),gi=P({color:nt,fdc3:O(pi)}),fi=P({name:nt,meta:gi,data:O(P())}),mi=P({path:nt,value:x()}),bi=k(mi),yi=P({name:nt}),wi=P({name:nt,read:_(),write:_(),windowId:O(nt)}),vi=P({name:nt,read:_(),write:_(),windowId:nt}),Ci=P({config:vi}),Ii=P({channels:k(wi)}),Si=P({windowId:nt}),_i=P({read:_(),write:_(),windowId:O(nt)}),xi=P({restrictions:_i}),Ti=P({settings:li,id:nt}),Pi=P({settings:li}),ki=P({permissionGranted:_()}),Oi=P({permission:R(T("default"),T("granted"),T("denied"))}),Ri=P({definition:di,action:O(I()),id:O(nt)}),Ai=P({allowed:O(k(nt)),blocked:O(k(nt))}),Mi=P({enable:O(_()),enableToasts:O(_()),sourceFilter:O(Ai),showNotificationBadge:O(_())}),Ei=P({configuration:Mi}),Di=P({configuration:P({enable:_(),enableToasts:_(),sourceFilter:P({allowed:k(nt),blocked:k(nt)}),showNotificationBadge:O(_())})}),ji=P({layoutType:R(T("Global"),T("Workspace")),layoutName:nt,context:O(x())}),Ni=P({windowContext:O(x())}),Fi=P({state:R(T("prompt"),T("denied"),T("granted"))}),Li=P({isAvailable:_()}),$i=P({itemId:nt}),Wi=P({isSupported:_()}),Hi=P({operation:nt}),Ui=P({bounds:pt}),qi=P({displayName:nt,name:nt}),Bi=P({theme:qi}),Gi=P({themes:k(qi)}),Ji=P({name:nt}),zi=P({id:nt,title:nt,clickInterop:O(si),actions:O(k(oi)),focusPlatformOnDefaultClick:O(_()),badge:O(I()),body:O(I()),data:O(x()),dir:O(R(T("auto"),T("ltr"),T("rtl"))),icon:O(I()),image:O(I()),lang:O(I()),renotify:O(_()),requireInteraction:O(_()),silent:O(_()),tag:O(I()),timestamp:O(it),vibrate:O(k(S())),severity:O(R(T("Low"),T("None"),T("Medium"),T("High"),T("Critical"))),showToast:O(_()),showInPanel:O(_()),state:O(ai)}),Vi=P({notification:zi}),Ki=P({notifications:k(zi)}),Zi=P({id:nt}),Qi=P({channel:nt}),Yi=P({windowIds:k(nt)}),Xi=R(T("appHello"),T("addChannel"),T("getMyChannel"),T("getWindowIdsOnChannel"),T("getWindowIdsWithChannels"),T("joinChannel"),T("restrict"),T("getRestrictions"),T("restrictAll"),T("notifyChannelsChanged"),T("leaveChannel"),T("getMode"),T("operationCheck")),er=R(T("single"),T("multi")),tr=P({mode:er}),nr=P({windowId:nt}),ir=P({mode:er,channels:k(nt),restrictions:k(wi)}),rr=P({channel:O(nt)}),sr=P({application:O(nt),channels:O(k(nt)),windowIds:O(k(nt))}),or=P({filter:O(sr)}),ar=P({windowIdsWithChannels:k(P({application:nt,channel:O(nt),windowId:nt}))}),cr=O(x()),dr=O(P({top:O(S()),left:O(S()),width:O(it),height:O(it),relativeTo:O(nt),relativeDirection:O(ut),waitForAGMReady:O(_()),channelId:O(nt),reuseId:O(nt),originIntentRequest:O(Fn)})),lr=P({channel:nt,windowId:nt}),hr=P({windowId:nt,channelName:O(nt)}),ur=P({windowId:nt,channelNames:k(nt)}),pr=P({channel:O(nt)}),gr=R(T("clear"),T("clearAll"),T("get"),T("getAll"),T("set"),T("update"),T("prefsChanged"),T("prefsHello"),T("operationCheck"),T("registerSubscriber")),fr=P({app:nt,data:P(),lastUpdate:O(nt)}),mr=P({app:nt}),br=P({prefs:fr}),yr=P({all:k(fr)}),wr=P({interopId:nt,appName:O(nt)}),vr=P({app:nt,data:P()}),Cr=P({platform:P({app:nt}),validNonExistentApps:O(k(nt)),isAppValidationEnabled:O(_())}),Ir=P({message:nt}),Sr=P({isClientErrorOperationSupported:_()}),_r=tt.common.nonEmptyStringDecoder,xr=tt.common.nonNegativeNumberDecoder,Tr=P({bundle:_r,styles:k(_r),fonts:O(k(_r))}),Pr=P({bundle:_r,styles:k(_r),fonts:O(k(_r))}),kr=P({bundle:_r,styles:k(_r),fonts:O(k(_r))}),Or=R(T("directional"),T("default")),Rr=P({type:O(Or),enable:O(_())}),Ar=R(T("top-left"),T("top-center"),T("top-right"),T("center-left"),T("center-right"),T("bottom-left"),T("bottom-center"),T("bottom-right")),Mr=R(T("all"),T("fdc3")),Er=P({selector:O(Rr),displayMode:O(Mr)}),Dr=P({channels:O(Er),position:O(Ar),displayInWorkspace:O(_()),restoreLastKnownPosition:O(_())}),jr=P({enable:_(),awaitFactory:O(_()),timeout:O(xr),channels:O(Er),position:O(Ar),displayInWorkspace:O(_()),restoreLastKnownPosition:O(_())}),Nr=P({alerts:O(P({enabled:_()})),dialogs:O(P({enabled:_()})),awaitFactory:O(_()),timeout:O(xr)}),Fr=R(T("getResources"),T("operationCheck"),T("showAlert"),T("showDialog"),T("alertInteropAction"),T("showResolver")),Lr=P({origin:_r}),$r=P({blockedOrigin:T(!0)}),Wr=A($r,P({blockedOrigin:T(!1),config:Dr,sources:Tr})),Hr=A($r,P({blockedOrigin:T(!1),sources:Pr})),Ur=A($r,P({blockedOrigin:T(!1),sources:kr})),qr=P({widget:O(Wr),modals:O(Hr),intentResolver:O(Ur)}),Br=P({resources:qr}),Gr=P({method:_r,arguments:O(x()),target:O(R(T("best"),T("all"),_r))}),Jr=R(T("Global"),T("WindowContainer"),_r),zr=P({instance:_r,container:O(R(T("Global"),T("WindowContainer")))}),Vr=P({variant:R(T("default"),T("success"),T("critical"),T("info"),T("warning")),text:_r,showCloseButton:O(_()),clickInterop:O(Gr),onCloseInterop:O(Gr),actions:O(k(P({id:_r,title:_r,clickInterop:Gr}))),data:O(x()),ttl:O(xr),target:O(Jr)}),Kr=P({config:Vr,target:zr}),Zr=P({templateName:_r,variables:x(),target:O(Jr),timer:O(P({duration:xr})),size:O(P({width:xr,height:xr})),movable:O(_()),transparent:O(_())}),Qr=P({isExpired:O(_()),isClosed:O(_()),isEnterPressed:O(_()),responseButtonClicked:O(P({id:_r,text:_r})),inputs:O(k(P({type:R(T("checkbox"),T("email"),T("number"),T("password"),T("text")),id:_r,checked:O(_()),value:O(I())})))});P({result:Qr});const Yr=P({config:Zr,target:zr}),Xr=P({id:_r}),es=P({id:_r,responsePromise:x()}),ts=P({response:Qr}),ns=P({name:_r,settings:Gr}),is=P({interopAction:ns}),rs=P({interopAction:ns}),ss=P({enable:_(),awaitFactory:O(_()),timeout:O(xr)}),os=P({id:_r}),as=P({preserveChoice:_()}),cs=P({intent:_r,handler:Pn,userSettings:as}),ds=P({isExpired:O(_()),isClosed:O(_()),userChoice:O(cs)}),ls=P({response:ds}),hs=M(A(P({intentRequest:Fn}),P({handlerFilter:Bn})),P({timeout:xr})),us=P({config:hs}),ps=P({result:ds}),gs={openWindow:{name:"openWindow",dataDecoder:ft,resultDecoder:bt},windowHello:{name:"windowHello",dataDecoder:mt,resultDecoder:wt},windowAdded:{name:"windowAdded",dataDecoder:bt},windowRemoved:{name:"windowRemoved",dataDecoder:yt},getBounds:{name:"getBounds",dataDecoder:yt,resultDecoder:St},getFrameBounds:{name:"getFrameBounds",dataDecoder:yt,resultDecoder:_t},getUrl:{name:"getUrl",dataDecoder:yt,resultDecoder:xt},moveResize:{name:"moveResize",dataDecoder:It},focus:{name:"focus",dataDecoder:yt},close:{name:"close",dataDecoder:yt},getTitle:{name:"getTitle",dataDecoder:yt,resultDecoder:vt},setTitle:{name:"setTitle",dataDecoder:vt},focusChange:{name:"focusChange",dataDecoder:Ct},getChannel:{name:"getChannel",dataDecoder:yt,resultDecoder:pr},notifyChannelsChanged:{name:"notifyChannelsChanged",dataDecoder:ur},setZoomFactor:{name:"setZoomFactor",dataDecoder:Tt},zoomFactorChange:{name:"zoomFactorChange",dataDecoder:Tt},refresh:{name:"refresh",dataDecoder:yt},operationCheck:{name:"operationCheck"}};function fs(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 r=n instanceof Error?n:new Error(n);if(t)t(r);else{var s='[ERROR] callback-registry: User callback for key "'+i+'" failed: '+r.stack;if(e)switch(e.errorHandling){case"log":return console.error(s);case"silent":return;case"throw":throw new Error(s)}console.error(s)}}return{add:function(e,t,r){var s=n[e];return s||(s=[],n[e]=s),s.push(t),r&&setTimeout(function(){r.forEach(function(r){var s;if(null===(s=n[e])||void 0===s?void 0:s.includes(t))try{Array.isArray(r)?t.apply(void 0,r):t.apply(void 0,[r])}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=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];var s=n[e];if(!s||0===s.length)return[];var o=[];return s.forEach(function(n){try{var r=n.apply(void 0,t);o.push(r)}catch(t){o.push(void 0),i(t,e)}}),o},clear:function(){n={}},clearKey:function(e){n[e]&&delete n[e]}}}fs.default=fs;var ms=e(fs);const bs=Object.freeze({0:24,1:33,2:50,3:67,4:75,5:80,6:90,7:100,8:110,9:125,10:150,11:175,12:200,13:250,14:300,15:400,16:500});class ys{_id;_name;_bridge;_logger;registry=ms();myCtxKey;ctxUnsubscribe;zoomFactorIndex=7;me;constructor(e,t,n,i){this._id=e,this._name=t,this._bridge=n,this._logger=i,this.myCtxKey=`___window___${this.id}`}get id(){return this._id.slice()}get name(){return this._name.slice()}get zoomFactor(){return bs[this.zoomFactorIndex]}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)}processSelfZoomFactorChangedEvent(e){this.zoomFactorIndex=e,this.registry.execute("zoom-factor-changed",this.me)}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,zoomFactor:this.zoomFactor,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),refresh:this.refresh.bind(this),onContextUpdated:this.onContextUpdated.bind(this),onFocusChanged:this.onFocusChanged.bind(this),getChannel:this.getChannel.bind(this),onChannelsChanged:this.onChannelsChanged.bind(this),zoomIn:this.zoomIn.bind(this),zoomOut:this.zoomOut.bind(this),setZoomFactor:this.setZoomFactor.bind(this),onZoomFactorChanged:this.onZoomFactorChanged.bind(this)},Object.defineProperties(this.me,{id:Q,name:Q,zoomFactor:{get:()=>this.zoomFactor,enumerable:!0}}),this.me}async getURL(){return(await this._bridge.send("windows",gs.getUrl,{windowId:this.id})).url}onFocusChanged(e){return"function"!=typeof e?re.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=X(kt,e),n=Object.assign({},t,{windowId:this.id,relative:!1});return await this._bridge.send("windows",gs.moveResize,n),this.me}async resizeTo(e,t){if(void 0===e&&void 0===t)return this.me;void 0!==e&&X(it,e),void 0!==t&&X(it,t);const n=Object.assign({},{width:e,height:t},{windowId:this.id,relative:!0});return await this._bridge.send("windows",gs.moveResize,n),this.me}async moveTo(e,t){if(void 0===e&&void 0===t)return this.me;void 0!==e&&X(S(),e),void 0!==t&&X(S(),t);const n=Object.assign({},{top:e,left:t},{windowId:this.id,relative:!0});return await this._bridge.send("windows",gs.moveResize,n),this.me}async focus(){return"Platform"===this.name?window.open(void 0,this.id):await this._bridge.send("windows",gs.focus,{windowId:this.id}),this.me}async close(){return await this._bridge.send("windows",gs.close,{windowId:this.id}),this.me}async getTitle(){return(await this._bridge.send("windows",gs.getTitle,{windowId:this.id})).title}async setTitle(e){const t=X(nt,e);return await this._bridge.send("windows",gs.setTitle,{windowId:this.id,title:t}),this.me}async getBounds(){return(await this._bridge.send("windows",gs.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=X(Pt,e);return await this._bridge.contextLib.update(this.myCtxKey,t),this.me}async setContext(e){const t=X(Pt,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 re.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",gs.getChannel,{windowId:this.id},void 0,{includeOperationCheck:!0})).channel}onChannelsChanged(e){return this.registry.add("channels-changed",e)}getClosestZoomFactorIndex(e){const t=Object.entries(bs).reduce((t,[n,i])=>Math.abs(i-e)<=Math.abs(bs[t]-e)?parseInt(n):t,0),n=bs[t];return n!==e&&this._logger.warn(`Zoom factor ${e} is not available, using closest value ${n} instead.`),t}async zoom(e){e!==this.zoomFactorIndex&&e in bs&&(await this._bridge.send("windows",gs.setZoomFactor,{windowId:this.id,factorIndex:e},void 0,{includeOperationCheck:!0}),this.zoomFactorIndex=e)}async zoomIn(){return await this.zoom(this.zoomFactorIndex+1),this.me}async zoomOut(){return await this.zoom(this.zoomFactorIndex-1),this.me}async setZoomFactor(e){const t=X(S(),e),n=this.getClosestZoomFactorIndex(t);return await this.zoom(n),this.me}onZoomFactorChanged(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to zoom factor changes, because the provided callback is not a function!"):this.registry.add("zoom-factor-changed",e)}async refresh(){return await this._bridge.send("windows",gs.refresh,{windowId:this.id},void 0,{includeOperationCheck:!0}),this.me}}const ws={operationCheck:{name:"operationCheck",dataDecoder:Hi,resultDecoder:Wi},getWorkspaceWindowFrameBounds:{name:"getWorkspaceWindowFrameBounds",resultDecoder:Ui,dataDecoder:$i}},vs=(e,t,n)=>new Promise((i,r)=>{let s=!0;const o=setTimeout(()=>{if(!s)return;s=!1;r(n||`Promise timeout hit: ${t}`)},t);e().then(e=>{s&&(s=!1,clearTimeout(o),i(e))}).catch(e=>{s&&(s=!1,clearTimeout(o),r(e))})}),Cs=(e,t,n)=>new Promise((i,r)=>{const s=setTimeout(()=>{r(n||`Promise timeout hit: ${t}`)},t);new Promise(e).then(e=>{clearTimeout(s),i(e)}).catch(e=>{clearTimeout(s),r(e)})});class Is{supportedOperationsNames=[];focusEventHandler;registry=ms();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=X(at,e.operation),n=gs[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=X(n.dataDecoder,e.data)),await n.execute(i)}async open(e,t,n){X(nt,e),X(st,t);const i=X(gt,n),r=await this.bridge.send("windows",gs.openWindow,{name:e,url:t,options:i});return this.waitForWindowAdded(r.windowId)}list(){return this.allWindowProjections.map(e=>e.api)}findById(e){return X(nt,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(){gs.focusChange.execute=this.handleFocusChangeEvent.bind(this),gs.windowAdded.execute=this.handleWindowAdded.bind(this),gs.windowRemoved.execute=this.handleWindowRemoved.bind(this),gs.getBounds.execute=this.handleGetBounds.bind(this),gs.getFrameBounds.execute=this.handleGetBounds.bind(this),gs.getTitle.execute=this.handleGetTitle.bind(this),gs.getUrl.execute=this.handleGetUrl.bind(this),gs.moveResize.execute=this.handleMoveResize.bind(this),gs.setTitle.execute=this.handleSetTitle.bind(this),gs.getChannel.execute=this.handleGetChannel.bind(this),gs.notifyChannelsChanged.execute=this.handleChannelsChanged.bind(this),gs.setZoomFactor.execute=this.handleSetZoomFactor.bind(this),gs.zoomFactorChange.execute=this.handleZoomFactorChanged.bind(this),gs.refresh.execute=this.handleRefresh.bind(this),gs.operationCheck.execute=async e=>te(this.supportedOperationsNames,e.operation),this.supportedOperationsNames=ee(gs)}my(){return Object.assign({},this.me)}onWindowAdded(e){return"function"!=typeof e?re.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?re.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?re.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?re.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",gs.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){const t=e.map(e=>`${e.windowId}:${e.name}`).join(", ");return re.raiseError(`Cannot initialize the window library, because I received no information about me -> id: ${this.publicWindowId} name: ${window.name} from the platform: known windows: ${t}`)}const n=await this.ioc.buildWebWindow(this.publicWindowId,t.name,this.logger);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)));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.logger);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}}:re.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}:re.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}:re.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,r="number"==typeof e.width?e.width:e.relative?0:window.innerWidth,s=e.relative?window.moveBy:window.moveTo,o=e.relative?window.resizeBy:window.resizeTo;s(n,t),o(r,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",ws.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):Cs(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",gs.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 re.raiseError("This window cannot report its channel, because it is not a ioConnect Window, most likely because it is an iframe");const e=this.channelsController.my();return{...e?{channel:e}:{}}}async handleRefresh(){if(!this.me)return re.raiseError("This window cannot refresh, because it is not an ioConnect Window, most likely because it is an iframe");setTimeout(()=>{window.location.reload()},0)}async handleChannelsChanged(e){const t=this.allWindowProjections.find(t=>t.id===e.windowId);t?.model.processChannelsChangedEvent(e.channelNames)}async handleSetZoomFactor(e){if(!this.me)return re.raiseError("This window cannot change its zoom factor, because it is not an ioConnect Window, most likely because it is an iframe");document.body.style.zoom=`${bs[e.factorIndex]}%`}async handleZoomFactorChanged(e){const t=this.allWindowProjections.find(t=>t.id===e.windowId);t&&t.model.processSelfZoomFactorChangedEvent(e.factorIndex)}}const Ss="T42.Web.Platform.Control",_s="T42.Web.Platform.Stream",xs="T42.Web.Client.Control",Ts="T42.Core.Plus.Themes.Stream";class Ps{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(xs)}async start(e){this.running=!0,this.controllers=e,await Promise.all([this.checkWaitMethod(Ss),this.checkWaitMethod(_s)]);const t=this.communicationId,[n]=await Promise.all([this.coreGlue.interop.subscribe(_s,t?{target:{instance:this.communicationId}}:void 0),this.coreGlue.interop.registerAsync(xs,(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,r){if(t.dataDecoder)try{t.dataDecoder.runWithException(n)}catch(e){return re.raiseError(`Unexpected Web->Platform outgoing validation error: ${e.message}, for operation: ${t.name} and input: ${JSON.stringify(e.input)}`)}if(!(!r?.includeOperationCheck||(await this.checkOperationSupported(e,t)).isSupported))return re.raiseError(`Cannot complete operation: ${t.name} for domain: ${e} because this client is connected to a platform which does not support it`);try{const r=await this.transmitMessage(e,t,n,i);return t.resultDecoder&&t.resultDecoder.runWithException(r),r}catch(e){return e?.kind?re.raiseError(`Unexpected Web<-Platform incoming validation error: ${e.message}, for operation: ${t.name} and input: ${JSON.stringify(e.input)}`):re.raiseError(e)}}async createThemesSubscription(){return this.coreGlue.interop.methods().some(e=>e.name===Ts)?this.coreGlue.interop.subscribe(Ts,this.communicationId?{target:{instance:this.communicationId}}:void 0):re.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,ws.operationCheck,{operation:t.name})}catch(e){return{isSupported:!1}}}checkWaitMethod(e){return Cs(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 r=i.method,s=i.server,o=!this.communicationId||s.instance===this.communicationId;r.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=ot.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 r=i.result;this.controllers[r].handleBridgeMessage(e).then(e=>{t&&t(e)}).catch(e=>{n&&n(e),console.warn(e)})}async transmitMessage(e,t,n,i){const r={domain:e,data:n,operation:t.name};let s;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(s=await this.coreGlue.interop.invoke(Ss,r,a?{instance:this.communicationId}:void 0,i),!s)throw new Error("Received unsupported result from the platform - empty result");if(!Array.isArray(s.all_return_values)||0===s.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 s.all_return_values[0].returned}}const ks={appHello:{name:"appHello",dataDecoder:mt,resultDecoder:qt},appDirectoryStateChange:{name:"appDirectoryStateChange",dataDecoder:Ut},instanceStarted:{name:"instanceStarted",dataDecoder:Ot},instanceStopped:{name:"instanceStopped",dataDecoder:Ot},applicationStart:{name:"applicationStart",dataDecoder:Wn,resultDecoder:Ot},instanceStop:{name:"instanceStop",dataDecoder:Bt},import:{name:"import"},remove:{name:"remove",dataDecoder:Lt},export:{name:"export",resultDecoder:$t},clear:{name:"clear"},operationCheck:{name:"operationCheck"}};class Os{me;supportedOperationsNames=[];baseApplicationsTimeoutMS=6e4;appImportTimeoutMS=20;registry=ms();ioc;bridge;publicWindowId;applications=[];instances=[];platformRegistration;logger;channelsController;interop;initialChannelId;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.interop=e.interop,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 postStart(){this.initialChannelId&&await this.channelsController.handleAppManagerInitialChannelId(this.initialChannelId)}async handleBridgeMessage(e){await this.platformRegistration;const t=X(ct,e.operation),n=ks[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=X(n.dataDecoder,e.data)),await n.execute(i)}onInstanceStarted(e){return"function"!=typeof e?re.raiseError("onInstanceStarted requires a single argument of type function"):this.registry.add("instance-started",e,this.instances)}onInstanceStopped(e){return"function"!=typeof e?re.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 re.raiseError(`The channel with name "${n.channelId}" doesn't exist!`);const r={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,startReason:{originApp:{name:this.me?.application.name,interopInstance:this.interop.instance.instance}}};n?.originIntentRequest&&(r.startReason.intentRequest=n.originIntentRequest);const s=await this.bridge.send("appManager",ks.applicationStart,r),o=this.applications.find(e=>e.name===s.applicationName);return this.ioc.buildInstance(s,o)}getApplication(e){const t=X(nt,e),n=this.applications.find(e=>e.name===t),i=n?.userProperties?.details?.iframeSandbox;return i&&(n.userProperties.details.workspacesSandbox=i),n}getInstances(){return this.instances.slice()}onAppAdded(e){return"function"!=typeof e?re.raiseError("onAppAdded requires a single argument of type function"):this.registry.add("application-added",e,this.applications)}onAppRemoved(e){return"function"!=typeof e?re.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(){ks.appDirectoryStateChange.execute=this.handleAppDirectoryStateChange.bind(this),ks.instanceStarted.execute=this.handleInstanceStartedMessage.bind(this),ks.instanceStopped.execute=this.handleInstanceStoppedMessage.bind(this),ks.operationCheck.execute=async e=>te(this.supportedOperationsNames,e.operation),this.supportedOperationsNames=ee(ks)}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?re.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 re.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(X(vn,t),!Array.isArray(e))return re.raiseError("Import must be called with an array of definitions");if(e.length>1e4)return re.raiseError("Cannot import more than 10000 app definitions in Glue42 Core.");const n=e.reduce((e,t)=>{const{isValid:n,error:i}=this.isValidDefinition(t);return n?e.valid.push(t):e.invalid.push({app:t?.name,error:i??`Provided definition is invalid ${JSON.stringify(t)}`}),e},{valid:[],invalid:[]}),i=this.baseApplicationsTimeoutMS+this.appImportTimeoutMS*n.valid.length;return await this.bridge.send("appManager",ks.import,{definitions:n.valid,mode:t},{methodResponseTimeoutMs:i}),{imported:n.valid.map(e=>e.name),errors:n.invalid}}isValidDefinition(e){if(e?.appId&&e?.details){const t=tt.fdc3.v2DefinitionDecoder.run(e);return{isValid:t.ok,error:t.ok?void 0:`Received invalid FDC3 v2 definition. Error: ${JSON.stringify(t.error)}`}}if(e?.appId&&e?.manifest){const t=tt.fdc3.v1DefinitionDecoder.run(e);return{isValid:t.ok,error:t.ok?void 0:`Received invalid FDC3 v1 definition. Error: ${JSON.stringify(t.error)}`}}const t=Ft.run(e);return{isValid:t.ok,error:t.ok?void 0:`Received invalid definition. Error: ${JSON.stringify(t.error)}`}}async remove(e){X(nt,e),await this.bridge.send("appManager",ks.remove,{name:e},{methodResponseTimeoutMs:this.baseApplicationsTimeoutMS})}async clear(){await this.bridge.send("appManager",ks.clear,void 0,{methodResponseTimeoutMs:this.baseApplicationsTimeoutMS})}async exportApps(){return(await this.bridge.send("appManager",ks.export,void 0,{methodResponseTimeoutMs:this.baseApplicationsTimeoutMS})).definitions}getApplications(){return this.applications.slice()}async registerWithPlatform(){const e=await this.bridge.send("appManager",ks.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`),this.initialChannelId=e.initialChannelId}findMyInstance(){for(const e of this.applications){const t=e.instances.find(e=>e.id===this.publicWindowId);if(t)return t}}}class Rs{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",ks.instanceStop,{id:this.data.id})}}class As{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),getConfiguration:this.getConfiguration.bind(this),onInstanceStarted:this.onInstanceStarted.bind(this),onInstanceStopped:this.onInstanceStopped.bind(this)};return this.me=e,this.me}onInstanceStarted(e){return"function"!=typeof e?re.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?re.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=X(cr,e),i=X(dr,t);return this.controller.startApplication(this.data.name,n,i)}async getConfiguration(){const{details:e,intents:t,hidden:n,...i}=this.data.userProperties,r={name:this.data.name,type:this.data.type,details:e,customProperties:i},s={title:this.data.title,version:this.data.version,icon:this.data.icon,caption:this.data.caption,intents:t,hidden:n,fdc3:this.data.fdc3};for(const[e,t]of Object.entries(s))void 0!==t&&(r[e]=t);return r}}const Ms={layoutAdded:{name:"layoutAdded",dataDecoder:rn},layoutChanged:{name:"layoutChanged",dataDecoder:rn},layoutRemoved:{name:"layoutRemoved",dataDecoder:rn},layoutRestored:{name:"layoutRestored",dataDecoder:rn},defaultLayoutChanged:{name:"defaultLayoutChanged",dataDecoder:wn},layoutRenamed:{name:"layoutRenamed",dataDecoder:sn},get:{name:"get",dataDecoder:hn,resultDecoder:_n},getAll:{name:"getAll",dataDecoder:bn,resultDecoder:In},getLayoutContents:{name:"getLayoutContents",dataDecoder:cn,resultDecoder:dn},export:{name:"export",dataDecoder:bn,resultDecoder:yn},import:{name:"import",dataDecoder:Cn},remove:{name:"remove",dataDecoder:hn},rename:{name:"rename",dataDecoder:pn,resultDecoder:gn},save:{name:"save",dataDecoder:un,resultDecoder:Sn},restore:{name:"restore",dataDecoder:mn},clientSaveRequest:{name:"clientSaveRequest",dataDecoder:ji,resultDecoder:Ni},getGlobalPermissionState:{name:"getGlobalPermissionState",resultDecoder:Fi},requestGlobalPermission:{name:"requestGlobalPermission",resultDecoder:Li},checkGlobalActivated:{name:"checkGlobalActivated",resultDecoder:Li},getDefaultGlobal:{name:"getDefaultGlobal",resultDecoder:_n},setDefaultGlobal:{name:"setDefaultGlobal",dataDecoder:xn},clearDefaultGlobal:{name:"clearDefaultGlobal"},getCurrent:{name:"getCurrent",resultDecoder:_n},updateMetadata:{name:"updateMetadata",dataDecoder:fn},operationCheck:{name:"operationCheck"}};class Es{supportedOperationsNames=[];defaultLayoutRestoreTimeoutMS=12e4;registry=ms();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=X(dt,e.operation),n=Ms[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=X(n.dataDecoder,e.data)),await n.execute(i)}toApi(){const e={get:this.get.bind(this),getAll:this.getAll.bind(this),getLayoutContents:this.getLayoutContents.bind(this),getCurrentLayout:this.getCurrentLayout.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),onDefaultGlobalChanged:this.onDefaultGlobalChanged.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),onRestored:this.onRestored.bind(this),updateMetadata:this.updateMetadata.bind(this)};return Object.freeze(e)}addOperationsExecutors(){Ms.layoutAdded.execute=this.handleOnAdded.bind(this),Ms.layoutChanged.execute=this.handleOnChanged.bind(this),Ms.layoutRemoved.execute=this.handleOnRemoved.bind(this),Ms.layoutRenamed.execute=this.handleOnRenamed.bind(this),Ms.layoutRestored.execute=this.handleOnRestored.bind(this),Ms.defaultLayoutChanged.execute=this.handleOnDefaultChanged.bind(this),Ms.clientSaveRequest.execute=this.handleSaveRequest.bind(this),Ms.operationCheck.execute=async e=>te(this.supportedOperationsNames,e.operation),this.supportedOperationsNames=ee(Ms)}async get(e,t){X(nt,e),X(Gt,t);return(await this.bridge.send("layouts",Ms.get,{name:e,type:t})).layout}async getCurrentLayout(){return(await this.bridge.send("layouts",Ms.getCurrent,void 0)).layout}async getAll(e){X(Gt,e);return(await this.bridge.send("layouts",Ms.getAll,{type:e})).summaries}async getLayoutContents(e){X(cn,e);const{name:t,type:n}=e;if("Workspace"!==n&&"Global"!==n)return re.raiseError(`getLayoutContents is only supported for Workspace and Global layouts, but got type "${n}"`);return(await this.bridge.send("layouts",Ms.getLayoutContents,{name:t,type:n},void 0,{includeOperationCheck:!0})).contents}async exportLayouts(e){X(Gt,e);return(await this.bridge.send("layouts",Ms.export,{type:e})).layouts}async importLayouts(e,t="replace"){if(X(vn,t),!Array.isArray(e))return re.raiseError("Import must be called with an array of layouts");if(e.length>1e3)return re.raiseError("Cannot import more than 1000 layouts at once in Glue42 Core.");const n=e.reduce((e,t)=>{const n=rn.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",Ms.import,{layouts:i,mode:t})}async save(e){X(on,e);return(await this.bridge.send("layouts",Ms.save,{layout:e})).layout}async restore(e){X(an,e);const t=e.timeout?2*e.timeout:this.defaultLayoutRestoreTimeoutMS;await this.bridge.send("layouts",Ms.restore,{layout:e},{methodResponseTimeoutMs:t})}async remove(e,t){X(Gt,e),X(nt,t),await this.bridge.send("layouts",Ms.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",Ms.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 re.raiseError("Cannot request permission for multi-window placement from any app other than the Platform.");return{permissionGranted:(await this.bridge.send("layouts",Ms.requestGlobalPermission,void 0,{methodResponseTimeoutMs:18e4})).isAvailable}}async checkGlobalActivated(){return{activated:(await this.bridge.send("layouts",Ms.checkGlobalActivated,void 0)).isAvailable}}async getDefaultGlobal(){return(await this.bridge.send("layouts",Ms.getDefaultGlobal,void 0,void 0,{includeOperationCheck:!0})).layout}async setDefaultGlobal(e){X(nt,e),await this.bridge.send("layouts",Ms.setDefaultGlobal,{name:e},void 0,{includeOperationCheck:!0})}async clearDefaultGlobal(){await this.bridge.send("layouts",Ms.clearDefaultGlobal,void 0,void 0,{includeOperationCheck:!0})}async rename(e,t){X(rn,e),X(nt,t);return await this.bridge.send("layouts",Ms.rename,{layout:e,newName:t},void 0,{includeOperationCheck:!0})}async updateMetadata(e){X(rn,e),await this.bridge.send("layouts",Ms.updateMetadata,{layout:e},void 0,{includeOperationCheck:!0})}onAdded(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to onAdded, because the provided callback is not a function!"):(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(Ms.layoutAdded.name,e))}onChanged(e){return this.registry.add(Ms.layoutChanged.name,e)}onDefaultGlobalChanged(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to onDefaultGlobalChanged, because the provided callback is not a function!"):(this.getDefaultGlobal().then(t=>e(t?{name:t.name}:void 0)).catch(()=>{}),this.registry.add(Ms.defaultLayoutChanged.name,e))}onRemoved(e){return this.registry.add(Ms.layoutRemoved.name,e)}onRenamed(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to onRenamed, because the provided callback is not a function!"):this.registry.add(Ms.layoutRenamed.name,e)}onRestored(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to onRestored, because the provided callback is not a function!"):this.registry.add(Ms.layoutRestored.name,e)}subscribeOnSaveRequested(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to onSaveRequested, because the provided argument is not a valid callback function."):this.saveRequestSubscription?re.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(Ms.layoutAdded.name,e)}async handleOnChanged(e){this.registry.execute(Ms.layoutChanged.name,e)}async handleOnDefaultChanged(e){this.registry.execute(Ms.defaultLayoutChanged.name,e)}async handleOnRemoved(e){this.registry.execute(Ms.layoutRemoved.name,e)}async handleOnRestored(e){this.registry.execute(Ms.layoutRestored.name,e)}async handleOnRenamed(e){const{prevName:t,...n}=e;this.registry.execute(Ms.layoutRenamed.name,n,{name:t})}}const Ds={raiseNotification:{name:"raiseNotification",dataDecoder:Ti,resultDecoder:Pi},requestPermission:{name:"requestPermission",resultDecoder:ki},notificationShow:{name:"notificationShow",dataDecoder:Ri},notificationClick:{name:"notificationClick",dataDecoder:Ri},getPermission:{name:"getPermission",resultDecoder:Oi},list:{name:"list",resultDecoder:Ki},notificationRaised:{name:"notificationRaised",dataDecoder:Vi},notificationClosed:{name:"notificationClosed",dataDecoder:Zi},click:{name:"click"},clear:{name:"clear"},clearAll:{name:"clearAll"},clearOld:{name:"clearOld"},configure:{name:"configure",dataDecoder:Ei,resultDecoder:Di},getConfiguration:{name:"getConfiguration",resultDecoder:Di},getActiveCount:{name:"getActiveCount",resultDecoder:ci},configurationChanged:{name:"configurationChanged",resultDecoder:Di},setState:{name:"setState",dataDecoder:hi},activeCountChange:{name:"activeCountChange",resultDecoder:ci},stateChange:{name:"stateChange",resultDecoder:hi},operationCheck:{name:"operationCheck"}};let js=(e=21)=>{let t="",n=0|e;for(;n--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return t};class Ns{supportedOperationsNames=[];registry=ms();logger;bridge;notificationsSettings;notifications={};coreGlue;buildNotificationFunc;notificationsConfiguration;notificationsActiveCount=0;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,this.notificationsConfiguration=await this.getConfiguration(),this.notificationsActiveCount=await this.getActiveCount();const n=this.toApi();this.addOperationExecutors(),e.notifications=n,this.logger.trace("notifications are ready")}async handleBridgeMessage(e){const t=X(lt,e.operation),n=Ds[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=X(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),onCounterChanged:this.onActiveCountChanged.bind(this),onStateChanged:this.onStateChanged.bind(this)};return Object.freeze(e)}async getPermission(){return(await this.bridge.send("notifications",Ds.getPermission,void 0)).permission}async requestPermission(){return(await this.bridge.send("notifications",Ds.requestPermission,void 0)).permissionGranted}async raise(e){const t=X(li,e);t.showToast="boolean"!=typeof t.showToast||t.showToast,t.showInPanel="boolean"!=typeof t.showInPanel||t.showInPanel;if(!await this.requestPermission())return re.raiseError("Cannot raise the notification, because the user has declined the permission request");const n=js(10),i=await this.bridge.send("notifications",Ds.raiseNotification,{settings:t,id:n}),r=this.buildNotificationFunc(i.settings,n);return this.notifications[n]=r,r}async list(){return(await this.bridge.send("notifications",Ds.list,void 0,void 0,{includeOperationCheck:!0})).notifications}onRaised(e){return"function"!=typeof e?re.raiseError("onRaised expects a callback of type function"):this.registry.add("notification-raised",e)}onClosed(e){return"function"!=typeof e?re.raiseError("onClosed expects a callback of type function"):this.registry.add("notification-closed",e)}async click(e,t){X(nt,e),t&&X(nt,t),await this.bridge.send("notifications",Ds.click,{id:e,action:t},void 0,{includeOperationCheck:!0})}async clear(e){X(nt,e),await this.bridge.send("notifications",Ds.clear,{id:e},void 0,{includeOperationCheck:!0})}async clearAll(){await this.bridge.send("notifications",Ds.clearAll,void 0,void 0,{includeOperationCheck:!0})}async clearOld(){await this.bridge.send("notifications",Ds.clearOld,void 0,void 0,{includeOperationCheck:!0})}async configure(e){const t=X(Mi,e);return(await this.bridge.send("notifications",Ds.configure,{configuration:t},void 0,{includeOperationCheck:!0})).configuration}async getConfiguration(){return(await this.bridge.send("notifications",Ds.getConfiguration,void 0,void 0,{includeOperationCheck:!0})).configuration}async getActiveCount(){try{return(await this.bridge.send("notifications",Ds.getActiveCount,void 0,void 0,{includeOperationCheck:!0})).count}catch(e){return console.warn("Failed to get accurate active notifications count",e),0}}async getFilter(){return(await this.bridge.send("notifications",Ds.getConfiguration,void 0,void 0,{includeOperationCheck:!0})).configuration.sourceFilter}async setFilter(e){const t=X(Ai,e);return await this.bridge.send("notifications",Ds.configure,{configuration:{sourceFilter:t}},void 0,{includeOperationCheck:!0}),t}async setState(e,t){X(nt,e),X(ai,t),await this.bridge.send("notifications",Ds.setState,{id:e,state:t},void 0,{includeOperationCheck:!0})}onConfigurationChanged(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to configuration changed, because the provided callback is not a function!"):(setTimeout(()=>e(this.notificationsConfiguration),0),this.registry.add("notifications-config-changed",e))}onActiveCountChanged(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to onActiveCountChanged changed, because the provided callback is not a function!"):(setTimeout(()=>e({count:this.notificationsActiveCount}),0),this.registry.add("notifications-active-count-changed",e))}onStateChanged(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to onStateChanged changed, because the provided callback is not a function!"):this.registry.add("notification-state-changed",e)}addOperationExecutors(){Ds.notificationShow.execute=this.handleNotificationShow.bind(this),Ds.notificationClick.execute=this.handleNotificationClick.bind(this),Ds.notificationRaised.execute=this.handleNotificationRaised.bind(this),Ds.notificationClosed.execute=this.handleNotificationClosed.bind(this),Ds.configurationChanged.execute=this.handleConfigurationChanged.bind(this),Ds.activeCountChange.execute=this.handleActiveCountChanged.bind(this),Ds.stateChange.execute=this.handleNotificationStateChanged.bind(this),Ds.operationCheck.execute=async e=>te(this.supportedOperationsNames,e.operation),this.supportedOperationsNames=ee(Ds)}async handleConfigurationChanged(e){this.notificationsConfiguration=e.configuration,this.registry.execute("notifications-config-changed",e.configuration)}async handleActiveCountChanged(e){this.notificationsActiveCount=e.count,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 Fs={getIntents:{name:"getIntents",resultDecoder:Mn},findIntent:{name:"findIntent",dataDecoder:jn,resultDecoder:Mn},raise:{name:"raise",dataDecoder:Jn,resultDecoder:zn},filterHandlers:{name:"filterHandlers",dataDecoder:Kn,resultDecoder:Vn},getIntentsByHandler:{name:"getIntentsByHandler",dataDecoder:Pn,resultDecoder:Xn}},Ls="Tick42.FDC3.Intents.";class $s{bridge;logger;interop;appManagerController;windowsController;myIntents=new Set;prefsController;uiController;useIntentsResolverUI=!0;intentsResolverAppName;intentResolverResponseTimeout=6e4;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.prefsController=t.prefsController,this.uiController=t.uiController,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=X(Tn,e.operation),n=Fs[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=X(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=X(Hn,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 r={intentRequest:n,resolverConfig:this.getLegacyResolverConfigByRequest({intentRequest:n}),embeddedResolverConfig:this.getEmbeddedResolverConfig()},s=n.waitUserResponseIndefinitely?Z:(n.timeout||this.intentResolverResponseTimeout)+3e4;this.logger.trace(`Sending raise request to the platform: ${JSON.stringify(e)} and method response timeout of ${s}ms`);const o=await this.bridge.send("intents",Fs.raise,r,{methodResponseTimeoutMs:s,waitTimeoutMs:s});return this.logger.trace(`Raise operation completed with response: ${JSON.stringify(o)}`),o}getLegacyResolverConfigByRequest(e){if(e.handlerFilter)return{enabled:"boolean"==typeof e.handlerFilter?.openResolver?e.handlerFilter?.openResolver:this.useIntentsResolverUI,appName:this.intentsResolverAppName,waitResponseTimeout:e.handlerFilter?.timeout||9e4};const t=e.intentRequest?.waitUserResponseIndefinitely?Z:this.intentResolverResponseTimeout;return{enabled:this.useIntentsResolverUI,appName:this.intentsResolverAppName,waitResponseTimeout:t}}getEmbeddedResolverConfig(){return{enabled:this.uiController.isIntentResolverEnabled(),initialCaller:{instanceId:this.interop.instance.instance}}}async all(){await Promise.all(this.unregisterIntentPromises);return(await this.bridge.send("intents",Fs.getIntents,void 0)).intents}addIntentListener(e,t){if(X(Qn,e),"function"!=typeof t)return re.raiseError("Cannot add intent listener, because the provided handler is not a function!");let n;const i="string"==typeof e?e:e.intent,r=this.buildInteropMethodName(i);if(this.myIntents.has(i))return re.raiseError(`Intent listener for intent ${i} already registered!`);this.myIntents.add(i);const s={unsubscribe:()=>{this.myIntents.delete(i),n.then(()=>this.interop.unregister(r)).catch(e=>this.logger.trace(`Unregistration of a method with name ${r} failed with reason: ${e}`))}};let o={};if("object"==typeof e){const{intent:t,...n}=e;o=n}return n=this.interop.register({name:r,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 ${r} failed with reason: ${e}`)}),s}async register(e,t){if(X(Qn,e),"function"!=typeof t)return re.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 re.raiseError(`Intent listener for intent ${n} already registered!`);this.myIntents.add(n);let r={};if("object"==typeof e){const{intent:t,...n}=e;r=n}try{await this.interop.register({name:i,flags:{intent:r}},e=>{if(this.myIntents.has(n)){const{_initialCallerId:n,...i}=e,r=this.interop.servers().find(e=>e.instance===n);return t(i,r)}})}catch(e){return this.myIntents.delete(n),re.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=X(Dn,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",Fs.findIntent,t)).intents}onHandlerAdded(e){if("function"!=typeof e)return re.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 re.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:n,method:i})=>{if(!i.name.startsWith(Ls))return;const r=i.name.replace(Ls,""),s=await this.buildIntentHandlerFromServerMethod(e,n,i,r);t(s,r)})}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,customConfig:t.customConfig}}async buildIntentHandlerFromServerMethod(e,t,n,i){const r=n.flags.intent,s=this.appManagerController.getApplication(t.application||t.applicationName);let o;"serverMethodAdded"===e&&t.windowId&&(o=await(this.windowsController.findById(t.windowId)?.getTitle()));const a=s?.userProperties?.intents?.find(e=>e.name===i);return{applicationName:t.application||t.applicationName||"",instanceId:t.windowId||t.instance,type:"instance",applicationIcon:r?.icon||s?.icon,applicationTitle:s?.title,applicationDescription:r?.description||s?.caption,contextTypes:r?.contextTypes||a?.contexts,instanceTitle:o,displayName:r?.displayName||a?.displayName,resultType:r?.resultType||a?.resultType,customConfig:r?.customConfig}}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`${Ls}${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){X(Bn,e),this.checkIfAtLeastOneFilterIsPresent(e);const t=this.getEmbeddedResolverConfig();if(e.openResolver&&!this.useIntentsResolverUI&&!t.enabled)return re.raiseError("Cannot resolve 'filterHandlers' request using Intents Resolver UI because it's globally disabled");const n=(e.timeout||9e4)+3e4,i={filterHandlersRequest:e,resolverConfig:this.getLegacyResolverConfigByRequest({handlerFilter:e}),embeddedResolverConfig:t};return await this.bridge.send("intents",Fs.filterHandlers,i,{methodResponseTimeoutMs:n,waitTimeoutMs:n},{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 re.raiseError(t);const{intent:n,resultType:i,contextTypes:r,applicationNames:s}=e,o=r?.length,a=s?.length;return n||i||o||a?void 0:re.raiseError(t)}async getIntentsByHandler(e){X(Pn,e);return await this.bridge.send("intents",Fs.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:this.getLegacyResolverConfigByRequest({intentRequest:e}),embeddedResolverConfig:this.getEmbeddedResolverConfig()};try{return await this.bridge.send("intents",Fs.raise,n)}catch(t){this.logger.trace(`Could not raise intent to remembered handler. Reason: ${t}. Removing it from Prefs store`),await this.removeRememberedHandler(e.intent)}}}const Ws={appHello:{name:"appHello",dataDecoder:nr,resultDecoder:ir},addChannel:{name:"addChannel",dataDecoder:fi},removeChannel:{name:"removeChannel",dataDecoder:yi},getMyChannel:{name:"getMyChannel",resultDecoder:rr},getWindowIdsOnChannel:{name:"getWindowIdsOnChannel",dataDecoder:Qi,resultDecoder:Yi},getWindowIdsWithChannels:{name:"getWindowIdsWithChannels",dataDecoder:or,resultDecoder:ar},joinChannel:{name:"joinChannel",dataDecoder:lr},restrict:{name:"restrict",dataDecoder:Ci},getRestrictions:{name:"getRestrictions",dataDecoder:Si,resultDecoder:Ii},restrictAll:{name:"restrictAll",dataDecoder:xi},notifyChannelsChanged:{name:"notifyChannelsChanged",dataDecoder:ur},leaveChannel:{name:"leaveChannel",dataDecoder:hr},requestChannelSelector:{name:"requestChannelSelector",dataDecoder:Et},getMode:{name:"getMode",resultDecoder:tr},operationCheck:{name:"operationCheck"}},Hs="___channel___",Us="subs",qs="changed",Bs="channels_changed",Gs="io_connect_channels",Js="inMemory";class zs{supportedOperationsNames=[];registry=ms();logger;contexts;interop;bridge;windowsController;_mode;myWindowId;storage;handlePlatformShutdown(){this.registry.clear(),this.storage.clear()}addOperationsExecutors(){Ws.getMyChannel.execute=this.handleGetMyChannel.bind(this),Ws.joinChannel.execute=this.handleJoinChannel.bind(this),Ws.leaveChannel.execute=this.handleLeaveChannel.bind(this),Ws.restrict.execute=this.handleRestrict.bind(this),Ws.getRestrictions.execute=({windowId:e})=>this.getRestrictions(e),Ws.restrictAll.execute=this.handleRestrictAll.bind(this),Ws.operationCheck.execute=async e=>te(this.supportedOperationsNames,e.operation),this.supportedOperationsNames=ee(Ws)}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.interop=e.interop,this.addOperationsExecutors(),this.bridge=t.bridge,this.windowsController=t.windowsController,this.storage=t.channelsStorage,this.logger.trace("no need for platform registration, attaching the channels property to glue and returning"),this.myWindowId=this.windowsController.my().id??this.interop.instance.instance,await this.initialize();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: ${Y(e)}`)}}async handleBridgeMessage(e){const t=X(Xi,e.operation),n=Ws[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=X(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();X(ei(n),e),X(rt,t);const i={channel:e,windowId:t??this.myWindowId};await this.bridge.send("channels",Ws.joinChannel,i,void 0,{includeOperationCheck:!0})}handleJoinChannel({channel:e}){return"single"===this._mode?this.switchToChannel(e):this.joinAdditionalChannel(e)}onChanged(e){return this.changed(e)}async leave(e={}){const t=X(ii,e),n="string"==typeof t?void 0:t.channel,i="string"==typeof t?t:t.windowId;if(n){const e=this.getAllChannelNames();X(ei(e),n)}const r={channelName:n,windowId:i??this.myWindowId};await this.bridge.send("channels",Ws.leaveChannel,r,void 0,{includeOperationCheck:!0})}async handleAppManagerInitialChannelId(e){if("inMemory"!==this.storage.mode&&!this.storage.getSessionStorageData())return this.handleJoinChannel({channel:e,windowId:this.myWindowId})}async handleLeaveChannel({channelName:e}){const t=e?[e]:this.storage.channels;t.forEach(e=>this.storage.invokeUnsubscribes(e)),this.storage.channels=this.storage.channels.filter(e=>!t.includes(e)),this.executeChangedEvents(),await this.notifyChannelsChanged()}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),clearChannelData:this.clearChannelData.bind(this),setPath:this.setPath.bind(this),setPaths:this.setPaths.bind(this)};return Object.freeze(e)}createContextName(e){return`${Hs}${e}`}getAllChannelNames(){return this.contexts.all().filter(e=>e.startsWith(Hs)).map(e=>e.replace(Hs,""))}async joinAdditionalChannel(e){if(this.storage.channels.includes(e))return;this.storage.channels=[...this.storage.channels,e];const t=this.createContextName(e),n=await this.contexts.subscribe(t,(e,t,n,i,r)=>{this.registry.execute(Us,e.data,e,t,r?.updaterId)});this.storage.addUnsubscribe(e,n),this.executeChangedEvents(e),await this.notifyChannelsChanged()}async switchToChannel(e){const t=this.storage.channels[0];if(e===t)return;this.storage.invokeUnsubscribes(t),this.storage.channels=[e];const n=this.createContextName(e),i=await this.contexts.subscribe(n,(e,t,n,i,r)=>{this.registry.execute(Us,e.data,e,t,r?.updaterId)});this.storage.addUnsubscribe(e,i),this.executeChangedEvents(e),await this.notifyChannelsChanged()}executeChangedEvents(e){this.registry.execute(qs,e),this.registry.execute(Bs,this.storage.channels)}async notifyChannelsChanged(){const e=this.windowsController.my().id;if(e)try{await this.bridge.send("channels",Ws.notifyChannelsChanged,{channelNames:this.storage.channels,windowId:e},void 0,{includeOperationCheck:!0})}catch(e){this.logger.warn(`Failed to notify channel changed: ${Y(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:V,value:i}),await this.contexts.setPaths(n,e)}else i&&(t[V]=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?re.raiseError("FDC3 does not support updating of multiple context keys"):t[0].split("_").slice(1).join("_")}subscribe(e,t){if("function"!=typeof e)return re.raiseError("Cannot subscribe to channels, because the provided callback is not a function!");t&&X(ti,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(Us,i)}async subscribeFor(e,t,n){const i=this.getAllChannelNames();if(X(ei(i),e),"function"!=typeof t)return re.raiseError(`Cannot subscribe to channel ${e}, because the provided callback is not a function!`);n&&X(ti,n);const r=this.createContextName(e),s=n?.contextType?this.getWrappedSubscribeCallbackWithFdc3Type(t,n.contextType):this.getWrappedSubscribeCallback(t);return this.contexts.subscribe(r,(e,t,n,i,r)=>{s(e.data,e,t,r?.updaterId)})}async publish(e,t){if("object"!=typeof e)return re.raiseError("Cannot publish to channel, because the provided data is not an object!");if(X(ni,t),"object"==typeof t)return this.publishWithOptions(e,t);if("string"==typeof t){const e=this.getAllChannelNames();X(ei(e),t)}if(!t&&this.storage.channels.length>1)return this.publishOnMultipleChannels(e);const n="string"==typeof t?t:this.storage.channels[0];if(!n)return re.raiseError("Cannot publish to channel, because not joined to a channel!");return this.isAllowedByRestrictions(n,"write")?this.updateData(n,e):re.raiseError(`Cannot publish on channel ${n} due to restrictions`)}async all(){return this.getAllChannelNames()}async get(e,t){const n=this.getAllChannelNames();X(ei(n),e),t&&X(ti,t);const i=this.createContextName(e),r=await this.contexts.get(i);return t?.contextType?this.getContextForFdc3Type(r,t.contextType):r.latest_fdc3_type?this.getContextWithFdc3Data(r):r}async getMyChannels(e){return Promise.all(this.storage.channels.map(t=>this.get(t,e)))}myChannels(){return this.storage.channels}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.storage.channels[0]}changed(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to channel changed, because the provided callback is not a function!"):this.registry.add(qs,e)}async add(e){const t=X(fi,e);return this.getAllChannelNames().includes(t.name)?re.raiseError("There's an already existing channel with such name"):(await this.bridge.send("channels",Ws.addChannel,t),{name:t.name,meta:t.meta,data:t.data||{}})}async remove(e){X(nt,e);if(!this.getAllChannelNames().includes(e))return re.raiseError("There's no channel with such name");await this.bridge.send("channels",Ws.removeChannel,{name:e},void 0,{includeOperationCheck:!0})}replaySubscribe=(e,t)=>{this.get(t).then(t=>{if(!t)return;const n=this.createContextName(t.name);return this.contexts.subscribe(n,(t,n,i,r,s)=>{e(t.data,t,n,s?.updaterId)})}).then(e=>e?.()).catch(e=>this.logger.trace(e))};async getMy(e){if(this.storage.channels.length)return e&&X(ti,e),this.get(this.storage.channels[this.storage.channels.length-1],e)}async getWindowsOnChannel(e){const t=this.getAllChannelNames();X(ei(t),e);const{windowIds:n}=await this.bridge.send("channels",Ws.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:X(sr,e)}:{},{windowIdsWithChannels:n}=await this.bridge.send("channels",Ws.getWindowIdsWithChannels,t,void 0,{includeOperationCheck:!0});return n.reduce((e,{application:t,channel:n,windowId:i})=>{const r=this.windowsController.findById(i);return r?[...e,{application:t,channel:n,window:r}]:e},[])}async clearChannelData(e){await this.handleSetPaths("clearChannelData",[{path:"data",value:{}},{path:"latest_fdc3_type",value:null}],e)}async restrict(e){X(wi,e);const t=this.getAllChannelNames();X(ei(t),e.name);const n={config:{...e,windowId:e.windowId??this.myWindowId}};await this.bridge.send("channels",Ws.restrict,n,void 0,{includeOperationCheck:!0})}async handleRestrict({config:e}){const t=await this.getMy();if(!t)return this.updateRestriction(e);const n=this.isAllowedByRestrictions(t.name,"read");this.updateRestriction(e);e.name===t.name&&!n&&e.read&&this.replaySubscribeCallback(e.name)}updateRestriction(e){const t=this.storage.restrictions.some(t=>t.name===e.name);this.storage.restrictions=t?this.storage.restrictions.map(t=>t.name===e.name?e:t):this.storage.restrictions.concat(e)}updateAllRestrictions(e){const t=this.getAllChannelNames();this.storage.restrictions=t.map(t=>({name:t,...e}))}async getRestrictions(e){X(rt,e);const t=e&&e!==this.interop.instance.instance;return e&&t?this.bridge.send("channels",Ws.getRestrictions,{windowId:e},void 0,{includeOperationCheck:!0}):{channels:this.storage.restrictions}}async restrictAll(e){X(_i,e);const t={restrictions:{...e,windowId:e.windowId??this.myWindowId}};await this.bridge.send("channels",Ws.restrictAll,t,void 0,{includeOperationCheck:!0})}async handleRestrictAll({restrictions:e}){const t=await this.getMy();if(!t)return void this.updateAllRestrictions(e);const n=this.isAllowedByRestrictions(t.name,"read");this.updateAllRestrictions(e),!n&&e.read&&this.replaySubscribeCallback(t.name)}async setPath(e,t){const n=X(mi,e),i=[{path:`data.${n.path}`,value:n.value}];await this.handleSetPaths("setPath",i,t)}async setPaths(e,t){const n=X(bi,e).map(({path:e,value:t})=>({path:`data.${e}`,value:t}));await this.handleSetPaths("setPaths",n,t)}async handleSetPaths(e,t,n){const i=n?[n]:this.storage.channels;if(!i.length)return re.raiseError(`Cannot complete ${e} operation, because channel is not specified. Either join one or pass a channel name as second argument!`);this.validateChannelNames(i);const{allowed:r,forbidden:s}=this.groupChannelsByPermission("write",i);if(i.length===s.length)return re.raiseError(`Cannot complete ${e} operation due to write restrictions to the following channels: ${i.join(", ")}`);s.length&&this.logger.warn(`Cannot set paths on channel${s.length>1?"s":""}: ${s.join(", ")} due to write restrictions`),await Promise.all(r.map(e=>{const n=this.createContextName(e);return this.contexts.setPaths(n,t)}))}validateChannelNames(e){const t=this.getAllChannelNames();e.forEach(e=>X(ei(t),e))}groupChannelsByPermission(e,t){return t.reduce((t,n)=>(this.isAllowedByRestrictions(n,e)?t.allowed.push(n):t.forbidden.push(n),t),{allowed:[],forbidden:[]})}isAllowedByRestrictions(e,t){const n=this.storage.restrictions.find(t=>t.name===e);return!n||n[t]}replaySubscribeCallback(e){const t=this.createContextName(e);this.contexts.subscribe(t,(e,t,n,i,r)=>{this.registry.execute(Us,e.data,e,t,r?.updaterId)}).then(e=>{e&&"function"==typeof e&&e()}).catch(e=>this.logger.error(e))}async publishWithOptions(e,t){if(t.name){const e=this.getAllChannelNames();X(ei(e),t.name)}if(!t.name&&this.storage.channels.length>1)return this.publishOnMultipleChannels(e,t.fdc3);const n=t.name||this.storage.channels[0];if(!n)return re.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):re.raiseError(`Cannot publish on channel ${n} due to restrictions`)}async publishOnMultipleChannels(e,t){const{allowed:n,forbidden:i}=this.groupChannelsByPermission("write",this.storage.channels);if(this.storage.channels.length===i.length)return re.raiseError(`Cannot complete 'publish' operation due to write restrictions to all joined channels: ${this.storage.channels.join(", ")}`);i.length&&this.logger.warn(`Data on channel${i.length>1?"s":""}: ${i.join(", ")} won't be published due to write restrictions`);const r=t?this.publishFdc3Data.bind(this):this.updateData.bind(this);await Promise.all(n.map(t=>r(t,e)))}async publishFdc3Data(e,t){X(ri,t);const{type:n,...i}=t,r=n.split(".").join("&"),s={[`fdc3_${r}`]:i};return this.updateData(e,s)}getWrappedSubscribeCallback(e){return(t,n,i,r)=>{if(!this.isAllowedByRestrictions(n.name,"read"))return;const{data:s,latest_fdc3_type:o}=n,a=`fdc3_${o}`;if(!o||i.data&&!i.data[a])return void e(t,n,r);const c={type:o.split("&").join("."),...s[a]},{[a]:d,...l}=t;e({...l,fdc3:c},n,r)}}getWrappedSubscribeCallbackWithFdc3Type(e,t){const n={replayed:!1};return(i,r,s,o)=>{if(!this.isAllowedByRestrictions(r.name,"read"))return;const{data:a,latest_fdc3_type:c}=r,d=`fdc3_${t.split(".").join("&")}`;if(!a[d]||s.data&&!s.data[d])return;if(n.replayed)return this.parseDataAndInvokeSubscribeCallback({latestFdc3TypeEncoded:c,searchedType:t,callback:e,context:r,updaterId:o});const l={type:t,...a[d]};e({fdc3:l},r,o),n.replayed=!0}}parseDataAndInvokeSubscribeCallback(e){const{latestFdc3TypeEncoded:t,searchedType:n,callback:i,context:r,updaterId:s}=e;if(t.split("&").join(".")!==n)return;i({fdc3:{type:n,...r.data[`fdc3_${t}`]}},r,s)}async requestChannelSelector(e){if(!e)return;const t=e.application,n=t.userProperties?.details;if(!n)return;if(!n?.channelSelector?.enabled)return;const i={windowId:e.id,channelsNames:this.storage.channels};await this.bridge.send("channels",Ws.requestChannelSelector,i,void 0,{includeOperationCheck:!0})}async getPlatformChannelsMode(){try{return(await this.bridge.send("channels",Ws.getMode,{},void 0,{includeOperationCheck:!0})).mode}catch(e){return this.logger.warn(e?.message||JSON.stringify(e)),"single"}}onChannelsChanged(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to channels changed, because the provided callback is not a function"):this.registry.add(Bs,e)}async initialize(){if(!await this.checkIfAppHelloSupported())return this.handleAppHelloFailure("Platform does not support 'appHello' operation and channel state persistence by windowId. Setting 'sessionStorage' mode for tracking channels and restrictions");const{success:e,error:t}=await this.sendAppHello();if(t)return this.handleAppHelloFailure(t);this.logger.trace(`Received 'appHelloSuccess' message. Setting initial channels state to: ${JSON.stringify(e)}`);const{mode:n,channels:i,restrictions:r}=e;this.storage.mode="inMemory",this._mode=n,this.storage.channels=i,this.storage.restrictions=r}async handleAppHelloFailure(e){this.logger.trace(e),this.storage.mode="sessionStorage",this._mode=await this.getPlatformChannelsMode()}async sendAppHello(){try{return{success:await this.bridge.send("channels",Ws.appHello,{windowId:this.myWindowId},void 0,{includeOperationCheck:!0}),error:void 0}}catch(e){return{error:`Failed to get initial state from platform. Error: ${Y(e)}`,success:void 0}}}async checkIfAppHelloSupported(){try{const{isSupported:e}=await this.bridge.send("channels",Ws.operationCheck,{operation:Ws.appHello.name},void 0,{includeOperationCheck:!0});return e}catch(e){return this.logger.trace(`Platform does not support 'appHello' operation and channel state persistence by windowId. Error: ${Y(e)}`),!1}}}const Vs={getEnvironment:{name:"getEnvironment",resultDecoder:Pt},getBase:{name:"getBase",resultDecoder:Pt},platformShutdown:{name:"platformShutdown"},isFdc3DataWrappingSupported:{name:"isFdc3DataWrappingSupported"},clientError:{name:"clientError",dataDecoder:Ir},systemHello:{name:"systemHello",resultDecoder:Sr},operationCheck:{name:"operationCheck"}};class Ks{supportedOperationsNames=[];bridge;ioc;logger;errorPort=K.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",Vs.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",Vs.clientError,{message:e.data},void 0,{includeOperationCheck:!0})},await this.setEnvironment()}async handleBridgeMessage(e){const t=X(ht,e.operation),n=Vs[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=X(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",Vs.getEnvironment,void 0),t=await this.bridge.send("system",Vs.getBase,void 0),n=window.glue42core||window.iobrowser,i=window.glue42core?"glue42core":"iobrowser",r=Object.assign({},n,t,{environment:e});window[i]=r}addOperationsExecutors(){Vs.platformShutdown.execute=this.processPlatformShutdown.bind(this),Vs.isFdc3DataWrappingSupported.execute=this.handleIsFdc3DataWrappingSupported.bind(this),Vs.operationCheck.execute=async e=>te(this.supportedOperationsNames,e.operation),this.supportedOperationsNames=ee(Vs)}async handleIsFdc3DataWrappingSupported(){return{isSupported:!0}}}class Zs{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}}R(T("clientHello"));const Qs={clientHello:{name:"clientHello",resultDecoder:P({widget:P({inject:_()})})}};class Ys{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",Qs.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 Xs{config;glue;registry=ms();glue42EventName="Glue42";_handleMessage;_resolveWidgetReadyPromise;_resolveModalsUIFactoryReadyPromise;_resolveIntentResolverUIFactoryReadyPromise;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)},modalsUIFactoryReady:{name:"modalsUIFactoryReady",handle:this.handleModalsUIFactoryReady.bind(this)},intentResolverUIFactoryReady:{name:"intentResolverUIFactoryReady",handle:this.handleIntentResolverUIFactoryReady.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(){const e=new Promise(e=>{this._resolveWidgetReadyPromise=e});return this.requestWidgetReady(),e}async modalsUIFactoryReady(){const e=new Promise(e=>{this._resolveModalsUIFactoryReadyPromise=e});return this.requestModalsUIFactoryReady(),e}async intentResolverUIFactoryReady(){const e=new Promise(e=>{this._resolveIntentResolverUIFactoryReadyPromise=e});return this.requestIntentResolverUIFactoryReady(),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,r=this.events[i];r&&r.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?.()}requestModalsUIFactoryReady(){this.send("requestModalsUIFactoryReady","glue42")}handleModalsUIFactoryReady(){this._resolveModalsUIFactoryReadyPromise?.()}requestIntentResolverUIFactoryReady(){this.send("requestIntentResolverUIFactoryReady","glue42")}handleIntentResolverUIFactoryReady(){this._resolveIntentResolverUIFactoryReadyPromise?.()}send(e,t,n){const i={};i[t]={event:e,message:n};const r=new CustomEvent(this.glue42EventName,{detail:i});window.dispatchEvent(r)}}class eo{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()===z))return re.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()===z,n=e.type,i=e.args,r=e.transactionId;return n===$.name?this.handleTransportSwitchRequest(i,r):n!==L.name||t?n===U.name?this.handleGetCurrentTransportResponse(i,r):n===q.name?this.handleCheckPreferredLogic(r):n===B.name?this.handleCheckPreferredConnection(i,r):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(H.name);this.sendPlatformMessage(H.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=js(10),i=new Promise((i,r)=>{let s=!0;t.lift=e=>{s=!1,delete this.transactionLocks[n],i(e)},t.fail=e=>{s=!1,delete this.transactionLocks[n],r(e)},setTimeout(()=>{s&&(s=!1,this.logger.warn(`Transaction for operation: ${e} timed out.`),delete this.transactionLocks[n],r(`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(W.name,t,{success:e.success})}).catch(e=>{this.logger.error(e),this.sendPlatformMessage(W.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(G.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(J.name,t,e)}).catch(e=>{this.logger.trace(`The connection to ${n} is not possible`),this.sendPlatformMessage(J.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()}}const to={getCurrent:{name:"getCurrent",resultDecoder:Bi},list:{name:"list",resultDecoder:Gi},select:{name:"select",dataDecoder:Ji}};class no{logger;bridge;registry=ms();themesSubscription;async start(e,t){this.logger=e.logger.subLogger("themes.controller.web"),this.logger.trace("starting the web themes controller"),this.bridge=t.bridge,await this.setupSubscription(),this.logger.trace("themes subscription is ready");const n=this.toApi();e.themes=n,this.logger.trace("themes are ready")}handlePlatformShutdown(){this.registry.clear(),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",to.getCurrent,void 0,void 0,{includeOperationCheck:!0})).theme}async list(){return(await this.bridge.send("themes",to.list,void 0,void 0,{includeOperationCheck:!0})).themes}async select(e){X(nt,e),await this.bridge.send("themes",to.select,{name:e},void 0,{includeOperationCheck:!0})}onChanged(e){return"function"!=typeof e?re.raiseError("onChanged requires a callback of type function"):this.registry.add("on-theme-change",e)}async setupSubscription(){this.themesSubscription=await this.bridge.createThemesSubscription(),this.themesSubscription.onData(this.handleStreamData.bind(this)),this.themesSubscription.onClosed(this.handleStreamClosure.bind(this))}handleStreamData(e){const t=e.data,n=Bi.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)}handleStreamClosure(){this.logger.warn("The Themes interop stream was closed, no theme changes notifications will be received"),this.registry.clear(),delete this.themesSubscription}}class io{sessionStorage=window.sessionStorage;_mode=Js;inMemoryChannels=[];inMemoryRestrictions=[];_unsubscribeDict={};clear(){this._mode=Js,this.inMemoryChannels=[],this.inMemoryRestrictions=[],this._unsubscribeDict={},this.sessionStorage.setItem(Gs,JSON.stringify([]))}get mode(){return this._mode}set mode(e){this._mode=e}get channels(){return"inMemory"===this.mode?this.inMemoryChannels.slice():this.getSessionStorageData()?.channels??[]}set channels(e){"inMemory"===this.mode&&(this.inMemoryChannels=e),this.setSessionStorageChannels(e)}get restrictions(){return"inMemory"===this.mode?this.inMemoryRestrictions.slice():this.getSessionStorageData()?.restrictions??[]}set restrictions(e){"inMemory"===this.mode&&(this.inMemoryRestrictions=e),this.setSessionStorageRestrictions(e)}getSessionStorageData(){return JSON.parse(this.sessionStorage.getItem(Gs)||"null")}addUnsubscribe(e,t){this._unsubscribeDict[e]=t}invokeUnsubscribes(e){if(e)return this._unsubscribeDict[e]?.(),void delete this._unsubscribeDict[e];Object.values(this._unsubscribeDict).forEach(e=>e()),this._unsubscribeDict={}}setSessionStorageChannels(e){const t=this.getSessionStorageData();if(t?.channels)return t.channels=e,this.setSessionStorageData(t);const n={channels:e,restrictions:t?.restrictions??[]};return this.setSessionStorageData(n)}setSessionStorageRestrictions(e){const t=this.getSessionStorageData();if(t?.restrictions)return t.restrictions=e,this.setSessionStorageData(t);const n={channels:t?.channels??[],restrictions:e};return this.setSessionStorageData(n)}setSessionStorageData(e){this.sessionStorage.setItem(Gs,JSON.stringify(e))}}const ro={clear:{name:"clear",dataDecoder:mr},clearAll:{name:"clearAll"},get:{name:"get",dataDecoder:mr,resultDecoder:br},getAll:{name:"getAll",resultDecoder:yr},set:{name:"set",dataDecoder:vr},update:{name:"update",dataDecoder:vr},prefsChanged:{name:"prefsChanged",dataDecoder:br},prefsHello:{name:"prefsHello",resultDecoder:Cr},operationCheck:{name:"operationCheck"},registerSubscriber:{name:"registerSubscriber",dataDecoder:wr}};class so{supportedOperationsNames=[];bridge;config;logger;appManagerController;platformAppName;registry=ms();validNonExistentApps;signaledSubscription=!1;interopId;isAppValidationEnabled;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.interopId=e.interop.instance.instance,this.bridge=t.bridge,this.config=t.config,this.appManagerController=t.appManagerController;try{const e=await this.bridge.send("prefs",ro.prefsHello,void 0,void 0,{includeOperationCheck:!0});this.platformAppName=e.platform.app,this.validNonExistentApps=e.validNonExistentApps??[],this.isAppValidationEnabled=e.isAppValidationEnabled??!0}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=X(gr,e.operation),n=ro[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=X(n.dataDecoder,e.data)),await n.execute(i)}async get(e){const t=null==e?this.getMyAppName():X(nt,e),{prefs:n}=await this.bridge.send("prefs",ro.get,{app:t},void 0,{includeOperationCheck:!0});return n}async update(e,t){const n=X(O(mr),t),i=n?.app??this.getMyAppName();await this.updateFor(i,e)}addOperationsExecutors(){ro.prefsChanged.execute=this.handleOnChanged.bind(this),ro.operationCheck.execute=async e=>te(this.supportedOperationsNames,e.operation),this.supportedOperationsNames=ee(ro)}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",ro.clearAll,void 0,void 0,{includeOperationCheck:!0})}async clearFor(e){const t=X(nt,e);await this.bridge.send("prefs",ro.clear,{app:t},void 0,{includeOperationCheck:!0})}async getAll(){return await this.bridge.send("prefs",ro.getAll,void 0,void 0,{includeOperationCheck:!0})}async set(e,t){const n=X(O(mr),t),i=n?.app??this.getMyAppName();await this.setFor(i,e)}async setFor(e,t){const n=X(nt,e),i=X(P(),t);await this.bridge.send("prefs",ro.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=X(nt,e),i=this.appManagerController.getApplications();if(!(!this.isAppValidationEnabled||(n===this.platformAppName||i.some(e=>e.name===n)||this.validNonExistentApps.includes(n))))return re.raiseError(`The provided app name "${e}" is not valid.`);if("function"!=typeof t)return re.raiseError("Cannot subscribe to prefs, because the provided callback is not a function!");this.signaledSubscription||(this.bridge.send("prefs",ro.registerSubscriber,{interopId:this.interopId,appName:n},void 0,{includeOperationCheck:!0}).catch(e=>{this.logger.warn("Failed to register subscriber for prefs"),this.logger.error(e)}),this.signaledSubscription=!0);const r=this.getSubscriptionKey(n);return this.get(n).then(t),this.registry.add(r,t)}async updateFor(e,t){const n=X(nt,e),i=X(P(),t);await this.bridge.send("prefs",ro.update,{app:n,data:i},void 0,{includeOperationCheck:!0})}getMyAppName(){const e=this.config.isPlatformInternal?this.platformAppName:this.appManagerController.me?.application.name;return e||re.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)}}const oo={getResources:{name:"getResources",dataDecoder:Lr,resultDecoder:Br},operationCheck:{name:"operationCheck",dataDecoder:Hi,resultDecoder:Wi},showAlert:{name:"showAlert",dataDecoder:Kr},showDialog:{name:"showDialog",dataDecoder:Yr},alertInteropAction:{name:"alertInteropAction",dataDecoder:rs},showResolver:{name:"showResolver",dataDecoder:us,resultDecoder:ps}},ao="io-modals-shadow-host",co="io-widget-shadow-host",lo="io-intent-resolver-shadow-host";class ho{ioc;supportedOperationsNames=[];logger;bridge;config;zIndexDictionary={[co]:"100",[ao]:"101",[lo]:"100"};widgetResources;modalsResources;intentResolverResources;rootElements=[];modalsUiApi;isDialogOpen=!1;intentResolverUiApi;isIntentResolverOpen=!1;constructor(e){this.ioc=e}async start(e,t){this.logger=e.logger.subLogger("ui.controller.web"),this.logger.trace("starting the ui controller"),this.bridge=t.bridge,this.config=t.config,this.addOperationsExecutors();const n=await this.getResources();n?(this.logger.trace(`Received UI resources from platform: ${JSON.stringify(n)}`),this.setResources(n)):this.logger.trace("No UI elements to display - platform is not initialized with any UI resources")}async handleBridgeMessage(e){const t=X(Fr,e.operation),n=oo[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=X(n.dataDecoder,e.data)),await n.execute(i)}async showComponents(e){const t=this.widgetResources?this.initializeWidget(e,this.widgetResources):Promise.resolve(),n=this.modalsResources?this.initializeModalsUi(e,this.modalsResources):Promise.resolve(),i=this.intentResolverResources?this.initializeIntentResolverUI(e,this.intentResolverResources):Promise.resolve();this.subscribeForThemeChanges(e),await Promise.all([this.config.widget.awaitFactory?t:Promise.resolve(),this.config.modals.awaitFactory?n:Promise.resolve(),this.config.intentResolver.awaitFactory?i:Promise.resolve()])}isIntentResolverEnabled(){return!!this.intentResolverResources&&this.config.intentResolver.enable}addOperationsExecutors(){oo.operationCheck.execute=async e=>te(this.supportedOperationsNames,e.operation),oo.showAlert.execute=this.handleShowAlert.bind(this),oo.showDialog.execute=this.handleShowDialog.bind(this),oo.showResolver.execute=this.handleShowResolver.bind(this),this.supportedOperationsNames=ee(oo)}async handleShowAlert({config:e}){if(!this.config.modals.alerts.enabled)return re.raiseError("Unable to perform showAlert operation because the client was initialized with 'modals: { alerts: { enabled: false } }' config.");const t=this.modalsUiApi;if(!t)return re.raiseError("Unable to perform showAlert operation because modalsUiApi is missing.");const{promise:n,resolve:i}=ie(),r=e=>{const t=is.run(e);if(!t.ok)return void this.logger.error(`alert.onClick() was invoked with an invalid config. Error: ${JSON.stringify(t.error)}.`);const{interopAction:n}=t.result;this.bridge.send("ui",oo.alertInteropAction,{interopAction:n},void 0,{includeOperationCheck:!0}).catch(e=>this.logger.warn(Y(e)))};let s;try{this.logger.trace(`Open alert with config: ${JSON.stringify(e)}`),s=t.alerts.open({...e,onClick:r,onClose:i})}catch(e){return re.raiseError(`modalsUiApi.alerts.open() failed. Reason: ${Y(e)}.`)}const o=Xr.run(s);if(!o.ok)return re.raiseError(`modalsUiApi.alerts.open() returned an invalid result. Error: ${JSON.stringify(o.error)}.`);const a=setTimeout(()=>{i()},ne(e.ttl??5e3));n.then(()=>{clearTimeout(a);try{t.alerts.close({id:o.result.id})}catch(e){this.logger.warn(`Failed to close alert with id ${o.result.id}. Reason: ${Y(e)}`)}})}async handleShowDialog({config:e}){if(!this.config.modals.dialogs.enabled)return re.raiseError("Unable to perform showDialog operation because the client was initialized with 'modals: { dialogs: { enabled: false } }' config.");const t=this.modalsUiApi;if(!t)return re.raiseError("Unable to perform showDialog operation because modalsUiApi is missing.");if(this.isDialogOpen)return re.raiseError("Cannot open a dialog because another one is already open.");const{promise:n,resolve:i}=ie();let r;try{this.logger.trace(`Open dialog with config: ${JSON.stringify(e)}`),r=t.dialogs.open({...e,onCompletion:i})}catch(e){return re.raiseError(`modalsUiApi.dialogs.open() failed. Reason: ${Y(e)}.`)}const s=es.run(r);if(!s.ok)return re.raiseError(`modalsUiApi.dialogs.open() returned an invalid result. Error: ${JSON.stringify(s.error)}.`);let o;this.isDialogOpen=!0,e.timer&&(o=setTimeout(()=>{i({response:{isExpired:!0}})},ne(e.timer.duration)));const a=await n;clearTimeout(o),this.isDialogOpen=!1;try{t.dialogs.close({id:s.result.id})}catch(e){this.logger.warn(`Failed to close dialog with id ${s.result.id}. Reason: ${Y(e)}`)}const c=ts.run(a);return c.ok?{result:c.result.response}:re.raiseError(`completionPromise was resolved with an invalid result. Error: ${JSON.stringify(c.error)}.`)}async handleShowResolver({config:e}){if(this.logger.trace(`Received open intent resolver request with config: ${JSON.stringify(e)}`),!this.config.intentResolver.enable)return re.raiseError("Unable to perform showResolver operation because the client was initialized with 'intentResolver: { enable: false }' config.");const t=this.intentResolverUiApi;if(!t)return re.raiseError("Unable to perform showResolver operation because intentResolverApi is missing.");if(this.isIntentResolverOpen)return re.raiseError("Cannot open the intent resolver because another one is already open.");const{promise:n,resolve:i}=ie();let r;try{this.logger.trace(`Open intent resolver with config: ${JSON.stringify(e)}`),r=t.open({...e,onUserResponse:i})}catch(e){return re.raiseError(`intentResolverUI.open() failed. Reason: ${Y(e)}.`)}const s=os.run(r);if(!s.ok)return re.raiseError(`intentResolverUI.open() returned an invalid result. Error: ${JSON.stringify(s.error)}.`);const o=setTimeout(()=>i({response:{isExpired:!0}}),ne(e.timeout)),a=await n;clearTimeout(o),this.isIntentResolverOpen=!1;try{t.close({id:s.result.id})}catch(e){this.logger.warn(`Failed to close intent resolver with id ${s.result.id}. Reason: ${Y(e)}`)}const c=ls.run(a);return c.ok?{result:c.result.response}:re.raiseError(`completionPromise was resolved with an invalid result. Error: ${JSON.stringify(c.error)}.`)}async getResources(){const e={origin:window.origin};try{return(await this.bridge.send("ui",oo.getResources,e,void 0,{includeOperationCheck:!0})).resources}catch(e){this.logger.warn(e?.message||JSON.stringify(e))}}appendModalsResources(e){return this.logger.trace("Appending modals resources"),this.appendResources(ao,"io-modals-root",e.sources)}appendWidgetResources(e){return this.logger.trace("Appending widget resources"),this.appendResources(co,"io-widget-root",e.sources)}appendIntentResolverResources(e){return this.logger.trace("Appending intent resolver resources"),this.appendResources(lo,"io-intent-resolver-root",e.sources)}appendResources(e,t,n){const{bundle:i,fonts:r=[],styles:s}=n,o=document.createElement("div");o.id=e,o.style.position="fixed",o.style.zIndex=this.zIndexDictionary[e];const a=o.attachShadow({mode:"open"}),c=document.createElement("script");c.src=i,c.type="module",a.appendChild(c);const d=document.createElement("div");return d.id=t,d.className="io-body io-variables",a.appendChild(d),s.forEach(e=>{const t=document.createElement("link");t.rel="stylesheet",t.href=e,a.appendChild(t)}),r.forEach(e=>{const t=document.createElement("link");t.rel="stylesheet",t.href=e,document.head.insertBefore(t,document.head.firstChild)}),document.body.appendChild(o),{rootElement:d}}async initializeWidget(e,t){this.logger.trace("Initializing IOBrowserWidget.");const{rootElement:n}=this.appendWidgetResources(t);this.rootElements.push(n);const i={...d(t.config,this.config.widget),rootElement:n};return vs(async()=>{await this.ioc.eventsDispatcher.widgetReady(),this.logger.trace(`IOBrowserWidget factory is available. Invoking it with config: ${JSON.stringify(i)}`),await window.IOBrowserWidget(e,i),this.logger.trace("IOBrowserWidget was initialized successfully.")},i.timeout,`Timeout of ${i.timeout}ms hit waiting for IOBrowserWidget to initialize.`)}async initializeModalsUi(e,t){this.logger.trace("Initializing IOBrowserModalsUI.");const{rootElement:n}=this.appendModalsResources(t);this.rootElements.push(n);const i={...this.config.modals,rootElement:n};return vs(async()=>{await this.ioc.eventsDispatcher.modalsUIFactoryReady(),this.logger.trace(`IOBrowserModalsUI factory is available. Invoking it with config: ${JSON.stringify(i)}`),this.modalsUiApi=await window.IOBrowserModalsUI(e,i),this.logger.trace("IOBrowserModalsUI was initialized successfully.")},i.timeout,`Timeout of ${i.timeout}ms hit waiting for IOBrowserModalsUI to initialize.`)}async initializeIntentResolverUI(e,t){this.logger.trace("Initializing IOBrowserIntentResolverUI.");const{rootElement:n}=this.appendIntentResolverResources(t);this.rootElements.push(n);const i={...this.config.intentResolver,rootElement:n},r=i.timeout;return vs(async()=>{await this.ioc.eventsDispatcher.intentResolverUIFactoryReady(),this.logger.trace(`IOBrowserIntentResolverUI factory is available. Invoking it with config: ${JSON.stringify(i)}`),this.intentResolverUiApi=await window.IOBrowserIntentResolverUI(e,i),this.logger.trace("IOBrowserIntentResolverUI initialized successfully.")},r,`Timeout of ${r}ms hit waiting for IOBrowserIntentResolverUI to initialize.`)}setResources(e){this.setWidgetResources(e.widget),this.setModalsUiResources(e.modals),this.setIntentResolverResources(e.intentResolver)}setWidgetResources(e){const t="Widget won't be displayed. Reason: ",n=jr.run(this.config.widget);n.ok?this.config.widget.enable?e?e.blockedOrigin?this.logger.warn(`${t} Platform has blocked client's origin ('${window.location.toString()}') from retrieving widget resources`):this.widgetResources=e:this.logger.trace(`${t} Platform did not provide resources`):this.logger.trace(`${t} Client initialized with 'widget: { enable: false }' config`):this.logger.warn(`${t} invalid widget config. Error: ${n.error}`)}setModalsUiResources(e){const t="Modals won't be displayed. Reason: ",n=Nr.run(this.config.modals);n.ok?this.config.modals.alerts.enabled||this.config.modals.dialogs.enabled?e?e.blockedOrigin?this.logger.warn(`${t} Platform has blocked client's origin ('${window.location.toString()}') from retrieving modals resources`):this.modalsResources=e:this.logger.trace(`${t} Platform did not provide resources`):this.logger.trace(`${t} Client initialized with 'modals: { alerts: { enabled: false }, dialogs: { enabled: false } }' config`):this.logger.warn(`${t} invalid modals config. Error: ${n.error}`)}setIntentResolverResources(e){const t="Intent Resolver UI won't be displayed. Reason: ",n=ss.run(this.config.intentResolver);n.ok?this.config.intentResolver.enable?e?e.blockedOrigin?this.logger.warn(`${t} Platform has blocked client's origin ('${window.location.toString()}') from retrieving intent resolver resources`):this.intentResolverResources=e:this.logger.trace(`${t} Platform did not provide resources`):this.logger.trace(`${t} Client initialized with 'intentResolver: { enable: false }' config`):this.logger.warn(`${t} invalid intent resolver config. Error: ${JSON.stringify(n.error)}`)}subscribeForThemeChanges(e){const t=e.themes;if(!t)return;const n=async e=>{await Promise.all(this.rootElements.map(n=>this.applyThemeToElement(n,t,e)))};t.onChanged(n),t.getCurrent().then(n)}async applyThemeToElement(e,t,n){if(e.classList.contains(n.name))return;const i=await t.list();e.classList.remove(...i.map(({name:e})=>e)),e.classList.add(n.name)}}class uo{_coreGlue;_communicationId;_publicWindowId;_webConfig;_windowsControllerInstance;_appManagerControllerInstance;_layoutsControllerInstance;_notificationsControllerInstance;_intentsControllerInstance;_channelsControllerInstance;_themesControllerInstance;_extensionController;_systemControllerInstance;_bridgeInstance;_eventsDispatcher;_preferredConnectionController;_channelsStorage;_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 Is),this._windowsControllerInstance}get uiController(){return this._uiController||(this._uiController=new ho(this)),this._uiController}get appManagerController(){return this._appManagerControllerInstance||(this._appManagerControllerInstance=new Os),this._appManagerControllerInstance}get layoutsController(){return this._layoutsControllerInstance||(this._layoutsControllerInstance=new Es),this._layoutsControllerInstance}get themesController(){return this._themesControllerInstance||(this._themesControllerInstance=new no),this._themesControllerInstance}get notificationsController(){return this._notificationsControllerInstance||(this._notificationsControllerInstance=new Ns),this._notificationsControllerInstance}get intentsController(){return this._intentsControllerInstance||(this._intentsControllerInstance=new $s),this._intentsControllerInstance}get systemController(){return this._systemControllerInstance||(this._systemControllerInstance=new Ks),this._systemControllerInstance}get channelsController(){return this._channelsControllerInstance||(this._channelsControllerInstance=new zs),this._channelsControllerInstance}get prefsController(){return this._prefsControllerInstance||(this._prefsControllerInstance=new so),this._prefsControllerInstance}get extensionController(){return this._extensionController||(this._extensionController=new Ys),this._extensionController}get eventsDispatcher(){return this._eventsDispatcher||(this._eventsDispatcher=new Xs(this.config)),this._eventsDispatcher}get bridge(){return this._bridgeInstance||(this._bridgeInstance=new Ps(this._coreGlue,this.communicationId)),this._bridgeInstance}get preferredConnectionController(){return this._preferredConnectionController||(this._preferredConnectionController=new eo(this._coreGlue)),this._preferredConnectionController}get channelsStorage(){return this._channelsStorage||(this._channelsStorage=new io),this._channelsStorage}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,n){const i=new ys(e,t,this.bridge,n),r=await i.toApi();return{id:e,model:i,api:r}}buildNotification(e,t){return new Zs(e,t)}async buildApplication(e,t){const n=new As(e,[],this.appManagerController).toApi(),i=t.map(e=>this.buildInstance(e,n));return n.instances.push(...i),n}buildInstance(e,t){return new Rs(e,this.bridge,t).toApi()}}var po="4.5.0";const go=(e,t)=>({getContainerInfo:async()=>{if(window!==window.parent)return window.name.includes("#wsp")?{workspaceFrame:{id:"N/A"}}:window.parent===window.top?{top:{}}:{parent:{}}},getProfileData:async()=>{if(!t)throw new Error("Bridge is not available and cannot fetch the profile data");return await t.send("system",{name:"getProfileData"},void 0)}});var fo=1,mo=2,bo=3,yo=4;function wo(e){return e.type===bo?"timestamp":e.type===mo?"number":e.type===fo?"string":e.type===yo?"object":"unknown"}function vo(e){return e.constructor===Date?"timestamp":"number"==typeof e?"number":"string"==typeof e?"string":"object"==typeof e?"object":"string"}function Co(e){const t={},n=wo(e);if("object"===n){const n=Object.keys(e.value).reduce((t,n)=>{const i=vo(e.value[n]);if("object"===i){const i=Io(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=So(e.path.join("/")+"/"+e.name),t.type=n,t.description=e.description,t.context={},t}function Io(e){return Object.keys(e).reduce((t,n)=>{const i=vo(e[n]);return t[n]="object"===i?{type:"object",description:"",context:{},composite:Io(e[n])}:{type:i,description:"",context:{}},t},{})}function So(e){return void 0!==e&&e.length>0&&"/"!==e[0]?"/"+e:e}function _o(e){return"timestamp"===wo(e)?Date.now():xo(e.value)}function xo(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]=xo(i):i.constructor===Date?t[n]=new Date(i).getTime():i.constructor===Boolean?t[n]=i.toString():t[n]=i,t},{})}function To(e){return e.reduce((e,t)=>e.concat(Array.isArray(t)?To(t):t),[])}function Po(e){const t=To(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 r=e.path.join(".");n===i.length-1?t+=r+"."+e.name+": "+e.description:t+=r+"."+e.name+": "+e.description+","}),t.length>100?t.slice(0,100)+"...":t}(t);return{description:i,value:n.state}}var ko=(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 Oo{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,r){this.definition=e,this.system=t,this.transport=n,this.value=i,this.type=r,ko(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 Ro extends Oo{constructor(e,t,n,i){super(e,t,n,i,mo)}incrementBy(e){this.update(this.value+e)}increment(){this.incrementBy(1)}decrement(){this.incrementBy(-1)}decrementBy(e){this.incrementBy(-1*e)}}class Ao extends Oo{constructor(e,t,n,i){super(e,t,n,i,yo)}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 Mo extends Oo{constructor(e,t,n,i){super(e,t,n,i,fo)}}class Eo extends Oo{constructor(e,t,n,i){super(e,t,n,i,bo)}now(){this.update(new Date)}}function Do(e,t,n,i,r){if(!t)throw new Error("Repository is required");if(!n)throw new Error("Transport is required");const s=n,o=e,a=r||"",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 f=t.root,m=[],b=[];function y(e,t,n,i){let r={name:""};r="string"==typeof e?{name:e}:e;const s=b.filter(e=>e.name===r.name);if(s.length>0){const e=s[0];if(e.type!==t)throw new Error(`A metric named ${r.name} is already defined with different type.`);return void 0!==n&&e.update(n).catch(()=>{}),e}const o=i(r);return b.push(o),o}const w={get name(){return o},get description(){return a},get repo(){return c},get parent(){return d},path:l,id:u,root:f,get subSystems(){return m},get metrics(){return b},subSystem:function(e,t){if(!e||0===e.length)throw new Error("name is required");const n=m.filter(t=>t.name===e);if(n.length>0)return n[0];const i=Do(e,c,s,w,t);return m.push(i),i},getState:()=>h,setState:function(e,t){h={state:e,description:t},s.updateSystem(w,h)},stringMetric:function(e,t){return y(e,fo,t,e=>new Mo(e,w,s,t))},timestampMetric:function(e,t){return y(e,bo,t,e=>new Eo(e,w,s,t))},objectMetric:function(e,t){return y(e,yo,t,e=>new Ao(e,w,s,t))},numberMetric:function(e,t){return y(e,mo,t,e=>new Ro(e,w,s,t))},getAggregateState:function(){const e=[];return Object.keys(h).length>0&&e.push({name:o,path:l,state:h.state,description:h.description}),m.forEach(t=>{const n=t.getAggregateState();n.length>0&&e.push(...n)}),e}};return s.createSystem(w),w}class jo{root;constructor(e,t){t.init(this),this.root=Do("",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 No{init(e){}createSystem(e){return Promise.resolve()}updateSystem(e,t){return Promise.resolve()}createMetric(e){return Promise.resolve()}updateMetric(e){return Promise.resolve()}}class Fo{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;if(!e||!e.memory)return;const t=e.memory;this.system.stringMetric("memory",JSON.stringify({totalJSHeapSize:t.totalJSHeapSize,usedJSHeapSize:t.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 Lo=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 r=e=>{s(e.root)},s=e=>{o(e),e.metrics.forEach(e=>{a(e)}),e.subSystems.forEach(e=>{s(e)})},o=async e=>{if(void 0===e.parent)return;await n;const r={type:"define",metrics:[{name:So(e.path.join("/")+"/"+e.name+"/State"),type:"object",composite:{Description:{type:"string",description:""},Value:{type:"number",description:""}},description:"System state",context:{}}]};i.sendFireAndForget(r).catch(n=>{t.logger.warn(`Failed to send define for system state metric of ${e.name}: ${JSON.stringify(n)}`)})},a=async e=>{const r=d(e);await n;const s={type:"define",metrics:[Co(r)]};i.sendFireAndForget(s).catch(n=>{t.logger.warn(`Failed to send define for metric ${e.name}: ${JSON.stringify(n)}`)}),void 0!==r.value&&c(r)},c=e=>{if(l()){const n=_o(e),r={type:"publish",values:[{name:So(e.path.join("/")+"/"+e.name),value:n,timestamp:Date.now()}]};return i.sendFireAndForget(r).catch(n=>{t.logger.warn(`Failed to publish metric ${e.name}: ${JSON.stringify(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:s=>{let o;n=new Promise(e=>{o=e}),i=e.domain("metrics"),i.onJoined(e=>{!e&&o&&(o(),o=void 0);const n={type:"define",metrics:[{name:"/State",type:"object",composite:{Description:{type:"string",description:""},Value:{type:"number",description:""}},description:"System state",context:{}}]};i.sendFireAndForget(n).catch(e=>{t.logger.warn(`Failed to send define for root state metric: ${JSON.stringify(e)}`)}),e&&r(s)}),i.join({system:t.system,service:t.service,instance:t.instance})},createSystem:o,updateSystem:async(r,s)=>{await n;const o={type:"publish",values:[{name:So(r.path.join("/")+"/"+r.name+"/State"),value:{Description:s.description,Value:s.state},timestamp:Date.now()}]};i.sendFireAndForget(o).catch(e=>{t.logger.warn(`Failed to send update for system state metric of ${r.name}: ${JSON.stringify(e)}`)});const a=Po(r),c={type:"publish",peer_id:e.peerId,values:[{name:"/State",value:{Description:a.description,Value:a.value},timestamp:Date.now()}]};i.sendFireAndForget(c).catch(e=>{t.logger.warn(`Failed to send update for root state metric of ${r.name}: ${JSON.stringify(e)}`)})},createMetric:a,updateMetric:async e=>{const t=d(e);await n,c(t)}}}(e.connection,e):new No;let n=new jo(e,t).root;e.disableAutoAppSystem||(n=n.subSystem("App"));const i=function(e){const t=e.subSystem("reporting"),n={name:"features"};let i;const r=(e,r,s)=>{if(void 0===e||""===e)throw new Error("name is mandatory");if(void 0===r||""===r)throw new Error("action is mandatory");if(void 0===s||""===s)throw new Error("payload is mandatory");i?i.update({name:e,action:r,payload:s}):i=t.objectMetric(n,{name:e,action:r,payload:s})};return e.featureMetric=r,e}(n);return function(e,t){if("undefined"==typeof window)return;const n=window?.glue42gd?.metrics?.pagePerformanceMetrics;n&&(t=n);t?.enabled&&new Fo(e,t.initialPublishTimeout,t.publishInterval)}(i,e.pagePerformanceMetrics),i};var $o,Wo,Ho="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Uo(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var qo=function(){if(Wo)return $o;function e(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 r=n instanceof Error?n:new Error(n);if(t)t(r);else{var s='[ERROR] callback-registry: User callback for key "'+i+'" failed: '+r.stack;if(e)switch(e.errorHandling){case"log":return console.error(s);case"silent":return;case"throw":throw new Error(s)}console.error(s)}}return{add:function(e,t,r){var s=n[e];return s||(s=[],n[e]=s),s.push(t),r&&setTimeout(function(){r.forEach(function(r){var s;if(null===(s=n[e])||void 0===s?void 0:s.includes(t))try{Array.isArray(r)?t.apply(void 0,r):t.apply(void 0,[r])}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=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];var s=n[e];if(!s||0===s.length)return[];var o=[];return s.forEach(function(n){try{var r=n.apply(void 0,t);o.push(r)}catch(t){o.push(void 0),i(t,e)}}),o},clear:function(){n={}},clearKey:function(e){n[e]&&delete n[e]}}}return Wo=1,e.default=e,$o=e}(),Bo=Uo(qo);class Go{gw;registry=Bo();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 Jo{logger;worker;registry=Bo();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 zo{static isNode(){if(void 0!==zo._isNode)return zo._isNode;if("undefined"!=typeof window)return zo._isNode=!1,!1;try{zo._isNode="[object process]"===Object.prototype.toString.call(global.process)}catch(e){zo._isNode=!1}return zo._isNode}static _isNode;static getMethodName(e){return"string"==typeof e?e:e?.name}}class Vo{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 Ko={};function Zo(e){const t=Ko[e];if(t)return t;const n=[];function i(){return(new Date).getTime()}const r=i();let s,o;function a(e,t){const r=t??i();let s=0;n.length>0&&(s=r-n[n.length-1].time),n.push({name:e,time:r,diff:s})}a("start",r);const c={get startTime(){return r},get endTime(){return s},get period(){return o},stop:function(){return s=i(),a("end",s),o=s-r,o},mark:a,marks:n};return Ko[e]=c,c}const Qo=zo.isNode()?null:window.WebSocket;function Yo(e,t,n,i){const r=!1!==i?.includeStack,s=e instanceof Error?e:e?.error;return s instanceof Error?JSON.stringify({name:s.name,message:s.message,code:s.code,stack:r?s.stack:void 0}):JSON.stringify({type:e?.type,readyState:t?.readyState,url:n,message:"string"==typeof e?.message?e.message:void 0})}class Xo{ws;logger;settings;startupTimer=Zo("connection");_running=!0;_registry=Bo();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 Vo;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){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);try{await this.initiateSocket(),this.startupTimer.mark("socket-initiated"),this.notifyForSocketState()}catch{if(void 0!==t&&t<=0)return void this.notifyForSocketState(`wait for socket on ${this.settings.ws} failed - no more retries left`);void 0!==t&&this.logger.debug(`will retry ${t-1} more times (every ${e} ms)`),setTimeout(()=>{const n=void 0===t?void 0:t-1;this.openSocket(e,n)},e)}}initiateSocket(){const e=new Vo;this.logger.debug(`initiating ws to ${this.settings.ws}...`),this.ws=new Qo(this.settings.ws??"");let t=!1;return this.ws.onerror=n=>{const i=Yo(n,this.ws,this.settings.ws);this.logger.info(`ws error - ${i}`),e.reject("error"),t&&(t=!1,this.notifyForSocketState("error"));const r=Yo(n,this.ws,this.settings.ws,{includeStack:!1});this.notifyStatusChanged(!1,r)},this.ws.onclose=n=>{var i;this.logger.info("ws closed - "+(i=n,`code: ${i?.code} reason: ${i?.reason||"(none)"} wasClean: ${i?.wasClean}`)),e.reject("closed"),t&&(t=!1,this.notifyForSocketState("closed")),this.notifyStatusChanged(!1)},this.ws.onopen=()=>{this.startupTimer.mark("ws-opened"),this.logger.info(`ws opened ${this.settings.identity?.application}`),e.resolve(),t=!0,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 ea{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 ta=(e=21)=>{let t="",n=0|e;for(;n--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return t};const na=(e,t,n)=>new Promise((i,r)=>{const s=setTimeout(()=>{r(n||`Promise timeout hit: ${t}`)},t);new Promise(e).then(e=>{clearTimeout(s),i(e)}).catch(e=>{clearTimeout(s),r(e)})});class ia{settings;logger;identity;isPreferredActivated;_connectionProtocolVersion;_communicationId;publicWindowId;selfAssignedWindowId;iAmConnected=!1;parentReady=!1;rejected=!1;parentPingResolve;parentPingInterval;connectionResolve;extConnectionResolve;extConnectionReject;connectionReject;port;myClientId;extContentAvailable=!1;extContentConnecting=!1;extContentConnected=!1;parentWindowId;parentInExtMode=!1;webNamespace="g42_core_web";parent;parentType;parentPingTimeout=5e3;connectionRequestTimeout=7e3;defaultTargetString="*";registry=Bo();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:()=>{}},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},window.origin);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(){this.logger.debug(`closing connection - clientId: ${this.myClientId}, windowId: ${this.identity?.windowId||"unknown"}, client connected: ${this.iAmConnected}`);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 na((t,n)=>{this.connectionResolve=t,this.connectionReject=n,this.myClientId=this.myClientId??ta(10);const i=this.getMyWindowId()||ta(10),r={glue42core:{type:this.messages.connectionRequest.name,clientId:this.myClientId,clientType:"child",bridgeInstanceId:i,selfAssignedWindowId:this.selfAssignedWindowId}};if(this.logger.debug(`sending connection request - clientId: ${this.myClientId}`),this.extContentConnecting)return r.glue42core.clientType="child",r.glue42core.bridgeInstanceId=this.myClientId,r.glue42core.parentWindowId=this.parentWindowId,window.postMessage(r,window.origin);if(!e)throw new Error("Cannot send a connection request, because no glue target was specified!");e.postMessage(r,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"):(this.logger.debug("setting up window message listener"),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"):(this.logger.debug("setting up unload event listeners"),window.addEventListener("beforeunload",()=>{this._connectionProtocolVersion||this.signalClientDisappearing()}),window.addEventListener("pagehide",()=>{this._connectionProtocolVersion&&this.signalClientDisappearing()}))}signalClientDisappearing(){if(this.extContentConnected)return;this.logger.debug(`signaling client disappearing for clientId: ${this.myClientId}`);const e={glue42core:{type:this.messages.clientUnload.name,data:{clientId:this.myClientId,ownWindowId:this.identity?.windowId}}};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.logger?.debug(`ignoring a connection accepted signal, because it is not targeted at me. My id: ${this.myClientId}, the id in the message: ${t.clientId}`):this.handleAcceptanceOfMyRequest(t)}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._connectionProtocolVersion=e.connectionProtocolVersion,this.publicWindowId=this.getMyWindowId(),this.identity&&(this.identity.windowId=this.publicWindowId,this.identity.instance=this.identity.instance?this.identity.instance:this.publicWindowId||ta(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}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(){this.extContentConnecting&&this.logger.debug("This connection request event is targeted at the extension content")}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.logger.debug("setting up platform unload listener"),this.onMessage(e=>{"platformUnload"===e.type&&(this.logger.debug("detected a web platform unload"),this.parentReady=!1,this.notifyStatusChanged(!1,"Gateway unloaded"))})}handleManualUnload(){this.logger.debug("handling manual unload");const e={glue42core:{type:this.messages.clientUnload.name,data:{clientId:this.myClientId,ownWindowId:this.identity?.windowId}}};if(this.extContentConnected)return window.postMessage({glue42ExtOut:e},window.origin);this.port?.postMessage(e)}handlePlatformPing(){}notifyStatusChanged(e,t){this.logger.debug(`status changed - connected: ${e}, reason: ${t||"none"}`),this.iAmConnected=e,this.registry.execute("onConnectedChanged",e,t)}checkMessageTypeValid(e){return"string"==typeof e&&!!this.messages[e]}requestConnectionPermissionFromExt(){return this.waitForContentScript().then(()=>na((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"}},window.origin)},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():na(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=na(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(){if("workspace"===this.parentType)return window.name.substring(0,window.name.indexOf("#wsp"));if(window!==window.top){const e=window.name.indexOf("#ifr");return-1!==e?window.name.substring(0,e):void 0}return window.name?.includes("g42")?window.name:(this.selfAssignedWindowId=this.selfAssignedWindowId||`g42-${ta(10)}`,this.selfAssignedWindowId)}}class ra{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 sa(e){if(e instanceof Error)return e;if("string"==typeof e)return new Error(e);const t=e,n="string"==typeof t?.message?t.message:void 0,i="string"==typeof t?.reason?t.reason:void 0;return void 0!==n&&n.length>0?new Error(n):void 0!==i&&i.length>0?new Error(i):""===n||""===i?new Error(""):new Error(aa(e))}function oa(e){try{if(e instanceof Error){if("string"==typeof e.stack)return e.stack;if("string"==typeof e.message){return`${"string"==typeof e.name&&e.name.length>0?e.name:"Error"}: ${e.message}`}}if("string"==typeof e)return e}catch{}return aa(e)}function aa(e){try{const t=new WeakSet,n=JSON.stringify(e,(e,n)=>{if("bigint"==typeof n)return`${n.toString()}n`;if("function"==typeof n)return"[Function]";if("symbol"==typeof n)return n.toString();if("object"==typeof n&&null!==n){if(t.has(n))return"[Circular]";t.add(n)}return n});if(void 0!==n)return n}catch{}if(null!==e&&"object"==typeof e){const t=e.constructor?.name??"Object";let n=[];try{n=Object.keys(e)}catch{}return n.length>0?`[${t} keys=${n.join(",")}]`:`[${t}]`}return String(e)}function ca(e,t,n,i,r){null==e&&(e="global"),i=i??["success"],r=r??["error"];let s,o="global"===e,a=!1,c=!1;const d=Bo();t.disconnected(function(){n.debug("connection is down"),c=!1,o=!1,a=!0,Object.keys(l).forEach(e=>{const t=l[e];t&&(n.trace(`failing pending request ${e} due to connection lost`),t.error({err:"Connection lost - gateway connection was disconnected"}))}),d.execute("onLeft",{disconnected:!0})}),t.loggedIn(async function(){if(c=!0,a){n.debug("connection is now up - trying to reconnect...");try{await h(s)}catch{n.trace("failed to reconnect")}}}),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))}),r&&r.forEach(e=>{t.on(e,e=>p(e))});const l={};function h(t){return s=t,new Promise((i,r)=>{if(o)return void i({});let s;if("global"===e)s=c?Promise.resolve({}):Promise.reject("not connected to gateway");else{n.debug(`joining domain ${e}`);s=b({type:"join",destination:e,domain:"global",options:t})}s.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)),r(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 f(){return ta(10)}let m=[];function b(i,r,s){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 Vo;if(m.push({msg:i,tag:r,options:s,pw:e}),1===m.length){const e=u(()=>{n.info(`joined - will now send queued messages (${m.length} -> [${m.map(e=>e.msg.type)}])`),m.forEach(e=>{b(e.msg,e.tag,e.options).then(t=>e.pw.resolve(t)).catch(t=>e.pw.reject(t))}),m=[],e()})}return e.promise}s=s??{},i.request_id=i.request_id??f(),i.domain=i.domain??e,s.skipPeerId||(i.peer_id=t.peerId);const a=i.request_id;return new Promise((e,n)=>{l[a]={success:t=>{delete l[a],t._tag=r,e(t)},error:e=>{console.warn(`Gateway error - ${JSON.stringify(e)}`),delete l[a],e._tag=r,n(e)}},t.send(i,s).catch(e=>{l[a]?.error({err:e})})})}return{join:h,leave:function(){return"global"===e?Promise.resolve():o?(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")})):(a=!1,Promise.resolve())},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:f(),n.domain=n.domain??e,n.peer_id=t.peerId,t.send(n)},on:(i,r)=>{t.on(i,t=>{if(t.domain===e)try{r(t)}catch(e){n.error(`Callback failed: ${oa(e)} \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 da{settings;logger;protocolVersion=3;peerId;token;info;resolvedIdentity;availableDomains;gatewayToken;replayer;messageHandlers={};ids=1;registry=Bo();_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 ra;_isLoggedIn=!1;shouldTryLogin=!0;pingTimer;reconnectTimeout;sessions=[];globalDomain;initialLogin=!0;initialLoginAttempts=3;remainingReconnectAttempts;loginConfig;loginRetryInProgress=!1;reconnectInProgress=!1;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 Go(e.inproc,t.subLogger("inMemory"));else if(e.sharedWorker)this.transport=new Jo(e.sharedWorker,t.subLogger("shared-worker"));else if(e.webPlatform)this.transport=new ia(e.webPlatform,t.subLogger("web-platform"),e.identity);else{if(void 0===e.ws)throw new Error("No connection information specified");this.transport=new Xo(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.logger.debug(`Login initiated - reconnect: ${t}, transport: ${this.transport.name()}`),this._defaultAuth||(this._defaultAuth=e),this._swapTransport){this.logger.trace("Detected a transport swap, swapping transports");e=this.transportSwap()??e}try{await this.transport.open(),this.logger.debug(`Transport: ${this.transport.name()} opened, logging in`),Zo("connection").mark("transport-opened");const n=await this.loginCore(e,t);return this.logger.debug(`Logged in with identity: ${JSON.stringify(n)}`),Zo("connection").mark("protocol-logged-in"),n}catch(e){throw this._switchInProgress&&(this.logger.debug("An error while logging in after a transport swap, preparing a default swap."),this.prepareDefaultSwap()),sa(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=ca(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"))}async reconnect(){if(!this.loginConfig)throw new Error("Cannot reconnect - no previous login configuration");if(this.reconnectInProgress)this.logger.debug("reconnect() already in progress, ignoring");else{this.reconnectInProgress=!0;try{for(this.shouldTryLogin=!1,this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0);this.loginRetryInProgress;)await new Promise(e=>setTimeout(e,50));this._isLoggedIn&&(this.setLoggedIn(!1),this.registry.execute("disconnected")),this.shouldTryLogin=!0,await this.login(this.loginConfig,!0)}finally{this.reconnectInProgress=!1}}}setLoggedIn(e){this._isLoggedIn=e,this._isLoggedIn&&(this.initialLogin=!1,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 ${oa(e)}`,e)}catch(t){console.log("Message handler failed",e)}}})}handleConnectionChanged(e){this._connected!==e?(this.logger.info("connection state changed to "+(e?"connected":"disconnected")),this._connected=e,e?(this.settings?.replaySpecs?.length&&(this.replayer=new ea(this.settings.replaySpecs),this.replayer.init(this)),this.registry.execute("connected")):(this.setLoggedIn(!1),this.shouldTryLogin&&(this.remainingReconnectAttempts=this.settings.reconnectAttempts,this.attemptLoginWithRetry()),this.registry.execute("disconnected"))):this.logger.trace("connection state unchanged, skipping")}async attemptLoginWithRetry(){if(!this.loginConfig)throw new Error("no login info");if(this.shouldTryLogin)if(this.loginRetryInProgress)this.logger.debug("login attempt already in progress, ignoring request...");else if(this._isLoggedIn)this.logger.debug("already logged in, ignoring request...");else{if(this.initialLogin){if(this.logger.debug(`initial login attempt failed, ${this.initialLoginAttempts} attempts remaining...`),this.initialLoginAttempts<=0)return void this.logger.info("maximum initial login attempts reached, will not try to login again");this.initialLoginAttempts--}else if(void 0!==this.remainingReconnectAttempts){if(this.remainingReconnectAttempts<=0)return void this.logger.info("maximum reconnect attempts reached, will not try to login again");this.logger.debug(`reconnect attempt, ${this.remainingReconnectAttempts} attempts remaining...`),this.remainingReconnectAttempts--}try{this.logger.debug(`will try a new login... ${this.loginRetryInProgress}`),this.loginRetryInProgress=!0,await this.login(this.loginConfig,!0)}catch(e){this.logger.error(`error trying to login: ${e?.message}`,e),this.shouldTryLogin&&(this.reconnectTimeout=setTimeout(this.attemptLoginWithRetry.bind(this),this.settings.reconnectInterval??1e3))}finally{this.loginRetryInProgress=!1}}else this.logger.debug("should not try to login, ignoring reconnect attempt...")}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 na(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 Xo(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.loginConfig=e,this.loginConfig||(this.loginConfig={username:"",password:""});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||(this.globalDomain=ca("global",this,this.logger.subLogger("global-domain"),["welcome","token","authentication-request"]));const r={skipPeerId:!0};this.initialLogin&&(r.retryInterval=this.settings.reconnectInterval,r.maxRetries=this.settings.reconnectAttempts);try{const t=await this.tryAuthenticate(this.globalDomain,i,r,e);return 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 r;for(;;){const s=await e.send(t,void 0,n);if("authentication-request"!==s.type){if("welcome"===s.type){r=s;break}throw"error"===s.type?new Error("Authentication failed: "+s.reason):new Error("Unexpected message type during authentication: "+s.type)}{const e=Buffer.from(s.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 r}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("core logging out..."),this.shouldTryLogin=!1,this.setLoggedIn(!1),this.pingTimer&&clearTimeout(this.pingTimer),this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0);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 la=["trace","debug","info","warn","error","off"];class ha{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.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 ha(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 la.indexOf(e)>=la.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 r=ha.Interop;if(r)try{if(r.methods({name:ha.InteropMethodName}).length>0){const s={msg:t,logger:i,level:e};n&&n instanceof Error&&(s.error={message:n.message,stack:n.stack??""}),r.invoke(ha.InteropMethodName,s).catch(e=>{this.logFn.error(`Unable to send log message to the platform: ${sa(e).message}`,e)})}}catch{}}if(this.canPublish(e)){let r="";if(this.includeTimeAndLevel){const t=new Date;r=`[${`${t.getHours()}:${t.getMinutes()}:${t.getSeconds()}:${t.getMilliseconds()}`}] [${e}] `}const s=`${r}${i}: ${t}`;switch(e){case"trace":this.logFn.debug(s);break;case"debug":this.logFn.debug?this.logFn.debug(s):this.logFn.log(s);break;case"info":this.logFn.info(s);break;case"warn":this.logFn.warn(s);break;case"error":n?this.logFn.error(s,n):this.logFn.error(s)}}}}const ua="create-context",pa="created",ga="destroyed",fa="context-created",ma="context-added",ba="subscribe-context",ya="subscribed-context",wa="unsubscribe-context",va="destroy-context",Ca="context-destroyed",Ia="update-context",Sa="context-updated",_a="joined",xa={get name(){return"context"},get types(){return[ua,pa,ga,fa,ma,ba,ya,wa,va,Ca,Ia,Sa,_a]}};var Ta,Pa,ka="6.11.0";
|
|
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";function e(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var t=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===n}(e)}(e)};var n="function"==typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function i(e,t){return!1!==t.clone&&t.isMergeableObject(e)?c((n=e,Array.isArray(n)?[]:{}),e,t):e;var n}function r(e,t,n){return e.concat(t).map(function(e){return i(e,n)})}function s(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 o(e,t){try{return t in e}catch(e){return!1}}function a(e,t,n){var r={};return n.isMergeableObject(e)&&s(e).forEach(function(t){r[t]=i(e[t],n)}),s(t).forEach(function(s){(function(e,t){return o(e,t)&&!(Object.hasOwnProperty.call(e,t)&&Object.propertyIsEnumerable.call(e,t))})(e,s)||(o(e,s)&&n.isMergeableObject(t[s])?r[s]=function(e,t){if(!t.customMerge)return c;var n=t.customMerge(e);return"function"==typeof n?n:c}(s,n)(e[s],t[s],n):r[s]=i(t[s],n))}),r}function c(e,n,s){(s=s||{}).arrayMerge=s.arrayMerge||r,s.isMergeableObject=s.isMergeableObject||t,s.cloneUnlessOtherwiseSpecified=i;var o=Array.isArray(n);return o===Array.isArray(e)?o?s.arrayMerge(e,n,s):a(e,n,s):i(n,s)}c.all=function(e,t){if(!Array.isArray(e))throw new Error("first argument should be an array");return e.reduce(function(e,n){return c(e,n,t)},{})};var d=e(c),l=function(e){return{ok:!0,result:e}},h=function(e){return{ok:!1,error:e}},u=function(e,t,n){return!1===t.ok?t:!1===n.ok?n:l(e(t.result,n.result))},p=function(e,t){return!0===t.ok?t:h(e(t.error))},g=function(){return g=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},g.apply(this,arguments)};function f(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(!f(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(!f(e[i[n]],t[i[n]]))return!1}return!0}}var m=function(e){return Array.isArray(e)},b=function(e){return"object"==typeof e&&null!==e&&!m(e)},y=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)},w=function(e){return e.map(function(e){return"string"==typeof e?"."+e:"["+e+"]"}).join("")},v=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 r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(t,["at"]);return g({at:e+(n||"")},i)},C=function(){function e(t){var n=this;this.decode=t,this.run=function(e){return p(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?l(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?l(e):h({message:y("a string",e)})})},e.number=function(){return new e(function(e){return"number"==typeof e?l(e):h({message:y("a number",e)})})},e.boolean=function(){return new e(function(e){return"boolean"==typeof e?l(e):h({message:y("a boolean",e)})})},e.constant=function(t){return new e(function(e){return f(e,t)?l(t):h({message:"expected "+JSON.stringify(t)+", got "+JSON.stringify(e)})})},e.object=function(t){return new e(function(e){if(b(e)&&t){var n={};for(var i in t)if(t.hasOwnProperty(i)){var r=t[i].decode(e[i]);if(!0!==r.ok)return void 0===e[i]?h({message:"the key '"+i+"' is required but was not present"}):h(v("."+i,r.error));void 0!==r.result&&(n[i]=r.result)}return l(n)}return b(e)?l(e):h({message:y("an object",e)})})},e.array=function(t){return new e(function(e){if(m(e)&&t){return e.reduce(function(e,n,i){return u(function(e,t){return e.concat([t])},e,function(e,n){return p(function(e){return v("["+n+"]",e)},t.decode(e))}(n,i))},l([]))}return m(e)?l(e):h({message:y("an array",e)})})},e.tuple=function(t){return new e(function(e){if(m(e)){if(e.length!==t.length)return h({message:"expected a tuple of length "+t.length+", got one of length "+e.length});for(var n=[],i=0;i<t.length;i++){var r=t[i].decode(e[i]);if(!r.ok)return h(v("["+i+"]",r.error));n[i]=r.result}return l(n)}return h({message:y("a tuple of length "+t.length,e)})})},e.union=function(t,n){for(var i=[],r=2;r<arguments.length;r++)i[r-2]=arguments[r];return e.oneOf.apply(e,[t,n].concat(i))},e.intersection=function(t,n){for(var i=[],r=2;r<arguments.length;r++)i[r-2]=arguments[r];return new e(function(e){return[t,n].concat(i).reduce(function(t,n){return u(Object.assign,t,n.decode(e))},l({}))})},e.anyJson=function(){return new e(function(e){return l(e)})},e.unknownJson=function(){return new e(function(e){return l(e)})},e.dict=function(t){return new e(function(e){if(b(e)){var n={};for(var i in e)if(e.hasOwnProperty(i)){var r=t.decode(e[i]);if(!0!==r.ok)return h(v("."+i,r.error));n[i]=r.result}return l(n)}return h({message:y("an object",e)})})},e.optional=function(t){return new e(function(e){return null==e?l(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 r=t[i].decode(e);if(!0===r.ok)return r;n[i]=r.error}var s=n.map(function(e){return"at error"+(e.at||"")+": "+e.message}).join('", "');return h({message:'expected a value matching one of the decoders, got the errors ["'+s+'"]'})})},e.withDefault=function(t,n){return new e(function(e){return l(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,r=0;r<t.length;r++){if(void 0===i)return h({at:w(t.slice(0,r+1)),message:"path does not exist"});if("string"==typeof t[r]&&!b(i))return h({at:w(t.slice(0,r+1)),message:y("an object",i)});if("number"==typeof t[r]&&!m(i))return h({at:w(t.slice(0,r+1)),message:y("an array",i)});i=i[t[r]]}return p(function(e){return void 0===i?{at:w(t),message:"path does not exist"}:v(w(t),e)},n.decode(i))})},e.succeed=function(t){return new e(function(e){return l(t)})},e.fail=function(t){return new e(function(e){return h({message:t})})},e.lazy=function(t){return new e(function(e){return t().decode(e)})},e}(),I=C.string,S=C.number,_=C.boolean,x=C.anyJson;C.unknownJson;var T=C.constant,P=C.object,k=C.array;C.tuple,C.dict;var O=C.optional,R=C.oneOf,A=C.union,M=C.intersection;C.withDefault,C.valueAt,C.succeed,C.fail;var E=C.lazy;const D={gateway:{webPlatform:{}},libraries:[],exposeAPI:!0},j={awaitFactory:!0,enable:!1,timeout:5e3,restoreLastKnownPosition:!0},N={alerts:{enabled:!1},dialogs:{enabled:!1},awaitFactory:!0,timeout:5e3},F={enable:!1,timeout:5e3,awaitFactory:!0},L={name:"platformUnload"},$={name:"transportSwitchRequest"},W={name:"transportSwitchResponse"},H={name:"getCurrentTransport"},U={name:"getCurrentTransportResponse"},q={name:"checkPreferredLogic"},B={name:"checkPreferredConnection"},G={name:"checkPreferredLogicResponse"},J={name:"checkPreferredConnectionResponse"},z="web-platform",V="latest_fdc3_type",K=new MessageChannel,Z=2147483647,Q={configurable:!1,enumerable:!0,writable:!1},Y=e=>"string"==typeof e?e:e?.message?"string"==typeof e.message?e.message:JSON.stringify(e.message):JSON.stringify(e),X=(e,t)=>{try{return e.runWithException(t)}catch(e){return re.raiseError(e,!0)}},ee=e=>Object.keys(e).filter(t=>e[t].execute),te=(e,t)=>({isSupported:e.some(e=>e.toLowerCase()===t.toLowerCase())}),ne=e=>Math.min(e,Z),ie=()=>{let e,t;return{promise:new Promise((n,i)=>{e=n,t=i}),resolve:e,reject:t}};const re=new class{raiseError(e,t){const n=Y(e);if(K.port1.postMessage(n),t)throw e;throw new Error(n)}},se=["name","title","version","customProperties","icon","caption","type"],oe=["appId","name","type","details","version","title","tooltip","lang","description","categories","icons","screenshots","contactEmail","moreInfo","publisher","customConfig","hostManifests","interop","localizedVersions"];var ae=function(e){return{ok:!0,result:e}},ce=function(e){return{ok:!1,error:e}},de=function(e,t,n){return!1===t.ok?t:!1===n.ok?n:ae(e(t.result,n.result))},le=function(e,t){return!0===t.ok?t:ce(e(t.error))},he=function(){return he=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},he.apply(this,arguments)};function ue(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(!ue(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(!ue(e[i[n]],t[i[n]]))return!1}return!0}}var pe=function(e){return Array.isArray(e)},ge=function(e){return"object"==typeof e&&null!==e&&!pe(e)},fe=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)},me=function(e){return e.map(function(e){return"string"==typeof e?"."+e:"["+e+"]"}).join("")},be=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 r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(t,["at"]);return he({at:e+(n||"")},i)},ye=function(){function e(t){var n=this;this.decode=t,this.run=function(e){return le(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?ae(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?ae(e):ce({message:fe("a string",e)})})},e.number=function(){return new e(function(e){return"number"==typeof e?ae(e):ce({message:fe("a number",e)})})},e.boolean=function(){return new e(function(e){return"boolean"==typeof e?ae(e):ce({message:fe("a boolean",e)})})},e.constant=function(t){return new e(function(e){return ue(e,t)?ae(t):ce({message:"expected "+JSON.stringify(t)+", got "+JSON.stringify(e)})})},e.object=function(t){return new e(function(e){if(ge(e)&&t){var n={};for(var i in t)if(t.hasOwnProperty(i)){var r=t[i].decode(e[i]);if(!0!==r.ok)return void 0===e[i]?ce({message:"the key '"+i+"' is required but was not present"}):ce(be("."+i,r.error));void 0!==r.result&&(n[i]=r.result)}return ae(n)}return ge(e)?ae(e):ce({message:fe("an object",e)})})},e.array=function(t){return new e(function(e){if(pe(e)&&t){return e.reduce(function(e,n,i){return de(function(e,t){return e.concat([t])},e,function(e,n){return le(function(e){return be("["+n+"]",e)},t.decode(e))}(n,i))},ae([]))}return pe(e)?ae(e):ce({message:fe("an array",e)})})},e.tuple=function(t){return new e(function(e){if(pe(e)){if(e.length!==t.length)return ce({message:"expected a tuple of length "+t.length+", got one of length "+e.length});for(var n=[],i=0;i<t.length;i++){var r=t[i].decode(e[i]);if(!r.ok)return ce(be("["+i+"]",r.error));n[i]=r.result}return ae(n)}return ce({message:fe("a tuple of length "+t.length,e)})})},e.union=function(t,n){for(var i=[],r=2;r<arguments.length;r++)i[r-2]=arguments[r];return e.oneOf.apply(e,[t,n].concat(i))},e.intersection=function(t,n){for(var i=[],r=2;r<arguments.length;r++)i[r-2]=arguments[r];return new e(function(e){return[t,n].concat(i).reduce(function(t,n){return de(Object.assign,t,n.decode(e))},ae({}))})},e.anyJson=function(){return new e(function(e){return ae(e)})},e.unknownJson=function(){return new e(function(e){return ae(e)})},e.dict=function(t){return new e(function(e){if(ge(e)){var n={};for(var i in e)if(e.hasOwnProperty(i)){var r=t.decode(e[i]);if(!0!==r.ok)return ce(be("."+i,r.error));n[i]=r.result}return ae(n)}return ce({message:fe("an object",e)})})},e.optional=function(t){return new e(function(e){return null==e?ae(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 r=t[i].decode(e);if(!0===r.ok)return r;n[i]=r.error}var s=n.map(function(e){return"at error"+(e.at||"")+": "+e.message}).join('", "');return ce({message:'expected a value matching one of the decoders, got the errors ["'+s+'"]'})})},e.withDefault=function(t,n){return new e(function(e){return ae(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,r=0;r<t.length;r++){if(void 0===i)return ce({at:me(t.slice(0,r+1)),message:"path does not exist"});if("string"==typeof t[r]&&!ge(i))return ce({at:me(t.slice(0,r+1)),message:fe("an object",i)});if("number"==typeof t[r]&&!pe(i))return ce({at:me(t.slice(0,r+1)),message:fe("an array",i)});i=i[t[r]]}return le(function(e){return void 0===i?{at:me(t),message:"path does not exist"}:be(me(t),e)},n.decode(i))})},e.succeed=function(t){return new e(function(e){return ae(t)})},e.fail=function(t){return new e(function(e){return ce({message:t})})},e.lazy=function(t){return new e(function(e){return t().decode(e)})},e}(),we=ye.string,ve=ye.number,Ce=ye.boolean,Ie=ye.anyJson;ye.unknownJson;var Se=ye.constant,_e=ye.object,xe=ye.array;ye.tuple;var Te=ye.dict,Pe=ye.optional,ke=ye.oneOf;ye.union,ye.intersection,ye.withDefault,ye.valueAt,ye.succeed;var Oe=ye.fail;ye.lazy;const Re=we().where(e=>e.length>0,"Expected a non-empty string"),Ae=ve().where(e=>e>=0,"Expected a non-negative number"),Me=Ie().andThen(e=>e instanceof RegExp?Ie():Oe("expected a regex, got a "+typeof e)),Ee=Re.andThen(e=>{try{const{protocol:t}=new URL(e),n=["data:","javascript:","vbscript:"];return n.includes(t)?Oe(`Expected a URL with a safe protocol, got: ${t} (disallowed protocols: ${n.join(", ")})`):Re}catch{return Oe("Expected a valid URL")}}),De=_e({name:Re,displayName:Pe(we()),contexts:Pe(xe(we())),customConfig:Pe(_e())}),je=ke(Se("web"),Se("native"),Se("citrix"),Se("onlineNative"),Se("other")),Ne=_e({url:Ee}),Fe=_e({src:Re,size:Pe(Re),type:Pe(Re)}),Le=_e({src:Re,size:Pe(Re),type:Pe(Re),label:Pe(Re)}),$e=_e({contexts:xe(Re),displayName:Pe(Re),resultType:Pe(Re),customConfig:Pe(Ie())}),We=_e({listensFor:Pe(Te($e)),raises:Pe(Te(xe(Re)))}),He=_e({broadcasts:Pe(xe(Re)),listensFor:Pe(xe(Re))}),Ue=_e({name:Pe(Re),id:Pe(Re),description:Pe(Re),broadcasts:Pe(xe(Re)),listensFor:Pe(xe(Re))}).where(e=>Boolean(e.name||e.id),"Expected at least a name or an id property to be present in the app channel definition"),qe=_e({intents:Pe(We),userChannels:Pe(He),appChannels:Pe(xe(Ue))}),Be=_e({url:Pe(Ee),top:Pe(ve()),left:Pe(ve()),width:Pe(Ae),height:Pe(Ae)}),Ge=_e({name:Pe(Re),type:Pe(Re.where(e=>"window"===e,"Expected a value of window")),title:Pe(Re),version:Pe(Re),customProperties:Pe(Ie()),icon:Pe(we()),caption:Pe(we()),details:Pe(Be),intents:Pe(xe(De)),hidden:Pe(Ce())}),Je=_e({name:Re,appId:Re,title:Pe(Re),version:Pe(Re),manifest:Re,manifestType:Re,tooltip:Pe(Re),description:Pe(Re),contactEmail:Pe(Re),supportEmail:Pe(Re),publisher:Pe(Re),images:Pe(xe(_e({url:Pe(Re)}))),icons:Pe(xe(_e({icon:Pe(Re)}))),customConfig:Ie(),intents:Pe(xe(De))}),ze=_e({appId:Pe(Re),name:Pe(Re),details:Pe(Ne),version:Pe(Re),title:Pe(Re),tooltip:Pe(Re),lang:Pe(Re),description:Pe(Re),categories:Pe(xe(Re)),icons:Pe(xe(Fe)),screenshots:Pe(xe(Le)),contactEmail:Pe(Re),supportEmail:Pe(Re),moreInfo:Pe(Re),publisher:Pe(Re),customConfig:Pe(xe(Ie())),hostManifests:Pe(Ie()),interop:Pe(qe)}),Ve=_e({appId:Re,name:Pe(Re),type:je,details:Ne,version:Pe(Re),title:Pe(Re),tooltip:Pe(Re),lang:Pe(Re),description:Pe(Re),categories:Pe(xe(Re)),icons:Pe(xe(Fe)),screenshots:Pe(xe(Le)),contactEmail:Pe(Re),supportEmail:Pe(Re),moreInfo:Pe(Re),publisher:Pe(Re),customConfig:Pe(xe(Ie())),hostManifests:Pe(Ie()),interop:Pe(qe),localizedVersions:Pe(Te(ze))}),Ke=ke(Je,Ve),Ze=e=>`${e.kind} at ${e.at}: ${JSON.stringify(e.input)}. Reason - ${e.message}`;class Qe{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:Ze(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: ${Ze(i.error)}`);const r=this.getUserPropertiesFromDefinition(e,n),s={url:this.getUrl(e,n)},o={name:e.appId,type:"window",createOptions:s,userProperties:{...r,intents:"1.2"===n?r.intents:this.getIntentsFromV2AppDefinition(e),details:s},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=Ge.run(a);if(!c.ok)throw new Error(`Invalid FDC3 ${n} definition. Error: ${Ze(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: ${Ze(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 r=e,s={name:r.appId,type:this.fdc3ToDesktopDefinitionType[r.type],details:r.details,version:r.version,title:r.title,tooltip:r.tooltip,caption:r.description,icon:this.getIconFromDefinition(r,"2.0"),intents:this.getIntentsFromV2AppDefinition(r),fdc3:{...r,definitionVersion:"2.0"}},o=e.hostManifests?.ioConnect||e.hostManifests?.Glue42;if(!o)return s;if("object"!=typeof o||Array.isArray(o))throw new Error(`Invalid '${e.hostManifests.ioConnect?"hostManifests.ioConnect":"hostManifests['Glue42']"}' key`);return this.mergeDesktopConfigWithGlueManifest(s,o)}getUserPropertiesFromDefinition(e,t){return"1.2"===t?Object.fromEntries(Object.entries(e).filter(([e])=>!se.includes(e))):Object.fromEntries(Object.entries(e).filter(([e])=>!se.includes(e)&&!oe.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.customProperties&&(n.userProperties={...e.userProperties,...t.customProperties}),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 Ye={common:{nonEmptyStringDecoder:Re,nonNegativeNumberDecoder:Ae,regexDecoder:Me,urlDecoder:Ee},fdc3:{allDefinitionsDecoder:Ke,v1DefinitionDecoder:Je,v2DefinitionDecoder:Ve}};var Xe;!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"}(Xe||(Xe={}));const et=new class{_fdc3;_decoders=Ye;_errors={intents:Xe};get fdc3(){return this._fdc3||(this._fdc3=(new Qe).toApi()),this._fdc3}get decoders(){return this._decoders}get errors(){return this._errors}};et.fdc3;const tt=et.decoders;et.errors;const nt=tt.common.nonEmptyStringDecoder,it=tt.common.nonNegativeNumberDecoder,rt=O(nt),st=tt.common.urlDecoder,ot=R(T("system"),T("windows"),T("appManager"),T("layouts"),T("intents"),T("notifications"),T("channels"),T("extension"),T("themes"),T("prefs"),T("ui")),at=R(T("openWindow"),T("windowHello"),T("windowAdded"),T("windowRemoved"),T("getBounds"),T("getFrameBounds"),T("getUrl"),T("moveResize"),T("focus"),T("close"),T("getTitle"),T("setTitle"),T("focusChange"),T("getChannel"),T("notifyChannelsChanged"),T("setZoomFactor"),T("zoomFactorChange"),T("refresh"),T("operationCheck")),ct=R(T("appHello"),T("appDirectoryStateChange"),T("instanceStarted"),T("instanceStopped"),T("applicationStart"),T("instanceStop"),T("clear"),T("operationCheck")),dt=R(T("layoutAdded"),T("layoutChanged"),T("layoutRemoved"),T("layoutRenamed"),T("get"),T("getAll"),T("getLayoutContents"),T("export"),T("import"),T("remove"),T("rename"),T("clientSaveRequest"),T("getGlobalPermissionState"),T("checkGlobalActivated"),T("requestGlobalPermission"),T("getDefaultGlobal"),T("setDefaultGlobal"),T("clearDefaultGlobal"),T("updateMetadata"),T("operationCheck"),T("getCurrent"),T("defaultLayoutChanged"),T("layoutRestored")),lt=R(T("raiseNotification"),T("requestPermission"),T("notificationShow"),T("notificationClick"),T("getPermission"),T("list"),T("notificationRaised"),T("notificationClosed"),T("click"),T("clear"),T("clearAll"),T("configure"),T("getConfiguration"),T("configurationChanged"),T("setState"),T("clearOld"),T("activeCountChange"),T("stateChange"),T("operationCheck"),T("getActiveCount")),ht=R(T("getEnvironment"),T("getBase"),T("platformShutdown"),T("isFdc3DataWrappingSupported"),T("isChannelsMetadataSupported"),T("clientError"),T("systemHello"),T("operationCheck")),ut=R(T("top"),T("left"),T("right"),T("bottom")),pt=P({top:S(),left:S(),width:it,height:it}),gt=O(P({top:O(S()),left:O(S()),width:O(it),height:O(it),context:O(x()),relativeTo:O(nt),relativeDirection:O(ut),windowId:O(nt),layoutComponentId:O(nt)})),ft=P({name:nt,url:st,options:gt}),mt=P({windowId:O(nt)}),bt=P({windowId:nt,name:nt}),yt=P({windowId:nt}),wt=P({windows:k(bt),isWorkspaceFrame:_()}),vt=P({windowId:nt,title:I()}),Ct=P({windowId:nt,hasFocus:_()}),It=P({windowId:nt,top:O(S()),left:O(S()),width:O(it),height:O(it),relative:O(_())}),St=P({windowId:nt,bounds:P({top:S(),left:S(),width:it,height:it})}),_t=P({bounds:P({top:S(),left:S(),width:it,height:it})}),xt=P({windowId:nt,url:st}),Tt=P({windowId:nt,factorIndex:it}),Pt=x(),kt=P({top:O(S()),left:O(S()),width:O(it),height:O(it)}),Ot=P({id:nt,applicationName:nt}),Rt=P({flags:I()}),At=P({flags:I()}),Mt=P({flags:I()}),Et=P({windowId:nt,channelsNames:k(nt)}),Dt=P({enabled:_()}),jt=P({url:st,top:O(S()),left:O(S()),width:O(it),height:O(it),workspacesSandbox:O(Mt),channelSelector:O(Dt),iframePermissionsPolicy:O(Rt),iframeSandbox:O(At)}),Nt=P({name:nt,displayName:O(I()),contexts:O(k(I())),customConfig:O(P()),resultType:O(I())}),Ft=P({name:nt,type:nt.where(e=>"window"===e,"Expected a value of window"),title:O(nt),version:O(nt),customProperties:O(x()),icon:O(I()),caption:O(I()),details:jt,intents:O(k(Nt)),hidden:O(_()),fdc3:O(tt.fdc3.v2DefinitionDecoder)}),Lt=P({name:nt}),$t=P({definitions:k(Ft)}),Wt=P({name:nt,type:nt.where(e=>"window"===e,"Expected a value of window"),instances:k(Ot),userProperties:O(x()),title:O(nt),version:O(nt),icon:O(I()),caption:O(nt),fdc3:O(x())}),Ht=P({name:nt,type:nt.where(e=>"window"===e,"Expected a value of window"),userProperties:x(),title:O(nt),version:O(nt),icon:O(I()),caption:O(nt),fdc3:O(x())}),Ut=P({appsAdded:k(Ht),appsChanged:k(Ht),appsRemoved:k(Ht)}),qt=P({apps:k(Wt),initialChannelId:O(nt)}),Bt=P({id:nt}),Gt=R(T("Global"),T("Activity"),T("ApplicationDefault"),T("Swimlane"),T("Workspace")),Jt=R(T("application"),T("activity")),zt=P({context:O(x()),bounds:pt,createArgs:P({name:O(nt),url:O(st),context:O(x())}),windowState:O(nt),restoreState:O(nt),instanceId:nt,isCollapsed:O(_()),isSticky:O(_()),restoreSettings:P({groupId:O(nt),groupZOrder:O(S())}),channelId:O(nt)}),Vt=P({type:T("window"),componentType:O(Jt),application:nt,state:zt}),Kt=P({type:T("window"),config:P({appName:nt,url:O(st),title:O(I()),allowExtract:O(_()),allowReorder:O(_()),showCloseButton:O(_()),isMaximized:O(_()),instanceId:O(nt)})}),Zt=P({type:T("group"),config:x(),children:k(R(Kt))}),Qt=P({type:T("column"),config:x(),children:k(R(Zt,Kt,E(()=>Qt),E(()=>Yt)))}),Yt=P({type:T("row"),config:x(),children:k(R(Qt,Zt,Kt,E(()=>Yt)))}),Xt=P({config:x(),context:x(),children:k(R(Yt,Qt,Zt,Kt))}),en=P({type:T("Workspace"),application:O(nt),state:Xt}),tn=P({bounds:pt,instanceId:nt,selectedWorkspace:it,workspaces:k(Xt),windowState:O(nt),restoreState:O(nt),context:O(x())}),nn=P({type:T("workspaceFrame"),application:nt,componentType:O(Jt),state:tn}),rn=P({name:nt,type:Gt,token:O(nt),components:k(R(Vt,en,nn)),context:O(x()),metadata:O(x()),version:O(S())}),sn=P({name:nt,type:Gt,token:O(nt),components:k(R(Vt,en,nn)),context:O(x()),metadata:O(x()),version:O(S()),prevName:nt}),on=P({name:nt,context:O(x()),metadata:O(x()),instances:O(k(nt)),ignoreInstances:O(k(nt)),setAsCurrent:O(_()),ignoreContexts:O(_()),saveWindowContexts:O(_())}),an=P({name:nt,context:O(x()),closeRunningInstance:O(_()),closeMe:O(_()),timeout:O(it)}),cn=P({name:nt,type:Gt}),dn=P({contents:P({appComponents:k(R(Vt,en,nn)),workspaceComponents:k(Xt),workspaceWindows:k(Kt)})}),ln=P({name:nt,type:Gt,context:O(x()),metadata:O(x())}),hn=P({name:nt,type:Gt}),un=P({layout:on}),pn=P({layout:rn,newName:nt}),gn=P({status:nt}),fn=P({layout:rn}),mn=P({layout:an}),bn=P({type:Gt}),yn=P({layouts:k(rn)}),wn=O(P({name:nt})),vn=R(T("replace"),T("merge")),Cn=P({layouts:k(rn),mode:vn,skipManagerRequest:O(_())}),In=P({summaries:k(ln)}),Sn=P({layout:rn}),_n=P({layout:O(rn)}),xn=P({name:nt}),Tn=R(T("findIntent"),T("getIntents"),T("getIntentsByHandler"),T("raise"),T("filterHandlers")),Pn=P({applicationName:nt,applicationTitle:O(I()),applicationDescription:O(I()),applicationIcon:O(I()),type:R(T("app"),T("instance")),displayName:O(I()),contextTypes:O(k(nt)),instanceId:O(I()),instanceTitle:O(I()),resultType:O(I()),customConfig:O(P())});P({applicationName:I(),applicationIcon:O(I()),instanceId:O(I())}),P({intent:nt,handler:Pn});const kn=P({name:nt,handlers:k(Pn)}),On=R(T("startNew"),T("reuse"),P({app:O(nt),instance:O(nt)})),Rn=P({type:O(nt),data:O(x())}),An=k(kn),Mn=P({intents:An}),En=P({name:O(nt),contextType:O(nt),resultType:O(nt)}),Dn=R(nt,En),jn=P({filter:O(En)}),Nn=P({top:O(S()),left:O(S()),width:O(it),height:O(it),relativeTo:O(nt),relativeDirection:O(ut),waitForAGMReady:O(_()),channelId:O(nt)}),Fn=P({intent:nt,target:O(On),context:O(Rn),options:O(Nn),handlers:O(k(Pn)),timeout:O(it),waitUserResponseIndefinitely:O(_()),clearSavedHandler:O(_())}),Ln=P({interopInstance:nt,name:O(nt)}),$n=P({originApp:Ln,intentRequest:O(Fn)}),Wn=P({name:nt,waitForAGMReady:_(),id:O(nt),context:O(x()),top:O(S()),left:O(S()),width:O(it),height:O(it),relativeTo:O(nt),relativeDirection:O(ut),forceChromeTab:O(_()),layoutComponentId:O(nt),channelId:O(nt),startReason:$n}),Hn=R(nt,Fn),Un=P({enabled:_(),appName:nt,waitResponseTimeout:S()}),qn=R(P({applicationName:nt}),P({instanceId:nt})),Bn=P({title:O(nt),openResolver:O(_()),timeout:O(it),intent:O(nt),contextTypes:O(k(nt)),resultType:O(nt),applicationNames:O(k(nt)),excludeList:O(k(qn))}),Gn=P({enabled:_(),initialCaller:P({instanceId:nt})}),Jn=P({intentRequest:Fn,resolverConfig:Un,embeddedResolverConfig:O(Gn)}),zn=P({request:Fn,handler:Pn,result:x()}),Vn=P({handlers:k(Pn)}),Kn=P({filterHandlersRequest:Bn,resolverConfig:Un,embeddedResolverConfig:O(Gn)}),Zn=P({intent:nt,contextTypes:O(k(nt)),displayName:O(I()),icon:O(I()),description:O(I()),resultType:O(I()),customConfig:O(P())}),Qn=R(nt,Zn),Yn=P({intent:nt,contextTypes:O(k(nt)),description:O(nt),displayName:O(nt),icon:O(nt),resultType:O(nt)}),Xn=P({intents:k(Yn)}),ei=e=>nt.where(t=>e.includes(t),"Expected a valid channel name"),ti=P({contextType:O(nt)}),ni=O(R(nt,P({name:O(nt),fdc3:O(_())}))),ii=R(nt,P({windowId:rt,channel:rt})),ri=x().where(e=>"string"==typeof e.type,"Expected a valid FDC3 Context with compulsory 'type' field"),si=P({method:nt,arguments:O(x()),target:O(R(T("all"),T("best")))}),oi=P({action:I(),title:nt,icon:O(I()),interop:O(si)}),ai=R(T("Active"),T("Acknowledged"),T("Seen"),T("Closed"),T("Stale"),T("Snoozed"),T("Processing")),ci=P({count:S()}),di=P({badge:O(I()),body:O(I()),data:O(x()),dir:O(R(T("auto"),T("ltr"),T("rtl"))),icon:O(I()),image:O(I()),lang:O(I()),renotify:O(_()),requireInteraction:O(_()),silent:O(_()),tag:O(I()),timestamp:O(it),vibrate:O(k(S()))}),li=P({title:nt,clickInterop:O(si),actions:O(k(oi)),focusPlatformOnDefaultClick:O(_()),badge:O(I()),body:O(I()),data:O(x()),dir:O(R(T("auto"),T("ltr"),T("rtl"))),icon:O(I()),image:O(I()),lang:O(I()),renotify:O(_()),requireInteraction:O(_()),silent:O(_()),tag:O(I()),timestamp:O(it),vibrate:O(k(S())),severity:O(R(T("Low"),T("None"),T("Medium"),T("High"),T("Critical"))),showToast:O(_()),showInPanel:O(_()),state:O(ai)}),hi=P({id:nt,state:ai});P().where(e=>!e.fdc3||"string"==typeof e.fdc3.type,"Expected a valid FDC3 Context with compulsory 'type' field");const ui=P({color:O(nt),icon:O(nt),name:O(nt),glyph:O(nt)}),pi=P({id:nt,displayMetadata:O(ui)}),gi=P({color:nt,fdc3:O(pi)}),fi=P({name:nt,meta:gi,data:O(P())}),mi=P({path:nt,value:x()}),bi=k(mi),yi=P({name:nt}),wi=P({name:nt,read:_(),write:_(),windowId:O(nt)}),vi=P({name:nt,read:_(),write:_(),windowId:nt}),Ci=P({config:vi}),Ii=P({channels:k(wi)}),Si=P({windowId:nt}),_i=P({read:_(),write:_(),windowId:O(nt)}),xi=P({restrictions:_i}),Ti=P({settings:li,id:nt}),Pi=P({settings:li}),ki=P({permissionGranted:_()}),Oi=P({permission:R(T("default"),T("granted"),T("denied"))}),Ri=P({definition:di,action:O(I()),id:O(nt)}),Ai=P({allowed:O(k(nt)),blocked:O(k(nt))}),Mi=P({enable:O(_()),enableToasts:O(_()),sourceFilter:O(Ai),showNotificationBadge:O(_())}),Ei=P({configuration:Mi}),Di=P({configuration:P({enable:_(),enableToasts:_(),sourceFilter:P({allowed:k(nt),blocked:k(nt)}),showNotificationBadge:O(_())})}),ji=P({layoutType:R(T("Global"),T("Workspace")),layoutName:nt,context:O(x())}),Ni=P({windowContext:O(x())}),Fi=P({state:R(T("prompt"),T("denied"),T("granted"))}),Li=P({isAvailable:_()}),$i=P({itemId:nt}),Wi=P({isSupported:_()}),Hi=P({operation:nt}),Ui=P({bounds:pt}),qi=P({displayName:nt,name:nt}),Bi=P({theme:qi}),Gi=P({themes:k(qi)}),Ji=P({name:nt}),zi=P({id:nt,title:nt,clickInterop:O(si),actions:O(k(oi)),focusPlatformOnDefaultClick:O(_()),badge:O(I()),body:O(I()),data:O(x()),dir:O(R(T("auto"),T("ltr"),T("rtl"))),icon:O(I()),image:O(I()),lang:O(I()),renotify:O(_()),requireInteraction:O(_()),silent:O(_()),tag:O(I()),timestamp:O(it),vibrate:O(k(S())),severity:O(R(T("Low"),T("None"),T("Medium"),T("High"),T("Critical"))),showToast:O(_()),showInPanel:O(_()),state:O(ai)}),Vi=P({notification:zi}),Ki=P({notifications:k(zi)}),Zi=P({id:nt}),Qi=P({channel:nt}),Yi=P({windowIds:k(nt)}),Xi=R(T("appHello"),T("addChannel"),T("getMyChannel"),T("getWindowIdsOnChannel"),T("getWindowIdsWithChannels"),T("joinChannel"),T("restrict"),T("getRestrictions"),T("restrictAll"),T("notifyChannelsChanged"),T("leaveChannel"),T("getMode"),T("operationCheck")),er=R(T("single"),T("multi")),tr=P({mode:er}),nr=P({windowId:nt}),ir=P({mode:er,channels:k(nt),restrictions:k(wi)}),rr=P({channel:O(nt)}),sr=P({application:O(nt),channels:O(k(nt)),windowIds:O(k(nt))}),or=P({filter:O(sr)}),ar=P({windowIdsWithChannels:k(P({application:nt,channel:O(nt),windowId:nt}))}),cr=O(x()),dr=O(P({top:O(S()),left:O(S()),width:O(it),height:O(it),relativeTo:O(nt),relativeDirection:O(ut),waitForAGMReady:O(_()),channelId:O(nt),reuseId:O(nt),originIntentRequest:O(Fn)})),lr=P({channel:nt,windowId:nt}),hr=P({windowId:nt,channelName:O(nt)}),ur=P({windowId:nt,channelNames:k(nt)}),pr=P({channel:O(nt)}),gr=R(T("clear"),T("clearAll"),T("get"),T("getAll"),T("set"),T("update"),T("prefsChanged"),T("prefsHello"),T("operationCheck"),T("registerSubscriber")),fr=P({app:nt,data:P(),lastUpdate:O(nt)}),mr=P({app:nt}),br=P({prefs:fr}),yr=P({all:k(fr)}),wr=P({interopId:nt,appName:O(nt)}),vr=P({app:nt,data:P()}),Cr=P({platform:P({app:nt}),validNonExistentApps:O(k(nt)),isAppValidationEnabled:O(_())}),Ir=P({message:nt}),Sr=P({isClientErrorOperationSupported:_()}),_r=tt.common.nonEmptyStringDecoder,xr=tt.common.nonNegativeNumberDecoder,Tr=P({bundle:_r,styles:k(_r),fonts:O(k(_r))}),Pr=P({bundle:_r,styles:k(_r),fonts:O(k(_r))}),kr=P({bundle:_r,styles:k(_r),fonts:O(k(_r))}),Or=R(T("directional"),T("default")),Rr=P({type:O(Or),enable:O(_())}),Ar=R(T("top-left"),T("top-center"),T("top-right"),T("center-left"),T("center-right"),T("bottom-left"),T("bottom-center"),T("bottom-right")),Mr=R(T("all"),T("fdc3")),Er=P({selector:O(Rr),displayMode:O(Mr)}),Dr=P({channels:O(Er),position:O(Ar),displayInWorkspace:O(_()),restoreLastKnownPosition:O(_())}),jr=P({enable:_(),awaitFactory:O(_()),timeout:O(xr),channels:O(Er),position:O(Ar),displayInWorkspace:O(_()),restoreLastKnownPosition:O(_())}),Nr=P({alerts:O(P({enabled:_()})),dialogs:O(P({enabled:_()})),awaitFactory:O(_()),timeout:O(xr)}),Fr=R(T("getResources"),T("operationCheck"),T("showAlert"),T("showDialog"),T("alertInteropAction"),T("showResolver")),Lr=P({origin:_r}),$r=P({blockedOrigin:T(!0)}),Wr=A($r,P({blockedOrigin:T(!1),config:Dr,sources:Tr})),Hr=A($r,P({blockedOrigin:T(!1),sources:Pr})),Ur=A($r,P({blockedOrigin:T(!1),sources:kr})),qr=P({widget:O(Wr),modals:O(Hr),intentResolver:O(Ur)}),Br=P({resources:qr}),Gr=P({method:_r,arguments:O(x()),target:O(R(T("best"),T("all"),_r))}),Jr=R(T("Global"),T("WindowContainer"),_r),zr=P({instance:_r,container:O(R(T("Global"),T("WindowContainer")))}),Vr=P({variant:R(T("default"),T("success"),T("critical"),T("info"),T("warning")),text:_r,showCloseButton:O(_()),clickInterop:O(Gr),onCloseInterop:O(Gr),actions:O(k(P({id:_r,title:_r,clickInterop:Gr}))),data:O(x()),ttl:O(xr),target:O(Jr)}),Kr=P({config:Vr,target:zr}),Zr=P({templateName:_r,variables:x(),target:O(Jr),timer:O(P({duration:xr})),size:O(P({width:xr,height:xr})),movable:O(_()),transparent:O(_())}),Qr=P({isExpired:O(_()),isClosed:O(_()),isEnterPressed:O(_()),responseButtonClicked:O(P({id:_r,text:_r})),inputs:O(k(P({type:R(T("checkbox"),T("email"),T("number"),T("password"),T("text")),id:_r,checked:O(_()),value:O(I())})))});P({result:Qr});const Yr=P({config:Zr,target:zr}),Xr=P({id:_r}),es=P({id:_r,responsePromise:x()}),ts=P({response:Qr}),ns=P({name:_r,settings:Gr}),is=P({interopAction:ns}),rs=P({interopAction:ns}),ss=P({enable:_(),awaitFactory:O(_()),timeout:O(xr)}),os=P({id:_r}),as=P({preserveChoice:_()}),cs=P({intent:_r,handler:Pn,userSettings:as}),ds=P({isExpired:O(_()),isClosed:O(_()),userChoice:O(cs)}),ls=P({response:ds}),hs=M(A(P({intentRequest:Fn}),P({handlerFilter:Bn})),P({timeout:xr})),us=P({config:hs}),ps=P({result:ds}),gs={openWindow:{name:"openWindow",dataDecoder:ft,resultDecoder:bt},windowHello:{name:"windowHello",dataDecoder:mt,resultDecoder:wt},windowAdded:{name:"windowAdded",dataDecoder:bt},windowRemoved:{name:"windowRemoved",dataDecoder:yt},getBounds:{name:"getBounds",dataDecoder:yt,resultDecoder:St},getFrameBounds:{name:"getFrameBounds",dataDecoder:yt,resultDecoder:_t},getUrl:{name:"getUrl",dataDecoder:yt,resultDecoder:xt},moveResize:{name:"moveResize",dataDecoder:It},focus:{name:"focus",dataDecoder:yt},close:{name:"close",dataDecoder:yt},getTitle:{name:"getTitle",dataDecoder:yt,resultDecoder:vt},setTitle:{name:"setTitle",dataDecoder:vt},focusChange:{name:"focusChange",dataDecoder:Ct},getChannel:{name:"getChannel",dataDecoder:yt,resultDecoder:pr},notifyChannelsChanged:{name:"notifyChannelsChanged",dataDecoder:ur},setZoomFactor:{name:"setZoomFactor",dataDecoder:Tt},zoomFactorChange:{name:"zoomFactorChange",dataDecoder:Tt},refresh:{name:"refresh",dataDecoder:yt},operationCheck:{name:"operationCheck"}};function fs(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 r=n instanceof Error?n:new Error(n);if(t)t(r);else{var s='[ERROR] callback-registry: User callback for key "'+i+'" failed: '+r.stack;if(e)switch(e.errorHandling){case"log":return console.error(s);case"silent":return;case"throw":throw new Error(s)}console.error(s)}}return{add:function(e,t,r){var s=n[e];return s||(s=[],n[e]=s),s.push(t),r&&setTimeout(function(){r.forEach(function(r){var s;if(null===(s=n[e])||void 0===s?void 0:s.includes(t))try{Array.isArray(r)?t.apply(void 0,r):t.apply(void 0,[r])}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=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];var s=n[e];if(!s||0===s.length)return[];var o=[];return s.forEach(function(n){try{var r=n.apply(void 0,t);o.push(r)}catch(t){o.push(void 0),i(t,e)}}),o},clear:function(){n={}},clearKey:function(e){n[e]&&delete n[e]}}}fs.default=fs;var ms=e(fs);const bs=Object.freeze({0:24,1:33,2:50,3:67,4:75,5:80,6:90,7:100,8:110,9:125,10:150,11:175,12:200,13:250,14:300,15:400,16:500});class ys{_id;_name;_bridge;_logger;registry=ms();myCtxKey;ctxUnsubscribe;zoomFactorIndex=7;me;constructor(e,t,n,i){this._id=e,this._name=t,this._bridge=n,this._logger=i,this.myCtxKey=`___window___${this.id}`}get id(){return this._id.slice()}get name(){return this._name.slice()}get zoomFactor(){return bs[this.zoomFactorIndex]}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)}processSelfZoomFactorChangedEvent(e){this.zoomFactorIndex=e,this.registry.execute("zoom-factor-changed",this.me)}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,zoomFactor:this.zoomFactor,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),refresh:this.refresh.bind(this),onContextUpdated:this.onContextUpdated.bind(this),onFocusChanged:this.onFocusChanged.bind(this),getChannel:this.getChannel.bind(this),onChannelsChanged:this.onChannelsChanged.bind(this),zoomIn:this.zoomIn.bind(this),zoomOut:this.zoomOut.bind(this),setZoomFactor:this.setZoomFactor.bind(this),onZoomFactorChanged:this.onZoomFactorChanged.bind(this)},Object.defineProperties(this.me,{id:Q,name:Q,zoomFactor:{get:()=>this.zoomFactor,enumerable:!0}}),this.me}async getURL(){return(await this._bridge.send("windows",gs.getUrl,{windowId:this.id})).url}onFocusChanged(e){return"function"!=typeof e?re.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=X(kt,e),n=Object.assign({},t,{windowId:this.id,relative:!1});return await this._bridge.send("windows",gs.moveResize,n),this.me}async resizeTo(e,t){if(void 0===e&&void 0===t)return this.me;void 0!==e&&X(it,e),void 0!==t&&X(it,t);const n=Object.assign({},{width:e,height:t},{windowId:this.id,relative:!0});return await this._bridge.send("windows",gs.moveResize,n),this.me}async moveTo(e,t){if(void 0===e&&void 0===t)return this.me;void 0!==e&&X(S(),e),void 0!==t&&X(S(),t);const n=Object.assign({},{top:e,left:t},{windowId:this.id,relative:!0});return await this._bridge.send("windows",gs.moveResize,n),this.me}async focus(){return"Platform"===this.name?window.open(void 0,this.id):await this._bridge.send("windows",gs.focus,{windowId:this.id}),this.me}async close(){return await this._bridge.send("windows",gs.close,{windowId:this.id}),this.me}async getTitle(){return(await this._bridge.send("windows",gs.getTitle,{windowId:this.id})).title}async setTitle(e){const t=X(nt,e);return await this._bridge.send("windows",gs.setTitle,{windowId:this.id,title:t}),this.me}async getBounds(){return(await this._bridge.send("windows",gs.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=X(Pt,e);return await this._bridge.contextLib.update(this.myCtxKey,t),this.me}async setContext(e){const t=X(Pt,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 re.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",gs.getChannel,{windowId:this.id},void 0,{includeOperationCheck:!0})).channel}onChannelsChanged(e){return this.registry.add("channels-changed",e)}getClosestZoomFactorIndex(e){const t=Object.entries(bs).reduce((t,[n,i])=>Math.abs(i-e)<=Math.abs(bs[t]-e)?parseInt(n):t,0),n=bs[t];return n!==e&&this._logger.warn(`Zoom factor ${e} is not available, using closest value ${n} instead.`),t}async zoom(e){e!==this.zoomFactorIndex&&e in bs&&(await this._bridge.send("windows",gs.setZoomFactor,{windowId:this.id,factorIndex:e},void 0,{includeOperationCheck:!0}),this.zoomFactorIndex=e)}async zoomIn(){return await this.zoom(this.zoomFactorIndex+1),this.me}async zoomOut(){return await this.zoom(this.zoomFactorIndex-1),this.me}async setZoomFactor(e){const t=X(S(),e),n=this.getClosestZoomFactorIndex(t);return await this.zoom(n),this.me}onZoomFactorChanged(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to zoom factor changes, because the provided callback is not a function!"):this.registry.add("zoom-factor-changed",e)}async refresh(){return await this._bridge.send("windows",gs.refresh,{windowId:this.id},void 0,{includeOperationCheck:!0}),this.me}}const ws={operationCheck:{name:"operationCheck",dataDecoder:Hi,resultDecoder:Wi},getWorkspaceWindowFrameBounds:{name:"getWorkspaceWindowFrameBounds",resultDecoder:Ui,dataDecoder:$i}},vs=(e,t,n)=>new Promise((i,r)=>{let s=!0;const o=setTimeout(()=>{if(!s)return;s=!1;r(n||`Promise timeout hit: ${t}`)},t);e().then(e=>{s&&(s=!1,clearTimeout(o),i(e))}).catch(e=>{s&&(s=!1,clearTimeout(o),r(e))})}),Cs=(e,t,n)=>new Promise((i,r)=>{const s=setTimeout(()=>{r(n||`Promise timeout hit: ${t}`)},t);new Promise(e).then(e=>{clearTimeout(s),i(e)}).catch(e=>{clearTimeout(s),r(e)})});class Is{supportedOperationsNames=[];focusEventHandler;registry=ms();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=X(at,e.operation),n=gs[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=X(n.dataDecoder,e.data)),await n.execute(i)}async open(e,t,n){X(nt,e),X(st,t);const i=X(gt,n),r=await this.bridge.send("windows",gs.openWindow,{name:e,url:t,options:i});return this.waitForWindowAdded(r.windowId)}list(){return this.allWindowProjections.map(e=>e.api)}findById(e){return X(nt,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(){gs.focusChange.execute=this.handleFocusChangeEvent.bind(this),gs.windowAdded.execute=this.handleWindowAdded.bind(this),gs.windowRemoved.execute=this.handleWindowRemoved.bind(this),gs.getBounds.execute=this.handleGetBounds.bind(this),gs.getFrameBounds.execute=this.handleGetBounds.bind(this),gs.getTitle.execute=this.handleGetTitle.bind(this),gs.getUrl.execute=this.handleGetUrl.bind(this),gs.moveResize.execute=this.handleMoveResize.bind(this),gs.setTitle.execute=this.handleSetTitle.bind(this),gs.getChannel.execute=this.handleGetChannel.bind(this),gs.notifyChannelsChanged.execute=this.handleChannelsChanged.bind(this),gs.setZoomFactor.execute=this.handleSetZoomFactor.bind(this),gs.zoomFactorChange.execute=this.handleZoomFactorChanged.bind(this),gs.refresh.execute=this.handleRefresh.bind(this),gs.operationCheck.execute=async e=>te(this.supportedOperationsNames,e.operation),this.supportedOperationsNames=ee(gs)}my(){return Object.assign({},this.me)}onWindowAdded(e){return"function"!=typeof e?re.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?re.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?re.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?re.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",gs.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){const t=e.map(e=>`${e.windowId}:${e.name}`).join(", ");return re.raiseError(`Cannot initialize the window library, because I received no information about me -> id: ${this.publicWindowId} name: ${window.name} from the platform: known windows: ${t}`)}const n=await this.ioc.buildWebWindow(this.publicWindowId,t.name,this.logger);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)));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.logger);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}}:re.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}:re.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}:re.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,r="number"==typeof e.width?e.width:e.relative?0:window.innerWidth,s=e.relative?window.moveBy:window.moveTo,o=e.relative?window.resizeBy:window.resizeTo;s(n,t),o(r,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",ws.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):Cs(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",gs.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 re.raiseError("This window cannot report its channel, because it is not a ioConnect Window, most likely because it is an iframe");const e=this.channelsController.my();return{...e?{channel:e}:{}}}async handleRefresh(){if(!this.me)return re.raiseError("This window cannot refresh, because it is not an ioConnect Window, most likely because it is an iframe");setTimeout(()=>{window.location.reload()},0)}async handleChannelsChanged(e){const t=this.allWindowProjections.find(t=>t.id===e.windowId);t?.model.processChannelsChangedEvent(e.channelNames)}async handleSetZoomFactor(e){if(!this.me)return re.raiseError("This window cannot change its zoom factor, because it is not an ioConnect Window, most likely because it is an iframe");document.body.style.zoom=`${bs[e.factorIndex]}%`}async handleZoomFactorChanged(e){const t=this.allWindowProjections.find(t=>t.id===e.windowId);t&&t.model.processSelfZoomFactorChangedEvent(e.factorIndex)}}const Ss="T42.Web.Platform.Control",_s="T42.Web.Platform.Stream",xs="T42.Web.Client.Control",Ts="T42.Core.Plus.Themes.Stream";class Ps{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(xs)}async start(e){this.running=!0,this.controllers=e,await Promise.all([this.checkWaitMethod(Ss),this.checkWaitMethod(_s)]);const t=this.communicationId,[n]=await Promise.all([this.coreGlue.interop.subscribe(_s,t?{target:{instance:this.communicationId}}:void 0),this.coreGlue.interop.registerAsync(xs,(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,r){if(t.dataDecoder)try{t.dataDecoder.runWithException(n)}catch(e){return re.raiseError(`Unexpected Web->Platform outgoing validation error: ${e.message}, for operation: ${t.name} and input: ${JSON.stringify(e.input)}`)}if(!(!r?.includeOperationCheck||(await this.checkOperationSupported(e,t)).isSupported))return re.raiseError(`Cannot complete operation: ${t.name} for domain: ${e} because this client is connected to a platform which does not support it`);try{const r=await this.transmitMessage(e,t,n,i);return t.resultDecoder&&t.resultDecoder.runWithException(r),r}catch(e){return e?.kind?re.raiseError(`Unexpected Web<-Platform incoming validation error: ${e.message}, for operation: ${t.name} and input: ${JSON.stringify(e.input)}`):re.raiseError(e)}}async createThemesSubscription(){return this.coreGlue.interop.methods().some(e=>e.name===Ts)?this.coreGlue.interop.subscribe(Ts,this.communicationId?{target:{instance:this.communicationId}}:void 0):re.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,ws.operationCheck,{operation:t.name})}catch(e){return{isSupported:!1}}}checkWaitMethod(e){return Cs(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 r=i.method,s=i.server,o=!this.communicationId||s.instance===this.communicationId;r.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=ot.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 r=i.result;this.controllers[r].handleBridgeMessage(e).then(e=>{t&&t(e)}).catch(e=>{n&&n(e),console.warn(e)})}async transmitMessage(e,t,n,i){const r={domain:e,data:n,operation:t.name};let s;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(s=await this.coreGlue.interop.invoke(Ss,r,a?{instance:this.communicationId}:void 0,i),!s)throw new Error("Received unsupported result from the platform - empty result");if(!Array.isArray(s.all_return_values)||0===s.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 s.all_return_values[0].returned}}const ks={appHello:{name:"appHello",dataDecoder:mt,resultDecoder:qt},appDirectoryStateChange:{name:"appDirectoryStateChange",dataDecoder:Ut},instanceStarted:{name:"instanceStarted",dataDecoder:Ot},instanceStopped:{name:"instanceStopped",dataDecoder:Ot},applicationStart:{name:"applicationStart",dataDecoder:Wn,resultDecoder:Ot},instanceStop:{name:"instanceStop",dataDecoder:Bt},import:{name:"import"},remove:{name:"remove",dataDecoder:Lt},export:{name:"export",resultDecoder:$t},clear:{name:"clear"},operationCheck:{name:"operationCheck"}};class Os{me;supportedOperationsNames=[];baseApplicationsTimeoutMS=6e4;appImportTimeoutMS=20;registry=ms();ioc;bridge;publicWindowId;applications=[];instances=[];platformRegistration;logger;channelsController;interop;initialChannelId;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.interop=e.interop,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 postStart(){this.initialChannelId&&await this.channelsController.handleAppManagerInitialChannelId(this.initialChannelId)}async handleBridgeMessage(e){await this.platformRegistration;const t=X(ct,e.operation),n=ks[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=X(n.dataDecoder,e.data)),await n.execute(i)}onInstanceStarted(e){return"function"!=typeof e?re.raiseError("onInstanceStarted requires a single argument of type function"):this.registry.add("instance-started",e,this.instances)}onInstanceStopped(e){return"function"!=typeof e?re.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 re.raiseError(`The channel with name "${n.channelId}" doesn't exist!`);const r={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,startReason:{originApp:{name:this.me?.application.name,interopInstance:this.interop.instance.instance}}};n?.originIntentRequest&&(r.startReason.intentRequest=n.originIntentRequest);const s=await this.bridge.send("appManager",ks.applicationStart,r),o=this.applications.find(e=>e.name===s.applicationName);return this.ioc.buildInstance(s,o)}getApplication(e){const t=X(nt,e),n=this.applications.find(e=>e.name===t),i=n?.userProperties?.details?.iframeSandbox;return i&&(n.userProperties.details.workspacesSandbox=i),n}getInstances(){return this.instances.slice()}onAppAdded(e){return"function"!=typeof e?re.raiseError("onAppAdded requires a single argument of type function"):this.registry.add("application-added",e,this.applications)}onAppRemoved(e){return"function"!=typeof e?re.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(){ks.appDirectoryStateChange.execute=this.handleAppDirectoryStateChange.bind(this),ks.instanceStarted.execute=this.handleInstanceStartedMessage.bind(this),ks.instanceStopped.execute=this.handleInstanceStoppedMessage.bind(this),ks.operationCheck.execute=async e=>te(this.supportedOperationsNames,e.operation),this.supportedOperationsNames=ee(ks)}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?re.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 re.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(X(vn,t),!Array.isArray(e))return re.raiseError("Import must be called with an array of definitions");if(e.length>1e4)return re.raiseError("Cannot import more than 10000 app definitions in Glue42 Core.");const n=e.reduce((e,t)=>{const{isValid:n,error:i}=this.isValidDefinition(t);return n?e.valid.push(t):e.invalid.push({app:t?.name,error:i??`Provided definition is invalid ${JSON.stringify(t)}`}),e},{valid:[],invalid:[]}),i=this.baseApplicationsTimeoutMS+this.appImportTimeoutMS*n.valid.length;return await this.bridge.send("appManager",ks.import,{definitions:n.valid,mode:t},{methodResponseTimeoutMs:i}),{imported:n.valid.map(e=>e.name),errors:n.invalid}}isValidDefinition(e){if(e?.appId&&e?.details){const t=tt.fdc3.v2DefinitionDecoder.run(e);return{isValid:t.ok,error:t.ok?void 0:`Received invalid FDC3 v2 definition. Error: ${JSON.stringify(t.error)}`}}if(e?.appId&&e?.manifest){const t=tt.fdc3.v1DefinitionDecoder.run(e);return{isValid:t.ok,error:t.ok?void 0:`Received invalid FDC3 v1 definition. Error: ${JSON.stringify(t.error)}`}}const t=Ft.run(e);return{isValid:t.ok,error:t.ok?void 0:`Received invalid definition. Error: ${JSON.stringify(t.error)}`}}async remove(e){X(nt,e),await this.bridge.send("appManager",ks.remove,{name:e},{methodResponseTimeoutMs:this.baseApplicationsTimeoutMS})}async clear(){await this.bridge.send("appManager",ks.clear,void 0,{methodResponseTimeoutMs:this.baseApplicationsTimeoutMS})}async exportApps(){return(await this.bridge.send("appManager",ks.export,void 0,{methodResponseTimeoutMs:this.baseApplicationsTimeoutMS})).definitions}getApplications(){return this.applications.slice()}async registerWithPlatform(){const e=await this.bridge.send("appManager",ks.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`),this.initialChannelId=e.initialChannelId}findMyInstance(){for(const e of this.applications){const t=e.instances.find(e=>e.id===this.publicWindowId);if(t)return t}}}class Rs{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",ks.instanceStop,{id:this.data.id})}}class As{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),getConfiguration:this.getConfiguration.bind(this),onInstanceStarted:this.onInstanceStarted.bind(this),onInstanceStopped:this.onInstanceStopped.bind(this)};return this.me=e,this.me}onInstanceStarted(e){return"function"!=typeof e?re.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?re.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=X(cr,e),i=X(dr,t);return this.controller.startApplication(this.data.name,n,i)}async getConfiguration(){const{details:e,intents:t,hidden:n,...i}=this.data.userProperties,r={name:this.data.name,type:this.data.type,details:e,customProperties:i},s={title:this.data.title,version:this.data.version,icon:this.data.icon,caption:this.data.caption,intents:t,hidden:n,fdc3:this.data.fdc3};for(const[e,t]of Object.entries(s))void 0!==t&&(r[e]=t);return r}}const Ms={layoutAdded:{name:"layoutAdded",dataDecoder:rn},layoutChanged:{name:"layoutChanged",dataDecoder:rn},layoutRemoved:{name:"layoutRemoved",dataDecoder:rn},layoutRestored:{name:"layoutRestored",dataDecoder:rn},defaultLayoutChanged:{name:"defaultLayoutChanged",dataDecoder:wn},layoutRenamed:{name:"layoutRenamed",dataDecoder:sn},get:{name:"get",dataDecoder:hn,resultDecoder:_n},getAll:{name:"getAll",dataDecoder:bn,resultDecoder:In},getLayoutContents:{name:"getLayoutContents",dataDecoder:cn,resultDecoder:dn},export:{name:"export",dataDecoder:bn,resultDecoder:yn},import:{name:"import",dataDecoder:Cn},remove:{name:"remove",dataDecoder:hn},rename:{name:"rename",dataDecoder:pn,resultDecoder:gn},save:{name:"save",dataDecoder:un,resultDecoder:Sn},restore:{name:"restore",dataDecoder:mn},clientSaveRequest:{name:"clientSaveRequest",dataDecoder:ji,resultDecoder:Ni},getGlobalPermissionState:{name:"getGlobalPermissionState",resultDecoder:Fi},requestGlobalPermission:{name:"requestGlobalPermission",resultDecoder:Li},checkGlobalActivated:{name:"checkGlobalActivated",resultDecoder:Li},getDefaultGlobal:{name:"getDefaultGlobal",resultDecoder:_n},setDefaultGlobal:{name:"setDefaultGlobal",dataDecoder:xn},clearDefaultGlobal:{name:"clearDefaultGlobal"},getCurrent:{name:"getCurrent",resultDecoder:_n},updateMetadata:{name:"updateMetadata",dataDecoder:fn},operationCheck:{name:"operationCheck"}};class Es{supportedOperationsNames=[];defaultLayoutRestoreTimeoutMS=12e4;registry=ms();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=X(dt,e.operation),n=Ms[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=X(n.dataDecoder,e.data)),await n.execute(i)}toApi(){const e={get:this.get.bind(this),getAll:this.getAll.bind(this),getLayoutContents:this.getLayoutContents.bind(this),getCurrentLayout:this.getCurrentLayout.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),onDefaultGlobalChanged:this.onDefaultGlobalChanged.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),onRestored:this.onRestored.bind(this),updateMetadata:this.updateMetadata.bind(this)};return Object.freeze(e)}addOperationsExecutors(){Ms.layoutAdded.execute=this.handleOnAdded.bind(this),Ms.layoutChanged.execute=this.handleOnChanged.bind(this),Ms.layoutRemoved.execute=this.handleOnRemoved.bind(this),Ms.layoutRenamed.execute=this.handleOnRenamed.bind(this),Ms.layoutRestored.execute=this.handleOnRestored.bind(this),Ms.defaultLayoutChanged.execute=this.handleOnDefaultChanged.bind(this),Ms.clientSaveRequest.execute=this.handleSaveRequest.bind(this),Ms.operationCheck.execute=async e=>te(this.supportedOperationsNames,e.operation),this.supportedOperationsNames=ee(Ms)}async get(e,t){X(nt,e),X(Gt,t);return(await this.bridge.send("layouts",Ms.get,{name:e,type:t})).layout}async getCurrentLayout(){return(await this.bridge.send("layouts",Ms.getCurrent,void 0)).layout}async getAll(e){X(Gt,e);return(await this.bridge.send("layouts",Ms.getAll,{type:e})).summaries}async getLayoutContents(e){X(cn,e);const{name:t,type:n}=e;if("Workspace"!==n&&"Global"!==n)return re.raiseError(`getLayoutContents is only supported for Workspace and Global layouts, but got type "${n}"`);return(await this.bridge.send("layouts",Ms.getLayoutContents,{name:t,type:n},void 0,{includeOperationCheck:!0})).contents}async exportLayouts(e){X(Gt,e);return(await this.bridge.send("layouts",Ms.export,{type:e})).layouts}async importLayouts(e,t="replace"){if(X(vn,t),!Array.isArray(e))return re.raiseError("Import must be called with an array of layouts");if(e.length>1e3)return re.raiseError("Cannot import more than 1000 layouts at once in Glue42 Core.");const n=e.reduce((e,t)=>{const n=rn.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",Ms.import,{layouts:i,mode:t})}async save(e){X(on,e);return(await this.bridge.send("layouts",Ms.save,{layout:e})).layout}async restore(e){X(an,e);const t=e.timeout?2*e.timeout:this.defaultLayoutRestoreTimeoutMS;await this.bridge.send("layouts",Ms.restore,{layout:e},{methodResponseTimeoutMs:t})}async remove(e,t){X(Gt,e),X(nt,t),await this.bridge.send("layouts",Ms.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",Ms.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 re.raiseError("Cannot request permission for multi-window placement from any app other than the Platform.");return{permissionGranted:(await this.bridge.send("layouts",Ms.requestGlobalPermission,void 0,{methodResponseTimeoutMs:18e4})).isAvailable}}async checkGlobalActivated(){return{activated:(await this.bridge.send("layouts",Ms.checkGlobalActivated,void 0)).isAvailable}}async getDefaultGlobal(){return(await this.bridge.send("layouts",Ms.getDefaultGlobal,void 0,void 0,{includeOperationCheck:!0})).layout}async setDefaultGlobal(e){X(nt,e),await this.bridge.send("layouts",Ms.setDefaultGlobal,{name:e},void 0,{includeOperationCheck:!0})}async clearDefaultGlobal(){await this.bridge.send("layouts",Ms.clearDefaultGlobal,void 0,void 0,{includeOperationCheck:!0})}async rename(e,t){X(rn,e),X(nt,t);return await this.bridge.send("layouts",Ms.rename,{layout:e,newName:t},void 0,{includeOperationCheck:!0})}async updateMetadata(e){X(rn,e),await this.bridge.send("layouts",Ms.updateMetadata,{layout:e},void 0,{includeOperationCheck:!0})}onAdded(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to onAdded, because the provided callback is not a function!"):(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(Ms.layoutAdded.name,e))}onChanged(e){return this.registry.add(Ms.layoutChanged.name,e)}onDefaultGlobalChanged(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to onDefaultGlobalChanged, because the provided callback is not a function!"):(this.getDefaultGlobal().then(t=>e(t?{name:t.name}:void 0)).catch(()=>{}),this.registry.add(Ms.defaultLayoutChanged.name,e))}onRemoved(e){return this.registry.add(Ms.layoutRemoved.name,e)}onRenamed(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to onRenamed, because the provided callback is not a function!"):this.registry.add(Ms.layoutRenamed.name,e)}onRestored(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to onRestored, because the provided callback is not a function!"):this.registry.add(Ms.layoutRestored.name,e)}subscribeOnSaveRequested(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to onSaveRequested, because the provided argument is not a valid callback function."):this.saveRequestSubscription?re.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(Ms.layoutAdded.name,e)}async handleOnChanged(e){this.registry.execute(Ms.layoutChanged.name,e)}async handleOnDefaultChanged(e){this.registry.execute(Ms.defaultLayoutChanged.name,e)}async handleOnRemoved(e){this.registry.execute(Ms.layoutRemoved.name,e)}async handleOnRestored(e){this.registry.execute(Ms.layoutRestored.name,e)}async handleOnRenamed(e){const{prevName:t,...n}=e;this.registry.execute(Ms.layoutRenamed.name,n,{name:t})}}const Ds={raiseNotification:{name:"raiseNotification",dataDecoder:Ti,resultDecoder:Pi},requestPermission:{name:"requestPermission",resultDecoder:ki},notificationShow:{name:"notificationShow",dataDecoder:Ri},notificationClick:{name:"notificationClick",dataDecoder:Ri},getPermission:{name:"getPermission",resultDecoder:Oi},list:{name:"list",resultDecoder:Ki},notificationRaised:{name:"notificationRaised",dataDecoder:Vi},notificationClosed:{name:"notificationClosed",dataDecoder:Zi},click:{name:"click"},clear:{name:"clear"},clearAll:{name:"clearAll"},clearOld:{name:"clearOld"},configure:{name:"configure",dataDecoder:Ei,resultDecoder:Di},getConfiguration:{name:"getConfiguration",resultDecoder:Di},getActiveCount:{name:"getActiveCount",resultDecoder:ci},configurationChanged:{name:"configurationChanged",resultDecoder:Di},setState:{name:"setState",dataDecoder:hi},activeCountChange:{name:"activeCountChange",resultDecoder:ci},stateChange:{name:"stateChange",resultDecoder:hi},operationCheck:{name:"operationCheck"}};let js=(e=21)=>{let t="",n=0|e;for(;n-- >0;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return t};class Ns{supportedOperationsNames=[];registry=ms();logger;bridge;notificationsSettings;notifications={};coreGlue;buildNotificationFunc;notificationsConfiguration;notificationsActiveCount=0;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,this.notificationsConfiguration=await this.getConfiguration(),this.notificationsActiveCount=await this.getActiveCount();const n=this.toApi();this.addOperationExecutors(),e.notifications=n,this.logger.trace("notifications are ready")}async handleBridgeMessage(e){const t=X(lt,e.operation),n=Ds[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=X(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),onCounterChanged:this.onActiveCountChanged.bind(this),onStateChanged:this.onStateChanged.bind(this)};return Object.freeze(e)}async getPermission(){return(await this.bridge.send("notifications",Ds.getPermission,void 0)).permission}async requestPermission(){return(await this.bridge.send("notifications",Ds.requestPermission,void 0)).permissionGranted}async raise(e){const t=X(li,e);t.showToast="boolean"!=typeof t.showToast||t.showToast,t.showInPanel="boolean"!=typeof t.showInPanel||t.showInPanel;if(!await this.requestPermission())return re.raiseError("Cannot raise the notification, because the user has declined the permission request");const n=js(10),i=await this.bridge.send("notifications",Ds.raiseNotification,{settings:t,id:n}),r=this.buildNotificationFunc(i.settings,n);return this.notifications[n]=r,r}async list(){return(await this.bridge.send("notifications",Ds.list,void 0,void 0,{includeOperationCheck:!0})).notifications}onRaised(e){return"function"!=typeof e?re.raiseError("onRaised expects a callback of type function"):this.registry.add("notification-raised",e)}onClosed(e){return"function"!=typeof e?re.raiseError("onClosed expects a callback of type function"):this.registry.add("notification-closed",e)}async click(e,t){X(nt,e),t&&X(nt,t),await this.bridge.send("notifications",Ds.click,{id:e,action:t},void 0,{includeOperationCheck:!0})}async clear(e){X(nt,e),await this.bridge.send("notifications",Ds.clear,{id:e},void 0,{includeOperationCheck:!0})}async clearAll(){await this.bridge.send("notifications",Ds.clearAll,void 0,void 0,{includeOperationCheck:!0})}async clearOld(){await this.bridge.send("notifications",Ds.clearOld,void 0,void 0,{includeOperationCheck:!0})}async configure(e){const t=X(Mi,e);return(await this.bridge.send("notifications",Ds.configure,{configuration:t},void 0,{includeOperationCheck:!0})).configuration}async getConfiguration(){return(await this.bridge.send("notifications",Ds.getConfiguration,void 0,void 0,{includeOperationCheck:!0})).configuration}async getActiveCount(){try{return(await this.bridge.send("notifications",Ds.getActiveCount,void 0,void 0,{includeOperationCheck:!0})).count}catch(e){return console.warn("Failed to get accurate active notifications count",e),0}}async getFilter(){return(await this.bridge.send("notifications",Ds.getConfiguration,void 0,void 0,{includeOperationCheck:!0})).configuration.sourceFilter}async setFilter(e){const t=X(Ai,e);return await this.bridge.send("notifications",Ds.configure,{configuration:{sourceFilter:t}},void 0,{includeOperationCheck:!0}),t}async setState(e,t){X(nt,e),X(ai,t),await this.bridge.send("notifications",Ds.setState,{id:e,state:t},void 0,{includeOperationCheck:!0})}onConfigurationChanged(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to configuration changed, because the provided callback is not a function!"):(setTimeout(()=>e(this.notificationsConfiguration),0),this.registry.add("notifications-config-changed",e))}onActiveCountChanged(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to onActiveCountChanged changed, because the provided callback is not a function!"):(setTimeout(()=>e({count:this.notificationsActiveCount}),0),this.registry.add("notifications-active-count-changed",e))}onStateChanged(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to onStateChanged changed, because the provided callback is not a function!"):this.registry.add("notification-state-changed",e)}addOperationExecutors(){Ds.notificationShow.execute=this.handleNotificationShow.bind(this),Ds.notificationClick.execute=this.handleNotificationClick.bind(this),Ds.notificationRaised.execute=this.handleNotificationRaised.bind(this),Ds.notificationClosed.execute=this.handleNotificationClosed.bind(this),Ds.configurationChanged.execute=this.handleConfigurationChanged.bind(this),Ds.activeCountChange.execute=this.handleActiveCountChanged.bind(this),Ds.stateChange.execute=this.handleNotificationStateChanged.bind(this),Ds.operationCheck.execute=async e=>te(this.supportedOperationsNames,e.operation),this.supportedOperationsNames=ee(Ds)}async handleConfigurationChanged(e){this.notificationsConfiguration=e.configuration,this.registry.execute("notifications-config-changed",e.configuration)}async handleActiveCountChanged(e){this.notificationsActiveCount=e.count,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 Fs={getIntents:{name:"getIntents",resultDecoder:Mn},findIntent:{name:"findIntent",dataDecoder:jn,resultDecoder:Mn},raise:{name:"raise",dataDecoder:Jn,resultDecoder:zn},filterHandlers:{name:"filterHandlers",dataDecoder:Kn,resultDecoder:Vn},getIntentsByHandler:{name:"getIntentsByHandler",dataDecoder:Pn,resultDecoder:Xn}},Ls="Tick42.FDC3.Intents.";class $s{bridge;logger;interop;appManagerController;windowsController;myIntents=new Set;prefsController;uiController;useIntentsResolverUI=!0;intentsResolverAppName;intentResolverResponseTimeout=6e4;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.prefsController=t.prefsController,this.uiController=t.uiController,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=X(Tn,e.operation),n=Fs[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=X(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=X(Hn,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 r={intentRequest:n,resolverConfig:this.getLegacyResolverConfigByRequest({intentRequest:n}),embeddedResolverConfig:this.getEmbeddedResolverConfig()},s=n.waitUserResponseIndefinitely?Z:(n.timeout||this.intentResolverResponseTimeout)+3e4;this.logger.trace(`Sending raise request to the platform: ${JSON.stringify(e)} and method response timeout of ${s}ms`);const o=await this.bridge.send("intents",Fs.raise,r,{methodResponseTimeoutMs:s,waitTimeoutMs:s});return this.logger.trace(`Raise operation completed with response: ${JSON.stringify(o)}`),o}getLegacyResolverConfigByRequest(e){if(e.handlerFilter)return{enabled:"boolean"==typeof e.handlerFilter?.openResolver?e.handlerFilter?.openResolver:this.useIntentsResolverUI,appName:this.intentsResolverAppName,waitResponseTimeout:e.handlerFilter?.timeout||9e4};const t=e.intentRequest?.waitUserResponseIndefinitely?Z:this.intentResolverResponseTimeout;return{enabled:this.useIntentsResolverUI,appName:this.intentsResolverAppName,waitResponseTimeout:t}}getEmbeddedResolverConfig(){return{enabled:this.uiController.isIntentResolverEnabled(),initialCaller:{instanceId:this.interop.instance.instance}}}async all(){await Promise.all(this.unregisterIntentPromises);return(await this.bridge.send("intents",Fs.getIntents,void 0)).intents}addIntentListener(e,t){if(X(Qn,e),"function"!=typeof t)return re.raiseError("Cannot add intent listener, because the provided handler is not a function!");let n;const i="string"==typeof e?e:e.intent,r=this.buildInteropMethodName(i);if(this.myIntents.has(i))return re.raiseError(`Intent listener for intent ${i} already registered!`);this.myIntents.add(i);const s={unsubscribe:()=>{this.myIntents.delete(i),n.then(()=>this.interop.unregister(r)).catch(e=>this.logger.trace(`Unregistration of a method with name ${r} failed with reason: ${e}`))}};let o={};if("object"==typeof e){const{intent:t,...n}=e;o=n}return n=this.interop.register({name:r,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 ${r} failed with reason: ${e}`)}),s}async register(e,t){if(X(Qn,e),"function"!=typeof t)return re.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 re.raiseError(`Intent listener for intent ${n} already registered!`);this.myIntents.add(n);let r={};if("object"==typeof e){const{intent:t,...n}=e;r=n}try{await this.interop.register({name:i,flags:{intent:r}},e=>{if(this.myIntents.has(n)){const{_initialCallerId:n,...i}=e,r=this.interop.servers().find(e=>e.instance===n);return t(i,r)}})}catch(e){return this.myIntents.delete(n),re.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=X(Dn,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",Fs.findIntent,t)).intents}onHandlerAdded(e){if("function"!=typeof e)return re.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 re.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:n,method:i})=>{if(!i.name.startsWith(Ls))return;const r=i.name.replace(Ls,""),s=await this.buildIntentHandlerFromServerMethod(e,n,i,r);t(s,r)})}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,customConfig:t.customConfig}}async buildIntentHandlerFromServerMethod(e,t,n,i){const r=n.flags.intent,s=this.appManagerController.getApplication(t.application||t.applicationName);let o;"serverMethodAdded"===e&&t.windowId&&(o=await(this.windowsController.findById(t.windowId)?.getTitle()));const a=s?.userProperties?.intents?.find(e=>e.name===i);return{applicationName:t.application||t.applicationName||"",instanceId:t.windowId||t.instance,type:"instance",applicationIcon:r?.icon||s?.icon,applicationTitle:s?.title,applicationDescription:r?.description||s?.caption,contextTypes:r?.contextTypes||a?.contexts,instanceTitle:o,displayName:r?.displayName||a?.displayName,resultType:r?.resultType||a?.resultType,customConfig:r?.customConfig}}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`${Ls}${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){X(Bn,e),this.checkIfAtLeastOneFilterIsPresent(e);const t=this.getEmbeddedResolverConfig();if(e.openResolver&&!this.useIntentsResolverUI&&!t.enabled)return re.raiseError("Cannot resolve 'filterHandlers' request using Intents Resolver UI because it's globally disabled");const n=(e.timeout||9e4)+3e4,i={filterHandlersRequest:e,resolverConfig:this.getLegacyResolverConfigByRequest({handlerFilter:e}),embeddedResolverConfig:t};return await this.bridge.send("intents",Fs.filterHandlers,i,{methodResponseTimeoutMs:n,waitTimeoutMs:n},{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 re.raiseError(t);const{intent:n,resultType:i,contextTypes:r,applicationNames:s}=e,o=r?.length,a=s?.length;return n||i||o||a?void 0:re.raiseError(t)}async getIntentsByHandler(e){X(Pn,e);return await this.bridge.send("intents",Fs.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:this.getLegacyResolverConfigByRequest({intentRequest:e}),embeddedResolverConfig:this.getEmbeddedResolverConfig()};try{return await this.bridge.send("intents",Fs.raise,n)}catch(t){this.logger.trace(`Could not raise intent to remembered handler. Reason: ${t}. Removing it from Prefs store`),await this.removeRememberedHandler(e.intent)}}}const Ws={appHello:{name:"appHello",dataDecoder:nr,resultDecoder:ir},addChannel:{name:"addChannel",dataDecoder:fi},removeChannel:{name:"removeChannel",dataDecoder:yi},getMyChannel:{name:"getMyChannel",resultDecoder:rr},getWindowIdsOnChannel:{name:"getWindowIdsOnChannel",dataDecoder:Qi,resultDecoder:Yi},getWindowIdsWithChannels:{name:"getWindowIdsWithChannels",dataDecoder:or,resultDecoder:ar},joinChannel:{name:"joinChannel",dataDecoder:lr},restrict:{name:"restrict",dataDecoder:Ci},getRestrictions:{name:"getRestrictions",dataDecoder:Si,resultDecoder:Ii},restrictAll:{name:"restrictAll",dataDecoder:xi},notifyChannelsChanged:{name:"notifyChannelsChanged",dataDecoder:ur},leaveChannel:{name:"leaveChannel",dataDecoder:hr},requestChannelSelector:{name:"requestChannelSelector",dataDecoder:Et},getMode:{name:"getMode",resultDecoder:tr},operationCheck:{name:"operationCheck"}},Hs="___channel___",Us="subs",qs="changed",Bs="channels_changed",Gs="io_connect_channels",Js="inMemory";class zs{supportedOperationsNames=[];registry=ms();logger;contexts;interop;bridge;windowsController;_mode;myWindowId;storage;handlePlatformShutdown(){this.registry.clear(),this.storage.clear()}addOperationsExecutors(){Ws.getMyChannel.execute=this.handleGetMyChannel.bind(this),Ws.joinChannel.execute=this.handleJoinChannel.bind(this),Ws.leaveChannel.execute=this.handleLeaveChannel.bind(this),Ws.restrict.execute=this.handleRestrict.bind(this),Ws.getRestrictions.execute=({windowId:e})=>this.getRestrictions(e),Ws.restrictAll.execute=this.handleRestrictAll.bind(this),Ws.operationCheck.execute=async e=>te(this.supportedOperationsNames,e.operation),this.supportedOperationsNames=ee(Ws)}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.interop=e.interop,this.addOperationsExecutors(),this.bridge=t.bridge,this.windowsController=t.windowsController,this.storage=t.channelsStorage,this.logger.trace("no need for platform registration, attaching the channels property to glue and returning"),this.myWindowId=this.windowsController.my().id??this.interop.instance.instance,await this.initialize();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: ${Y(e)}`)}}async handleBridgeMessage(e){const t=X(Xi,e.operation),n=Ws[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=X(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();X(ei(n),e),X(rt,t);const i={channel:e,windowId:t??this.myWindowId};await this.bridge.send("channels",Ws.joinChannel,i,void 0,{includeOperationCheck:!0})}handleJoinChannel({channel:e}){return"single"===this._mode?this.switchToChannel(e):this.joinAdditionalChannel(e)}onChanged(e){return this.changed(e)}async leave(e={}){const t=X(ii,e),n="string"==typeof t?void 0:t.channel,i="string"==typeof t?t:t.windowId;if(n){const e=this.getAllChannelNames();X(ei(e),n)}const r={channelName:n,windowId:i??this.myWindowId};await this.bridge.send("channels",Ws.leaveChannel,r,void 0,{includeOperationCheck:!0})}async handleAppManagerInitialChannelId(e){if("inMemory"!==this.storage.mode&&!this.storage.getSessionStorageData())return this.handleJoinChannel({channel:e,windowId:this.myWindowId})}async handleLeaveChannel({channelName:e}){const t=e?[e]:this.storage.channels;t.forEach(e=>this.storage.invokeUnsubscribes(e)),this.storage.channels=this.storage.channels.filter(e=>!t.includes(e)),this.executeChangedEvents(),await this.notifyChannelsChanged()}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),clearChannelData:this.clearChannelData.bind(this),setPath:this.setPath.bind(this),setPaths:this.setPaths.bind(this)};return Object.freeze(e)}createContextName(e){return`${Hs}${e}`}getAllChannelNames(){return this.contexts.all().filter(e=>e.startsWith(Hs)).map(e=>e.replace(Hs,""))}async joinAdditionalChannel(e){if(this.storage.channels.includes(e))return;this.storage.channels=[...this.storage.channels,e];const t=this.createContextName(e),n=await this.contexts.subscribe(t,(e,t,n,i,r)=>{this.registry.execute(Us,e.data,e,t,r?.updaterId)});this.storage.addUnsubscribe(e,n),this.executeChangedEvents(e),await this.notifyChannelsChanged()}async switchToChannel(e){const t=this.storage.channels[0];if(e===t)return;this.storage.invokeUnsubscribes(t),this.storage.channels=[e];const n=this.createContextName(e),i=await this.contexts.subscribe(n,(e,t,n,i,r)=>{this.registry.execute(Us,e.data,e,t,r?.updaterId)});this.storage.addUnsubscribe(e,i),this.executeChangedEvents(e),await this.notifyChannelsChanged()}executeChangedEvents(e){this.registry.execute(qs,e),this.registry.execute(Bs,this.storage.channels)}async notifyChannelsChanged(){const e=this.windowsController.my().id;if(e)try{await this.bridge.send("channels",Ws.notifyChannelsChanged,{channelNames:this.storage.channels,windowId:e},void 0,{includeOperationCheck:!0})}catch(e){this.logger.warn(`Failed to notify channel changed: ${Y(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:V,value:i}),await this.contexts.setPaths(n,e)}else i&&(t[V]=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?re.raiseError("FDC3 does not support updating of multiple context keys"):t[0].split("_").slice(1).join("_")}subscribe(e,t){if("function"!=typeof e)return re.raiseError("Cannot subscribe to channels, because the provided callback is not a function!");t&&X(ti,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(Us,i)}async subscribeFor(e,t,n){const i=this.getAllChannelNames();if(X(ei(i),e),"function"!=typeof t)return re.raiseError(`Cannot subscribe to channel ${e}, because the provided callback is not a function!`);n&&X(ti,n);const r=this.createContextName(e),s=n?.contextType?this.getWrappedSubscribeCallbackWithFdc3Type(t,n.contextType):this.getWrappedSubscribeCallback(t);return this.contexts.subscribe(r,(e,t,n,i,r)=>{s(e.data,e,t,r?.updaterId)})}async publish(e,t){if("object"!=typeof e)return re.raiseError("Cannot publish to channel, because the provided data is not an object!");if(X(ni,t),"object"==typeof t)return this.publishWithOptions(e,t);if("string"==typeof t){const e=this.getAllChannelNames();X(ei(e),t)}if(!t&&this.storage.channels.length>1)return this.publishOnMultipleChannels(e);const n="string"==typeof t?t:this.storage.channels[0];if(!n)return re.raiseError("Cannot publish to channel, because not joined to a channel!");return this.isAllowedByRestrictions(n,"write")?this.updateData(n,e):re.raiseError(`Cannot publish on channel ${n} due to restrictions`)}async all(){return this.getAllChannelNames()}async get(e,t){const n=this.getAllChannelNames();X(ei(n),e),t&&X(ti,t);const i=this.createContextName(e),r=await this.contexts.get(i);return t?.contextType?this.getContextForFdc3Type(r,t.contextType):r.latest_fdc3_type?this.getContextWithFdc3Data(r):r}async getMyChannels(e){return Promise.all(this.storage.channels.map(t=>this.get(t,e)))}myChannels(){return this.storage.channels}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.storage.channels[0]}changed(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to channel changed, because the provided callback is not a function!"):this.registry.add(qs,e)}async add(e){const t=X(fi,e);return this.getAllChannelNames().includes(t.name)?re.raiseError("There's an already existing channel with such name"):(await this.bridge.send("channels",Ws.addChannel,t),{name:t.name,meta:t.meta,data:t.data||{}})}async remove(e){X(nt,e);if(!this.getAllChannelNames().includes(e))return re.raiseError("There's no channel with such name");await this.bridge.send("channels",Ws.removeChannel,{name:e},void 0,{includeOperationCheck:!0})}replaySubscribe=(e,t)=>{this.get(t).then(t=>{if(!t)return;const n=this.createContextName(t.name);return this.contexts.subscribe(n,(t,n,i,r,s)=>{e(t.data,t,n,s?.updaterId)})}).then(e=>e?.()).catch(e=>this.logger.trace(e))};async getMy(e){if(this.storage.channels.length)return e&&X(ti,e),this.get(this.storage.channels[this.storage.channels.length-1],e)}async getWindowsOnChannel(e){const t=this.getAllChannelNames();X(ei(t),e);const{windowIds:n}=await this.bridge.send("channels",Ws.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:X(sr,e)}:{},{windowIdsWithChannels:n}=await this.bridge.send("channels",Ws.getWindowIdsWithChannels,t,void 0,{includeOperationCheck:!0});return n.reduce((e,{application:t,channel:n,windowId:i})=>{const r=this.windowsController.findById(i);return r?[...e,{application:t,channel:n,window:r}]:e},[])}async clearChannelData(e){await this.handleSetPaths("clearChannelData",[{path:"data",value:{}},{path:"latest_fdc3_type",value:null}],e)}async restrict(e){X(wi,e);const t=this.getAllChannelNames();X(ei(t),e.name);const n={config:{...e,windowId:e.windowId??this.myWindowId}};await this.bridge.send("channels",Ws.restrict,n,void 0,{includeOperationCheck:!0})}async handleRestrict({config:e}){const t=await this.getMy();if(!t)return this.updateRestriction(e);const n=this.isAllowedByRestrictions(t.name,"read");this.updateRestriction(e);e.name===t.name&&!n&&e.read&&this.replaySubscribeCallback(e.name)}updateRestriction(e){const t=this.storage.restrictions.some(t=>t.name===e.name);this.storage.restrictions=t?this.storage.restrictions.map(t=>t.name===e.name?e:t):this.storage.restrictions.concat(e)}updateAllRestrictions(e){const t=this.getAllChannelNames();this.storage.restrictions=t.map(t=>({name:t,...e}))}async getRestrictions(e){X(rt,e);const t=e&&e!==this.interop.instance.instance;return e&&t?this.bridge.send("channels",Ws.getRestrictions,{windowId:e},void 0,{includeOperationCheck:!0}):{channels:this.storage.restrictions}}async restrictAll(e){X(_i,e);const t={restrictions:{...e,windowId:e.windowId??this.myWindowId}};await this.bridge.send("channels",Ws.restrictAll,t,void 0,{includeOperationCheck:!0})}async handleRestrictAll({restrictions:e}){const t=await this.getMy();if(!t)return void this.updateAllRestrictions(e);const n=this.isAllowedByRestrictions(t.name,"read");this.updateAllRestrictions(e),!n&&e.read&&this.replaySubscribeCallback(t.name)}async setPath(e,t){const n=X(mi,e),i=[{path:`data.${n.path}`,value:n.value}];await this.handleSetPaths("setPath",i,t)}async setPaths(e,t){const n=X(bi,e).map(({path:e,value:t})=>({path:`data.${e}`,value:t}));await this.handleSetPaths("setPaths",n,t)}async handleSetPaths(e,t,n){const i=n?[n]:this.storage.channels;if(!i.length)return re.raiseError(`Cannot complete ${e} operation, because channel is not specified. Either join one or pass a channel name as second argument!`);this.validateChannelNames(i);const{allowed:r,forbidden:s}=this.groupChannelsByPermission("write",i);if(i.length===s.length)return re.raiseError(`Cannot complete ${e} operation due to write restrictions to the following channels: ${i.join(", ")}`);s.length&&this.logger.warn(`Cannot set paths on channel${s.length>1?"s":""}: ${s.join(", ")} due to write restrictions`),await Promise.all(r.map(e=>{const n=this.createContextName(e);return this.contexts.setPaths(n,t)}))}validateChannelNames(e){const t=this.getAllChannelNames();e.forEach(e=>X(ei(t),e))}groupChannelsByPermission(e,t){return t.reduce((t,n)=>(this.isAllowedByRestrictions(n,e)?t.allowed.push(n):t.forbidden.push(n),t),{allowed:[],forbidden:[]})}isAllowedByRestrictions(e,t){const n=this.storage.restrictions.find(t=>t.name===e);return!n||n[t]}replaySubscribeCallback(e){const t=this.createContextName(e);this.contexts.subscribe(t,(e,t,n,i,r)=>{this.registry.execute(Us,e.data,e,t,r?.updaterId)}).then(e=>{e&&"function"==typeof e&&e()}).catch(e=>this.logger.error(e))}async publishWithOptions(e,t){if(t.name){const e=this.getAllChannelNames();X(ei(e),t.name)}if(!t.name&&this.storage.channels.length>1)return this.publishOnMultipleChannels(e,t.fdc3);const n=t.name||this.storage.channels[0];if(!n)return re.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):re.raiseError(`Cannot publish on channel ${n} due to restrictions`)}async publishOnMultipleChannels(e,t){const{allowed:n,forbidden:i}=this.groupChannelsByPermission("write",this.storage.channels);if(this.storage.channels.length===i.length)return re.raiseError(`Cannot complete 'publish' operation due to write restrictions to all joined channels: ${this.storage.channels.join(", ")}`);i.length&&this.logger.warn(`Data on channel${i.length>1?"s":""}: ${i.join(", ")} won't be published due to write restrictions`);const r=t?this.publishFdc3Data.bind(this):this.updateData.bind(this);await Promise.all(n.map(t=>r(t,e)))}async publishFdc3Data(e,t){X(ri,t);const{type:n,...i}=t,r=n.split(".").join("&"),s={[`fdc3_${r}`]:i};return this.updateData(e,s)}getWrappedSubscribeCallback(e){return(t,n,i,r)=>{if(!this.isAllowedByRestrictions(n.name,"read"))return;const{data:s,latest_fdc3_type:o}=n,a=`fdc3_${o}`;if(!o||i.data&&!i.data[a])return void e(t,n,r);const c={type:o.split("&").join("."),...s[a]},{[a]:d,...l}=t;e({...l,fdc3:c},n,r)}}getWrappedSubscribeCallbackWithFdc3Type(e,t){const n={replayed:!1};return(i,r,s,o)=>{if(!this.isAllowedByRestrictions(r.name,"read"))return;const{data:a,latest_fdc3_type:c}=r,d=`fdc3_${t.split(".").join("&")}`;if(!a[d]||s.data&&!s.data[d])return;if(n.replayed)return this.parseDataAndInvokeSubscribeCallback({latestFdc3TypeEncoded:c,searchedType:t,callback:e,context:r,updaterId:o});const l={type:t,...a[d]};e({fdc3:l},r,o),n.replayed=!0}}parseDataAndInvokeSubscribeCallback(e){const{latestFdc3TypeEncoded:t,searchedType:n,callback:i,context:r,updaterId:s}=e;if(t.split("&").join(".")!==n)return;i({fdc3:{type:n,...r.data[`fdc3_${t}`]}},r,s)}async requestChannelSelector(e){if(!e)return;const t=e.application,n=t.userProperties?.details;if(!n)return;if(!n?.channelSelector?.enabled)return;const i={windowId:e.id,channelsNames:this.storage.channels};await this.bridge.send("channels",Ws.requestChannelSelector,i,void 0,{includeOperationCheck:!0})}async getPlatformChannelsMode(){try{return(await this.bridge.send("channels",Ws.getMode,{},void 0,{includeOperationCheck:!0})).mode}catch(e){return this.logger.warn(e?.message||JSON.stringify(e)),"single"}}onChannelsChanged(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to channels changed, because the provided callback is not a function"):this.registry.add(Bs,e)}async initialize(){if(!await this.checkIfAppHelloSupported())return this.handleAppHelloFailure("Platform does not support 'appHello' operation and channel state persistence by windowId. Setting 'sessionStorage' mode for tracking channels and restrictions");const{success:e,error:t}=await this.sendAppHello();if(t)return this.handleAppHelloFailure(t);this.logger.trace(`Received 'appHelloSuccess' message. Setting initial channels state to: ${JSON.stringify(e)}`);const{mode:n,channels:i,restrictions:r}=e;this.storage.mode="inMemory",this._mode=n,this.storage.channels=i,this.storage.restrictions=r}async handleAppHelloFailure(e){this.logger.trace(e),this.storage.mode="sessionStorage",this._mode=await this.getPlatformChannelsMode()}async sendAppHello(){try{return{success:await this.bridge.send("channels",Ws.appHello,{windowId:this.myWindowId},void 0,{includeOperationCheck:!0}),error:void 0}}catch(e){return{error:`Failed to get initial state from platform. Error: ${Y(e)}`,success:void 0}}}async checkIfAppHelloSupported(){try{const{isSupported:e}=await this.bridge.send("channels",Ws.operationCheck,{operation:Ws.appHello.name},void 0,{includeOperationCheck:!0});return e}catch(e){return this.logger.trace(`Platform does not support 'appHello' operation and channel state persistence by windowId. Error: ${Y(e)}`),!1}}}const Vs={getEnvironment:{name:"getEnvironment",resultDecoder:Pt},getBase:{name:"getBase",resultDecoder:Pt},platformShutdown:{name:"platformShutdown"},isFdc3DataWrappingSupported:{name:"isFdc3DataWrappingSupported"},isChannelsMetadataSupported:{name:"isChannelsMetadataSupported"},clientError:{name:"clientError",dataDecoder:Ir},systemHello:{name:"systemHello",resultDecoder:Sr},operationCheck:{name:"operationCheck"}};class Ks{supportedOperationsNames=[];bridge;ioc;logger;errorPort=K.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",Vs.systemHello,void 0,void 0,{includeOperationCheck:!0});n=e.isClientErrorOperationSupported}catch{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",Vs.clientError,{message:e.data},void 0,{includeOperationCheck:!0})},await this.setEnvironment()}async handleBridgeMessage(e){const t=X(ht,e.operation),n=Vs[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=X(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",Vs.getEnvironment,void 0),t=await this.bridge.send("system",Vs.getBase,void 0),n=window.glue42core||window.iobrowser,i=window.glue42core?"glue42core":"iobrowser",r=Object.assign({},n,t,{environment:e});window[i]=r}addOperationsExecutors(){Vs.platformShutdown.execute=this.processPlatformShutdown.bind(this),Vs.isFdc3DataWrappingSupported.execute=this.handleIsFdc3DataWrappingSupported.bind(this),Vs.isChannelsMetadataSupported.execute=this.handleIsChannelsMetadataSupported.bind(this),Vs.operationCheck.execute=async e=>te(this.supportedOperationsNames,e.operation),this.supportedOperationsNames=ee(Vs)}async handleIsFdc3DataWrappingSupported(){return{isSupported:!0}}async handleIsChannelsMetadataSupported(){return{isSupported:!1}}}class Zs{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}}R(T("clientHello"));const Qs={clientHello:{name:"clientHello",resultDecoder:P({widget:P({inject:_()})})}};class Ys{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",Qs.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 Xs{config;glue;registry=ms();glue42EventName="Glue42";_handleMessage;_resolveWidgetReadyPromise;_resolveModalsUIFactoryReadyPromise;_resolveIntentResolverUIFactoryReadyPromise;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)},modalsUIFactoryReady:{name:"modalsUIFactoryReady",handle:this.handleModalsUIFactoryReady.bind(this)},intentResolverUIFactoryReady:{name:"intentResolverUIFactoryReady",handle:this.handleIntentResolverUIFactoryReady.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(){const e=new Promise(e=>{this._resolveWidgetReadyPromise=e});return this.requestWidgetReady(),e}async modalsUIFactoryReady(){const e=new Promise(e=>{this._resolveModalsUIFactoryReadyPromise=e});return this.requestModalsUIFactoryReady(),e}async intentResolverUIFactoryReady(){const e=new Promise(e=>{this._resolveIntentResolverUIFactoryReadyPromise=e});return this.requestIntentResolverUIFactoryReady(),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,r=this.events[i];r&&r.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?.()}requestModalsUIFactoryReady(){this.send("requestModalsUIFactoryReady","glue42")}handleModalsUIFactoryReady(){this._resolveModalsUIFactoryReadyPromise?.()}requestIntentResolverUIFactoryReady(){this.send("requestIntentResolverUIFactoryReady","glue42")}handleIntentResolverUIFactoryReady(){this._resolveIntentResolverUIFactoryReadyPromise?.()}send(e,t,n){const i={};i[t]={event:e,message:n};const r=new CustomEvent(this.glue42EventName,{detail:i});window.dispatchEvent(r)}}class eo{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()===z))return re.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()===z,n=e.type,i=e.args,r=e.transactionId;return n===$.name?this.handleTransportSwitchRequest(i,r):n!==L.name||t?n===U.name?this.handleGetCurrentTransportResponse(i,r):n===q.name?this.handleCheckPreferredLogic(r):n===B.name?this.handleCheckPreferredConnection(i,r):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(H.name);this.sendPlatformMessage(H.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=js(10),i=new Promise((i,r)=>{let s=!0;t.lift=e=>{s=!1,delete this.transactionLocks[n],i(e)},t.fail=e=>{s=!1,delete this.transactionLocks[n],r(e)},setTimeout(()=>{s&&(s=!1,this.logger.warn(`Transaction for operation: ${e} timed out.`),delete this.transactionLocks[n],r(`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(W.name,t,{success:e.success})}).catch(e=>{this.logger.error(e),this.sendPlatformMessage(W.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(G.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(J.name,t,e)}).catch(e=>{this.logger.trace(`The connection to ${n} is not possible`),this.sendPlatformMessage(J.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()}}const to={getCurrent:{name:"getCurrent",resultDecoder:Bi},list:{name:"list",resultDecoder:Gi},select:{name:"select",dataDecoder:Ji}};class no{logger;bridge;registry=ms();themesSubscription;async start(e,t){this.logger=e.logger.subLogger("themes.controller.web"),this.logger.trace("starting the web themes controller"),this.bridge=t.bridge,await this.setupSubscription(),this.logger.trace("themes subscription is ready");const n=this.toApi();e.themes=n,this.logger.trace("themes are ready")}handlePlatformShutdown(){this.registry.clear(),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",to.getCurrent,void 0,void 0,{includeOperationCheck:!0})).theme}async list(){return(await this.bridge.send("themes",to.list,void 0,void 0,{includeOperationCheck:!0})).themes}async select(e){X(nt,e),await this.bridge.send("themes",to.select,{name:e},void 0,{includeOperationCheck:!0})}onChanged(e){return"function"!=typeof e?re.raiseError("onChanged requires a callback of type function"):this.registry.add("on-theme-change",e)}async setupSubscription(){this.themesSubscription=await this.bridge.createThemesSubscription(),this.themesSubscription.onData(this.handleStreamData.bind(this)),this.themesSubscription.onClosed(this.handleStreamClosure.bind(this))}handleStreamData(e){const t=e.data,n=Bi.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)}handleStreamClosure(){this.logger.warn("The Themes interop stream was closed, no theme changes notifications will be received"),this.registry.clear(),delete this.themesSubscription}}class io{sessionStorage=window.sessionStorage;_mode=Js;inMemoryChannels=[];inMemoryRestrictions=[];_unsubscribeDict={};clear(){this._mode=Js,this.inMemoryChannels=[],this.inMemoryRestrictions=[],this._unsubscribeDict={},this.sessionStorage.setItem(Gs,JSON.stringify([]))}get mode(){return this._mode}set mode(e){this._mode=e}get channels(){return"inMemory"===this.mode?this.inMemoryChannels.slice():this.getSessionStorageData()?.channels??[]}set channels(e){"inMemory"===this.mode&&(this.inMemoryChannels=e),this.setSessionStorageChannels(e)}get restrictions(){return"inMemory"===this.mode?this.inMemoryRestrictions.slice():this.getSessionStorageData()?.restrictions??[]}set restrictions(e){"inMemory"===this.mode&&(this.inMemoryRestrictions=e),this.setSessionStorageRestrictions(e)}getSessionStorageData(){return JSON.parse(this.sessionStorage.getItem(Gs)||"null")}addUnsubscribe(e,t){this._unsubscribeDict[e]=t}invokeUnsubscribes(e){if(e)return this._unsubscribeDict[e]?.(),void delete this._unsubscribeDict[e];Object.values(this._unsubscribeDict).forEach(e=>e()),this._unsubscribeDict={}}setSessionStorageChannels(e){const t=this.getSessionStorageData();if(t?.channels)return t.channels=e,this.setSessionStorageData(t);const n={channels:e,restrictions:t?.restrictions??[]};return this.setSessionStorageData(n)}setSessionStorageRestrictions(e){const t=this.getSessionStorageData();if(t?.restrictions)return t.restrictions=e,this.setSessionStorageData(t);const n={channels:t?.channels??[],restrictions:e};return this.setSessionStorageData(n)}setSessionStorageData(e){this.sessionStorage.setItem(Gs,JSON.stringify(e))}}const ro={clear:{name:"clear",dataDecoder:mr},clearAll:{name:"clearAll"},get:{name:"get",dataDecoder:mr,resultDecoder:br},getAll:{name:"getAll",resultDecoder:yr},set:{name:"set",dataDecoder:vr},update:{name:"update",dataDecoder:vr},prefsChanged:{name:"prefsChanged",dataDecoder:br},prefsHello:{name:"prefsHello",resultDecoder:Cr},operationCheck:{name:"operationCheck"},registerSubscriber:{name:"registerSubscriber",dataDecoder:wr}};class so{supportedOperationsNames=[];bridge;config;logger;appManagerController;platformAppName;registry=ms();validNonExistentApps;signaledSubscription=!1;interopId;isAppValidationEnabled;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.interopId=e.interop.instance.instance,this.bridge=t.bridge,this.config=t.config,this.appManagerController=t.appManagerController;try{const e=await this.bridge.send("prefs",ro.prefsHello,void 0,void 0,{includeOperationCheck:!0});this.platformAppName=e.platform.app,this.validNonExistentApps=e.validNonExistentApps??[],this.isAppValidationEnabled=e.isAppValidationEnabled??!0}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=X(gr,e.operation),n=ro[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=X(n.dataDecoder,e.data)),await n.execute(i)}async get(e){const t=null==e?this.getMyAppName():X(nt,e),{prefs:n}=await this.bridge.send("prefs",ro.get,{app:t},void 0,{includeOperationCheck:!0});return n}async update(e,t){const n=X(O(mr),t),i=n?.app??this.getMyAppName();await this.updateFor(i,e)}addOperationsExecutors(){ro.prefsChanged.execute=this.handleOnChanged.bind(this),ro.operationCheck.execute=async e=>te(this.supportedOperationsNames,e.operation),this.supportedOperationsNames=ee(ro)}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",ro.clearAll,void 0,void 0,{includeOperationCheck:!0})}async clearFor(e){const t=X(nt,e);await this.bridge.send("prefs",ro.clear,{app:t},void 0,{includeOperationCheck:!0})}async getAll(){return await this.bridge.send("prefs",ro.getAll,void 0,void 0,{includeOperationCheck:!0})}async set(e,t){const n=X(O(mr),t),i=n?.app??this.getMyAppName();await this.setFor(i,e)}async setFor(e,t){const n=X(nt,e),i=X(P(),t);await this.bridge.send("prefs",ro.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=X(nt,e),i=this.appManagerController.getApplications();if(!(!this.isAppValidationEnabled||(n===this.platformAppName||i.some(e=>e.name===n)||this.validNonExistentApps.includes(n))))return re.raiseError(`The provided app name "${e}" is not valid.`);if("function"!=typeof t)return re.raiseError("Cannot subscribe to prefs, because the provided callback is not a function!");this.signaledSubscription||(this.bridge.send("prefs",ro.registerSubscriber,{interopId:this.interopId,appName:n},void 0,{includeOperationCheck:!0}).catch(e=>{this.logger.warn("Failed to register subscriber for prefs"),this.logger.error(e)}),this.signaledSubscription=!0);const r=this.getSubscriptionKey(n);return this.get(n).then(t),this.registry.add(r,t)}async updateFor(e,t){const n=X(nt,e),i=X(P(),t);await this.bridge.send("prefs",ro.update,{app:n,data:i},void 0,{includeOperationCheck:!0})}getMyAppName(){const e=this.config.isPlatformInternal?this.platformAppName:this.appManagerController.me?.application.name;return e||re.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)}}const oo={getResources:{name:"getResources",dataDecoder:Lr,resultDecoder:Br},operationCheck:{name:"operationCheck",dataDecoder:Hi,resultDecoder:Wi},showAlert:{name:"showAlert",dataDecoder:Kr},showDialog:{name:"showDialog",dataDecoder:Yr},alertInteropAction:{name:"alertInteropAction",dataDecoder:rs},showResolver:{name:"showResolver",dataDecoder:us,resultDecoder:ps}},ao="io-modals-shadow-host",co="io-widget-shadow-host",lo="io-intent-resolver-shadow-host";class ho{ioc;supportedOperationsNames=[];logger;bridge;config;zIndexDictionary={[co]:"100",[ao]:"101",[lo]:"100"};widgetResources;modalsResources;intentResolverResources;rootElements=[];modalsUiApi;isDialogOpen=!1;intentResolverUiApi;isIntentResolverOpen=!1;constructor(e){this.ioc=e}async start(e,t){this.logger=e.logger.subLogger("ui.controller.web"),this.logger.trace("starting the ui controller"),this.bridge=t.bridge,this.config=t.config,this.addOperationsExecutors();const n=await this.getResources();n?(this.logger.trace(`Received UI resources from platform: ${JSON.stringify(n)}`),this.setResources(n)):this.logger.trace("No UI elements to display - platform is not initialized with any UI resources")}async handleBridgeMessage(e){const t=X(Fr,e.operation),n=oo[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=X(n.dataDecoder,e.data)),await n.execute(i)}async showComponents(e){const t=this.widgetResources?this.initializeWidget(e,this.widgetResources):Promise.resolve(),n=this.modalsResources?this.initializeModalsUi(e,this.modalsResources):Promise.resolve(),i=this.intentResolverResources?this.initializeIntentResolverUI(e,this.intentResolverResources):Promise.resolve();this.subscribeForThemeChanges(e),await Promise.all([this.config.widget.awaitFactory?t:Promise.resolve(),this.config.modals.awaitFactory?n:Promise.resolve(),this.config.intentResolver.awaitFactory?i:Promise.resolve()])}isIntentResolverEnabled(){return!!this.intentResolverResources&&this.config.intentResolver.enable}addOperationsExecutors(){oo.operationCheck.execute=async e=>te(this.supportedOperationsNames,e.operation),oo.showAlert.execute=this.handleShowAlert.bind(this),oo.showDialog.execute=this.handleShowDialog.bind(this),oo.showResolver.execute=this.handleShowResolver.bind(this),this.supportedOperationsNames=ee(oo)}async handleShowAlert({config:e}){if(!this.config.modals.alerts.enabled)return re.raiseError("Unable to perform showAlert operation because the client was initialized with 'modals: { alerts: { enabled: false } }' config.");const t=this.modalsUiApi;if(!t)return re.raiseError("Unable to perform showAlert operation because modalsUiApi is missing.");const{promise:n,resolve:i}=ie(),r=e=>{const t=is.run(e);if(!t.ok)return void this.logger.error(`alert.onClick() was invoked with an invalid config. Error: ${JSON.stringify(t.error)}.`);const{interopAction:n}=t.result;this.bridge.send("ui",oo.alertInteropAction,{interopAction:n},void 0,{includeOperationCheck:!0}).catch(e=>this.logger.warn(Y(e)))};let s;try{this.logger.trace(`Open alert with config: ${JSON.stringify(e)}`),s=t.alerts.open({...e,onClick:r,onClose:i})}catch(e){return re.raiseError(`modalsUiApi.alerts.open() failed. Reason: ${Y(e)}.`)}const o=Xr.run(s);if(!o.ok)return re.raiseError(`modalsUiApi.alerts.open() returned an invalid result. Error: ${JSON.stringify(o.error)}.`);const a=setTimeout(()=>{i()},ne(e.ttl??5e3));n.then(()=>{clearTimeout(a);try{t.alerts.close({id:o.result.id})}catch(e){this.logger.warn(`Failed to close alert with id ${o.result.id}. Reason: ${Y(e)}`)}})}async handleShowDialog({config:e}){if(!this.config.modals.dialogs.enabled)return re.raiseError("Unable to perform showDialog operation because the client was initialized with 'modals: { dialogs: { enabled: false } }' config.");const t=this.modalsUiApi;if(!t)return re.raiseError("Unable to perform showDialog operation because modalsUiApi is missing.");if(this.isDialogOpen)return re.raiseError("Cannot open a dialog because another one is already open.");const{promise:n,resolve:i}=ie();let r;try{this.logger.trace(`Open dialog with config: ${JSON.stringify(e)}`),r=t.dialogs.open({...e,onCompletion:i})}catch(e){return re.raiseError(`modalsUiApi.dialogs.open() failed. Reason: ${Y(e)}.`)}const s=es.run(r);if(!s.ok)return re.raiseError(`modalsUiApi.dialogs.open() returned an invalid result. Error: ${JSON.stringify(s.error)}.`);let o;this.isDialogOpen=!0,e.timer&&(o=setTimeout(()=>{i({response:{isExpired:!0}})},ne(e.timer.duration)));const a=await n;clearTimeout(o),this.isDialogOpen=!1;try{t.dialogs.close({id:s.result.id})}catch(e){this.logger.warn(`Failed to close dialog with id ${s.result.id}. Reason: ${Y(e)}`)}const c=ts.run(a);return c.ok?{result:c.result.response}:re.raiseError(`completionPromise was resolved with an invalid result. Error: ${JSON.stringify(c.error)}.`)}async handleShowResolver({config:e}){if(this.logger.trace(`Received open intent resolver request with config: ${JSON.stringify(e)}`),!this.config.intentResolver.enable)return re.raiseError("Unable to perform showResolver operation because the client was initialized with 'intentResolver: { enable: false }' config.");const t=this.intentResolverUiApi;if(!t)return re.raiseError("Unable to perform showResolver operation because intentResolverApi is missing.");if(this.isIntentResolverOpen)return re.raiseError("Cannot open the intent resolver because another one is already open.");const{promise:n,resolve:i}=ie();let r;try{this.logger.trace(`Open intent resolver with config: ${JSON.stringify(e)}`),r=t.open({...e,onUserResponse:i})}catch(e){return re.raiseError(`intentResolverUI.open() failed. Reason: ${Y(e)}.`)}const s=os.run(r);if(!s.ok)return re.raiseError(`intentResolverUI.open() returned an invalid result. Error: ${JSON.stringify(s.error)}.`);const o=setTimeout(()=>i({response:{isExpired:!0}}),ne(e.timeout)),a=await n;clearTimeout(o),this.isIntentResolverOpen=!1;try{t.close({id:s.result.id})}catch(e){this.logger.warn(`Failed to close intent resolver with id ${s.result.id}. Reason: ${Y(e)}`)}const c=ls.run(a);return c.ok?{result:c.result.response}:re.raiseError(`completionPromise was resolved with an invalid result. Error: ${JSON.stringify(c.error)}.`)}async getResources(){const e={origin:window.origin};try{return(await this.bridge.send("ui",oo.getResources,e,void 0,{includeOperationCheck:!0})).resources}catch(e){this.logger.warn(e?.message||JSON.stringify(e))}}appendModalsResources(e){return this.logger.trace("Appending modals resources"),this.appendResources(ao,"io-modals-root",e.sources)}appendWidgetResources(e){return this.logger.trace("Appending widget resources"),this.appendResources(co,"io-widget-root",e.sources)}appendIntentResolverResources(e){return this.logger.trace("Appending intent resolver resources"),this.appendResources(lo,"io-intent-resolver-root",e.sources)}appendResources(e,t,n){const{bundle:i,fonts:r=[],styles:s}=n,o=document.createElement("div");o.id=e,o.style.position="fixed",o.style.zIndex=this.zIndexDictionary[e];const a=o.attachShadow({mode:"open"}),c=document.createElement("script");c.src=i,c.type="module",a.appendChild(c);const d=document.createElement("div");return d.id=t,d.className="io-body io-variables",a.appendChild(d),s.forEach(e=>{const t=document.createElement("link");t.rel="stylesheet",t.href=e,a.appendChild(t)}),r.forEach(e=>{const t=document.createElement("link");t.rel="stylesheet",t.href=e,document.head.insertBefore(t,document.head.firstChild)}),document.body.appendChild(o),{rootElement:d}}async initializeWidget(e,t){this.logger.trace("Initializing IOBrowserWidget.");const{rootElement:n}=this.appendWidgetResources(t);this.rootElements.push(n);const i={...d(t.config,this.config.widget),rootElement:n};return vs(async()=>{await this.ioc.eventsDispatcher.widgetReady(),this.logger.trace(`IOBrowserWidget factory is available. Invoking it with config: ${JSON.stringify(i)}`),await window.IOBrowserWidget(e,i),this.logger.trace("IOBrowserWidget was initialized successfully.")},i.timeout,`Timeout of ${i.timeout}ms hit waiting for IOBrowserWidget to initialize.`)}async initializeModalsUi(e,t){this.logger.trace("Initializing IOBrowserModalsUI.");const{rootElement:n}=this.appendModalsResources(t);this.rootElements.push(n);const i={...this.config.modals,rootElement:n};return vs(async()=>{await this.ioc.eventsDispatcher.modalsUIFactoryReady(),this.logger.trace(`IOBrowserModalsUI factory is available. Invoking it with config: ${JSON.stringify(i)}`),this.modalsUiApi=await window.IOBrowserModalsUI(e,i),this.logger.trace("IOBrowserModalsUI was initialized successfully.")},i.timeout,`Timeout of ${i.timeout}ms hit waiting for IOBrowserModalsUI to initialize.`)}async initializeIntentResolverUI(e,t){this.logger.trace("Initializing IOBrowserIntentResolverUI.");const{rootElement:n}=this.appendIntentResolverResources(t);this.rootElements.push(n);const i={...this.config.intentResolver,rootElement:n},r=i.timeout;return vs(async()=>{await this.ioc.eventsDispatcher.intentResolverUIFactoryReady(),this.logger.trace(`IOBrowserIntentResolverUI factory is available. Invoking it with config: ${JSON.stringify(i)}`),this.intentResolverUiApi=await window.IOBrowserIntentResolverUI(e,i),this.logger.trace("IOBrowserIntentResolverUI initialized successfully.")},r,`Timeout of ${r}ms hit waiting for IOBrowserIntentResolverUI to initialize.`)}setResources(e){this.setWidgetResources(e.widget),this.setModalsUiResources(e.modals),this.setIntentResolverResources(e.intentResolver)}setWidgetResources(e){const t="Widget won't be displayed. Reason: ",n=jr.run(this.config.widget);n.ok?this.config.widget.enable?e?e.blockedOrigin?this.logger.warn(`${t} Platform has blocked client's origin ('${window.location.toString()}') from retrieving widget resources`):this.widgetResources=e:this.logger.trace(`${t} Platform did not provide resources`):this.logger.trace(`${t} Client initialized with 'widget: { enable: false }' config`):this.logger.warn(`${t} invalid widget config. Error: ${n.error}`)}setModalsUiResources(e){const t="Modals won't be displayed. Reason: ",n=Nr.run(this.config.modals);n.ok?this.config.modals.alerts.enabled||this.config.modals.dialogs.enabled?e?e.blockedOrigin?this.logger.warn(`${t} Platform has blocked client's origin ('${window.location.toString()}') from retrieving modals resources`):this.modalsResources=e:this.logger.trace(`${t} Platform did not provide resources`):this.logger.trace(`${t} Client initialized with 'modals: { alerts: { enabled: false }, dialogs: { enabled: false } }' config`):this.logger.warn(`${t} invalid modals config. Error: ${n.error}`)}setIntentResolverResources(e){const t="Intent Resolver UI won't be displayed. Reason: ",n=ss.run(this.config.intentResolver);n.ok?this.config.intentResolver.enable?e?e.blockedOrigin?this.logger.warn(`${t} Platform has blocked client's origin ('${window.location.toString()}') from retrieving intent resolver resources`):this.intentResolverResources=e:this.logger.trace(`${t} Platform did not provide resources`):this.logger.trace(`${t} Client initialized with 'intentResolver: { enable: false }' config`):this.logger.warn(`${t} invalid intent resolver config. Error: ${JSON.stringify(n.error)}`)}subscribeForThemeChanges(e){const t=e.themes;if(!t)return;const n=async e=>{await Promise.all(this.rootElements.map(n=>this.applyThemeToElement(n,t,e)))};t.onChanged(n),t.getCurrent().then(n)}async applyThemeToElement(e,t,n){if(e.classList.contains(n.name))return;const i=await t.list();e.classList.remove(...i.map(({name:e})=>e)),e.classList.add(n.name)}}class uo{_coreGlue;_communicationId;_publicWindowId;_webConfig;_windowsControllerInstance;_appManagerControllerInstance;_layoutsControllerInstance;_notificationsControllerInstance;_intentsControllerInstance;_channelsControllerInstance;_themesControllerInstance;_extensionController;_systemControllerInstance;_bridgeInstance;_eventsDispatcher;_preferredConnectionController;_channelsStorage;_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 Is),this._windowsControllerInstance}get uiController(){return this._uiController||(this._uiController=new ho(this)),this._uiController}get appManagerController(){return this._appManagerControllerInstance||(this._appManagerControllerInstance=new Os),this._appManagerControllerInstance}get layoutsController(){return this._layoutsControllerInstance||(this._layoutsControllerInstance=new Es),this._layoutsControllerInstance}get themesController(){return this._themesControllerInstance||(this._themesControllerInstance=new no),this._themesControllerInstance}get notificationsController(){return this._notificationsControllerInstance||(this._notificationsControllerInstance=new Ns),this._notificationsControllerInstance}get intentsController(){return this._intentsControllerInstance||(this._intentsControllerInstance=new $s),this._intentsControllerInstance}get systemController(){return this._systemControllerInstance||(this._systemControllerInstance=new Ks),this._systemControllerInstance}get channelsController(){return this._channelsControllerInstance||(this._channelsControllerInstance=new zs),this._channelsControllerInstance}get prefsController(){return this._prefsControllerInstance||(this._prefsControllerInstance=new so),this._prefsControllerInstance}get extensionController(){return this._extensionController||(this._extensionController=new Ys),this._extensionController}get eventsDispatcher(){return this._eventsDispatcher||(this._eventsDispatcher=new Xs(this.config)),this._eventsDispatcher}get bridge(){return this._bridgeInstance||(this._bridgeInstance=new Ps(this._coreGlue,this.communicationId)),this._bridgeInstance}get preferredConnectionController(){return this._preferredConnectionController||(this._preferredConnectionController=new eo(this._coreGlue)),this._preferredConnectionController}get channelsStorage(){return this._channelsStorage||(this._channelsStorage=new io),this._channelsStorage}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,n){const i=new ys(e,t,this.bridge,n),r=await i.toApi();return{id:e,model:i,api:r}}buildNotification(e,t){return new Zs(e,t)}async buildApplication(e,t){const n=new As(e,[],this.appManagerController).toApi(),i=t.map(e=>this.buildInstance(e,n));return n.instances.push(...i),n}buildInstance(e,t){return new Rs(e,this.bridge,t).toApi()}}var po="4.6.0";const go=(e,t)=>({getContainerInfo:async()=>{if(window!==window.parent)return window.name.includes("#wsp")?{workspaceFrame:{id:"N/A"}}:window.parent===window.top?{top:{}}:{parent:{}}},getProfileData:async()=>{if(!t)throw new Error("Bridge is not available and cannot fetch the profile data");return await t.send("system",{name:"getProfileData"},void 0)}});var fo=1,mo=2,bo=3,yo=4;function wo(e){return e.type===bo?"timestamp":e.type===mo?"number":e.type===fo?"string":e.type===yo?"object":"unknown"}function vo(e){return e.constructor===Date?"timestamp":"number"==typeof e?"number":"string"==typeof e?"string":"object"==typeof e?"object":"string"}function Co(e){const t={},n=wo(e);if("object"===n){const n=Object.keys(e.value).reduce((t,n)=>{const i=vo(e.value[n]);if("object"===i){const i=Io(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=So(e.path.join("/")+"/"+e.name),t.type=n,t.description=e.description,t.context={},t}function Io(e){return Object.keys(e).reduce((t,n)=>{const i=vo(e[n]);return t[n]="object"===i?{type:"object",description:"",context:{},composite:Io(e[n])}:{type:i,description:"",context:{}},t},{})}function So(e){return void 0!==e&&e.length>0&&"/"!==e[0]?"/"+e:e}function _o(e){return"timestamp"===wo(e)?Date.now():xo(e.value)}function xo(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]=xo(i):i.constructor===Date?t[n]=new Date(i).getTime():i.constructor===Boolean?t[n]=i.toString():t[n]=i,t},{})}function To(e){return e.reduce((e,t)=>e.concat(Array.isArray(t)?To(t):t),[])}function Po(e){const t=To(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 r=e.path.join(".");n===i.length-1?t+=r+"."+e.name+": "+e.description:t+=r+"."+e.name+": "+e.description+","}),t.length>100?t.slice(0,100)+"...":t}(t);return{description:i,value:n.state}}var ko=(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 Oo{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,r){this.definition=e,this.system=t,this.transport=n,this.value=i,this.type=r,ko(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 Ro extends Oo{constructor(e,t,n,i){super(e,t,n,i,mo)}incrementBy(e){this.update(this.value+e)}increment(){this.incrementBy(1)}decrement(){this.incrementBy(-1)}decrementBy(e){this.incrementBy(-1*e)}}class Ao extends Oo{constructor(e,t,n,i){super(e,t,n,i,yo)}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 Mo extends Oo{constructor(e,t,n,i){super(e,t,n,i,fo)}}class Eo extends Oo{constructor(e,t,n,i){super(e,t,n,i,bo)}now(){this.update(new Date)}}function Do(e,t,n,i,r){if(!t)throw new Error("Repository is required");if(!n)throw new Error("Transport is required");const s=n,o=e,a=r||"",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 f=t.root,m=[],b=[];function y(e,t,n,i){let r={name:""};r="string"==typeof e?{name:e}:e;const s=b.filter(e=>e.name===r.name);if(s.length>0){const e=s[0];if(e.type!==t)throw new Error(`A metric named ${r.name} is already defined with different type.`);return void 0!==n&&e.update(n).catch(()=>{}),e}const o=i(r);return b.push(o),o}const w={get name(){return o},get description(){return a},get repo(){return c},get parent(){return d},path:l,id:u,root:f,get subSystems(){return m},get metrics(){return b},subSystem:function(e,t){if(!e||0===e.length)throw new Error("name is required");const n=m.filter(t=>t.name===e);if(n.length>0)return n[0];const i=Do(e,c,s,w,t);return m.push(i),i},getState:()=>h,setState:function(e,t){h={state:e,description:t},s.updateSystem(w,h)},stringMetric:function(e,t){return y(e,fo,t,e=>new Mo(e,w,s,t))},timestampMetric:function(e,t){return y(e,bo,t,e=>new Eo(e,w,s,t))},objectMetric:function(e,t){return y(e,yo,t,e=>new Ao(e,w,s,t))},numberMetric:function(e,t){return y(e,mo,t,e=>new Ro(e,w,s,t))},getAggregateState:function(){const e=[];return Object.keys(h).length>0&&e.push({name:o,path:l,state:h.state,description:h.description}),m.forEach(t=>{const n=t.getAggregateState();n.length>0&&e.push(...n)}),e}};return s.createSystem(w),w}class jo{root;constructor(e,t){t.init(this),this.root=Do("",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 No{init(e){}createSystem(e){return Promise.resolve()}updateSystem(e,t){return Promise.resolve()}createMetric(e){return Promise.resolve()}updateMetric(e){return Promise.resolve()}}class Fo{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;if(!e||!e.memory)return;const t=e.memory;this.system.stringMetric("memory",JSON.stringify({totalJSHeapSize:t.totalJSHeapSize,usedJSHeapSize:t.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 Lo=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 r=e=>{s(e.root)},s=e=>{o(e),e.metrics.forEach(e=>{a(e)}),e.subSystems.forEach(e=>{s(e)})},o=async e=>{if(void 0===e.parent)return;await n;const r={type:"define",metrics:[{name:So(e.path.join("/")+"/"+e.name+"/State"),type:"object",composite:{Description:{type:"string",description:""},Value:{type:"number",description:""}},description:"System state",context:{}}]};i.sendFireAndForget(r).catch(n=>{t.logger.warn(`Failed to send define for system state metric of ${e.name}: ${JSON.stringify(n)}`)})},a=async e=>{const r=d(e);await n;const s={type:"define",metrics:[Co(r)]};i.sendFireAndForget(s).catch(n=>{t.logger.warn(`Failed to send define for metric ${e.name}: ${JSON.stringify(n)}`)}),void 0!==r.value&&c(r)},c=e=>{if(l()){const n=_o(e),r={type:"publish",values:[{name:So(e.path.join("/")+"/"+e.name),value:n,timestamp:Date.now()}]};return i.sendFireAndForget(r).catch(n=>{t.logger.warn(`Failed to publish metric ${e.name}: ${JSON.stringify(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:s=>{let o;n=new Promise(e=>{o=e}),i=e.domain("metrics"),i.onJoined(e=>{!e&&o&&(o(),o=void 0);const n={type:"define",metrics:[{name:"/State",type:"object",composite:{Description:{type:"string",description:""},Value:{type:"number",description:""}},description:"System state",context:{}}]};i.sendFireAndForget(n).catch(e=>{t.logger.warn(`Failed to send define for root state metric: ${JSON.stringify(e)}`)}),e&&r(s)}),i.join({system:t.system,service:t.service,instance:t.instance})},createSystem:o,updateSystem:async(r,s)=>{await n;const o={type:"publish",values:[{name:So(r.path.join("/")+"/"+r.name+"/State"),value:{Description:s.description,Value:s.state},timestamp:Date.now()}]};i.sendFireAndForget(o).catch(e=>{t.logger.warn(`Failed to send update for system state metric of ${r.name}: ${JSON.stringify(e)}`)});const a=Po(r),c={type:"publish",peer_id:e.peerId,values:[{name:"/State",value:{Description:a.description,Value:a.value},timestamp:Date.now()}]};i.sendFireAndForget(c).catch(e=>{t.logger.warn(`Failed to send update for root state metric of ${r.name}: ${JSON.stringify(e)}`)})},createMetric:a,updateMetric:async e=>{const t=d(e);await n,c(t)}}}(e.connection,e):new No;let n=new jo(e,t).root;e.disableAutoAppSystem||(n=n.subSystem("App"));const i=function(e){const t=e.subSystem("reporting"),n={name:"features"};let i;const r=(e,r,s)=>{if(void 0===e||""===e)throw new Error("name is mandatory");if(void 0===r||""===r)throw new Error("action is mandatory");if(void 0===s||""===s)throw new Error("payload is mandatory");i?i.update({name:e,action:r,payload:s}):i=t.objectMetric(n,{name:e,action:r,payload:s})};return e.featureMetric=r,e}(n);return function(e,t){if("undefined"==typeof window)return;const n=window?.glue42gd?.metrics?.pagePerformanceMetrics;n&&(t=n);t?.enabled&&new Fo(e,t.initialPublishTimeout,t.publishInterval)}(i,e.pagePerformanceMetrics),i};var $o,Wo,Ho="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Uo(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var qo=function(){if(Wo)return $o;function e(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 r=n instanceof Error?n:new Error(n);if(t)t(r);else{var s='[ERROR] callback-registry: User callback for key "'+i+'" failed: '+r.stack;if(e)switch(e.errorHandling){case"log":return console.error(s);case"silent":return;case"throw":throw new Error(s)}console.error(s)}}return{add:function(e,t,r){var s=n[e];return s||(s=[],n[e]=s),s.push(t),r&&setTimeout(function(){r.forEach(function(r){var s;if(null===(s=n[e])||void 0===s?void 0:s.includes(t))try{Array.isArray(r)?t.apply(void 0,r):t.apply(void 0,[r])}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=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];var s=n[e];if(!s||0===s.length)return[];var o=[];return s.forEach(function(n){try{var r=n.apply(void 0,t);o.push(r)}catch(t){o.push(void 0),i(t,e)}}),o},clear:function(){n={}},clearKey:function(e){n[e]&&delete n[e]}}}return Wo=1,e.default=e,$o=e}(),Bo=Uo(qo);class Go{gw;registry=Bo();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 Jo{logger;worker;registry=Bo();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 zo{static isNode(){if(void 0!==zo._isNode)return zo._isNode;if("undefined"!=typeof window)return zo._isNode=!1,!1;try{zo._isNode="[object process]"===Object.prototype.toString.call(global.process)}catch(e){zo._isNode=!1}return zo._isNode}static _isNode;static getMethodName(e){return"string"==typeof e?e:e?.name}}class Vo{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 Ko={};function Zo(e){const t=Ko[e];if(t)return t;const n=[];function i(){return(new Date).getTime()}const r=i();let s,o;function a(e,t){const r=t??i();let s=0;n.length>0&&(s=r-n[n.length-1].time),n.push({name:e,time:r,diff:s})}a("start",r);const c={get startTime(){return r},get endTime(){return s},get period(){return o},stop:function(){return s=i(),a("end",s),o=s-r,o},mark:a,marks:n};return Ko[e]=c,c}const Qo=zo.isNode()?null:window.WebSocket;function Yo(e,t,n,i){const r=!1!==i?.includeStack,s=e instanceof Error?e:e?.error;return s instanceof Error?JSON.stringify({name:s.name,message:s.message,code:s.code,stack:r?s.stack:void 0}):JSON.stringify({type:e?.type,readyState:t?.readyState,url:n,message:"string"==typeof e?.message?e.message:void 0})}class Xo{ws;logger;settings;startupTimer=Zo("connection");_running=!0;_registry=Bo();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 Vo;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){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);try{await this.initiateSocket(),this.startupTimer.mark("socket-initiated"),this.notifyForSocketState()}catch{if(void 0!==t&&t<=0)return void this.notifyForSocketState(`wait for socket on ${this.settings.ws} failed - no more retries left`);void 0!==t&&this.logger.debug(`will retry ${t-1} more times (every ${e} ms)`),setTimeout(()=>{const n=void 0===t?void 0:t-1;this.openSocket(e,n)},e)}}initiateSocket(){const e=new Vo;this.logger.debug(`initiating ws to ${this.settings.ws}...`),this.ws=new Qo(this.settings.ws??"");let t=!1;return this.ws.onerror=n=>{const i=Yo(n,this.ws,this.settings.ws);this.logger.info(`ws error - ${i}`),e.reject("error"),t&&(t=!1,this.notifyForSocketState("error"));const r=Yo(n,this.ws,this.settings.ws,{includeStack:!1});this.notifyStatusChanged(!1,r)},this.ws.onclose=n=>{var i;this.logger.info("ws closed - "+(i=n,`code: ${i?.code} reason: ${i?.reason||"(none)"} wasClean: ${i?.wasClean}`)),e.reject("closed"),t&&(t=!1,this.notifyForSocketState("closed")),this.notifyStatusChanged(!1)},this.ws.onopen=()=>{this.startupTimer.mark("ws-opened"),this.logger.info(`ws opened ${this.settings.identity?.application}`),e.resolve(),t=!0,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 ea{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 ta=(e=21)=>{let t="",n=0|e;for(;n--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return t};const na=(e,t,n)=>new Promise((i,r)=>{const s=setTimeout(()=>{r(n||`Promise timeout hit: ${t}`)},t);new Promise(e).then(e=>{clearTimeout(s),i(e)}).catch(e=>{clearTimeout(s),r(e)})});class ia{settings;logger;identity;isPreferredActivated;_connectionProtocolVersion;_communicationId;publicWindowId;selfAssignedWindowId;iAmConnected=!1;parentReady=!1;rejected=!1;parentPingResolve;parentPingInterval;connectionResolve;extConnectionResolve;extConnectionReject;connectionReject;port;myClientId;extContentAvailable=!1;extContentConnecting=!1;extContentConnected=!1;parentWindowId;parentInExtMode=!1;webNamespace="g42_core_web";parent;parentType;parentPingTimeout=5e3;connectionRequestTimeout=7e3;defaultTargetString="*";registry=Bo();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:()=>{}},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},window.origin);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(){this.logger.debug(`closing connection - clientId: ${this.myClientId}, windowId: ${this.identity?.windowId||"unknown"}, client connected: ${this.iAmConnected}`);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 na((t,n)=>{this.connectionResolve=t,this.connectionReject=n,this.myClientId=this.myClientId??ta(10);const i=this.getMyWindowId()||ta(10),r={glue42core:{type:this.messages.connectionRequest.name,clientId:this.myClientId,clientType:"child",bridgeInstanceId:i,selfAssignedWindowId:this.selfAssignedWindowId}};if(this.logger.debug(`sending connection request - clientId: ${this.myClientId}`),this.extContentConnecting)return r.glue42core.clientType="child",r.glue42core.bridgeInstanceId=this.myClientId,r.glue42core.parentWindowId=this.parentWindowId,window.postMessage(r,window.origin);if(!e)throw new Error("Cannot send a connection request, because no glue target was specified!");e.postMessage(r,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"):(this.logger.debug("setting up window message listener"),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"):(this.logger.debug("setting up unload event listeners"),window.addEventListener("beforeunload",()=>{this._connectionProtocolVersion||this.signalClientDisappearing()}),window.addEventListener("pagehide",()=>{this._connectionProtocolVersion&&this.signalClientDisappearing()}))}signalClientDisappearing(){if(this.extContentConnected)return;this.logger.debug(`signaling client disappearing for clientId: ${this.myClientId}`);const e={glue42core:{type:this.messages.clientUnload.name,data:{clientId:this.myClientId,ownWindowId:this.identity?.windowId}}};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.logger?.debug(`ignoring a connection accepted signal, because it is not targeted at me. My id: ${this.myClientId}, the id in the message: ${t.clientId}`):this.handleAcceptanceOfMyRequest(t)}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._connectionProtocolVersion=e.connectionProtocolVersion,this.publicWindowId=this.getMyWindowId(),this.identity&&(this.identity.windowId=this.publicWindowId,this.identity.instance=this.identity.instance?this.identity.instance:this.publicWindowId||ta(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}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(){this.extContentConnecting&&this.logger.debug("This connection request event is targeted at the extension content")}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.logger.debug("setting up platform unload listener"),this.onMessage(e=>{"platformUnload"===e.type&&(this.logger.debug("detected a web platform unload"),this.parentReady=!1,this.notifyStatusChanged(!1,"Gateway unloaded"))})}handleManualUnload(){this.logger.debug("handling manual unload");const e={glue42core:{type:this.messages.clientUnload.name,data:{clientId:this.myClientId,ownWindowId:this.identity?.windowId}}};if(this.extContentConnected)return window.postMessage({glue42ExtOut:e},window.origin);this.port?.postMessage(e)}handlePlatformPing(){}notifyStatusChanged(e,t){this.logger.debug(`status changed - connected: ${e}, reason: ${t||"none"}`),this.iAmConnected=e,this.registry.execute("onConnectedChanged",e,t)}checkMessageTypeValid(e){return"string"==typeof e&&!!this.messages[e]}requestConnectionPermissionFromExt(){return this.waitForContentScript().then(()=>na((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"}},window.origin)},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():na(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=na(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(){if("workspace"===this.parentType)return window.name.substring(0,window.name.indexOf("#wsp"));if(window!==window.top){const e=window.name.indexOf("#ifr");return-1!==e?window.name.substring(0,e):void 0}return window.name?.includes("g42")?window.name:(this.selfAssignedWindowId=this.selfAssignedWindowId||`g42-${ta(10)}`,this.selfAssignedWindowId)}}class ra{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 sa(e){if(e instanceof Error)return e;if("string"==typeof e)return new Error(e);const t=e,n="string"==typeof t?.message?t.message:void 0,i="string"==typeof t?.reason?t.reason:void 0;return void 0!==n&&n.length>0?new Error(n):void 0!==i&&i.length>0?new Error(i):""===n||""===i?new Error(""):new Error(aa(e))}function oa(e){try{if(e instanceof Error){if("string"==typeof e.stack)return e.stack;if("string"==typeof e.message){return`${"string"==typeof e.name&&e.name.length>0?e.name:"Error"}: ${e.message}`}}if("string"==typeof e)return e}catch{}return aa(e)}function aa(e){try{const t=new WeakSet,n=JSON.stringify(e,(e,n)=>{if("bigint"==typeof n)return`${n.toString()}n`;if("function"==typeof n)return"[Function]";if("symbol"==typeof n)return n.toString();if("object"==typeof n&&null!==n){if(t.has(n))return"[Circular]";t.add(n)}return n});if(void 0!==n)return n}catch{}if(null!==e&&"object"==typeof e){const t=e.constructor?.name??"Object";let n=[];try{n=Object.keys(e)}catch{}return n.length>0?`[${t} keys=${n.join(",")}]`:`[${t}]`}return String(e)}function ca(e,t,n,i,r){null==e&&(e="global"),i=i??["success"],r=r??["error"];let s,o="global"===e,a=!1,c=!1;const d=Bo();t.disconnected(function(){n.debug("connection is down"),c=!1,o=!1,a=!0,Object.keys(l).forEach(e=>{const t=l[e];t&&(n.trace(`failing pending request ${e} due to connection lost`),t.error({err:"Connection lost - gateway connection was disconnected"}))}),d.execute("onLeft",{disconnected:!0})}),t.loggedIn(async function(){if(c=!0,a){n.debug("connection is now up - trying to reconnect...");try{await h(s)}catch{n.trace("failed to reconnect")}}}),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))}),r&&r.forEach(e=>{t.on(e,e=>p(e))});const l={};function h(t){return s=t,new Promise((i,r)=>{if(o)return void i({});let s;if("global"===e)s=c?Promise.resolve({}):Promise.reject("not connected to gateway");else{n.debug(`joining domain ${e}`);s=b({type:"join",destination:e,domain:"global",options:t})}s.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)),r(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 f(){return ta(10)}let m=[];function b(i,r,s){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 Vo;if(m.push({msg:i,tag:r,options:s,pw:e}),1===m.length){const e=u(()=>{n.info(`joined - will now send queued messages (${m.length} -> [${m.map(e=>e.msg.type)}])`),m.forEach(e=>{b(e.msg,e.tag,e.options).then(t=>e.pw.resolve(t)).catch(t=>e.pw.reject(t))}),m=[],e()})}return e.promise}s=s??{},i.request_id=i.request_id??f(),i.domain=i.domain??e,s.skipPeerId||(i.peer_id=t.peerId);const a=i.request_id;return new Promise((e,n)=>{l[a]={success:t=>{delete l[a],t._tag=r,e(t)},error:e=>{console.warn(`Gateway error - ${JSON.stringify(e)}`),delete l[a],e._tag=r,n(e)}},t.send(i,s).catch(e=>{l[a]?.error({err:e})})})}return{join:h,leave:function(){return"global"===e?Promise.resolve():o?(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")})):(a=!1,Promise.resolve())},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:f(),n.domain=n.domain??e,n.peer_id=t.peerId,t.send(n)},on:(i,r)=>{t.on(i,t=>{if(t.domain===e)try{r(t)}catch(e){n.error(`Callback failed: ${oa(e)} \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 da{settings;logger;protocolVersion=3;peerId;token;info;resolvedIdentity;availableDomains;gatewayToken;replayer;messageHandlers={};ids=1;registry=Bo();_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 ra;_isLoggedIn=!1;shouldTryLogin=!0;pingTimer;reconnectTimeout;sessions=[];globalDomain;initialLogin=!0;initialLoginAttempts=3;remainingReconnectAttempts;loginConfig;loginRetryInProgress=!1;reconnectInProgress=!1;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 Go(e.inproc,t.subLogger("inMemory"));else if(e.sharedWorker)this.transport=new Jo(e.sharedWorker,t.subLogger("shared-worker"));else if(e.webPlatform)this.transport=new ia(e.webPlatform,t.subLogger("web-platform"),e.identity);else{if(void 0===e.ws)throw new Error("No connection information specified");this.transport=new Xo(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.logger.debug(`Login initiated - reconnect: ${t}, transport: ${this.transport.name()}`),this._defaultAuth||(this._defaultAuth=e),this._swapTransport){this.logger.trace("Detected a transport swap, swapping transports");e=this.transportSwap()??e}try{await this.transport.open(),this.logger.debug(`Transport: ${this.transport.name()} opened, logging in`),Zo("connection").mark("transport-opened");const n=await this.loginCore(e,t);return this.logger.debug(`Logged in with identity: ${JSON.stringify(n)}`),Zo("connection").mark("protocol-logged-in"),n}catch(e){throw this._switchInProgress&&(this.logger.debug("An error while logging in after a transport swap, preparing a default swap."),this.prepareDefaultSwap()),sa(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=ca(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"))}async reconnect(){if(!this.loginConfig)throw new Error("Cannot reconnect - no previous login configuration");if(this.reconnectInProgress)this.logger.debug("reconnect() already in progress, ignoring");else{this.reconnectInProgress=!0;try{for(this.shouldTryLogin=!1,this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0);this.loginRetryInProgress;)await new Promise(e=>setTimeout(e,50));this._isLoggedIn&&(this.setLoggedIn(!1),this.registry.execute("disconnected")),this.shouldTryLogin=!0,await this.login(this.loginConfig,!0)}finally{this.reconnectInProgress=!1}}}setLoggedIn(e){this._isLoggedIn=e,this._isLoggedIn&&(this.initialLogin=!1,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 ${oa(e)}`,e)}catch(t){console.log("Message handler failed",e)}}})}handleConnectionChanged(e){this._connected!==e?(this.logger.info("connection state changed to "+(e?"connected":"disconnected")),this._connected=e,e?(this.settings?.replaySpecs?.length&&(this.replayer=new ea(this.settings.replaySpecs),this.replayer.init(this)),this.registry.execute("connected")):(this.setLoggedIn(!1),this.shouldTryLogin&&(this.remainingReconnectAttempts=this.settings.reconnectAttempts,this.attemptLoginWithRetry()),this.registry.execute("disconnected"))):this.logger.trace("connection state unchanged, skipping")}async attemptLoginWithRetry(){if(!this.loginConfig)throw new Error("no login info");if(this.shouldTryLogin)if(this.loginRetryInProgress)this.logger.debug("login attempt already in progress, ignoring request...");else if(this._isLoggedIn)this.logger.debug("already logged in, ignoring request...");else{if(this.initialLogin){if(this.logger.debug(`initial login attempt failed, ${this.initialLoginAttempts} attempts remaining...`),this.initialLoginAttempts<=0)return void this.logger.info("maximum initial login attempts reached, will not try to login again");this.initialLoginAttempts--}else if(void 0!==this.remainingReconnectAttempts){if(this.remainingReconnectAttempts<=0)return void this.logger.info("maximum reconnect attempts reached, will not try to login again");this.logger.debug(`reconnect attempt, ${this.remainingReconnectAttempts} attempts remaining...`),this.remainingReconnectAttempts--}try{this.logger.debug(`will try a new login... ${this.loginRetryInProgress}`),this.loginRetryInProgress=!0,await this.login(this.loginConfig,!0)}catch(e){this.logger.error(`error trying to login: ${e?.message}`,e),this.shouldTryLogin&&(this.reconnectTimeout=setTimeout(this.attemptLoginWithRetry.bind(this),this.settings.reconnectInterval??1e3))}finally{this.loginRetryInProgress=!1}}else this.logger.debug("should not try to login, ignoring reconnect attempt...")}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 na(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 Xo(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.loginConfig=e,this.loginConfig||(this.loginConfig={username:"",password:""});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||(this.globalDomain=ca("global",this,this.logger.subLogger("global-domain"),["welcome","token","authentication-request"]));const r={skipPeerId:!0};this.initialLogin&&(r.retryInterval=this.settings.reconnectInterval,r.maxRetries=this.settings.reconnectAttempts);try{const t=await this.tryAuthenticate(this.globalDomain,i,r,e);return 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 r;for(;;){const s=await e.send(t,void 0,n);if("authentication-request"!==s.type){if("welcome"===s.type){r=s;break}throw"error"===s.type?new Error("Authentication failed: "+s.reason):new Error("Unexpected message type during authentication: "+s.type)}{const e=Buffer.from(s.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 r}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("core logging out..."),this.shouldTryLogin=!1,this.setLoggedIn(!1),this.pingTimer&&clearTimeout(this.pingTimer),this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0);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 la=["trace","debug","info","warn","error","off"];class ha{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.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 ha(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 la.indexOf(e)>=la.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 r=ha.Interop;if(r)try{if(r.methods({name:ha.InteropMethodName}).length>0){const s={msg:t,logger:i,level:e};n&&n instanceof Error&&(s.error={message:n.message,stack:n.stack??""}),r.invoke(ha.InteropMethodName,s).catch(e=>{this.logFn.error(`Unable to send log message to the platform: ${sa(e).message}`,e)})}}catch{}}if(this.canPublish(e)){let r="";if(this.includeTimeAndLevel){const t=new Date;r=`[${`${t.getHours()}:${t.getMinutes()}:${t.getSeconds()}:${t.getMilliseconds()}`}] [${e}] `}const s=`${r}${i}: ${t}`;switch(e){case"trace":this.logFn.debug(s);break;case"debug":this.logFn.debug?this.logFn.debug(s):this.logFn.log(s);break;case"info":this.logFn.info(s);break;case"warn":this.logFn.warn(s);break;case"error":n?this.logFn.error(s,n):this.logFn.error(s)}}}}const ua="create-context",pa="created",ga="destroyed",fa="context-created",ma="context-added",ba="subscribe-context",ya="subscribed-context",wa="unsubscribe-context",va="destroy-context",Ca="context-destroyed",Ia="update-context",Sa="context-updated",_a="joined",xa={get name(){return"context"},get types(){return[ua,pa,ga,fa,ma,ba,ya,wa,va,Ca,Ia,Sa,_a]}};var Ta,Pa,ka="6.11.0";
|
|
2
2
|
/*!
|
|
3
3
|
* is-plain-object <https://github.com/jonschlinkert/is-plain-object>
|
|
4
4
|
*
|