iobroker.javascript
Version:
Rules Engine for ioBroker
1 lines • 1.73 MB
JavaScript
import{o as xe,g as gr,c as Tr,a as Dr}from"./createTheme-Bm92JF8u.js";import{R as n,C as $}from"./ConfigCustomJavascriptSet__loadShare__react__loadShare__-BNbscXK6.js";import{C as g}from"./ConfigCustomJavascriptSet__loadShare___mf_0_mui_mf_1_material__loadShare__-BqzgglHd.js";import{C as m,a as wc,D as pn,u as Cc}from"./index-t-NMdeH5.js";import{g as Ac}from"./_commonjsHelpers-CE1G-McA.js";import{u as mc}from"./useTheme-DFGylj2o.js";import"./ConfigCustomJavascriptSet__mf_v__runtimeInit__mf_v__-jdUmHa_i.js";import"./index-DcK0RDrH.js";import"./defaultTheme-BlO0eCf6.js";import"./useTheme-Cgjfsi-1.js";const pi=11/23/100;function yr(i){const e={r:0,g:0,b:0};if(i.length===7)e.r=parseInt(i.substring(1,3),16),e.g=parseInt(i.substring(3,5),16),e.b=parseInt(i.substring(5,7),16);else if(i.length===4){const t=i[1],s=i[2],o=i[3];e.r=parseInt(t+t,16),e.g=parseInt(s+s,16),e.b=parseInt(o+o,16)}return e}function pc(i){return`#${Math.round(i.r).toString(16)}${Math.round(i.g).toString(16)}${Math.round(i.b).toString(16)}`}function Oc(i,e,t){const s=yr(i),o=yr(e);return s.r+=o.r*(.05+pi*(t-1)),s.g+=o.g*(.05+pi*(t-1)),s.b+=o.b*(.05+pi*(t-1)),pc(s)}function Oi(i,e){const t={};for(let s=1;s<=24;s++)t[`elevation${s}`]={backgroundColor:Oc(i,e,s)};return t}function Ec(i,e){var M,a,u,l,N,c,L,j,T,y,z;let t,s;i==="dark"?(s={MuiAppBar:{colorDefault:{backgroundColor:"#272727"}},MuiLink:{root:{textTransform:"uppercase",transition:"color .3s ease",color:xe[200],"&:hover":{color:xe[100]}}},MuiPaper:Oi("#121212","#fff")},t={name:i,palette:{mode:"dark",background:{paper:"#121212",default:"#121212"},primary:{main:"#4dabf5"},secondary:{main:"#436a93"},expert:"#14bb00",text:{primary:"#ffffff",secondary:"#ffffff"}}}):i==="blue"?(s={MuiAppBar:{colorDefault:{backgroundColor:"#3399CC"}},MuiLink:{root:{textTransform:"uppercase",transition:"color .3s ease",color:xe[400],"&:hover":{color:xe[300]}}}},t={name:i,palette:{mode:"dark",background:{paper:"#151d21",default:"#151d21"},primary:{main:"#4dabf5"},secondary:{main:"#436a93"},expert:"#14bb00",text:{primary:"#ffffff",secondary:"#ffffff"}}}):i==="colored"?(s={MuiAppBar:{colorDefault:{backgroundColor:"#2a3135"}},MuiLink:{root:{textTransform:"uppercase",transition:"color .3s ease",color:xe[200],"&:hover":{color:xe[100]}}},MuiPaper:Oi("#151d21","#fff")},t={name:i,palette:{mode:"light",primary:{main:"#3399CC"},secondary:{main:"#164477"},expert:"#96fc96"}}):i==="PT"?(s={MuiAppBar:{colorDefault:{backgroundColor:"#0F99DE"}},MuiLink:{root:{textTransform:"uppercase",transition:"color .3s ease",color:xe[400],"&:hover":{color:xe[300]}}}},t={name:i,palette:{mode:"light",primary:{main:"#0F99DE"},secondary:{main:"#88A536"},expert:"#BD1B24"}}):i==="NW"?(s={MuiAppBar:{colorDefault:{backgroundColor:"#272727"}},MuiLink:{root:{textTransform:"uppercase",transition:"color .3s ease",color:xe[400],"&:hover":{color:xe[300]}}},MuiPaper:Oi("#121212","#fff")},t={name:i,palette:{mode:"dark",background:{paper:"#121212",default:"#121212"},primary:{main:"#00af78"},secondary:{main:"#005a40"},expert:"#14bb00",text:{primary:"#ffffff",secondary:"#ffffff"}}}):(s={MuiLink:{root:{textTransform:"uppercase",transition:"color .3s ease",color:xe[400],"&:hover":{color:xe[300]}}}},t={name:i,palette:{mode:"light",primary:{main:"#3399CC",dark:"#256c97",light:"#76d0fd"},secondary:{main:"#164477"},expert:"#14bb00"}}),t.toolbar={height:48},t.saveToolbar={background:(a=(M=t.palette)==null?void 0:M.primary)==null?void 0:a.main,button:{borderRadius:3,height:32}},t.palette&&(t.palette.grey={main:gr[300],dark:gr[400]});const o=Tr(t),r=o.palette;return Tr(o,{...e||void 0,components:{...s,MuiButton:{variants:[{props:{variant:"contained",color:"grey"},style:{backgroundColor:(u=r.grey)==null?void 0:u[300],color:r.getContrastText&&((l=r.grey)!=null&&l[300])?r.getContrastText(r.grey[300]):void 0}},{props:{variant:"outlined",color:"grey"},style:{color:(N=r.text)==null?void 0:N.primary,borderColor:r.mode==="light"?"rgba(0, 0, 0, 0.23)":"rgba(255, 255, 255, 0.23)","&.Mui-disabled":{border:`1px solid ${(c=r.action)==null?void 0:c.disabledBackground}`},"&:hover":{borderColor:r.mode==="light"?"rgba(0, 0, 0, 0.23)":"rgba(255, 255, 255, 0.23)",backgroundColor:Dr(((L=r.text)==null?void 0:L.primary)||"",((j=r.action)==null?void 0:j.hoverOpacity)||.04)}}},{props:{variant:"text",color:"grey"},style:{color:(T=r.text)==null?void 0:T.primary,"&:hover":{backgroundColor:Dr(((y=r.text)==null?void 0:y.primary)||"",((z=r.action)==null?void 0:z.hoverOpacity)||.04)}}}]},...(e==null?void 0:e.components)||void 0}})}function _c(){let i,e;const t=new Promise((s,o)=>{i=s,e=o});return t.resolve=i,t.reject=e,t}function qi(i){return(i==null?void 0:i.rows.map(e=>e.value).filter(e=>!!e))??[]}function tt(i){return i!=null&&i.startsWith("system.host.")||(i=`system.host.${i}`),i}function cs(i){return i!=null&&i.startsWith("system.host.")&&(i=i.substring(12)),i}function dr(i){return new Promise(e=>{setTimeout(e,i)})}function Us(i){i=(i||"").toString();const e=i[0]==="*",t=i[i.length-1]==="*";return i=i.replace(/[-/\\^$+?.()|[\]{}]/g,"\\$&").replace(/\*/g,".*"),(e?"":"^")+i+(t?"":"$")}typeof globalThis.process<"u"&&(globalThis.location||={href:"http://localhost:8081/",protocol:"http:",host:"localhost:8081",pathname:"/",hostname:"localhost",reload:()=>{}},globalThis.localStorage||={_keys:{},setItem:(i,e)=>{globalThis.localStorage._keys[i]=e},getItem:i=>i in globalThis.localStorage._keys?globalThis.localStorage._keys[i]:null,removeItem:i=>{i in globalThis.localStorage._keys&&delete globalThis.localStorage._keys[i]}},globalThis.sessionStorage||=globalThis.localStorage,globalThis.navigator||={language:"en"});var Be;(function(i){i[i.CONNECTING=0]="CONNECTING",i[i.CONNECTED=1]="CONNECTED",i[i.OBJECTS_LOADED=2]="OBJECTS_LOADED",i[i.READY=3]="READY"})(Be||(Be={}));var ye;(function(i){i.PERMISSION_ERROR="permissionError",i.NOT_CONNECTED="notConnectedError",i.TIMEOUT="timeout",i.NOT_ADMIN="Allowed only in admin",i.NOT_SUPPORTED="Not supported"})(ye||(ye={}));const Z0e=ye.PERMISSION_ERROR;ye.NOT_CONNECTED;const Sc=["material","echarts","vis"];class ge{props;connId;lastAccessToken=null;ignoreState="";connected=!1;subscribed=!1;firstConnect=!0;waitForRestart=!1;loaded=!1;simStates={};objectViewCached;constructor(e){this.props=this.applyDefaultProps(e),this.connId=`${this.props.name?`${this.props.name}-`:""}${Math.round(Math.random()*1e6).toString().padStart(6,"0")}`,this.waitForSocketLib().then(()=>this.startSocket()).catch(t=>{alert(`Socket connection could not be initialized: ${t}`)})}applyDefaultProps(e){return{...e,protocol:e.protocol||globalThis.location.protocol,host:e.host||globalThis.location.hostname,port:e.port||(globalThis.location.port==="3000"?8081:globalThis.location.port),ioTimeout:Math.max(e.ioTimeout||2e4,2e4),cmdTimeout:Math.max(e.cmdTimeout||5e3,5e3),admin5only:e.admin5only||!1,autoSubscribes:e.autoSubscribes??[],autoSubscribeLog:e.autoSubscribeLog??!1,doNotLoadACL:e.doNotLoadACL??!0,doNotLoadAllObjects:e.doNotLoadAllObjects??!0}}statesSubscribes={};filesSubscribes={};objectsSubscribes={};objects={};states={};acl=null;isSecure=!1;onReadyDone=!1;onConnectionHandlers=[];onLogHandlers=[];onCmdStdoutHandler;onCmdStderrHandler;onCmdExitHandler;onError(e){(this.props.onError??console.error)(e)}_socket;_waitForSocketPromise;_waitForFirstConnectionPromise=_c();_instanceSubscriptions={};_promises={};_authTimer=null;_refreshTimer=null;_systemConfig;get systemConfig(){return this._systemConfig}systemLang="en";static isWeb(){return globalThis.socketUrl!==void 0}waitForSocketLib(){return this._waitForSocketPromise?this._waitForSocketPromise:(this._waitForSocketPromise=new Promise(async(e,t)=>{if(this.props.connect){e();return}if(typeof globalThis.io>"u"&&typeof globalThis.iob>"u")if(typeof globalThis.registerSocketOnLoad=="function")globalThis.registerSocketOnLoad(()=>e());else{for(let s=1;s<=30;s++){if(globalThis.io||globalThis.iob)return e();await dr(100)}t(new Error("Socket library could not be loaded!"))}else e()}),this._waitForSocketPromise)}async startSocket(){if(this._socket)return;let e=this.props.host,t=this.props.port,s=(this.props.protocol||globalThis.location.protocol).replace(":",""),o=globalThis.location.pathname;if(globalThis.location.hostname==="iobroker.net"||globalThis.location.hostname==="iobroker.pro")o="";else{if(globalThis.socketUrl){const u=new globalThis.URL(globalThis.socketUrl);e=u.hostname,t=u.port,s=u.protocol.replace(":","")}const a=o.lastIndexOf("/");if(a!==-1&&(o=o.substring(0,a+1)),ge.isWeb()){const u=o.split("/");u.length>2&&(u.pop(),u.pop(),Sc.includes(u[u.length-1])&&u.pop(),o=u.join("/"),o.endsWith("/")||(o+="/"))}}const r=t?`${s}://${e}:${t}`:`${s}://${e}`,M=this.props.connect||(globalThis.io||globalThis.iob).connect;return this._socket=M(r,{path:o.endsWith("/")?`${o}socket.io`:`${o}/socket.io`,query:"ws=true",name:this.props.name,timeout:this.props.ioTimeout,uuid:this.props.uuid,token:this.props.token}),this._socket.on("connect",a=>{var l;(l=globalThis.addEventListener)==null||l.call(globalThis,"storage",this.onAccessTokenUpdated);const u=ge.readTokens();if(u&&!u.owner){const N=Date.now();this.saveTokens({access_token:u.access_token,refresh_token:u.refresh_token,expires_in:Math.round((u.expires_in.getTime()-N)/1e3),refresh_token_expires_in:Math.round((u.refresh_token_expires_in.getTime()-N)/1e3),token_type:"Bearer"},u.stayLoggedIn)}this.onReadyDone=!1,a!==!0?(this.connected=!0,setTimeout(()=>this.getVersion().then(N=>{const[c,L,j]=N.version.split(".");parseInt(c,10)*1e4+parseInt(L,10)*100+parseInt(j,10)<40102?(this._authTimer=null,this.onPreConnect(!1,!1)):this._socket.emit("authenticate",(y,z)=>this.onPreConnect(y,z))}).catch(N=>this.onError({message:N.toString(),operation:"getVersion"})),500)):this._socket.emit("authenticate",(N,c)=>{this.onPreConnect(N,c)})}),this._socket.on("reconnect",()=>{var a,u;this.onReadyDone=!1,(u=(a=this.props).onProgress)==null||u.call(a,Be.READY),this.connected=!0,this.waitForRestart?globalThis.location.reload():(this._subscribe(!0),this.onConnectionHandlers.forEach(l=>l(!0)))}),this._socket.on("disconnect",()=>{var a,u;this.onReadyDone=!1,this.connected=!1,this.subscribed=!1,(u=(a=this.props).onProgress)==null||u.call(a,Be.CONNECTING),this.onConnectionHandlers.forEach(l=>l(!1))}),this._socket.on("reauthenticate",()=>this.authenticate()),this._socket.on("log",a=>{var u,l;(l=(u=this.props).onLog)==null||l.call(u,a),this.onLogHandlers.forEach(N=>N(a))}),this._socket.on("error",a=>{let u;a==null?u="":typeof a.toString=="function"?u=a.toString():(u=JSON.stringify(a),console.error(`Received strange error: ${u}`)),u.includes("User not authorized")?this.authenticate():u.includes("websocket error")?(console.error(`Socket Error => reload: ${a}`),globalThis.location.reload()):console.error(`Socket Error: ${a}`)}),this._socket.on("connect_error",a=>console.error(`Connect error: ${a}`)),this._socket.on("permissionError",a=>this.onError({message:"no permission",operation:a.operation,type:a.type,id:a.id||""})),this._socket.on("objectChange",(a,u)=>{setTimeout(()=>this.objectChange(a,u),0)}),this._socket.on("stateChange",(a,u)=>{setTimeout(()=>this.stateChange(a,u),0)}),this._socket.on("im",(a,u,l)=>{setTimeout(()=>this.instanceMessage(a,u,l),0)}),this._socket.on("fileChange",(a,u,l)=>{setTimeout(()=>this.fileChange(a,u,l),0)}),this._socket.on("cmdStdout",(a,u)=>{var l;(l=this.onCmdStdoutHandler)==null||l.call(this,a,u)}),this._socket.on("cmdStderr",(a,u)=>{var l;(l=this.onCmdStderrHandler)==null||l.call(this,a,u)}),this._socket.on("cmdExit",(a,u)=>{var l;(l=this.onCmdExitHandler)==null||l.call(this,a,u)}),Promise.resolve()}onPreConnect(e,t){var s,o;this._authTimer&&(clearTimeout(this._authTimer),this._authTimer=null),this.connected=!0,this.isSecure=t,this.waitForRestart?globalThis.location.reload():(this.firstConnect?this.loadData().catch(r=>{console.error(`Cannot load data: ${r}`)}):(o=(s=this.props).onProgress)==null||o.call(s,Be.READY),this._subscribe(!0),this.onConnectionHandlers.forEach(r=>r(!0)),this.checkAccessTokenExpire()),this._waitForFirstConnectionPromise.resolve()}static readTokens(){let e=globalThis.sessionStorage.getItem("iob_tokens");const t=!e;if(e||(e=globalThis.localStorage.getItem("iob_tokens")),!e)return null;const[s,o,r,M,a]=e.split(";"),u=new Date(o);return u.getTime()<Date.now()?null:{refresh_token:s,refresh_token_expires_in:u,access_token:r,expires_in:new Date(M),owner:a,stayLoggedIn:t}}static saveTokensStatic(e,t,s){const o=`${e.refresh_token};${new Date(Date.now()+e.refresh_token_expires_in*1e3).toISOString()};${e.access_token};${new Date(Date.now()+e.expires_in*1e3).toISOString()}${s?`;${s}`:""}`;t?globalThis.localStorage.setItem("iob_tokens",o):globalThis.sessionStorage.setItem("iob_tokens",o)}saveTokens(e,t){ge.saveTokensStatic(e,t,this.connId)}static deleteTokensStatic(){globalThis.localStorage.removeItem("iob_tokens"),globalThis.sessionStorage.removeItem("iob_tokens")}deleteTokens(e,t){const s=ge.readTokens();s&&(t?ge.deleteTokensStatic():s.stayLoggedIn===e&&s.owner===this.connId&&(s.stayLoggedIn?globalThis.localStorage.removeItem("iob_tokens"):globalThis.sessionStorage.removeItem("iob_tokens")))}onAccessTokenUpdated=e=>{if(e.key==="iob_tokens"){const t=ge.readTokens();t&&(console.log(`Tab ${this.connId} received updated token: ${t.access_token}`),this.updateTokenExpiration(t.access_token))}};updateTokenExpiration(e){this.lastAccessToken!==e&&(this.lastAccessToken=e,this._socket.emit("updateTokenExpiration",e,(t,s)=>{t?(console.error(`[UPDATE/${new Date().toISOString()}] cannot say to server about new token: ${t}`),globalThis.location.reload()):s?console.log(`[UPDATE/${new Date().toISOString()}] server accepted new token: ${e}`):(console.error(`[UPDATE/${new Date().toISOString()}] cannot say to server about new token`),globalThis.location.reload())})),this.checkAccessTokenExpire()}refreshTokens(e,t){if(!e){console.log(`[REFRESH/${new Date().toISOString()}] No token structure found => reloading the page`),setTimeout(()=>globalThis.location.reload(),500);return}t||!e.owner||e.owner===this.connId?(console.log(`[REFRESH/${new Date().toISOString()}] claim ownership of the token`),this.acquireTokenLock()?(console.log(`[REFRESH/${new Date().toISOString()}] refreshing token`),fetch("./oauth/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:`grant_type=refresh_token&refresh_token=${e.refresh_token}&client_id=ioBroker&stayloggedin=${e.stayLoggedIn}`}).then(s=>{if(s.ok)return s.json();throw new Error("Cannot refresh access token")}).then(s=>{if(s.access_token)console.log(`[REFRESH/${new Date().toISOString()}] received new token: ${s.access_token}`),this.saveTokens(s,e.stayLoggedIn),this.releaseTokenLock(),this.updateTokenExpiration(s.access_token);else throw new Error("Cannot get access token")}).catch(s=>{console.warn(`[REFRESH/${new Date().toISOString()}] cannot refresh token: ${s}`),this.releaseTokenLock(),this.deleteTokens(e.stayLoggedIn),console.error(s),globalThis.location.reload()})):(console.log(`[REFRESH/${new Date().toISOString()}] Someone else is updating the token, so wait for the next check`),this.checkAccessTokenExpire())):this.lastAccessToken!==e.access_token&&this.updateTokenExpiration(e.access_token)}acquireTokenLock(){const e=Date.now(),t=globalThis.localStorage.getItem("iob_token_semaphore");if(t)try{const o=JSON.parse(t);if(e<o.expiry)return!1}catch{}const s={connId:this.connId,expiry:e+10*1e3};return globalThis.localStorage.setItem("iob_token_semaphore",JSON.stringify(s)),!0}releaseTokenLock(){const e=globalThis.localStorage.getItem("iob_token_semaphore");if(e)try{JSON.parse(e).connId===this.connId&&globalThis.localStorage.removeItem("iob_token_semaphore")}catch{globalThis.localStorage.removeItem("iob_token_semaphore")}}checkAccessTokenExpire(){if(this._refreshTimer&&(clearTimeout(this._refreshTimer),this._refreshTimer=null),this.isSecure){const e=ge.readTokens();if(e){const t=e.expires_in.getTime();if(t<Date.now()+3e4){const s=t<Date.now()+5500;console.log(`[TOKEN/${new Date().toISOString()}] Updating refresh token ${e.access_token}`),e.refresh_token?e.owner===this.connId||s?(e.owner===this.connId?console.log(`[TOKEN/${new Date().toISOString()}] We are the owner of the token`):console.log(`[TOKEN/${new Date().toISOString()}] We are not the owner of the token, but we will take ownership`),this.props.tokenTimeoutHandler?(console.log(`[TOKEN/${new Date().toISOString()}] Asking GUI if we should prolong the token`),this.props.tokenTimeoutHandler(t).then(o=>{o?(console.log(`[TOKEN/${new Date().toISOString()}] Token will be prolonged`),this.refreshTokens(e,s)):(console.log(`[TOKEN/${new Date().toISOString()}] Token will not be prolonged. Reloading the page`),setTimeout(()=>globalThis.location.reload(),Date.now()>t?500:t-Date.now()))})):(console.log(`[TOKEN/${new Date().toISOString()}] No tokenTimeoutHandler defined. Prolonging the token`),this.refreshTokens(e,s))):this.lastAccessToken!==e.access_token?(console.log(`[TOKEN/${new Date().toISOString()}] We are not the owner of the token, but we will inform the server about new token`),this.refreshTokens(e)):(console.log(`[TOKEN/${new Date().toISOString()}] We are not the owner of the token and the token did not change. Check in 3 seconds if the owner updated the token`),this._refreshTimer=setTimeout(()=>{this._refreshTimer=null,this.checkAccessTokenExpire()},3e3)):(console.log(`[TOKEN/${new Date().toISOString()}] We do not have a refresh token, so we need to reauthenticate`),setTimeout(()=>globalThis.location.reload(),Date.now()>t?500:t-Date.now()))}else this._refreshTimer=setTimeout(()=>{this._refreshTimer=null,this.checkAccessTokenExpire()},t-Date.now()-3e4>12e4?12e4:t-Date.now()-3e4)}}}static isCloud(){return globalThis.location.hostname.includes("amazonaws.com")||globalThis.location.hostname.includes("iobroker.in")?!0:typeof globalThis.socketUrl>"u"?!1:globalThis.socketUrl.includes("iobroker.in")||globalThis.socketUrl.includes("amazonaws")}isConnected(){return this.connected}waitForFirstConnection(){return this._waitForFirstConnectionPromise}async getUserPermissions(){return this.request({commandTimeout:!1,executor:(e,t)=>{this._socket.emit("getUserPermissions",(s,o)=>{s?t(s):e(o||null)})}})}async loadData(){if(this.loaded)return;const e=10;for(let t=1;t<=e;t++){if(this.doLoadData().catch(s=>console.error(`Cannot load data: ${s}`)),this.loaded)return;await dr(ge.isCloud()?5e3:1e3)}}async doLoadData(){var e,t,s,o,r,M,a,u,l;if(!this.loaded){if(!this.props.doNotLoadACL)try{this.acl=await this.getUserPermissions()}catch(N){this.onError(`Cannot read user permissions: ${N}`);return}try{this.props.admin5only&&!ge.isWeb()&&(!globalThis.vendorPrefix||globalThis.vendorPrefix==="@@vendorPrefix@@")?this._systemConfig=await this.getCompactSystemConfig():this._systemConfig=await this.getSystemConfig()}catch(N){this.onError(`Cannot read system config: ${N}`);return}this._systemConfig&&(this.systemLang=(e=this._systemConfig.common)==null?void 0:e.language,this.systemLang||(this.systemLang=globalThis.navigator.userLanguage||globalThis.navigator.language,/^(en|de|ru|pt|nl|fr|it|es|pl|uk)-?/.test(this.systemLang)?this.systemLang=this.systemLang.substring(0,2):/^(en|de|ru|pt|nl|fr|it|es|pl|uk|zh-cn)$/.test(this.systemLang)||(this.systemLang="en"),this._systemConfig.common.language=this.systemLang)),(s=(t=this.props).onLanguage)==null||s.call(t,this.systemLang),this.loaded=!0,(r=(o=this.props).onProgress)==null||r.call(o,Be.CONNECTED),this.firstConnect=!1,this.props.doNotLoadAllObjects?this.props.admin5only?this.objects={}:this.objects={"system.config":this._systemConfig}:this.objects=await this.getObjects(),(a=(M=this.props).onProgress)==null||a.call(M,Be.READY),this.onReadyDone||(this.onReadyDone=!0,(l=(u=this.props).onReady)==null||l.call(u,this.objects))}}authenticate(){globalThis.location.search.includes("&href=")?globalThis.location.href=`${globalThis.location.protocol}//${globalThis.location.host}${globalThis.location.pathname}${globalThis.location.search}`:globalThis.location.href=`${globalThis.location.protocol}//${globalThis.location.host}${globalThis.location.pathname}?login&href=${encodeURIComponent(globalThis.location.search+globalThis.location.hash)}`}async subscribeState(...e){let t,s,o;e.length===3?[t,s,o]=e:([t,o]=e,s=!1);let r;if(Array.isArray(t)?r=t:r=[t],typeof o!="function")throw new Error("The state change handler must be a function!");const M=[];for(let a=0;a<r.length;a++){const u=r[a];this.statesSubscribes[u]?!this.statesSubscribes[u].cbs.includes(o)&&this.statesSubscribes[u].cbs.push(o):(this.statesSubscribes[u]={reg:new RegExp(Us(u)),cbs:[o]},t!==this.ignoreState&&M.push(u))}if(this.connected)if(M.length&&this._socket.emit("subscribe",M),s){let a;for(let u=0;u<r.length;u++){try{a=await this.getBinaryState(r[u])}catch(l){console.error(`Cannot getBinaryState "${r[u]}": ${JSON.stringify(l)}`),a=void 0}a!=null&&o(r[u],a)}}else if(r.find(a=>a.includes("*"))){let a;for(let u=0;u<r.length;u++){try{a=await this.getForeignStates(r[u])}catch(l){console.error(`Cannot getForeignStates "${r[u]}": ${JSON.stringify(l)}`);return}if(a)for(const[l,N]of Object.entries(a)){const c=o(l,N);c instanceof Promise&&c.catch(L=>console.error(`Cannot call state change handler: ${L}`))}}}else try{const a=await(ge.isWeb()?this.getStates(r):this.getForeignStates(r));if(a)for(const[u,l]of Object.entries(a)){const N=o(u,l);N instanceof Promise&&N.catch(c=>console.error(`Cannot call state change handler: ${c}`))}}catch(a){console.error(`Cannot getState "${r.join(", ")}": ${a.message}`);return}}async subscribeStateAsync(e,t){return this.subscribeState(e,t)}unsubscribeState(e,t){var r;let s;Array.isArray(e)?s=e:s=[e];const o=[];for(let M=0;M<s.length;M++){const a=s[M];if(this.statesSubscribes[a]){const u=this.statesSubscribes[a];if(t){const l=u.cbs.indexOf(t);l!==-1&&u.cbs.splice(l,1)}else u.cbs=[];(r=u.cbs)!=null&&r.length||(delete this.statesSubscribes[a],a!==this.ignoreState&&o.push(a))}}this.connected&&o.length&&this._socket.emit("unsubscribe",s)}subscribeObject(e,t){let s;if(Array.isArray(e)?s=e:s=[e],typeof t!="function")throw new Error("The object change handler must be a function!");const o=[];for(let r=0;r<s.length;r++){const M=s[r];this.objectsSubscribes[M]?!this.objectsSubscribes[M].cbs.includes(t)&&this.objectsSubscribes[M].cbs.push(t):(this.objectsSubscribes[M]={reg:new RegExp(Us(M)),cbs:[t]},o.push(M))}return this.connected&&o.length&&this._socket.emit("subscribeObjects",o),Promise.resolve()}unsubscribeObject(e,t){var r;let s;Array.isArray(e)?s=e:s=[e];const o=[];for(let M=0;M<s.length;M++){const a=s[M];if(this.objectsSubscribes[a]){const u=this.objectsSubscribes[a];if(t){const l=u.cbs.indexOf(t);l!==-1&&u.cbs.splice(l,1)}else u.cbs=[];(r=u.cbs)!=null&&r.length||(delete this.objectsSubscribes[a],o.push(a))}}return this.connected&&o.length&&this._socket.emit("unsubscribeObjects",o),Promise.resolve()}objectChange(e,t){var r,M;let s;this.objects[e]&&(s={_id:e,type:this.objects[e].type});let o=!1;t?(t._rev&&this.objects[e]&&(this.objects[e]._rev=t._rev),(!this.objects[e]||JSON.stringify(this.objects[e])!==JSON.stringify(t))&&(this.objects[e]=t,o=!0)):this.objects[e]&&(delete this.objects[e],o=!0);for(const[a,u]of Object.entries(this.objectsSubscribes))(a===e||u.reg.test(e))&&u.cbs.forEach(l=>{try{const N=l(e,t,s);N instanceof Promise&&N.catch(c=>console.error(`Cannot call object change handler: ${c}`))}catch(N){console.error(`Error by callback of objectChange: ${N}`)}});if(o){const a=(M=(r=this.props).onObjectChange)==null?void 0:M.call(r,e,t);a instanceof Promise&&a.catch(u=>console.error(`Cannot call object change handler: ${u}`))}}stateChange(e,t){for(const s of Object.values(this.statesSubscribes))if(s.reg.test(e))for(const o of s.cbs)try{const r=o(e,t??null);r instanceof Promise&&r.catch(M=>console.error(`Cannot call state change handler: ${M}`))}catch(r){console.error(`Error by callback of stateChanged: ${r}`)}}instanceMessage(e,t,s){var o;(o=this._instanceSubscriptions[t])==null||o.forEach(r=>{if(r.messageType===e){const M=r.callback(s,t,e);M instanceof Promise&&M.catch(a=>console.error(`Cannot call instance message handler: ${a}`))}})}fileChange(e,t,s){for(const o of Object.values(this.filesSubscribes))if(o.regId.test(e)&&o.regFilePattern.test(t))for(const r of o.cbs)try{r(e,t,s)}catch(M){console.error(`Error by callback of fileChange: ${M}`)}}async subscribeFiles(e,t,s){if(typeof s!="function")throw new Error("The state change handler must be a function!");let o;Array.isArray(t)?o=t:o=[t];const r=[];for(let M=0;M<o.length;M++){const a=o[M],u=`${e}$%$${a}`;this.filesSubscribes[u]?!this.filesSubscribes[u].cbs.includes(s)&&this.filesSubscribes[u].cbs.push(s):(this.filesSubscribes[u]={regId:new RegExp(Us(e)),regFilePattern:new RegExp(Us(a)),cbs:[s]},r.push(a))}return this.connected&&r.length&&this._socket.emit("subscribeFiles",e,r),Promise.resolve()}unsubscribeFiles(e,t,s){var M;let o;Array.isArray(t)?o=t:o=[t];const r=[];for(let a=0;a<o.length;a++){const u=o[a],l=`${e}$%$${u}`;if(this.filesSubscribes[l]){const N=this.filesSubscribes[l];if(s){const c=N.cbs.indexOf(s);c!==-1&&N.cbs.splice(c,1)}else N.cbs=[];(M=N.cbs)!=null&&M.length||(delete this.filesSubscribes[l],r.push(u))}}this.connected&&r.length&&this._socket.emit("unsubscribeFiles",e,r)}async request({cacheKey:e,forceUpdate:t,commandTimeout:s,onTimeout:o,requireAdmin:r,requireFeatures:M,executor:a}){if(r&&ge.isWeb())return Promise.reject(new Error(ye.NOT_ADMIN));if(e&&!t&&e in this._promises)return this._promises[e];if(!this.connected)return Promise.reject(new Error(ye.NOT_CONNECTED));if(M!=null&&M.length){for(const l of M)if(!await this.checkFeatureSupported(l))throw new Error(ye.NOT_SUPPORTED)}const u=new Promise(async(l,N)=>{const c={elapsed:!1,clearTimeout:()=>{}};let L;s!==!1&&(L=setTimeout(()=>{c.elapsed=!0,o==null||o(),e&&this._promises[e]instanceof Promise&&delete this._promises[e],N(new Error(ye.TIMEOUT))},s??this.props.cmdTimeout),c.clearTimeout=()=>{clearTimeout(L)});try{await a(l,N,c)}catch(j){e&&this._promises[e]instanceof Promise&&delete this._promises[e],N(new Error(j.toString()))}});return e&&(this._promises[e]=u),u}resetCache(e,t){t?Object.keys(this._promises).filter(s=>s.startsWith(e)).forEach(s=>{delete this._promises[s]}):delete this._promises[e]}getStates(e){return this.request({commandTimeout:!1,executor:(t,s)=>{this._socket.emit("getStates",e,(o,r)=>{this.states=r??{},o?s(o):t(this.states)})}})}getState(e){return this.request({commandTimeout:!1,executor:(t,s)=>{if(e&&e===this.ignoreState){t(this.simStates[e]||{val:null,ack:!0});return}this._socket.emit("getState",e,(o,r)=>{o?s(o):t(r)})}})}getBinaryState(e){return this.request({commandTimeout:!1,executor:(t,s)=>{this._socket.emit("getBinaryState",e,(o,r)=>{o?s(o):t(r)})}})}setBinaryState(e,t){return this.request({commandTimeout:!1,executor:(s,o)=>{this._socket.emit("setBinaryState",e,t,r=>{r?o(r):s()})}})}setState(e,t,s){return typeof s=="boolean"&&(t={val:t,ack:s}),this.request({commandTimeout:!1,executor:(o,r)=>{if(e&&e===this.ignoreState){let M;if(typeof s=="boolean"||typeof t=="object"&&t.val!==void 0?M=t:M={val:t,ack:!1,ts:Date.now(),lc:Date.now(),from:"system.adapter.vis.0"},this.simStates[e]=M,this.statesSubscribes[e])for(const a of this.statesSubscribes[e].cbs)try{const u=a(e,M);u instanceof Promise&&u.catch(l=>console.error(`Cannot call state change handler: ${l}`))}catch(u){console.error(`Error by callback of stateChanged: ${u}`)}o();return}this._socket.emit("setState",e,t,M=>{M?r(M):o()})}})}getObjects(e,t){return this.request({commandTimeout:!1,executor:(s,o)=>{if(!e&&this.objects){s(this.objects);return}this._socket.emit(ge.isWeb()?"getObjects":"getAllObjects",(r,M)=>{var a,u;t||(u=(a=this.props).onProgress)==null||u.call(a,Be.OBJECTS_LOADED),r?o(r):(this.objects=M??{},s(this.objects))})}})}getObjectsById(e){return this.request({commandTimeout:!1,executor:(t,s)=>{this._socket.emit("getObjects",e,(o,r)=>{o?s(o):t(r)})}})}_subscribe(e){var t,s;if(e&&!this.subscribed){this.subscribed=!0,(t=this.props.autoSubscribes)!=null&&t.length&&this._socket.emit("subscribeObjects",this.props.autoSubscribes);const o=Object.keys(this.objectsSubscribes);o.length&&this._socket.emit("subscribeObjects",o),Object.keys(this.objectsSubscribes).forEach(r=>this._socket.emit("subscribeObjects",r)),this.props.autoSubscribeLog&&this._socket.emit("requireLog",!0),Object.keys(this.statesSubscribes).forEach(r=>this._socket.emit("subscribe",r)),Object.keys(this.filesSubscribes).forEach(r=>{const[M,a]=r.split("$%$");this._socket.emit("subscribeFiles",M,a)})}else if(!e&&this.subscribed){this.subscribed=!1,(s=this.props.autoSubscribes)!=null&&s.length&&this._socket.emit("unsubscribeObjects",this.props.autoSubscribes);const o=Object.keys(this.objectsSubscribes);o.length&&this._socket.emit("unsubscribeObjects",o),this.props.autoSubscribeLog&&this._socket.emit("requireLog",!1),Object.keys(this.statesSubscribes).forEach(r=>this._socket.emit("unsubscribe",r)),Object.keys(this.filesSubscribes).forEach(r=>{const[M,a]=r.split("$%$");this._socket.emit("unsubscribeFiles",M,a)})}}requireLog(e){return this.request({commandTimeout:!1,executor:(t,s)=>{this._socket.emit("requireLog",e,o=>{o?s(o):t()})}})}delObject(e,t=!1){return this.request({commandTimeout:!1,executor:(s,o)=>{this._socket.emit("delObject",e,{maintenance:t},r=>{r?o(r):s()})}})}delObjects(e,t){return this.request({commandTimeout:!1,executor:(s,o)=>{this._socket.emit("delObjects",e,{maintenance:t},r=>{r?o(r):s()})}})}setObject(e,t){return t?(t=JSON.parse(JSON.stringify(t)),delete t.from,delete t.user,delete t.ts,this.request({commandTimeout:!1,executor:(s,o)=>{this._socket.emit("setObject",e,t,r=>{r?o(r):s()})}})):Promise.reject(new Error("Null object is not allowed"))}getObject(e){return this.request({commandTimeout:!1,executor:(t,s)=>{if(e&&e===this.ignoreState){t({_id:this.ignoreState,type:"state",common:{name:"ignored state",type:"mixed"}});return}this._socket.emit("getObject",e,(o,r)=>{o?s(o):t(r)})}})}sendTo(e,t,s){return this.request({commandTimeout:!1,executor:o=>{this._socket.emit("sendTo",e,t,s,r=>{o(r)})}})}extendObject(e,t){return t?(t=JSON.parse(JSON.stringify(t)),delete t.from,delete t.user,delete t.ts,this.request({commandTimeout:!1,executor:(s,o)=>{this._socket.emit("extendObject",e,t,r=>{r?o(r):s()})}})):Promise.reject(new Error("Null object is not allowed"))}registerLogHandler(e){this.onLogHandlers.includes(e)||this.onLogHandlers.push(e)}unregisterLogHandler(e){const t=this.onLogHandlers.indexOf(e);t!==-1&&this.onLogHandlers.splice(t,1)}registerConnectionHandler(e){this.onConnectionHandlers.includes(e)||this.onConnectionHandlers.push(e)}unregisterConnectionHandler(e){const t=this.onConnectionHandlers.indexOf(e);t!==-1&&this.onConnectionHandlers.splice(t,1)}registerCmdStdoutHandler(e){this.onCmdStdoutHandler=e}unregisterCmdStdoutHandler(){this.onCmdStdoutHandler=void 0}registerCmdStderrHandler(e){this.onCmdStderrHandler=e}unregisterCmdStderrHandler(){this.onCmdStderrHandler=void 0}registerCmdExitHandler(e){this.onCmdExitHandler=e}unregisterCmdExitHandler(){this.onCmdExitHandler=void 0}getEnums(e,t){return this.request({cacheKey:`enums_${e||"all"}`,forceUpdate:t,commandTimeout:!1,executor:(s,o)=>{this._socket.emit("getObjectView","system","enum",{startkey:`enum.${e||""}`,endkey:e?`enum.${e}.香`:"enum.香"},(r,M)=>{if(r)o(r);else{const a={};if(M)for(let u=0;u<M.rows.length;u++)e&&M.rows[u].id===`enum.${e}`||(a[M.rows[u].id]=M.rows[u].value);s(a)}})}})}getObjectView(e,t,s){return this.getObjectViewCustom("system",s,e,t)}async getObjectViewSystem(e,t,s){var M;const o=`${e}_${t||""}_${s||""}`,r=await this.getObjectViewCustom("system",e,t,s);return(M=this.objectViewCached)!=null&&M[o]&&(this.objectViewCached[o]=r),r}async getObjectViewSystemCached(e,t,s){var M;const o=`${e}_${t||""}_${s||""}`;if((M=this.objectViewCached)!=null&&M[o])return Promise.resolve(this.objectViewCached[o]);const r=await this.getObjectViewCustom("system",e,t,s);return this.objectViewCached||={},this.objectViewCached[o]=r,r}getObjectViewCustom(e,t,s,o){return this.request({commandTimeout:!1,executor:(r,M)=>{s||="",o||="香",this._socket.emit("getObjectView",e,t,{startkey:s,endkey:o},(a,u)=>{if(a)M(a);else{const l={};if(u&&u.rows)for(let N=0;N<u.rows.length;N++)l[u.rows[N].id]=u.rows[N].value;r(l)}})}})}readMetaItems(){return this.request({commandTimeout:!1,executor:(e,t)=>{this._socket.emit("getObjectView","system","meta",{startkey:"",endkey:"香"},(s,o)=>{var r;s?t(s):e((r=o.rows)==null?void 0:r.map(M=>M.value).filter(M=>!!M))})}})}readDir(e,t){return this.request({commandTimeout:!1,executor:(s,o)=>{this._socket.emit("readDir",e,t,(r,M)=>{r?o(r):s(M)})}})}readFile(e,t,s){return this.request({commandTimeout:!1,executor:(o,r)=>{this._socket.emit(s?"readFile64":"readFile",e,t,(M,a,u)=>{M?r(M):o({file:a,mimeType:u})})}})}writeFile64(e,t,s){return this.request({commandTimeout:!1,executor:(o,r)=>{if(typeof s=="string")this._socket.emit("writeFile",e,t,s,M=>{M?r(M):o()});else{const M=btoa(new Uint8Array(s).reduce((a,u)=>a+String.fromCharCode(u),""));this._socket.emit("writeFile64",e,t,M,a=>{a?r(a):o()})}}})}deleteFile(e,t){return this.request({commandTimeout:!1,executor:(s,o)=>{this._socket.emit("deleteFile",e,t,r=>{r?o(r):s()})}})}deleteFolder(e,t){return this.request({commandTimeout:!1,executor:(s,o)=>{this._socket.emit("deleteFolder",e,t,r=>{r?o(r):s()})}})}rename(e,t,s){return this.request({commandTimeout:!1,executor:(o,r)=>{this._socket.emit("rename",e,t,s,M=>{M?r(M):o()})}})}renameFile(e,t,s){return this.request({commandTimeout:!1,executor:(o,r)=>{this._socket.emit("renameFile",e,t,s,M=>{M?r(M):o()})}})}cmdExec(e,t,s,o){return this.request({commandTimeout:o,executor:(r,M,a)=>{e=tt(e),this._socket.emit("cmdExec",e,s,t,u=>{a.elapsed||(a.clearTimeout(),u?M(u):r())})}})}getSystemConfig(e){return this.request({cacheKey:"systemConfig",forceUpdate:e,commandTimeout:!1,executor:async t=>{let s=await this.getObject("system.config");s??={},s.common??={},s.native??={},t(s)}})}getCompactSystemConfig(e){return this.request({cacheKey:"systemConfigCommon",forceUpdate:e,commandTimeout:!1,requireAdmin:!0,executor:(t,s)=>{this._socket.emit("getCompactSystemConfig",(o,r)=>{o?s(o):(r??={},r.common??={},r.native??={},t(r))})}})}getForeignStates(e){return this.request({commandTimeout:!1,executor:(t,s)=>{this._socket.emit("getForeignStates",e||"*",(o,r)=>{o?s(o):t(r??{})})}})}getForeignObjects(e,t){return this.request({commandTimeout:!1,executor:(s,o)=>{this._socket.emit("getForeignObjects",e||"*",t,(r,M)=>{r?o(r):s(M)})}})}setSystemConfig(e){return this.setObject("system.config",e)}getRawSocket(){return this._socket}getHistory(e,t){return this.request({commandTimeout:!1,executor:(s,o)=>{this._socket.emit("getHistory",e,t,(r,M)=>{r?o(r):s(M)})}})}getHistoryEx(e,t){return this.request({commandTimeout:!1,executor:(s,o)=>{this._socket.emit("getHistory",e,t,(r,M,a,u)=>{r?o(r):s({values:M,sessionId:u,step:a})})}})}getIpAddresses(e,t){return e=tt(e),this.request({cacheKey:`IPs_${e}`,forceUpdate:t,commandTimeout:!1,executor:async s=>{const o=await this.getObject(e);s((o==null?void 0:o.common.address)??[])}})}getVersion(e){return this.request({cacheKey:"version",forceUpdate:e,commandTimeout:!1,executor:(t,s)=>{this._socket.emit("getVersion",(o,r,M)=>{o&&!r&&typeof o=="string"&&o.match(/\d+\.\d+\.\d+/)?t({version:o,serverName:"socketio"}):o?s(o):t({version:r,serverName:M})})}})}getWebServerName(){return this.request({cacheKey:"webName",commandTimeout:!1,executor:(e,t)=>{this._socket.emit("getAdapterName",(s,o)=>{s?t(s):e(o)})}})}fileExists(e,t){return this.request({commandTimeout:!1,executor:(s,o)=>{this._socket.emit("fileExists",e,t,(r,M)=>{r?o(r):s(!!M)})}})}getCurrentUser(){return this.request({commandTimeout:!1,executor:e=>{this._socket.emit("authEnabled",(t,s)=>{e(s)})}})}getUuid(){return this.request({cacheKey:"uuid",commandTimeout:!1,executor:async e=>{var s;const t=await this.getObject("system.meta.uuid");e((s=t==null?void 0:t.native)==null?void 0:s.uuid)}})}checkFeatureSupported(e,t){return this.request({cacheKey:`supportedFeatures_${e}`,forceUpdate:t,commandTimeout:!1,executor:(s,o)=>{this._socket.emit("checkFeatureSupported",e,(r,M)=>{r?o(r):s(M)})}})}getAdapterInstances(e,t){return typeof e=="boolean"&&(t=e,e=""),e||="",this.request({cacheKey:`instances_${e}`,forceUpdate:t,commandTimeout:!1,executor:async s=>{const o=e?`system.adapter.${e}.`:"system.adapter.",r=`${o}香`,M=await this.getObjectViewSystem("instance",o,r),a=Object.values(M);s(e?a.filter(u=>u.common.name===e):a)}})}getAdapters(e,t){return typeof e=="boolean"&&(t=e,e=""),e||="",this.request({cacheKey:`adapter_${e}`,forceUpdate:t,commandTimeout:!1,executor:async s=>{const o=await this.getObjectViewSystem("adapter",`system.adapter.${e||""}`,`system.adapter.${e||"香"}`),r=Object.values(o);s(e?r.filter(M=>M.common.name===e):r)}})}getGroups(e){return this.request({cacheKey:"groups",forceUpdate:e,commandTimeout:!1,executor:(t,s)=>{this._socket.emit("getObjectView","system","group",{startkey:"system.group.",endkey:"system.group.香"},(o,r)=>{o?s(o):t(qi(r))})}})}logout(){return this.request({commandTimeout:!1,executor:(e,t)=>{this._socket.emit("logout",s=>{s?t(s):e(null)})}})}subscribeOnInstance(e,t,s,o){return this.request({commandTimeout:!1,executor:(r,M)=>{this._socket.emit("clientSubscribe",e,t,s,(a,u)=>{a?M(a):u&&(u.error?M(u.error):(e.startsWith("system.adapter.")||(e=`system.adapter.${e}`),this._instanceSubscriptions[e]=this._instanceSubscriptions[e]||[],this._instanceSubscriptions[e].find(l=>l.messageType===t&&l.callback===o)||this._instanceSubscriptions[e].push({messageType:t,callback:o}),r(u)))})}})}unsubscribeFromInstance(e,t,s){var M;e.startsWith("system.adapter.")||(e=`system.adapter.${e}`);let o;const r=[];do{o=!1;const a=(M=this._instanceSubscriptions[e])==null?void 0:M.findIndex(u=>(!t||u.messageType===t)&&(!s||u.callback===s));if(a!=null&&a!==-1){o=!0;const u=this._instanceSubscriptions[e][a].messageType;this._instanceSubscriptions[e].splice(a,1),this._instanceSubscriptions[e].length||delete this._instanceSubscriptions[e],this._instanceSubscriptions[e]&&this._instanceSubscriptions[e].find(N=>N.messageType===u)||r.push(this.request({commandTimeout:!1,executor:(N,c)=>{this._socket.emit("clientUnsubscribe",e,t,(L,j)=>L?c(L):N(j))}}))}}while(o&&(!s||!t));return r.length?Promise.all(r).then(a=>!!a.find(u=>u)):Promise.resolve(!1)}log(e,t){return e?this.request({commandTimeout:!1,executor:s=>(this._socket.emit("log",e,t),s(null))}):Promise.resolve(null)}setStateToIgnore(e){this.ignoreState=e}}function fc(i,e){if(!e)return;let t;if(e.length<700&&(e.indexOf("/")!==-1||e.indexOf("\\")!==-1))if(i.toLowerCase().includes("private"))t="private";else if(e.toLowerCase().includes("private"))t="private";else if(i.toLowerCase().includes("public"))t="public";else if(e.toLowerCase().includes("public"))t="public";else if(i.toLowerCase().includes("chain"))t="chained";else if(e.toLowerCase().includes("chain"))t="chained";else return;else t=e.substring(0,26)==="-----BEGIN RSA PRIVATE KEY"||e.substring(0,22)==="-----BEGIN PRIVATE KEY"?"private":"public",t==="public"&&e.split("-----END CERTIFICATE-----").filter(o=>o.replace(/\r\n|\r|\n/,"").trim()).length>1&&(t="chained");return{name:i,type:t}}function xc(i){var s,o,r,M;const e=[{name:"[IPv4] 0.0.0.0 - Listen on all IPs",address:"0.0.0.0",family:"ipv4"}],t=[{name:"[IPv6] :: - Listen on all IPs",address:"::",family:"ipv6"}];if((o=(s=i.native)==null?void 0:s.hardware)!=null&&o.networkInterfaces){const a=(M=(r=i.native)==null?void 0:r.hardware)==null?void 0:M.networkInterfaces;Object.keys(a).forEach(u=>{var l;(l=a[u])==null||l.forEach(N=>{N.family!=="IPv6"?e.push({name:`[${N.family}] ${N.address} - ${u}`,address:N.address,family:"ipv4"}):t.push({name:`[${N.family}] ${N.address} - ${u}`,address:N.address,family:"ipv6"})})})}return{IPs4:e,IPs6:t}}class X0e extends ge{constructor(e){super(e)}request(e){return super.request({requireAdmin:!0,...e})}getCertificates(e){return this.request({cacheKey:"cert",forceUpdate:e,commandTimeout:!1,executor:async t=>{var o;const s=await this.getObject("system.certificates");(o=s==null?void 0:s.native)!=null&&o.certificates?t(Object.entries(s.native.certificates).map(([r,M])=>fc(r,M)).filter(r=>!!r)):t([])}})}getLogs(e,t=200){return this.request({commandTimeout:!1,executor:s=>{this._socket.emit("sendToHost",e,"getLogs",t||200,o=>{s(o)})}})}upgradeAdapterWithWebserver(e,t){return this.request({commandTimeout:!1,executor:s=>{this._socket.emit("sendToHost",e,"upgradeAdapterWithWebserver",t,o=>{s(o)})}})}upgradeController(e,t,s){return this.request({commandTimeout:!1,executor:(o,r)=>{this._socket.emit("sendToHost",e,"upgradeController",{version:t,adminInstance:s},M=>{const a=M;a.error?r(a.error):o(a.result)})}})}updateLicenses(e,t){return this.request({commandTimeout:!1,executor:(s,o)=>{this._socket.emit("updateLicenses",e,t,(r,M)=>{r?o(r):s(M)})}})}upgradeOsPackages(e,t,s){return this.request({commandTimeout:!1,executor:o=>{this._socket.emit("sendToHost",e,"upgradeOsPackages",{packages:t,restart:!!s},r=>{o(r)})}})}getLogsFiles(e){return this.request({commandTimeout:!1,executor:(t,s)=>{this._socket.emit("readLogs",e,(o,r)=>{o&&s(o),t(r)})}})}delLogs(e){return this.request({commandTimeout:!1,executor:(t,s)=>{this._socket.emit("sendToHost",e,"delLogs",null,o=>{o&&s(o),t()})}})}deleteFile(e,t){return this.request({commandTimeout:!1,executor:(s,o)=>{this._socket.emit("deleteFile",e,t,r=>{r&&o(r),s()})}})}deleteFolder(e,t){return this.request({commandTimeout:!1,executor:(s,o)=>{this._socket.emit("deleteFolder",e,t,r=>{r&&o(r),s()})}})}rename(e,t,s){return this.request({commandTimeout:!1,executor:(o,r)=>{this._socket.emit("rename",e,t,s,M=>{M&&r(M),o()})}})}renameFile(e,t,s){return this.request({commandTimeout:!1,executor:(o,r)=>{this._socket.emit("renameFile",e,t,s,M=>{M&&r(M),o()})}})}getHosts(e){return this.request({cacheKey:"hosts",forceUpdate:e,commandTimeout:!1,executor:(t,s)=>{this._socket.emit("getObjectView","system","host",{startkey:"system.host.",endkey:"system.host.香"},(o,r)=>{o?s(o):t(qi(r))})}})}getUsers(e){return this.request({cacheKey:"users",forceUpdate:e,commandTimeout:!1,executor:(t,s)=>{this._socket.emit("getObjectView","system","user",{startkey:"system.user.",endkey:"system.user.香"},(o,r)=>{o?s(o):t(qi(r))})}})}renameGroup(e,t,s){return this.request({commandTimeout:!1,executor:async o=>{const r=await this.getGroups(!0),M=r.filter(u=>u._id.startsWith(`${e}.`));for(const u of M){const l=u._id,N=t+u._id.substring(e.length);u._id=N,await this.setObject(N,u),await this.delObject(l)}const a=r.find(u=>u._id===e);if(a){const u=a._id;a._id=t,s!==void 0&&(a.common??={},a.common.name=s),await this.setObject(t,a),await this.delObject(u)}o()}})}getHostInfo(e,t,s){return e=tt(e),this.request({cacheKey:`hostInfo_${e}`,forceUpdate:t,commandTimeout:s,executor:(o,r,M)=>{this._socket.emit("sendToHost",e,"getHostInfo",null,a=>{M.elapsed||(M.clearTimeout(),a===ye.PERMISSION_ERROR?r('May not read "getHostInfo"'):a?o(a):r('Cannot read "getHostInfo"'))})}})}getHostInfoShort(e,t,s){return e=tt(e),this.request({cacheKey:`hostInfoShort_${e}`,forceUpdate:t,commandTimeout:s,executor:(o,r,M)=>{this._socket.emit("sendToHost",e,"getHostInfoShort",null,a=>{M.elapsed||(M.clearTimeout(),a===ye.PERMISSION_ERROR?r('May not read "getHostInfoShort"'):a?o(a):r('Cannot read "getHostInfoShort"'))})}})}getRepository(e,t,s,o){return this.request({cacheKey:`repository_${e}`,forceUpdate:s,commandTimeout:o,executor:(r,M,a)=>{this._socket.emit("sendToHost",e,"getRepository",t,u=>{a.elapsed||(a.clearTimeout(),u===ye.PERMISSION_ERROR?M('May not read "getRepository"'):u?r(u):M('Cannot read "getRepository"'))})}})}getInstalled(e,t,s){return e=tt(e),this.request({cacheKey:`installed_${e}`,forceUpdate:t,commandTimeout:s,executor:(o,r,M)=>{this._socket.emit("sendToHost",e,"getInstalled",null,a=>{M.elapsed||(M.clearTimeout(),a===ye.PERMISSION_ERROR?r('May not read "getInstalled"'):a?o(a):r('Cannot read "getInstalled"'))})}})}cmdExec(e,t,s,o){return this.request({commandTimeout:o,executor:(r,M,a)=>{e=tt(e),this._socket.emit("cmdExec",e,s,t,u=>{a.elapsed||(a.clearTimeout(),u&&M(u),r())})}})}readBaseSettings(e){return e=cs(e),this.request({requireFeatures:["CONTROLLER_READWRITE_BASE_SETTINGS"],executor:(t,s,o)=>{this._socket.emit("sendToHost",e,"readBaseSettings",null,r=>{o.elapsed||(o.clearTimeout(),r===ye.PERMISSION_ERROR?s('May not read "BaseSettings"'):r?r.error?s(new Error(r.error)):t(r):s('Cannot read "BaseSettings"'))})}})}writeBaseSettings(e,t){return e=cs(e),this.request({requireFeatures:["CONTROLLER_READWRITE_BASE_SETTINGS"],executor:(s,o,r)=>{this._socket.emit("sendToHost",e,"writeBaseSettings",t,M=>{r.elapsed||(r.clearTimeout(),M===ye.PERMISSION_ERROR?o('May not write "BaseSettings"'):M?s(M):o('Cannot write "BaseSettings"'))})}})}restartController(e){return e=cs(e),this.request({executor:(t,s,o)=>{this._socket.emit("sendToHost",e,"restartController",null,()=>{o.elapsed||(o.clearTimeout(),t(!0))})}})}getDiagData(e,t){return e=cs(e),this.request({executor:(s,o,r)=>{this._socket.emit("sendToHost",e,"getDiagData",t,M=>{r.elapsed||(r.clearTimeout(),s(M||null))})}})}changePassword(e,t){return this.request({executor:(s,o,r)=>{this._socket.emit("changePassword",e,t,M=>{r.elapsed||(r.clearTimeout(),M&&o(M),s())})}})}getIpAddresses(e,t){return e=tt(e),this.request({cacheKey:`IPs_${e}`,forceUpdate:t,commandTimeout:!1,executor:async s=>{const o=await this.getObject(e);s((o==null?void 0:o.common.address)??[])}})}getHostByIp(e,t){return e=cs(e),this.request({cacheKey:`rIPs_${e}`,forceUpdate:t,executor:(s,o,r)=>{this._socket.emit("getHostByIp",e,(M,a)=>{if(r.elapsed)return;r.clearTimeout();const{IPs4:u,IPs6:l}=xc(a);s([...u,...l])})}})}encrypt(e){return this.request({executor:(t,s,o)=>{this._socket.emit("encrypt",e,(r,M)=>{o.elapsed||(o.clearTimeout(),r&&s(r),t(M))})}})}decrypt(e){return this.request({executor:(t,s,o)=>{this._socket.emit("decrypt",e,(r,M)=>{o.elapsed||(o.clearTimeout(),r&&s(r),t(M))})}})}chmodFile(e,t,s){return this.request({executor:(o,r,M)=>{this._socket.emit("chmodFile",e,t,s,(a,u)=>{M.elapsed||(M.clearTimeout(),a&&r(a),o(u))})}})}chownFile(e,t,s){return this.request({executor:(o,r,M)=>{this._socket.emit("chownFile",e,t,s,(a,u)=>{M.elapsed||(M.clearTimeout(),a&&r(a),o(u))})}})}getNotifications(e,t){return this.request({executor:(s,o,r)=>{this._socket.emit("sendToHost",e,"getNotifications",{category:t},M=>{r.elapsed||(r.clearTimeout(),s(M))})}})}clearNotifications(e,t){return this.request({executor:(s,o,r)=>{this._socket.emit("sendToHost",e,"clearNotifications",{category:t},M=>{r.elapsed||(r.clearTimeout(),s(M))})}})}getIsEasyModeStrict(){return this.request({executor:(e,t,s)=>{this._socket.emit("getIsEasyModeStrict",(o,r)=>{s.elapsed||(s.clearTimeout(),o&&t(o),e(!!r))})}})}getEasyMode(){return this.request({executor:(e,t,s)=>{this._socket.emit("getEasyMode",(o,r)=>{s.elapsed||(s.clearTimeout(),o?t(new Error(o)):e(r))})}})}getRatings(e){return this.request({executor:(t,s,o)=>{this._socket.emit("getRatings",!!e,(r,M)=>{o.elapsed||(o.clearTimeout(),r?s(new Error(r)):t(M))})}})}getCurrentSession(e){const t=new AbortController;return this.request({commandTimeout:e||5e3,onTimeout:()=>{t.abort()},executor:async(s,o,r)=>{try{const M=await fetch("./session",{signal:t.signal});if(r.elapsed)return;r.clearTimeout();const a=await M.json();s(a)}catch(M){o(`getCurrentSession: ${M}`)}}})}getCurrentInstance(){return this.request({cacheKey:"currentInstance",executor:(e,t,s)=>{this._socket.emit("getCurrentInstance",(o,r)=>{s.elapsed||(s.clearTimeout(),o?t(o):e(r))})}})}getAdapterInstances(e,t){let s;return typeof e=="boolean"?(t=e,s=""):s=e||"",this.request({cacheKey:`instances_${s}`,forceUpdate:t,executor:(o,r,M)=>{this._socket.emit("getAdapterInstances",s,(a,u)=>{M.elapsed||(M.clearTimeout(),a&&r(a),o(u))})}})}getAdapters(e,t){let s;return typeof e=="boolean"?(t=e,s=""):s=e||"",this.request({cacheKey:`adapter_${s}`,forceUpdate:t,executor:(o,r,M)=>{this._socket.emit("getAdapters",s,(a,u)=>{M.elapsed||(M.clearTimeout(),a&&r(a),o(u))})}})}getCompactAdapters(e){return this.request({cacheKey:"compactAdapters",forceUpdate:e,executor:(t,s,o)=>{this._socket.emit("getCompactAdapters",(r,M)=>{o.elapsed||(o.clearTimeout(),r&&s(r),t(M))})}})}getAdaptersResetCache(e){e=e??"",this.resetCache(`adapter_${e}`),this.resetCache("compactAdapters")}getCompactInstances(e){return this.request({cacheKey:"compactInstances",forceUpdate:e,executor:(t,s,o)=>{this._socket.emit("getCompactInstances",(r,M)=>{o.elapsed||(o.clearTimeout(),r&&s(r),t(M))})}})}getAdapterInstancesResetCache(e){e=e??"",this.resetCache(`instances_${e}`),this.resetCache("compactInstances")}getCompactInstalled(e,t,s){return e=tt(e),this.request({cacheKey:`installedCompact_${e}`,forceUpdate:t,commandTimeout:s,executor:(o,r,M)=>{this._socket.emit("getCompactInstalled",e,a=>{M.elapsed||(M.clearTimeout(),a===ye.PERMISSION_ERROR?r('May not read "getCompactInstalled"'):a?o(a):r('Cannot read "getCompactInstalled"'))})}})}getInstalledResetCache(e){e?(this.resetCache(`installedCompact_${e}`),this.resetCache(`installed_${e}`)):(this.resetCache("installedCompact_",!0),this.resetCache("installed_",!0))}getCompactRepository(e,t,s){return e=tt(e),this.request({cacheKey:`repositoryCompact_${e}`,forceUpdate:t,commandTimeout:s,executor:(o,r,M)=>{this._socket.emit("getCompactRepository",e,a=>{M.elapsed||(M.clearTimeout(),a===ye.PERMISSION_ERROR?r('May not read "getCompactRepository"'):a?o(a):r('Cannot read "getCompactRepository"'))})}})}getRepositoryResetCache(e){e?(this.resetCache(`repositoryCompact_${e}`),this.resetCache(`repository_${e}`)):(this.resetCache("repositoryCompact_",!0),this.resetCache("repository_",!0))}getCompactHosts(e){return this.request({cacheKey:"hostsCompact",forceUpdate:e,executor:(t,s,o)=>{this._socket.emit("getCompactHosts",(r,M)=>{o.elapsed||(o.clearTimeout(),r&&s(r),t(M))})}})}getCompactSystemRepositories(e){return this.reques