@eva-ics/webengine
Version:
EVA ICS HMI Web Engine
3 lines (2 loc) • 48.2 kB
JavaScript
var j=Object.defineProperty;var P=(b,w,e)=>w in b?j(b,w,{enumerable:!0,configurable:!0,writable:!0,value:e}):b[w]=e;var n=(b,w,e)=>(P(b,typeof w!="symbol"?w+"":w,e),e),$=(b,w,e)=>{if(!w.has(b))throw TypeError("Cannot "+e)};var N=(b,w,e)=>($(b,w,"read from private field"),e?e.call(b):w.get(b)),x=(b,w,e)=>{if(w.has(b))throw TypeError("Cannot add the same private member more than once");w instanceof WeakSet?w.add(b):w.set(b,e)},B=(b,w,e,t)=>($(b,w,"write to private field"),t?t.call(b,e):w.set(b,e),e);(function(b,w){typeof exports=="object"&&typeof module<"u"?w(exports,require("bmat/log"),require("bmat/dom")):typeof define=="function"&&define.amd?define(["exports","bmat/log","bmat/dom"],w):(b=typeof globalThis<"u"?globalThis:b||self,w(b.webengine={},b.log,b.dom))})(this,function(exports,log,dom){var b,w;"use strict";var m=Object.defineProperty,M=(e,t,s)=>t in e?m(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,g=(e,t,s)=>(M(e,typeof t!="symbol"?t+"":t,s),s),W=(e,t,s)=>{if(!t.has(e))throw TypeError("Cannot "+s)},u=(e,t,s)=>(W(e,t,"read from private field"),s?s.call(e):t.get(e)),E=(e,t,s)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,s)},h=(e,t,s,i)=>(W(e,t,"write to private field"),i?i.call(e,s):t.set(e,s),s);class C{constructor(){g(this,"subscribers"),g(this,"subtopics"),g(this,"subtopics_by_regex"),g(this,"subtopics_any"),g(this,"sub_any"),this.subscribers=new Set,this.subtopics=new Map,this.subtopics_by_regex=[],this.sub_any=new Set}isEmpty(){return this.subscribers.size===0&&this.subtopics.size===0&&this.subtopics_by_regex.length===0&&this.subtopics_any===void 0&&this.sub_any.size===0}}var l,_,f,p,y;class I{constructor(){g(this,"subscriptions"),g(this,"subscribed_topics"),E(this,l,void 0),E(this,_,void 0),E(this,f,void 0),E(this,p,void 0),E(this,y,void 0),this.subscriptions=new C,this.subscribed_topics=new Map,h(this,l,0),h(this,_,"/"),h(this,p,new Set(["?"])),h(this,y,new Set(["*"]))}separator(t){return h(this,_,t),this}regexPrefix(t){return h(this,f,t),this}matchAny(t){return Array.isArray(t)?h(this,p,new Set(t)):h(this,p,new Set([t])),this}wildcard(t){return Array.isArray(t)?h(this,y,new Set(t)):h(this,y,new Set([t])),this}listClients(){return Array.from(this.subscriptions.subscribers)}listTopics(t){return Array.from(this.subscribed_topics.get(t)||[])}isEmpty(){return this.subscribed_topics.size===0}registerClient(t){return this.subscribed_topics.has(t)?!1:(this.subscribed_topics.set(t,new Set),!0)}unregisterClient(t){const s=this.subscribed_topics.get(t);if(s===void 0)return!1;for(const i of s)d(this.subscriptions,i.split(u(this,_)),0,t,u(this,y),u(this,p),u(this,f)),h(this,l,u(this,l)-1);return this.subscribed_topics.delete(t),!0}subscribe(t,s){const i=this.subscribed_topics.get(s);return i===void 0?!1:(i.has(t)||(R(this.subscriptions,t.split(u(this,_)),0,s,u(this,y),u(this,p),u(this,f)),i.add(t),h(this,l,u(this,l)+1)),!0)}unsubscribe(t,s){const i=this.subscribed_topics.get(s);return i===void 0?!1:(i.has(t)&&(d(this.subscriptions,t.split(u(this,_)),0,s,u(this,y),u(this,p),u(this,f)),i.delete(t),h(this,l,u(this,l)-1)),!0)}unsubscribeAll(t){const s=this.subscribed_topics.get(t);if(s===void 0)return!1;for(const i of s)d(this.subscriptions,i.split(u(this,_)),0,t,u(this,y),u(this,p),u(this,f));return h(this,l,u(this,l)-s.size),s.clear(),!0}getSubscribers(t){const s=new Set;return z(this.subscriptions,t.split(u(this,_)),0,u(this,f),s),s}isSubscribed(t){return v(this.subscriptions,t.split(u(this,_)),0,u(this,f))}subscriptionCount(){return u(this,l)}clientCount(){return this.subscribed_topics.size}}l=new WeakMap,_=new WeakMap,f=new WeakMap,p=new WeakMap,y=new WeakMap;function R(e,t,s,i,a,r,o){if(s<t.length){const c=t[s];if(a.has(c))e.sub_any.add(i);else if(r.has(c))e.subtopics_any||(e.subtopics_any=new C),R(e.subtopics_any,t,s+1,i,a,r,o);else if(o&&c.startsWith(o)){const A=c.slice(o.length);try{const O=new RegExp(A);let k=e.subtopics_by_regex.find(T=>T.regex.source===O.source);k||(k={regex:O,sub:new C},e.subtopics_by_regex.push(k)),R(k.sub,t,s+1,i,a,r,o)}catch{}}else e.subtopics.has(c)||e.subtopics.set(c,new C),R(e.subtopics.get(c),t,s+1,i,a,r,o)}else e.subscribers.add(i)}function d(e,t,s,i,a,r,o){if(s<t.length){const c=t[s];if(a.has(c))e.sub_any.delete(i);else if(r.has(c))e.subtopics_any&&(d(e.subtopics_any,t,s+1,i,a,r,o),e.subtopics_any.isEmpty()&&(e.subtopics_any=void 0));else if(o&&c.startsWith(o)){const A=c.slice(o.length);try{const O=new RegExp(A),k=e.subtopics_by_regex.findIndex(T=>T.regex.source===O.source);if(k!==-1){const T=e.subtopics_by_regex[k].sub;d(T,t,s+1,i,a,r,o),T.isEmpty()&&e.subtopics_by_regex.splice(k,1)}}catch{}}else{const A=e.subtopics.get(c);A&&(d(A,t,s+1,i,a,r,o),A.isEmpty()&&e.subtopics.delete(c))}}else e.subscribers.delete(i)}function z(e,t,s,i,a){if(s<t.length){const r=t[s];for(const o of e.sub_any)a.add(o);if(i&&r.startsWith(i)){const o=r.slice(i.length);try{const c=new RegExp(o);for(const[A,O]of e.subtopics)c.test(A)&&z(O,t,s+1,i,a)}catch{}}else{const o=e.subtopics.get(r);o&&z(o,t,s+1,i,a)}for(const o of e.subtopics_by_regex)o.regex.test(r)&&z(o.sub,t,s+1,i,a);e.subtopics_any&&z(e.subtopics_any,t,s+1,i,a)}else for(const r of e.subscribers)a.add(r)}function v(e,t,s,i){if(s<t.length){const a=t[s];if(e.sub_any.size>0)return!0;if(i&&a.startsWith(i)){const r=a.slice(i.length);try{const o=new RegExp(r);for(const[c,A]of e.subtopics)if(o.test(c)&&v(A,t,s+1,i))return!0}catch{}}else{const r=e.subtopics.get(a);if(r&&v(r,t,s+1,i))return!0}for(const r of e.subtopics_by_regex)if(r.regex.test(a)&&v(r.sub,t,s+1,i))return!0;if(e.subtopics_any&&v(e.subtopics_any,t,s+1,i))return!0}else if(e.subscribers.size>0)return!0;return!1}const eva_webengine_version="0.9.15",WILDCARDS=["*","#"],MATCH_ANY=["+","?"],isMask=e=>{for(let t of e)if(WILDCARDS.includes(t)||MATCH_ANY.includes(t))return!0;return!1};var SerializationKind=(e=>(e.JSON="json",e.MsgPack="msgpack",e))(SerializationKind||{}),EvaErrorKind=(e=>(e[e.NOT_FOUND=-32001]="NOT_FOUND",e[e.ACCESS_DENIED=-32002]="ACCESS_DENIED",e[e.SYSTEM_ERROR=-32003]="SYSTEM_ERROR",e[e.OTHER=-32004]="OTHER",e[e.NOT_READY=-32005]="NOT_READY",e[e.UNSUPPORTED=-32006]="UNSUPPORTED",e[e.CORE_ERROR=-32007]="CORE_ERROR",e[e.TIMEOUT=-32008]="TIMEOUT",e[e.INVALID_DATA=-32009]="INVALID_DATA",e[e.FUNC_FAILED=-32010]="FUNC_FAILED",e[e.ABORTED=-32011]="ABORTED",e[e.ALREADY_EXISTS=-32012]="ALREADY_EXISTS",e[e.BUSY=-32013]="BUSY",e[e.METHOD_NOT_IMPLEMENTED=-32014]="METHOD_NOT_IMPLEMENTED",e[e.TOKEN_RESTRICTED=-32015]="TOKEN_RESTRICTED",e[e.IO=-32016]="IO",e[e.REGISTRY=-32017]="REGISTRY",e[e.EVAHI_AUTH_REQUIRED=-32018]="EVAHI_AUTH_REQUIRED",e[e.ACCESS_DENIED_MORE_DATA_REQUIRED=-32022]="ACCESS_DENIED_MORE_DATA_REQUIRED",e[e.PARSE=-32700]="PARSE",e[e.INVALID_REQUEST=-32600]="INVALID_REQUEST",e[e.METHOD_NOT_FOUND=-32601]="METHOD_NOT_FOUND",e[e.INVALID_PARAMS=-32602]="INVALID_PARAMS",e[e.INTERNAL_RPC=-32603]="INTERNAL_RPC",e[e.BUS_CLIENT_NOT_REGISTERED=-32113]="BUS_CLIENT_NOT_REGISTERED",e[e.BUS_DATA=-32114]="BUS_DATA",e[e.BUS_IO=-32115]="BUS_IO",e[e.BUS_OTHER=-32116]="BUS_OTHER",e[e.BUS_NOT_SUPPORTED=-32117]="BUS_NOT_SUPPORTED",e[e.BUS_BUSY=-32118]="BUS_BUSY",e[e.BUS_NOT_DELIVERED=-32119]="BUS_NOT_DELIVERED",e[e.BUS_TIMEOUT=-32120]="BUS_TIMEOUT",e[e.BUS_ACCESS=-32121]="BUS_ACCESS",e))(EvaErrorKind||{}),EventKind=(e=>(e.HeartbeatSuccess="heartbeat.success",e.HeartbeatError="heartbeat.error",e.LoginSuccess="login.success",e.LoginFailed="login.failed",e.LoginOTPRequired="login.otp_required",e.LoginOTPInvalid="login.otp_invalid",e.LoginOTPSetup="login.otp_setup",e.WsEvent="ws.event",e.ServerReload="server.reload",e.ServerRestart="server.restart",e.LogRecord="log.record",e.LogPostProcess="log.postprocess",e.WASMError="wasm.error",e))(EventKind||{}),StateProp=(e=>(e.Status="status",e.Value="value",e.Any="any",e))(StateProp||{});const GLOBAL_BLOCK_NAME=".",ERR_REQUIRE_LOGGED_IN="Not logged in";var IntervalKind=(e=>(e.AjaxReload="ajax_reload",e.AjaxLogReload="log_reload",e.ActionWatch="action_watch",e.Heartbeat="heartbeat",e.Reload="reload",e.Restart="restart",e.WSBufTTL="ws_buf_ttl",e))(IntervalKind||{});class EvaError{constructor(t,s,i){n(this,"code");n(this,"message");n(this,"data");this.code=t,this.message=s,this.data=i}}class EvaBulkRequestPartHandler{constructor(){n(this,"fn_ok");n(this,"fn_err")}then(t){return this.fn_ok=t,this}catch(t){return this.fn_err=t,this}}class EvaBulkRequest{constructor(t){n(this,"requests");n(this,"payload");n(this,"eva");this.requests=new Map,this.payload=[],this.eva=t}prepare(t,s,i){let a;typeof s=="string"||Array.isArray(s)?(a=i||{},a.i=s):a=s;let r=this.eva._prepare_call_params(a),o=this.eva._prepare_api_call(t,r),c=new EvaBulkRequestPartHandler;return this.requests.set(o.id,c),this.payload.push(o),c}call(){let t=`${this.eva.api_uri}/jrpc`;return this.eva._debug("call_bulk",`${t}`),new Promise((s,i)=>{if(this.eva.allow_logged_in_calls_only&&!this.eva.logged_in)throw new EvaError(-32002,ERR_REQUIRE_LOGGED_IN);if(this.payload.length==0){s(!0);return}this.eva.external.fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"error",body:JSON.stringify(this.payload)}).then(a=>{if(a.ok)a.json().then(r=>{if(this.eva._debug("call_bulk success"),Array.isArray(r))r.forEach(o=>{if(typeof o.id>"u"||typeof o.result>"u"&&typeof o.error>"u")i({code:-32009,message:"Invalid server response",data:o});else{let c=o.id,A=this.requests.get(c),O,k;A!==void 0&&(O=A.fn_ok,k=A.fn_err),o.error!==void 0?(this.eva._debug("call_bulk req",`${c} failed: ${o.error.code} (${o.error.message})`),k&&k({code:o.error.code,message:o.error.message,data:o})):(this.eva.debug==2&&this.eva.log.info(`call_bulk API ${c} ${A.func} response`,o.result),O&&O(o.result))}}),s(!0);else{let o=-32009,c="Invalid server response (not an array)";this.eva._debug("call_bulk",`failed: ${o} (${c})`),i(new EvaError(o,c,r))}}).catch(r=>{let o=-32009,c="Invalid server response";this.eva._debug("call_bulk",`failed: ${o} (${c})`),i(new EvaError(o,c,r))});else{let r=-32007,o="Server error";this.eva._debug("call_bulk",`failed: ${r} (${o})`),i(new EvaError(r,o))}}).catch(a=>{let r=-32007,o="Server error";this.eva._debug("call_bulk",`failed: ${r} (${o})`),i(new EvaError(r,o,a))})})}}class Eva_ACTION{constructor(t){n(this,"eva");this.eva=t}async start(t,s=!0){return this.exec(t,{v:1},s)}async stop(t,s=!0){return this.exec(t,{v:0},s)}async toggle(t,s=!0){return this._act("action.toggle",t,{},s)}exec(t,s,i=!0){return this._act("action",t,s,i)}async kill(t){await this.eva.call("action.kill",t)}async terminate(t){let s="action.terminate";await this.eva.call(s,{u:t})}async run(t,s,i=!0){return this._act("run",t,s,i)}_act(t,s,i,a=!1){return new Promise((r,o)=>{this.eva.call(t,s,i).then(c=>{a===!1?r(c):this.eva.watch_action(c.uuid,A=>{A.uuid!==void 0?A.finished&&r(A):o(A)})}).catch(c=>{o(c)})})}}class Eva_LVAR{constructor(t){n(this,"eva");this.eva=t}async reset(t){await this.eva.call("lvar.reset",t)}async clear(t){await this.eva.call("lvar.clear",t)}async toggle(t){await this.eva.call("lvar.toggle",t)}async incr(t){return(await this.eva.call("lvar.incr",t)).result}async decr(t){return(await this.eva.call("lvar.decr",t)).result}async set(t,s,i){let a={};s!==void 0&&(a.status=s),i!==void 0&&(a.value=i),Object.keys(a).length&&await this.eva.call("lvar.set",t,a)}async set_status(t,s){await this.set(t,s)}async set_value(t,s){await this.set(t,s=s)}expires(t){let s=this.eva.state(t);if(s===void 0||s.t===void 0)return;if(!s.meta||s.meta.expires===void 0||s.meta.expires==0)return null;if(s.status==0)return-2;if(s.status==-1)return-1;let i=s.meta.expires-new Date().getTime()/1e3+this.eva.tsdiff+s.t;return i<0&&(i=0),i}}class _EvaStream{constructor(t,s,i){n(this,"oid");n(this,"eva");n(this,"name");n(this,"ws");n(this,"onStart");n(this,"onData");n(this,"onError");n(this,"onEOS");this.oid=t,this.name=s,this.eva=i,this.ws=null,this.onStart=()=>{},this.onData=a=>{},this.onError=a=>{this.eva.log.error(`Stream ${this.name} error`,a)},this.onEOS=()=>{}}_restart(){this._stop(),this._start()}_start(){if(!this.eva.ws_mode){this.onError(new EvaError(-32006,"WebSocket mode is disabled in EVA ICS WebEngine"));return}if(!this.eva.api_token){this.onError(new EvaError(-32002,"Not logged in"));return}let t=this.eva._get_ws_uri();t+=`k=${this.eva.api_token}`;const s=new this.eva.external.WebSocket(t);s.binaryType="arraybuffer",s.onerror=i=>{this.onError(new EvaError(-32010,`WebSocket error: ${i.type}`)),this._stop()},s.onmessage=i=>{if(typeof i.data=="string"){let a=JSON.parse(i.data);if(a.s!=="stream")return;switch(a.d){case"start":this.onStart();break;case"eos":this.onEOS();break;case"forbidden":this.onError(new EvaError(-32002,`Stream ${this.name} access denied (${this.oid})`)),this._stop();break}}else this.onData(i.data)},s.onclose=()=>{this._stop()},s.addEventListener("open",()=>{let i={m:"stream.start",p:{i:this.oid}};s.send(JSON.stringify(i)),s.send("")}),this.ws=s}_stop(){const t=this.ws;if(t)try{t.onclose=null,t.onmessage=()=>{},t.onerror=()=>{},t.close()}catch{setTimeout(()=>{try{t==null||t.close()}catch{}},100)}}}class _EvaStateBlock{constructor(t,s,i){n(this,"state_updates");n(this,"eva");n(this,"name");n(this,"_ajax_reloader");this.name=t,this.state_updates=s,this.eva=i}_start(){this.eva.ws_mode&&this.eva._start_ws(this.state_updates,this.name),this.eva._load_states(this.state_updates,this.name).then(()=>{if(this.eva.ws_mode){const t=this.eva._intervals.get("reload");t&&(this._ajax_reloader=setInterval(()=>{if(!this.eva.logged_in){this._stop();return}this.eva._load_states(this.state_updates,this.name)},t*1e3))}else this._ajax_reloader=setInterval(()=>{this.eva._load_states(this.state_updates,this.name)},this.eva._intervals.get("ajax_reload"))})}_restart(){this._stop(),this._start()}_stop(){this._ajax_reloader&&clearInterval(this._ajax_reloader);let t=this.eva.ws.get(this.name);if(t){this.eva.ws.delete(this.name);try{t.onclose=null,t.onerror=function(){},t.close()}catch{setTimeout(()=>{try{t==null||t.close()}catch{}},100)}}}}var TokenMode=(e=>(e.Normal="normal",e.ReadOnly="readonly",e))(TokenMode||{}),SessionAuthKind=(e=>(e.Token="token",e.Key="key",e.Login="login",e.No="unauthorized",e))(SessionAuthKind||{}),ACLOp=(e=>(e.Log="log",e.Developer="developer",e.Moderator="moderator",e.Supervisor="supervisor",e))(ACLOp||{}),LoginState=(e=>(e.Active="active",e.Starting="starting",e.Stopping="stopping",e.Inactive="inactive",e.Failed="failed",e.OTPRequired="otp.required",e.OTPInvalid="otp.invalid",e.OTPSetup="otp.setup",e))(LoginState||{});const defaultSessionState=()=>({login:"inactive",error:null,otp:null});var EventTopic=(e=>(e.ItemState="ST",e.Server="SERVER",e.Supervisor="SUPERVISOR",e.WeSession="WE/SESSION",e.WeItemState="WE/ST",e))(EventTopic||{});class Eva{constructor(){n(this,"action");n(this,"lvar");n(this,"api_uri");n(this,"ws_uri");x(this,b,void 0);n(this,"api_token");n(this,"authorized_user");n(this,"clear_unavailable");n(this,"debug");n(this,"allow_logged_in_calls_only");n(this,"external");n(this,"evajw");n(this,"in_evaHI");n(this,"log_params");n(this,"log");n(this,"logged_in");n(this,"login");n(this,"login_xopts");n(this,"log_level_names");x(this,w,void 0);n(this,"set_auth_cookies");n(this,"state_updates");n(this,"tsdiff");n(this,"version");n(this,"wasm");n(this,"ws_mode");n(this,"server_info");n(this,"ignore_password_set_on_next_login");n(this,"_event_map");n(this,"_api_call_id");n(this,"_handlers");n(this,"_intervals");n(this,"_ws_handler_registered");n(this,"_heartbeat_reloader");n(this,"_ajax_reloader");n(this,"_log_reloader");n(this,"_scheduled_restarter");n(this,"_states");n(this,"_blocks");n(this,"_streams");n(this,"_last_ping");n(this,"_last_pong");n(this,"ws");n(this,"_action_states");n(this,"_action_watch_functions");n(this,"_log_subscribed");n(this,"_log_started");n(this,"_log_first_load");n(this,"_log_loaded");n(this,"_update_state_functions");n(this,"_update_state_mask_functions");n(this,"_lr2p");n(this,"_deserializePromise",(e,t)=>{switch(t){case"msgpack":return new Promise((s,i)=>{e.arrayBuffer().then(a=>{try{const r=this.external.msgpack.decode(a);s(r)}catch(r){i(new EvaError(-32009,"Invalid MsgPack response",r))}})});case"json":return e.json();default:throw new EvaError(-32006,"Unknown serialization kind")}});this.version=eva_webengine_version,this.log=new log.Logger,this.login="",B(this,w,""),this.login_xopts=null,B(this,b,""),this.api_uri="",this.ws_uri="/ws",this.set_auth_cookies=!0,this.api_token="",this.authorized_user=null,this.logged_in=!1,this.ignore_password_set_on_next_login=!1,this.debug=!1,this.allow_logged_in_calls_only=!1,this.state_updates=!0,this.wasm=!1,this.clear_unavailable=!1,this._ws_handler_registered=!1,this.ws_mode=!0,this.ws=new Map,this._api_call_id=0,this.tsdiff=0,this._last_ping=new Map,this._last_ping.set(GLOBAL_BLOCK_NAME,null),this._last_pong=new Map,this._last_pong.set(GLOBAL_BLOCK_NAME,null),this._streams=new Map,this._log_subscribed=!1,this._log_started=!1,this._log_first_load=!1,this._log_loaded=!1,this._lr2p=[],this._event_map=null,this.in_evaHI=typeof navigator<"u"&&typeof navigator.userAgent=="string"&&navigator.userAgent.startsWith("evaHI "),this.log_params={level:20,records:200},this._update_state_functions=new Map,this._update_state_mask_functions=new Map,this._handlers=new Map,this._handlers.set("heartbeat.error",this.restart),this._handlers.set("wasm.error",e=>{this.log.error(e),this._critical("WASM load error",!0,!0)}),this._states=new Map,this._states.set(GLOBAL_BLOCK_NAME,new Map),this._blocks=new Map,this._intervals=new Map([["ajax_reload",2],["log_reload",2],["action_watch",.5],["heartbeat",5],["reload",5],["restart",1],["ws_buf_ttl",0]]),this.log_level_names=new Map([[10,"DEBUG"],[20,"INFO"],[30,"WARNING"],[40,"ERROR"],[50,"CRITICAL"]]),this._heartbeat_reloader=null,this._ajax_reloader=null,this._log_reloader=null,this._scheduled_restarter=null,this._action_watch_functions=new Map,this._action_states=new Map,this._clear(),this._clear_watchers(),this.action=new Eva_ACTION(this),this.lvar=new Eva_LVAR(this),this.evajw=null,this.external={},this.server_info=null,typeof window<"u"?typeof window.fetch<"u"&&(this.external.fetch=window.fetch.bind(window)):typeof fetch<"u"?this.external.fetch=fetch:this.external.fetch=null,typeof WebSocket<"u"?this.external.WebSocket=WebSocket:this.external.WebSocket=null,typeof window<"u"&&typeof window.QRious<"u"?this.external.QRious=window.QRious:this.external.QRious=null}enable_event_map(){this._event_map===null&&(this._event_map=new I().matchAny(MATCH_ANY).wildcard(WILDCARDS).regexPrefix("r~").separator("/"))}subscribe_event_topic(e,t){return this.enable_event_map(),this._event_map.registerClient(t),this._event_map.subscribe(e,t),!0}subscribe_event_topics(e,t){this.enable_event_map(),this._event_map.registerClient(t);for(let s of e)this._event_map.subscribe(s,t);return!0}unsubscribe_event_topic(e,t){var s;(s=this._event_map)==null||s.unsubscribe(e,t)}unsubscribe_event_topics(e,t){var s;for(let i of e)(s=this._event_map)==null||s.unsubscribe(i,t)}unsubscribe_all_event_topics(e){var t,s;(t=this._event_map)==null||t.unsubscribeAll(e),(s=this._event_map)==null||s.unregisterClient(e)}_push_event_topic(e,t){if(this._event_map){const s=this._event_map.getSubscribers(e);for(const i of s)i(e,t)}}set_login_password(e,t){this.login=e||"",B(this,w,t||""),B(this,b,"")}set_api_key(e){B(this,b,e||""),this.login="",B(this,w,"")}is_password_set(){return N(this,w)!==""}is_auth_set(){return N(this,b)!==""||this.login!==""&&N(this,w)!==""}clear_auth(){this.login="",B(this,w,""),B(this,b,"")}start_stream(e){const t=this._streams.get(e.oid);t&&t._stop();const s=new _EvaStream(e.oid,e.name,this);e.onStart&&(s.onStart=e.onStart),e.onData&&(s.onData=e.onData),e.onError&&(s.onError=e.onError),e.onEOS&&(s.onEOS=e.onEOS),this._streams.set(e.name,s),s._start()}stop_stream(e){let t=this._streams.get(e);t&&(t._stop(),this._streams.delete(e))}register_state_block(e,t){if(e==GLOBAL_BLOCK_NAME)throw new EvaError(-32602,`WebEngine state block name ${GLOBAL_BLOCK_NAME} is reserved`);check_state_updates(t);let s=this._blocks.get(e);s&&(console.error(`WebEngine state block ${e} has been already registered, removing the old instance`),s._stop());let i=new _EvaStateBlock(e,t,this);this.logged_in&&i._start(),this._blocks.set(e,i),this._init_block(e),this._push_event_topic(`WE/ST/${e}`,t)}unregister_state_block(e){let t=this._blocks.get(e);t&&(t._stop(),this._delete_block(e),this._blocks.delete(e),this._push_event_topic(`WE/ST/${e}`,null))}unregister_all_state_blocks(){for(let[e,t]of this._blocks)t._stop(),this._delete_block(e),this._push_event_topic(`WE/ST/${e}`,null);this._blocks.clear()}bulk_request(){return new EvaBulkRequest(this)}get_mode(){return"js"}start(){if(this._cancel_scheduled_restart(),this._debug("EVA ICS WebEngine",`version: ${this.version}`),typeof fetch>"u"){this.log.error('"fetch" function is unavailable. Upgrade your web browser or connect polyfill');return}if(this.logged_in){this._debug("start","already logged in");return}this.wasm&&!this.evajw?this._start_evajw():this._start_engine()}_start_engine(){this._push_event_topic("WE/SESSION",{login:"starting",error:null,otp:null}),this._clear_last_pings();let e={};if(N(this,b))e={k:N(this,b)},this.login_xopts&&(e.xopts=this.login_xopts),this._debug("start","logging in with API key");else if(this.api_token)e={a:this.api_token},this._debug("start","logging in with existing auth token");else if(N(this,w)&&!this.ignore_password_set_on_next_login)e={u:this.login,p:N(this,w)},this.api_token&&(e.a=this.api_token),this.login_xopts&&(e.xopts=this.login_xopts),this._debug("start","logging in with password");else if(this.set_auth_cookies){let s=dom.cookies.read("auth");s&&(e={a:s},this._debug("start","logging in with cookie-cached auth token"))}Object.keys(e).length===0&&this._debug("start","logging in without credentials");let t;return this.ignore_password_set_on_next_login=!1,this._api_call("login",e).then(s=>(this.api_token=s.token,t=s.user,this._set_token_cookie(),Promise.all([this._load_states(this.state_updates,GLOBAL_BLOCK_NAME),this._heartbeat(!0),this._start_ws(this.state_updates,GLOBAL_BLOCK_NAME)]))).then(()=>{if(!this.ws_mode)this._ajax_reloader&&clearInterval(this._ajax_reloader),this._ajax_reloader=setInterval(()=>{this._load_states(this.state_updates,GLOBAL_BLOCK_NAME).catch(()=>{})},this._intervals.get("ajax_reload")*1e3);else{this._ajax_reloader&&clearInterval(this._ajax_reloader);let s=this._intervals.get("reload");s&&(this._ajax_reloader=setInterval(()=>{this._load_states(this.state_updates,GLOBAL_BLOCK_NAME).catch(()=>{})},s*1e3))}this._heartbeat_reloader&&clearInterval(this._heartbeat_reloader),this._heartbeat_reloader=setInterval(()=>{this._heartbeat(!1).catch(()=>{})},this._intervals.get("heartbeat")*1e3),this._debug("start",`login successful, user: ${t}`),this.logged_in=!0,this.authorized_user=t,this._invoke_handler("login.success"),this._push_event_topic("WE/SESSION",{login:"active",error:null,otp:null});for(let[s,i]of this._blocks)i._restart()}).catch(s=>{this._debug("start",s),this.logged_in=!1,(s==null?void 0:s.code)===void 0&&(s=new EvaError(-32004,"Unknown error")),this._debug("start",`login failed: ${s.code} (${s.message})`),this._stop_engine(),(s.code!=-32007||s.message!="Server error")&&this.erase_token_cookie(),this.error_handler(s,"login")}),!0}system_name(){return this.server_info?this.server_info.system_name:null}async sleep(e){return new Promise(t=>setTimeout(t,e*1e3))}log_start(e){this._log_started=!0,e!==void 0&&(this.log_params.level=e),(!this.ws_mode||this._log_first_load)&&(this._log_loaded=!1,this._load_log_entries(!0),this.ws_mode||(this._log_reloader=setInterval(()=>{this._load_log_entries(!1)},this._intervals.get("log_reload")*1e3)))}async set_state_updates(e,t){check_state_updates(e),this.state_updates=e,this._push_event_topic("WE/ST",e);let s=this.ws.get(GLOBAL_BLOCK_NAME);if(s&&s.readyState===1){let i={m:"unsubscribe.state"};if(s.send(JSON.stringify(i)),s.send(""),this.state_updates){let a={m:"subscribe.state"},r;this.state_updates==!0?r=["#"]:r=this.state_updates,a.p=r,s.send(JSON.stringify(a)),s.send("")}}t&&this._clear_states(GLOBAL_BLOCK_NAME),await this._load_states(this.state_updates,GLOBAL_BLOCK_NAME)}set_log_level(e){this.log_params.level=e,this._set_ws_log_level(e),this._load_log_entries(!0)}restart(){this._cancel_scheduled_restart(),this._debug("restart","performing restart"),this.stop(!0,!0).then(()=>{this._schedule_restart()}).catch(()=>{this._schedule_restart()})}erase_token_cookie(){this.api_token="",this.authorized_user=null,this._set_token_cookie()}load_config(e){return new Promise((t,s)=>{const i=e||"config.json";this.log.debug("Eva::load_config",`loading configuration from ${i}`),this.external.fetch(i).then(a=>a.json()).then(a=>{this.apply_config(a),t(a)}).catch(a=>s(a))})}apply_config(e){const t=e.engine;t&&(t.api_uri&&(this.api_uri=t.api_uri),t.apikey&&B(this,b,t.apikey),t.debug!==void 0&&(this.debug=t.debug),t.login&&(this.login=t.login),t.password&&B(this,w,t.password),t.set_auth_cookies!==void 0&&(this.set_auth_cookies=t.set_auth_cookies),t.state_updates!==void 0&&(this.state_updates=t.state_updates,this._push_event_topic("WE/ST",this.state_updates)),t.wasm!==void 0&&(this.wasm=t.wasm),t.ws_mode!==void 0&&(this.ws_mode=t.ws_mode),t.log_params&&(this.log_params=t.log_params),t.interval&&Object.keys(t.interval).forEach(s=>{const i=s;this.set_interval(i,t.interval[i])}))}async api_call({method:e,params:t,serialization_kind:s}){return this.call(e,t,void 0,s)}async call(e,t,s,i){if(this.allow_logged_in_calls_only&&!this.logged_in)throw new EvaError(-32002,ERR_REQUIRE_LOGGED_IN);let a;typeof t=="string"||Array.isArray(t)?(a=s||{},a.i=t):a=t;let r=this._prepare_call_params(a);return this._api_call(e,r,i)}set_readonly(){return new Promise((e,t)=>{this.call("session.set_readonly").then(()=>{this.server_info&&(this.server_info.aci.token_mode="readonly"),this._push_event_topic("SERVER",this.server_info),e()}).catch(s=>{t(s)})})}set_normal(e,t,s){let i={};return typeof t>"u"||t===null?i={k:e}:i={u:e,p:t},i.a=this.api_token,s!==void 0&&(i.xopts=s),this._api_call("login",i).then(()=>{this.server_info&&(this.server_info.aci.token_mode="normal"),this._invoke_handler("login.success")}).catch(a=>{this.error_handler(a,"set_normal")}),!0}error_handler(e,t){if(e.code==-32022){let s=this.parse_svc_message(e.message);if(s.method=t,s&&s.kind=="OTP")switch(s.message){case"REQ":this._invoke_handler("login.otp_required",s),this._push_event_topic("WE/SESSION",{login:"otp.required",error:null,otp:s});return;case"INVALID":this._invoke_handler("login.otp_invalid",s),this._push_event_topic("WE/SESSION",{login:"otp.invalid",error:null,otp:s});return;case"SETUP":this._invoke_handler("login.otp_setup",s),this._push_event_topic("WE/SESSION",{login:"otp.setup",error:null,otp:s});return}}this._invoke_handler("login.failed",e),t=="login"&&(e.data=void 0,this._push_event_topic("WE/SESSION",{login:"failed",error:e,otp:null}))}on(e,t){this._handlers.set(e,t),this._debug("on",`setting handler for ${e}`),e=="ws.event"&&(this._ws_handler_registered=!0)}set_interval(e,t){this._intervals.set(e,t)}date_local_to_server(e){return new Date(e.getTime()-this.tsdiff*1e3)}date_server_to_local(e){return new Date(e.getTime()+this.tsdiff*1e3)}watch(e,t,s=!1,i=!1){if(isMask(e)){let a=this._update_state_mask_functions,r=a==null?void 0:a.get(e);if(r===void 0&&(r=[],a==null||a.set(e,r)),r.push({func:t,prot:i}),!s){let o=this.state(e);Array.isArray(o)?o.map(t):o!==void 0&&t(o)}}else{let a=this._update_state_functions,r=a==null?void 0:a.get(e);if(r===void 0&&(r=[],a==null||a.set(e,r)),r.push({func:t,prot:i}),!s){let o=this.state(e);o!==void 0&&t(o)}}}watch_action(e,t){let s=this._action_watch_functions.get(e);if(s===void 0){s=[],this._action_watch_functions.set(e,s),s.push(t);const i=()=>{this.call("action.result",{u:e}).then(a=>{let r=this._action_states.get(e);if(r===void 0||r.status!=a.status){this._action_states.set(e,a);let o=this._action_watch_functions.get(e);o!==void 0&&o.map(c=>c(a))}a.finished?(this._action_watch_functions.delete(e),this._action_states.delete(e)):setTimeout(i,this._intervals.get("action_watch")*1e3)}).catch(a=>{let r=this._action_watch_functions.get(e);r&&r.map(o=>o(a)),this._action_watch_functions.delete(e),this._action_states.delete(e)})};setTimeout(i,this._intervals.get("action_watch")*1e3)}else{s.push(t);let i=this._action_states.get(e);i!==void 0&&t(i)}}unwatch(e,t){e?isMask(e)?t?this._unwatch_mask_func(e,t):this._unwatch_mask_all(e):t?this._unwatch_func(e,t):this._unwatch_all(e):this._clear_watchers()}_unwatch_func(e,t){let s=this._update_state_functions,i=s==null?void 0:s.get(e);if(i!==void 0){const a=i.filter(r=>r.func!==t);a.length>0?s==null||s.set(e,a):s==null||s.delete(e)}}_unwatch_all(e){let t=this._update_state_functions,s=t==null?void 0:t.get(e);if(s===void 0)return;const i=s.filter(a=>a.prot);i.length>0?t==null||t.set(e,i):t==null||t.delete(e)}_unwatch_mask_func(e,t){let s=this._update_state_mask_functions,i=s==null?void 0:s.get(e);i!==void 0&&(s==null||s.set(e,i.filter(a=>a.func!==t)))}_unwatch_mask_all(e){let t=this._update_state_mask_functions,s=t==null?void 0:t.get(e);if(s===void 0)return;const i=s.filter(a=>a.prot);i.length>0?t==null||t.set(e,i):t==null||t.delete(e)}status(e){let t=this.state(e);if(t!=null)return t.status}value(e){let t=this.state(e);if(t!=null)return Number(t.value)==t.value?Number(t.value):t.value}state(e){let t;(i=>{i[i.Single=0]="Single",i[i.Mask=1]="Mask"})(t||(t={}));let s=0;for(let i of e)if(WILDCARDS.includes(i)||MATCH_ANY.includes(i)){s=1;break}switch(s){case 0:return this._state(e);case 1:return this._states_by_mask(e)}}_state(e){var t;for(let[s,i]of this._states){if(s==GLOBAL_BLOCK_NAME)continue;const a=i.get(e);if(a!==void 0)return a}return(t=this._states.get(GLOBAL_BLOCK_NAME))==null?void 0:t.get(e)}_states_by_mask(e){var i;let t=[],s=new Set;for(let[a,r]of this._states)a!=GLOBAL_BLOCK_NAME&&r.forEach((o,c)=>{this._oid_match(c,e)&&(s.has(c)||(t.push(o),s.add(c)))});return(i=this._states.get(GLOBAL_BLOCK_NAME))==null||i.forEach((a,r)=>{this._oid_match(r,e)&&(s.has(r)||(t.push(a),s.add(r)))}),t}async stop(e,t){this._push_event_topic("WE/SESSION",{login:"stopping",error:null,otp:null});const s={login:"inactive",error:null,otp:null};return new Promise((i,a)=>{if(this._stop_engine(),this.logged_in=!1,e)t||this._push_event_topic("WE/SESSION",s),i();else if(this.api_token){let r=this.api_token;this.erase_token_cookie(),this._api_call("logout",{a:r}).then(()=>{this.api_token="",t||this._push_event_topic("WE/SESSION",s),i()}).catch(o=>{t||this._push_event_topic("WE/SESSION",s),a(o)})}else t||this._push_event_topic("WE/SESSION",s),i()})}_inject_evajw(e){if(e)e.init(void 0,this).then(()=>{e.init_engine(),this.evajw=e,typeof window<"u"&&(window.evajw=this.evajw);let t=e.get_build();this.log.info("EVA ICS JavaScript WASM engine loaded. Build: "+t);try{e.check_license()}catch{this.log.error("License check failed. WASM engine disabled"),this.wasm=!1,this._start_engine();return}if(this._clear_watchers=e.clear_watchers,this._clear_states=e.clear_states,this._report_cleanup=e.report_cleanup,this.watch=e.watch,this.get_mode=e.get_mode,this._unwatch_func=e.unwatch_func,this._unwatch_all=e.unwatch_all,this._unwatch_mask_func=e.unwatch_mask_func,this._unwatch_mask_all=e.unwatch_mask_all,this.status=e.status,this.value=e.value,this._state=e.state,this._states_by_mask=e.states_by_mask,this._process_loaded_states=e.process_loaded_states,this._process_ws=e.process_ws,this._clear_state=e.clear_state,this._init_block_states=e.init_block_states,this.enable_event_map=e.enable_event_map,this.subscribe_event_topic=e.subscribe_event_topic,this.subscribe_event_topics=e.subscribe_event_topics,this.unsubscribe_event_topic=e.unsubscribe_event_topic,this.unsubscribe_all_event_topics=e.unsubscribe_all_event_topics,this._event_map)for(const[i,a]of this._event_map.subscribed_topics)this.subscribe_event_topics(Array.from(a),i);this._push_event_topic=e.push_event_topic;for(const i of this._blocks.keys())this._delete_block_states(i),this._init_block_states(i);this._delete_block_states=e.delete_block_states;function s(i,a){i.forEach((r,o)=>{r.forEach(c=>{a.watch(o,c.func,!1,c.prot)})})}return s(this._update_state_functions,e),s(this._update_state_mask_functions,e),this._start_engine()});else return this.evajw=null,!1}_init_block(e){this._init_block_states(e),this._last_ping.set(e,null),this._last_pong.set(e,null)}_init_block_states(e){this._states.set(e,new Map)}_delete_block(e){this._last_ping.delete(e),this._last_pong.delete(e),this._delete_block_states(e)}_delete_block_states(e){this._report_cleanup(e),this._states.delete(e)}_start_evajw(){this.evajw=void 0;const js_path=this.wasm===!0?"./evajw/evajw.js":this.wasm;eval(`import("${js_path}?" + new Date().getTime()).catch((e)=>{this._invoke_handler("wasm.error", e);this._start_engine()}).then((m)=>{this._inject_evajw(m)})`)}_is_ws_handler_registered(){return this._ws_handler_registered}_clear_watchers(){this._update_state_functions.forEach((e,t)=>{const s=e.filter(i=>i.prot);s.length>0?this._update_state_functions.set(t,s):this._update_state_functions.delete(t)}),this._update_state_mask_functions.forEach((e,t)=>{const s=e.filter(i=>i.prot);s.length>0?this._update_state_mask_functions.set(t,s):this._update_state_mask_functions.delete(t)})}_report_cleanup(e){var t;if(this._event_map!==null)for(const s of((t=this._states.get(e))==null?void 0:t.values())||[]){if(!s.oid)continue;let i=!1;for(const[a,r]of this._states)if(a!=e&&r.get(s.oid)){i=!0;break}if(!i){const a=s.oid.replace(":","/"),r={oid:s.oid,status:null,value:null};this._push_event_topic(`WE/ST/${e}/${a}`,r),this._push_event_topic(`ST/${a}/`,r)}}}_clear_states(e){var t;if(e!==void 0)this._report_cleanup(e),(t=this._states.get(e))==null||t.clear();else for(let[s,i]of this._states)this._report_cleanup(s),i.clear()}_clear_last_pings(){this._last_ping.set(GLOBAL_BLOCK_NAME,null);for(let[e,t]of this._blocks)this._last_ping.set(e,null),this._last_pong.set(e,null)}_clear(){this._clear_states(),this._clear_last_pings(),this.server_info=null,this._push_event_topic("SERVER",this.server_info),this.tsdiff=0,this._log_subscribed=!1,this._log_first_load=!0,this._log_loaded=!1,this._log_started=!1,this._lr2p=[]}_critical(e,t=!1,s=!0){if(t){let i=document.getElementsByTagName("body");i&&(i[0].innerHTML=`<font color="red" size="30">${e}</font>`)}if(this.log.critical(e),s)throw new Error(`critical: ${e}`)}_prepare_api_call(e,t){this._api_call_id==4294967295&&(this._api_call_id=0),this._api_call_id+=1;let s=this._api_call_id;return this.debug==2&&this.log.debug(e,t),{jsonrpc:"2.0",method:e,params:t,id:s}}async _api_call(e,t,s){const i=this._prepare_api_call(e,t),a=i.id;let r=`${this.api_uri}/jrpc`;return this.debug&&(r+=`?${e}`),this._debug("_api_call",`${a}: ${r}: ${e}`),new Promise((o,c)=>{let A,O,k=s||"json";switch(k){case"msgpack":if(!this.external.msgpack){c(new EvaError(-32006,"MsgPack serialization is not supported - no methods set"));return}A="application/x-msgpack",O=this.external.msgpack.encode(i);break;case"json":A="application/json",O=JSON.stringify(i);break;default:c(new EvaError(-32006,"Unsupported serialization kind"))}this.external.fetch(r,{method:"POST",headers:{"Content-Type":A},redirect:"error",body:O}).then(T=>{if(T.ok)this._debug(e,`api call ${a} completed`),this._deserializePromise(T,k).then(S=>{S.id!=a||S.result===void 0&&S.error===void 0?c(new EvaError(-32009,"Invalid server response",S)):S.error?(this._debug(e,`api call ${a} failed: ${S.error.code} (${S.error.message})`),c(new EvaError(S.error.code,S.error.message,S))):(this.debug==2&&this.log.debug(`API ${a} ${e} response`,S.result),o(S.result))}).catch(S=>{let L=-32009,D="Invalid server response";this._debug(e,`api call ${a} failed: ${L} (${D})`),c(new EvaError(L,D,S))});else{let S=-32007,L="Server error";this._debug(e,`api call ${a} failed: ${S} (${L})`),c(new EvaError(S,L))}}).catch(T=>{let S=-32007,L="Server error";this._debug(e,`api call ${a} failed: ${S} (${L})`),c(new EvaError(S,L,T))})})}async _heartbeat(e){return new Promise((t,s)=>{if(e&&this._clear_last_pings(),this.ws_mode){if(!e){for(let[i,a]of this._last_ping)if(a){const r=this._last_pong.get(i)||null;if(r===null||a-r>this._intervals.get("heartbeat")*2){this._debug("heartbeat",`error: ws ping timeout, block ${i||GLOBAL_BLOCK_NAME}`);const o=new EvaError(-32008,"WS ping timeout");this._invoke_handler("heartbeat.error",o),s(o);return}}}for(let[i,a]of this.ws)if(a&&(a==null?void 0:a.readyState)>=1){this._last_ping.set(i,Date.now()/1e3);try{this._debug(`block ${i||GLOBAL_BLOCK_NAME} heartbeat`,"ws ping");let r={m:"ping"};a.send(JSON.stringify(r)),a.send("")}catch(r){this._debug("heartbeat","error: unable to send ws ping"),this._invoke_handler("heartbeat.error",r),s();return}}}this.call("test").then(i=>{this.server_info=i,this._push_event_topic("SERVER",this.server_info),this.tsdiff=new Date().getTime()/1e3-i.time,this._invoke_handler("heartbeat.success"),t()}).catch(i=>{this._debug("heartbeat","error: unable to send test API call"),i.code==-32002&&this.erase_token_cookie(),this._invoke_handler("heartbeat.error",i)}),this._debug("heartbeat","ok")})}_load_log_entries(e){this.ws_mode&&(this._lr2p=[]),this.call("log.get",{l:this.log_params.level,n:this.log_params.records}).then(t=>{this.ws_mode&&this._log_first_load&&this._set_ws_log_level(this.log_params.level),t.map(s=>this._invoke_handler("log.record",s)),this._log_loaded=!0,this._lr2p.map(s=>this._invoke_handler("log.record",s)),e&&this._invoke_handler("log.postprocess"),this._log_first_load=!1}).catch(t=>{this.log.error(`unable to load log entries: ${t.message}`)})}_schedule_restart(){this._scheduled_restarter=setTimeout(()=>{this.start()},this._intervals.get("restart")*1e3)}_cancel_scheduled_restart(){this._scheduled_restarter&&(clearTimeout(this._scheduled_restarter),this._scheduled_restarter=null)}_stop_engine(){for(let[t,s]of this._blocks)s._stop();for(let[t,s]of this._streams)s._stop();this._clear(),this._heartbeat_reloader&&(clearInterval(this._heartbeat_reloader),this._heartbeat_reloader=null),this._ajax_reloader&&(clearInterval(this._ajax_reloader),this._ajax_reloader=null),this._log_reloader&&(clearInterval(this._log_reloader),this._log_reloader=null);let e=this.ws.get(GLOBAL_BLOCK_NAME);if(e)try{e.onclose=null,e.onerror=function(){},e.close()}catch{setTimeout(()=>{try{e==null||e.close()}catch{}},100)}}_prepare_call_params(e){let t=e||{};return this.api_token?t.k=this.api_token:N(this,b)&&(t.k=N(this,b)),t}_set_token_cookie(){this.set_auth_cookies&&typeof document<"u"&&[this.api_uri+"/ui",this.api_uri+"/pvt",this.api_uri+"/rpvt",this.api_uri+"/upload"].map(e=>document.cookie=`auth=${this.api_token}; Path=${e}; SameSite=Lax`,this)}_process_loaded_states(e,t,s){let i=[];if(t&&e.map(a=>{a.oid!==void 0&&i.push(a.oid)}),e.map(a=>this._process_state(a,t,s)),t){let a=this._states.get(s);a==null||a.forEach((r,o)=>{r.status!==void 0&&r.status!==null&&!i.includes(o)&&(this._debug(`clearing unavailable item ${o}`),this._clear_state(o,s))})}}async _load_states(e,t){return new Promise((s,i)=>{if(!e)s();else{let a={full:!0};e==!0?a.i="#":a.i=e,this.call("item.state",a).then(r=>{this._process_loaded_states(r,this.clear_unavailable,t),s()}).catch(r=>{i(r)})}})}_get_ws_uri(){let e;if(this.api_uri)if(e=this.api_uri,e.startsWith("http://"))e=e.replace("http://","ws://");else if(e.startsWith("https://"))e=e.replace("https://","wss://");else{let s=window.location;s.protocol==="https:"?e="wss:":e="ws:",e+="//"+s.host+this.api_uri}else{let s=window.location;s.protocol==="https:"?e="wss:":e="ws:",e+="//"+s.host}return`${e}${this.ws_uri}?`}async _start_ws(e,t){return check_state_updates(e),new Promise(s=>{if(this.ws_mode){let i=this._get_ws_uri();t&&(i+=`_block=${t}&`),i+=`k=${this.api_token}`;let a=this._intervals.get("ws_buf_ttl");a>0&&(i+=`&buf_ttl=${a}`);const r=new this.external.WebSocket(i);this.ws.set(t,r),r.onmessage=o=>{this._process_ws(o.data,t)},r.addEventListener("open",()=>{this._debug("_start_ws","ws connected");let o={m:"ping"};if(r.send(JSON.stringify(o)),r.send(""),e){let c={m:"subscribe.state"},A;e==!0?A=["#"]:A=e,c.p=A,r.send(JSON.stringify(c)),r.send("")}this._log_subscribed&&this.set_log_level(this.log_params.level)})}s()})}_set_ws_log_level(e){this._log_subscribed=!0;try{if(this.ws){let t={m:"subscribe.log",p:e};this.ws.get(GLOBAL_BLOCK_NAME).send(JSON.stringify(t)),this.ws.get(GLOBAL_BLOCK_NAME).send("")}}catch(t){this._debug("log_level","warning: unable to send ws packet",t)}}_process_ws_frame_pong(e){this._last_pong.set(e,Date.now()/1e3)}_process_ws_frame_log(e){Array.isArray(e)?e.map(t=>this._preprocess_log_record(t)):this._preprocess_log_record(e),this._invoke_handler("log.postprocess")}_process_ws(e,t){let s=JSON.parse(e);if(s.s=="pong"){this._debug("ws","pong"),this._process_ws_frame_pong(t);return}if(t===GLOBAL_BLOCK_NAME){if(s.s=="reload"){this._debug("ws","reload"),this._invoke_handler("server.reload"),this._push_event_topic("SERVER/RELOAD",!0);return}if(s.s=="server"){let i="server."+s.d;this._debug("ws",i),this._invoke_handler(i),this._push_event_topic(`SERVER/${s.d}`,!0);return}if(s.s.substring(0,11)=="supervisor."){this._debug("ws",s.s),this._invoke_handler(s.s,s.d),this._push_event_topic(`SUPERVISOR/${s.s.substring(11)}`,s.d);return}if(this._invoke_handler("ws.event",s)===!1)return;if(s.s=="log"){this._debug("ws","log"),this._process_ws_frame_log(s.d);return}}if(s.s=="state"){this._debug("ws","state"),Array.isArray(s.d)?s.d.map(i=>this._process_state(i,!0,t),this):this._process_state(s.d,!0,t);return}}_preprocess_log_record(e){this._log_loaded?this._invoke_handler("log.record",e):this._lr2p.push(e)}_clear_state(e,t){var s;(s=this._states.get(t))==null||s.delete(e),this._process_state({oid:e,status:null,value:null},!1,t)}_process_state(e,t=!1,s){let i=this._states.get(s);try{if(e.oid===void 0)return;let a=e.oid,r=i==null?void 0:i.get(a);if(!r&&t)return;if(r===void 0||e.node!=r.node||e.ieid!==void 0&&(r.ieid===void 0||e.ieid[0]==0||r.ieid[0]<e.ieid[0]||r.ieid[0]==e.ieid[0]&&r.ieid[1]<e.ieid[1])){if(r&&(t||e.ieid==null)&&Object.keys(r).map(function(c){c in e||(e[c]=r[c])}),this._debug("process_state",`${a} s: ${e.status} v: "${e.value}"`,`act: ${e.act} t: "${e.t}"`),i==null||i.set(a,e),this._event_map!==null){const c=a.replace(":","/");this._push_event_topic(`ST/${c}`,e),this._push_event_topic(`WE/ST/${s}/${c}`,e)}let o=this._update_state_functions.get(a);o&&o.map(c=>{try{c.func(e)}catch(A){this.log.error(`state function processing for ${a}:`,A)}}),this._update_state_mask_functions.forEach((c,A)=>{this._oid_match(a,A)&&c.map(O=>{try{O.func(e)}catch(k){this.log.error(`state function processing for ${a}:`,k)}})})}}catch(a){this.log.error("State processing error, invalid object received",a)}}_invoke_handler(e,...t){let s=this._handlers.get(e);if(s){this._debug("invoke_handler","invoking for "+e);try{return s.apply(this,t)}catch(i){if(e==="wasm.error")throw i;this.log.error(`handler for ${e}:`,i)}}}_oid_match(e,t){if(WILDCARDS.includes(t))return!0;let[s,i]=e.split(":");if(!i)return this.log.error(`Invalid OID: ${e}`),!1;let[a,r]=t.split(":");if(!r)return this.log.error(`Invalid OID mask: ${t}`),!1;if(!MATCH_ANY.includes(a)&&a!==s)return!1;let o=r.split("/");for(let c of i.split("/")){let A=o.shift();if(!A)return!1;if(WILDCARDS.includes(A))return!0;if(!MATCH_ANY.includes(A)&&A!==c)return!1}return o.length===0}_debug(e,...t){this.debug&&this.log.debug.apply(this.log,[`Eva::${e}`].concat(t))}parse_svc_message(e){if(e&&e.startsWith("|")){let t=e.split("|"),s=t[1];if(s){let i={kind:s,svc:t[2]},a=t[3];if(a){let r=a.split("=");i.message=r[0],i.value=r[1]}return i}}return null}otpQR(e,t,s){if(typeof document!="object"){this.log.error("document object not found");return}s||(s={});let i=s.size||200,a=s.issuer||`HMI ${document.location.hostname}`,r=s.user||this.login,o="otpauth://totp/"+encodeURIComponent(r)+`?secret=${t}&issuer=`+encodeURIComponent(a);return s.xtr&&(o+=s.xtr),new this.external.QRious({element:typeof e=="object"?e:document.getElementById(e),value:o,size:i})}hiQR(e,t){if(typeof document!="object"){this.log.error("document object not found");return}t||(t={});let s=t.url||document.location.href,i=t.user||this.authorized_user||"";if(!s||!i||i.startsWith("."))return;let a=t.password;a===void 0&&(a=N(this,w));let r=t.size||200,o=document.createElement("a");o.href=s;let c=o.protocol.substring(0,o.protocol.length-1),A=o.hostname,O=o.port||(c=="http"?"80":"443"),k=`scheme:${c}|address:${A}|port:${O}|user:${i}`;return a&&(k+=`|password:${a}`),new this.external.QRious({element:typeof e=="object"?e:document.getElementById(e),value:k,size:r})}register_globals(){if(typeof window<"u")window.$eva=this;else throw new Error("the method can be started in web browsers only")}register_legacy_globals(){this.register_globals()}}b=new WeakMap,w=new WeakMap;const check_state_updates=e=>{if(!Array.isArray(e)&&e!==!0&&e!==!1)throw new EvaError(-32602,"state_updates must be an array or boolean")},NO_FREEZE_ID="eva-webengine-nofreeze";function disableTabFreeze(e){const t="data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQAAAtptZGF0AAACrQYF//+p3EXpvebZSLeWLNgg2SPu73gyNjQgLSBjb3JlIDE1OSByMjk5MSAxNzcxYjU1IC0gSC4yNjQvTVBFRy00IEFWQyBjb2RlYyAtIENvcHlsZWZ0IDIwMDMtMjAxOSAtIGh0dHA6Ly93d3cudmlkZW9sYW4ub3JnL3gyNjQuaHRtbCAtIG9wdGlvbnM6IGNhYmFjPTEgcmVmPTMgZGVibG9jaz0xOjA6MCBhbmFseXNlPTB4MzoweDExMyBtZT1oZXggc3VibWU9NyBwc3k9MSBwc3lfcmQ9MS4wMDowLjAwIG1peGVkX3JlZj0xIG1lX3JhbmdlPTE2IGNocm9tYV9tZT0xIHRyZWxsaXM9MSA4eDhkY3Q9MSBjcW09MCBkZWFkem9uZT0yMSwxMSBmYXN0X3Bza2lwPTEgY2hyb21hX3FwX29mZnNldD0tMiB0aHJlYWRzPTEgbG9va2FoZWFkX3RocmVhZHM9MSBzbGljZWRfdGhyZWFkcz0wIG5yPTAgZGVjaW1hdGU9MSBpbnRlcmxhY2VkPTAgYmx1cmF5X2NvbXBhdD0wIGNvbnN0cmFpbmVkX2ludHJhPTAgYmZyYW1lcz0zIGJfcHlyYW1pZD0yIGJfYWRhcHQ9MSBiX2JpYXM9MCBkaXJlY3Q9MSB3ZWlnaHRiPTEgb3Blbl9nb3A9MCB3ZWlnaHRwPTIga2V5aW50PTI1MCBrZXlpbnRfbWluPTEgc2NlbmVjdXQ9NDAgaW50cmFfcmVmcmVzaD0wIHJjX2xvb2thaGVhZD00MCByYz1jcmYgbWJ0cmVlPTEgY3JmPTIzLjAgcWNvbXA9MC42MCBxcG1pbj0wIHFwbWF4PTY5IHFwc3RlcD00IGlwX3JhdGlvPTEuNDAgYXE9MToxLjAwAIAAAAANZYiEAJ/+xkPApcjsHQAAAAxBmiFsSf/xWlGfYYAAAAMIbW9vdgAAAGxtdmhkAAAAAAAAAAAAAAAAAAAD6AAAB9AAAQAAAQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAjJ0cmFrAAAAXHRraGQAAAADAAAAAAAAAAAAAAABAAAAAAAAB9AAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAABAAAAAQAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAAfQAAAAAAABAAAAAAGqbWRpYQAAACBtZGhkAAAAAAAAAAAAAAAAAABAAAAAgABVxAAAAAAALWhkbHIAAAAAAAAAAHZpZGUAAAAAAAAAAAAAAABWaWRlb0hhbmRsZXIAAAABVW1pbmYAAAAUdm1oZAAAAAEAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAARVzdGJsAAAAlXN0c2QAAAAAAAAAAQAAAIVhdmMxAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAABAAEABIAAAASAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGP//AAAAL2F2Y0MBZAAK/+EAFmdkAAqs2V6EAAADAAQAAAMACDxIllgBAAZo6+PLIsAAAAAYc3R0cwAAAAAAAAABAAAAAgAAQAAAAAAUc3RzcwAAAAAAAAABAAAAAQAAABxzdHNjAAAAAAAAAAEAAAABAAAAAgAAAAEAAAAcc3RzegAAAAAAAAAAAAAAAgAAAsIAAAAQAAAAFHN0Y28AAAAAAAAAAQAAADAAAABidWR0YQAAAFptZXRhAAAAAAAAACFoZGxyAAAAAAAAAABtZGlyYXBwbAAAAAAAAAAAAAAAAC1pbHN0AAAAJal0b28AAAAdZGF0YQAAAAEAAAAATGF2ZjU4LjI5LjEwMA==";let s=document.getElementById(NO_FREEZE_ID);s?console.warn("disableTabFreeze() function has been called multiple times"):(s=document.createElement("video"),s.id=NO_FREEZE_ID,document.body.appendChild(s)),s.src=t,s.loop=!0,s.muted=!0,s.autoplay=!0,s.width=2,s.height=1,e||(s.width=0)}exports.ACLOp=ACLOp,exports.Eva=Eva,exports.EvaError=EvaError,exports.EvaErrorKind=EvaErrorKind,exports.EventKind=EventKind,exports.EventTopic=EventTopic,exports.IntervalKind=IntervalKind,exports.LoginState=LoginState,exports.SerializationKind=SerializationKind,exports.SessionAuthKind=SessionAuthKind,exports.StateProp=StateProp,exports.TokenMode=TokenMode,exports.defaultSessionState=defaultSessionState,exports.disableTabFreeze=disableTabFreeze,Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"})});
//# sourceMappingURL=webengine.cjs.map