UNPKG

iobroker.javascript

Version:
1 lines 1.81 MB
import{o as We,a as UM,b as $M,d as PM,c as P,j as $,P as _}from"./createSvgIcon-DlIk-fDn.js";import{R as a,i as x}from"./iobroker_javascript__loadShare__react__loadShare__-i8pXne9X.js";import{i as j,c as Ne,C as Oe,a as ot,L as OL,g as fL,k as fi,j as CN,H as pN,b as AN,S as EL,T as K,U as xL,V as _L,W as SL,X as kL,Y as WM,Z as YL,$ as vL,a0 as QL,a1 as bL,a2 as UL,a3 as BM,a4 as $L,a5 as PL,a6 as WL,a7 as BL,a8 as JL,a9 as RL,aa as FL,ab as GL,ac as HL,ad as VL,ae as ZL,af as XL,ag as JM,ah as RM,ai as KL,aj as FM,t as qL,ak as eg,al as tg,am as sg,an as GM,ao as ig,ap as rg,aq as og,N as ng,h as Nn,I as Ji}from"./index-Cjl4b70e.js";import{I as Ln}from"./Save-DXaUpIPM.js";import{c as ar,g as ag}from"./_commonjsHelpers-Cpj98o6Y.js";import{u as Mg}from"./useTheme-DakN8Abq.js";import{t as F}from"./index-DZ3lKVw8.js";import"./iobroker_javascript__mf_v__runtimeInit__mf_v__-DZdFIfoQ.js";const fo=11/23/100;function HM(s){const e={r:0,g:0,b:0};if(s.length===7)e.r=parseInt(s.substring(1,3),16),e.g=parseInt(s.substring(3,5),16),e.b=parseInt(s.substring(5,7),16);else if(s.length===4){const t=s[1],i=s[2],r=s[3];e.r=parseInt(t+t,16),e.g=parseInt(i+i,16),e.b=parseInt(r+r,16)}return e}function cg(s){return`#${Math.round(s.r).toString(16)}${Math.round(s.g).toString(16)}${Math.round(s.b).toString(16)}`}function ug(s,e,t){const i=HM(s),r=HM(e);return i.r+=r.r*(.05+fo*(t-1)),i.g+=r.g*(.05+fo*(t-1)),i.b+=r.b*(.05+fo*(t-1)),cg(i)}function Eo(s,e){const t={};for(let i=1;i<=24;i++)t[`elevation${i}`]={backgroundColor:ug(s,e,i)};return t}function lg(s,e){var n,M,c,l,N,u,L,g,y,T,D;let t,i;s==="dark"?(i={MuiAppBar:{colorDefault:{backgroundColor:"#272727"}},MuiLink:{root:{textTransform:"uppercase",transition:"color .3s ease",color:We[200],"&:hover":{color:We[100]}}},MuiPaper:Eo("#121212","#fff")},t={name:s,palette:{mode:"dark",background:{paper:"#121212",default:"#121212"},primary:{main:"#4dabf5"},secondary:{main:"#436a93"},expert:"#14bb00",text:{primary:"#ffffff",secondary:"#ffffff"}}}):s==="blue"?(i={MuiAppBar:{colorDefault:{backgroundColor:"#3399CC"}},MuiLink:{root:{textTransform:"uppercase",transition:"color .3s ease",color:We[400],"&:hover":{color:We[300]}}}},t={name:s,palette:{mode:"dark",background:{paper:"#151d21",default:"#151d21"},primary:{main:"#4dabf5"},secondary:{main:"#436a93"},expert:"#14bb00",text:{primary:"#ffffff",secondary:"#ffffff"}}}):s==="colored"?(i={MuiAppBar:{colorDefault:{backgroundColor:"#2a3135"}},MuiLink:{root:{textTransform:"uppercase",transition:"color .3s ease",color:We[200],"&:hover":{color:We[100]}}},MuiPaper:Eo("#151d21","#fff")},t={name:s,palette:{mode:"light",primary:{main:"#3399CC"},secondary:{main:"#164477"},expert:"#96fc96"}}):s==="PT"?(i={MuiAppBar:{colorDefault:{backgroundColor:"#0F99DE"}},MuiLink:{root:{textTransform:"uppercase",transition:"color .3s ease",color:We[400],"&:hover":{color:We[300]}}}},t={name:s,palette:{mode:"light",primary:{main:"#0F99DE"},secondary:{main:"#88A536"},expert:"#BD1B24"}}):s==="NW"?(i={MuiAppBar:{colorDefault:{backgroundColor:"#272727"}},MuiLink:{root:{textTransform:"uppercase",transition:"color .3s ease",color:We[400],"&:hover":{color:We[300]}}},MuiPaper:Eo("#121212","#fff")},t={name:s,palette:{mode:"dark",background:{paper:"#121212",default:"#121212"},primary:{main:"#00af78"},secondary:{main:"#005a40"},expert:"#14bb00",text:{primary:"#ffffff",secondary:"#ffffff"}}}):(i={MuiLink:{root:{textTransform:"uppercase",transition:"color .3s ease",color:We[400],"&:hover":{color:We[300]}}}},t={name:s,palette:{mode:"light",primary:{main:"#3399CC",dark:"#256c97",light:"#76d0fd"},secondary:{main:"#164477"},expert:"#14bb00"}}),t.toolbar={height:48},t.saveToolbar={background:(M=(n=t.palette)==null?void 0:n.primary)==null?void 0:M.main,button:{borderRadius:3,height:32}},t.palette&&(t.palette.grey={main:UM[300],dark:UM[400]});const r=$M(t),o=r.palette;return $M(r,{...e||void 0,components:{...i,MuiButton:{variants:[{props:{variant:"contained",color:"grey"},style:{backgroundColor:(c=o.grey)==null?void 0:c[300],color:o.getContrastText&&((l=o.grey)!=null&&l[300])?o.getContrastText(o.grey[300]):void 0}},{props:{variant:"outlined",color:"grey"},style:{color:(N=o.text)==null?void 0:N.primary,borderColor:o.mode==="light"?"rgba(0, 0, 0, 0.23)":"rgba(255, 255, 255, 0.23)","&.Mui-disabled":{border:`1px solid ${(u=o.action)==null?void 0:u.disabledBackground}`},"&:hover":{borderColor:o.mode==="light"?"rgba(0, 0, 0, 0.23)":"rgba(255, 255, 255, 0.23)",backgroundColor:PM(((L=o.text)==null?void 0:L.primary)||"",((g=o.action)==null?void 0:g.hoverOpacity)||.04)}}},{props:{variant:"text",color:"grey"},style:{color:(y=o.text)==null?void 0:y.primary,"&:hover":{backgroundColor:PM(((T=o.text)==null?void 0:T.primary)||"",((D=o.action)==null?void 0:D.hoverOpacity)||.04)}}}]},...(e==null?void 0:e.components)||void 0}})}function Ng(){let s,e;const t=new Promise((i,r)=>{s=i,e=r});return t.resolve=s,t.reject=e,t}function gn(s){return(s==null?void 0:s.rows.map(e=>e.value).filter(e=>!!e))??[]}function Tt(s){return s!=null&&s.startsWith("system.host.")||(s=`system.host.${s}`),s}function Ni(s){return s!=null&&s.startsWith("system.host.")&&(s=s.substring(12)),s}function VM(s){return new Promise(e=>{setTimeout(e,s)})}function Mr(s){s=(s||"").toString();const e=s[0]==="*",t=s[s.length-1]==="*";return s=s.replace(/[-/\\^$+?.()|[\]{}]/g,"\\$&").replace(/\*/g,".*"),(e?"":"^")+s+(t?"":"$")}typeof globalThis.process<"u"&&(globalThis.location||={href:"http://localhost:8081/",protocol:"http:",host:"localhost:8081",pathname:"/",hostname:"localhost",reload:()=>{}},globalThis.localStorage||={_keys:{},setItem:(s,e)=>{globalThis.localStorage._keys[s]=e},getItem:s=>s in globalThis.localStorage._keys?globalThis.localStorage._keys[s]:null,removeItem:s=>{s in globalThis.localStorage._keys&&delete globalThis.localStorage._keys[s]}},globalThis.sessionStorage||=globalThis.localStorage,globalThis.navigator||={language:"en"});var it;(function(s){s[s.CONNECTING=0]="CONNECTING",s[s.CONNECTED=1]="CONNECTED",s[s.OBJECTS_LOADED=2]="OBJECTS_LOADED",s[s.READY=3]="READY"})(it||(it={}));var Ce;(function(s){s.PERMISSION_ERROR="permissionError",s.NOT_CONNECTED="notConnectedError",s.TIMEOUT="timeout",s.NOT_ADMIN="Allowed only in admin",s.NOT_SUPPORTED="Not supported"})(Ce||(Ce={}));const v5e=Ce.PERMISSION_ERROR;Ce.NOT_CONNECTED;const Lg=["material","echarts","vis"];class ze{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=Ng();_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 i=1;i<=30;i++){if(globalThis.io||globalThis.iob)return e();await VM(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,i=(this.props.protocol||globalThis.location.protocol).replace(":",""),r=globalThis.location.pathname;if(globalThis.location.hostname==="iobroker.net"||globalThis.location.hostname==="iobroker.pro")r="";else{if(globalThis.socketUrl){const c=new globalThis.URL(globalThis.socketUrl);e=c.hostname,t=c.port,i=c.protocol.replace(":","")}const M=r.lastIndexOf("/");if(M!==-1&&(r=r.substring(0,M+1)),ze.isWeb()){const c=r.split("/");c.length>2&&(c.pop(),c.pop(),Lg.includes(c[c.length-1])&&c.pop(),r=c.join("/"),r.endsWith("/")||(r+="/"))}}const o=t?`${i}://${e}:${t}`:`${i}://${e}`,n=this.props.connect||(globalThis.io||globalThis.iob).connect;return this._socket=n(o,{path:r.endsWith("/")?`${r}socket.io`:`${r}/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",M=>{var l;(l=globalThis.addEventListener)==null||l.call(globalThis,"storage",this.onAccessTokenUpdated);const c=ze.readTokens();if(c&&!c.owner){const N=Date.now();this.saveTokens({access_token:c.access_token,refresh_token:c.refresh_token,expires_in:Math.round((c.expires_in.getTime()-N)/1e3),refresh_token_expires_in:Math.round((c.refresh_token_expires_in.getTime()-N)/1e3),token_type:"Bearer"},c.stayLoggedIn)}this.onReadyDone=!1,M!==!0?(this.connected=!0,setTimeout(()=>this.getVersion().then(N=>{const[u,L,g]=N.version.split(".");parseInt(u,10)*1e4+parseInt(L,10)*100+parseInt(g,10)<40102?(this._authTimer=null,this.onPreConnect(!1,!1)):this._socket.emit("authenticate",(T,D)=>this.onPreConnect(T,D))}).catch(N=>this.onError({message:N.toString(),operation:"getVersion"})),500)):this._socket.emit("authenticate",(N,u)=>{this.onPreConnect(N,u)})}),this._socket.on("reconnect",()=>{var M,c;this.onReadyDone=!1,(c=(M=this.props).onProgress)==null||c.call(M,it.READY),this.connected=!0,this.waitForRestart?globalThis.location.reload():(this._subscribe(!0),this.onConnectionHandlers.forEach(l=>l(!0)))}),this._socket.on("disconnect",()=>{var M,c;this.onReadyDone=!1,this.connected=!1,this.subscribed=!1,(c=(M=this.props).onProgress)==null||c.call(M,it.CONNECTING),this.onConnectionHandlers.forEach(l=>l(!1))}),this._socket.on("reauthenticate",()=>this.authenticate()),this._socket.on("log",M=>{var c,l;(l=(c=this.props).onLog)==null||l.call(c,M),this.onLogHandlers.forEach(N=>N(M))}),this._socket.on("error",M=>{let c;M==null?c="":typeof M.toString=="function"?c=M.toString():(c=JSON.stringify(M),console.error(`Received strange error: ${c}`)),c.includes("User not authorized")?this.authenticate():c.includes("websocket error")?(console.error(`Socket Error => reload: ${M}`),globalThis.location.reload()):console.error(`Socket Error: ${M}`)}),this._socket.on("connect_error",M=>console.error(`Connect error: ${M}`)),this._socket.on("permissionError",M=>this.onError({message:"no permission",operation:M.operation,type:M.type,id:M.id||""})),this._socket.on("objectChange",(M,c)=>{setTimeout(()=>this.objectChange(M,c),0)}),this._socket.on("stateChange",(M,c)=>{setTimeout(()=>this.stateChange(M,c),0)}),this._socket.on("im",(M,c,l)=>{setTimeout(()=>this.instanceMessage(M,c,l),0)}),this._socket.on("fileChange",(M,c,l)=>{setTimeout(()=>this.fileChange(M,c,l),0)}),this._socket.on("cmdStdout",(M,c)=>{var l;(l=this.onCmdStdoutHandler)==null||l.call(this,M,c)}),this._socket.on("cmdStderr",(M,c)=>{var l;(l=this.onCmdStderrHandler)==null||l.call(this,M,c)}),this._socket.on("cmdExit",(M,c)=>{var l;(l=this.onCmdExitHandler)==null||l.call(this,M,c)}),Promise.resolve()}onPreConnect(e,t){var i,r;this._authTimer&&(clearTimeout(this._authTimer),this._authTimer=null),this.connected=!0,this.isSecure=t,this.waitForRestart?globalThis.location.reload():(this.firstConnect?this.loadData().catch(o=>{console.error(`Cannot load data: ${o}`)}):(r=(i=this.props).onProgress)==null||r.call(i,it.READY),this._subscribe(!0),this.onConnectionHandlers.forEach(o=>o(!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[i,r,o,n,M]=e.split(";"),c=new Date(r);return c.getTime()<Date.now()?null:{refresh_token:i,refresh_token_expires_in:c,access_token:o,expires_in:new Date(n),owner:M,stayLoggedIn:t}}static saveTokensStatic(e,t,i){const r=`${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()}${i?`;${i}`:""}`;t?globalThis.localStorage.setItem("iob_tokens",r):globalThis.sessionStorage.setItem("iob_tokens",r)}saveTokens(e,t){ze.saveTokensStatic(e,t,this.connId)}static deleteTokensStatic(){globalThis.localStorage.removeItem("iob_tokens"),globalThis.sessionStorage.removeItem("iob_tokens")}deleteTokens(e,t){const i=ze.readTokens();i&&(t?ze.deleteTokensStatic():i.stayLoggedIn===e&&i.owner===this.connId&&(i.stayLoggedIn?globalThis.localStorage.removeItem("iob_tokens"):globalThis.sessionStorage.removeItem("iob_tokens")))}onAccessTokenUpdated=e=>{if(e.key==="iob_tokens"){const t=ze.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,i)=>{t?(console.error(`[UPDATE/${new Date().toISOString()}] cannot say to server about new token: ${t}`),globalThis.location.reload()):i?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(i=>{if(i.ok)return i.json();throw new Error("Cannot refresh access token")}).then(i=>{if(i.access_token)console.log(`[REFRESH/${new Date().toISOString()}] received new token: ${i.access_token}`),this.saveTokens(i,e.stayLoggedIn),this.releaseTokenLock(),this.updateTokenExpiration(i.access_token);else throw new Error("Cannot get access token")}).catch(i=>{console.warn(`[REFRESH/${new Date().toISOString()}] cannot refresh token: ${i}`),this.releaseTokenLock(),this.deleteTokens(e.stayLoggedIn),console.error(i),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 r=JSON.parse(t);if(e<r.expiry)return!1}catch{}const i={connId:this.connId,expiry:e+10*1e3};return globalThis.localStorage.setItem("iob_token_semaphore",JSON.stringify(i)),!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=ze.readTokens();if(e){const t=e.expires_in.getTime();if(t<Date.now()+3e4){const i=t<Date.now()+5500;console.log(`[TOKEN/${new Date().toISOString()}] Updating refresh token ${e.access_token}`),e.refresh_token?e.owner===this.connId||i?(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(r=>{r?(console.log(`[TOKEN/${new Date().toISOString()}] Token will be prolonged`),this.refreshTokens(e,i)):(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,i))):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",(i,r)=>{i?t(i):e(r||null)})}})}async loadData(){if(this.loaded)return;const e=10;for(let t=1;t<=e;t++){if(this.doLoadData().catch(i=>console.error(`Cannot load data: ${i}`)),this.loaded)return;await VM(ze.isCloud()?5e3:1e3)}}async doLoadData(){var e,t,i,r,o,n,M,c,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&&!ze.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)),(i=(t=this.props).onLanguage)==null||i.call(t,this.systemLang),this.loaded=!0,(o=(r=this.props).onProgress)==null||o.call(r,it.CONNECTED),this.firstConnect=!1,this.props.doNotLoadAllObjects?this.props.admin5only?this.objects={}:this.objects={"system.config":this._systemConfig}:this.objects=await this.getObjects(),(M=(n=this.props).onProgress)==null||M.call(n,it.READY),this.onReadyDone||(this.onReadyDone=!0,(l=(c=this.props).onReady)==null||l.call(c,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,i,r;e.length===3?[t,i,r]=e:([t,r]=e,i=!1);let o;if(Array.isArray(t)?o=t:o=[t],typeof r!="function")throw new Error("The state change handler must be a function!");const n=[];for(let M=0;M<o.length;M++){const c=o[M];this.statesSubscribes[c]?!this.statesSubscribes[c].cbs.includes(r)&&this.statesSubscribes[c].cbs.push(r):(this.statesSubscribes[c]={reg:new RegExp(Mr(c)),cbs:[r]},t!==this.ignoreState&&n.push(c))}if(this.connected)if(n.length&&this._socket.emit("subscribe",n),i){let M;for(let c=0;c<o.length;c++){try{M=await this.getBinaryState(o[c])}catch(l){console.error(`Cannot getBinaryState "${o[c]}": ${JSON.stringify(l)}`),M=void 0}M!=null&&r(o[c],M)}}else if(o.find(M=>M.includes("*"))){let M;for(let c=0;c<o.length;c++){try{M=await this.getForeignStates(o[c])}catch(l){console.error(`Cannot getForeignStates "${o[c]}": ${JSON.stringify(l)}`);return}if(M)for(const[l,N]of Object.entries(M)){const u=r(l,N);u instanceof Promise&&u.catch(L=>console.error(`Cannot call state change handler: ${L}`))}}}else try{const M=await(ze.isWeb()?this.getStates(o):this.getForeignStates(o));if(M)for(const[c,l]of Object.entries(M)){const N=r(c,l);N instanceof Promise&&N.catch(u=>console.error(`Cannot call state change handler: ${u}`))}}catch(M){console.error(`Cannot getState "${o.join(", ")}": ${M.message}`);return}}async subscribeStateAsync(e,t){return this.subscribeState(e,t)}unsubscribeState(e,t){var o;let i;Array.isArray(e)?i=e:i=[e];const r=[];for(let n=0;n<i.length;n++){const M=i[n];if(this.statesSubscribes[M]){const c=this.statesSubscribes[M];if(t){const l=c.cbs.indexOf(t);l!==-1&&c.cbs.splice(l,1)}else c.cbs=[];(o=c.cbs)!=null&&o.length||(delete this.statesSubscribes[M],M!==this.ignoreState&&r.push(M))}}this.connected&&r.length&&this._socket.emit("unsubscribe",i)}subscribeObject(e,t){let i;if(Array.isArray(e)?i=e:i=[e],typeof t!="function")throw new Error("The object change handler must be a function!");const r=[];for(let o=0;o<i.length;o++){const n=i[o];this.objectsSubscribes[n]?!this.objectsSubscribes[n].cbs.includes(t)&&this.objectsSubscribes[n].cbs.push(t):(this.objectsSubscribes[n]={reg:new RegExp(Mr(n)),cbs:[t]},r.push(n))}return this.connected&&r.length&&this._socket.emit("subscribeObjects",r),Promise.resolve()}unsubscribeObject(e,t){var o;let i;Array.isArray(e)?i=e:i=[e];const r=[];for(let n=0;n<i.length;n++){const M=i[n];if(this.objectsSubscribes[M]){const c=this.objectsSubscribes[M];if(t){const l=c.cbs.indexOf(t);l!==-1&&c.cbs.splice(l,1)}else c.cbs=[];(o=c.cbs)!=null&&o.length||(delete this.objectsSubscribes[M],r.push(M))}}return this.connected&&r.length&&this._socket.emit("unsubscribeObjects",r),Promise.resolve()}objectChange(e,t){var o,n;let i;this.objects[e]&&(i={_id:e,type:this.objects[e].type});let r=!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,r=!0)):this.objects[e]&&(delete this.objects[e],r=!0);for(const[M,c]of Object.entries(this.objectsSubscribes))(M===e||c.reg.test(e))&&c.cbs.forEach(l=>{try{const N=l(e,t,i);N instanceof Promise&&N.catch(u=>console.error(`Cannot call object change handler: ${u}`))}catch(N){console.error(`Error by callback of objectChange: ${N}`)}});if(r){const M=(n=(o=this.props).onObjectChange)==null?void 0:n.call(o,e,t);M instanceof Promise&&M.catch(c=>console.error(`Cannot call object change handler: ${c}`))}}stateChange(e,t){for(const i of Object.values(this.statesSubscribes))if(i.reg.test(e))for(const r of i.cbs)try{const o=r(e,t??null);o instanceof Promise&&o.catch(n=>console.error(`Cannot call state change handler: ${n}`))}catch(o){console.error(`Error by callback of stateChanged: ${o}`)}}instanceMessage(e,t,i){var r;(r=this._instanceSubscriptions[t])==null||r.forEach(o=>{if(o.messageType===e){const n=o.callback(i,t,e);n instanceof Promise&&n.catch(M=>console.error(`Cannot call instance message handler: ${M}`))}})}fileChange(e,t,i){for(const r of Object.values(this.filesSubscribes))if(r.regId.test(e)&&r.regFilePattern.test(t))for(const o of r.cbs)try{o(e,t,i)}catch(n){console.error(`Error by callback of fileChange: ${n}`)}}async subscribeFiles(e,t,i){if(typeof i!="function")throw new Error("The state change handler must be a function!");let r;Array.isArray(t)?r=t:r=[t];const o=[];for(let n=0;n<r.length;n++){const M=r[n],c=`${e}$%$${M}`;this.filesSubscribes[c]?!this.filesSubscribes[c].cbs.includes(i)&&this.filesSubscribes[c].cbs.push(i):(this.filesSubscribes[c]={regId:new RegExp(Mr(e)),regFilePattern:new RegExp(Mr(M)),cbs:[i]},o.push(M))}return this.connected&&o.length&&this._socket.emit("subscribeFiles",e,o),Promise.resolve()}unsubscribeFiles(e,t,i){var n;let r;Array.isArray(t)?r=t:r=[t];const o=[];for(let M=0;M<r.length;M++){const c=r[M],l=`${e}$%$${c}`;if(this.filesSubscribes[l]){const N=this.filesSubscribes[l];if(i){const u=N.cbs.indexOf(i);u!==-1&&N.cbs.splice(u,1)}else N.cbs=[];(n=N.cbs)!=null&&n.length||(delete this.filesSubscribes[l],o.push(c))}}this.connected&&o.length&&this._socket.emit("unsubscribeFiles",e,o)}async request({cacheKey:e,forceUpdate:t,commandTimeout:i,onTimeout:r,requireAdmin:o,requireFeatures:n,executor:M}){if(o&&ze.isWeb())return Promise.reject(new Error(Ce.NOT_ADMIN));if(e&&!t&&e in this._promises)return this._promises[e];if(!this.connected)return Promise.reject(new Error(Ce.NOT_CONNECTED));if(n!=null&&n.length){for(const l of n)if(!await this.checkFeatureSupported(l))throw new Error(Ce.NOT_SUPPORTED)}const c=new Promise(async(l,N)=>{const u={elapsed:!1,clearTimeout:()=>{}};let L;i!==!1&&(L=setTimeout(()=>{u.elapsed=!0,r==null||r(),e&&this._promises[e]instanceof Promise&&delete this._promises[e],N(new Error(Ce.TIMEOUT))},i??this.props.cmdTimeout),u.clearTimeout=()=>{clearTimeout(L)});try{await M(l,N,u)}catch(g){e&&this._promises[e]instanceof Promise&&delete this._promises[e],N(new Error(g.toString()))}});return e&&(this._promises[e]=c),c}resetCache(e,t){t?Object.keys(this._promises).filter(i=>i.startsWith(e)).forEach(i=>{delete this._promises[i]}):delete this._promises[e]}getStates(e){return this.request({commandTimeout:!1,executor:(t,i)=>{this._socket.emit("getStates",e,(r,o)=>{this.states=o??{},r?i(r):t(this.states)})}})}getState(e){return this.request({commandTimeout:!1,executor:(t,i)=>{if(e&&e===this.ignoreState){t(this.simStates[e]||{val:null,ack:!0});return}this._socket.emit("getState",e,(r,o)=>{r?i(r):t(o)})}})}getBinaryState(e){return this.request({commandTimeout:!1,executor:(t,i)=>{this._socket.emit("getBinaryState",e,(r,o)=>{r?i(r):t(o)})}})}setBinaryState(e,t){return this.request({commandTimeout:!1,executor:(i,r)=>{this._socket.emit("setBinaryState",e,t,o=>{o?r(o):i()})}})}setState(e,t,i){return typeof i=="boolean"&&(t={val:t,ack:i}),this.request({commandTimeout:!1,executor:(r,o)=>{if(e&&e===this.ignoreState){let n;if(typeof i=="boolean"||typeof t=="object"&&t.val!==void 0?n=t:n={val:t,ack:!1,ts:Date.now(),lc:Date.now(),from:"system.adapter.vis.0"},this.simStates[e]=n,this.statesSubscribes[e])for(const M of this.statesSubscribes[e].cbs)try{const c=M(e,n);c instanceof Promise&&c.catch(l=>console.error(`Cannot call state change handler: ${l}`))}catch(c){console.error(`Error by callback of stateChanged: ${c}`)}r();return}this._socket.emit("setState",e,t,n=>{n?o(n):r()})}})}getObjects(e,t){return this.request({commandTimeout:!1,executor:(i,r)=>{if(!e&&this.objects){i(this.objects);return}this._socket.emit(ze.isWeb()?"getObjects":"getAllObjects",(o,n)=>{var M,c;t||(c=(M=this.props).onProgress)==null||c.call(M,it.OBJECTS_LOADED),o?r(o):(this.objects=n??{},i(this.objects))})}})}getObjectsById(e){return this.request({commandTimeout:!1,executor:(t,i)=>{this._socket.emit("getObjects",e,(r,o)=>{r?i(r):t(o)})}})}_subscribe(e){var t,i;if(e&&!this.subscribed){this.subscribed=!0,(t=this.props.autoSubscribes)!=null&&t.length&&this._socket.emit("subscribeObjects",this.props.autoSubscribes);const r=Object.keys(this.objectsSubscribes);r.length&&this._socket.emit("subscribeObjects",r),Object.keys(this.objectsSubscribes).forEach(o=>this._socket.emit("subscribeObjects",o)),this.props.autoSubscribeLog&&this._socket.emit("requireLog",!0),Object.keys(this.statesSubscribes).forEach(o=>this._socket.emit("subscribe",o)),Object.keys(this.filesSubscribes).forEach(o=>{const[n,M]=o.split("$%$");this._socket.emit("subscribeFiles",n,M)})}else if(!e&&this.subscribed){this.subscribed=!1,(i=this.props.autoSubscribes)!=null&&i.length&&this._socket.emit("unsubscribeObjects",this.props.autoSubscribes);const r=Object.keys(this.objectsSubscribes);r.length&&this._socket.emit("unsubscribeObjects",r),this.props.autoSubscribeLog&&this._socket.emit("requireLog",!1),Object.keys(this.statesSubscribes).forEach(o=>this._socket.emit("unsubscribe",o)),Object.keys(this.filesSubscribes).forEach(o=>{const[n,M]=o.split("$%$");this._socket.emit("unsubscribeFiles",n,M)})}}requireLog(e){return this.request({commandTimeout:!1,executor:(t,i)=>{this._socket.emit("requireLog",e,r=>{r?i(r):t()})}})}delObject(e,t=!1){return this.request({commandTimeout:!1,executor:(i,r)=>{this._socket.emit("delObject",e,{maintenance:t},o=>{o?r(o):i()})}})}delObjects(e,t){return this.request({commandTimeout:!1,executor:(i,r)=>{this._socket.emit("delObjects",e,{maintenance:t},o=>{o?r(o):i()})}})}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:(i,r)=>{this._socket.emit("setObject",e,t,o=>{o?r(o):i()})}})):Promise.reject(new Error("Null object is not allowed"))}getObject(e){return this.request({commandTimeout:!1,executor:(t,i)=>{if(e&&e===this.ignoreState){t({_id:this.ignoreState,type:"state",common:{name:"ignored state",type:"mixed"}});return}this._socket.emit("getObject",e,(r,o)=>{r?i(r):t(o)})}})}sendTo(e,t,i){return this.request({commandTimeout:!1,executor:r=>{this._socket.emit("sendTo",e,t,i,o=>{r(o)})}})}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:(i,r)=>{this._socket.emit("extendObject",e,t,o=>{o?r(o):i()})}})):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:(i,r)=>{this._socket.emit("getObjectView","system","enum",{startkey:`enum.${e||""}`,endkey:e?`enum.${e}.香`:"enum.香"},(o,n)=>{if(o)r(o);else{const M={};if(n)for(let c=0;c<n.rows.length;c++)e&&n.rows[c].id===`enum.${e}`||(M[n.rows[c].id]=n.rows[c].value);i(M)}})}})}getObjectView(e,t,i){return this.getObjectViewCustom("system",i,e,t)}async getObjectViewSystem(e,t,i){var n;const r=`${e}_${t||""}_${i||""}`,o=await this.getObjectViewCustom("system",e,t,i);return(n=this.objectViewCached)!=null&&n[r]&&(this.objectViewCached[r]=o),o}async getObjectViewSystemCached(e,t,i){var n;const r=`${e}_${t||""}_${i||""}`;if((n=this.objectViewCached)!=null&&n[r])return Promise.resolve(this.objectViewCached[r]);const o=await this.getObjectViewCustom("system",e,t,i);return this.objectViewCached||={},this.objectViewCached[r]=o,o}getObjectViewCustom(e,t,i,r){return this.request({commandTimeout:!1,executor:(o,n)=>{i||="",r||="香",this._socket.emit("getObjectView",e,t,{startkey:i,endkey:r},(M,c)=>{if(M)n(M);else{const l={};if(c&&c.rows)for(let N=0;N<c.rows.length;N++)l[c.rows[N].id]=c.rows[N].value;o(l)}})}})}readMetaItems(){return this.request({commandTimeout:!1,executor:(e,t)=>{this._socket.emit("getObjectView","system","meta",{startkey:"",endkey:"香"},(i,r)=>{var o;i?t(i):e((o=r.rows)==null?void 0:o.map(n=>n.value).filter(n=>!!n))})}})}readDir(e,t){return this.request({commandTimeout:!1,executor:(i,r)=>{this._socket.emit("readDir",e,t,(o,n)=>{o?r(o):i(n)})}})}readFile(e,t,i){return this.request({commandTimeout:!1,executor:(r,o)=>{this._socket.emit(i?"readFile64":"readFile",e,t,(n,M,c)=>{n?o(n):r({file:M,mimeType:c})})}})}writeFile64(e,t,i){return this.request({commandTimeout:!1,executor:(r,o)=>{if(typeof i=="string")this._socket.emit("writeFile",e,t,i,n=>{n?o(n):r()});else{const n=btoa(new Uint8Array(i).reduce((M,c)=>M+String.fromCharCode(c),""));this._socket.emit("writeFile64",e,t,n,M=>{M?o(M):r()})}}})}deleteFile(e,t){return this.request({commandTimeout:!1,executor:(i,r)=>{this._socket.emit("deleteFile",e,t,o=>{o?r(o):i()})}})}deleteFolder(e,t){return this.request({commandTimeout:!1,executor:(i,r)=>{this._socket.emit("deleteFolder",e,t,o=>{o?r(o):i()})}})}rename(e,t,i){return this.request({commandTimeout:!1,executor:(r,o)=>{this._socket.emit("rename",e,t,i,n=>{n?o(n):r()})}})}renameFile(e,t,i){return this.request({commandTimeout:!1,executor:(r,o)=>{this._socket.emit("renameFile",e,t,i,n=>{n?o(n):r()})}})}cmdExec(e,t,i,r){return this.request({commandTimeout:r,executor:(o,n,M)=>{e=Tt(e),this._socket.emit("cmdExec",e,i,t,c=>{M.elapsed||(M.clearTimeout(),c?n(c):o())})}})}getSystemConfig(e){return this.request({cacheKey:"systemConfig",forceUpdate:e,commandTimeout:!1,executor:async t=>{let i=await this.getObject("system.config");i??={},i.common??={},i.native??={},t(i)}})}getCompactSystemConfig(e){return this.request({cacheKey:"systemConfigCommon",forceUpdate:e,commandTimeout:!1,requireAdmin:!0,executor:(t,i)=>{this._socket.emit("getCompactSystemConfig",(r,o)=>{r?i(r):(o??={},o.common??={},o.native??={},t(o))})}})}getForeignStates(e){return this.request({commandTimeout:!1,executor:(t,i)=>{this._socket.emit("getForeignStates",e||"*",(r,o)=>{r?i(r):t(o??{})})}})}getForeignObjects(e,t){return this.request({commandTimeout:!1,executor:(i,r)=>{this._socket.emit("getForeignObjects",e||"*",t,(o,n)=>{o?r(o):i(n)})}})}setSystemConfig(e){return this.setObject("system.config",e)}getRawSocket(){return this._socket}getHistory(e,t){return this.request({commandTimeout:!1,executor:(i,r)=>{this._socket.emit("getHistory",e,t,(o,n)=>{o?r(o):i(n)})}})}getHistoryEx(e,t){return this.request({commandTimeout:!1,executor:(i,r)=>{this._socket.emit("getHistory",e,t,(o,n,M,c)=>{o?r(o):i({values:n,sessionId:c,step:M})})}})}getIpAddresses(e,t){return e=Tt(e),this.request({cacheKey:`IPs_${e}`,forceUpdate:t,commandTimeout:!1,executor:async i=>{const r=await this.getObject(e);i((r==null?void 0:r.common.address)??[])}})}getVersion(e){return this.request({cacheKey:"version",forceUpdate:e,commandTimeout:!1,executor:(t,i)=>{this._socket.emit("getVersion",(r,o,n)=>{r&&!o&&typeof r=="string"&&r.match(/\d+\.\d+\.\d+/)?t({version:r,serverName:"socketio"}):r?i(r):t({version:o,serverName:n})})}})}getWebServerName(){return this.request({cacheKey:"webName",commandTimeout:!1,executor:(e,t)=>{this._socket.emit("getAdapterName",(i,r)=>{i?t(i):e(r)})}})}fileExists(e,t){return this.request({commandTimeout:!1,executor:(i,r)=>{this._socket.emit("fileExists",e,t,(o,n)=>{o?r(o):i(!!n)})}})}getCurrentUser(){return this.request({commandTimeout:!1,executor:e=>{this._socket.emit("authEnabled",(t,i)=>{e(i)})}})}getUuid(){return this.request({cacheKey:"uuid",commandTimeout:!1,executor:async e=>{var i;const t=await this.getObject("system.meta.uuid");e((i=t==null?void 0:t.native)==null?void 0:i.uuid)}})}checkFeatureSupported(e,t){return this.request({cacheKey:`supportedFeatures_${e}`,forceUpdate:t,commandTimeout:!1,executor:(i,r)=>{this._socket.emit("checkFeatureSupported",e,(o,n)=>{o?r(o):i(n)})}})}getAdapterInstances(e,t){return typeof e=="boolean"&&(t=e,e=""),e||="",this.request({cacheKey:`instances_${e}`,forceUpdate:t,commandTimeout:!1,executor:async i=>{const r=e?`system.adapter.${e}.`:"system.adapter.",o=`${r}香`,n=await this.getObjectViewSystem("instance",r,o),M=Object.values(n);i(e?M.filter(c=>c.common.name===e):M)}})}getAdapters(e,t){return typeof e=="boolean"&&(t=e,e=""),e||="",this.request({cacheKey:`adapter_${e}`,forceUpdate:t,commandTimeout:!1,executor:async i=>{const r=await this.getObjectViewSystem("adapter",`system.adapter.${e||""}`,`system.adapter.${e||"香"}`),o=Object.values(r);i(e?o.filter(n=>n.common.name===e):o)}})}getGroups(e){return this.request({cacheKey:"groups",forceUpdate:e,commandTimeout:!1,executor:(t,i)=>{this._socket.emit("getObjectView","system","group",{startkey:"system.group.",endkey:"system.group.香"},(r,o)=>{r?i(r):t(gn(o))})}})}logout(){return this.request({commandTimeout:!1,executor:(e,t)=>{this._socket.emit("logout",i=>{i?t(i):e(null)})}})}subscribeOnInstance(e,t,i,r){return this.request({commandTimeout:!1,executor:(o,n)=>{this._socket.emit("clientSubscribe",e,t,i,(M,c)=>{M?n(M):c&&(c.error?n(c.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===r)||this._instanceSubscriptions[e].push({messageType:t,callback:r}),o(c)))})}})}unsubscribeFromInstance(e,t,i){var n;e.startsWith("system.adapter.")||(e=`system.adapter.${e}`);let r;const o=[];do{r=!1;const M=(n=this._instanceSubscriptions[e])==null?void 0:n.findIndex(c=>(!t||c.messageType===t)&&(!i||c.callback===i));if(M!=null&&M!==-1){r=!0;const c=this._instanceSubscriptions[e][M].messageType;this._instanceSubscriptions[e].splice(M,1),this._instanceSubscriptions[e].length||delete this._instanceSubscriptions[e],this._instanceSubscriptions[e]&&this._instanceSubscriptions[e].find(N=>N.messageType===c)||o.push(this.request({commandTimeout:!1,executor:(N,u)=>{this._socket.emit("clientUnsubscribe",e,t,(L,g)=>L?u(L):N(g))}}))}}while(r&&(!i||!t));return o.length?Promise.all(o).then(M=>!!M.find(c=>c)):Promise.resolve(!1)}log(e,t){return e?this.request({commandTimeout:!1,executor:i=>(this._socket.emit("log",e,t),i(null))}):Promise.resolve(null)}setStateToIgnore(e){this.ignoreState=e}}function gg(s,e){if(!e)return;let t;if(e.length<700&&(e.indexOf("/")!==-1||e.indexOf("\\")!==-1))if(s.toLowerCase().includes("private"))t="private";else if(e.toLowerCase().includes("private"))t="private";else if(s.toLowerCase().includes("public"))t="public";else if(e.toLowerCase().includes("public"))t="public";else if(s.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(r=>r.replace(/\r\n|\r|\n/,"").trim()).length>1&&(t="chained");return{name:s,type:t}}function jg(s){var i,r,o,n;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((r=(i=s.native)==null?void 0:i.hardware)!=null&&r.networkInterfaces){const M=(n=(o=s.native)==null?void 0:o.hardware)==null?void 0:n.networkInterfaces;Object.keys(M).forEach(c=>{var l;(l=M[c])==null||l.forEach(N=>{N.family!=="IPv6"?e.push({name:`[${N.family}] ${N.address} - ${c}`,address:N.address,family:"ipv4"}):t.push({name:`[${N.family}] ${N.address} - ${c}`,address:N.address,family:"ipv6"})})})}return{IPs4:e,IPs6:t}}class Q5e extends ze{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 r;const i=await this.getObject("system.certificates");(r=i==null?void 0:i.native)!=null&&r.certificates?t(Object.entries(i.native.certificates).map(([o,n])=>gg(o,n)).filter(o=>!!o)):t([])}})}getLogs(e,t=200){return this.request({commandTimeout:!1,executor:i=>{this._socket.emit("sendToHost",e,"getLogs",t||200,r=>{i(r)})}})}upgradeAdapterWithWebserver(e,t){return this.request({commandTimeout:!1,executor:i=>{this._socket.emit("sendToHost",e,"upgradeAdapterWithWebserver",t,r=>{i(r)})}})}upgradeController(e,t,i){return this.request({commandTimeout:!1,executor:(r,o)=>{this._socket.emit("sendToHost",e,"upgradeController",{version:t,adminInstance:i},n=>{const M=n;M.error?o(M.error):r(M.result)})}})}updateLicenses(e,t){return this.request({commandTimeout:!1,executor:(i,r)=>{this._socket.emit("updateLicenses",e,t,(o,n)=>{o?r(o):i(n)})}})}upgradeOsPackages(e,t,i){return this.request({commandTimeout:!1,executor:r=>{this._socket.emit("sendToHost",e,"upgradeOsPackages",{packages:t,restart:!!i},o=>{r(o)})}})}getLogsFiles(e){return this.request({commandTimeout:!1,executor:(t,i)=>{this._socket.emit("readLogs",e,(r,o)=>{r&&i(r),t(o)})}})}delLogs(e){return this.request({commandTimeout:!1,executor:(t,i)=>{this._socket.emit("sendToHost",e,"delLogs",null,r=>{r&&i(r),t()})}})}deleteFile(e,t){return this.request({commandTimeout:!1,executor:(i,r)=>{this._socket.emit("deleteFile",e,t,o=>{o&&r(o),i()})}})}deleteFolder(e,t){return this.request({commandTimeout:!1,executor:(i,r)=>{this._socket.emit("deleteFolder",e,t,o=>{o&&r(o),i()})}})}rename(e,t,i){return this.request({commandTimeout:!1,executor:(r,o)=>{this._socket.emit("rename",e,t,i,n=>{n&&o(n),r()})}})}renameFile(e,t,i){return this.request({commandTimeout:!1,executor:(r,o)=>{this._socket.emit("renameFile",e,t,i,n=>{n&&o(n),r()})}})}getHosts(e){return this.request({cacheKey:"hosts",forceUpdate:e,commandTimeout:!1,executor:(t,i)=>{this._socket.emit("getObjectView","system","host",{startkey:"system.host.",endkey:"system.host.香"},(r,o)=>{r?i(r):t(gn(o))})}})}getUsers(e){return this.request({cacheKey:"users",forceUpdate:e,commandTimeout:!1,executor:(t,i)=>{this._socket.emit("getObjectView","system","user",{startkey:"system.user.",endkey:"system.user.香"},(r,o)=>{r?i(r):t(gn(o))})}})}renameGroup(e,t,i){return this.request({commandTimeout:!1,executor:async r=>{const o=await this.getGroups(!0),n=o.filter(c=>c._id.startsWith(`${e}.`));for(const c of n){const l=c._id,N=t+c._id.substring(e.length);c._id=N,await this.setObject(N,c),await this.delObject(l)}const M=o.find(c=>c._id===e);if(M){const c=M._id;M._id=t,i!==void 0&&(M.common??={},M.common.name=i),await this.setObject(t,M),await this.delObject(c)}r()}})}getHostInfo(e,t,i){return e=Tt(e),this.request({cacheKey:`hostInfo_${e}`,forceUpdate:t,commandTimeout:i,executor:(r,o,n)=>{this._socket.emit("sendToHost",e,"getHostInfo",null,M=>{n.elapsed||(n.clearTimeout(),M===Ce.PERMISSION_ERROR?o('May not read "getHostInfo"'):M?r(M):o('Cannot read "getHostInfo"'))})}})}getHostInfoShort(e,t,i){return e=Tt(e),this.request({cacheKey:`hostInfoShort_${e}`,forceUpdate:t,commandTimeout:i,executor:(r,o,n)=>{this._socket.emit("sendToHost",e,"getHostInfoShort",null,M=>{n.elapsed||(n.clearTimeout(),M===Ce.PERMISSION_ERROR?o('May not read "getHostInfoShort"'):M?r(M):o('Cannot read "getHostInfoShort"'))})}})}getRepository(e,t,i,r){return this.request({cacheKey:`repository_${e}`,forceUpdate:i,commandTimeout:r,executor:(o,n,M)=>{this._socket.emit("sendToHost",e,"getRepository",t,c=>{M.elapsed||(M.clearTimeout(),c===Ce.PERMISSION_ERROR?n('May not read "getRepository"'):c?o(c):n('Cannot read "getRepository"'))})}})}getInstalled(e,t,i){return e=Tt(e),this.request({cacheKey:`installed_${e}`,forceUpdate:t,commandTimeout:i,executor:(r,o,n)=>{this._socket.emit("sendToHost",e,"getInstalled",null,M=>{n.elapsed||(n.clearTimeout(),M===Ce.PERMISSION_ERROR?o('May not read "getInstalled"'):M?r(M):o('Cannot read "getInstalled"'))})}})}cmdExec(e,t,i,r){return this.request({commandTimeout:r,executor:(o,n,M)=>{e=Tt(e),this._socket.emit("cmdExec",e,i,t,c=>{M.elapsed||(M.clearTimeout(),c&&n(c),o())})}})}readBaseSettings(e){return e=Ni(e),this.request({requireFeatures:["CONTROLLER_READWRITE_BASE_SETTINGS"],executor:(t,i,r)=>{this._socket.emit("sendToHost",e,"readBaseSettings",null,o=>{r.elapsed||(r.clearTimeout(),o===Ce.PERMISSION_ERROR?i('May not read "BaseSettings"'):o?o.error?i(new Error(o.error)):t(o):i('Cannot read "BaseSettings"'))})}})}writeBaseSettings(e,t){return e=Ni(e),this.request({requireFeatures:["CONTROLLER_READWRITE_BASE_SETTINGS"],executor:(i,r,o)=>{this._socket.emit("sendToHost",e,"writeBaseSettings",t,n=>{o.elapsed||(o.clearTimeout(),n===Ce.PERMISSION_ERROR?r('May not write "BaseSettings"'):n?i(n):r('Cannot write "BaseSettings"'))})}})}restartController(e){return e=Ni(e),this.request({executor:(t,i,r)=>{this._socket.emit("sendToHost",e,"restartController",null,()=>{r.elapsed||(r.clearTimeout(),t(!0))})}})}getDiagData(e,t){return e=Ni(e),this.request({executor:(i,r,o)=>{this._socket.emit("sendToHost",e,"getDiagData",t,n=>{o.elapsed||(o.clearTimeout(),i(n||null))})}})}changePassword(e,t){return this.request({executor:(i,r,o)=>{this._socket.emit("changePassword",e,t,n=>{o.elapsed||(o.clearTimeout(),n&&r(n),i())})}})}getIpAddresses(e,t){return e=Tt(e),this.request({cacheKey:`IPs_${e}`,forceUpdate:t,commandTimeout:!1,executor:async i=>{const r=await this.getObject(e);i((r==null?void 0:r.common.address)??[])}})}getHostByIp(e,t){return e=Ni(e),this.request({cacheKey:`rIPs_${e}`,forceUpdate:t,executor:(i,r,o)=>{this._socket.emit("getHostByIp",e,(n,M)=>{if(o.elapsed)return;o.clearTimeout();const{IPs4:c,IPs6:l}=jg(M);i([...c,...l])})}})}encrypt(e){return this.request({executor:(t,i,r)=>{this._socket.emit("encrypt",e,(o,n)=>{r.elapsed||(r.clearTimeout(),o&&i(o),t(n))})}})}decrypt(e){return this.request({executor:(t,i,r)=>{this._socket.emit("decrypt",e,(o,n)=>{r.elapsed||(r.clearTimeout(),o&&i(o),t(n))})}})}chmodFile(e,t,i){return this.request({executor:(r,o,n)=>{this._socket.emit("chmodFile",e,t,i,(M,c)=>{n.elapsed||(n.clearTimeout(),M&&o(M),r(c))})}})}chownFile(e,t,i){return this.request({executor:(r,o,n)=>{this._socket.emit("chownFile",e,t,i,(M,c)=>{n.elapsed||(n.clearTimeout(),M&&o(M),r(c))})}})}getNotifications(e,t){return this.request({executor:(i,r,o)=>{this._socket.emit("sendToHost",e,"getNotifications",{category:t},n=>{o.elapsed||(o.clearTimeout(),i(n))})}})}clearNotifications(e,t){return this.request({executor:(i,r,o)=>{this._socket.emit("sendToHost",e,"clearNotifications",{category:t},n=>{o.elapsed||(o.clearTimeout(),i(n))})}})}getIsEasyModeStrict(){return this.request({executor:(e,t,i)=>{this._socket.emit("getIsEasyModeStrict",(r,o)=>{i.elapsed||(i.clearTimeout(),r&&t(r),e(!!o))})}})}getEasyMode(){return this.request({executor:(e,t,i)=>{this._socket.emit("getEasyMode",(r,o)=>{i.elapsed||(i.clearTimeout(),r?t(new Error(r)):e(o))})}})}getRatings(e){return this.request({executor:(t,i,r)=>{this._socket.emit("getRatings",!!e,(o,n)=>{r.elapsed||(r.clearTimeout(),o?i(new Error(o)):t(n))})}})}getCurrentSession(e){const t=new AbortController;return this.request({commandTimeout:e||5e3,onTimeout:()=>{t.abort()},executor:async(i,r,o)=>{try{const n=await fetch("./session",{signal:t.signal});if(o.elapsed)return;o.clearTimeout();const M=await n.json();i(M)}catch(n){r(`getCurrentSession: ${n}`)}}})}getCurrentInstance(){return this.request({cacheKey:"currentInstance",executor:(e,t,i)=>{this._socket.emit("getCurrentInstance",(r,o)=>{i.elapsed||(i.clearTimeout(),r?t(r):e(o))})}})}getAdapterInstances(e,t){let i;return typeof e=="boolean"?(t=e,i=""):i=e||"",this.request({cacheKey:`instances_${i}`,forceUpdate:t,executor:(r,o,n)=>{this._socket.emit("getAdapterInstances",i,(M,c)=>{n.elapsed||(n.clearTimeout(),M&&o(M),r(c))})}})}getAdapters(e,t){let i;return typeof e=="boolean"?(t=e,i=""):i=e||"",this.request({cacheKey:`adapter_${i}`,forceUpdate:t,executor:(r,o,n)=>{this._socket.emit("getAdapters",i,(M,c)=>{n.elapsed||(n.clearTimeout(),M&&o(M),r(c))})}})}getCompactAdapters(e){return this.request({cacheKey:"compactAdapters",forceUpdate:e,executor:(t,i,r)=>{this._socket.emit("getCompactAdapters",(o,n)=>{r.elapsed||(r.clearTimeout(),o&&i(o),t(n))})}})}getAdaptersResetCache(e){e=e??"",this.resetCache(`adapter_${e}`),this.resetCache("compactAdapters")}getCompactInstances(e){return this.request({cacheKey:"compactInstances",forceUpdate:e,executor:(t,i,r)=>{this._socket.emit("getCompactInstances",(o,n)=>{r.elapsed||(r.clearTimeout(),o&&i(o),t(n))})}})}getAdapterInstancesResetCache(e){e=e??"",this.resetCache(`instances_${e}`),this.resetCache("compactInstances")}getCompactInstalled(e,t,i){return e=Tt(e),this.request({cacheKey:`installedCompact_${e}`,forceUpdate:t,commandTimeout:i,executor:(r,o,n)=>{this._socket.emit("getCompactInstalled",e,M=>{n.elapsed||(n.clearTimeout(),M===Ce.PERMISSION_ERROR?o('May not read "getCompactInstalled"'):M?r(M):o('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,i){return e=Tt(e),this.request({cacheKey:`repositoryCompact_${e}`,forceUpdate:t,commandTimeout:i,executor:(r,o,n)=>{this._socket.emit("getCompactRepository",e,M=>{n.elapsed||(n.clearTimeout(),M===Ce.PERMISSION_ERROR?o('May not read "getCompactRepository"'):M?r(M):o('Cannot read "getCompactRepository"'))})}})}getRepositoryResetCache(e){e?(this.resetCache(`repositoryCompact_${e}`),this.resetCache(`repository_${e}`)):(this.resetCache("reposito