lavva.exalushome 2.0.136 → 2.0.138
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/exalushome-library-bundle.js +1 -1
- package/build/exalushome-library-bundle.js.map +1 -1
- package/build/js/Services/Scenes/ScenesBuilder.js +4 -1
- package/build/js/Services/Scenes/ScenesBuilder.js.map +1 -1
- package/build/js/Services/Scenes/ScenesService.js +15 -6
- package/build/js/Services/Scenes/ScenesService.js.map +1 -1
- package/build/js/Services/Updates/IUpdatesService.d.ts +38 -0
- package/build/js/Services/Updates/IUpdatesService.js +29 -0
- package/build/js/Services/Updates/IUpdatesService.js.map +1 -1
- package/build/js/Services/Updates/UpdateProviderServices/IDeviceUpdateProviderService.d.ts +3 -1
- package/build/js/Services/Updates/UpdatesService.d.ts +3 -1
- package/build/js/Services/Updates/UpdatesService.js +73 -1
- package/build/js/Services/Updates/UpdatesService.js.map +1 -1
- package/build/tsconfig.tsbuildinfo +1 -1
- package/package.json +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(()=>{"use strict";var e,t={d:(e,n)=>{for(var s in n)t.o(n,s)&&!t.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:n[s]})}};t.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),t.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),t.d({},{j:()=>Ov});class n{constructor(){this.handlers=[]}Subscribe(e){this.handlers.push(e)}Unsubscribe(e){this.handlers=this.handlers.filter((t=>t!==e))}Invoke(e){this.handlers.slice(0).forEach((t=>{var n;try{t(e)}catch(e){null===(n=r.Log)||void 0===n||n.Error(e)}}))}}!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warning=2]="Warning",e[e.Error=3]="Error",e[e.None=4]="None"}(e||(e={}));class s{constructor(){this._blockedServices=[],this._logLevel=e.Debug,void 0!==window.loglevel&&null!==window.loglevel&&(this._logLevel=window.loglevel),window.logger=this}EnableStackTrace(){s.DoesThrowStackTrace=!0}DisableStackTrace(){s.DoesThrowStackTrace=!1}IsBlocked(e){return void 0!==e&&this._blockedServices.any((t=>t==e))}DisableLogsFrom(e){this._blockedServices.all((t=>t!=e))&&this._blockedServices.push(e),this.Debug(s.ServiceName,`Disabling logs from ${e}`)}EnableLogsFrom(e){this._blockedServices.any((t=>t==e))&&(this._blockedServices=this._blockedServices.where((t=>t!=e)).toArray()),this.Debug(s.ServiceName,`Enaabling logs from ${e}`)}get LogLevel(){return this._logLevel}set LogLevel(e){this._logLevel=e}GetServiceName(){return s.ServiceName}GetTimeStamp(){const e=new Date;return`${e.getHours()}:${e.getMinutes()}:${e.getSeconds()}.${e.getMilliseconds()} | `}Warning(t,n){switch(this._logLevel){case e.Warning:case e.Info:case e.Debug:break;case e.None:default:return}void 0===t||this.IsBlocked(t)||null!=t&&(null==n?console.warn(`${this.GetTimeStamp()}[WARN] ${t}`):console.warn(`${this.GetTimeStamp()}[WARN] [${t}] ${n}`))}Error(t,n){switch(this._logLevel){case e.Warning:case e.Info:case e.Debug:case e.Error:break;case e.None:default:return}null!=t&&(null==n?console.error(`${this.GetTimeStamp()}[ERROR] ${t}`):console.error(`${this.GetTimeStamp()}[ERROR] [${t}] ${n}`))}Info(t,n){switch(this._logLevel){case e.Info:case e.Debug:break;case e.None:default:return}void 0===t||this.IsBlocked(t)||null!=t&&(null==n?console.info(`${this.GetTimeStamp()}[INFO] ${t}`):console.info(`${this.GetTimeStamp()}[INFO] [${t}] ${n}`))}Debug(t,n){switch(this._logLevel){case e.Debug:break;case e.None:default:return}void 0===t||this.IsBlocked(t)||null!=t&&(null==n?console.debug(`${this.GetTimeStamp()}[DEBUG] ${t}`):s.DoesThrowStackTrace||!0===window.stacktrace?console.debug(`${this.GetTimeStamp()}[DEBUG] [${t}] ${n} \nstack:\n${(new Error).stack}}`):console.debug(`${this.GetTimeStamp()}[DEBUG] [${t}] ${n}`))}Log(t,n){this._logLevel!==e.None&&(void 0===t||this.IsBlocked(t)||null!=t&&(null==n?console.log(`${this.GetTimeStamp()}[LOG] ${t}`):console.log(`${this.GetTimeStamp()}[LOG] [${t}] ${n}`)))}}s.ServiceName="LoggerService",s.DoesThrowStackTrace=!1;class r{constructor(){this._services={},this._serviceRegistrationEvent=new n}static get Instance(){return null!=r._instance||(r._instance=new r,this.Log=new s,this.Log.Warning("Initializing DependencyContainer"),r._instance.RegisterService(this.Log),this.IsInitialized=!0,window.services=this),r._instance}RegisterService(e){var t;null===(t=r.Log)||void 0===t||t.Debug("DependencyContainer",`Registering new service: ${e.GetServiceName()}`),this._services[e.GetServiceName()]=e,this._serviceRegistrationEvent.Invoke(e)}GetService(e){var t;return null===(t=r.Log)||void 0===t||t.Debug("DependencyContainer",`Getting service [${e}] by GetService<T>()`),this._services[e]}GetServiceAsync(e,t){var n,s;return null===(n=r.Log)||void 0===n||n.Debug("DependencyContainer",`Waiting for service availability [${e}] by GetServiceAsync<T>()`),this._services.hasOwnProperty(e)?(null===(s=r.Log)||void 0===s||s.Debug("DependencyContainer",`Got service [${e}] by GetServiceAsync<T>()`),Promise.resolve(this._services[e])):new Promise(((n,s)=>{var o=t=>{var s;(null==t?void 0:t.GetServiceName())===e&&(null===(s=r.Log)||void 0===s||s.Debug("DependencyContainer",`Got service [${e}] by GetServiceAsync<T>()`),this._serviceRegistrationEvent.Unsubscribe(o),n(t))},i=()=>{var n;null===(n=r.Log)||void 0===n||n.Debug("DependencyContainer",`Cancelled service [${e}] retrieval by GetServiceAsync<T>()`),this._serviceRegistrationEvent.Unsubscribe(o),null==t||t.CancellationEvent.Unsubscribe(i),s(new Error("Operation cancelled!"))};null==t||t.CancellationEvent.Subscribe(i),this._serviceRegistrationEvent.Subscribe(o)}))}GetServiceWithTimeoutAsync(e,t){var n,s;return null===(n=r.Log)||void 0===n||n.Debug("DependencyContainer",`Waiting for service[${e}] availability by GetServiceWithTimeoutAsync<T>()`),this._services.hasOwnProperty(e)?(null===(s=r.Log)||void 0===s||s.Debug("DependencyContainer",`Got service [${e}] by GetServiceWithTimeoutAsync<T>()`),Promise.resolve(this._services[e])):new Promise(((n,s)=>{let o=0,i=e=>{var t;(null==e?void 0:e.GetClassName())===e&&(null===(t=r.Log)||void 0===t||t.Debug("DependencyContainer",`Got service [${e}] by GetServiceWithTimeoutAsync<T>()`),window.clearTimeout(o),this._serviceRegistrationEvent.Unsubscribe(i),n(e))};o=window.setTimeout((()=>{var t;window.clearTimeout(o),this._serviceRegistrationEvent.Unsubscribe(i),null===(t=r.Log)||void 0===t||t.Error("DependencyContainer",`Failed to get service [${e}] in time by GetServiceWithTimeoutAsync<T>()`),s(new Error("Operation cancelled!"))}),t),this._serviceRegistrationEvent.Subscribe(i)}))}}r.IsInitialized=!1;class o{GetServiceName(){return o.ServiceName}GetResourceName(e,t){return`_exalus_${Ov.WorksInContextOf}_${e}_${t}`}Remove(e,t){localStorage.removeItem(this.GetResourceName(e,t))}DropStorage(e){let t=`_exalus_${e}`;for(const e in localStorage)(null==e?void 0:e.startsWith(t))&&localStorage.removeItem(e)}Save(e,t,n){localStorage.setItem(this.GetResourceName(e,t),JSON.stringify(n))}Read(e,t){var n;try{let n=this.GetResourceName(e,t),s=localStorage.getItem(n);return null==s?null:JSON.parse(s)}catch(s){return null===(n=r.Log)||void 0===n||n.Error(o.ServiceName,`Exception has occurred while reading ${this.GetResourceName(e,t)}`),null}}}o.ServiceName="LocalStorageService";const i=[0,2e3,1e4,3e4,null];class a{constructor(e){this._retryDelays=void 0!==e?[...e,null]:i}nextRetryDelayInMilliseconds(e){return this._retryDelays[e.previousRetryCount]}}class c{}c.Authorization="Authorization",c.Cookie="Cookie";class u{constructor(e,t,n){this.statusCode=e,this.statusText=t,this.content=n}}class l{get(e,t){return this.send({...t,method:"GET",url:e})}post(e,t){return this.send({...t,method:"POST",url:e})}delete(e,t){return this.send({...t,method:"DELETE",url:e})}getCookieString(e){return""}}class d extends l{constructor(e,t){super(),this._innerClient=e,this._accessTokenFactory=t}async send(e){let t=!0;this._accessTokenFactory&&(!this._accessToken||e.url&&e.url.indexOf("/negotiate?")>0)&&(t=!1,this._accessToken=await this._accessTokenFactory()),this._setAuthorizationHeader(e);const n=await this._innerClient.send(e);return t&&401===n.statusCode&&this._accessTokenFactory?(this._accessToken=await this._accessTokenFactory(),this._setAuthorizationHeader(e),await this._innerClient.send(e)):n}_setAuthorizationHeader(e){e.headers||(e.headers={}),this._accessToken?e.headers[c.Authorization]=`Bearer ${this._accessToken}`:this._accessTokenFactory&&e.headers[c.Authorization]&&delete e.headers[c.Authorization]}getCookieString(e){return this._innerClient.getCookieString(e)}}class h extends Error{constructor(e,t){const n=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=n}}class g extends Error{constructor(e="A timeout occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class p extends Error{constructor(e="An abort occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class f extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="UnsupportedTransportError",this.__proto__=n}}class v extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="DisabledTransportError",this.__proto__=n}}class m extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="FailedToStartTransportError",this.__proto__=n}}class y extends Error{constructor(e){const t=new.target.prototype;super(e),this.errorType="FailedToNegotiateWithServerError",this.__proto__=t}}class w extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.innerErrors=t,this.__proto__=n}}var S,A,_,C,T;!function(e){e[e.Trace=0]="Trace",e[e.Debug=1]="Debug",e[e.Information=2]="Information",e[e.Warning=3]="Warning",e[e.Error=4]="Error",e[e.Critical=5]="Critical",e[e.None=6]="None"}(S||(S={}));class D{constructor(){}log(e,t){}}D.instance=new D;class k{static isRequired(e,t){if(null==e)throw new Error(`The '${t}' argument is required.`)}static isNotEmpty(e,t){if(!e||e.match(/^\s*$/))throw new Error(`The '${t}' argument should not be empty.`)}static isIn(e,t,n){if(!(e in t))throw new Error(`Unknown ${n} value: ${e}.`)}}class G{static get isBrowser(){return!G.isNode&&"object"==typeof window&&"object"==typeof window.document}static get isWebWorker(){return!G.isNode&&"object"==typeof self&&"importScripts"in self}static get isReactNative(){return!G.isNode&&"object"==typeof window&&void 0===window.document}static get isNode(){return"undefined"!=typeof process&&process.release&&"node"===process.release.name}}function b(e,t){let n="";return N(e)?(n=`Binary data of length ${e.byteLength}`,t&&(n+=`. Content: '${function(e){const t=new Uint8Array(e);let n="";return t.forEach((e=>{n+=`0x${e<16?"0":""}${e.toString(16)} `})),n.substr(0,n.length-1)}(e)}'`)):"string"==typeof e&&(n=`String data of length ${e.length}`,t&&(n+=`. Content: '${e}'`)),n}function N(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function E(e,t,n,s,r,o){const i={},[a,c]=P();i[a]=c,e.log(S.Trace,`(${t} transport) sending data. ${b(r,o.logMessageContent)}.`);const u=N(r)?"arraybuffer":"text",l=await n.post(s,{content:r,headers:{...i,...o.headers},responseType:u,timeout:o.timeout,withCredentials:o.withCredentials});e.log(S.Trace,`(${t} transport) request complete. Response status: ${l.statusCode}.`)}class I{constructor(e,t){this._subject=e,this._observer=t}dispose(){const e=this._subject.observers.indexOf(this._observer);e>-1&&this._subject.observers.splice(e,1),0===this._subject.observers.length&&this._subject.cancelCallback&&this._subject.cancelCallback().catch((e=>{}))}}class R{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const n=`[${(new Date).toISOString()}] ${S[e]}: ${t}`;switch(e){case S.Critical:case S.Error:this.out.error(n);break;case S.Warning:this.out.warn(n);break;case S.Information:this.out.info(n);break;default:this.out.log(n)}}}}function P(){let e="X-SignalR-User-Agent";return G.isNode&&(e="User-Agent"),[e,O("8.0.7",U(),G.isNode?"NodeJS":"Browser",M())]}function O(e,t,n,s){let r="Microsoft SignalR/";const o=e.split(".");return r+=`${o[0]}.${o[1]}`,r+=` (${e}; `,r+=t&&""!==t?`${t}; `:"Unknown OS; ",r+=`${n}`,r+=s?`; ${s}`:"; Unknown Runtime Version",r+=")",r}function U(){if(!G.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function M(){if(G.isNode)return process.versions.node}function x(e){return e.stack?e.stack:e.message?e.message:`${e}`}class F extends l{constructor(e){if(super(),this._logger=e,"undefined"==typeof fetch||G.isNode){const e=require;this._jar=new(e("tough-cookie").CookieJar),"undefined"==typeof fetch?this._fetchType=e("node-fetch"):this._fetchType=fetch,this._fetchType=e("fetch-cookie")(this._fetchType,this._jar)}else this._fetchType=fetch.bind(function(){if("undefined"!=typeof globalThis)return globalThis;if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==t.g)return t.g;throw new Error("could not find global")}());if("undefined"==typeof AbortController){const e=require;this._abortControllerType=e("abort-controller")}else this._abortControllerType=AbortController}async send(e){if(e.abortSignal&&e.abortSignal.aborted)throw new p;if(!e.method)throw new Error("No method defined.");if(!e.url)throw new Error("No url defined.");const t=new this._abortControllerType;let n;e.abortSignal&&(e.abortSignal.onabort=()=>{t.abort(),n=new p});let s,r=null;if(e.timeout){const s=e.timeout;r=setTimeout((()=>{t.abort(),this._logger.log(S.Warning,"Timeout from HTTP request."),n=new g}),s)}""===e.content&&(e.content=void 0),e.content&&(e.headers=e.headers||{},N(e.content)?e.headers["Content-Type"]="application/octet-stream":e.headers["Content-Type"]="text/plain;charset=UTF-8");try{s=await this._fetchType(e.url,{body:e.content,cache:"no-cache",credentials:!0===e.withCredentials?"include":"same-origin",headers:{"X-Requested-With":"XMLHttpRequest",...e.headers},method:e.method,mode:"cors",redirect:"follow",signal:t.signal})}catch(e){if(n)throw n;throw this._logger.log(S.Warning,`Error from HTTP request. ${e}.`),e}finally{r&&clearTimeout(r),e.abortSignal&&(e.abortSignal.onabort=null)}if(!s.ok){const e=await L(s,"text");throw new h(e||s.statusText,s.status)}const o=L(s,e.responseType),i=await o;return new u(s.status,s.statusText,i)}getCookieString(e){let t="";return G.isNode&&this._jar&&this._jar.getCookies(e,((e,n)=>t=n.join("; "))),t}}function L(e,t){let n;switch(t){case"arraybuffer":n=e.arrayBuffer();break;case"text":default:n=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`)}return n}class B extends l{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new p):e.method?e.url?new Promise(((t,n)=>{const s=new XMLHttpRequest;s.open(e.method,e.url,!0),s.withCredentials=void 0===e.withCredentials||e.withCredentials,s.setRequestHeader("X-Requested-With","XMLHttpRequest"),""===e.content&&(e.content=void 0),e.content&&(N(e.content)?s.setRequestHeader("Content-Type","application/octet-stream"):s.setRequestHeader("Content-Type","text/plain;charset=UTF-8"));const r=e.headers;r&&Object.keys(r).forEach((e=>{s.setRequestHeader(e,r[e])})),e.responseType&&(s.responseType=e.responseType),e.abortSignal&&(e.abortSignal.onabort=()=>{s.abort(),n(new p)}),e.timeout&&(s.timeout=e.timeout),s.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),s.status>=200&&s.status<300?t(new u(s.status,s.statusText,s.response||s.responseText)):n(new h(s.response||s.responseText||s.statusText,s.status))},s.onerror=()=>{this._logger.log(S.Warning,`Error from HTTP request. ${s.status}: ${s.statusText}.`),n(new h(s.statusText,s.status))},s.ontimeout=()=>{this._logger.log(S.Warning,"Timeout from HTTP request."),n(new g)},s.send(e.content)})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class W extends l{constructor(e){if(super(),"undefined"!=typeof fetch||G.isNode)this._httpClient=new F(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new B(e)}}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new p):e.method?e.url?this._httpClient.send(e):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}getCookieString(e){return this._httpClient.getCookieString(e)}}!function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(A||(A={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(_||(_={}));class ${constructor(){this._isAborted=!1,this.onabort=null}abort(){this._isAborted||(this._isAborted=!0,this.onabort&&this.onabort())}get signal(){return this}get aborted(){return this._isAborted}}class q{get pollAborted(){return this._pollAbort.aborted}constructor(e,t,n){this._httpClient=e,this._logger=t,this._pollAbort=new $,this._options=n,this._running=!1,this.onreceive=null,this.onclose=null}async connect(e,t){if(k.isRequired(e,"url"),k.isRequired(t,"transferFormat"),k.isIn(t,_,"transferFormat"),this._url=e,this._logger.log(S.Trace,"(LongPolling transport) Connecting."),t===_.Binary&&"undefined"!=typeof XMLHttpRequest&&"string"!=typeof(new XMLHttpRequest).responseType)throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported.");const[n,s]=P(),r={[n]:s,...this._options.headers},o={abortSignal:this._pollAbort.signal,headers:r,timeout:1e5,withCredentials:this._options.withCredentials};t===_.Binary&&(o.responseType="arraybuffer");const i=`${e}&_=${Date.now()}`;this._logger.log(S.Trace,`(LongPolling transport) polling: ${i}.`);const a=await this._httpClient.get(i,o);200!==a.statusCode?(this._logger.log(S.Error,`(LongPolling transport) Unexpected response code: ${a.statusCode}.`),this._closeError=new h(a.statusText||"",a.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,o)}async _poll(e,t){try{for(;this._running;)try{const n=`${e}&_=${Date.now()}`;this._logger.log(S.Trace,`(LongPolling transport) polling: ${n}.`);const s=await this._httpClient.get(n,t);204===s.statusCode?(this._logger.log(S.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==s.statusCode?(this._logger.log(S.Error,`(LongPolling transport) Unexpected response code: ${s.statusCode}.`),this._closeError=new h(s.statusText||"",s.statusCode),this._running=!1):s.content?(this._logger.log(S.Trace,`(LongPolling transport) data received. ${b(s.content,this._options.logMessageContent)}.`),this.onreceive&&this.onreceive(s.content)):this._logger.log(S.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof g?this._logger.log(S.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(S.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}finally{this._logger.log(S.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?E(this._logger,"LongPolling",this._httpClient,this._url,e,this._options):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(S.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(S.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,n]=P();e[t]=n;const s={headers:{...e,...this._options.headers},timeout:this._options.timeout,withCredentials:this._options.withCredentials};let r;try{await this._httpClient.delete(this._url,s)}catch(e){r=e}r?r instanceof h&&(404===r.statusCode?this._logger.log(S.Trace,"(LongPolling transport) A 404 response was returned from sending a DELETE request."):this._logger.log(S.Trace,`(LongPolling transport) Error sending a DELETE request: ${r}`)):this._logger.log(S.Trace,"(LongPolling transport) DELETE request accepted.")}finally{this._logger.log(S.Trace,"(LongPolling transport) Stop finished."),this._raiseOnClose()}}_raiseOnClose(){if(this.onclose){let e="(LongPolling transport) Firing onclose event.";this._closeError&&(e+=" Error: "+this._closeError),this._logger.log(S.Trace,e),this.onclose(this._closeError)}}}class V{constructor(e,t,n,s){this._httpClient=e,this._accessToken=t,this._logger=n,this._options=s,this.onreceive=null,this.onclose=null}async connect(e,t){return k.isRequired(e,"url"),k.isRequired(t,"transferFormat"),k.isIn(t,_,"transferFormat"),this._logger.log(S.Trace,"(SSE transport) Connecting."),this._url=e,this._accessToken&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(this._accessToken)}`),new Promise(((n,s)=>{let r,o=!1;if(t===_.Text){if(G.isBrowser||G.isWebWorker)r=new this._options.EventSource(e,{withCredentials:this._options.withCredentials});else{const t=this._httpClient.getCookieString(e),n={};n.Cookie=t;const[s,o]=P();n[s]=o,r=new this._options.EventSource(e,{withCredentials:this._options.withCredentials,headers:{...n,...this._options.headers}})}try{r.onmessage=e=>{if(this.onreceive)try{this._logger.log(S.Trace,`(SSE transport) data received. ${b(e.data,this._options.logMessageContent)}.`),this.onreceive(e.data)}catch(e){return void this._close(e)}},r.onerror=e=>{o?this._close():s(new Error("EventSource failed to connect. The connection could not be found on the server, either the connection ID is not present on the server, or a proxy is refusing/buffering the connection. If you have multiple servers check that sticky sessions are enabled."))},r.onopen=()=>{this._logger.log(S.Information,`SSE connected to ${this._url}`),this._eventSource=r,o=!0,n()}}catch(e){return void s(e)}}else s(new Error("The Server-Sent Events transport only supports the 'Text' transfer format"))}))}async send(e){return this._eventSource?E(this._logger,"SSE",this._httpClient,this._url,e,this._options):Promise.reject(new Error("Cannot send until the transport is connected"))}stop(){return this._close(),Promise.resolve()}_close(e){this._eventSource&&(this._eventSource.close(),this._eventSource=void 0,this.onclose&&this.onclose(e))}}class H{constructor(e,t,n,s,r,o){this._logger=n,this._accessTokenFactory=t,this._logMessageContent=s,this._webSocketConstructor=r,this._httpClient=e,this.onreceive=null,this.onclose=null,this._headers=o}async connect(e,t){let n;return k.isRequired(e,"url"),k.isRequired(t,"transferFormat"),k.isIn(t,_,"transferFormat"),this._logger.log(S.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory&&(n=await this._accessTokenFactory()),new Promise(((s,r)=>{let o;e=e.replace(/^http/,"ws");const i=this._httpClient.getCookieString(e);let a=!1;if(G.isNode||G.isReactNative){const t={},[s,r]=P();t[s]=r,n&&(t[c.Authorization]=`Bearer ${n}`),i&&(t[c.Cookie]=i),o=new this._webSocketConstructor(e,void 0,{headers:{...t,...this._headers}})}else n&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(n)}`);o||(o=new this._webSocketConstructor(e)),t===_.Binary&&(o.binaryType="arraybuffer"),o.onopen=t=>{this._logger.log(S.Information,`WebSocket connected to ${e}.`),this._webSocket=o,a=!0,s()},o.onerror=e=>{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"There was an error with the transport",this._logger.log(S.Information,`(WebSockets transport) ${t}.`)},o.onmessage=e=>{if(this._logger.log(S.Trace,`(WebSockets transport) data received. ${b(e.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(e.data)}catch(e){return void this._close(e)}},o.onclose=e=>{if(a)this._close(e);else{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"WebSocket failed to connect. The connection could not be found on the server, either the endpoint may not be a SignalR endpoint, the connection ID is not present on the server, or there is a proxy blocking WebSockets. If you have multiple servers check that sticky sessions are enabled.",r(new Error(t))}}}))}send(e){return this._webSocket&&this._webSocket.readyState===this._webSocketConstructor.OPEN?(this._logger.log(S.Trace,`(WebSockets transport) sending data. ${b(e,this._logMessageContent)}.`),this._webSocket.send(e),Promise.resolve()):Promise.reject("WebSocket is not in the OPEN state")}stop(){return this._webSocket&&this._close(void 0),Promise.resolve()}_close(e){this._webSocket&&(this._webSocket.onclose=()=>{},this._webSocket.onmessage=()=>{},this._webSocket.onerror=()=>{},this._webSocket.close(),this._webSocket=void 0),this._logger.log(S.Trace,"(WebSockets transport) socket closed."),this.onclose&&(!this._isCloseEvent(e)||!1!==e.wasClean&&1e3===e.code?e instanceof Error?this.onclose(e):this.onclose():this.onclose(new Error(`WebSocket closed with status code: ${e.code} (${e.reason||"no reason given"}).`)))}_isCloseEvent(e){return e&&"boolean"==typeof e.wasClean&&"number"==typeof e.code}}class j{constructor(e,t={}){var n;if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,k.isRequired(e,"url"),this._logger=void 0===(n=t.logger)?new R(S.Information):null===n?D.instance:void 0!==n.log?n:new R(n),this.baseUrl=this._resolveUrl(e),(t=t||{}).logMessageContent=void 0!==t.logMessageContent&&t.logMessageContent,"boolean"!=typeof t.withCredentials&&void 0!==t.withCredentials)throw new Error("withCredentials option was not a 'boolean' or 'undefined' value");t.withCredentials=void 0===t.withCredentials||t.withCredentials,t.timeout=void 0===t.timeout?1e5:t.timeout;let s=null,r=null;if(G.isNode){const e=require;s=e("ws"),r=e("eventsource")}G.isNode||"undefined"==typeof WebSocket||t.WebSocket?G.isNode&&!t.WebSocket&&s&&(t.WebSocket=s):t.WebSocket=WebSocket,G.isNode||"undefined"==typeof EventSource||t.EventSource?G.isNode&&!t.EventSource&&void 0!==r&&(t.EventSource=r):t.EventSource=EventSource,this._httpClient=new d(t.httpClient||new W(this._logger),t.accessTokenFactory),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=t,this.onreceive=null,this.onclose=null}async start(e){if(e=e||_.Binary,k.isIn(e,_,"transferFormat"),this._logger.log(S.Debug,`Starting connection with transfer format '${_[e]}'.`),"Disconnected"!==this._connectionState)return Promise.reject(new Error("Cannot start an HttpConnection that is not in the 'Disconnected' state."));if(this._connectionState="Connecting",this._startInternalPromise=this._startInternal(e),await this._startInternalPromise,"Disconnecting"===this._connectionState){const e="Failed to start the HttpConnection before stop() was called.";return this._logger.log(S.Error,e),await this._stopPromise,Promise.reject(new p(e))}if("Connected"!==this._connectionState){const e="HttpConnection.startInternal completed gracefully but didn't enter the connection into the connected state!";return this._logger.log(S.Error,e),Promise.reject(new p(e))}this._connectionStarted=!0}send(e){return"Connected"!==this._connectionState?Promise.reject(new Error("Cannot send data if the connection is not in the 'Connected' State.")):(this._sendQueue||(this._sendQueue=new K(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(S.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(S.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState="Disconnecting",this._stopPromise=new Promise((e=>{this._stopPromiseResolver=e})),await this._stopInternal(e),void await this._stopPromise)}async _stopInternal(e){this._stopError=e;try{await this._startInternalPromise}catch(e){}if(this.transport){try{await this.transport.stop()}catch(e){this._logger.log(S.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(S.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let t=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory,this._httpClient._accessTokenFactory=this._accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==A.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(A.WebSockets),await this._startTransport(t,e)}else{let n=null,s=0;do{if(n=await this._getNegotiationResponse(t),"Disconnecting"===this._connectionState||"Disconnected"===this._connectionState)throw new p("The connection was stopped during negotiation.");if(n.error)throw new Error(n.error);if(n.ProtocolVersion)throw new Error("Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server. See https://aka.ms/signalr-core-differences for details.");if(n.url&&(t=n.url),n.accessToken){const e=n.accessToken;this._accessTokenFactory=()=>e,this._httpClient._accessToken=e,this._httpClient._accessTokenFactory=void 0}s++}while(n.url&&s<100);if(100===s&&n.url)throw new Error("Negotiate redirection limit exceeded.");await this._createTransport(t,this._options.transport,n,e)}this.transport instanceof q&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(S.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(S.Error,"Failed to start the connection: "+e),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(e)}}async _getNegotiationResponse(e){const t={},[n,s]=P();t[n]=s;const r=this._resolveNegotiateUrl(e);this._logger.log(S.Debug,`Sending negotiation request: ${r}.`);try{const e=await this._httpClient.post(r,{content:"",headers:{...t,...this._options.headers},timeout:this._options.timeout,withCredentials:this._options.withCredentials});if(200!==e.statusCode)return Promise.reject(new Error(`Unexpected status code returned from negotiate '${e.statusCode}'`));const n=JSON.parse(e.content);return(!n.negotiateVersion||n.negotiateVersion<1)&&(n.connectionToken=n.connectionId),n.useStatefulReconnect&&!0!==this._options._useStatefulReconnect?Promise.reject(new y("Client didn't negotiate Stateful Reconnect but the server did.")):n}catch(e){let t="Failed to complete negotiation with the server: "+e;return e instanceof h&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(S.Error,t),Promise.reject(new y(t))}}_createConnectUrl(e,t){return t?e+(-1===e.indexOf("?")?"?":"&")+`id=${t}`:e}async _createTransport(e,t,n,s){let r=this._createConnectUrl(e,n.connectionToken);if(this._isITransport(t))return this._logger.log(S.Debug,"Connection was provided an instance of ITransport, using that directly."),this.transport=t,await this._startTransport(r,s),void(this.connectionId=n.connectionId);const o=[],i=n.availableTransports||[];let a=n;for(const n of i){const i=this._resolveTransportOrError(n,t,s,!0===(null==a?void 0:a.useStatefulReconnect));if(i instanceof Error)o.push(`${n.transport} failed:`),o.push(i);else if(this._isITransport(i)){if(this.transport=i,!a){try{a=await this._getNegotiationResponse(e)}catch(e){return Promise.reject(e)}r=this._createConnectUrl(e,a.connectionToken)}try{return await this._startTransport(r,s),void(this.connectionId=a.connectionId)}catch(e){if(this._logger.log(S.Error,`Failed to start the transport '${n.transport}': ${e}`),a=void 0,o.push(new m(`${n.transport} failed: ${e}`,A[n.transport])),"Connecting"!==this._connectionState){const e="Failed to select transport before stop() was called.";return this._logger.log(S.Debug,e),Promise.reject(new p(e))}}}}return o.length>0?Promise.reject(new w(`Unable to connect to the server with any of the available transports. ${o.join(" ")}`,o)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(e){switch(e){case A.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new H(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent,this._options.WebSocket,this._options.headers||{});case A.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new V(this._httpClient,this._httpClient._accessToken,this._logger,this._options);case A.LongPolling:return new q(this._httpClient,this._logger,this._options);default:throw new Error(`Unknown transport: ${e}.`)}}_startTransport(e,t){return this.transport.onreceive=this.onreceive,this.features.reconnect?this.transport.onclose=async n=>{let s=!1;if(this.features.reconnect){try{this.features.disconnected(),await this.transport.connect(e,t),await this.features.resend()}catch{s=!0}s&&this._stopConnection(n)}else this._stopConnection(n)}:this.transport.onclose=e=>this._stopConnection(e),this.transport.connect(e,t)}_resolveTransportOrError(e,t,n,s){const r=A[e.transport];if(null==r)return this._logger.log(S.Debug,`Skipping transport '${e.transport}' because it is not supported by this client.`),new Error(`Skipping transport '${e.transport}' because it is not supported by this client.`);if(!function(e,t){return!e||!!(t&e)}(t,r))return this._logger.log(S.Debug,`Skipping transport '${A[r]}' because it was disabled by the client.`),new v(`'${A[r]}' is disabled by the client.`,r);if(!(e.transferFormats.map((e=>_[e])).indexOf(n)>=0))return this._logger.log(S.Debug,`Skipping transport '${A[r]}' because it does not support the requested transfer format '${_[n]}'.`),new Error(`'${A[r]}' does not support ${_[n]}.`);if(r===A.WebSockets&&!this._options.WebSocket||r===A.ServerSentEvents&&!this._options.EventSource)return this._logger.log(S.Debug,`Skipping transport '${A[r]}' because it is not supported in your environment.'`),new f(`'${A[r]}' is not supported in your environment.`,r);this._logger.log(S.Debug,`Selecting transport '${A[r]}'.`);try{return this.features.reconnect=r===A.WebSockets?s:void 0,this._constructTransport(r)}catch(e){return e}}_isITransport(e){return e&&"object"==typeof e&&"connect"in e}_stopConnection(e){if(this._logger.log(S.Debug,`HttpConnection.stopConnection(${e}) called while in state ${this._connectionState}.`),this.transport=void 0,e=this._stopError||e,this._stopError=void 0,"Disconnected"!==this._connectionState){if("Connecting"===this._connectionState)throw this._logger.log(S.Warning,`Call to HttpConnection.stopConnection(${e}) was ignored because the connection is still in the connecting state.`),new Error(`HttpConnection.stopConnection(${e}) was called while the connection is still in the connecting state.`);if("Disconnecting"===this._connectionState&&this._stopPromiseResolver(),e?this._logger.log(S.Error,`Connection disconnected with error '${e}'.`):this._logger.log(S.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch((e=>{this._logger.log(S.Error,`TransportSendQueue.stop() threw error '${e}'.`)})),this._sendQueue=void 0),this.connectionId=void 0,this._connectionState="Disconnected",this._connectionStarted){this._connectionStarted=!1;try{this.onclose&&this.onclose(e)}catch(t){this._logger.log(S.Error,`HttpConnection.onclose(${e}) threw error '${t}'.`)}}}else this._logger.log(S.Debug,`Call to HttpConnection.stopConnection(${e}) was ignored because the connection is already in the disconnected state.`)}_resolveUrl(e){if(0===e.lastIndexOf("https://",0)||0===e.lastIndexOf("http://",0))return e;if(!G.isBrowser)throw new Error(`Cannot resolve '${e}'.`);const t=window.document.createElement("a");return t.href=e,this._logger.log(S.Information,`Normalizing '${e}' to '${t.href}'.`),t.href}_resolveNegotiateUrl(e){const t=new URL(e);t.pathname.endsWith("/")?t.pathname+="negotiate":t.pathname+="/negotiate";const n=new URLSearchParams(t.searchParams);return n.has("negotiateVersion")||n.append("negotiateVersion",this._negotiateVersion.toString()),n.has("useStatefulReconnect")?"true"===n.get("useStatefulReconnect")&&(this._options._useStatefulReconnect=!0):!0===this._options._useStatefulReconnect&&n.append("useStatefulReconnect","true"),t.search=n.toString(),t.toString()}}class K{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new z,this._transportResult=new z,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new z),this._transportResult.promise}stop(){return this._executing=!1,this._sendBufferedData.resolve(),this._sendLoopPromise}_bufferData(e){if(this._buffer.length&&typeof this._buffer[0]!=typeof e)throw new Error(`Expected data to be of type ${typeof this._buffer} but was of type ${typeof e}`);this._buffer.push(e),this._sendBufferedData.resolve()}async _sendLoop(){for(;;){if(await this._sendBufferedData.promise,!this._executing){this._transportResult&&this._transportResult.reject("Connection stopped.");break}this._sendBufferedData=new z;const e=this._transportResult;this._transportResult=void 0;const t="string"==typeof this._buffer[0]?this._buffer.join(""):K._concatBuffers(this._buffer);this._buffer.length=0;try{await this._transport.send(t),e.resolve()}catch(t){e.reject(t)}}}static _concatBuffers(e){const t=e.map((e=>e.byteLength)).reduce(((e,t)=>e+t)),n=new Uint8Array(t);let s=0;for(const t of e)n.set(new Uint8Array(t),s),s+=t.byteLength;return n.buffer}}class z{constructor(){this.promise=new Promise(((e,t)=>[this._resolver,this._rejecter]=[e,t]))}resolve(){this._resolver()}reject(e){this._rejecter(e)}}class J{static write(e){return`${e}${J.RecordSeparator}`}static parse(e){if(e[e.length-1]!==J.RecordSeparator)throw new Error("Message is incomplete.");const t=e.split(J.RecordSeparator);return t.pop(),t}}J.RecordSeparatorCode=30,J.RecordSeparator=String.fromCharCode(J.RecordSeparatorCode);class Y{writeHandshakeRequest(e){return J.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,n;if(N(e)){const s=new Uint8Array(e),r=s.indexOf(J.RecordSeparatorCode);if(-1===r)throw new Error("Message is incomplete.");const o=r+1;t=String.fromCharCode.apply(null,Array.prototype.slice.call(s.slice(0,o))),n=s.byteLength>o?s.slice(o).buffer:null}else{const s=e,r=s.indexOf(J.RecordSeparator);if(-1===r)throw new Error("Message is incomplete.");const o=r+1;t=s.substring(0,o),n=s.length>o?s.substring(o):null}const s=J.parse(t),r=JSON.parse(s[0]);if(r.type)throw new Error("Expected a handshake response from the server.");return[n,r]}}!function(e){e[e.Invocation=1]="Invocation",e[e.StreamItem=2]="StreamItem",e[e.Completion=3]="Completion",e[e.StreamInvocation=4]="StreamInvocation",e[e.CancelInvocation=5]="CancelInvocation",e[e.Ping=6]="Ping",e[e.Close=7]="Close",e[e.Ack=8]="Ack",e[e.Sequence=9]="Sequence"}(C||(C={}));class X{constructor(){this.observers=[]}next(e){for(const t of this.observers)t.next(e)}error(e){for(const t of this.observers)t.error&&t.error(e)}complete(){for(const e of this.observers)e.complete&&e.complete()}subscribe(e){return this.observers.push(e),new I(this,e)}}class Q{constructor(e,t,n){this._bufferSize=1e5,this._messages=[],this._totalMessageCount=0,this._waitForSequenceMessage=!1,this._nextReceivingSequenceId=1,this._latestReceivedSequenceId=0,this._bufferedByteCount=0,this._reconnectInProgress=!1,this._protocol=e,this._connection=t,this._bufferSize=n}async _send(e){const t=this._protocol.writeMessage(e);let n=Promise.resolve();if(this._isInvocationMessage(e)){this._totalMessageCount++;let e=()=>{},s=()=>{};N(t)?this._bufferedByteCount+=t.byteLength:this._bufferedByteCount+=t.length,this._bufferedByteCount>=this._bufferSize&&(n=new Promise(((t,n)=>{e=t,s=n}))),this._messages.push(new Z(t,this._totalMessageCount,e,s))}try{this._reconnectInProgress||await this._connection.send(t)}catch{this._disconnected()}await n}_ack(e){let t=-1;for(let n=0;n<this._messages.length;n++){const s=this._messages[n];if(s._id<=e.sequenceId)t=n,N(s._message)?this._bufferedByteCount-=s._message.byteLength:this._bufferedByteCount-=s._message.length,s._resolver();else{if(!(this._bufferedByteCount<this._bufferSize))break;s._resolver()}}-1!==t&&(this._messages=this._messages.slice(t+1))}_shouldProcessMessage(e){if(this._waitForSequenceMessage)return e.type===C.Sequence&&(this._waitForSequenceMessage=!1,!0);if(!this._isInvocationMessage(e))return!0;const t=this._nextReceivingSequenceId;return this._nextReceivingSequenceId++,t<=this._latestReceivedSequenceId?(t===this._latestReceivedSequenceId&&this._ackTimer(),!1):(this._latestReceivedSequenceId=t,this._ackTimer(),!0)}_resetSequence(e){e.sequenceId>this._nextReceivingSequenceId?this._connection.stop(new Error("Sequence ID greater than amount of messages we've received.")):this._nextReceivingSequenceId=e.sequenceId}_disconnected(){this._reconnectInProgress=!0,this._waitForSequenceMessage=!0}async _resend(){const e=0!==this._messages.length?this._messages[0]._id:this._totalMessageCount+1;await this._connection.send(this._protocol.writeMessage({type:C.Sequence,sequenceId:e}));const t=this._messages;for(const e of t)await this._connection.send(e._message);this._reconnectInProgress=!1}_dispose(e){null!=e||(e=new Error("Unable to reconnect to server."));for(const t of this._messages)t._rejector(e)}_isInvocationMessage(e){switch(e.type){case C.Invocation:case C.StreamItem:case C.Completion:case C.StreamInvocation:case C.CancelInvocation:return!0;case C.Close:case C.Sequence:case C.Ping:case C.Ack:return!1}}_ackTimer(){void 0===this._ackTimerHandle&&(this._ackTimerHandle=setTimeout((async()=>{try{this._reconnectInProgress||await this._connection.send(this._protocol.writeMessage({type:C.Ack,sequenceId:this._latestReceivedSequenceId}))}catch{}clearTimeout(this._ackTimerHandle),this._ackTimerHandle=void 0}),1e3))}}class Z{constructor(e,t,n,s){this._message=e,this._id=t,this._resolver=n,this._rejector=s}}!function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"}(T||(T={}));class ee{static create(e,t,n,s,r,o,i){return new ee(e,t,n,s,r,o,i)}constructor(e,t,n,s,r,o,i){this._nextKeepAlive=0,this._freezeEventListener=()=>{this._logger.log(S.Warning,"The page is being frozen, this will likely lead to the connection being closed and messages being lost. For more information see the docs at https://learn.microsoft.com/aspnet/core/signalr/javascript-client#bsleep")},k.isRequired(e,"connection"),k.isRequired(t,"logger"),k.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=null!=r?r:3e4,this.keepAliveIntervalInMilliseconds=null!=o?o:15e3,this._statefulReconnectBufferSize=null!=i?i:1e5,this._logger=t,this._protocol=n,this.connection=e,this._reconnectPolicy=s,this._handshakeProtocol=new Y,this.connection.onreceive=e=>this._processIncomingData(e),this.connection.onclose=e=>this._connectionClosed(e),this._callbacks={},this._methods={},this._closedCallbacks=[],this._reconnectingCallbacks=[],this._reconnectedCallbacks=[],this._invocationId=0,this._receivedHandshakeResponse=!1,this._connectionState=T.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:C.Ping})}get state(){return this._connectionState}get connectionId(){return this.connection&&this.connection.connectionId||null}get baseUrl(){return this.connection.baseUrl||""}set baseUrl(e){if(this._connectionState!==T.Disconnected&&this._connectionState!==T.Reconnecting)throw new Error("The HubConnection must be in the Disconnected or Reconnecting state to change the url.");if(!e)throw new Error("The HubConnection url must be a valid url.");this.connection.baseUrl=e}start(){return this._startPromise=this._startWithStateTransitions(),this._startPromise}async _startWithStateTransitions(){if(this._connectionState!==T.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=T.Connecting,this._logger.log(S.Debug,"Starting HubConnection.");try{await this._startInternal(),G.isBrowser&&window.document.addEventListener("freeze",this._freezeEventListener),this._connectionState=T.Connected,this._connectionStarted=!0,this._logger.log(S.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=T.Disconnected,this._logger.log(S.Debug,`HubConnection failed to start successfully because of error '${e}'.`),Promise.reject(e)}}async _startInternal(){this._stopDuringStartError=void 0,this._receivedHandshakeResponse=!1;const e=new Promise(((e,t)=>{this._handshakeResolver=e,this._handshakeRejecter=t}));await this.connection.start(this._protocol.transferFormat);try{let t=this._protocol.version;this.connection.features.reconnect||(t=1);const n={protocol:this._protocol.name,version:t};if(this._logger.log(S.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(n)),this._logger.log(S.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await e,this._stopDuringStartError)throw this._stopDuringStartError;!!this.connection.features.reconnect&&(this._messageBuffer=new Q(this._protocol,this.connection,this._statefulReconnectBufferSize),this.connection.features.disconnected=this._messageBuffer._disconnected.bind(this._messageBuffer),this.connection.features.resend=()=>{if(this._messageBuffer)return this._messageBuffer._resend()}),this.connection.features.inherentKeepAlive||await this._sendMessage(this._cachedPingMessage)}catch(e){throw this._logger.log(S.Debug,`Hub handshake failed with error '${e}' during start(). Stopping HubConnection.`),this._cleanupTimeout(),this._cleanupPingTimer(),await this.connection.stop(e),e}}async stop(){const e=this._startPromise;this.connection.features.reconnect=!1,this._stopPromise=this._stopInternal(),await this._stopPromise;try{await e}catch(e){}}_stopInternal(e){if(this._connectionState===T.Disconnected)return this._logger.log(S.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve();if(this._connectionState===T.Disconnecting)return this._logger.log(S.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise;const t=this._connectionState;return this._connectionState=T.Disconnecting,this._logger.log(S.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(S.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(t===T.Connected&&this._sendCloseMessage(),this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new p("The connection was stopped before the hub handshake could complete."),this.connection.stop(e))}async _sendCloseMessage(){try{await this._sendWithProtocol(this._createCloseMessage())}catch{}}stream(e,...t){const[n,s]=this._replaceStreamingParams(t),r=this._createStreamInvocation(e,t,s);let o;const i=new X;return i.cancelCallback=()=>{const e=this._createCancelInvocation(r.invocationId);return delete this._callbacks[r.invocationId],o.then((()=>this._sendWithProtocol(e)))},this._callbacks[r.invocationId]=(e,t)=>{t?i.error(t):e&&(e.type===C.Completion?e.error?i.error(new Error(e.error)):i.complete():i.next(e.item))},o=this._sendWithProtocol(r).catch((e=>{i.error(e),delete this._callbacks[r.invocationId]})),this._launchStreams(n,o),i}_sendMessage(e){return this._resetKeepAliveInterval(),this.connection.send(e)}_sendWithProtocol(e){return this._messageBuffer?this._messageBuffer._send(e):this._sendMessage(this._protocol.writeMessage(e))}send(e,...t){const[n,s]=this._replaceStreamingParams(t),r=this._sendWithProtocol(this._createInvocation(e,t,!0,s));return this._launchStreams(n,r),r}invoke(e,...t){const[n,s]=this._replaceStreamingParams(t),r=this._createInvocation(e,t,!1,s);return new Promise(((e,t)=>{this._callbacks[r.invocationId]=(n,s)=>{s?t(s):n&&(n.type===C.Completion?n.error?t(new Error(n.error)):e(n.result):t(new Error(`Unexpected message type: ${n.type}`)))};const s=this._sendWithProtocol(r).catch((e=>{t(e),delete this._callbacks[r.invocationId]}));this._launchStreams(n,s)}))}on(e,t){e&&t&&(e=e.toLowerCase(),this._methods[e]||(this._methods[e]=[]),-1===this._methods[e].indexOf(t)&&this._methods[e].push(t))}off(e,t){if(!e)return;e=e.toLowerCase();const n=this._methods[e];if(n)if(t){const s=n.indexOf(t);-1!==s&&(n.splice(s,1),0===n.length&&delete this._methods[e])}else delete this._methods[e]}onclose(e){e&&this._closedCallbacks.push(e)}onreconnecting(e){e&&this._reconnectingCallbacks.push(e)}onreconnected(e){e&&this._reconnectedCallbacks.push(e)}_processIncomingData(e){if(this._cleanupTimeout(),this._receivedHandshakeResponse||(e=this._processHandshakeResponse(e),this._receivedHandshakeResponse=!0),e){const t=this._protocol.parseMessages(e,this._logger);for(const e of t)if(!this._messageBuffer||this._messageBuffer._shouldProcessMessage(e))switch(e.type){case C.Invocation:this._invokeClientMethod(e).catch((e=>{this._logger.log(S.Error,`Invoke client method threw error: ${x(e)}`)}));break;case C.StreamItem:case C.Completion:{const t=this._callbacks[e.invocationId];if(t){e.type===C.Completion&&delete this._callbacks[e.invocationId];try{t(e)}catch(e){this._logger.log(S.Error,`Stream callback threw error: ${x(e)}`)}}break}case C.Ping:break;case C.Close:{this._logger.log(S.Information,"Close message received from server.");const t=e.error?new Error("Server returned an error on close: "+e.error):void 0;!0===e.allowReconnect?this.connection.stop(t):this._stopPromise=this._stopInternal(t);break}case C.Ack:this._messageBuffer&&this._messageBuffer._ack(e);break;case C.Sequence:this._messageBuffer&&this._messageBuffer._resetSequence(e);break;default:this._logger.log(S.Warning,`Invalid message type: ${e.type}.`)}}this._resetTimeoutPeriod()}_processHandshakeResponse(e){let t,n;try{[n,t]=this._handshakeProtocol.parseHandshakeResponse(e)}catch(e){const t="Error parsing handshake response: "+e;this._logger.log(S.Error,t);const n=new Error(t);throw this._handshakeRejecter(n),n}if(t.error){const e="Server returned handshake error: "+t.error;this._logger.log(S.Error,e);const n=new Error(e);throw this._handshakeRejecter(n),n}return this._logger.log(S.Debug,"Server handshake complete."),this._handshakeResolver(),n}_resetKeepAliveInterval(){this.connection.features.inherentKeepAlive||(this._nextKeepAlive=(new Date).getTime()+this.keepAliveIntervalInMilliseconds,this._cleanupPingTimer())}_resetTimeoutPeriod(){if(!(this.connection.features&&this.connection.features.inherentKeepAlive||(this._timeoutHandle=setTimeout((()=>this.serverTimeout()),this.serverTimeoutInMilliseconds),void 0!==this._pingServerHandle))){let e=this._nextKeepAlive-(new Date).getTime();e<0&&(e=0),this._pingServerHandle=setTimeout((async()=>{if(this._connectionState===T.Connected)try{await this._sendMessage(this._cachedPingMessage)}catch{this._cleanupPingTimer()}}),e)}}serverTimeout(){this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server."))}async _invokeClientMethod(e){const t=e.target.toLowerCase(),n=this._methods[t];if(!n)return this._logger.log(S.Warning,`No client method with the name '${t}' found.`),void(e.invocationId&&(this._logger.log(S.Warning,`No result given for '${t}' method and invocation ID '${e.invocationId}'.`),await this._sendWithProtocol(this._createCompletionMessage(e.invocationId,"Client didn't provide a result.",null))));const s=n.slice(),r=!!e.invocationId;let o,i,a;for(const n of s)try{const s=o;o=await n.apply(this,e.arguments),r&&o&&s&&(this._logger.log(S.Error,`Multiple results provided for '${t}'. Sending error to server.`),a=this._createCompletionMessage(e.invocationId,"Client provided multiple results.",null)),i=void 0}catch(e){i=e,this._logger.log(S.Error,`A callback for the method '${t}' threw error '${e}'.`)}a?await this._sendWithProtocol(a):r?(i?a=this._createCompletionMessage(e.invocationId,`${i}`,null):void 0!==o?a=this._createCompletionMessage(e.invocationId,null,o):(this._logger.log(S.Warning,`No result given for '${t}' method and invocation ID '${e.invocationId}'.`),a=this._createCompletionMessage(e.invocationId,"Client didn't provide a result.",null)),await this._sendWithProtocol(a)):o&&this._logger.log(S.Error,`Result given for '${t}' method but server is not expecting a result.`)}_connectionClosed(e){this._logger.log(S.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new p("The underlying connection was closed before the hub handshake could complete."),this._handshakeResolver&&this._handshakeResolver(),this._cancelCallbacksWithError(e||new Error("Invocation canceled due to the underlying connection being closed.")),this._cleanupTimeout(),this._cleanupPingTimer(),this._connectionState===T.Disconnecting?this._completeClose(e):this._connectionState===T.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===T.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=T.Disconnected,this._connectionStarted=!1,this._messageBuffer&&(this._messageBuffer._dispose(null!=e?e:new Error("Connection closed.")),this._messageBuffer=void 0),G.isBrowser&&window.document.removeEventListener("freeze",this._freezeEventListener);try{this._closedCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(S.Error,`An onclose callback called with error '${e}' threw error '${t}'.`)}}}async _reconnect(e){const t=Date.now();let n=0,s=void 0!==e?e:new Error("Attempting to reconnect due to a unknown error."),r=this._getNextRetryDelay(n++,0,s);if(null===r)return this._logger.log(S.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=T.Reconnecting,e?this._logger.log(S.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(S.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(S.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==T.Reconnecting)return void this._logger.log(S.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==r;){if(this._logger.log(S.Information,`Reconnect attempt number ${n} will start in ${r} ms.`),await new Promise((e=>{this._reconnectDelayHandle=setTimeout(e,r)})),this._reconnectDelayHandle=void 0,this._connectionState!==T.Reconnecting)return void this._logger.log(S.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=T.Connected,this._logger.log(S.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((e=>e.apply(this,[this.connection.connectionId])))}catch(e){this._logger.log(S.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(S.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==T.Reconnecting)return this._logger.log(S.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===T.Disconnecting&&this._completeClose());s=e instanceof Error?e:new Error(e.toString()),r=this._getNextRetryDelay(n++,Date.now()-t,s)}}this._logger.log(S.Information,`Reconnect retries have been exhausted after ${Date.now()-t} ms and ${n} failed attempts. Connection disconnecting.`),this._completeClose()}_getNextRetryDelay(e,t,n){try{return this._reconnectPolicy.nextRetryDelayInMilliseconds({elapsedMilliseconds:t,previousRetryCount:e,retryReason:n})}catch(n){return this._logger.log(S.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${n}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach((n=>{const s=t[n];try{s(null,e)}catch(t){this._logger.log(S.Error,`Stream 'error' callback called with '${e}' threw error: ${x(t)}`)}}))}_cleanupPingTimer(){this._pingServerHandle&&(clearTimeout(this._pingServerHandle),this._pingServerHandle=void 0)}_cleanupTimeout(){this._timeoutHandle&&clearTimeout(this._timeoutHandle)}_createInvocation(e,t,n,s){if(n)return 0!==s.length?{arguments:t,streamIds:s,target:e,type:C.Invocation}:{arguments:t,target:e,type:C.Invocation};{const n=this._invocationId;return this._invocationId++,0!==s.length?{arguments:t,invocationId:n.toString(),streamIds:s,target:e,type:C.Invocation}:{arguments:t,invocationId:n.toString(),target:e,type:C.Invocation}}}_launchStreams(e,t){if(0!==e.length){t||(t=Promise.resolve());for(const n in e)e[n].subscribe({complete:()=>{t=t.then((()=>this._sendWithProtocol(this._createCompletionMessage(n))))},error:e=>{let s;s=e instanceof Error?e.message:e&&e.toString?e.toString():"Unknown error",t=t.then((()=>this._sendWithProtocol(this._createCompletionMessage(n,s))))},next:e=>{t=t.then((()=>this._sendWithProtocol(this._createStreamItemMessage(n,e))))}})}}_replaceStreamingParams(e){const t=[],n=[];for(let s=0;s<e.length;s++){const r=e[s];if(this._isObservable(r)){const o=this._invocationId;this._invocationId++,t[o]=r,n.push(o.toString()),e.splice(s,1)}}return[t,n]}_isObservable(e){return e&&e.subscribe&&"function"==typeof e.subscribe}_createStreamInvocation(e,t,n){const s=this._invocationId;return this._invocationId++,0!==n.length?{arguments:t,invocationId:s.toString(),streamIds:n,target:e,type:C.StreamInvocation}:{arguments:t,invocationId:s.toString(),target:e,type:C.StreamInvocation}}_createCancelInvocation(e){return{invocationId:e,type:C.CancelInvocation}}_createStreamItemMessage(e,t){return{invocationId:e,item:t,type:C.StreamItem}}_createCompletionMessage(e,t,n){return t?{error:t,invocationId:e,type:C.Completion}:{invocationId:e,result:n,type:C.Completion}}_createCloseMessage(){return{type:C.Close}}}class te{constructor(){this.name="json",this.version=2,this.transferFormat=_.Text}parseMessages(e,t){if("string"!=typeof e)throw new Error("Invalid input for JSON hub protocol. Expected a string.");if(!e)return[];null===t&&(t=D.instance);const n=J.parse(e),s=[];for(const e of n){const n=JSON.parse(e);if("number"!=typeof n.type)throw new Error("Invalid payload.");switch(n.type){case C.Invocation:this._isInvocationMessage(n);break;case C.StreamItem:this._isStreamItemMessage(n);break;case C.Completion:this._isCompletionMessage(n);break;case C.Ping:case C.Close:break;case C.Ack:this._isAckMessage(n);break;case C.Sequence:this._isSequenceMessage(n);break;default:t.log(S.Information,"Unknown message type '"+n.type+"' ignored.");continue}s.push(n)}return s}writeMessage(e){return J.write(JSON.stringify(e))}_isInvocationMessage(e){this._assertNotEmptyString(e.target,"Invalid payload for Invocation message."),void 0!==e.invocationId&&this._assertNotEmptyString(e.invocationId,"Invalid payload for Invocation message.")}_isStreamItemMessage(e){if(this._assertNotEmptyString(e.invocationId,"Invalid payload for StreamItem message."),void 0===e.item)throw new Error("Invalid payload for StreamItem message.")}_isCompletionMessage(e){if(e.result&&e.error)throw new Error("Invalid payload for Completion message.");!e.result&&e.error&&this._assertNotEmptyString(e.error,"Invalid payload for Completion message."),this._assertNotEmptyString(e.invocationId,"Invalid payload for Completion message.")}_isAckMessage(e){if("number"!=typeof e.sequenceId)throw new Error("Invalid SequenceId for Ack message.")}_isSequenceMessage(e){if("number"!=typeof e.sequenceId)throw new Error("Invalid SequenceId for Sequence message.")}_assertNotEmptyString(e,t){if("string"!=typeof e||""===e)throw new Error(t)}}const ne={trace:S.Trace,debug:S.Debug,info:S.Information,information:S.Information,warn:S.Warning,warning:S.Warning,error:S.Error,critical:S.Critical,none:S.None};class se{configureLogging(e){if(k.isRequired(e,"logging"),void 0!==e.log)this.logger=e;else if("string"==typeof e){const t=function(e){const t=ne[e.toLowerCase()];if(void 0!==t)return t;throw new Error(`Unknown log level: ${e}`)}(e);this.logger=new R(t)}else this.logger=new R(e);return this}withUrl(e,t){return k.isRequired(e,"url"),k.isNotEmpty(e,"url"),this.url=e,this.httpConnectionOptions="object"==typeof t?{...this.httpConnectionOptions,...t}:{...this.httpConnectionOptions,transport:t},this}withHubProtocol(e){return k.isRequired(e,"protocol"),this.protocol=e,this}withAutomaticReconnect(e){if(this.reconnectPolicy)throw new Error("A reconnectPolicy has already been set.");return e?Array.isArray(e)?this.reconnectPolicy=new a(e):this.reconnectPolicy=e:this.reconnectPolicy=new a,this}withServerTimeout(e){return k.isRequired(e,"milliseconds"),this._serverTimeoutInMilliseconds=e,this}withKeepAliveInterval(e){return k.isRequired(e,"milliseconds"),this._keepAliveIntervalInMilliseconds=e,this}withStatefulReconnect(e){return void 0===this.httpConnectionOptions&&(this.httpConnectionOptions={}),this.httpConnectionOptions._useStatefulReconnect=!0,this._statefulReconnectBufferSize=null==e?void 0:e.bufferSize,this}build(){const e=this.httpConnectionOptions||{};if(void 0===e.logger&&(e.logger=this.logger),!this.url)throw new Error("The 'HubConnectionBuilder.withUrl' method must be called before building the connection.");const t=new j(this.url,e);return ee.create(t,this.logger||D.instance,this.protocol||new te,this.reconnectPolicy,this._serverTimeoutInMilliseconds,this._keepAliveIntervalInMilliseconds,this._statefulReconnectBufferSize)}}class re{static GenerateUUID(){var e=(new Date).getTime(),t="undefined"!=typeof performance&&performance.now&&1e3*performance.now()||0;return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(n){var s=16*Math.random();return e>0?(s=(e+s)%16|0,e=Math.floor(e/16)):(s=(t+s)%16|0,t=Math.floor(t/16)),("x"===n?s:3&s|8).toString(16)}))}static GenerateMd5(e){let t="0123456789abcdef";function n(e){let n,s="";for(n=0;n<=3;n++)s+=t.charAt(e>>8*n+4&15)+t.charAt(e>>8*n&15);return s}function s(e,t){let n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}function r(e,t,n,r,o,i){return s(function(e,t){return e<<t|e>>>32-t}(s(s(t,e),s(r,i)),o),n)}function o(e,t,n,s,o,i,a){return r(t&n|~t&s,e,t,o,i,a)}function i(e,t,n,s,o,i,a){return r(t&s|n&~s,e,t,o,i,a)}function a(e,t,n,s,o,i,a){return r(t^n^s,e,t,o,i,a)}function c(e,t,n,s,o,i,a){return r(n^(t|~s),e,t,o,i,a)}let u,l,d,h,g,p=function(e){let t,n=1+(e.length+8>>6),s=new Array(16*n);for(t=0;t<16*n;t++)s[t]=0;for(t=0;t<e.length;t++)s[t>>2]|=e.charCodeAt(t)<<t%4*8;return s[t>>2]|=128<<t%4*8,s[16*n-2]=8*e.length,s}(""+e),f=1732584193,v=-271733879,m=-1732584194,y=271733878;for(u=0;u<p.length;u+=16)l=f,d=v,h=m,g=y,f=o(f,v,m,y,p[u+0],7,-680876936),y=o(y,f,v,m,p[u+1],12,-389564586),m=o(m,y,f,v,p[u+2],17,606105819),v=o(v,m,y,f,p[u+3],22,-1044525330),f=o(f,v,m,y,p[u+4],7,-176418897),y=o(y,f,v,m,p[u+5],12,1200080426),m=o(m,y,f,v,p[u+6],17,-1473231341),v=o(v,m,y,f,p[u+7],22,-45705983),f=o(f,v,m,y,p[u+8],7,1770035416),y=o(y,f,v,m,p[u+9],12,-1958414417),m=o(m,y,f,v,p[u+10],17,-42063),v=o(v,m,y,f,p[u+11],22,-1990404162),f=o(f,v,m,y,p[u+12],7,1804603682),y=o(y,f,v,m,p[u+13],12,-40341101),m=o(m,y,f,v,p[u+14],17,-1502002290),v=o(v,m,y,f,p[u+15],22,1236535329),f=i(f,v,m,y,p[u+1],5,-165796510),y=i(y,f,v,m,p[u+6],9,-1069501632),m=i(m,y,f,v,p[u+11],14,643717713),v=i(v,m,y,f,p[u+0],20,-373897302),f=i(f,v,m,y,p[u+5],5,-701558691),y=i(y,f,v,m,p[u+10],9,38016083),m=i(m,y,f,v,p[u+15],14,-660478335),v=i(v,m,y,f,p[u+4],20,-405537848),f=i(f,v,m,y,p[u+9],5,568446438),y=i(y,f,v,m,p[u+14],9,-1019803690),m=i(m,y,f,v,p[u+3],14,-187363961),v=i(v,m,y,f,p[u+8],20,1163531501),f=i(f,v,m,y,p[u+13],5,-1444681467),y=i(y,f,v,m,p[u+2],9,-51403784),m=i(m,y,f,v,p[u+7],14,1735328473),v=i(v,m,y,f,p[u+12],20,-1926607734),f=a(f,v,m,y,p[u+5],4,-378558),y=a(y,f,v,m,p[u+8],11,-2022574463),m=a(m,y,f,v,p[u+11],16,1839030562),v=a(v,m,y,f,p[u+14],23,-35309556),f=a(f,v,m,y,p[u+1],4,-1530992060),y=a(y,f,v,m,p[u+4],11,1272893353),m=a(m,y,f,v,p[u+7],16,-155497632),v=a(v,m,y,f,p[u+10],23,-1094730640),f=a(f,v,m,y,p[u+13],4,681279174),y=a(y,f,v,m,p[u+0],11,-358537222),m=a(m,y,f,v,p[u+3],16,-722521979),v=a(v,m,y,f,p[u+6],23,76029189),f=a(f,v,m,y,p[u+9],4,-640364487),y=a(y,f,v,m,p[u+12],11,-421815835),m=a(m,y,f,v,p[u+15],16,530742520),v=a(v,m,y,f,p[u+2],23,-995338651),f=c(f,v,m,y,p[u+0],6,-198630844),y=c(y,f,v,m,p[u+7],10,1126891415),m=c(m,y,f,v,p[u+14],15,-1416354905),v=c(v,m,y,f,p[u+5],21,-57434055),f=c(f,v,m,y,p[u+12],6,1700485571),y=c(y,f,v,m,p[u+3],10,-1894986606),m=c(m,y,f,v,p[u+10],15,-1051523),v=c(v,m,y,f,p[u+1],21,-2054922799),f=c(f,v,m,y,p[u+8],6,1873313359),y=c(y,f,v,m,p[u+15],10,-30611744),m=c(m,y,f,v,p[u+6],15,-1560198380),v=c(v,m,y,f,p[u+13],21,1309151649),f=c(f,v,m,y,p[u+4],6,-145523070),y=c(y,f,v,m,p[u+11],10,-1120210379),m=c(m,y,f,v,p[u+2],15,718787259),v=c(v,m,y,f,p[u+9],21,-343485551),f=s(f,l),v=s(v,d),m=s(m,h),y=s(y,g);return n(f)+n(v)+n(m)+n(y)}}class oe{static Delay(e){return new Promise((t=>setTimeout(t,e)))}}function ie(e){return new Map(Object.entries(e))}class ae{constructor(){this.TransactionId=re.GenerateUUID()}}var ce,ue,le,de,he,ge,pe,fe,ve,me,ye,we,Se,Ae;(we=ce||(ce={}))[we.OK=0]="OK",we[we.UnknownError=1]="UnknownError",we[we.FatalError=2]="FatalError",we[we.WrongData=3]="WrongData",we[we.ResourceDoesNotExists=4]="ResourceDoesNotExists",we[we.NoPermissionToPerformThisOperation=5]="NoPermissionToPerformThisOperation",we[we.SessionHasAlreadyLoggedOnUser=6]="SessionHasAlreadyLoggedOnUser",we[we.OperationNotPermitted=7]="OperationNotPermitted",we[we.NoPermissionsToCallGivenResource=8]="NoPermissionsToCallGivenResource",we[we.ResourceIsNotAvailable=9]="ResourceIsNotAvailable",we[we.Error=10]="Error",we[we.NoData=11]="NoData",we[we.NotSupportedMethod=12]="NotSupportedMethod",we[we.UserIsNotLoggedIn=13]="UserIsNotLoggedIn",we[we.MultiDataResponseStart=14]="MultiDataResponseStart",we[we.MultiDataResponse=15]="MultiDataResponse",we[we.MultiDataResponseStop=16]="MultiDataResponseStop",function(e){e[e.Get=0]="Get",e[e.Post=1]="Post",e[e.Delete=2]="Delete",e[e.Put=3]="Put",e[e.Options=4]="Options",e[e.Head=5]="Head"}(ue||(ue={}));class _e{constructor(e,t){this.serialNumber=e,this.pin=t,this.SerialNumber=e,this.PIN=t}}!function(e){e[e.ByCloud=0]="ByCloud",e[e.LocalNetwork=1]="LocalNetwork",e[e.P2P=2]="P2P"}(le||(le={})),function(e){e[e.FailedToConnect=0]="FailedToConnect",e[e.AuthorizationFailed=1]="AuthorizationFailed",e[e.FailedToConnectToServer=2]="FailedToConnectToServer",e[e.Connected=3]="Connected",e[e.ControllerIsNotConnected=4]="ControllerIsNotConnected"}(de||(de={})),function(e){e[e.Disconnected=0]="Disconnected",e[e.Connecting=1]="Connecting",e[e.Connected=3]="Connected",e[e.Disconnecting=4]="Disconnecting",e[e.Failed=5]="Failed",e[e.Reconnecting=6]="Reconnecting"}(he||(he={}));class Ce{constructor(){this._log=Ov.Get(s.ServiceName),this.handlers=[]}Subscribe(e){this.handlers.push(e)}Unsubscribe(e){this.handlers=this.handlers.filter((t=>t!==e))}Invoke(){this.handlers.slice(0).forEach((e=>{try{e()}catch(e){this._log.Error(e)}}))}}(Ae=ge||(ge={}))[Ae.Any=0]="Any",Ae[Ae.Guest=10]="Guest",Ae[Ae.Standard=20]="Standard",Ae[Ae.Admin=30]="Admin",Ae[Ae.Installator=40]="Installator",Ae[Ae.Support=50]="Support",(Se=pe||(pe={}))[Se.Unknown=0]="Unknown",Se[Se.Men=1]="Men",Se[Se.Woman=2]="Woman",Se[Se.Other=3]="Other",function(e){e[e.En_Us=0]="En_Us",e[e.Pl_Pl=1]="Pl_Pl"}(fe||(fe={})),function(e){e[e.Unknown=0]="Unknown",e[e.WrongAuthData=1]="WrongAuthData",e[e.NoResponseFromController=2]="NoResponseFromController",e[e.AuthDisabled=3]="AuthDisabled",e[e.MethodNotSupported=4]="MethodNotSupported"}(ve||(ve={}));class Te{constructor(e,t){this._type=me.Unknown,this._data="",this._type=e,this._data=t}get Type(){return this._type}set Type(e){this._type=e}get Data(){return this._data}set Data(e){this._data=e}}class De{constructor(e,t){this._type=null,this._data="",this._type=e,this._data=t}get Type(){return this._type}set Type(e){this._type=e}get Data(){return this._data}set Data(e){this._data=e}}!function(e){e[e.ResourceDoesNotExists=-6]="ResourceDoesNotExists",e[e.UnknownError=-5]="UnknownError",e[e.NoPermissions=-4]="NoPermissions",e[e.WrongData=-3]="WrongData",e[e.ControllerResponseTimeout=-2]="ControllerResponseTimeout",e[e.Failed=-1]="Failed",e[e.Unknown=0]="Unknown",e[e.Changed=1]="Changed"}(me||(me={})),function(e){e[e.Device=1]="Device",e[e.Person=2]="Person",e[e.DevicesGroups=3]="DevicesGroups"}(ye||(ye={}));class ke{constructor(){this._guid="",this._ownerGuid="",this._ownerIdentity="",this._base64Image="",this._imageType=ye.Device,this._dateTime=""}get Guid(){return this._guid}get OwnerGuid(){return this._ownerGuid}get OwnerIdentity(){return this._ownerIdentity}get Base64Image(){return this._base64Image}get ImageType(){return this._imageType}get DateTime(){return this._dateTime}set Base64Image(e){this._base64Image=e}set Guid(e){this._guid=e}set OwnerGuid(e){this._ownerGuid=e}set OwnerIdentity(e){this._ownerIdentity=e}set ImageType(e){this._imageType=e}}class Ge{constructor(){this._log=Ov.Get(s.ServiceName),Ge._localStorageService=Ov.Get(o.ServiceName)}GetServiceName(){return Ge.ServiceName}GetResourceName(e){return`${e.Resource}_${e.Method}`}Cache(e){var t;e.Status===ce.OK&&(this._log.Debug(Ge.ServiceName,`Caching request: ${e.Resource} ${e.Method}`),null===(t=Ge._localStorageService)||void 0===t||t.Save(this.GetServiceName(),this.GetResourceName(e),e))}GetCache(e){var t;let n=null===(t=Ge._localStorageService)||void 0===t?void 0:t.Read(this.GetServiceName(),this.GetResourceName(e));return null!=n&&this._log.Debug(Ge.ServiceName,`Got request response from cache: ${e.Resource} ${e.Method}`),n}ClearCache(){var e;null===(e=Ge._localStorageService)||void 0===e||e.DropStorage(this.GetServiceName()),this._log.Debug(Ge.ServiceName,`Clearing cache for ${this.GetServiceName()}`)}Remove(e){var t;null===(t=Ge._localStorageService)||void 0===t||t.Remove(this.GetServiceName(),this.GetResourceName(e)),this._log.Debug(Ge.ServiceName,`Clearing cache for cache: ${e.Resource} ${e.Method}`)}}Ge._localStorageService=null,Ge.ServiceName="WebApiCacheService";var be=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class Ne{constructor(){this._imageExistsCaseNumber=0,this._connection=Ov.Get(Pt.ServiceName),this._logger=Ov.Get(s.ServiceName)}GetServiceName(){return Ne.ServiceName}AddPictureAsync(e){return be(this,void 0,void 0,(function*(){var t,n;try{if(e.Base64Image.length*(3/4)>=512e3)return this._logger.Error(Ne.ServiceName,"Cannot add picture - Base64Imgae size exceeded."),ce.WrongData;let s=new Image;const r=new Promise(((t,n)=>{s.src=e.Base64Image,s.onload=function(){t(!0)},setTimeout((()=>t(!1)),5e3)}));if(!(yield r))return this._logger.Error(Ne.ServiceName,"Cannot add picture - cannot load image - ensure that given base64 string is an image!"),ce.WrongData;if(0===s.height||0===s.width)return this._logger.Error(Ne.ServiceName,"Cannot add picture - cannot read width/height of image - ensure that given base64 string is an image!"),ce.WrongData;if(null!=e.Guid&&""!=e.Guid)return this._logger.Error(Ne.ServiceName,"Cannot add picture - Guid must be empty."),ce.WrongData;const o=new Ie;o.Guid=re.GenerateUUID(),o.DateTime=(new Date).toISOString(),o.ImageType=e.ImageType,o.OwnerGuid=`${e.OwnerGuid}_${e.OwnerIdentity}`,o.Base64Image=e.Base64Image;const i=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Pe(o.Guid),8e3,!1);if(null==i||null==i.Status)return this._logger.Error(Ne.ServiceName,"Cannot add picture - unknown error!"),ce.UnknownError;if(i.Status==ce.ResourceDoesNotExists){const e=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new Me(o),8e3,!1);return null==e||null==e.Status?(this._logger.Error(Ne.ServiceName,"Cannot add picture - unknown error!"),ce.UnknownError):e.Status}return i.Status==ce.OK?(this._logger.Warning(Ne.ServiceName,"Cannot add picture - picture already exists, trying to add with regenerated GUID."),this._imageExistsCaseNumber<2?(this._imageExistsCaseNumber++,this.AddPictureAsync(e)):ce.UnknownError):(this._logger.Error(Ne.ServiceName,"Cannot add picture - cannot get current picture status."),ce.Error)}catch(e){return this._logger.Error(Ne.ServiceName,`Cannot add picture! ${e}`),ce.FatalError}}))}EditPictureAsync(e){return be(this,void 0,void 0,(function*(){var t,n;try{if(""==e.Guid||null==e.Guid)return this._logger.Error(Ne.ServiceName,"Cannot edit picture - guid is empty."),ce.WrongData;if(e.Base64Image.length*(3/4)>=512e3)return this._logger.Error(Ne.ServiceName,"Cannot edit picture - Base64Imgae size exceeded."),ce.WrongData;let s=new Image;const r=new Promise(((t,n)=>{s.src=e.Base64Image,s.onload=function(){t(!0)},setTimeout((()=>t(!1)),5e3)}));if(!(yield r))return this._logger.Error(Ne.ServiceName,"Cannot edit picture - cannot load image - ensure that given base64 string is an image!"),ce.WrongData;if(0===s.height||0===s.width)return this._logger.Error(Ne.ServiceName,"Cannot edit picture - cannot read width/height of image - ensure that given base64 string is an image!"),ce.WrongData;const o=new Ie;o.DateTime=(new Date).toISOString(),o.ImageType=e.ImageType,o.Base64Image=e.Base64Image,o.Guid=e.Guid,e.Guid.includes("profilePicture")||e.Guid.includes("devices_group")?o.OwnerGuid=e.OwnerGuid:o.OwnerGuid=`${e.OwnerGuid}_${e.OwnerIdentity}`;const i=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Pe(o.Guid),8e3,!1);if(Ov.Get(Ge.ServiceName).ClearCache(),Ov.Get(rt.ServiceName).ExitConfigurationModeAsync(),null==i||null==i.Status)return this._logger.Error(Ne.ServiceName,"Cannot edit picture - unknown error!"),ce.UnknownError;if(i.Status==ce.ResourceDoesNotExists)return this._logger.Error(Ne.ServiceName,"Cannot edit picture - picture not exists."),ce.OperationNotPermitted;if(i.Status==ce.OK){const e=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new Me(o),8e3,!1);return Ov.Get(Ge.ServiceName).ClearCache(),Ov.Get(rt.ServiceName).ExitConfigurationModeAsync(),null==e||null==e.Status?(this._logger.Error(Ne.ServiceName,"Cannot edit picture - unknown error!"),ce.UnknownError):e.Status}return this._logger.Error(Ne.ServiceName,"Cannot edit picture - cannot get current picture status."),ce.Error}catch(e){return this._logger.Error(Ne.ServiceName,`Cannot edit picture! ${e}`),ce.FatalError}}))}DeletePictureAsync(e){return be(this,void 0,void 0,(function*(){var t;try{if(""==e.Guid||null==e.Guid)return this._logger.Error(Ne.ServiceName,"Cannot delete picture - guid is empty."),ce.WrongData;const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new xe(e.Guid),8e3,!1);return Ov.Get(Ge.ServiceName).ClearCache(),Ov.Get(rt.ServiceName).ExitConfigurationModeAsync(),null==n||null==n.Status?(this._logger.Error(Ne.ServiceName,"Cannot edit picture - unknown error!"),ce.UnknownError):n.Status}catch(e){return this._logger.Error(Ne.ServiceName,`Cannot delete picture! ${e}`),ce.FatalError}}))}GetPicturesInfoAsync(){return be(this,void 0,void 0,(function*(){var e;try{const t=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new Oe,8e3,!1);return null==t||null==t.Status?(this._logger.Error(Ne.ServiceName,"Cannot get pictures info - unknown error!"),new De(ce.UnknownError,"NoDataInResult")):t.Status!=ce.OK?(this._logger.Error(Ne.ServiceName,`Cannot get pictures info - controler responded with status ${t.Status}.`),new De(t.Status,"UnknownReason")):null==t.Data?(this._logger.Error(Ne.ServiceName,"Cannot get pictures info - controler responded with OK, but no data in result.}."),new De(ce.UnknownError,"NoDataInResult")):t.Data.map((e=>{const t=new Re;return t.DateTime=e.DateTime,t.Guid=e.Guid,t.OwnerGuid=e.OwnerGuid,-1!=e.OwnerGuid.indexOf("_")?(t.OwnerGuid=e.OwnerGuid.substring(0,e.OwnerGuid.indexOf("_")),t.OwnerIdentity=e.OwnerGuid.substring(e.OwnerGuid.indexOf("_")+1)):e.Guid.includes("profilePicture")?(t.OwnerIdentity=e.Guid.substring(e.Guid.indexOf("_")+1),t.OwnerGuid=e.OwnerGuid):e.Guid.includes("devices_group")?(t.OwnerIdentity=e.Guid.substring(0,e.Guid.lastIndexOf("_")),t.OwnerGuid=e.OwnerGuid):(t.OwnerGuid=e.OwnerGuid,t.OwnerIdentity=""),t}))}catch(e){return this._logger.Error(Ne.ServiceName,`Cannot get picture info! ${e}`),new De(ce.FatalError,"ExceptionOccurred")}}))}GetPictureAsync(e){return be(this,void 0,void 0,(function*(){var t;try{const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Pe(e),8e3,!1);if(null==n||null==n.Status)return this._logger.Error(Ne.ServiceName,"Cannot get picture - unknown error!"),new De(ce.UnknownError,"NoDataInResult");switch(n.Status){case ce.ResourceDoesNotExists:return new De(ce.ResourceDoesNotExists,"PictureNotFound");case ce.OK:if(null==n.Data)return new De(ce.Error,"RespondedWithOKButNoData");const e=new Ee;return e.Base64Image=n.Data.Base64Image,e.DateTime=n.Data.DateTime,e.ImageType=n.Data.ImageType,e.Guid=n.Data.Guid,-1!=n.Data.OwnerGuid.indexOf("_")?(e.OwnerGuid=n.Data.OwnerGuid.substring(0,n.Data.OwnerGuid.indexOf("_")),e.OwnerIdentity=n.Data.OwnerGuid.substring(n.Data.OwnerGuid.indexOf("_")+1)):n.Data.Guid.includes("profilePicture")?(e.OwnerIdentity=n.Data.Guid.substring(n.Data.Guid.indexOf("_")+1),e.OwnerGuid=n.Data.OwnerGuid):n.Data.Guid.includes("devices_group")?(e.OwnerIdentity=n.Data.Guid.substring(0,n.Data.Guid.lastIndexOf("_")),e.OwnerGuid=n.Data.OwnerGuid):(e.OwnerGuid=n.Data.OwnerGuid,e.OwnerIdentity=""),e;default:return new De(n.Status,"UnknownReason")}}catch(e){return this._logger.Error(Ne.ServiceName,`Cannot get picture! ${e}`),new De(ce.FatalError,"ExceptionOccurred")}}))}GetPicturesListAsync(){return be(this,void 0,void 0,(function*(){var e;try{const t=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new Ue,8e3,!1);return null==t||null==t.Status?(this._logger.Error(Ne.ServiceName,"Cannot get pictures - unknown error!"),new De(ce.UnknownError,"NoDataInResult")):t.Status!=ce.OK?(this._logger.Error(Ne.ServiceName,`Cannot get pictures - controler responded with status ${t.Status}.`),new De(t.Status,"UnknownReason")):null==t.Data?(this._logger.Error(Ne.ServiceName,"Cannot get pictures - controler responded with OK, but no data in result.}."),new De(ce.UnknownError,"NoDataInResult")):t.Data.map((e=>{const t=new Ee;return t.Base64Image=e.Base64Image,t.DateTime=e.DateTime,t.Guid=e.Guid,t.ImageType=e.ImageType,-1!=e.OwnerGuid.indexOf("_")?(t.OwnerGuid=e.OwnerGuid.substring(0,e.OwnerGuid.indexOf("_")),t.OwnerIdentity=e.OwnerGuid.substring(e.OwnerGuid.indexOf("_")+1)):e.Guid.includes("profilePicture")?(t.OwnerIdentity=e.Guid.substring(e.Guid.indexOf("_")+1),t.OwnerGuid=e.OwnerGuid):e.Guid.includes("devices_group")?(t.OwnerIdentity=e.Guid.substring(0,e.Guid.lastIndexOf("_")),t.OwnerGuid=e.OwnerGuid):(t.OwnerGuid=e.OwnerGuid,t.OwnerIdentity=""),t}))}catch(e){return this._logger.Error(Ne.ServiceName,`Cannot get pictures! ${e}`),new De(ce.FatalError,"ExceptionOccurred")}}))}}Ne.ServiceName="PictureService";class Ee extends ke{set DateTime(e){this._dateTime=e}}class Ie{constructor(){this.Guid="",this.OwnerGuid="",this.Base64Image="",this.ImageType=ye.Device,this.DateTime=""}}class Re{constructor(){this._guid="",this._dateTime="",this._ownerGuid="",this._ownerIdentity=""}get Guid(){return this._guid}get DateTime(){return this._dateTime}get OwnerGuid(){return this._ownerGuid}get OwnerIdentity(){return this._ownerIdentity}set Guid(e){this._guid=e}set DateTime(e){this._dateTime=e}set OwnerGuid(e){this._ownerGuid=e}set OwnerIdentity(e){this._ownerIdentity=e}}class Pe extends ae{constructor(e){super(),this.Resource="/pictures/picture",this.Method=ue.Get,this.Data=e}}class Oe extends ae{constructor(){super(),this.Resource="/pictures/info",this.Method=ue.Get}}class Ue extends ae{constructor(){super(),this.Resource="/pictures/list",this.Method=ue.Get}}class Me extends ae{constructor(e){super(),this.Resource="/pictures/picture",this.Method=ue.Put,this.Data=e}}class xe extends ae{constructor(e){super(),this.Resource="/pictures/picture",this.Method=ue.Delete,this.Data=e}}var Fe=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class Le{constructor(){this._connection=null,this._connection=Ov.Get(Pt.ServiceName),this._pictureService=Ov.Get(Ne.ServiceName),this._sessionService=Ov.Get(Ke.ServiceName)}CanEditUser(e){const t=this._sessionService.User;return e.Guid===(null==t?void 0:t.Guid)||this.CanEditUsersOfAccessLevel(e.AccessLevel)}CanEditUsersOfAccessLevel(e){var t;const n=null===(t=this._sessionService.User)||void 0===t?void 0:t.AccessLevel;if(void 0===n)return!1;switch(e){case ge.Support:return n===ge.Support;case ge.Installator:return n>=ge.Installator;case ge.Admin:default:return n>=ge.Admin}}GetServiceName(){return Le.ServiceName}GetUsersAsync(){return Fe(this,void 0,void 0,(function*(){var e,t;const n=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new qe,2e4,!1);if(null==n)return Promise.resolve([]);if((null==n?void 0:n.Status)==ce.OK){if(null!=n.Data){const e=[];return n.Data.forEach((t=>{var n=new He;n.AccessLevel=t.AccessLevel,n.Email=t.Email,n.Gender=t.Gender,n.Guid=t.Guid,n.IsAccountOnline=t.IsAccountOnline,n.Name=t.Name,n.IsActive=t.IsActive,n.IsBanned=t.IsBanned,n.Phone=t.Phone,n.Surname=t.Surname,e.push(n)})),e}return Promise.resolve([])}if((null==n?void 0:n.Status)==ce.NoData)return Promise.resolve([]);throw null===(t=r.Log)||void 0===t||t.Debug(Le.ServiceName,`Failed to retrieve users, error: ${n.Status}`),new Error(`Failed to retrieve users, error: ${n.Status}`)}))}GetUserAsync(e){return Fe(this,void 0,void 0,(function*(){var t,n;if(""===e)return Promise.resolve(null);null==e&&(e="");const s=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Be(e),2e4,!1);if(null==s||null==s.Data)return Promise.resolve(null);if(s.Status!=ce.OK)return null===(n=r.Log)||void 0===n||n.Debug(Le.ServiceName,`Failed to retrieve user, error: ${s.Status}`),Promise.resolve(null);const o=new He;return o.AccessLevel=s.Data.AccessLevel,o.Email=s.Data.Email,o.Gender=s.Data.Gender,o.Guid=s.Data.Guid,o.IsAccountOnline=s.Data.IsAccountOnline,o.Name=s.Data.Name,o.IsActive=s.Data.IsActive,o.IsBanned=s.Data.IsBanned,o.Phone=s.Data.Phone,o.Surname=s.Data.Surname,o}))}CreateUserAsync(e,t){return Fe(this,void 0,void 0,(function*(){var n;if(null!=e.Guid&&""!=e.Guid)return new De(ce.WrongData,"GuidMustBeEmpty");const s=new We;s.Name=e.Name.trim(),s.Surname=e.Surname.trim(),s.Email=e.Email.trim(),s.Password=t.trim(),s.Phone=e.Phone.trim(),s.Gender=e.Gender,s.AccessLevel=e.AccessLevel;const r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new $e(s),2e4,!1);return Ov.Get(Ge.ServiceName).ClearCache(),null==r||null==r.Status?new De(ce.FatalError,"UnknownError"):(null==r.Data&&(r.Data=""),new De(r.Status,r.Data))}))}UpdateUserAsync(e){return Fe(this,void 0,void 0,(function*(){var t;if(null==e.Guid||""==e.Guid)return new De(ce.WrongData,"GuidCannotBeEmpty");const n=new We;n.Guid=e.Guid,n.Name=e.Name.trim(),n.Surname=e.Surname.trim(),n.Email=e.Email.trim(),n.Phone=e.Phone.trim(),n.Gender=e.Gender,n.AccessLevel=e.AccessLevel;const s=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new $e(n),2e4,!1);return Ov.Get(Ge.ServiceName).ClearCache(),null==s||null==s.Status?new De(ce.FatalError,"UnknownError"):(null==s.Data&&(s.Data=""),new De(s.Status,s.Data))}))}ChangePasswordAsync(e,t){return Fe(this,void 0,void 0,(function*(){var n;if(null==e.Guid||""==e.Guid)return new De(ce.WrongData,"GuidCannotBeEmpty");const s=yield this.GetUserAsync(e.Guid);if(null==s)return new De(ce.ResourceIsNotAvailable,"CannotGetUser");const r=new We;r.Guid=e.Guid,r.Password=t,r.AccessLevel=s.AccessLevel,r.Email=s.Email;const o=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new $e(r),2e4,!1);return null==o||null==o.Status?new De(ce.FatalError,"UnknownError"):(null==o.Data&&(o.Data=""),new De(o.Status,o.Data))}))}DeleteUserAsync(e){return Fe(this,void 0,void 0,(function*(){var t,n;if(""===e)return ce.WrongData;null==e&&(e="");const s=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Ve(e),2e4,!1);return Ov.Get(Ge.ServiceName).ClearCache(),null==s||null==s.Status?ce.FatalError:(s.Status!=ce.OK&&(null===(n=r.Log)||void 0===n||n.Debug(Le.ServiceName,`Failed to delete user, error: ${s.Status}`)),s.Status)}))}GetUserProfilePictureAsync(e){return Fe(this,void 0,void 0,(function*(){if(null==e.Guid||""==e.Guid)return new De(ce.WrongData,"GuidCannotBeEmpty");const t=yield this._pictureService.GetPicturesInfoAsync();if(null!=t.Type)return t;const n=t.find((t=>"profilePicture"==t.OwnerIdentity&&t.OwnerGuid==e.Guid));if(null!=n){const e=yield this._pictureService.GetPictureAsync(n.Guid);return Ov.Get(Ge.ServiceName).ClearCache(),null!=e.Type?t:e}return new De(ce.ResourceDoesNotExists,"PictureNotFound")}))}SetUserProfilePictureAsync(e,t){return Fe(this,void 0,void 0,(function*(){if(null==e.Guid||""==e.Guid)return new De(ce.WrongData,"GuidCannotBeEmpty");let n=new ke;n.ImageType=ye.Person,n.OwnerGuid=e.Guid,n.OwnerIdentity="profilePicture",n.Base64Image=t;const s=yield this.GetUserProfilePictureAsync(e);if(Ov.Get(Ge.ServiceName).ClearCache(),s.Type==ce.ResourceDoesNotExists){const e=yield this._pictureService.AddPictureAsync(n);return e===ce.OK?new De(ce.OK,"PictureSet"):new De(e,"PictureServiceError")}if(null!=s.Type)return new De(ce.Error,"ErrorWhenTryingToCheckIfCurrentProfilePictureExists");{n.Guid=s.Guid,n.OwnerGuid=s.OwnerGuid;const e=yield this._pictureService.EditPictureAsync(n);return e===ce.OK?new De(ce.OK,"PictureSet"):new De(e,"PictureServiceError")}}))}}Le.ServiceName="UsersService";class Be extends ae{constructor(e){super(),this.Resource="/users/user",this.Method=ue.Get,this.Data=e}}class We{constructor(){this.Guid="",this.Name="",this.Surname="",this.Email="",this.Password="",this.Phone="",this.Gender=pe.Unknown,this.AccessLevel=ge.Any}}class $e extends ae{constructor(e){super(),this.Resource="/users/user",this.Method=ue.Put,this.Data=e}}class qe extends ae{constructor(){super(),this.Resource="/users/list",this.Method=ue.Get}}class Ve extends ae{constructor(e){super(),this.Resource="/users/user",this.Method=ue.Delete,this.Data=e}}class He{constructor(){this._guid="",this._cloudGuid="",this._name="",this._surname="",this._phone="",this._email="",this._isAccountOnline=!0,this._isAccountActive=!0,this._isAccountBanned=!0,this._notificationChannels=[],this._gender=pe.Unknown,this._accessLevel=ge.Any,this._localization=fe.En_Us,this._softwareVersion=""}get Guid(){return this._guid}set Guid(e){this._guid=e}get CloudGuid(){return this._cloudGuid}set CloudGuid(e){this._cloudGuid=e}get Name(){return this._name}set Name(e){this._name=e}get Surname(){return this._surname}set Surname(e){this._surname=e}get Phone(){return this._phone}set Phone(e){this._phone=e}get AccessLevel(){return this._accessLevel}set AccessLevel(e){this._accessLevel=e}get Email(){return this._email}set Email(e){this._email=e}get IsAccountOnline(){return this._isAccountOnline}set IsAccountOnline(e){this._isAccountOnline=e}get IsActive(){return this._isAccountActive}set IsActive(e){this._isAccountActive=e}get IsBanned(){return this._isAccountBanned}set IsBanned(e){this._isAccountBanned=e}get NotificationChannels(){return this._notificationChannels}set NotificationChannels(e){this._notificationChannels=e}get Gender(){return this._gender}set Gender(e){this._gender=e}get Localization(){return this._localization}set Localization(e){this._localization=e}get SoftwareVersion(){return this._softwareVersion}set SoftwareVersion(e){this._softwareVersion=e}GetUserProfilePictureAsync(){return Ov.Get(Le.ServiceName).GetUserProfilePictureAsync({Guid:this._guid})}SetUserProfilePictureAsync(e){return Ov.Get(Le.ServiceName).SetUserProfilePictureAsync({Guid:this._guid},e)}}var je=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class Ke{constructor(){this._onUserLoggedInEvent=new n,this._onUserLoggedOutEvent=new n,this._email="",this._password="",this._authToken="",this._loginTaskCompletionSource=this.CreateSessionCompletionSourceAsync(),this._alreadySubsribedToNetworkEvents=!1,this._user=null}CreateSessionCompletionSourceAsync(){return je(this,void 0,void 0,(function*(){var e;null===(e=r.Log)||void 0===e||e.Debug(Ke.ServiceName,"Creating _loginTaskCompletionSource"),this._loginTaskCompletionSource=new Promise((e=>{let t=n=>{var s;null===(s=r.Log)||void 0===s||s.Debug(Ke.ServiceName,`Logged in as ${n.Name}, completing CreateSessionCompletionSourceAsync()`),e(),this.OnUserLoggedInEvent().Unsubscribe(t)};this.OnUserLoggedInEvent().Subscribe(t)}))}))}RestoreSessionAsync(){return je(this,void 0,void 0,(function*(){var e;null===(e=r.Log)||void 0===e||e.Debug(Ke.ServiceName,`Creating RestoreSessionAsync ${this._email} ${this._password}`),void 0!==this._user&&null!==this._user&&(yield this.UserLogInAsync(this._email,this._password))}))}WaitForSessionCreationAsync(){return je(this,void 0,void 0,(function*(){return this._loginTaskCompletionSource}))}OnUserLoggedInEvent(){return this._onUserLoggedInEvent}OnUserLoggedOutEvent(){return this._onUserLoggedOutEvent}get User(){return this._user}UserLogOutAsync(){return je(this,void 0,void 0,(function*(){var e,t,n=new ae;n.Resource="/users/user/logout",n.Method=ue.Put,this._email="",this._password="",(yield Ov.Get(Pt.ServiceName).SendAndWaitForResponseAsync(n,2e4,!1)).Status==ce.OK?(this._onUserLoggedOutEvent.Invoke(this._user),null===(e=r.Log)||void 0===e||e.Debug(Ke.ServiceName,"User has been logged out.")):null===(t=r.Log)||void 0===t||t.Debug(Ke.ServiceName,"Failed to logout user!")}))}OnConnectionStateChanged(e){return je(this,void 0,void 0,(function*(){switch(e){case he.Disconnected:case he.Failed:break;case he.Connected:Ov.Get(Ke.ServiceName).RestoreSessionAsync()}}))}AuthorizeAppAsync(e){return je(this,void 0,void 0,(function*(){var t,n,s,o,i=Ov.Get(Pt.ServiceName);const a=yield i.SendAndWaitForResponseAsync(new Je(e),2e4,!1);if(a.Status==ce.OK&&null!=a.Data){this._authToken=e;var c=new He;return this._user=c,c.AccessLevel=a.Data.AccessLevel,c.Email=a.Data.Email,this._email=a.Data.Email,c.Gender=a.Data.Gender,c.Guid=a.Data.Guid,c.IsAccountOnline=a.Data.IsAccountOnline,c.Name=a.Data.Name,c.IsActive=a.Data.IsActive,c.IsBanned=a.Data.IsBanned,c.Phone=a.Data.Phone,c.Surname=a.Data.Surname,c.SoftwareVersion=a.Data.SoftwareVersion,this._alreadySubsribedToNetworkEvents||(this._alreadySubsribedToNetworkEvents=!0,i.OnConnectionStateChangedEvent().Subscribe(this.OnConnectionStateChanged)),null===(t=r.Log)||void 0===t||t.Debug(Ke.ServiceName,`Did logging in succeded?: ${a.Status==ce.OK}`),this._onUserLoggedInEvent.Invoke(this._user),c}return a.Status===ce.OperationNotPermitted?(null===(n=r.Log)||void 0===n||n.Debug(Ke.ServiceName,`App login response: ${a.Data}`),ve.AuthDisabled):a.Status===ce.ResourceDoesNotExists?(null===(s=r.Log)||void 0===s||s.Debug(Ke.ServiceName,`App login response: ${a.Data}`),ve.MethodNotSupported):(null===(o=r.Log)||void 0===o||o.Debug(Ke.ServiceName,`App login response: ${a.Data}`),ve.WrongAuthData)}))}UserLogInAsync(e,t){return je(this,void 0,void 0,(function*(){var n,s,o=Ov.Get(Pt.ServiceName);const i=yield o.SendAndWaitForResponseAsync(new Ye(e,t),2e4,!1);if(i.Status==ce.OK&&null!=i.Data){this._email=e,this._password=t;var a=new He;return this._user=a,a.AccessLevel=i.Data.AccessLevel,a.Email=i.Data.Email,a.Gender=i.Data.Gender,a.Guid=i.Data.Guid,a.IsAccountOnline=i.Data.IsAccountOnline,a.Name=i.Data.Name,a.IsActive=i.Data.IsActive,a.IsBanned=i.Data.IsBanned,a.Phone=i.Data.Phone,a.Surname=i.Data.Surname,a.SoftwareVersion=i.Data.SoftwareVersion,this._alreadySubsribedToNetworkEvents||(this._alreadySubsribedToNetworkEvents=!0,o.OnConnectionStateChangedEvent().Subscribe(this.OnConnectionStateChanged)),null===(n=r.Log)||void 0===n||n.Debug(Ke.ServiceName,`Did logging in succeded?: ${i.Status==ce.OK}`),this._onUserLoggedInEvent.Invoke(this._user),a}return null===(s=r.Log)||void 0===s||s.Debug(Ke.ServiceName,`User login response: ${i.Data}`),ve.WrongAuthData}))}GetServiceName(){return Ke.ServiceName}}Ke.ServiceName="SessionService";class ze{constructor(e,t){this.Email="",this.Password="",this.Email=e,this.Password=t}}class Je extends ae{constructor(e){super(),this.Data=e,this.Resource="/applications/app/auth",this.Method=ue.Put}}class Ye extends ae{constructor(e,t){super(),this.Data=new ze(e,t),this.Resource="/users/user/login",this.Method=ue.Put}}class Xe{constructor(e){if(this.initialCount=e,this._running=0,this._waiting=[],this.Take=()=>{if(this._waiting.length>0&&this._running<this.initialCount){this._running++;const e=this._waiting.shift();null==e||e.Resolve({Release:this.Release})}},this.AcquireAsync=()=>this._running<this.initialCount?(this._running++,Promise.resolve({Release:this.Release})):new Promise(((e,t)=>{this._waiting.push({Resolve:e,Reject:t})})),this.Release=()=>{this._running--,this.Take()},this.Purge=()=>{this._waiting.forEach((e=>{e.Reject(new Error("The semaphore was purged and as a result this task has been cancelled"))})),this._running=0,this._waiting=[]},e<1)throw new Error(`The semaphore was created with a max value of ${e} but the max value cannot be less than 1`)}}var Qe=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class Ze{constructor(){this._extensionInfoCache=new Map,this._protocolInfoCache=new Map,this._isExtensionInfoInitialized=!1,this._semaphore=new Xe(1)}GetServiceName(){return Ze.ServiceName}GetExtensionsInfoAsync(e){return Qe(this,arguments,void 0,(function*(e,t=!1){Ov.Get(s.ServiceName).Debug(Ze.ServiceName,`Getting ExtensionsInfo, data loaded from cache: ${!t}`);var n=yield this._semaphore.AcquireAsync();if(this._isExtensionInfoInitialized&&!t||(yield this.GetExtensionInfoFromControllerAsync()),n.Release(),0==[...this._extensionInfoCache.values()].length)return[];if(null!=e){const t=this._extensionInfoCache.get(e);if(null==t)throw new nt("Cannot get ExtensionsInfo, extension not found.");return[t]}return[...this._extensionInfoCache.values()]}))}GetProtocolInfoAsync(e){return Qe(this,arguments,void 0,(function*(e,t=!1,n=!1){if(Ov.Get(s.ServiceName).Debug(Ze.ServiceName,`Getting ProtocolInfo, data loaded from cache: ${!t}`),t&&(yield this.GetProtocolExtensionInfoFromControllerAsync()),0!=[...this._protocolInfoCache.values()].length||n){if(0==[...this._protocolInfoCache.values()].length)throw new nt("Cannot get ProtocolInfo, controler may return empty list of Extensions or other unknown error occurs!")}else yield this.GetProtocolInfoAsync(e,!0,!0);if(null!=e){const t=this._protocolInfoCache.get(e);if(null==t)throw new nt("Cannot get ProtocolInfo, extension not found.");return[t]}return[...this._protocolInfoCache.values()]}))}GetExtensionInfoFromControllerAsync(){return Qe(this,void 0,void 0,(function*(){const e=new et,t=yield Ov.Get(Pt.ServiceName).SendAndWaitForResponseAsync(e,16e3,!1);if(null==t||null==t.Status)throw new nt("Cannot get ExtensionsInfo from controller, controller response does not contain data!");if(t.Status!=ce.OK)throw new nt(`Cannot get ExtensionsInfo from controller! Response status: ${t.Status}`);if(null==t.Data)throw new nt("Cannot get ExtensionsInfo from controller, controller response does not contain data!");t.Data.forEach((e=>{this._extensionInfoCache.set(e.ExtensionGuid,e)})),0!=[...this._extensionInfoCache.values()].length&&(this._isExtensionInfoInitialized=!0)}))}GetProtocolExtensionInfoFromControllerAsync(){return Qe(this,void 0,void 0,(function*(){const e=new tt,t=yield Ov.Get(Pt.ServiceName).SendAndWaitForResponseAsync(e,16e3,!1);if(null==t||null==t.Status)throw new nt("Cannot get ProtocolInfo from controller, controller response does not contain data!");switch(t.Status){case ce.OK:if(null==t.Data)throw new nt("Cannot get ProtocolInfo from controller, controller response does not contain data!");t.Data.forEach((e=>{this._protocolInfoCache.set(e.PublicGuid,e)}));break;case ce.ResourceDoesNotExists:Ov.Get(s.ServiceName).Debug(Ze.ServiceName,"Cannot get ProtocolInfo from controller, controller software does not implement this yet, update controller to the newest software!");break;default:throw new nt(`Cannot get ProtocolInfo from controller! Response status: ${t.Status}`)}}))}}Ze.ServiceName="StatisticsInfoService";class et extends ae{constructor(){super(),this.Resource="/controller/extensions/",this.Method=ue.Get}}class tt extends ae{constructor(){super(),this.Resource="/controller/protocols/",this.Method=ue.Get}}class nt extends Error{constructor(e){super(e),this.message=e,this.name="CannotGetExtensions"}}var st=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class rt{GetServiceName(){return rt.ServiceName}constructor(){this._connection=null,this._session=null,this._localStorage=null,this._onEnteredConfigurationEvent=new Ce,this._onExitedConfigurationEvent=new Ce,this._onConfigurationTimeCheckedEvent=new n,this._configurationTime=new Date,this._appEnteredConfigurationMode=!1,this._didConfigurationChange=!1,this._synchronizationTaskCompletionSource=new Promise((e=>{Ov.Get(Ke.ServiceName).OnUserLoggedInEvent().Subscribe((t=>st(this,void 0,void 0,(function*(){this._didConfigurationChange=yield this.CheckIfConfigurationHasChangedAsync(),this._didConfigurationChange&&Ov.Get(Ge.ServiceName).ClearCache(),e()}))))})),this._connection=Ov.Get(Pt.ServiceName),this._session=Ov.Get(Ke.ServiceName),this._localStorage=Ov.Get(o.ServiceName),this._connection.SubscribeTo("/info/configuration/mode/entry",(e=>{Ov.Get(Ge.ServiceName).ClearCache(),this._appEnteredConfigurationMode||this._onEnteredConfigurationEvent.Invoke()})),this._connection.SubscribeTo("/info/configuration/mode/exit",(e=>{Ov.Get(Ge.ServiceName).ClearCache(),this._appEnteredConfigurationMode||this._onExitedConfigurationEvent.Invoke()}))}ImportControllerConfigurationAsync(e){return st(this,void 0,void 0,(function*(){var t,n,s;let r=yield e.text(),o=this.SplitStringBySize(r),i=new ot("");i.Status=ce.MultiDataResponseStart;let a=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(i,6e3,!1);if(void 0===a||(null==a?void 0:a.Status)!=ce.OK)return ce.Error;for(const e of o){let t=new ot(e);t.Status=ce.MultiDataResponse;let s=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(t,6e3,!1);if(void 0===s||(null==s?void 0:s.Status)!=ce.OK)return ce.Error}i.Status=ce.MultiDataResponseStop;let c=yield null===(s=this._connection)||void 0===s?void 0:s.SendAndWaitForResponseAsync(i,12e4,!1);return void 0===c||(null==c?void 0:c.Status)!=ce.OK?ce.Error:ce.OK}))}SplitStringBySize(e,t=1e5){const n=Math.floor(t/2),s=[];let r=0;for(;r<e.length;){let o=e.slice(r,r+n);for(;new Blob([o]).size>t;)o=o.slice(0,-1);s.push(o),r+=o.length}return s}GetControllerSystemTimeAsync(){return st(this,void 0,void 0,(function*(){var e;try{var t=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new gt,8e3,!1);return null==t||null==t.Status?ce.Error:t.Status!=ce.OK?t.Status:null==t.Data?ce.ResourceIsNotAvailable:new Date(t.Data)}catch(e){return Ov.Get(s.ServiceName).Error(rt.ServiceName,`Cannot get current controller time! ${e}`),ce.FatalError}}))}SetControllerSystemTimeAsync(e){return st(this,void 0,void 0,(function*(){var t;try{var n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new pt(e.toISOString()),8e3,!1);return null==n||null==n.Status?ce.Error:n.Status}catch(e){return Ov.Get(s.ServiceName).Error(rt.ServiceName,`Cannot set current controller time! ${e}`),ce.FatalError}}))}StartNtpTimeSynchronizationAsync(){return st(this,void 0,void 0,(function*(){var e;try{var t=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new ft,8e3,!1);return null==t||null==t.Status?ce.Error:t.Status}catch(e){return Ov.Get(s.ServiceName).Error(rt.ServiceName,`Cannot set current controller time! ${e}`),ce.FatalError}}))}FactoryResetAsync(e){return st(this,void 0,void 0,(function*(){var t,n;try{Ov.Get(Ge.ServiceName).ClearCache();var s=null===(n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new ct,2e3,!1))||void 0===n?void 0:n.Status;if(s==ce.OK){let t=300,n=0,s=100/t,r=setInterval((()=>{n+=s,e(parseFloat(n.toPrecision(1)))}),1e3);return yield oe.Delay(1e3*t),Ov.Get(Ge.ServiceName).ClearCache(),clearInterval(r),ce.OK}return s}catch(e){return ce.FatalError}}))}RollbackLastUpdateAsync(e){return st(this,void 0,void 0,(function*(){var t,n;try{Ov.Get(Ge.ServiceName).ClearCache();var s=null===(n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new ut,2e3,!1))||void 0===n?void 0:n.Status;if(s==ce.OK){let t=420,n=0,s=100/t,r=setInterval((()=>{n+=s,e(parseFloat(n.toPrecision(1)))}),1e3);return yield oe.Delay(1e3*t),Ov.Get(Ge.ServiceName).ClearCache(),clearInterval(r),ce.OK}return s}catch(e){return ce.FatalError}}))}RestartControllerAsync(e){return st(this,void 0,void 0,(function*(){var t,n;try{Ov.Get(Ge.ServiceName).ClearCache();var s=null===(n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new at,2e3,!1))||void 0===n?void 0:n.Status;if(s==ce.OK){let t=240,n=0,s=100/t,r=setInterval((()=>{n+=s,e(parseFloat(n.toPrecision(1)))}),1e3);return yield oe.Delay(1e3*t),Ov.Get(Ge.ServiceName).ClearCache(),clearInterval(r),ce.OK}return s}catch(e){return ce.FatalError}}))}DidCofigurationChangeAsync(){return st(this,void 0,void 0,(function*(){return yield this._synchronizationTaskCompletionSource,Promise.resolve(this._didConfigurationChange)}))}GetLastKnownConfigurationChangeTime(){var e;const t=null===(e=this._localStorage)||void 0===e?void 0:e.Read(this.GetServiceName(),"last_configuration_time");return null!=t?new Date(t):new Date}SaveLastConfigurationChangeTime(e){var t;null===(t=this._localStorage)||void 0===t||t.Save(this.GetServiceName(),"last_configuration_time",e.toString())}EnterConfigurationModeAsync(){return st(this,void 0,void 0,(function*(){var e;this._appEnteredConfigurationMode=!0,Ov.Get(Ge.ServiceName).ClearCache(),yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new lt,2e4,!1)}))}ExitConfigurationModeAsync(){return st(this,void 0,void 0,(function*(){var e;this._appEnteredConfigurationMode=!0,Ov.Get(Ge.ServiceName).ClearCache(),yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new dt,2e4,!1),Ov.Get(Ge.ServiceName).ClearCache(),this._appEnteredConfigurationMode=!1}))}OnEnteredConfigurationEvent(){return this._onEnteredConfigurationEvent}OnExitedConfigurationEvent(){return this._onExitedConfigurationEvent}OnConfigurationTimeCheckedEvent(){return this._onConfigurationTimeCheckedEvent}GetLastConfigurationChangeTimeAsync(){return st(this,void 0,void 0,(function*(){var e;const t=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new ht,2e4,!1);if(null==t||(null==t?void 0:t.Status)!=ce.OK)throw new Error("Failed to get last configuration change time");return this._configurationTime=new Date(t.Data),this._configurationTime}))}CheckIfConfigurationHasChangedAsync(){return st(this,void 0,void 0,(function*(){const e=yield this.GetLastConfigurationChangeTimeAsync();return this.GetLastKnownConfigurationChangeTime().toString()!=e.toString()&&(this.SaveLastConfigurationChangeTime(e),this._onConfigurationTimeCheckedEvent.Invoke(e),Ov.Get(Ge.ServiceName).ClearCache(),!0)}))}CanExportOrImportControllerConfigurationAsync(){return st(this,void 0,void 0,(function*(){try{let e=yield Ov.Get(Ze.ServiceName).GetExtensionsInfoAsync(),t=Ov.Get(Ke.ServiceName).User;return null!=t&&null!=t.AccessLevel&&t.AccessLevel>=ge.Admin&&e.any((e=>"f4f0f066-7c43-46c6-a0bd-aedf93903dc0"==e.ExtensionGuid))}catch(e){return!1}}))}ExportControllerConfigurationAsync(){return st(this,void 0,void 0,(function*(){var e;let t=[];yield null===(e=this._connection)||void 0===e?void 0:e.SendAndHandleResponseAsync(new it,3e4,(e=>{switch(e.Status){case ce.MultiDataResponseStart:break;case ce.MultiDataResponse:null!=e.Data&&void 0!==e.Data&&t.push(e.Data);case ce.MultiDataResponseStop:}}),!0);let n=JSON.stringify(JSON.parse(t.join("")),null,2);return console.log(n),Ov.ExportStringAsFileToDownload(this.GetCurrentTimestampedFilename(),n)}))}GetCurrentTimestampedFilename(){var e,t;const n=new Date,s=n.getHours().toString().padStart(2,"0"),r=n.getMinutes().toString().padStart(2,"0"),o=n.getDate().toString().padStart(2,"0"),i=(n.getMonth()+1).toString().padStart(2,"0"),a=n.getFullYear().toString();return`${null===(t=null===(e=this._connection)||void 0===e?void 0:e.GetAuthorizationInfo())||void 0===t?void 0:t.SerialNumber}_${s}-${r}-${o}-${i}-${a}-config.cexp`}}rt.ServiceName="ControllerConfigurationService";class ot extends ae{constructor(e){super(),this.Resource="/configuration/backup/import",this.Method=ue.Put,this.Data=e}}class it extends ae{constructor(){super(),this.Resource="/configuration/backup/export",this.Method=ue.Get}}class at extends ae{constructor(){super(),this.Resource="/controller/restart",this.Method=ue.Post}}class ct extends ae{constructor(){super(),this.Resource="/controller/factory_reset",this.Method=ue.Post}}class ut extends ae{constructor(){super(),this.Resource="/controller/backups/restore/previous",this.Method=ue.Post}}class lt extends ae{constructor(){super(),this.Resource="/system/configuration/mode/entry",this.Method=ue.Put}}class dt extends ae{constructor(){super(),this.Resource="/system/configuration/mode/exit",this.Method=ue.Put}}class ht extends ae{constructor(){super(),this.Resource="/system/configuration/change/time",this.Method=ue.Get}}class gt extends ae{constructor(){super(),this.Resource="/system/time",this.Method=ue.Get}}class pt extends ae{constructor(e){super(),this.Resource="/system/time",this.Method=ue.Put,this.Data=e}}class ft extends ae{constructor(){super(),this.Resource="/system/time/ntp/update",this.Method=ue.Put}}var vt,mt,yt,wt,St,At,_t,Ct,Tt,Dt,kt,Gt,bt,Nt,Et,It,Rt=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class Pt{constructor(){this._logPackets=!1,this._pingInterval=5e3,this._disconnectedOnPurpose=!1,this._defaultPacketsBrokerAddress="br1.tr7.pl",this._serversBrokerAddress="https://broker.tr7.pl",this._serversBrokerAddressList=["https://broker.tr7.pl","https://dev-brokers.lavva.tech"],this._allBrokersChecked=!1,this._address="br1.tr7.pl",this._isEstabilished=!1,this._timeout=1e4,this._dataReceivedEvent=new n,this._pongReceivedEvent=new Ce,this._authorizationReceivedEvent=new n,this._registrationReceivedEvent=new n,this._connectionStateChangedEvent=new n,this._errorOccuredEvent=new n,this._log=Ov.Get(s.ServiceName),this._controllerConfiguration=null,this._cache=null,this._session=null,this._packetsBrokerServers=["br1.tr7.pl","br1.exala.pl"],this._lastReceivedPacketTime=Date.now(),this._connectedAtLeastOnce=!1}SubscribeTo(e,t){let n=n=>{n.Resource===e&&t(n)};return this.OnDataReceivedEvent().Subscribe(n),()=>this.OnDataReceivedEvent().Unsubscribe(n)}GetControllerSerialNumber(){return this._serialId}GetControllerPin(){return this._PIN}GetServiceName(){return Pt.ServiceName}EnablePacketsLogging(){this._logPackets=!0}DisablePacketsLogging(){this._logPackets=!1}InitializeConnection(){if(this._controllerConfiguration=Ov.Get(rt.ServiceName),this._cache=Ov.Get(Ge.ServiceName),this._session=Ov.Get(Ke.ServiceName),this._connection){try{this._connection.stop()}catch(e){}this._connection=void 0}if(!this._address)throw new Error("Domain is not set");if(!this._serialId)throw new Error("SerialId is not set");if(!this._PIN)throw new Error("PIN is not set");this._connection=(new se).withUrl(`https://${this._address}/broker`).build(),this._dataReceivedEvent.Subscribe((e=>{this._lastReceivedPacketTime=Date.now()})),setInterval((()=>Rt(this,void 0,void 0,(function*(){yield this.PingControllerAsync()}))),this._pingInterval)}GetAuthorizationInfo(){return null!=this._serialId&&null!=this._PIN?new _e(this._serialId,this._PIN):null}SetServersBrokerAddress(e){this._serversBrokerAddress=e}SetDefaultPacketsBrokerAddress(e){this._defaultPacketsBrokerAddress=e,this._address=e}GetServerAddressAsync(){return Rt(this,void 0,void 0,(function*(){try{let e=yield fetch(`${this._serversBrokerAddress}/api/connections/broker/whichserver/${this._serialId}`);if(200===e.status){let t=yield e.text();return t?(this._log.Debug(Pt.ServiceName,`Got server address: ${t}`),t):(this._log.Error(Pt.ServiceName,`Failed to get server address, status: ${e.status}`),null)}return this._allBrokersChecked?(this._allBrokersChecked=!1,null):204===e.status?(this.swapBrokersAsync(!1),this.GetServerAddressAsync()):(this._log.Error(Pt.ServiceName,`Failed to get server address, status: ${e.status}`),null)}catch(e){return this._log.Error(Pt.ServiceName,e),null}}))}ConnectAsync(e){return Rt(this,void 0,void 0,(function*(){return this._connectedAtLeastOnce=!1,this._address=e,yield this.connectAsync()}))}AuthorizeAsync(e){return new Promise(((t,n)=>Rt(this,void 0,void 0,(function*(){var n;let s=0,r=e=>{window.clearTimeout(s),this._log.Debug(Pt.ServiceName,`Got authorization result: ${e}`),this._connectedAtLeastOnce=!0,t(e)};s=window.setTimeout((()=>{window.clearTimeout(s),this._authorizationReceivedEvent.Unsubscribe(r),t(!1)}),2e3),this._log.Debug(Pt.ServiceName,`Authorizing to cloud using: ${e.SerialNumber} PIN: ${e.PIN}`),this._authorizationReceivedEvent.Subscribe(r),yield null===(n=this._connection)||void 0===n?void 0:n.send("AuthorizeTo",e.SerialNumber,e.PIN)}))))}ConnectAndAuthorizeAsync(e){return Rt(this,void 0,void 0,(function*(){this._connectedAtLeastOnce=!1,Ov.WorksInContextOf=e.SerialNumber,this._serialId=e.SerialNumber,this._PIN=e.PIN;var t=yield this.GetServerAddressAsync();if(t&&null!=t){this._log.Debug(Pt.ServiceName,`Got packets broker address: ${t}`),this.SetDefaultPacketsBrokerAddress(t);let s=yield this.connectAsync();if(s!=de.Connected)return s;var n=yield this.AuthorizeAsync(e);if(!n){if(this._connectedAtLeastOnce=!1,yield this.swapBrokersAsync(),!this._allBrokersChecked)return this.ConnectAndAuthorizeAsync(e);this._allBrokersChecked=!1}return n&&(this._connectedAtLeastOnce=!0),n?de.Connected:de.AuthorizationFailed}{let t=de.ControllerIsNotConnected;this._log.Warning(Pt.ServiceName,"Server did not return packets broker address, trying to connect to known brokers.");for(let n of this._packetsBrokerServers){this._log.Warning(Pt.ServiceName,`Testing connection to ${n}`),this.SetDefaultPacketsBrokerAddress(n);try{yield this.DisconnectAsync()}catch(e){}this._log.Warning(Pt.ServiceName,`Connecting to server: ${n}`);let s=yield this.connectAsync();if(this._log.Warning(Pt.ServiceName,`Connection result: ${s}`),s==de.Connected){if(yield this.AuthorizeAsync(e))return t=de.Connected,this._connectedAtLeastOnce=!0,t;this._log.Warning(Pt.ServiceName,`Failed to authorize in ${n}`)}}return t}}))}swapBrokersAsync(){return Rt(this,arguments,void 0,(function*(e=!0){e&&(yield this.DisconnectAsync());var t=this._serversBrokerAddressList.lastIndexOf(this._serversBrokerAddress);t+1<this._serversBrokerAddressList.length?(this._serversBrokerAddress=this._serversBrokerAddressList[t+1],this._log.Debug(`Changing address of next broker from: ${this._serversBrokerAddressList[t]} to: ${this._serversBrokerAddressList[t+1]}`)):(this._log.Debug(`All brokers checked, changing address to first one: ${this._serversBrokerAddressList[0]}`),this._allBrokersChecked=!0,this._serversBrokerAddress=this._serversBrokerAddressList[0])}))}connectAsync(){return Rt(this,void 0,void 0,(function*(){var e,t,n,s,r,o,i,a,c;if(de.FailedToConnect,!this._address)return Promise.resolve(de.ControllerIsNotConnected);this._disconnectedOnPurpose&&(this._disconnectedOnPurpose=!1),this._connectionStateChangedEvent,this.InitializeConnection(),null===(e=this._connection)||void 0===e||e.onclose((()=>Rt(this,void 0,void 0,(function*(){var e,t;if(this._disconnectedOnPurpose?this._log.Info(Pt.ServiceName,"Connection closed on demand."):this._log.Error(Pt.ServiceName,"Connection closed"),Ov.Get(Ke.ServiceName).CreateSessionCompletionSourceAsync(),this.FireConnectionStateChanged(),(null===(e=this._connection)||void 0===e?void 0:e.state)===T.Disconnected&&!this._disconnectedOnPurpose)return yield null===(t=this._connection)||void 0===t?void 0:t.start(),null!=this._connection&&(yield this.AuthorizeAsync(new _e(this._serialId,this._PIN)))?(this._log.Info(Pt.ServiceName,"Reconnected from onClose"),this.FireConnectionStateChanged()):de.FailedToConnect})))),null===(t=this._connection)||void 0===t||t.onreconnected((()=>Rt(this,void 0,void 0,(function*(){if(yield this.AuthorizeAsync(new _e(this._serialId,this._PIN)))return this._log.Info(Pt.ServiceName,"Reconnected from onreconnected"),this.FireConnectionStateChanged()})))),null===(n=this._connection)||void 0===n||n.onreconnecting((()=>(this._log.Warning(Pt.ServiceName,"Reconnecting..."),this.FireConnectionStateChanged()))),yield null===(s=this._connection)||void 0===s?void 0:s.start(),null===(r=this._connection)||void 0===r||r.on("Pong",(()=>{this._log.Debug(Pt.ServiceName,"Pong received <-"),this._pongReceivedEvent.Invoke()})),null===(o=this._connection)||void 0===o||o.on("Registration",(e=>{var t;null===(t=this._registrationReceivedEvent)||void 0===t||t.Invoke(e)})),null===(i=this._connection)||void 0===i||i.on("Authorization",(e=>{var t;null===(t=this._authorizationReceivedEvent)||void 0===t||t.Invoke(e)})),null===(a=this._connection)||void 0===a||a.on("SendError",((e,t)=>Rt(this,void 0,void 0,(function*(){e.startsWith("NotAuthorized:")?(this._log.Error(Pt.ServiceName,"Failed to authorize!"),yield this.AuthorizeAsync(new _e(this._serialId,this._PIN))):(this._log.Error(Pt.ServiceName,`Server returned error: ${e} ${t}`),this._errorOccuredEvent.Invoke([e,t]))}))));let u=this._dataReceivedEvent;return null===(c=this._connection)||void 0===c||c.on("Data",((e,t)=>{const n=JSON.parse(t);(this._logPackets||!0===window.packets)&&this._log.Debug(Pt.ServiceName,`Received data:\n${JSON.stringify(n,null,2)}`),u.Invoke(n)})),null!=this._connection?this.FireConnectionStateChanged():de.FailedToConnect}))}FireConnectionStateChanged(){var e;const t=this._connectionStateChangedEvent;switch(null===(e=this._connection)||void 0===e?void 0:e.state){case T.Connected:return t.Invoke(he.Connected),de.Connected;case T.Connecting:return t.Invoke(he.Connecting),de.Connected;case T.Disconnected:if(this._connectedAtLeastOnce)return t.Invoke(he.Disconnected),de.FailedToConnect;break;case T.Disconnecting:if(this._connectedAtLeastOnce)return t.Invoke(he.Disconnecting),de.FailedToConnect;break;case T.Reconnecting:return t.Invoke(he.Reconnecting),de.FailedToConnect}return de.FailedToConnect}DisconnectAsync(){return Rt(this,void 0,void 0,(function*(){var e;this._disconnectedOnPurpose=!0,yield null===(e=this._connection)||void 0===e?void 0:e.stop()}))}IsConnected(){var e;return(null===(e=this._connection)||void 0===e?void 0:e.state)===T.Connected}SendAndWaitForResponseAsync(e,t,n,s=!0){return this.SendAndWaitForResponseWithRepeatAsync(e,t,n,s)}SendAndWaitForResponseWithRepeatAsync(e,t,n){return Rt(this,arguments,void 0,(function*(e,t,n,s=!0,r=!0){var o,i,a;if(e.Method===ue.Get&&n&&!(yield null===(o=this._controllerConfiguration)||void 0===o?void 0:o.DidCofigurationChangeAsync())){let t=null===(i=this._cache)||void 0===i?void 0:i.GetCache(e);if(null!==t)return Promise.resolve(t)}let c=0;const u=Date.now();if(!this.IsConnected())throw new Error("Connection is not established");return"/users/user/login"!==e.Resource&&(yield null===(a=this._session)||void 0===a?void 0:a.WaitForSessionCreationAsync()),new Promise(((o,i)=>Rt(this,void 0,void 0,(function*(){let a=i=>Rt(this,void 0,void 0,(function*(){var l,d,h,g;if((null==i?void 0:i.TransactionId)==e.TransactionId){window.clearTimeout(c),this._dataReceivedEvent.Unsubscribe(a);const p=Date.now()-u;r&&this._log.Debug(Pt.ServiceName,`Received response for: ${null==i?void 0:i.Resource} ${null==i?void 0:i.Method} id: ${null==i?void 0:i.TransactionId} in ${p}ms`),e.Method===ue.Get&&n&&(null===(l=this._cache)||void 0===l||l.Cache(i)),!n&&(null==i?void 0:i.Status)===ce.UserIsNotLoggedIn&&s&&((null===(d=this._session)||void 0===d?void 0:d.OnUserLoggedOutEvent()).Invoke(null===(h=this._session)||void 0===h?void 0:h.User),yield null===(g=this._session)||void 0===g?void 0:g.RestoreSessionAsync(),o(yield this.SendAndWaitForResponseWithRepeatAsync(e,t,n,!1,r))),o(i)}}));if(this._dataReceivedEvent.Subscribe(a),c=window.setTimeout((()=>{this._dataReceivedEvent.Unsubscribe(a);let t=`Response timeout, resource: ${e.Resource} method: ${e.Method} transaction id: ${e.TransactionId}`;this._log.Error(Pt.ServiceName,t),i(new g(t))}),t),!(yield this.SendAsync(e,r))){let t=`Failed to send request, resource: ${e.Resource} method: ${e.Method} transaction id: ${e.TransactionId}`;i(new Error(t))}}))))}))}SendAndHandleResponseAsync(e,t,n){return Rt(this,arguments,void 0,(function*(e,t,n,s=!0){var r;let o=0;const i=Date.now();if(!this.IsConnected())throw new Error("Connection is not established");return"/users/user/login"!==e.Resource&&(yield null===(r=this._session)||void 0===r?void 0:r.WaitForSessionCreationAsync()),new Promise(((r,a)=>Rt(this,void 0,void 0,(function*(){const c=()=>window.setTimeout((()=>{this._dataReceivedEvent.Unsubscribe(u);let t=`Response timeout, resource: ${e.Resource} method: ${e.Method} transaction id: ${e.TransactionId}`;this._log.Error(Pt.ServiceName,t),a(new g(t))}),t);let u=l=>Rt(this,void 0,void 0,(function*(){var d,h,g;if((null==l?void 0:l.TransactionId)==e.TransactionId){window.clearTimeout(o);const p=Date.now()-i;switch((s||!0===window.packets)&&this._log.Debug(Pt.ServiceName,`Received response for: ${null==l?void 0:l.Resource} ${null==l?void 0:l.Method} id: ${null==l?void 0:l.TransactionId} in ${p}ms`),(null==l?void 0:l.Status)===ce.UserIsNotLoggedIn&&(this._dataReceivedEvent.Unsubscribe(u),(null===(d=this._session)||void 0===d?void 0:d.OnUserLoggedOutEvent()).Invoke(null===(h=this._session)||void 0===h?void 0:h.User),yield null===(g=this._session)||void 0===g?void 0:g.RestoreSessionAsync(),r(yield this.SendAndHandleResponseAsync(e,t,n,s))),null==l?void 0:l.Status){case ce.MultiDataResponseStart:case ce.MultiDataResponse:n(l),o=c();break;case ce.MultiDataResponseStop:n(l),this._dataReceivedEvent.Unsubscribe(u),r();break;default:let t=`Failed to process MultiDataResponse - recived incorrect response status: ${null==l?void 0:l.Status} method: ${e.Method} transaction id: ${e.TransactionId}\n make sure that the requested endpoint uses MultiDataResponse, otherwise use SendAndWaitForResponseAsync<T> method.`;a(new Error(t))}}}));if(this._dataReceivedEvent.Subscribe(u),o=c(),!(yield this.SendAsync(e,s))){let t=`Failed to send request, resource: ${e.Resource} method: ${e.Method} transaction id: ${e.TransactionId}`;a(new Error(t))}}))))}))}PingControllerAsync(){return Rt(this,void 0,void 0,(function*(){var e;if((null===(e=this._connection)||void 0===e?void 0:e.state)!==T.Connected)return!1;if(null!==this._lastReceivedPacketTime&&Date.now()-this._lastReceivedPacketTime<this._pingInterval)return!1;let t=new ae;return t.Resource="/system/ping",t.Method=ue.Get,yield this.SendAndWaitForResponseAsync(t,2e3,!1,!1).then((()=>!0)).catch((()=>!1))}))}SendAsync(e,t=!1){if(!this.IsConnected())throw new Error("Connection is not established");return new Promise((n=>{var s;this._logPackets||!0===window.packets?this._log.Debug(Pt.ServiceName,`Sent DataFrame ${e.Resource} ${e.Method} transaction id: ${e.TransactionId} data:\n${JSON.stringify(e,null,2)}`):t&&this._log.Debug(Pt.ServiceName,`Sent DataFrame ${e.Resource} ${e.Method} transaction id: ${e.TransactionId}`),null===(s=this._connection)||void 0===s||s.invoke("SendTo",this._serialId,e).then((()=>{n(!0)})).catch((e=>{this._log.Error(Pt.ServiceName,`${e}`),n(!1)}))}))}OnDataReceivedEvent(){return this._dataReceivedEvent}OnConnectionStateChangedEvent(){return this._connectionStateChangedEvent}OnErrorOccuredEvent(){return this._errorOccuredEvent}}Pt.ServiceName="ExalusConnectionService",function(e){e[e.NoTasksExecuting=0]="NoTasksExecuting",e[e.ExecutingTasks=1]="ExecutingTasks"}(vt||(vt={})),(Gt=mt||(mt={}))[Gt.Default=0]="Default",Gt[Gt.Monostable=1]="Monostable",Gt[Gt.Bistable=2]="Bistable",Gt[Gt.Gate=3]="Gate",Gt[Gt.Gateway=4]="Gateway",function(e){e[e.None=0]="None",e[e.OnOff=1]="OnOff",e[e.OnOffLights=2]="OnOffLights",e[e.OnOffWithDelay=3]="OnOffWithDelay",e[e.GateSwitchState=4]="GateSwitchState",e[e.GatePulse=5]="GatePulse",e[e.GateOpenClose=6]="GateOpenClose",e[e.GatewayOpenClose=7]="GatewayOpenClose",e[e.GatewayPulse=8]="GatewayPulse",e[e.Monostable=9]="Monostable",e[e.Dimmer=10]="Dimmer",e[e.Blind=11]="Blind",e[e.Roller=12]="Roller",e[e.TemperatureSensor=13]="TemperatureSensor",e[e.BrightnessSensor=14]="BrightnessSensor",e[e.HumiditySensor=15]="HumiditySensor",e[e.PowerMeter=16]="PowerMeter",e[e.RGBLight=17]="RGBLight",e[e.RGBWLight=18]="RGBWLight",e[e.LightsWarmth=19]="LightsWarmth",e[e.TemperatureControl=20]="TemperatureControl",e[e.BlindsWithPrecisePosition=21]="BlindsWithPrecisePosition",e[e.MovementSensor=21]="MovementSensor",e[e.SimpleRemote=22]="SimpleRemote",e[e.BlindsRemote=23]="BlindsRemote",e[e.DistanceSensor=24]="DistanceSensor",e[e.Multisensor=25]="Multisensor",e[e.IOTransmitter=26]="IOTransmitter",e[e.DoorOpenClose=27]="DoorOpenClose",e[e.WindSensor=28]="WindSensor",e[e.BatterySensor=29]="BatterySensor",e[e.PressureSensor=30]="PressureSensor"}(yt||(yt={}));class Ot{constructor(){this._type=St.Unknown,this._interfaceType=""}get Type(){return this._type}get InterfaceType(){return this._interfaceType}set InterfaceType(e){this._interfaceType=e,this._type=e}}(bt=wt||(wt={}))[bt.Unknown=0]="Unknown",bt[bt.BlindMotor=1]="BlindMotor",bt[bt.DinModule=2]="DinModule",bt[bt.DinModuleWithAntenna=3]="DinModuleWithAntenna",bt[bt.Remote=4]="Remote",bt[bt.RemoteForBlinds=5]="RemoteForBlinds",bt[bt.RemoteForFacadeBlinds=6]="RemoteForFacadeBlinds",bt[bt.MovementSensor=7]="MovementSensor",bt[bt.TemperatureSensor=8]="TemperatureSensor",bt[bt.HumiditySensor=9]="HumiditySensor",bt[bt.DinPowerMeter=10]="DinPowerMeter",bt[bt.Intercom=11]="Intercom",bt[bt.SecurityCamera=12]="SecurityCamera",bt[bt.Multisensor=13]="Multisensor",bt[bt.FloodSensor=14]="FloodSensor",bt[bt.FlushMountedReceiver=15]="FlushMountedReceiver",bt[bt.FlushMountedBlindController=16]="FlushMountedBlindController",bt[bt.FlushMountedDimmer=17]="FlushMountedDimmer",bt[bt.FlushMountedRelay=18]="FlushMountedRelay",bt[bt.FlushMountedGateController=19]="FlushMountedGateController",bt[bt.WindSensor=20]="WindSensor",bt[bt.FlushMountedGateAndGatewayController=21]="FlushMountedGateAndGatewayController",bt[bt.AirPressureSensor=22]="AirPressureSensor",bt[bt.LightBrightnessSensor=23]="LightBrightnessSensor",bt[bt.ReedSensor=24]="ReedSensor",bt[bt.FlushMountedTransceiver=25]="FlushMountedTransceiver",bt[bt.FlushMountedRGBLightController=26]="FlushMountedRGBLightController",bt[bt.WallMountedThermoregulator=27]="WallMountedThermoregulator",bt[bt.ImpulseCounter=28]="ImpulseCounter",bt[bt.FlushMountedFacadeController=29]="FlushMountedFacadeController",bt[bt.WallMountedGateController=30]="WallMountedGateController",bt[bt.WallMountedRGBLightController=31]="WallMountedRGBLightController",bt[bt.WallMountedDimmer=32]="WallMountedDimmer",bt[bt.WallMountedRemote=33]="WallMountedRemote",bt[bt.DinRelay=34]="DinRelay",bt[bt.DinReceiver=35]="DinReceiver",bt[bt.DinBlindController=36]="DinBlindController",bt[bt.DinTransceiver=37]="DinTransceiver",bt[bt.SocketPlugIn=38]="SocketPlugIn",bt[bt.WallMountedRelay=39]="WallMountedRelay",bt[bt.Retransmitter=40]="Retransmitter",function(e){e.Unknown="Unknown",e.SetBlindPosition="IBlindPosition",e.SetBlindPositionSimple="IBlindPositionSimple",e.SetBlindMicroventilation="IMicroventilation",e.TurnOff="IChannelOff",e.TurnOn="IChannelOn",e.TurnOnWithTime="IChannelOnWithTime",e.TogleState="IChannelSwitchState",e.SetLightBrightnessDynamicly="IDynamicLightBrightness",e.SetLightBrightness="ILightBrightness",e.SetLightColor="ILightColor",e.SetLightTemperature="ILightTemperature",e.PairDevice="IPair",e.UnpairDevice="IUnpair",e.IdentifyDevice="IIdentifyDevice",e.GetChannelsState="IGetDeviceState",e.GetPowerMeasurements="IGetPowerMeasurements",e.GetAvailableData="IGetAvailableData",e.MultipleDataRequest="IMultipleDataRequest",e.SetBlindOpenCloseTime="ISetBlindOpenCloseTime",e.SetTemperature="IChangeTemperature",e.SetGatePosition="IGatePosition",e.SetGatewayPosition="IGatewayPosition",e.ChangeGatePositionPulse="IGatePulse",e.ChangeGatewayPositionPulse="IGatewayPulse",e.SetFacadePosition="IFacadePosition",e.GetFacadeType="IGetFacadeType",e.LightRGBW="ILightRGBW",e.PreciseGateControl="IPreciseGateControl"}(St||(St={}));class Ut{constructor(){this._type=At.Unknown,this._interfaceType=""}get Type(){return this._type}get InterfaceType(){return this._interfaceType}set InterfaceType(e){this._interfaceType=e,this._type=e}}!function(e){e.Unknown="Unknown",e.BatteryState="IBatteryState",e.BinarySensorState="IBinarySensor",e.BlindOpenCloseTime="IBlindOpenCloseTime",e.BlindPosition="IBlindPosition",e.BlindRemoteButtonState="IBlindsControlButton",e.BlindErrorState="IBlindError",e.MeasuredBrightness="IBrightness",e.RemoteButtonState="IButtonState",e.ChannelOnOffState="IChannelOnOff",e.IntercomState="IIntercom",e.DoorBellState="IDoorBell",e.FacadeRemoteButtonState="IFacadeControlButton",e.FacadePosition="IFacadeState",e.FacadeType="IFacadeType",e.FloodSensorState="IFloodSensor",e.GatePosition="IGatePosition",e.GatewayPosition="IGatewayPosition",e.GateControllerHealth="IGateControllerHealth",e.HumiditySensorState="IHumiditySensor",e.LightBrightness="ILightBrightness",e.LightColor="ILightColor",e.LightWarmth="ILightTemperature",e.LightTreshold="ILightTreshold",e.MovementSensorState="IMovementSensor",e.OnlineCamera="IOnlineCamera",e.OvercurrentProtectionState="IOvercurrentProtection",e.OvercurrentProtectionThreshold="IOvercurrentProtectionThreshold",e.ReedState="IReedState",e.SignalStrength="ISignalStrength",e.SmokeSensorState="ISmokeSensor",e.MeasuredTemperature="ITemperature",e.VibrationSensorState="IVibrationSensor",e.MeasuredWindSpeed="IWindSpeed",e.WindThreshold="IWindThreshold",e.MeasuredEnergy="IEnergy",e.MeasuredDistance="DistanceSensor",e.BlindCalibration="BlindCalibration",e.ConfigurationState="ConfigurationState",e.CurrentWindThreshold="CurrentWindThreshold",e.CurrentLightThreshold="CurrentLightThreshold",e.WindSpeedState="WindSpeed",e.TamperProtectionState="ITamperProtection",e.PressureSensorState="IPressureSensor",e.LightRGBWState="ILightRGBW"}(At||(At={})),(It=_t||(_t={}))[It.NotResponding=0]="NotResponding",It[It.Working=1]="Working",It[It.Broken=2]="Broken",It[It.FirmareUpgradeMode=3]="FirmareUpgradeMode",(Et=Ct||(Ct={}))[Et.TwoWay=1]="TwoWay",Et[Et.OneWay=2]="OneWay",Et[Et.ConditionalTwoWay=3]="ConditionalTwoWay",(Nt=Tt||(Tt={}))[Nt.Unknown=-1]="Unknown",Nt[Nt.Multipurpose=0]="Multipurpose",Nt[Nt.Controller=1]="Controller",Nt[Nt.Driver=2]="Driver",Nt[Nt.Receiver=3]="Receiver",Nt[Nt.Remote=4]="Remote",Nt[Nt.Sensor=5]="Sensor",Nt[Nt.Scene=6]="Scene";class Mt{constructor(){this.DeviceGuid="",this.Channel=0,this.Status=vt.NoTasksExecuting}}!function(e){e[e.Unknown=0]="Unknown",e[e.Executed=1]="Executed",e[e.ResponseTimeout=2]="ResponseTimeout",e[e.TaskRepeatedAndExecuted=3]="TaskRepeatedAndExecuted",e[e.TaskRepeatedResponseTimeout=4]="TaskRepeatedResponseTimeout",e[e.FlowControlNotAvailable=5]="FlowControlNotAvailable",e[e.ExecutionError=6]="ExecutionError"}(Dt||(Dt={})),function(e){e[e.ControllerResponseTimeout=-4]="ControllerResponseTimeout",e[e.DeviceNotFound=-3]="DeviceNotFound",e[e.DeviceResponseTimeout=-2]="DeviceResponseTimeout",e[e.Failed=-1]="Failed",e[e.Unknown=0]="Unknown",e[e.Executed=1]="Executed"}(kt||(kt={}));class xt{constructor(){this.Device=null,this.Channel=0,this.Task=null,this.Result=kt.Unknown}}var Ft,Lt,Bt,Wt,$t,qt,Vt,Ht,jt,Kt,zt,Jt,Yt,Xt,Qt,Zt,en,tn,nn,sn,rn,on,an,cn,un,ln,dn,hn,gn,pn,fn;class vn{constructor(){this._type="",this._data=null,this._typeAsEnum=At.Unknown,this._serializedDataWithoutTime=""}get Data(){return this._data}set Data(e){this._data=e;let{Time:t}=e,n=function(e,t){var n={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(n[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(s=Object.getOwnPropertySymbols(e);r<s.length;r++)t.indexOf(s[r])<0&&Object.prototype.propertyIsEnumerable.call(e,s[r])&&(n[s[r]]=e[s[r]])}return n}(e,["Time"]);this._serializedDataWithoutTime=JSON.stringify(n)}get Type(){return this._type}set Type(e){this._type=e}get TypeAsEnum(){return this._typeAsEnum}set TypeAsEnum(e){this._typeAsEnum=e}get StatesComparisonData(){return this._serializedDataWithoutTime}}(fn=Ft||(Ft={}))[fn.Confident=0]="Confident",fn[fn.Unconfident=1]="Unconfident";class mn extends vn{constructor(e){super(),this.TypeAsEnum=At.ChannelOnOffState,this.Type="ChannelOnOffState",this.Data=e.state}}class yn{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.State=Lt.Unknown,this.Time=""}}!function(e){e[e.On=0]="On",e[e.Off=1]="Off",e[e.Unknown=2]="Unknown"}(Lt||(Lt={})),function(e){e[e.Idle=0]="Idle",e[e.IncomingCall=1]="IncomingCall",e[e.AnsweringCall=2]="AnsweringCall",e[e.Busy=3]="Busy",e[e.NoAnswerToCall=4]="NoAnswerToCall",e[e.Unknown=5]="Unknown"}(Bt||(Bt={}));class wn extends vn{constructor(e){super(),this.TypeAsEnum=At.OnlineCamera,this.Type="OnlineCameraState",this.Data=e.state}}class Sn extends vn{constructor(e){super(),this.TypeAsEnum=At.DoorBellState,this.Type="DoorBellState",this.Data=e.state}}class An{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.State=Wt.Relased,this.Time=""}}!function(e){e[e.Pressed=0]="Pressed",e[e.Relased=1]="Relased",e[e.PressedAndRelased=2]="PressedAndRelased"}(Wt||(Wt={}));class _n extends vn{constructor(e){super(),this.TypeAsEnum=At.ReedState,this.Type="ReedState",this.Data=e.state}}class Cn{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.State=!1,this.Time=""}}class Tn extends vn{constructor(e){super(),this.TypeAsEnum=At.BlindPosition,this.Type="BlindPostionState",this.Data=e.state}GetBlindStatus(){switch(this.Data.Position){case 200:return $t.UnableToMove;case 201:return $t.MotorOverheatedPleaseWait;default:return $t.Working}}}!function(e){e[e.Unknown=0]="Unknown",e[e.Working=1]="Working",e[e.UnableToMove=200]="UnableToMove",e[e.MotorOverheatedPleaseWait=201]="MotorOverheatedPleaseWait"}($t||($t={}));class Dn{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.Position=0,this.RawPosition=0,this.Time=""}}class kn extends vn{constructor(e){super(),this.TypeAsEnum=At.RemoteButtonState,this.Type="RemoteButtonState",this.Data=e.state}}class Gn{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.State=qt.Relased,this.Time=""}}!function(e){e[e.Pressed=1]="Pressed",e[e.Relased=2]="Relased",e[e.PressedAndRelased=3]="PressedAndRelased"}(qt||(qt={}));class bn extends vn{constructor(e){super(),this.TypeAsEnum=At.LightColor,this.Type="LightColorState",this.Data=e.state}}class Nn{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.R=0,this.G=0,this.B=0,this.Time=""}}class En extends vn{constructor(e){super(),this.TypeAsEnum=At.LightWarmth,this.Type="LightWarmthState",this.Data=e.state}}class In{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.Temperature=0,this.Time=""}}class Rn extends vn{constructor(e){super(),this.TypeAsEnum=At.LightBrightness,this.Type="LightBrightnessState",this.Data=e.state}}class Pn{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.Brightness=0,this.Time=""}}class On extends vn{constructor(e){super(),this.TypeAsEnum=At.MeasuredTemperature,this.Type="MeasuredTemperatureState",this.Data=e.state}}class Un{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.Temperature=0,this.Type=Vt.InsideTemperature,this.Time=""}}!function(e){e[e.AirTemperature=0]="AirTemperature",e[e.InsideTemperature=1]="InsideTemperature",e[e.OutsideTemperature=2]="OutsideTemperature",e[e.FloorTemperature=3]="FloorTemperature",e[e.SafetyTemperature=4]="SafetyTemperature",e[e.SetTemperature=5]="SetTemperature"}(Vt||(Vt={}));class Mn extends vn{constructor(e){super(),this.TypeAsEnum=At.BatteryState,this.Type="BatteryState",this.Data=e.state}}class xn{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.State=Ht.Half,this.Percentage=-1,this.Time=""}}!function(e){e[e.Unknown=-1]="Unknown",e[e.Full=0]="Full",e[e.Empty=1]="Empty",e[e.Half=2]="Half",e[e.Percentage=3]="Percentage",e[e.Low=4]="Low",e[e.ExternalPower=5]="ExternalPower"}(Ht||(Ht={}));class Fn extends vn{constructor(e){super(),this.TypeAsEnum=At.MeasuredBrightness,this.Type="MeasuredBrightnessState",this.Data=e.state}}class Ln{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.Brightness=0,this.Time=""}}class Bn extends vn{constructor(e){super(),this.TypeAsEnum=At.MeasuredEnergy,this.Type="MeasuredEnergyState",this.Data=e.state,this.Data.MeasurementParameters=new Map(Object.entries(e.state.MeasurementParameters))}}class Wn{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.Time="",this.MeasurementParameters=new Map}}!function(e){e.Voltage="Voltage",e.Current="Current",e.PhaseShift="PhaseShift",e.ActivePower="ActivePower",e.ReactivePower="ReactivePower",e.ApparentPower="ApparentPower",e.PowerFactor="PowerFactor",e.ActiveForwardEnergy="ActiveForwardEnergy",e.ActiveReverseEnergy="ActiveReverseEnergy",e.ApparentEnergy="ApparentEnergy",e.ReactiveForwardEnergy="ReactiveForwardEnergy",e.ReactiveReverseEnergy="ReactiveReverseEnergy",e.Frequency="Frequency",e.SPIErrorRate="SPIErrorRate",e.CRCErrorRate="CRCErrorRate",e.Timestamp="Timestamp",e.FailedMeasurementsRate="FailedMeasurementsRate",e.FundamentalActivePower="FundamentalActivePower",e.HarmonicActivePower="HarmonicActivePower"}(jt||(jt={}));class $n extends vn{constructor(e){super(),this.TypeAsEnum=At.MeasuredDistance,this.Type="MeasuredDistanceState",this.Data=e.state}}!function(e){e[e.No=0]="No",e[e.Yes=1]="Yes"}(Kt||(Kt={}));class qn extends vn{constructor(e){super(),this.TypeAsEnum=At.MovementSensorState,this.Type="MovementSensorState",this.Data=e.state}}class Vn{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.Intensity=0,this.Movement=zt.No,this.Time=""}}!function(e){e[e.No=0]="No",e[e.Yes=1]="Yes"}(zt||(zt={}));class Hn extends vn{constructor(e){super(),this.TypeAsEnum=At.BlindRemoteButtonState,this.Type="BlindRemoteButtonState",this.Data=e.state}}class jn{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.State=Jt.StopReleased,this.Time=""}}!function(e){e[e.OpenPressed=1]="OpenPressed",e[e.OpenReleased=2]="OpenReleased",e[e.StopPressed=3]="StopPressed",e[e.StopReleased=4]="StopReleased",e[e.ClosePressed=5]="ClosePressed",e[e.CloseReleased=6]="CloseReleased"}(Jt||(Jt={}));class Kn extends vn{constructor(e){super(),this.TypeAsEnum=At.FacadeRemoteButtonState,this.Type="FacadeRemoteButtonState",this.Data=e.state}}class zn{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.State=Yt.StopReleased,this.Time=""}}!function(e){e[e.OpenPressed=1]="OpenPressed",e[e.OpenReleased=2]="OpenReleased",e[e.StopPressed=3]="StopPressed",e[e.StopReleased=4]="StopReleased",e[e.ClosePressed=5]="ClosePressed",e[e.CloseReleased=6]="CloseReleased"}(Yt||(Yt={}));class Jn extends vn{constructor(e){super(),this.TypeAsEnum=At.SignalStrength,this.Type="SignalStrenghtState",this.Data=e.state}}!function(e){e[e.Unknown=0]="Unknown",e[e.Excellent=1]="Excellent",e[e.Good=2]="Good",e[e.Acceptable=3]="Acceptable",e[e.Low=4]="Low",e[e.Terrible=5]="Terrible",e[e.NoLink=6]="NoLink"}(Xt||(Xt={}));class Yn extends vn{constructor(e){super(),this.TypeAsEnum=At.GatePosition,this.Type="GatePositionState",this.Data=e.state}}class Xn{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.PositionType=Qt.Unknown,this.Position=0,this.Time=""}}!function(e){e[e.Unknown=0]="Unknown",e[e.Open=1]="Open",e[e.PartiallyOpen=2]="PartiallyOpen",e[e.Close=3]="Close",e[e.On=4]="On",e[e.Off=5]="Off",e[e.Percentage=6]="Percentage"}(Qt||(Qt={}));class Qn extends vn{constructor(e){super(),this.TypeAsEnum=At.GatewayPosition,this.Type="GatewayPositionState",this.Data=e.state}}!function(e){e[e.Unknown=0]="Unknown",e[e.Open=1]="Open",e[e.PartiallyOpen=2]="PartiallyOpen",e[e.Close=3]="Close",e[e.On=4]="On",e[e.Off=5]="Off"}(Zt||(Zt={}));class Zn extends vn{constructor(e){super(),this.TypeAsEnum=At.GateControllerHealth,this.Type="GateControllerHealthState",this.Data=e.state}}!function(e){e[e.Unknown=-1]="Unknown",e[e.Inactive=0]="Inactive",e[e.Active=1]="Active",e[e.UnconnectedOrMalfunction=2]="UnconnectedOrMalfunction"}(en||(en={}));class es extends vn{constructor(e){super(),this.TypeAsEnum=At.BlindCalibration,this.Type="BlindCalibrationState",this.Data=e.state}}!function(e){e[e.AutoLernIdle=0]="AutoLernIdle",e[e.AutoLernInProgress=1]="AutoLernInProgress",e[e.AutoLernSuccessfull=2]="AutoLernSuccessfull",e[e.AutoLernCancelled=4]="AutoLernCancelled"}(tn||(tn={}));class ts extends vn{constructor(e){super(),this.TypeAsEnum=At.HumiditySensorState,this.Type="HumiditySensorState",this.Data=e.state}}class ns{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.Type=nn.AirHumidity,this.Humidity=0,this.Time=""}}!function(e){e[e.AirHumidity=0]="AirHumidity",e[e.InsideHumidity=1]="InsideHumidity",e[e.OutsideHumidity=2]="OutsideHumidity",e[e.SafetyHumidity=3]="SafetyHumidity",e[e.SetHumidity=4]="SetHumidity"}(nn||(nn={}));class ss extends vn{constructor(e){super(),this.TypeAsEnum=At.VibrationSensorState,this.Type="VibrationSensorState",this.Data=e.state}}!function(e){e[e.No=0]="No",e[e.Yes=1]="Yes"}(sn||(sn={}));class rs extends vn{constructor(e){super(),this.TypeAsEnum=At.BinarySensorState,this.Type="BinarySensorState",this.Data=e.state}}class os{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.State=rn.Low,this.Time=""}}!function(e){e[e.High=1]="High",e[e.Low=0]="Low"}(rn||(rn={}));class is extends vn{constructor(e){super(),this.TypeAsEnum=At.ConfigurationState,this.Type="ConfigurationState",this.Data=e.state}}!function(e){e[e.Unknown=0]="Unknown",e[e.OngoingConfiguration=1]="OngoingConfiguration",e[e.NotConfigured=2]="NotConfigured",e[e.Configured=3]="Configured",e[e.PartiallyConfigured=4]="PartiallyConfigured"}(on||(on={}));class as extends vn{constructor(e){super(),this.TypeAsEnum=At.BlindOpenCloseTime,this.Type="BlindOpenCloseTimeState",this.Data=e.state}}class cs extends vn{constructor(e){super(),this.TypeAsEnum=At.OvercurrentProtectionState,this.Type="OvercurrentProtectionState",this.Data=e.state}}class us extends vn{constructor(e){super(),this.TypeAsEnum=At.OvercurrentProtectionThreshold,this.Type="OvercurrentProtectionThresholdState",this.Data=e.state}}class ls extends vn{constructor(e){super(),this.TypeAsEnum=At.FacadePosition,this.Type="FacadePositionState",this.Data=e.state}}class ds extends vn{constructor(e){super(),this.TypeAsEnum=At.FacadeType,this.Type="FacadeTypeState",this.Data=e.state}}class hs extends vn{constructor(e){super(),this.TypeAsEnum=At.CurrentWindThreshold,this.Type="CurrentWindThresholdState",this.Data=e.state}}class gs{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.WindThreshold=an.Unknown,this.Time=""}}!function(e){e[e.Unknown=0]="Unknown",e[e.Below=1]="Below",e[e.Exceeded=2]="Exceeded",e[e.Inactive=3]="Inactive"}(an||(an={}));class ps extends vn{constructor(e){super(),this.TypeAsEnum=At.CurrentLightThreshold,this.Type="CurrentLightThresholdState",this.Data=e.state}}!function(e){e[e.Unknown=0]="Unknown",e[e.Below=1]="Below",e[e.Exceeded=2]="Exceeded"}(cn||(cn={}));class fs extends vn{constructor(e){super(),this.TypeAsEnum=At.WindSpeedState,this.Type="WindSpeedState",this.Data=e.state}}class vs{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.Value=0,this.Time=""}}class ms extends vn{constructor(e){super(),this.TypeAsEnum=At.FloodSensorState,this.Type="FloodSensorState",this.Data=e.state}}class ys{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.State=un.NoFloodDetected,this.Time=""}}!function(e){e[e.FloodDetected=1]="FloodDetected",e[e.NoFloodDetected=0]="NoFloodDetected"}(un||(un={})),function(e){e[e.AirHumidity=0]="AirHumidity",e[e.InsideHumidity=1]="InsideHumidity",e[e.OutsideHumidity=2]="OutsideHumidity",e[e.SafetyHumidity=3]="SafetyHumidity",e[e.SetHumidity=4]="SetHumidity"}(ln||(ln={}));class ws extends vn{constructor(e){super(),this.TypeAsEnum=At.PressureSensorState,this.Type="PressureSensorState",this.Data=e.state}}class Ss{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.Pressure=0,this.Time="",this.PressureType=dn.OutsidePressure}}!function(e){e[e.InsidePressure=0]="InsidePressure",e[e.OutsidePressure=1]="OutsidePressure",e[e.SetPressure=2]="SetPressure"}(dn||(dn={})),function(e){e[e.Facade90=0]="Facade90",e[e.Facade180=1]="Facade180"}(hn||(hn={}));class As extends vn{constructor(e){super(),this.TypeAsEnum=At.TamperProtectionState,this.Type="TamperProtection",this.Data=e.state}}!function(e){e[e.OK=0]="OK",e[e.Breach=1]="Breach"}(gn||(gn={}));class _s extends vn{constructor(e){super(),this.TypeAsEnum=At.LightRGBWState,this.Type="LightRGBW",this.Data=e.state}}class Cs extends vn{constructor(e){super(),this.TypeAsEnum=At.BlindErrorState,this.Type="BlindError",this.Data=e.state}}!function(e){e[e.Unknown=0]="Unknown",e[e.ObstacleDetected=1]="ObstacleDetected",e[e.MotorFailure=2]="MotorFailure"}(pn||(pn={}));class Ts{constructor(){this._onDeviceStateChangedEvent=new n,this._onDeviceStateRefreshedOrChangedEvent=new n,this._onDeviceTasksExecutionChangedOnChannelsEvent=new n,this._onDeviceFirmwareVersionChangedEvent=new n,this._iconType=wt.Unknown,this._serialNumber=null,this._model=null,this._modelGuid=null,this._manufacturerGuid=null,this._isVirtual=!1,this._isEnabled=!1,this._deviceState=_t.Working,this._deviceType=Tt.Unknown,this._communicationWay=Ct.OneWay,this._availableTasksTypes=[],this._availableResponseTypes=[],this._channels=[],this._protocolGuid=null,this._softwareVersion=null,null==Ts._devicesService&&(Ts._devicesService=Ov.Get(xo.ServiceName));const e=this._onDeviceStateChangedEvent,t=this._onDeviceTasksExecutionChangedOnChannelsEvent;Ts._devicesService.OnDeviceStateChangedEvent().Subscribe((t=>{t.Device.Guid==this._guid&&e.Invoke(t.State)})),Ts._devicesService.OnDeviceStateRefreshedOrChangedEvent().Subscribe((e=>{e.Device.Guid==this._guid&&this._onDeviceStateRefreshedOrChangedEvent.Invoke(e.State)})),Ts._devicesService.OnDevicesTasksExecutionChangeEvent().Subscribe((e=>{t.Invoke(e.filter((e=>e.DeviceGuid==this._guid)).map((e=>e.Channel)))}))}OnDeviceFirmwareVersionChangedEvent(){return this._onDeviceFirmwareVersionChangedEvent}OnDeviceStateRefreshedOrChangedEvent(){return this._onDeviceStateRefreshedOrChangedEvent}get ShouldChannelsBeGrouped(){if(this._deviceType===Tt.Remote)switch(this._modelGuid){case"afea26ac-d5de-4aa9-8e74-ff69679d097b":case"908a71ec-ca46-4431-9504-05b7801e77f8":case"d8fea502-541e-42d9-8ece-a1bcfaaa93f9":return!1;default:return this._availableTasksTypes.all((e=>e.Type!==St.SetBlindPositionSimple))}return!1}get States(){return s.DoesThrowStackTrace?Ov.Get(xo.ServiceName).GetDeviceStates(this).selectMany((e=>e.States)).toArray():Ts._devicesService.GetDeviceStates(this).selectMany((e=>e.States)).toArray()}RemoveDeviceAsync(){return Ts._devicesService.RemoveDeviceAsync(this)}ExecuteDeviceTaskAsync(e){return Ts._devicesService.ExecuteDeviceTaskAsync(this,e)}OnDeviceTasksExecutionChangedOnChannelsEvent(){return this._onDeviceTasksExecutionChangedOnChannelsEvent}OnDeviceStateChangedEvent(){return this._onDeviceStateChangedEvent}get Guid(){return null==this._guid?"":this._guid}set Guid(e){this._guid=e}get IconType(){return this._iconType}set IconType(e){this._iconType=e}get Name(){return null==this._name?"":this._name}set Name(e){this._name=e}set SoftwareVersion(e){this._softwareVersion=e}get SoftwareVersion(){return this._softwareVersion}get ChannelsAmount(){return null==this._channelsAmount?0:this._channelsAmount}set ChannelsAmount(e){this._channelsAmount=e}get SerialNumber(){return this._serialNumber}set SerialNumber(e){this._serialNumber=e}get Model(){return this._model}set Model(e){this._model=e}get ModelGuid(){return this._modelGuid}set ModelGuid(e){this._modelGuid=e}get ManufacturerGuid(){return this._manufacturerGuid}set ManufacturerGuid(e){this._manufacturerGuid=e}get IsVirtual(){return this._isVirtual}set IsVirtual(e){this._isVirtual=e}get IsEnabled(){return this._isEnabled}set IsEnabled(e){this._isEnabled=e}get DeviceState(){return this._deviceState}set DeviceState(e){this._deviceState=e}get DeviceType(){return this._deviceType}set DeviceType(e){this._deviceType=e}get CommunicationWay(){return this._communicationWay}set CommunicationWay(e){this._communicationWay=e}get AvailableTaskTypes(){return this._availableTasksTypes}set AvailableTaskTypes(e){this._availableTasksTypes=e}get AvailableResponseTypes(){return this._availableResponseTypes}set AvailableResponseTypes(e){this._availableResponseTypes=e}get Channels(){return this._channels}get ProtocolGuid(){return this._protocolGuid}set ProtocolGuid(e){this._protocolGuid=e}ChangeDeviceNameAsync(e){return t=this,n=void 0,r=function*(){try{const t=yield Ov.Get(Pt.ServiceName).SendAndWaitForResponseAsync(new Ds(this,e),2e4,!1);switch(t.Status){case ce.OK:return this._name=e,Ov.Get(Ge.ServiceName).ClearCache(),Ov.Get(rt.ServiceName).ExitConfigurationModeAsync(),new Te(me.Changed,"");case ce.WrongData:if("DeviceNotFound"==t.Data)return new Te(me.Failed,"DeviceNotFound");break;case ce.NoPermissionsToCallGivenResource:return new Te(me.NoPermissions,"")}}catch(e){return e.message.includes("timeout")?new Te(me.ControllerResponseTimeout,""):new Te(me.UnknownError,"")}return new Te(me.Unknown,"")},new((s=void 0)||(s=Promise))((function(e,o){function i(e){try{c(r.next(e))}catch(e){o(e)}}function a(e){try{c(r.throw(e))}catch(e){o(e)}}function c(t){var n;t.done?e(t.value):(n=t.value,n instanceof s?n:new s((function(e){e(n)}))).then(i,a)}c((r=r.apply(t,n||[])).next())}));var t,n,s,r}ExecuteTaskAsync(e){return Ts._devicesService.ExecuteDeviceTaskAsync(this,e)}}class Ds extends ae{constructor(e,t){super(),this.Resource="/devices/device/name",this.Method=ue.Put;const n=new ks;n.DeviceGuid=e.Guid,n.Name=t,this.Data=n}}class ks{constructor(){this.DeviceGuid="",this.Name=""}}var Gs,bs,Ns,Es,Is,Rs=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class Ps{constructor(){this._device=new Ts,this._number=0,this._name="",this._iconName="",this._channelId="",this._mode=mt.Default,this._channelGroups=[],this._isHidden=!1,this._availableTasksTypes=[],this._availableResponseTypes=[],this._customData={},this._roles=[],this._configurations={},this.CustomDataAndRolesSupported=!1,this._onTasksExecutionChangedEvent=new n,this._onChannelStateChangedEvent=new n,this._onChannelStateRefreshedOrChangedEvent=new n,null==Ps._devicesService&&(Ps._devicesService=Ov.Get(xo.ServiceName))}OnChannelStateChangedEvent(){return this._onChannelStateChangedEvent}OnChannelStateRefreshedOrChangedEvent(){return this._onChannelStateRefreshedOrChangedEvent}get Configurations(){return this._configurations}set Configurations(e){this._configurations=e}IsCustomDataAndRolesSupported(){return this.CustomDataAndRolesSupported}get CustomData(){return this._customData}set CustomData(e){this._customData=e}get Roles(){return this._roles}set Roles(e){this._roles=e}get ChannelId(){return this._channelId}SetDevice(e){this._device=e,this._channelId=`${e.Guid}_${this.Number}`,this._device.OnDeviceStateChangedEvent().Subscribe((e=>{e.Data.Channel==this.Number&&this._onChannelStateChangedEvent.Invoke(e)})),this._device.OnDeviceStateRefreshedOrChangedEvent().Subscribe((e=>{e.Data.Channel==this.Number&&this._onChannelStateRefreshedOrChangedEvent.Invoke(e)}))}GetDevice(){return this._device}SetCustomDataAsync(e,t){return Rs(this,void 0,void 0,(function*(){const n=this.GetChannelConfigurationData();n.CustomData[e]=t,this._customData[e]=t;const s=new Os;return s.DeviceGuid=this._device.Guid,s.ChannelConfiguration=n,this.ChangeConfigurationAsync(s)}))}RemoveCustomDataAsync(e){const t=this.GetChannelConfigurationData();delete t.CustomData[e],delete this._customData[e];const n=new Os;return n.DeviceGuid=this._device.Guid,n.ChannelConfiguration=t,this.ChangeConfigurationAsync(n)}GetChannelConfigurationData(){const e=new Us;return e.Channel=this._number,e.ChannelName=this._name,e.Configuration=this._mode,e.CustomData=this._customData,e.GroupsGuids=this._channelGroups,e.Hidden=this._isHidden,e.IconName=this._iconName,e}HideAsync(){const e=this.GetChannelConfigurationData();this._isHidden=!0,e.Hidden=!0;const t=new Os;return t.DeviceGuid=this._device.Guid,t.ChannelConfiguration=e,this.ChangeConfigurationAsync(t)}ShowAsync(){const e=this.GetChannelConfigurationData();e.Hidden=!1,this._isHidden=!1;const t=new Os;return t.DeviceGuid=this._device.Guid,t.ChannelConfiguration=e,this.ChangeConfigurationAsync(t)}ChangeNameAsync(e){const t=this.GetChannelConfigurationData(),n=new Os;return n.DeviceGuid=this._device.Guid,n.ChannelConfiguration=t,t.ChannelName=e,this._name=e,this.ChangeConfigurationAsync(n)}ChangeIconNameAsync(e){const t=this.GetChannelConfigurationData();t.IconName=e;const n=new Os;return n.DeviceGuid=this._device.Guid,n.ChannelConfiguration=t,this._iconName=e,this.ChangeConfigurationAsync(n)}ChangeGroupsAsync(e){const t=this.GetChannelConfigurationData();t.GroupsGuids=e;const n=new Os;return n.DeviceGuid=this._device.Guid,n.ChannelConfiguration=t,this._channelGroups=e,this.ChangeConfigurationAsync(n)}ChangeConfigurationAsync(e){return Rs(this,void 0,void 0,(function*(){var t;try{const n=yield Ov.Get(Pt.ServiceName).SendAndWaitForResponseAsync(new Ms(e),2e4,!1);switch(Ov.Get(Ge.ServiceName).ClearCache(),yield Ov.Get(rt.ServiceName).ExitConfigurationModeAsync(),n.Status){case ce.OK:return this._name=e.ChannelConfiguration.ChannelName,this._iconName=e.ChannelConfiguration.IconName,this._channelGroups=e.ChannelConfiguration.GroupsGuids,this._isHidden=e.ChannelConfiguration.Hidden,this._mode=e.ChannelConfiguration.Configuration,this._customData=e.ChannelConfiguration.CustomData,this._roles=e.ChannelConfiguration.Roles,this._configurations=e.ChannelConfiguration.Configurations,new Te(me.Changed,"");case ce.WrongData:if("DeviceNotFound"===n.Data)return null===(t=r.Log)||void 0===t||t.Error("Failed to change channel configuration, referenced device does not exist!"),new Te(me.WrongData,"DeviceNotFound");break;case ce.FatalError:return new Te(me.UnknownError,"")}}catch(e){if(e.message.includes("timeout"))return new Te(me.ControllerResponseTimeout,"")}return new Te(me.Unknown,"")}))}get Number(){return this._number}set Number(e){this._number=e}get Name(){return this._name}set Name(e){this._name=e}get IconName(){return this._iconName}set IconName(e){this._iconName=e}get States(){return s.DoesThrowStackTrace?Ov.Get(xo.ServiceName).GetDeviceStates(this.GetDevice()).where((e=>e.Channel==this.Number)).selectMany((e=>e.States)).toArray():Ps._devicesService.GetDeviceStates(this.GetDevice()).where((e=>e.Channel==this.Number)).selectMany((e=>e.States)).toArray()}get Mode(){return this._mode}set Mode(e){this._mode=e}get ChannelGroups(){return this._channelGroups}set ChannelGroups(e){this._channelGroups=e}get IsHidden(){return this._isHidden}set IsHidden(e){this._isHidden=e}get AvailableTaskTypes(){return this._availableTasksTypes}set AvailableTaskTypes(e){this._availableTasksTypes=e}get AvailableResponseTypes(){return this._availableResponseTypes}set AvailableResponseTypes(e){this._availableResponseTypes=e}OnTasksExecutionChangeEvent(){return this._onTasksExecutionChangedEvent}ExecuteTaskAsync(e){return null!=this._device?(e.Channel=this.Number,e.DeviceGuid=this._device.Guid,Ps._devicesService.ExecuteDeviceTaskAsync(this._device,e)):Promise.resolve(kt.Failed)}}Ps._devicesService=null;class Os{constructor(){this.DeviceGuid="",this.ChannelConfiguration=new Us}}class Us{constructor(){this.Channel=0,this.ChannelName="",this.Configuration=mt.Default,this.GroupsGuids=[],this.IconName="",this.Hidden=!1,this.Configurations={},this.CustomData={},this.Roles=[]}}class Ms extends ae{constructor(e){super(),this.Resource="/devices/device/channel/configuration",this.Method=ue.Put,this.Data=e}}!function(e){e[e.TurnOn=0]="TurnOn",e[e.TurnOff=1]="TurnOff",e[e.ToggleState=2]="ToggleState",e[e.SetBlindPosition=3]="SetBlindPosition",e[e.SetLightColor=4]="SetLightColor",e[e.SetLightTemperature=5]="SetLightTemperature",e[e.SetLightBrightness=6]="SetLightBrightness",e[e.SetTemperature=7]="SetTemperature",e[e.GetState=8]="GetState",e[e.TurnOnWithTimeout=9]="TurnOnWithTimeout",e[e.SetLightBrightnessDynamicly=10]="SetLightBrightnessDynamicly",e[e.IdentifyDevice=11]="IdentifyDevice",e[e.SetBlindOpenCloseTime=12]="SetBlindOpenCloseTime",e[e.SetBlindMicroventilation=13]="SetBlindMicroventilation",e[e.GatewayPulse=25]="GatewayPulse",e[e.GatePulse=26]="GatePulse",e[e.SetFacadePositionAndTilt=29]="SetFacadePositionAndTilt",e[e.GetFacadeType=30]="GetFacadeType",e[e.LightRGBW=31]="LightRGBW",e[e.SetGatePositionPrecise=32]="SetGatePositionPrecise"}(Gs||(Gs={}));class xs{static NewGuid(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))}}class Fs{constructor(){this._taskType=St.GetChannelsState,this._featureType=Gs.GetState,this._channel=0,this._guid=xs.NewGuid(),this._deviceGuid=""}get TaskType(){return this._taskType}set TaskType(e){this._taskType=e}get FeatureType(){return this._featureType}set FeatureType(e){this._featureType=e}get Guid(){return this._guid}set Guid(e){this._guid=e}get DeviceGuid(){return this._deviceGuid}set DeviceGuid(e){this._deviceGuid=e}get Channel(){return this._channel}set Channel(e){this._channel=e}}class Ls extends Fs{constructor(){super(),this.Temperature=0,this.FeatureType=Gs.SetTemperature,this.TaskType=St.SetTemperature}}class Bs extends Fs{constructor(){super(),this.FeatureType=Gs.TurnOff,this.TaskType=St.TurnOff}}class Ws extends Fs{constructor(){super(),this.FeatureType=Gs.TurnOn,this.TaskType=St.TurnOn}}class $s extends Fs{constructor(){super(),this.SwitchOffDelaySeconds=0,this.FeatureType=Gs.TurnOnWithTimeout,this.TaskType=St.TurnOnWithTime}}class qs extends Fs{constructor(){super(),this.Brightness=0,this.FeatureType=Gs.SetLightBrightness,this.TaskType=St.SetLightBrightness}}class Vs extends Fs{constructor(){super(),this.FeatureType=Gs.ToggleState,this.TaskType=St.TogleState}}class Hs extends Fs{constructor(){super(),this.R=0,this.G=0,this.B=0,this.FeatureType=Gs.SetLightColor,this.TaskType=St.SetLightColor}}class js extends Fs{constructor(){super(),this.Temperature=0,this.FeatureType=Gs.SetLightTemperature,this.TaskType=St.SetLightTemperature}}class Ks extends Fs{constructor(){super(),this.Action=bs.Stop,this.Position=0,this.FeatureType=Gs.SetBlindPosition,this.TaskType=St.SetBlindPosition}}!function(e){e[e.Open=0]="Open",e[e.Close=1]="Close",e[e.Stop=2]="Stop",e[e.Percentage=3]="Percentage"}(bs||(bs={})),function(e){e[e.Open=0]="Open",e[e.Close=1]="Close",e[e.Stop=2]="Stop",e[e.Percentage=3]="Percentage"}(Ns||(Ns={})),function(e){e[e.Open=0]="Open",e[e.Close=1]="Close",e[e.Stop=2]="Stop"}(Es||(Es={}));class zs extends Fs{constructor(){super(),this.Brightness=0,this.FeatureType=Gs.SetLightBrightnessDynamicly,this.TaskType=St.SetLightBrightnessDynamicly}}class Js extends Fs{constructor(){super(),this.FeatureType=Gs.IdentifyDevice,this.TaskType=St.IdentifyDevice}}class Ys extends Fs{constructor(){super(),this.Data=new Xs,this.FeatureType=Gs.SetBlindOpenCloseTime,this.TaskType=St.SetBlindOpenCloseTime}}class Xs{constructor(){this.Channel=0,this.CloseTime=0,this.OpenTime=0}}class Qs extends Fs{constructor(){super(),this.FeatureType=Gs.GetState,this.TaskType=St.GetChannelsState}}class Zs extends Fs{constructor(){super(),this.Position=0,this.FeatureType=Gs.SetBlindMicroventilation,this.TaskType=St.SetBlindMicroventilation}}class er extends Fs{constructor(){super(),this.FeatureType=Gs.GatePulse,this.TaskType=St.ChangeGatewayPositionPulse}}class tr extends Fs{constructor(){super(),this.FeatureType=Gs.GatewayPulse,this.TaskType=St.ChangeGatewayPositionPulse}}class nr extends Fs{constructor(){super(),this.FacadeAction=Is.Stop,this.Tilt=0,this.Position=0,this.FeatureType=Gs.SetFacadePositionAndTilt,this.TaskType=St.SetFacadePosition}}class sr extends Fs{constructor(){super(),this.FeatureType=Gs.GetFacadeType,this.TaskType=St.GetFacadeType}}!function(e){e[e.Open=0]="Open",e[e.Close=1]="Close",e[e.Stop=2]="Stop",e[e.Percentage=3]="Percentage",e[e.Tilt=4]="Tilt",e[e.TiltAndPercentage=5]="TiltAndPercentage"}(Is||(Is={}));class rr{constructor(){this.R=0,this.G=0,this.B=0,this.W=0,this.Brightness=0,this.Channel=0}}class or extends Fs{constructor(){super(),this.Data=new rr,this.FeatureType=Gs.LightRGBW,this.TaskType=St.LightRGBW}}var ir=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class ar{constructor(){this._manualDeviceProtocolServices=new Map}GetServiceName(){return ar.ServiceName}RegisterManuallyPairedDevicesProtocol(e){Ov.Get(s.ServiceName).Debug(ar.ServiceName,`Registering new manual device protocol service: ${e.GetServiceName()}`),Ov.Get(Ge.ServiceName).ClearCache(),Ov.Get(rt.ServiceName).ExitConfigurationModeAsync(),this._manualDeviceProtocolServices.set(e.GetServiceName(),e)}GetDevicesForManualPairingAsync(e){return ir(this,void 0,void 0,(function*(){const t=[...this._manualDeviceProtocolServices.values()],n=[];if(null!=e)if(Array.isArray(e))for(let s=0;s<t.length;s++)e.any((e=>e==t[s].ProtocolExtensionGuid))&&n.push(...yield t[s].GetDevicesForManualPairingAsync());else{const s=t.find((t=>t.ProtocolExtensionGuid==e));null!=s&&n.push(...yield s.GetDevicesForManualPairingAsync())}else for(let e=0;e<t.length;e++)n.push(...yield t[e].GetDevicesForManualPairingAsync());return n}))}AddManuallyPairedDeviceAsync(e){return ir(this,void 0,void 0,(function*(){const t=[...this._manualDeviceProtocolServices.values()].find((t=>t.ProtocolExtensionGuid==e.ProtocolExtensionGuid));return null!=t?t.AddManuallyPairedDeviceAsync(e):(Ov.Get(Ge.ServiceName).ClearCache(),Ov.Get(rt.ServiceName).ExitConfigurationModeAsync(),kt.Failed)}))}GetRegisteredProtocolGuids(){return[...this._manualDeviceProtocolServices.values()].map((e=>e.ProtocolExtensionGuid))}}ar.ServiceName="ManualDeviceService";class cr{constructor(){this.ResourceGuid="",this.Data=null,this.IsGlobal=!1,this.InsertTime=new Date}}var ur,lr=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class dr{constructor(){this._connection=null,this._localDb=null,this._connection=Ov.Get(Pt.ServiceName),this._localDb=Ov.Get(o.ServiceName)}GetLocalDbName(e,t){return`${e}_${t}`}SaveAsync(e,t,n){return lr(this,void 0,void 0,(function*(){let s=new hr(e,t,n),r=yield this._connection.SendAndWaitForResponseAsync(s,35e3,!1);if(r.Status===ce.OK){const s=new fr;s.ResourceGuid=e,s.Data=JSON.stringify(n),s.IsGlobal=t,this._localDb.Save(dr.ServiceName,this.GetLocalDbName(e,t),s)}return r.Status}))}ReadAsync(e,t,n){return lr(this,void 0,void 0,(function*(){let s=new gr(e,t);if(!n){const n=this._localDb.Read(dr.ServiceName,this.GetLocalDbName(e,t));if(null!=n){const e=n,t=new cr;return t.Data=JSON.parse(e.Data),t.IsGlobal=e.IsGlobal,t.ResourceGuid=e.ResourceGuid,t}}let r=yield this._connection.SendAndWaitForResponseAsync(s,35e3,!1);if(r.Status===ce.OK){const e=new cr;return e.ResourceGuid=r.ResourceGuid,e.Data=JSON.parse(r.Data),e.IsGlobal=r.IsGlobal,e}return r.Status}))}RemoveAsync(e,t){return lr(this,void 0,void 0,(function*(){let n=new pr(e,t);return(yield this._connection.SendAndWaitForResponseAsync(n,35e3,!1)).Status}))}GetServiceName(){return dr.ServiceName}}dr.ServiceName="RemoteStorageService";class hr extends ae{constructor(e,t,n){super(),this.ResourceGuid="",this.Global=!1,this.Resource="/sync/config/",this.Method=ue.Put,this.ResourceGuid=e,this.Global=t,this.Data=JSON.stringify(n)}}class gr extends ae{constructor(e,t){super(),this.ResourceGuid="",this.Global=!1,this.Resource="/sync/config/",this.Method=ue.Get,this.ResourceGuid=e,this.Global=t}}class pr extends ae{constructor(e,t){super(),this.ResourceGuid="",this.Global=!1,this.Resource="/sync/config/",this.Method=ue.Delete,this.ResourceGuid=e,this.Global=t}}class fr extends ae{constructor(){super(...arguments),this.ResourceGuid="",this.Data="",this.IsGlobal=!1,this.InsertTime=new Date}}class vr{constructor(){this.Longitude=0,this.Latitude=0}}class mr{constructor(){this.Longitude=0,this.Latitude=0,this.IsNetworkBased=!1}}!function(e){e[e.OK=0]="OK",e[e.NoPermissions=1]="NoPermissions",e[e.UserIsNotLoggedIn=2]="UserIsNotLoggedIn",e[e.UnknownError=3]="UnknownError"}(ur||(ur={}));var yr,wr,Sr,Ar,_r,Cr,Tr,Dr,kr,Gr,br,Nr,Er,Ir,Rr,Pr,Or=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class Ur{IsControllerGeolocationSetAsync(){return Or(this,void 0,void 0,(function*(){let e=new Mr,t=yield Ov.Get(Pt.ServiceName).SendAndWaitForResponseAsync(e,15e3,!0);return(null==t?void 0:t.Status)===ce.OK?null==t?void 0:t.Data:null==t?void 0:t.Status}))}GetCurrentGeolocationAsync(){return Or(this,void 0,void 0,(function*(){return new Promise(((e,t)=>Or(this,void 0,void 0,(function*(){window.navigator.geolocation.getCurrentPosition((t=>{e(t)}),(t=>{e(t)}))}))))}))}SetControllerGeolocationAsync(e){return Or(this,void 0,void 0,(function*(){var t,n;let s=new Fr;s.Data.Latitude=e.Latitude,s.Data.Longitude=e.Longitude,null===(t=r.Log)||void 0===t||t.Warning(Ur.ServiceName,`SetControllerGeolocationAsync() ${JSON.stringify(s)}`);let o=yield Ov.Get(Pt.ServiceName).SendAndWaitForResponseAsync(s,15e3,!1);switch(null===(n=r.Log)||void 0===n||n.Warning(Ur.ServiceName,`${JSON.stringify(o)}`),Ov.Get(Ge.ServiceName).ClearCache(),Ov.Get(rt.ServiceName).ExitConfigurationModeAsync(),null==o?void 0:o.Status){case ce.OK:return new De(ur.OK,"");case ce.NoPermissionToPerformThisOperation:case ce.NoPermissionsToCallGivenResource:return new De(ur.NoPermissions,"");case ce.UserIsNotLoggedIn:return new De(ur.UserIsNotLoggedIn,"");default:return new De(ur.UnknownError,"")}}))}GetControlllerGeolocationAsync(){return Or(this,void 0,void 0,(function*(){var e,t;let n=new xr;null===(e=r.Log)||void 0===e||e.Warning(Ur.ServiceName,`GetControlllerGeolocationAsync(): ${JSON.stringify(n)}`);let s=yield Ov.Get(Pt.ServiceName).SendAndWaitForResponseAsync(n,15e3,!0);if(null===(t=r.Log)||void 0===t||t.Warning(Ur.ServiceName,`${JSON.stringify(s)}`),(null==s?void 0:s.Status)===ce.OK){let e=new mr;return e.IsNetworkBased=(null==s?void 0:s.Data).IsNetworkBased,e.Latitude=(null==s?void 0:s.Data).Latitude,e.Longitude=(null==s?void 0:s.Data).Longitude,e}return null==s?void 0:s.Status}))}GetServiceName(){return Ur.ServiceName}}Ur.ServiceName="GeolocationService";class Mr extends ae{constructor(){super(),this.Resource="/geolocation/isset",this.Method=ue.Get}}class xr extends ae{constructor(){super(),this.Resource="/geolocation/get",this.Method=ue.Get}}class Fr extends ae{constructor(){super(),this.Data=new vr,this.Resource="/geolocation/save",this.Method=ue.Put}}!function(e){e.OtherError="OtherError",e.FatalError="FatalError",e.NoData="NoData",e.InvalidSceneGuid="InvalidSceneGuid"}(yr||(yr={}));class Lr{constructor(){this._comparisonParams=new Map,this.Type=At.Unknown,this.DeviceGuid="",this.ComparisonMethod=wr.Default}GetCheckDeviceState(){return this._checkDeviceState}SetCheckDeviceState(e){this._checkDeviceState=e,e instanceof xn&&(this.Type=At.BatteryState),e instanceof os&&(this.Type=At.BinarySensorState),e instanceof Dn&&(this.Type=At.BlindPosition),e instanceof Pn&&(this.Type=At.LightBrightness),e instanceof Ln&&(this.Type=At.MeasuredBrightness),e instanceof Gn&&(this.Type=At.RemoteButtonState),e instanceof yn&&(this.Type=At.ChannelOnOffState),e instanceof An&&(this.Type=At.DoorBellState),e instanceof Wn&&(this.Type=At.MeasuredEnergy),e instanceof ys&&(this.Type=At.FloodSensorState),e instanceof Xn&&(this.Type=At.GatePosition),e instanceof Nn&&(this.Type=At.LightColor),e instanceof In&&(this.Type=At.LightWarmth),e instanceof Cn&&(this.Type=At.ReedState),e instanceof Un&&(this.Type=At.MeasuredTemperature),e instanceof ns&&(this.Type=At.HumiditySensorState),e instanceof jn&&(this.Type=At.BlindRemoteButtonState),e instanceof zn&&(this.Type=At.FacadeRemoteButtonState),e instanceof Vn&&(this.Type=At.MovementSensorState),e instanceof Wn&&(this.Type=At.MeasuredEnergy),e instanceof Ss&&(this.Type=At.PressureSensorState),e instanceof vs&&(this.Type=At.WindSpeedState),e instanceof gs&&(this.Type=At.CurrentWindThreshold)}GetComparisonParam(e){return this._comparisonParams.get(e)}GetComparisonParams(){return this._comparisonParams}SetComparisonParam(e,t){this._comparisonParams.set(e,t)}}class Br{constructor(e){this._value=e}get Value(){return this._value}set Value(e){this._value=e}}class Wr{constructor(...e){this._value="00:00:00",e.length>1?this.SetTimeSpan(e[0],e[1],e[2],e[3]):this._value=e[0]}SetTimeSpan(e,t,n,s){this._value=s<=0?`${n.toString().padStart(2,"0")}:${t.toString().padStart(2,"0")}:${e.toString().padStart(2,"0")}`:`${s}.${n.toString().padStart(2,"0")}:${t.toString().padStart(2,"0")}:${e.toString().padStart(2,"0")}`}get Value(){return this._value}}!function(e){e[e.Default=0]="Default",e[e.Delta=1]="Delta",e[e.StateRepeat=2]="StateRepeat"}(wr||(wr={})),function(e){e[e.DeltaValue=0]="DeltaValue",e[e.DeltaCalculationTimeRange=1]="DeltaCalculationTimeRange",e[e.StateRepeatCount=2]="StateRepeatCount",e[e.StateRepeatTimeRange=3]="StateRepeatTimeRange"}(Sr||(Sr={})),function(e){e[e.SunRise=1]="SunRise",e[e.SunSet=2]="SunSet"}(Ar||(Ar={}));class $r{constructor(){this.DeviceGuid=""}}!function(e){e[e.Unknown=-1]="Unknown",e[e.DeviceTask=0]="DeviceTask",e[e.DelayTask=1]="DelayTask",e[e.NotifyTask=2]="NotifyTask",e[e.LockExecution=3]="LockExecution"}(_r||(_r={})),function(e){e.Unknown="Unknown",e.DeviceTask="DeviceTask",e.DelayTask="DelayTask",e.NotifyTask="NotifyTask",e.LockExecution="LockExecution"}(Cr||(Cr={})),(Pr=Tr||(Tr={}))[Pr.Unknown=0]="Unknown",Pr[Pr.Second=1]="Second",Pr[Pr.Minute=2]="Minute",Pr[Pr.Hour=3]="Hour",Pr[Pr.Day=4]="Day",Pr[Pr.DayOfWeek=5]="DayOfWeek",Pr[Pr.Month=6]="Month",Pr[Pr.Year=7]="Year",Pr[Pr.Date=8]="Date",Pr[Pr.Time=9]="Time",Pr[Pr.WeatherType=11]="WeatherType",Pr[Pr.CompareNumbers=12]="CompareNumbers",Pr[Pr.CompareBooleans=13]="CompareBooleans",Pr[Pr.DeviceState=14]="DeviceState",Pr[Pr.Timer=15]="Timer",Pr[Pr.Temperature=17]="Temperature",Pr[Pr.DaysOfWeek=18]="DaysOfWeek",Pr[Pr.AstronomicalClockWithOffset=19]="AstronomicalClockWithOffset",Pr[Pr.SceneExecuted=20]="SceneExecuted",(Rr=Dr||(Dr={}))[Rr.Unknown=0]="Unknown",Rr[Rr.Equal=1]="Equal",Rr[Rr.NotEqueal=2]="NotEqueal",Rr[Rr.BiggerThan=3]="BiggerThan",Rr[Rr.SmallerThan=4]="SmallerThan",Rr[Rr.BiggerThanOrEqual=5]="BiggerThanOrEqual",Rr[Rr.SmallerThanOrEqual=6]="SmallerThanOrEqual",Rr[Rr.OneOfBothIsTrue=7]="OneOfBothIsTrue",Rr[Rr.BothAreTrue=8]="BothAreTrue",function(e){e[e.Unknown=0]="Unknown",e[e.BatteryState=1]="BatteryState",e[e.BinarySensor=2]="BinarySensor",e[e.BlindPosition=3]="BlindPosition",e[e.Brightness=4]="Brightness",e[e.ButtonState=5]="ButtonState",e[e.ChannelOnOff=6]="ChannelOnOff",e[e.DoorBell=7]="DoorBell",e[e.Energy=8]="Energy",e[e.FloodSensor=9]="FloodSensor",e[e.GatePosition=10]="GatePosition",e[e.HeatSensor=11]="HeatSensor",e[e.LightBrightness=12]="LightBrightness",e[e.LightColor=13]="LightColor",e[e.LightTemperature=14]="LightTemperature",e[e.MeasuredCurrent=15]="MeasuredCurrent",e[e.MeasuredPower=16]="MeasuredPower",e[e.MeasuredVoltage=17]="MeasuredVoltage",e[e.ReedState=18]="ReedState",e[e.SmokeSensor=19]="SmokeSensor",e[e.Temperature=20]="Temperature",e[e.BlindsControlButton=21]="BlindsControlButton",e[e.Movement=22]="Movement",e[e.WindSpeed=24]="WindSpeed",e[e.Humidity=25]="Humidity",e[e.AirPressure=26]="AirPressure",e[e.WindThreshold=31]="WindThreshold",e[e.FacadeControlButton=36]="FacadeControlButton"}(kr||(kr={})),function(e){e[e.Null=0]="Null",e[e.Condition=1]="Condition",e[e.ConditionGroup=2]="ConditionGroup",e[e.ArgumentAsInt=3]="ArgumentAsInt",e[e.ArgumentAsTimeSpan=4]="ArgumentAsTimeSpan",e[e.ArgumentAsBoolean=5]="ArgumentAsBoolean",e[e.ArgumentAsTimeout=6]="ArgumentAsTimeout",e[e.ArgumentAsDayOfWeek=7]="ArgumentAsDayOfWeek",e[e.ArgumentAsDaysOfWeek=8]="ArgumentAsDaysOfWeek",e[e.ArgumentAsAstronomicalClock=9]="ArgumentAsAstronomicalClock",e[e.ArgumentAsTime=10]="ArgumentAsTime",e[e.ArgumentAsDeviceState=11]="ArgumentAsDeviceState",e[e.ArgumentAsNumber=12]="ArgumentAsNumber",e[e.ArgumentAsAstronomicalClockWithOffset=13]="ArgumentAsAstronomicalClockWithOffset",e[e.ArgumentAsConditionInfo=14]="ArgumentAsConditionInfo"}(Gr||(Gr={})),(Ir=br||(br={})).Null="Null",Ir.Condition="Condition",Ir.ConditionGroup="ConditionGroup",Ir.ArgumentAsInt="ArgumentAsInt",Ir.ArgumentAsTimeSpan="ArgumentAsTimeSpan",Ir.ArgumentAsBoolean="ArgumentAsBoolean",Ir.ArgumentAsTimeout="ArgumentAsTimeout",Ir.ArgumentAsDayOfWeek="ArgumentAsDayOfWeek",Ir.ArgumentAsDaysOfWeek="ArgumentAsDaysOfWeek",Ir.ArgumentAsAstronomicalClock="ArgumentAsAstronomicalClock",Ir.ArgumentAsTime="ArgumentAsTime",Ir.ArgumentAsDeviceState="ArgumentAsDeviceState",Ir.ArgumentAsNumber="ArgumentAsNumber",Ir.ArgumentAsAstronomicalClockWithOffset="ArgumentAsAstronomicalClockWithOffset",Ir.ArgumentAsConditionInfo="ArgumentAsConditionInfo";class qr extends Error{constructor(e){super(e),this.message=e,this.name="UnsupportedScenesDeviceState"}}!function(e){e[e.Device=0]="Device",e[e.Controller=1]="Controller"}(Nr||(Nr={}));class Vr{constructor(){this.UpdateGuid="",this.Channel="",this.Version="",this.CurrentVersion="",this.DownloadUri="",this.Download="",this.Name="",this.Description="",this.UpdateType=Er.Unknown,this.ResourceGuid=""}}class Hr{constructor(){this.UpdateDescription=new Map,this.Update=new Vr,this.UpdatedResourceName="",this.CurrentResourceVersion=""}}!function(e){e[e.Unknown=0]="Unknown",e[e.Container=1]="Container",e[e.RadioFirmware=2]="RadioFirmware",e[e.DeviceFirmware=3]="DeviceFirmware",e[e.Configuration=4]="Configuration",e[e.ContainerScript=5]="ContainerScript",e[e.ContainerSoftware=6]="ContainerSoftware",e[e.RuntimeSoftware=7]="RuntimeSoftware",e[e.RuntimeScript=8]="RuntimeScript",e[e.RuntimeFixingScript=9]="RuntimeFixingScript"}(Er||(Er={}));class jr extends Error{constructor(e){super(e),this.message=e,this.name="UpdateProviderNotFound"}}var Kr,zr,Jr,Yr=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class Xr{constructor(){this._services=new Map,this._runtimeInfo=new Qr,this._hardwareInfo=new eo,this._semaphore=new Xe(1),this._isRuntimeInfoInitialized=!1,this._isHardwareInfoInitialized=!1}GetServiceName(){return Xr.ServiceName}RegisterUpdatesProvider(e){Ov.Get(s.ServiceName).Debug(Xr.ServiceName,`Registering new update provider: ${e.GetUpdateProviderName()}`),this._services.set(e.GetUpdateProviderName(),e)}GetUpdatesProviderAsync(e){return Yr(this,void 0,void 0,(function*(){Ov.Get(s.ServiceName).Debug(Xr.ServiceName,`Getting update provider [${e}] by GetUpdateProviderAsync<T>()`);const t=this._services.get(e);if(null==t)throw new jr("Cannot get update provider! Requested update provider has not been registered.");return t}))}GetUpdatesProvidersAsync(e){return Yr(this,void 0,void 0,(function*(){Ov.Get(s.ServiceName).Debug(Xr.ServiceName,`Getting update providers with type ${e} by GetUpdateProvidersAsync<T>()`);let t=[];if(t=[...this._services.values()].filter((t=>t.ProviderType==e)),0==t.length)throw new jr("Cannot get update providers! Requested update providers has not been registered.");return t}))}GetUpdatesProvidersByProtocolAsync(e,t,n){return Yr(this,void 0,void 0,(function*(){if(new RegExp("^[{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]?$").test(e)){Ov.Get(s.ServiceName).Debug(Xr.ServiceName,`Getting update providers with protocol guid: [${e}] by GetUpdateProvidersByProtocolAsync<T>()`);let r=[];if(r=null!=n?[...this._services.values()].filter((s=>s.ProtocolGuid==e&&s.ProviderType==t&&s.AvailableExtensionVersion==n)):[...this._services.values()].filter((n=>n.ProtocolGuid==e&&n.ProviderType==t)),0==r.length)throw new jr("Cannot get update providers! Requested update providers has not been registered.");return r}throw new jr("Cannot get update providers! Bad parameters.")}))}GetUpdatesProvidersByExtensionAsync(e,t,n){return Yr(this,void 0,void 0,(function*(){if(new RegExp("^[{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]?$").test(e)){Ov.Get(s.ServiceName).Debug(Xr.ServiceName,`Getting update providers with extension guid: [${e}] by GetUpdateProvidersByExtensionAsync<T>()`);let r=[];if(r=null!=n?[...this._services.values()].filter((s=>s.ExtensionGuid==e&&s.ProviderType==t&&s.AvailableExtensionVersion==n)):[...this._services.values()].filter((n=>n.ExtensionGuid==e&&n.ProviderType==t)),0==r.length)throw new jr("Cannot get update providers! Requested update providers has not been registered.");return r}throw new jr("Cannot get update providers! Bad parameters.")}))}GetSoftwareRuntimeInfoAsync(){return Yr(this,arguments,void 0,(function*(e=!1){var t=yield this._semaphore.AcquireAsync();return!this._isRuntimeInfoInitialized||e?(yield this.GetRuntimeControllerInfoAsync(),t.Release(),this._runtimeInfo):(t.Release(),this._runtimeInfo)}))}GetRuntimeControllerInfoAsync(){return Yr(this,void 0,void 0,(function*(){Ov.Get(s.ServiceName).Debug(Xr.ServiceName,"Getting runtime version info from controller.");try{const e=yield Ov.Get(Pt.ServiceName).SendAndWaitForResponseAsync(new Zr,16e3,!1);if(null==e||null==e.Status)throw new no('Cannot get runtime info, controller response result is empty."',Kr.EmptyResponse);if(e.Status!=ce.OK)throw new no(`Cannot get runtime info, controller responded with status ${e.Status}.`,Kr.WrongResponseStatus);if(null==e.Data)throw new no("Cannot get runtime info, controller responded with status OK but response does not contains data.",Kr.NoDataInResponse);this._runtimeInfo=e.Data,this._isRuntimeInfoInitialized=!0}catch(e){throw e instanceof g?new no("Cannot get runtime info, controller response timeout.",Kr.Timeout):e}}))}GetHardwareInfoAsync(){return Yr(this,arguments,void 0,(function*(e=!1){return!this._isHardwareInfoInitialized||e?(yield this.GetHardwareControllerInfoAsync(),this._hardwareInfo):this._hardwareInfo}))}GetHardwareControllerInfoAsync(){return Yr(this,void 0,void 0,(function*(){Ov.Get(s.ServiceName).Debug(Xr.ServiceName,"Getting hardware info from controller.");const e=yield Ov.Get(Pt.ServiceName).SendAndWaitForResponseAsync(new to,8e3,!1);if(null==e||null==e.Status)throw new no('Cannot get hardware info, controller response result is empty."',Kr.EmptyResponse);if(e.Status!=ce.OK)throw new no(`Cannot get hardware info, controller responded with status ${e.Status}.`,Kr.WrongResponseStatus);if(null==e.Data)throw new no("Cannot get hardware info, controller responded with status OK but response does not contains data.",Kr.NoDataInResponse);this._hardwareInfo=e.Data,this._isRuntimeInfoInitialized=!0}))}}Xr.ServiceName="UpdateProvider";class Qr{constructor(){this.BaseLinuxVersion="",this.BaseMonoVersion="",this.RuntimeVersion="",this.UpdateChannel="",this.SoftwareVersion=""}}class Zr extends ae{constructor(){super(),this.Resource="/controller/software/info",this.Method=ue.Get}}class eo{constructor(){this.GetControllerHardwareVersion=0,this.DevicePIN="",this.GetControllerSerialNumber="",this.HostnamePrefix="",this.DefaultStaticIpAddress="",this.GetAvailableHardware=[],this.ControllerSecret=""}}class to extends ae{constructor(){super(),this.Resource="/controller/hardware/info",this.Method=ue.Get}}class no extends Error{constructor(e,t){super(e),this.message=e,this.code=0,this.name="CannotGetRuntimeInfo",this.code=t}}!function(e){e[e.Unknown=0]="Unknown",e[e.EmptyResponse=1]="EmptyResponse",e[e.NoDataInResponse=2]="NoDataInResponse",e[e.WrongResponseStatus=3]="WrongResponseStatus",e[e.Timeout=4]="Timeout"}(Kr||(Kr={})),function(e){e[e.None=0]="None",e[e.AppNotification=1]="AppNotification",e[e.Email=2]="Email"}(zr||(zr={})),function(e){e[e.Timeout=0]="Timeout",e[e.TimeRange=1]="TimeRange"}(Jr||(Jr={}));var so,ro,oo,io;class ao{constructor(e,t="Cube"){this._result=null,this._tmp=new co,this._tmpTask=null,this._prevSeqGuid="",this._currentSeqGuid="",this._editingExistingSequence=!1,this._rawExistingSequenceTasks=null,this._sequenceName="",this._sequenceIcon="",this._service=Ov.Get(Do.ServiceName),e&&(this._sequenceName=e,this._sequenceIcon=t,this._tmp.Guid=xs.NewGuid())}SetSequenceName(e){this._sequenceName=e,this._editingExistingSequence&&null!=this._result&&(this._result.Name=e)}SetSequenceIcon(e){this._sequenceIcon=e,this._editingExistingSequence&&null!=this._result&&(this._result.Icon=e)}GetNext(){if(null==this._result)return null;if(""==this._currentSeqGuid)return this._currentSeqGuid=this._result.Guid,this._service.MapSequence(JSON.parse(JSON.stringify(this._result)),!0);{const e=this.FindArgumentWithGuid(this._result,this._currentSeqGuid);return null==e?null:e.RightArgumentType==io.Condition?(this._prevSeqGuid=this._currentSeqGuid,this._currentSeqGuid=e.RightArgument.Guid,this._service.MapSequence(JSON.parse(JSON.stringify(e.RightArgument)),!0)):null}}CloneCurrentBuilder(){var e=new ao;return e._currentSeqGuid="",e._prevSeqGuid="",e._editingExistingSequence=structuredClone(this._editingExistingSequence),e._rawExistingSequenceTasks=structuredClone(this._rawExistingSequenceTasks),e._result=structuredClone(this._result),e._sequenceIcon=structuredClone(this._sequenceIcon),e._sequenceName=structuredClone(this._sequenceName),e._tmp=structuredClone(this._tmp),(e=>{const t=e=>{e.Guid=xs.NewGuid(),e.RightArgumentType==io.Condition&&t(e.RightArgument)};null!=e._result&&t(e._result),null!=this._tmp&&(this._tmp.Guid=xs.NewGuid())})(e),e}GetPrevious(){let e="";const t=(n,s)=>n.Guid==s?{sequence:n,prevGuid:e}:n.RightArgumentType==io.Condition?(e=n.Guid,t(n.RightArgument,s)):null;if(null==this._result)return null;if(""==this._currentSeqGuid||""==this._prevSeqGuid)return null;const n=t(this._result,this._prevSeqGuid);return null==n?null:(this._currentSeqGuid=n.sequence.Guid,this._prevSeqGuid=n.prevGuid,this._service.MapSequence(JSON.parse(JSON.stringify(n.sequence)),!0))}GetByGuid(e){if(null==this._result)return null;const t=this.FindArgumentWithGuid(this._result,e);return null==t?null:this._service.MapSequence(t)}EditCurrentSequence(e){const t=e=>{if(e.RightArgumentType!=io.Null)return t(e.RightArgument);this._rawExistingSequenceTasks=JSON.parse(JSON.stringify(e.Tasks))};return this._editingExistingSequence=!0,t(e._rawRequestData),Object.hasOwn(e._rawRequestData,"Condition")?this._result=e._rawRequestData.Condition:this._result=e._rawRequestData,{GetNext:()=>this.GetNext(),GetPrevious:()=>this.GetPrevious(),GetByGuid:e=>this.GetByGuid(e),GetAllowedArguments:()=>this.GetAllowedArguments(),RemoveSequence:e=>this.RemoveSequenceByGuid(e),ArgumentAsAstronomicalClockWithOffset:(e,t,n)=>this.ArgumentAsAstronomicalClockWithOffset(e,t,n),ArgumentAsDaysOfWeek:(e,t,n)=>this.ArgumentAsDaysOfWeek(e,t,n),ArgumentAsDeviceState:(e,t,n,s=Dr.Equal)=>this.ArgumentAsDeviceState(e,t,n,s),ArgumentAsTime:(e,t,n=Dr.Equal)=>this.ArgumentAsTime(e,t,n),ArgumentAsTimeSpan:(e,t)=>this.ArgumentAsTimeSpan(e,t),ArgumentAsSceneExecuted:e=>this.ArgumentAsSceneExecuted(e),RemoveTask:e=>this.RemoveTask(e)}}ArgumentAsAstronomicalClockWithOffset(e,t,n){if(this._tmp.Guid=xs.NewGuid(),this._tmp.HandledType=Tr.AstronomicalClockWithOffset,this._tmp.LeftArgumentType=io.ArgumentAsAstronomicalClockWithOffset,this._tmp.AtMeetCondition=t,t&&null!=n&&n!=Dr.Equal)throw new wo("AtmeetCondition supports only comparation type 'Equal'.");if(e.Offset<-3600||e.Offset>3600)throw new wo("Offset must be in range between -3600 and 3600 seconds.");if(t)this._tmp.ConditionType=Dr.Equal;else{if(null==n)throw new wo("Comparasion type must be provided if atMeetCondition is false!");this._tmp.ConditionType=n}return this._tmp.LeftArgument.Argument=e,this._tmp.LeftArgument.HandledType=io.ArgumentAsAstronomicalClockWithOffset,{AddArgument:()=>this.AddSequence(),EditArgument:e=>this.EditSequence(e)}}ArgumentAsActionWithEmptyCondition(){return this._tmp.Guid=xs.NewGuid(),this._tmp.HandledType=Tr.Unknown,this._tmp.LeftArgumentType=io.Null,this._tmp.ConditionType=Dr.Equal,this._tmp.LeftArgument.Argument=null,this._tmp.LeftArgument.HandledType=io.Null,this._tmp.Name=this._sequenceName,this._tmp.Icon=this._sequenceIcon,this._tmp.AtMeetCondition=!1,{AddArgument:()=>this.AddSequence(),EditArgument:e=>this.EditSequence(e)}}ArgumentAsDaysOfWeek(e,t,n=Dr.Equal){return this._tmp.Guid=xs.NewGuid(),this._tmp.HandledType=Tr.DaysOfWeek,this._tmp.LeftArgumentType=io.ArgumentAsDaysOfWeek,this._tmp.ConditionType=n,this._tmp.LeftArgument.Argument=e,this._tmp.LeftArgument.HandledType=io.ArgumentAsDaysOfWeek,this._tmp.AtMeetCondition=t,{AddArgument:()=>this.AddSequence(),EditArgument:e=>this.EditSequence(e)}}ArgumentAsTimeSpan(e,t=Dr.Equal){return this._tmp.Guid=xs.NewGuid(),this._tmp.HandledType=Tr.Timer,this._tmp.LeftArgumentType=io.ArgumentAsTimeSpan,this._tmp.ConditionType=t,this._tmp.AtMeetCondition=!0,this._tmp.LeftArgument.Argument=e,this._tmp.LeftArgument.HandledType=io.ArgumentAsTimeSpan,{AddArgument:()=>this.AddSequence(),EditArgument:e=>this.EditSequence(e)}}ArgumentAsTime(e,t,n=Dr.Equal){return this._tmp.Guid=xs.NewGuid(),this._tmp.HandledType=Tr.Time,this._tmp.LeftArgumentType=io.ArgumentAsTime,this._tmp.ConditionType=n,this._tmp.AtMeetCondition=t,this._tmp.LeftArgument.Argument=e,this._tmp.LeftArgument.HandledType=io.ArgumentAsTime,{AddArgument:()=>this.AddSequence(),EditArgument:e=>this.EditSequence(e)}}ArgumentAsDeviceState(e,t,n,s=Dr.Equal){return this._tmp.Guid=xs.NewGuid(),this._tmp.HandledType=Tr.DeviceState,this._tmp.LeftArgumentType=io.ArgumentAsDeviceState,this._tmp.ConditionType=s,this._tmp.AtMeetCondition=t,this._tmp.ConditionTimeout=n,this._tmp.LeftArgument.Argument=this.GenerateDeviceStateArgument(e),this._tmp.LeftArgument.HandledType=io.ArgumentAsDeviceState,{AddArgument:()=>this.AddSequence(),EditArgument:e=>this.EditSequence(e)}}ArgumentAsSceneExecuted(e){this._tmp.Guid=xs.NewGuid(),this._tmp.HandledType=Tr.SceneExecuted,this._tmp.LeftArgumentType=io.ArgumentAsConditionInfo,this._tmp.ConditionType=Dr.Equal,this._tmp.AtMeetCondition=!0;const t=new $r;return t.DeviceGuid=e.DeviceGuid,this._tmp.LeftArgument.Argument=t,this._tmp.LeftArgument.HandledType=io.ArgumentAsConditionInfo,{AddArgument:()=>this.AddSequence(),EditArgument:e=>this.EditSequence(e)}}GenerateDeviceStateArgument(e){const t=new ho;t.Channel=e.GetCheckDeviceState().Channel,t.ComparisonMethod=e.ComparisonMethod;let n={},s=e.GetComparisonParams().entries();for(const[e,t]of s)n=Object.assign(Object.assign({},n),{[Sr[e]]:t.Value});switch(t.ComparisonParams=n,t.DeviceGuid=e.DeviceGuid,t.DeviceStateType=this.MapResponseTypeToDeviceStateType(e.Type),e.Type){case At.BatteryState:t.CheckedDeviceState.State=e.GetCheckDeviceState().State,t.CheckedDeviceState.Percentage=e.GetCheckDeviceState().Percentage;break;case At.BinarySensorState:t.CheckedDeviceState.State=e.GetCheckDeviceState().State;break;case At.BlindPosition:t.CheckedDeviceState.Position=e.GetCheckDeviceState().Position;break;case At.LightBrightness:case At.MeasuredBrightness:t.CheckedDeviceState.Brightness=e.GetCheckDeviceState().Brightness;break;case At.RemoteButtonState:case At.ChannelOnOffState:case At.DoorBellState:t.CheckedDeviceState.State=e.GetCheckDeviceState().State;break;case At.MeasuredEnergy:{let n={},s=e.GetCheckDeviceState().MeasurementParameters.entries();for(const[e,t]of s)n=Object.assign(Object.assign({},n),{[jt[e]]:t});t.CheckedDeviceState.MeasurementParameters=n;break}case At.FloodSensorState:t.CheckedDeviceState.State=e.GetCheckDeviceState().State;break;case At.GatePosition:t.CheckedDeviceState.Position=e.GetCheckDeviceState().Position,t.CheckedDeviceState.PositionType=e.GetCheckDeviceState().PositionType;break;case At.LightColor:{const n=e.GetCheckDeviceState();t.CheckedDeviceState.R=n.R,t.CheckedDeviceState.G=n.G,t.CheckedDeviceState.B=n.B;break}case At.LightWarmth:t.CheckedDeviceState.Temperature=e.GetCheckDeviceState().Temperature;break;case At.ReedState:t.CheckedDeviceState.State=e.GetCheckDeviceState().State;break;case At.SmokeSensorState:throw new qr("Unsupported device state!");case At.MeasuredTemperature:t.CheckedDeviceState.Temperature=e.GetCheckDeviceState().Temperature;break;case At.HumiditySensorState:t.CheckedDeviceState.Humidity=e.GetCheckDeviceState().Humidity;break;case At.BlindRemoteButtonState:t.CheckedDeviceState.State=e.GetCheckDeviceState().State;break;case At.LightRGBWState:{let n=e.GetCheckDeviceState();t.CheckedDeviceState.R=n.R,t.CheckedDeviceState.G=n.G,t.CheckedDeviceState.B=n.B,t.CheckedDeviceState.W=n.W;break}case At.FacadeRemoteButtonState:t.CheckedDeviceState.State=e.GetCheckDeviceState().State;break;case At.MovementSensorState:{let n=e.GetCheckDeviceState();t.CheckedDeviceState.Movement=n.Movement,t.CheckedDeviceState.Intensity=n.Intensity;break}case At.PressureSensorState:t.CheckedDeviceState.Pressure=e.GetCheckDeviceState().Pressure,t.CheckedDeviceState.PressureType=e.GetCheckDeviceState().PressureType;break;case At.WindSpeedState:t.CheckedDeviceState.Value=e.GetCheckDeviceState().Value;break;case At.CurrentWindThreshold:t.CheckedDeviceState.WindThreshold=e.GetCheckDeviceState().WindThreshold;break;case At.Unknown:t.CheckedDeviceState={};break;default:throw new qr("Unsupported device state!")}return t}MapResponseTypeToDeviceStateType(e){switch(e){case At.BatteryState:return kr.BatteryState;case At.BinarySensorState:return kr.BinarySensor;case At.BlindPosition:return kr.BlindPosition;case At.LightBrightness:return kr.LightBrightness;case At.RemoteButtonState:return kr.ButtonState;case At.ChannelOnOffState:return kr.ChannelOnOff;case At.DoorBellState:return kr.DoorBell;case At.MeasuredEnergy:return kr.Energy;case At.FloodSensorState:return kr.FloodSensor;case At.GatePosition:return kr.GatePosition;case At.MeasuredBrightness:return kr.Brightness;case At.LightColor:return kr.LightColor;case At.LightWarmth:return kr.LightTemperature;case At.ReedState:return kr.ReedState;case At.SmokeSensorState:return kr.SmokeSensor;case At.MeasuredTemperature:return kr.Temperature;case At.HumiditySensorState:return kr.Humidity;case At.BlindRemoteButtonState:return kr.BlindsControlButton;case At.FacadeRemoteButtonState:return kr.FacadeControlButton;case At.MovementSensorState:return kr.Movement;case At.PressureSensorState:return kr.AirPressure;case At.WindSpeedState:return kr.WindSpeed;case At.CurrentWindThreshold:return kr.WindThreshold;default:return kr.Unknown}}AddSequence(){const e=(t,n)=>{if(t.RightArgumentType!=io.Null)return e(t.RightArgument,n);t.RightArgumentType=io.Condition,t.RightArgument=n,this._editingExistingSequence&&null!=this._rawExistingSequenceTasks&&(n.Tasks=JSON.parse(JSON.stringify(this._rawExistingSequenceTasks)),t.Tasks=new go)};null==this._result?(this._tmp.Name=this._sequenceName,this._tmp.Icon=this._sequenceIcon,this._result=this._tmp,this._result.AtMeetCondition=!0):e(this._result,this._tmp);const t=this._service.MapSequence(JSON.parse(JSON.stringify(this._tmp)));return this._tmp=new co,{GetNext:()=>this.GetNext(),GetPrevious:()=>this.GetPrevious(),GetByGuid:e=>this.GetByGuid(e),GetAllowedArguments:()=>this.GetAllowedArguments(),RemoveSequenceByGuid:e=>this.RemoveSequenceByGuid(e),Commit:()=>this.Commit(),ArgumentAsActionWithEmptyCondition:()=>this.ArgumentAsActionWithEmptyCondition(),ArgumentAsAstronomicalClockWithOffset:(e,t,n)=>this.ArgumentAsAstronomicalClockWithOffset(e,t,n),ArgumentAsDaysOfWeek:(e,t,n)=>this.ArgumentAsDaysOfWeek(e,t,n),ArgumentAsDeviceState:(e,t,n,s=Dr.Equal)=>this.ArgumentAsDeviceState(e,t,n,s),ArgumentAsTime:(e,t,n=Dr.Equal)=>this.ArgumentAsTime(e,t,n),ArgumentAsTimeSpan:(e,t)=>this.ArgumentAsTimeSpan(e,t),ArgumentAsSceneExecuted:e=>this.ArgumentAsSceneExecuted(e),SequenceData:t}}EditSequence(e){const t=(n,s)=>{if(n.Guid!=e||n.ObjectType!=io.Condition){if(n.RightArgumentType==io.Condition)return t(n.RightArgument,s);throw new So(`Cannot edit sequence with given GUID ${e} - sequence not foud in chain`)}n.AtMeetCondition=s.AtMeetCondition,n.ConditionTimeout=s.ConditionTimeout,n.ConditionType=s.ConditionType,n.ExecuteOnce=s.ExecuteOnce,n.HandledType=s.HandledType,n.IsDisabled=s.IsDisabled,n.LeftArgument=s.LeftArgument,n.LeftArgumentType=s.LeftArgumentType,n.ObjectType=s.ObjectType,n.Tasks=s.Tasks,s.Guid=n.Guid,s.Icon=n.Icon,s.Name=n.Name};if(null==this._result)throw new So(`Cannot edit sequence with given GUID ${e} - sequence not initialized (no root element)`);t(this._result,this._tmp);const n=this._service.MapSequence(JSON.parse(JSON.stringify(this._tmp)));return this._tmp=new co,console.log(`new tmp guid: ${this._tmp.Guid}`),this._result.AtMeetCondition||(this._result.AtMeetCondition=!0),{GetNext:()=>this.GetNext(),GetPrevious:()=>this.GetPrevious(),GetByGuid:e=>this.GetByGuid(e),GetAllowedArguments:()=>this.GetAllowedArguments(),RemoveSequenceByGuid:e=>this.RemoveSequenceByGuid(e),Commit:()=>this.Commit(),ArgumentAsActionWithEmptyCondition:()=>this.ArgumentAsActionWithEmptyCondition(),ArgumentAsAstronomicalClockWithOffset:(e,t,n)=>this.ArgumentAsAstronomicalClockWithOffset(e,t,n),ArgumentAsDaysOfWeek:(e,t,n)=>this.ArgumentAsDaysOfWeek(e,t,n),ArgumentAsDeviceState:(e,t,n,s=Dr.Equal)=>this.ArgumentAsDeviceState(e,t,n,s),ArgumentAsTime:(e,t,n=Dr.Equal)=>this.ArgumentAsTime(e,t,n),ArgumentAsTimeSpan:(e,t)=>this.ArgumentAsTimeSpan(e,t),ArgumentAsSceneExecuted:e=>this.ArgumentAsSceneExecuted(e),SequenceData:n}}RemoveSequenceByGuid(e){let t;const n=(e,n)=>{""==this._currentSeqGuid&&""==this._prevSeqGuid||(this._currentSeqGuid==n?(this._currentSeqGuid=e.RightArgumentType==io.Condition?e.RightArgument.Guid:"",this._prevSeqGuid=null!=t?t.Guid:""):this._prevSeqGuid==n&&(this._prevSeqGuid=null!=t?t.Guid:""))},s=(e,r)=>{if(e.Guid!=r){if(t=e,e.RightArgumentType==io.Null)throw new So(`Cannot remove sequence, sequence with given guid ${r} not found!`);return s(e.RightArgument,r)}null==t?this._result=null:(t.RightArgument=e.RightArgument,t.RightArgumentType=e.RightArgumentType),n(e,r)};if(null==this._result)throw new So("Cannot remove sequence, sequence not configured!");return this._result.Guid==e&&this._result.RightArgumentType!=io.Null?(this._result.RightArgument.Name=this._result.Name,this._result.RightArgument.Icon=this._result.Icon,this._result.RightArgument.Guid=this._result.Guid,this._result=this._result.RightArgument,this._result.AtMeetCondition=!0,n(this._result,e)):s(this._result,e),{GetNext:()=>this.GetNext(),GetPrevious:()=>this.GetPrevious(),GetByGuid:e=>this.GetByGuid(e),GetAllowedArguments:()=>this.GetAllowedArguments(),RemoveSequenceByGuid:e=>this.RemoveSequenceByGuid(e),Commit:()=>this.Commit(),ArgumentAsActionWithEmptyCondition:()=>this.ArgumentAsActionWithEmptyCondition(),ArgumentAsAstronomicalClockWithOffset:(e,t,n)=>this.ArgumentAsAstronomicalClockWithOffset(e,t,n),ArgumentAsDaysOfWeek:(e,t,n)=>this.ArgumentAsDaysOfWeek(e,t,n),ArgumentAsDeviceState:(e,t,n,s=Dr.Equal)=>this.ArgumentAsDeviceState(e,t,n,s),ArgumentAsTime:(e,t,n=Dr.Equal)=>this.ArgumentAsTime(e,t,n),ArgumentAsTimeSpan:(e,t)=>this.ArgumentAsTimeSpan(e,t),ArgumentAsSceneExecuted:e=>this.ArgumentAsSceneExecuted(e),SequenceData:null}}Commit(){const e=t=>{if(t.RightArgumentType!=io.Null)return e(t.RightArgument);null!=this._rawExistingSequenceTasks&&(t.Tasks=this._rawExistingSequenceTasks)};if(null==this._result)throw new So("Sequence are not initialized! Not found root sequence.");return this._editingExistingSequence&&e(this._result),{GetSupportedTypesOfTasks:()=>this.GetSupportedTaskTypesAsync(),DeviceTask:e=>this.DeviceTask(e),DelayTask:e=>this.DelayTask(e),NotifyTask:(e,t)=>this.NotifyTask(e,t),LockExecutionTask:e=>this.LockExecutionTask(e),RemoveTask:e=>this.RemoveTask(e),Build:()=>this.Build(),BuildToISequence:()=>this._service.MapSequence(JSON.parse(JSON.stringify(this._result))),ValidateScene:()=>this.ValidateScene()}}DeviceTask(e){if(this._tmpTask=this.ParseDeviceTask(e),null==this._result)throw new Error("No context!");return{AddTask:()=>this.AddTask(),EditTask:e=>this.EditTask(e),TaskId:re.GenerateMd5(JSON.stringify(this._tmpTask))}}ParseDeviceTask(e){const t=new fo;return t.Channel=e.Channel,t.DeviceGuid=e.DeviceGuid,t.ControlFeature=this.MapTaskTypeToControlFeature(e.TaskType),t.Data={},t.Data.Channel=e.Channel,e.TaskType==St.SetBlindPosition||e instanceof Ks?(t.Data.Position=e.Position,t.Data.Action=e.Action):e.TaskType==St.SetLightColor||e instanceof Hs?(t.Data.R=e.R,t.Data.G=e.G,t.Data.B=e.B):e.TaskType==St.SetLightTemperature||e instanceof js?t.Data.Temperature=e.Temperature:e.TaskType==St.SetLightBrightness||e instanceof qs?t.Data.Brightness=e.Brightness:e.TaskType==St.SetTemperature||e instanceof Ls?t.Data.Temperature=e.Temperature:e.TaskType==St.TurnOnWithTime||e instanceof $s?t.Data.SwitchOffDelaySeconds=e.SwitchOffDelaySeconds:e.TaskType==St.SetLightBrightnessDynamicly||e instanceof zs?t.Data.Brightness=e.Brightness:e.TaskType==St.SetBlindOpenCloseTime||e instanceof Ys?(t.Data.CloseTime=e.Data.CloseTime,t.Data.OpenTime=e.Data.OpenTime):e.TaskType==St.SetBlindMicroventilation||e instanceof Zs?t.Data.Position=e.Position:e.TaskType==St.SetFacadePosition||e instanceof nr?(t.Data.FacadeAction=e.FacadeAction,t.Data.Position=e.Position,t.Data.Tilt=e.Tilt):(e.TaskType==St.LightRGBW||e instanceof or)&&(t.Data.R=e.Data.R,t.Data.G=e.Data.G,t.Data.B=e.Data.B,t.Data.W=e.Data.W,t.Data.Brightness=e.Data.Brightness),t}DelayTask(e){const t=new vo;if(t.Delay=e.Delay.Value,this._tmpTask=t,null==this._result)throw new Error("No context!");return{AddTask:()=>this.AddTask(),EditTask:e=>this.EditTask(e),TaskId:re.GenerateMd5(JSON.stringify(t))}}NotifyTask(e,t){if(e.NotifyType==zr.Email)throw new _o("NotifyType 'Email' is not supported!");if(e.NotifyType==zr.None)throw new Error("NotifyType mus be set!");if(""==e.Message)throw new wo("Message must be set!");if(e.Message.length>1e3)throw new wo("Message is too long! Max length is 1000 characters.");const n=new yo;if(n.NotifyType=e.NotifyType,n.Message=e.Message,n.Title=this._sequenceName,null!=t&&t.length>0&&(n.NotificationClients=t),this._tmpTask=n,null==this._result)throw new Error("No context!");return{AddTask:()=>this.AddTask(),EditTask:e=>this.EditTask(e),TaskId:re.GenerateMd5(JSON.stringify(n))}}LockExecutionTask(e){const t=new mo;if(t.LockType=e.LockType,t.LockType==Jr.Timeout&&"00:00:00"!=t.LockEndHour)throw new _o("Parameter LockEndHour at lock type `Timeout` must be default!");if(t.LockStartHour=e.LockStartHour.Value,t.LockEndHour=e.LockEndHour.Value,t.ResetLockScenesGuids=e.ResetLockScenesGuids,this._tmpTask=t,null==this._result)throw new Error("No context!");return{AddTask:()=>this.AddTask(),EditTask:e=>this.EditTask(e),TaskId:re.GenerateMd5(JSON.stringify(t))}}AddTask(){const e=t=>{if(t.RightArgumentType!=io.Null)return e(t.RightArgument);if(null==this._tmpTask)throw Error("No task context!");void 0!==t.Tasks.DevicesTasks&&null!==t.Tasks.DevicesTasks||(t.Tasks.DevicesTasks=[]),this._tmpTask instanceof fo&&t.Tasks.DevicesTasks.push(structuredClone(this._tmpTask)),t.Tasks.ControllerTasks.push(structuredClone(this._tmpTask)),this._tmpTask=null,Ov.Get(s.ServiceName).Debug(`Task added to sequence: \n${JSON.stringify(this._tmpTask)} \ntasks on a list: \n${JSON.stringify(t.Tasks)}`)};if(null==this._result)throw new Error("No context!");return e(this._result),{GetSupportedTypesOfTasks:()=>this.GetSupportedTaskTypesAsync(),DeviceTask:e=>this.DeviceTask(e),DelayTask:e=>this.DelayTask(e),NotifyTask:(e,t)=>this.NotifyTask(e,t),LockExecutionTask:e=>this.LockExecutionTask(e),RemoveTask:e=>this.RemoveTask(e),Build:()=>this.Build(),BuildToISequence:()=>this._service.MapSequence(JSON.parse(JSON.stringify(this._result))),ValidateScene:()=>this.ValidateScene()}}EditTask(e){const t=n=>{if(n.RightArgumentType!=io.Null)return t(n.RightArgument);if(null==this._tmpTask)throw Error("No task context!");if(null==n.Tasks.ControllerTasks||0==n.Tasks.ControllerTasks.length)throw new Ao("Task not found, cannot edit!");this._tmpTask instanceof fo&&null!=n.Tasks.DevicesTasks&&(n.Tasks.DevicesTasks=n.Tasks.DevicesTasks.map((t=>re.GenerateMd5(JSON.stringify(t))==e?structuredClone(this._tmpTask):t))),n.Tasks.ControllerTasks=n.Tasks.ControllerTasks.map((t=>re.GenerateMd5(JSON.stringify(t))==e?structuredClone(this._tmpTask):t)),this._tmpTask=null,Ov.Get(s.ServiceName).Debug(`Task edited in sequence: \n${JSON.stringify(this._tmpTask)} \ntasks on a list: \n${JSON.stringify(n.Tasks)}`)};if(null==this._result)throw new Error("No context!");return t(this._result),{GetSupportedTypesOfTasks:()=>this.GetSupportedTaskTypesAsync(),DeviceTask:e=>this.DeviceTask(e),DelayTask:e=>this.DelayTask(e),NotifyTask:(e,t)=>this.NotifyTask(e,t),LockExecutionTask:e=>this.LockExecutionTask(e),RemoveTask:e=>this.RemoveTask(e),Build:()=>this.Build(),BuildToISequence:()=>this._service.MapSequence(JSON.parse(JSON.stringify(this._result))),ValidateScene:()=>this.ValidateScene()}}RemoveTask(e){const t=(e,n)=>{if(e.RightArgumentType!=io.Null)return t(e.RightArgument,n);{const t=e.Tasks.ControllerTasks.filter((e=>re.GenerateMd5(JSON.stringify(e))!=n));if(e.Tasks.ControllerTasks=null==t?[]:t,e.Tasks.DevicesTasks.any()){const t=e.Tasks.DevicesTasks.filter((e=>re.GenerateMd5(JSON.stringify(e))!=n));e.Tasks.DevicesTasks=null==t?[]:t}}};if(null==this._result)throw Error("Cannot remove task, sequence not configured!");t(this._result,e)}MapTaskTypeToControlFeature(e){switch(e){case St.Unknown:throw new wo("Unsupported task type!");case St.SetBlindPosition:case St.SetBlindPositionSimple:return Gs.SetBlindPosition;case St.SetBlindMicroventilation:return Gs.SetBlindMicroventilation;case St.TurnOff:return Gs.TurnOff;case St.TurnOn:return Gs.TurnOn;case St.TurnOnWithTime:return Gs.TurnOnWithTimeout;case St.TogleState:return Gs.ToggleState;case St.SetLightBrightnessDynamicly:return Gs.SetLightBrightnessDynamicly;case St.SetLightBrightness:return Gs.SetLightBrightness;case St.SetLightColor:return Gs.SetLightColor;case St.SetLightTemperature:return Gs.SetLightTemperature;case St.PairDevice:case St.UnpairDevice:throw new wo("Unsupported task type!");case St.IdentifyDevice:return Gs.IdentifyDevice;case St.GetChannelsState:return Gs.GetState;case St.GetPowerMeasurements:case St.GetAvailableData:case St.MultipleDataRequest:throw new wo("Unsupported task type!");case St.SetBlindOpenCloseTime:return Gs.SetBlindOpenCloseTime;case St.SetTemperature:return Gs.SetTemperature;case St.ChangeGatePositionPulse:return Gs.GatePulse;case St.ChangeGatewayPositionPulse:return Gs.GatewayPulse;case St.SetFacadePosition:case St.GetFacadeType:return Gs.SetFacadePositionAndTilt;case St.LightRGBW:return Gs.LightRGBW;default:throw new wo("Unsupported task type!")}}GetSupportedTaskTypesAsync(){return e=this,t=void 0,s=function*(){const e=yield Ov.Get(Xr.ServiceName).GetSoftwareRuntimeInfoAsync(),[t,n]=e.SoftwareVersion.split(".").map((e=>parseInt(e))),s=[ro.DeviceTask];return t>=5&&n>=27&&s.push(ro.DelayTask),t>=5&&n>=37&&s.push(ro.LockExecutionTask),t>=5&&n>=106&&s.push(ro.NotifyTaskAppNotify),s},new((n=void 0)||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}));var e,t,n,s}Build(){const e=t=>{if(t.RightArgumentType!=io.Null)return e(t.RightArgument);t.Tasks.ControllerTasks=t.Tasks.ControllerTasks.map((e=>(Object.hasOwn(e,"_taskGuid")&&delete e._taskGuid,e)))};if(null!=this._result)return e(this._result),this._result;throw Error("Cannot build sequence, sequence not configured!")}FindArgumentWithGuid(e,t){return e.Guid==t?e:e.RightArgumentType==io.Condition?this.FindArgumentWithGuid(e.RightArgument,t):null}GetAllowedArguments(){const e=[];return null==this._result?(e.push({ArgumentType:oo.ArgumentAsAstronomicalClockWithOffset,InitialAtMeetConditionValue:!0,ChangableAtMeetCondition:!1}),e.push({ArgumentType:oo.ArgumentAsDaysOfWeek,InitialAtMeetConditionValue:!0,ChangableAtMeetCondition:!1}),e.push({ArgumentType:oo.ArgumentAsDeviceState,InitialAtMeetConditionValue:!0,ChangableAtMeetCondition:!1}),e.push({ArgumentType:oo.ArgumentAsSceneExecuted,InitialAtMeetConditionValue:!0,ChangableAtMeetCondition:!1}),e.push({ArgumentType:oo.ArgumentAsTime,InitialAtMeetConditionValue:!0,ChangableAtMeetCondition:!1}),e.push({ArgumentType:oo.ArgumentAsTimeSpan,InitialAtMeetConditionValue:!0,ChangableAtMeetCondition:!1})):null!=this._result&&(null==this._result.RightArgument||this._result.RightArgument instanceof uo)&&(this._result.LeftArgumentType==io.ArgumentAsDaysOfWeek&&(e.push({ArgumentType:oo.ArgumentAsTime,InitialAtMeetConditionValue:!0,ChangableAtMeetCondition:!0}),e.push({ArgumentType:oo.ArgumentAsAstronomicalClockWithOffset,InitialAtMeetConditionValue:!0,ChangableAtMeetCondition:!0})),this._result.LeftArgumentType==io.ArgumentAsTime&&e.push({ArgumentType:oo.ArgumentAsDaysOfWeek,InitialAtMeetConditionValue:!1,ChangableAtMeetCondition:!1}),this._result.LeftArgumentType==io.ArgumentAsAstronomicalClockWithOffset&&e.push({ArgumentType:oo.ArgumentAsDaysOfWeek,InitialAtMeetConditionValue:!1,ChangableAtMeetCondition:!1})),0==e.any((e=>e.ArgumentType==oo.ArgumentAsAstronomicalClockWithOffset))&&e.push({ArgumentType:oo.ArgumentAsAstronomicalClockWithOffset,InitialAtMeetConditionValue:!1,ChangableAtMeetCondition:!0}),0==e.any((e=>e.ArgumentType==oo.ArgumentAsDaysOfWeek))&&e.push({ArgumentType:oo.ArgumentAsDaysOfWeek,InitialAtMeetConditionValue:!1,ChangableAtMeetCondition:!0}),0==e.any((e=>e.ArgumentType==oo.ArgumentAsDeviceState))&&e.push({ArgumentType:oo.ArgumentAsDeviceState,InitialAtMeetConditionValue:!0,ChangableAtMeetCondition:!0}),0==e.any((e=>e.ArgumentType==oo.ArgumentAsSceneExecuted))&&e.push({ArgumentType:oo.ArgumentAsSceneExecuted,InitialAtMeetConditionValue:!0,ChangableAtMeetCondition:!1}),0==e.any((e=>e.ArgumentType==oo.ArgumentAsTime))&&e.push({ArgumentType:oo.ArgumentAsTime,InitialAtMeetConditionValue:!1,ChangableAtMeetCondition:!0}),0==e.any((e=>e.ArgumentType==oo.ArgumentAsTimeSpan))&&e.push({ArgumentType:oo.ArgumentAsTimeSpan,InitialAtMeetConditionValue:!0,ChangableAtMeetCondition:!1}),e}ValidateScene(){var e,t,n,s;if(null==this._result)throw new Error("No context!");const r=[],o=(e,t,n)=>e.RightArgumentType==io.Null?e.LeftArgumentType==t&&e.AtMeetCondition==n?e:null:e.LeftArgumentType==t&&e.AtMeetCondition==n?e:o(e.RightArgument,t,n),i=o(this._result,io.ArgumentAsDaysOfWeek,!0);null!=i&&((null===(e=i.RightArgument)||void 0===e?void 0:e.LeftArgumentType)==io.ArgumentAsTime||(null===(t=i.RightArgument)||void 0===t?void 0:t.LeftArgumentType)==io.ArgumentAsAstronomicalClockWithOffset)&&r.push(so.OptimizeDayOfWeekArgument);const a=o(this._result,io.ArgumentAsTime,!0);return null!=a&&(null===(n=a.RightArgument)||void 0===n?void 0:n.LeftArgumentType)==io.ArgumentAsDaysOfWeek&&(null===(s=a.RightArgument)||void 0===s?void 0:s.AtMeetCondition)&&r.push(so.OptimizeAtInDayOfWeekArgument),{IsValid:0==r.length,Errors:r,TryFix:()=>this.TryFix(r),Ignore:()=>this.Commit()}}TryFix(e){if(null==this._result)throw new Error("No context!");if(e.includes(so.OptimizeDayOfWeekArgument)){const e=t=>{var n,s;return t.LeftArgumentType==io.ArgumentAsDaysOfWeek?(null===(n=t.RightArgument)||void 0===n?void 0:n.LeftArgumentType)==io.ArgumentAsTime||(null===(s=t.RightArgument)||void 0===s?void 0:s.LeftArgumentType)==io.ArgumentAsAstronomicalClockWithOffset?t:e(t.RightArgument):t.RightArgumentType==io.Null?null:e(t.RightArgument)},t=e(this._result);if(null==t)throw new Error("Something wrong! Cannot find 'days of week' argument! Cannot fix!");const n=structuredClone(t),s=t.RightArgument;t.LeftArgument=s.LeftArgument,t.LeftArgumentType=s.LeftArgumentType,t.HandledType=s.HandledType,s.LeftArgument=n.LeftArgument,s.LeftArgumentType=n.LeftArgumentType,s.HandledType=n.HandledType,s.AtMeetCondition=!1}if(e.includes(so.OptimizeAtInDayOfWeekArgument)){const e=t=>{var n,s;return t.LeftArgumentType==io.ArgumentAsTime?(null===(n=t.RightArgument)||void 0===n?void 0:n.LeftArgumentType)==io.ArgumentAsDaysOfWeek&&(null===(s=t.RightArgument)||void 0===s?void 0:s.AtMeetCondition)?t:e(t.RightArgument):t.RightArgumentType==io.Null?null:e(t.RightArgument)},t=e(this._result);if(null==t)throw new Error("Something wrong! Cannot find 'time' argument! Cannot fix!");t.RightArgument.AtMeetCondition=!1}return this.Commit()}}!function(e){e.OptimizeDayOfWeekArgument="OptimizeDayOfWeekArgument",e.OptimizeAtInDayOfWeekArgument="OptimizeAtInDayOfWeekArgument"}(so||(so={})),function(e){e.DeviceTask="DeviceTask",e.DelayTask="DelayTask",e.LockExecutionTask="LockExecutionTask",e.NotifyTaskAppNotify="NotifyTaskAppNotify",e.NotifyTaskEmailNotify="NotifyTaskEmailNotify"}(ro||(ro={})),function(e){e.Unknown="Unknown",e.ArgumentAsAstronomicalClockWithOffset="ArgumentAsAstronomicalClockWithOffset",e.ArgumentAsDaysOfWeek="ArgumentAsDaysOfWeek",e.ArgumentAsTimeSpan="ArgumentAsTimeSpan",e.ArgumentAsTime="ArgumentAsTime",e.ArgumentAsDeviceState="ArgumentAsDeviceState",e.ArgumentAsSceneExecuted="ArgumentAsSceneExecuted"}(oo||(oo={}));class co{constructor(){this.Tasks=new go,this.Guid="",this.ObjectType=1,this.Name="",this.Icon="",this.AtMeetCondition=!1,this.ExecuteOnce=!1,this.IsDisabled=!1,this.HandledType=Tr.Unknown,this.ConditionType=Dr.Unknown,this.ConditionTimeout=0,this.LeftArgumentType=io.Null,this.RightArgumentType=io.Null,this.LeftArgument=new lo({},io.Null),this.RightArgument=new uo}}class uo{constructor(){this.HandledType=0,this.Argument=null}}class lo{constructor(e,t){this.Argument=e,this.HandledType=t}}class ho{constructor(){this.DeviceStateType=kr.Unknown,this.Channel=0,this.DeviceGuid="",this.ComparisonMethod=wr.Default,this.ComparisonParams=null,this.CheckedDeviceState={}}}class go{constructor(){this.ControllerTasks=[],this.DevicesTasks=[]}}class po{constructor(){this.RunParallel=!1,this.TaskType=_r.Unknown}}class fo extends po{constructor(){super(...arguments),this.TaskType=_r.DeviceTask,this.DeviceGuid="",this.Channel=0,this.ControlFeature=Gs.TurnOn}}class vo extends po{constructor(){super(...arguments),this.TaskType=_r.DelayTask,this.Delay="00:00:00"}}class mo extends po{constructor(){super(...arguments),this.TaskType=_r.LockExecution,this.LockType=Jr.Timeout,this.LockStartHour="00:00:00",this.LockEndHour="00:00:00",this.ResetLockScenesGuids=[]}}class yo extends po{constructor(){super(...arguments),this.TaskType=_r.NotifyTask,this.Title="",this.Message="",this.NotifyType=zr.None,this.NotificationClients=[]}}!function(e){e[e.Null=0]="Null",e[e.Condition=1]="Condition",e[e.ConditionGroup=2]="ConditionGroup",e[e.ArgumentAsInt=3]="ArgumentAsInt",e[e.ArgumentAsTimeSpan=4]="ArgumentAsTimeSpan",e[e.ArgumentAsBoolean=5]="ArgumentAsBoolean",e[e.ArgumentAsTimeout=6]="ArgumentAsTimeout",e[e.ArgumentAsDayOfWeek=7]="ArgumentAsDayOfWeek",e[e.ArgumentAsDaysOfWeek=8]="ArgumentAsDaysOfWeek",e[e.ArgumentAsAstronomicalClock=9]="ArgumentAsAstronomicalClock",e[e.ArgumentAsTime=10]="ArgumentAsTime",e[e.ArgumentAsDeviceState=11]="ArgumentAsDeviceState",e[e.ArgumentAsNumber=12]="ArgumentAsNumber",e[e.ArgumentAsAstronomicalClockWithOffset=13]="ArgumentAsAstronomicalClockWithOffset",e[e.ArgumentAsConditionInfo=14]="ArgumentAsConditionInfo"}(io||(io={}));class wo extends Error{constructor(e){super(e),this.message=e,this.name="BadParametersScenesBuilderException"}}class So extends Error{constructor(e){super(e),this.message=e,this.name="SequenceNotFoundScenesBuilderException"}}class Ao extends Error{constructor(e){super(e),this.message=e,this.name="TaskNotFoundScenesBuilderException"}}class _o extends Error{constructor(e){super(e),this.message=e,this.name="UnsupportedArgumentScenesBuilderException"}}var Co,To=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class Do{constructor(){this._connection=Ov.Get(Pt.ServiceName),this._configurationService=Ov.Get(rt.ServiceName)}GetServiceName(){return Do.ServiceName}GetSequencesListAsync(){return To(this,void 0,void 0,(function*(){var e;const t=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new ko,12e3,!1);return Ov.Get(s.ServiceName).Debug(`GetSequencesListAsync result:\n ${JSON.stringify(t)}}`),null==t?new De(yr.OtherError,"Cannot get sequences list - response is null."):t.Status!=ce.OK?new De(yr.OtherError,`Cannot get sequences list - controller responded with response code ${t.Status}.`):null==t.Data?new De(yr.NoData,"Cannot get sequences list - controller responded with status OK, but response does not contain data!"):t.Data}))}GetSequenceAsync(e){return To(this,void 0,void 0,(function*(){var t;let n="";n="string"==typeof e?e:e.Guid;const s=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Go(n),12e3,!1);if(null==s)return new De(yr.OtherError,"Cannot get sequence - response is null.");if(s.Status!=ce.OK)return new De(yr.OtherError,`Cannot get sequence - controller responded with response code ${s.Status}.`);if(null==s.Data)return new De(yr.NoData,"Cannot get sequence - controller responded with status OK, but response does not contain data!");const r=s.Data;return this.MapSequence(r)}))}GetSequenceBuilder(e,t){return new ao(e,t)}CreateSequenceAsync(e){return To(this,void 0,void 0,(function*(){var t;try{yield this._configurationService.EnterConfigurationModeAsync(),Ov.Get(s.ServiceName).Debug(`Creating sequence ${e.Name} json: \n${JSON.stringify(e)}`);const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Io(e),2e4,!1);return null==n||null==n.Status?ce.Error:n.Status}catch(t){return Ov.Get(s.ServiceName).Error(`Creating sequence ${e.Name} error: ${t}`),ce.FatalError}finally{yield this._configurationService.ExitConfigurationModeAsync()}}))}CheckIfSequenceIsUsedInAnotherSequenceAsync(e){return To(this,void 0,void 0,(function*(){var t;try{let n="";n="string"==typeof e?e:e.Guid;const s=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new bo(n),12e3,!1);if(null==s)return new De(yr.OtherError,"Cannot get sequence - response is null.");switch(s.Status){case ce.WrongData:return new De(yr.InvalidSceneGuid,"Cannot check if sequence is used in another sequence! Sequence not found, invalid sequence guid!");case ce.OK:return null==s.Data?new De(yr.NoData,"Cannot get sequence - controller responded with status OK, but response does not contain data!"):s.Data;default:return new De(yr.OtherError,`Cannot check if sequence is used in another sequence! Controller responded with code: ${s.Status}`)}}catch(e){return new De(yr.FatalError,`Cannot check if sequence is used in another sequence! Fatal error! ${e}`)}}))}DeleteSequenceAsync(e){return To(this,void 0,void 0,(function*(){var t;try{let n="";n="string"==typeof e?e:e.Guid,yield this._configurationService.EnterConfigurationModeAsync();const s=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Po(n),12e3,!1);return null==s||null==s.Status?ce.Error:s.Status}catch(e){return ce.FatalError}finally{yield this._configurationService.ExitConfigurationModeAsync()}}))}EditSequenceAsync(e){return To(this,void 0,void 0,(function*(){var t;try{const n={Guid:e.Guid,Icon:e.Icon,Name:e.Name,Condition:e};yield this._configurationService.EnterConfigurationModeAsync();const s=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Ro(n),2e4,!1);return null==s||null==s.Status?ce.Error:s.Status}catch(t){return Ov.Get(s.ServiceName).Error(`Editing sequence ${e.Name} error: ${t}`),ce.FatalError}finally{yield this._configurationService.ExitConfigurationModeAsync()}}))}EnableSequenceAsync(e){return To(this,void 0,void 0,(function*(){var t;let n="";n="string"==typeof e?e:e.Guid;const s=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Oo(n),12e3,!1);return null==s||null==s.Status?ce.Error:s.Status}))}DisableSequenceAsync(e){return To(this,void 0,void 0,(function*(){var t;let n="";n="string"==typeof e?e:e.Guid;const s=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Uo(n),12e3,!1);return null==s||null==s.Status?ce.Error:s.Status}))}RunSequenceAsync(e){return To(this,void 0,void 0,(function*(){let t="";if("string"==typeof e){const n=yield this.GetSequencesListAsync();if(null!=n.Type)return ce.Error;{const s=n.find((t=>t.Guid==e));if(!s)return ce.Error;t=s.DeviceGuid}}else t=e.DeviceGuid;const n=new Ws;switch(n.Channel=1,n.DeviceGuid=t,yield Ov.Get(xo.ServiceName).ExecuteDeviceTaskAsync({Guid:t},n)){case kt.Executed:return ce.OK;case kt.DeviceNotFound:return ce.WrongData;default:return ce.Error}}))}GetUtilsAsync(){return To(this,void 0,void 0,(function*(){const e=yield this.SunCalculatorAsync();return{GetSunRiseTime:e.GetSunRiseTime,GetSunSetTime:e.GetSunSetTime,ParseLinearScaleToLux:this._parseLinearScaleToLux,ParseLuxToLinearScale:this._parseLuxToLinearScale}}))}_parseLinearScaleToLux(e){if(!(e<0||e>1))return Math.round(Math.pow(10,5*e))}_parseLuxToLinearScale(e){if(e<=0)return 0;const t=Math.log10(e)/5;return t>1?1:t}SunCalculatorAsync(){return To(this,void 0,void 0,(function*(){const e=Ov.Get(Ur.ServiceName),t=new vr;let n=!1;t.Latitude=49.9958888026741,t.Longitude=18.9172596008914;try{if(yield e.IsControllerGeolocationSetAsync()){const n=yield e.GetControlllerGeolocationAsync();n instanceof mr&&(t.Latitude=n.Latitude,t.Longitude=n.Longitude)}}catch(e){Ov.Get(s.ServiceName).Warning(`Cannot get localization data, using default values: 49.9958888026741, 18.9172596008914. Error: ${e}`)}const r=e=>{let n=7.95204*Math.sin(.01768*e+3.03217)+9.98906*Math.sin(.03383*e+3.4687)+4*(t.Longitude-15*Math.round(t.Longitude/15));return((e=new Date)=>{const t=new Date(e.getFullYear(),0,1).getTimezoneOffset(),n=new Date(e.getFullYear(),6,1).getTimezoneOffset();return Math.max(t,n)!==e.getTimezoneOffset()})()&&(n-=60),n},o=e=>Math.asin(-.39795*Math.cos(2*Math.PI*(e+10)/365)),i=e=>{const n=t.Latitude*Math.PI/180;let s=Math.sin(n)*Math.sin(e)/(Math.cos(n)*Math.cos(e));return s=(e=>(e<-1&&(e=-1),e>1&&(e=1),e))(s),s},a=e=>{const t=Math.ceil(e/60),n=e-60*t,s=new Date;return new Date(s.getFullYear(),s.getMonth(),s.getDate(),t,n)},c=e=>{const t=new Date;t.setDate(t.getDate()+e);const s=(u=t,Math.floor((u.valueOf()-new Date(u.getFullYear(),0,0).valueOf())/1e3/60/60/24));var u;const l=r(s),d=o(s),h=((e,t)=>{let n=720-720/Math.PI*Math.acos(-e)-t;return n<0&&(n+=1440),n})(i(d),l),g=a(h);return new Date>g&&!n?(n=!0,c(1)):(n=!1,new Date(t.getFullYear(),t.getMonth(),t.getDate(),g.getHours(),g.getMinutes()))},u=e=>{const t=new Date;t.setDate(t.getDate()+e);const s=(c=t,Math.floor((c.valueOf()-new Date(c.getFullYear(),0,0).valueOf())/1e3/60/60/24));var c;const l=r(s),d=o(s),h=i(d),g=Math.floor(((e,t)=>{let n=720+720/Math.PI*Math.acos(-e)-t;return n>1439&&(n-=1439),n})(h,l)),p=a(g);return new Date>p&&!n?(n=!0,u(1)):(n=!1,new Date(t.getFullYear(),t.getMonth(),t.getDate(),p.getHours(),p.getMinutes()))};return{GetSunRiseTime:()=>c(0),GetSunSetTime:()=>u(0)}}))}MapSequence(e,t=!1){const n=Object.assign({},e),s=e=>{if(e.RightArgumentType!=Co.Null)return!Object.hasOwn(e.Tasks,"ControllerTasks")&&Object.hasOwn(e.Tasks,"DevicesTasks")&&delete Object.assign(e.Tasks,{ControllerTasks:e.Tasks.DevicesTasks}).DevicesTasks,s(e.RightArgument);!Object.hasOwn(e.Tasks,"ControllerTasks")&&Object.hasOwn(e.Tasks,"DevicesTasks")&&(delete Object.assign(e.Tasks,{ControllerTasks:e.Tasks.DevicesTasks}).DevicesTasks,e.Tasks.ControllerTasks.map((e=>{e.TaskType=_r.DeviceTask,e.RunParallel=!1})))};return s(e),n._rawRequestData=JSON.parse(JSON.stringify(e)),t?(n.RightArgument=null,n.RightArgumentType=br.Null):(n.RightArgumentType=this.MapArgumentType(e.RightArgumentType),n.RightArgument=this.MapRightArgument(e.RightArgument,n.RightArgumentType)),n.LeftArgumentType=this.MapArgumentType(e.LeftArgumentType),n.LeftArgument=this.MapLeftArgument(e.LeftArgument,n.LeftArgumentType),n.Tasks.ControllerTasks=this.MapControllerTasks(e.Tasks.ControllerTasks),void 0===n.DoesHaveTriggers&&(n.DoesHaveTriggers=n.LeftArgumentType==br.Null),n}MapRightArgument(e,t){return 0==e.HandledType||(e.LeftArgumentType=this.MapArgumentType(e.LeftArgumentType),e.LeftArgument=this.MapLeftArgument(e.LeftArgument,e.LeftArgumentType),e.Tasks.ControllerTasks=this.MapControllerTasks(e.Tasks.ControllerTasks),Object.hasOwn(e.Tasks,"DevicesTasks")&&delete e.Tasks.DevicesTasks,t===br.Condition&&(e.RightArgumentType=this.MapArgumentType(e.RightArgumentType),e.RightArgument=this.MapRightArgument(e.RightArgument,e.RightArgumentType))),e}MapLeftArgument(e,t){let n=new No;switch(n.HandledType=e.HandledType,t){case br.ArgumentAsAstronomicalClock:n.Argument.ArgumentAsAstronomicalClock={Position:e.Argument};break;case br.ArgumentAsAstronomicalClockWithOffset:n.Argument.ArgumentAsAstronomicalClockWithOffset={Offset:e.Argument.Offset,Position:e.Argument.Position};break;case br.ArgumentAsBoolean:n.Argument.ArgumentAsBoolean=e.Argument;break;case br.ArgumentAsDayOfWeek:n.Argument.ArgumentAsDayOfWeek=e.Argument;break;case br.ArgumentAsDaysOfWeek:n.Argument.ArgumentAsDaysOfWeek=e.Argument;break;case br.ArgumentAsInt:n.Argument.ArgumentAsInt=e.Argument;break;case br.ArgumentAsTimeout:n.Argument.ArgumentAsTimeout=e.Argument;break;case br.ArgumentAsTimeSpan:n.Argument.ArgumentAsTimeSpan={days:e.Argument.days,hours:e.Argument.hours,minutes:e.Argument.minutes,seconds:e.Argument.seconds};break;case br.ArgumentAsTime:n.Argument.ArgumentAsTime={Hour:e.Argument.Hour,Minute:e.Argument.Minute,Second:e.Argument.Second};break;case br.ArgumentAsDeviceState:{const t=new Lr;t.Type=this.MapDeviceStateTypeToResponseType(e.Argument.DeviceStateType),t.SetCheckDeviceState(this.CreateDeviceState(e.Argument.CheckedDeviceState,e.Argument.Channel,t.Type)),t.DeviceGuid=e.Argument.DeviceGuid,t.ComparisonMethod=null==e.Argument.ComparisonMethod?wr.Default:e.Argument.ComparisonMethod,null!=e.Argument.ComparisonParams&&Object.entries(e.Argument.ComparisonParams).forEach((e=>{switch(e[0]){case"DeltaValue":case"StateRepeatCount":t.SetComparisonParam(Sr[e[0]],new Br(e[1]));break;case"DeltaCalculationTimeRange":case"StateRepeatTimeRange":t.SetComparisonParam(Sr[e[0]],new Wr(e[1]))}})),n.Argument.ArgumentAsDeviceState=t;break}case br.ArgumentAsConditionInfo:n.Argument.ArgumentAsConditionInfo={DeviceGuid:e.Argument.DeviceGuid}}return n}MapArgumentType(e){return br[Co[e]]}MapDeviceStateTypeToResponseType(e){switch(e){case kr.BatteryState:return At.BatteryState;case kr.BinarySensor:return At.BinarySensorState;case kr.BlindPosition:return At.BlindPosition;case kr.Brightness:return At.MeasuredBrightness;case kr.ButtonState:return At.RemoteButtonState;case kr.ChannelOnOff:return At.ChannelOnOffState;case kr.DoorBell:return At.DoorBellState;case kr.Energy:return At.MeasuredEnergy;case kr.FloodSensor:return At.FloodSensorState;case kr.GatePosition:return At.GatePosition;case kr.LightBrightness:return At.LightBrightness;case kr.LightColor:return At.LightColor;case kr.LightTemperature:return At.LightWarmth;case kr.ReedState:return At.ReedState;case kr.SmokeSensor:return At.SmokeSensorState;case kr.Temperature:return At.MeasuredTemperature;case kr.Humidity:return At.HumiditySensorState;case kr.BlindsControlButton:return At.BlindRemoteButtonState;case kr.FacadeControlButton:return At.FacadeRemoteButtonState;case kr.Movement:return At.MovementSensorState;case kr.AirPressure:return At.PressureSensorState;case kr.WindSpeed:return At.WindSpeedState;case kr.WindThreshold:return At.CurrentWindThreshold;default:return At.Unknown}}CreateDeviceState(e,t,n){switch(n){case At.BatteryState:return{Channel:t,StateReliability:Ft.Unconfident,Percentage:e.Percentage,State:e.State,Time:""};case At.BinarySensorState:return{Channel:t,StateReliability:Ft.Unconfident,State:e.State,Time:""};case At.BlindPosition:return{Channel:t,StateReliability:Ft.Unconfident,Position:e.Position,RawPosition:e.RawPosition,Time:""};case At.LightBrightness:case At.MeasuredBrightness:return{Channel:t,StateReliability:Ft.Unconfident,Brightness:e.Brightness,Time:""};case At.RemoteButtonState:case At.ChannelOnOffState:case At.DoorBellState:return{Channel:t,StateReliability:Ft.Unconfident,State:e.State,Time:""};case At.MeasuredEnergy:{const n=new Map;for(let[t,s]of Object.entries(e.MeasurementParameters))n.set(jt[t],s);return{Channel:t,StateReliability:Ft.Unconfident,MeasurementParameters:n,Time:""}}case At.FloodSensorState:return{Channel:t,StateReliability:Ft.Unconfident,State:e.State,Time:""};case At.GatePosition:return{Channel:t,StateReliability:Ft.Unconfident,Position:e.Position,PositionType:e.PositionType,Time:""};case At.LightColor:return{Channel:t,StateReliability:Ft.Unconfident,R:e.R,G:e.G,B:e.B,Time:""};case At.LightWarmth:return{Channel:t,StateReliability:Ft.Unconfident,Temperature:e.Temperature,Time:""};case At.ReedState:return{Channel:t,StateReliability:Ft.Unconfident,State:e.State,Time:""};case At.SmokeSensorState:throw new qr("Unsupported device state!");case At.MeasuredTemperature:return{Channel:t,StateReliability:Ft.Unconfident,Temperature:e.Temperature,Time:"",Type:e.Type};case At.HumiditySensorState:return{Channel:t,StateReliability:Ft.Unconfident,Humidity:e.Humidity,Time:"",Type:e.Type};case At.BlindRemoteButtonState:return{Channel:t,StateReliability:Ft.Unconfident,State:e.State,Time:""};case At.LightRGBWState:return{StateReliability:Ft.Unconfident,Channel:t,Time:"",Brightness:100,R:e.R,G:e.G,B:e.B,W:e.W};case At.FacadeRemoteButtonState:return{Channel:t,Time:"",StateReliability:Ft.Unconfident,State:e.State};case At.MovementSensorState:return{Channel:t,Time:"",StateReliability:Ft.Unconfident,Movement:e.Movement,Intensity:e.Intensity};case At.PressureSensorState:return{Channel:t,Time:"",StateReliability:Ft.Unconfident,Pressure:e.Pressure,PressureType:e.PressureType};case At.WindSpeedState:return{Channel:t,Time:"",StateReliability:Ft.Unconfident,Value:e.Value};case At.CurrentWindThreshold:return{Channel:t,Time:"",StateReliability:Ft.Unconfident,WindThreshold:e.WindThreshold};case At.Unknown:return new vn;default:throw new qr("Unsupported device state!")}}MapDeviceTask(e){let t=new Fs,n=e;switch(Ov.Get(s.ServiceName).Debug(`[TASK] object: ${JSON.stringify(n)}`),n.ControlFeature){case Gs.TurnOn:t=new Ws,t.TaskType=St.TurnOn;break;case Gs.TurnOff:t=new Bs,t.TaskType=St.TurnOff;break;case Gs.ToggleState:t=new Vs,t.TaskType=St.TogleState;break;case Gs.SetBlindPosition:t=new Ks,t.TaskType=St.SetBlindPosition,t.Action=n.Data.Action,t.Position=n.Data.Position;break;case Gs.SetLightColor:t=new Hs,t.TaskType=St.SetLightColor,t.R=n.Data.R,t.G=n.Data.G,t.B=n.Data.B;break;case Gs.SetLightTemperature:t=new js,t.TaskType=St.SetLightTemperature,t.Temperature=n.Data.Temperature;break;case Gs.SetLightBrightness:t=new qs,t.TaskType=St.SetLightBrightness,t.Brightness=n.Data.Brightness;break;case Gs.SetTemperature:t=new Ls,t.TaskType=St.SetTemperature,t.Temperature=n.Data.Temperature;break;case Gs.GetState:t=new Qs,t.TaskType=St.GetChannelsState;break;case Gs.TurnOnWithTimeout:t=new $s,t.TaskType=St.TurnOnWithTime,t.SwitchOffDelaySeconds=n.Data.SwitchOffDelaySeconds;break;case Gs.SetLightBrightnessDynamicly:t=new zs,t.TaskType=St.SetLightBrightnessDynamicly,t.Brightness=n.Data.Brightness;break;case Gs.IdentifyDevice:t=new Js,t.TaskType=St.IdentifyDevice;break;case Gs.SetBlindOpenCloseTime:t=new Ys,t.TaskType=St.SetBlindOpenCloseTime,t.Data.CloseTime=n.Data;break;case Gs.SetBlindMicroventilation:t=new Zs,t.TaskType=St.SetBlindMicroventilation,t.Position=n.Data.Position;break;case Gs.GatewayPulse:t=new tr,t.TaskType=St.ChangeGatewayPositionPulse;break;case Gs.GatePulse:t=new er,t.TaskType=St.ChangeGatePositionPulse;break;case Gs.SetFacadePositionAndTilt:t=new nr,t.TaskType=St.SetFacadePosition,t.Position=n.Data.Position,t.Tilt=n.Data.Tilt,t.FacadeAction=Is.TiltAndPercentage;break;case Gs.GetFacadeType:t=new sr,t.TaskType=St.GetFacadeType;break;case Gs.LightRGBW:t=new or,t.TaskType=St.LightRGBW,t.Data=n.Data}return t.Channel=n.Channel,t.DeviceGuid=n.DeviceGuid,t.FeatureType=n.ControlFeature,t.Guid=xs.NewGuid(),t}MapControllerTasks(e){const t=[];Ov.Get(s.ServiceName).Debug(`[TASKS] received tasks object: ${JSON.stringify(e)}`);for(let n of e){const e=new Eo;switch(e.TaskId=re.GenerateMd5(JSON.stringify(n)),n.TaskType){case _r.DeviceTask:e.TaskType=Cr.DeviceTask,e.Task.DeviceTask=this.MapDeviceTask(n);break;case _r.DelayTask:e.TaskType=Cr.DelayTask,e.Task.DelayTask={Delay:new Wr(n.Delay)};break;case _r.NotifyTask:e.TaskType=Cr.NotifyTask,e.Task.NotifyTask={Message:n.Message,NotifyType:n.NotifyType};break;case _r.LockExecution:case _r.LockExecution:e.TaskType=Cr.LockExecution,Ov.Get(s.ServiceName).Debug(`[TASKS] received task LockExecution object: ${JSON.stringify(n)}`),e.Task.LockExecution={LockStartHour:new Wr(n.LockStartHour),LockEndHour:new Wr(n.LockEndHour),LockType:n.LockType,ResetLockScenesGuids:n.ResetLockScenesGuids};case _r.Unknown:}t.push(e)}return t}}Do.ServiceName="ScenesService";class ko extends ae{constructor(){super(),this.Resource="/logic/sequences/list",this.Method=ue.Get}}class Go extends ae{constructor(e){super(),this.Resource="/logic/sequence",this.Method=ue.Get,this.Data=e}}class bo extends ae{constructor(e){super(),this.Resource="/logic/sequences/used",this.Method=ue.Get,this.Data=e}}class No{constructor(){this.HandledType=Co.Null,this.Argument={}}}!function(e){e[e.Null=0]="Null",e[e.Condition=1]="Condition",e[e.ConditionGroup=2]="ConditionGroup",e[e.ArgumentAsInt=3]="ArgumentAsInt",e[e.ArgumentAsTimeSpan=4]="ArgumentAsTimeSpan",e[e.ArgumentAsBoolean=5]="ArgumentAsBoolean",e[e.ArgumentAsTimeout=6]="ArgumentAsTimeout",e[e.ArgumentAsDayOfWeek=7]="ArgumentAsDayOfWeek",e[e.ArgumentAsDaysOfWeek=8]="ArgumentAsDaysOfWeek",e[e.ArgumentAsAstronomicalClock=9]="ArgumentAsAstronomicalClock",e[e.ArgumentAsTime=10]="ArgumentAsTime",e[e.ArgumentAsDeviceState=11]="ArgumentAsDeviceState",e[e.ArgumentAsNumber=12]="ArgumentAsNumber",e[e.ArgumentAsAstronomicalClockWithOffset=13]="ArgumentAsAstronomicalClockWithOffset",e[e.ArgumentAsConditionInfo=14]="ArgumentAsConditionInfo"}(Co||(Co={}));class Eo{constructor(){this.TaskId="",this.TaskType=Cr.Unknown,this.Task={}}}class Io extends ae{constructor(e){super(),this.Resource="/logic/sequence",this.Method=ue.Put,this.Data=e}}class Ro extends ae{constructor(e){super(),this.Resource="/logic/sequence/edit",this.Method=ue.Put,this.Data=e}}class Po extends ae{constructor(e){super(),this.Resource="/logic/sequence",this.Method=ue.Delete,this.Data=e}}class Oo extends ae{constructor(e){super(),this.Resource="/logic/sequence/enable",this.Method=ue.Post,this.Data=e}}class Uo extends ae{constructor(e){super(),this.Resource="/logic/sequence/disable",this.Method=ue.Post,this.Data=e}}var Mo=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class xo{constructor(){this._devices=[],this._onDevicesTasksChangedEvent=new n,this._onDeviceFoundEvent=new n,this._onDeviceRegisteredEvent=new n,this._onDeviceRemovedEvent=new n,this._onDeviceFirmwareVersionChangedEvent=new n,this._onDeviceStateChangedEvent=new n,this._onDeviceStateRefreshedOrChangedEvent=new n,this._connection=null,this._session=null,this._controllerConfiguration=null,this._synchronized=!1,this._synchronizedDevicesStates=!1,this._devicesChannelsStates=[],this._synchronizationTaskCompletionSource=null,this._deviceStatesSynchronizationTaskCompletionSource=null,this._connection=Ov.Get(Pt.ServiceName),this._session=Ov.Get(Ke.ServiceName),this._controllerConfiguration=Ov.Get(rt.ServiceName),this._onDeviceStateChangedEvent.Subscribe((e=>Mo(this,void 0,void 0,(function*(){return this.PutDeviceStateOnList(e.Device,e.State)})))),this._synchronizationTaskCompletionSource=new Promise((e=>{var t;null===(t=this._session)||void 0===t||t.OnUserLoggedInEvent().Subscribe((t=>Mo(this,void 0,void 0,(function*(){var t;try{this._devices=yield this.GetPairedDevicesAsync()}catch(e){null===(t=r.Log)||void 0===t||t.Error(xo.ServiceName,`Failed to get paired devices: ${e}`)}this._synchronized=!0,e()}))))})),this._deviceStatesSynchronizationTaskCompletionSource=new Promise((e=>{var t;null===(t=this._session)||void 0===t||t.OnUserLoggedInEvent().Subscribe((t=>Mo(this,void 0,void 0,(function*(){var t;try{yield this.WaitForSynchronizationAsync(),yield this.SyncDevicesStatesAsync()}catch(e){null===(t=r.Log)||void 0===t||t.Error(xo.ServiceName,`Failed to sync devices states: ${e}`)}this._synchronizedDevicesStates=!0,e()}))))})),this._connection.SubscribeTo("/info/devices/tasks",(e=>{this.ParseDeviceTaskInfo(e.Data)})),this._connection.SubscribeTo("/info/devices/device/found",(e=>{this.MapApiDevices(e.Data).forEach((e=>{var t;e.DeviceType!=Tt.Scene&&(null===(t=r.Log)||void 0===t||t.Debug(xo.ServiceName,`Found device: ${e.Name} guid: ${e.Guid}`),this._onDeviceFoundEvent.Invoke(e))}))})),this._connection.SubscribeTo("/info/devices/device/firmware/updated",(e=>{const t=e.Data.DeviceGuid,n=e.Data.Version,s=this._devices.find((e=>e.Guid==t));void 0!==s&&(this._onDeviceFirmwareVersionChangedEvent.Invoke({Device:s,FirmwareVersion:n}),s.SoftwareVersion=n,s.OnDeviceFirmwareVersionChangedEvent().Invoke({FirmwareVersion:n}))})),this._connection.SubscribeTo("/devices/blinds/times",(e=>{})),this._connection.SubscribeTo("/info/devices/device/state/changed",(e=>{var t;const n=e.Data,s=this._devices.filter((e=>e.Guid==n.DeviceGuid));if(s.length>0){const e=s[0],r=this.MapApiDeviceStateToDeviceState(e,n);if(null!=r){this._onDeviceStateRefreshedOrChangedEvent.Invoke({Device:e,State:r}),r.TypeAsEnum==At.SignalStrength?e.Channels.forEach((t=>{let s=new Jn(Object.assign({},n));s.Data.Channel=t.Number,this._onDeviceStateRefreshedOrChangedEvent.Invoke({Device:e,State:s})})):r.TypeAsEnum==At.BatteryState&&e.Channels.forEach((t=>{let s=new Mn(Object.assign({},n));s.Data.Channel=t.Number,this._onDeviceStateRefreshedOrChangedEvent.Invoke({Device:e,State:s})}));let s=e.States.find((e=>e.TypeAsEnum===r.TypeAsEnum&&e.Data.Channel===r.Data.Channel));if(s){let o=s.StatesComparisonData;if(r.TypeAsEnum==At.BlindErrorState&&(null===(t=r.Data)||void 0===t?void 0:t.ErrorCode)!=s.Data.ErrorCode)return void this._onDeviceStateChangedEvent.Invoke({Device:e,State:r});s.Data=r.Data,o!==r.StatesComparisonData&&(this._onDeviceStateChangedEvent.Invoke({Device:e,State:r}),r.TypeAsEnum==At.SignalStrength?e.Channels.forEach((t=>{let s=new Jn(Object.assign({},n));s.Data.Channel=t.Number,this._onDeviceStateChangedEvent.Invoke({Device:e,State:s})})):r.TypeAsEnum==At.BatteryState&&e.Channels.forEach((t=>{let s=new Mn(Object.assign({},n));s.Data.Channel=t.Number,this._onDeviceStateChangedEvent.Invoke({Device:e,State:s})})))}else e.States.push(r),this._onDeviceStateChangedEvent.Invoke({Device:e,State:r}),r.TypeAsEnum==At.SignalStrength?e.Channels.forEach((t=>{let s=new Jn(Object.assign({},n));s.Data.Channel=t.Number,this._onDeviceStateChangedEvent.Invoke({Device:e,State:s})})):r.TypeAsEnum==At.BatteryState&&e.Channels.forEach((t=>{let s=new Mn(Object.assign({},n));s.Data.Channel=t.Number,this._onDeviceStateChangedEvent.Invoke({Device:e,State:s})}))}}})),this._connection.SubscribeTo("/info/devices/devices/registered",(e=>{Ov.Get(Ge.ServiceName).ClearCache(),this.MapApiDevices(e.Data).forEach((e=>{var t;null===(t=r.Log)||void 0===t||t.Debug(xo.ServiceName,`Registered device: ${e.Name} guid: ${e.Guid}`),this._devices.push(e),this._onDeviceRegisteredEvent.Invoke(e)}))})),this._connection.SubscribeTo("/info/devices/devices/removed",(e=>{Ov.Get(Ge.ServiceName).ClearCache(),this.MapApiDevices(e.Data).forEach((e=>{var t;null===(t=r.Log)||void 0===t||t.Debug(xo.ServiceName,`Removed device: ${e.Name} guid: ${e.Guid}`),this._devices=this._devices.filter((t=>t.Guid!=e.Guid)),this._onDeviceRemovedEvent.Invoke(e)}))}))}ProtocolGuidToProtocolName(e){switch(e){case"1fca7e8a-a2dc-4883-bd94-4e9b2012f685":return"ExtaLife";case"cd25bdff-628c-4dbc-a16a-648c96a819d4":return"Portos 433MHz";case"634c2bb2-1a4f-4db6-8dd4-d5fbaf92678e":return"Supla";case"194aeb81-990c-4a02-9236-59e902958fda":return"RTSP";case"b3e4644e-ab5b-494e-b3c5-66fabe7fff64":return"Wekta";case"247198e1-e360-4355-9886-232ac1456eea":return"Lavva Wi-Fi";default:return null}}CheckIfDeviceUsedInScenesAsync(e){return Mo(this,void 0,void 0,(function*(){var t,n,s,o,i,a;try{let a;if("string"==typeof e){const n=this.GetDevice(e);if(null==n)return null===(t=r.Log)||void 0===t||t.Error("Cannot check if device is used in scenes! Device with given guid not exists"),ce.ResourceDoesNotExists;a=n}else a=e;const u=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new Xo(a.Guid),2e4,!1);if(null==u||null==u.Status)return null===(s=r.Log)||void 0===s||s.Error("Cannot check if device is used in scenes! Response or status is null!"),ce.FatalError;if(u.Status!=ce.OK)return u.Status;if(null==u.Data)return null===(o=r.Log)||void 0===o||o.Error("Cannot check if device is used in scenes! No data!"),ce.FatalError;var c=yield Ov.Get(Do.ServiceName).GetSequencesListAsync();if(c instanceof De)return null===(i=r.Log)||void 0===i||i.Error(`Cannot check if device is used in scenes! Cannot get sequence list, ScenesServiceErrorCode: ${c.Type}`),ce.Error;const l=new ti;return l.DeviceGuid=a.Guid,u.Data.ConditionsAsCondition.forEach((e=>{const t=c.find((t=>t.Guid==e));t&&l.ConditionsAsCondition.push(t)})),u.Data.ConditionsAsTask.forEach((e=>{const t=c.find((t=>t.Guid==e));t&&l.ConditionsAsCondition.push(t)})),l}catch(e){return null===(a=r.Log)||void 0===a||a.Error(`Cannot check if device is used in scenes! ${e}`),ce.FatalError}}))}CanEditDevicesInfo(){var e,t;return null!==this._session&&void 0!==this._session&&null!==this._session.User&&void 0!==this._session.User&&(null===(t=null===(e=this._session)||void 0===e?void 0:e.User)||void 0===t?void 0:t.AccessLevel)>=ge.Admin}CanAddAndRemoveAndConfigureDevices(){var e,t;return null!==this._session&&void 0!==this._session&&null!==this._session.User&&void 0!==this._session.User&&(null===(t=null===(e=this._session)||void 0===e?void 0:e.User)||void 0===t?void 0:t.AccessLevel)>=ge.Installator}GetDeviceChannelByChannelId(e){return this._devices.firstOrDefault((t=>t.Channels.any((t=>t.ChannelId==e)))).Channels.firstOrDefault((t=>t.ChannelId==e))}EnableFastStatesSyncAsync(){return Mo(this,void 0,void 0,(function*(){const e=Ov.Get(dr.ServiceName).SaveAsync("FastDevicesSync",!1,!0);return yield Ov.Get(rt.ServiceName).ExitConfigurationModeAsync(),e}))}DisableFastStatesSyncAsync(){return Mo(this,void 0,void 0,(function*(){const e=Ov.Get(dr.ServiceName).SaveAsync("FastDevicesSync",!1,!1);return yield Ov.Get(rt.ServiceName).ExitConfigurationModeAsync(),e}))}IsFastStatesSyncEnabledAsync(){return Mo(this,void 0,void 0,(function*(){const e=yield Ov.Get(dr.ServiceName).ReadAsync("FastDevicesSync",!1,!1);return e instanceof cr?e.Data:e!=ce.ResourceDoesNotExists&&e}))}GetDevicesForManualPairingAsync(e){return Mo(this,void 0,void 0,(function*(){let t=Ov.Get(ar.ServiceName);const n=new RegExp("^[{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]?$");return Array.isArray(e)||n.test(e)?yield t.GetDevicesForManualPairingAsync(e):yield t.GetDevicesForManualPairingAsync()}))}AddManuallyPairedDevice(e){return Mo(this,void 0,void 0,(function*(){var t=yield Ov.Get(ar.ServiceName).AddManuallyPairedDeviceAsync(e);return yield Ov.Get(rt.ServiceName).ExitConfigurationModeAsync(),t}))}GetDeviceChannelStates(e,t){var n,s;return null!==(s=null===(n=this._devicesChannelsStates.firstOrDefault((t=>t.DeviceGuid==e.Guid)))||void 0===n?void 0:n.ChannelsStates.filter((e=>e.Channel==t)))&&void 0!==s?s:[]}GetDeviceStates(e){var t,n;return null!==(n=null===(t=this._devicesChannelsStates.firstOrDefault((t=>t.DeviceGuid==e.Guid)))||void 0===t?void 0:t.ChannelsStates)&&void 0!==n?n:[]}PutDeviceStateOnList(e,t){let n=this._devicesChannelsStates.firstOrDefault((t=>t.DeviceGuid==e.Guid));if(null==n){let s=new Fo;s.Channel=t.Data.Channel,s.States=[t],n={DeviceGuid:e.Guid,ChannelsStates:[s]},this._devicesChannelsStates.push(n)}else{let e=n.ChannelsStates.firstOrDefault((e=>e.Channel==t.Data.Channel));if(null==e)e=new Fo,e.Channel=t.Data.Channel,e.States=[t],n.ChannelsStates.push(e);else{let n=e.States.firstOrDefault((e=>e.TypeAsEnum==t.TypeAsEnum));null!=n&&(n.TypeAsEnum==At.BlindErrorState?e.States=e.States.where((e=>e.Data.ErrorCode!=t.Data.ErrorCode)).toArray():e.States=e.States.where((e=>e.TypeAsEnum!=t.TypeAsEnum)).toArray()),e.States.push(t)}}}WaitForSynchronizationAsync(){return this._synchronizationTaskCompletionSource}WaitForDevicesStatesSynchronizationAsync(){return this._deviceStatesSynchronizationTaskCompletionSource}GetCurrentlyRunningTaksAsync(){return Mo(this,void 0,void 0,(function*(){var e;const t=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new Ho,15e3,!1);(null==t?void 0:t.Status)==ce.OK&&null!=t.Data&&this.ParseDeviceTaskInfo(t.Data)}))}ParseDeviceTaskInfo(e){const t=[];e.forEach((e=>{var n;const s=e.split(";"),o=new Mt;o.DeviceGuid=s[0],o.Channel=Number(s[1]),o.Status=vt.ExecutingTasks,t.push(o),null===(n=r.Log)||void 0===n||n.Debug(xo.ServiceName,`Device ${o.DeviceGuid} has task on channel ${o.Channel}`)})),this._onDevicesTasksChangedEvent.Invoke(t)}MapApiDeviceStateToDeviceState(e,t){var n;switch(t.state,t.DataType){case"ChannelOnOff":return new mn(t);case"DoorBell":return new Sn(t);case"ReedPosition":return new _n(t);case"BlindPosition":return new Tn(t);case"ButtonState":return new kn(t);case"LightColor":return new bn(t);case"LightTemperature":return new En(t);case"LightBrightness":return new Rn(t);case"TemperatureSensor":case"TemperatureState":case"MeasuredTemperature":return new On(t);case"BatteryState":return new Mn(t);case"MeasuredBrightness":case"DeviceBrightnessState":return new Fn(t);case"EnergyMeasuredPower":case"EnergyMeasuredCurrent":case"EnergyMeasuredVoltage":break;case"IEnergy":case"Energy":return new Bn(t);case"DistanceSensor":return new $n(t);case"MovementSensor":return new qn(t);case"BlindsControlButton":return new Hn(t);case"FacadeControlButton":return new Kn(t);case"SignalStrength":return new Jn(t);case"GatePosition":return new Yn(t);case"GatewayPosition":return new Qn(t);case"GateControllerHealth":return new Zn(t);case"IBlindCalibrationStatus":case"BlindCalibration":return new es(t);case"HumiditySensor":case"HumidityState":return new ts(t);case"VibrationSensor":return new ss(t);case"DigitalInputSensor":return new rs(t);case"ConfigurationState":return new is(t);case"BlindOpenCloseTime":case"IBlindOpenCloseTime":return new as(t);case"IOvercurrentProtection":case"OvercurrentProtection":return new cs(t);case"IOvercurrentProtectionThreshold":case"OvercurrentProtectionThreshold":return new us(t);case"FacadePosition":case"FacadeState":return new ls(t);case"FacadeTypeState":return new ds(t);case"CurrentWindThreshold":return new hs(t);case"CurrentLightThreshold":return new ps(t);case"WindSpeed":return new fs(t);case"FloodSensor":return new ms(t);case"PressureState":return new ws(t);case"ITamperProtection":case"TamperProtection":return new As(t);case"ILightRGBW":case"LightRGBW":return new _s(t);case"OnlineCamera":case"IOnlineCamera":return new wn(t);case"BlindError":case"IBlindError":return t.state.ErrorData=ie(t.state.ErrorData),new Cs(t);default:null===(n=r.Log)||void 0===n||n.Debug(xo.ServiceName,`Not supported device state ${t.DataType}`)}return null}GetServiceName(){return xo.ServiceName}SyncDevicesStatesAsync(){return Mo(this,arguments,void 0,(function*(e=!1){var t,n,s;const r=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Bo,15e3,!1);if(yield this.IsFastStatesSyncEnabledAsync()){if(e){let e=new Wo;e.Data=!0;const t=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(e,35e3,!1);return(null==t?void 0:t.Status)==ce.OK}return(null==r?void 0:r.Status)==ce.OK}{let e=new Wo;e.Data=!0;const t=yield null===(s=this._connection)||void 0===s?void 0:s.SendAndWaitForResponseAsync(e,35e3,!1);return(null==t?void 0:t.Status)==ce.OK}}))}OnDevicesTasksExecutionChangeEvent(){return this._onDevicesTasksChangedEvent}OnDeviceStateChangedEvent(){return this._onDeviceStateChangedEvent}OnDeviceStateRefreshedOrChangedEvent(){return this._onDeviceStateRefreshedOrChangedEvent}OnDeviceRegisteredEvent(){return this._onDeviceRegisteredEvent}OnDeviceRemovedEvent(){return this._onDeviceRemovedEvent}OnDeviceFoundEvent(){return this._onDeviceFoundEvent}MapApiDevices(e){const t=[];return null==e?[]:(e.forEach((e=>{var n,s,o,i,a=new Ts;a.Guid=e.Guid,a.Name=e.DeviceName,a.ChannelsAmount=e.ChannelsNumber,a.DeviceType=e.DeviceType,a.CommunicationWay=e.CommunicationWay,a.DeviceState=e.DeviceState,a.IsEnabled=e.IsEnabled,a.IsVirtual=e.IsVirtual,a.SerialNumber=e.DeviceSerialNumber,a.ManufacturerGuid=e.ManufacturerGuid,a.ModelGuid=e.DeviceModelGuid,a.Model=e.DeviceModel,a.Name=e.DeviceName,a.ProtocolGuid=e.ProtocolGuid,void 0!==e.IconType&&null!==e.IconType?a.IconType=e.IconType:a.IconType=wt.Unknown;try{null===(n=e.AvailableTasks)||void 0===n||n.forEach((e=>{var t=new Ot;if(a.CommunicationWay==Ct.OneWay)"IBlindPosition"===e&&(t.InterfaceType="IBlindPositionSimple");else switch(e){case"IGatePosition":t.InterfaceType="IGatePulse";break;case"IGatewayPosition":t.InterfaceType="IGatewayPulse";break;default:t.InterfaceType=e}a.AvailableTaskTypes.push(t)})),null===(s=e.AvailableResponses)||void 0===s||s.forEach((e=>{var t=new Ut;t.InterfaceType=e,a.AvailableResponseTypes.push(t)})),null===(o=e.ChannelsConfiguration)||void 0===o||o.forEach((e=>{var t,n,s;try{var o=new Ps;o.Number=e.Channel,a.Channels.push(o),o.SetDevice(a),o.Name=e.ChannelName,o.ChannelGroups=e.GroupsGuids,o.IconName=e.IconName,o.IsHidden=e.Hidden,o.Configurations=e.Configurations,o.CustomDataAndRolesSupported=void 0!==e.CustomData&&null!==e.CustomData,void 0!==e.CustomData&&null!==e.CustomData&&(o.CustomData=e.CustomData),void 0!==e.Roles&&null!==e.Roles&&(o.Roles=e.Roles),null===(t=e.AvailableResponses)||void 0===t||t.forEach((e=>{var t=new Ut;t.InterfaceType=e,o.AvailableResponseTypes.push(t)})),null===(n=e.AvailableTasks)||void 0===n||n.forEach((e=>{var t=new Ot;a.AvailableTaskTypes.any((e=>"IBlindPositionSimple"==e.InterfaceType))?"IBlindPosition"==e&&(t.InterfaceType="IBlindPositionSimple"):t.InterfaceType=e,o.AvailableTaskTypes.push(t)}))}catch(e){null===(s=r.Log)||void 0===s||s.Error(e)}}))}catch(e){null===(i=r.Log)||void 0===i||i.Error(e)}t.push(a)})),t)}GetPairedDevicesAsync(){return Mo(this,arguments,void 0,(function*(e=!1){var t,n,s;if(this._synchronized&&!(yield null===(t=this._controllerConfiguration)||void 0===t?void 0:t.DidCofigurationChangeAsync()))return Promise.resolve(this._devices);const o=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new Lo,15e3,!0);return null==o||void 0===o?[]:o.Status==ce.OK&&null!=o.Data?e?this.MapApiDevices(o.Data):this.MapApiDevices(o.Data.filter((e=>e.DeviceType!=Tt.Scene))):(null===(s=r.Log)||void 0===s||s.Error(xo.ServiceName,`Failed to get devices. ${o.Status} ${o.Data}`),[])}))}GetDevicesAsync(){return Mo(this,arguments,void 0,(function*(e=!1){return yield this.WaitForSynchronizationAsync(),this.GetPairedDevicesAsync(e)}))}GetFoundDevicesAsync(){return Mo(this,void 0,void 0,(function*(){var e,t;const n=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new Vo,15e3,!1);return null==n?[]:n.Status==ce.OK&&null!=n.Data?this.MapApiDevices(n.Data).where((e=>e.DeviceType!==Tt.Scene)).toArray():(null===(t=r.Log)||void 0===t||t.Error(xo.ServiceName,`Failed to get found devices. ${n.Status} ${n.Data}`),[])}))}GetDevice(e){return this._devices.find((t=>t.Guid===e))}FindDevicesAsync(){return Mo(this,void 0,void 0,(function*(){var e;Ov.Get(Ge.ServiceName).ClearCache(),yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new $o,35e3,!1)}))}StopSearchingForDevices(){return Mo(this,void 0,void 0,(function*(){var e;yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new qo,2e4,!1)}))}RegisterDeviceAsync(e){return Mo(this,void 0,void 0,(function*(){var t,n;try{const n=new jo;n.Data=e.Guid;const s=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(n,2e4,!1);return Ov.Get(Ge.ServiceName).ClearCache(),Ov.Get(rt.ServiceName).ExitConfigurationModeAsync(),(null==s?void 0:s.Status)==ce.OK?(this._devices.any((t=>t.Guid==e.Guid))||this._devices.push(e),this._onDeviceRegisteredEvent.Invoke(e),kt.Executed):kt.Failed}catch(e){return null===(n=r.Log)||void 0===n||n.Error(xo.ServiceName,`Failed to paired devices: ${e}`),kt.ControllerResponseTimeout}}))}RemoveDeviceAsync(e){return Mo(this,arguments,void 0,(function*(e,t=!1){var n,s=new Ko;t&&(s=new zo),s.Data=e.Guid;const r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(s,35e3,!1);return Ov.Get(Ge.ServiceName).ClearCache(),Ov.Get(rt.ServiceName).ExitConfigurationModeAsync(),(null==r?void 0:r.Status)==ce.OK?(this._devices=this._devices.where((t=>t.Guid!=e.Guid)).toArray(),this._onDeviceRemovedEvent.Invoke(e),kt.Executed):kt.Failed}))}MapDeviceTaskToDeviceTaskInfo(e,t){let n=new Qo;const s=t;switch(s.FeatureType){case Gs.SetTemperature:n.Data=s.Temperature;break;case Gs.SetLightBrightness:n.Data=s.Brightness;break;case Gs.SetLightColor:n=new Zo;const e=s;n.R=e.R,n.G=e.G,n.B=e.B;break;case Gs.SetLightTemperature:n.Data=s.Temperature;break;case Gs.SetGatePositionPrecise:switch(s.GateControlAction){case Ns.Open:n.Data=101;break;case Ns.Close:n.Data=102;break;case Ns.Stop:n.Data=103;break;case Ns.Percentage:n.Data=s.Position}break;case Gs.SetBlindPosition:switch(s.Action){case bs.Open:n.Data=101;break;case bs.Close:n.Data=102;break;case bs.Stop:n.Data=103;break;case bs.Percentage:n.Data=s.Position}break;case Gs.SetLightBrightnessDynamicly:n.Data=s.Brightness;break;case Gs.SetBlindOpenCloseTime:n.Data=s.Data;break;case Gs.SetBlindMicroventilation:n.Data=s.Position;break;case Gs.SetFacadePositionAndTilt:n=new ei;const t=s;n.FacadeAction=t.FacadeAction,n.Tilt=t.Tilt,n.Position=t.Position;break;case Gs.LightRGBW:n.Data=s.Data;break;case Gs.GatePulse:case Gs.GatewayPulse:n.Data=0;break;case Gs.TurnOnWithTimeout:n.Data=s.SwitchOffDelaySeconds}return n.Channel=s.Channel,n.DeviceGuid=e.Guid,n.ControlFeature=s.FeatureType,n}ExecuteDeviceTaskAsync(e,t){return Mo(this,void 0,void 0,(function*(){var n,s,o,i,a,c,u,l;try{null===(n=r.Log)||void 0===n||n.Debug(xo.ServiceName,`Preparing device task execution, device: ${e.Guid} task: ${t.TaskType} channel: ${t.Channel}`);let l=this.MapDeviceTaskToDeviceTaskInfo(e,t);try{const e=new Jo(l);null===(s=r.Log)||void 0===s||s.Debug(xo.ServiceName,`Sending device task for execution, device: ${l.DeviceGuid} task: ${l.ControlFeature} channel: ${l.Channel} request: ${JSON.stringify(e)}`);const t=yield null===(o=this._connection)||void 0===o?void 0:o.SendAndWaitForResponseAsync(e,15e3,!1);switch(null==t?void 0:t.Status){case ce.OK:return kt.Executed;case ce.FatalError:return null===(i=r.Log)||void 0===i||i.Error(xo.ServiceName,`Fatal error occured when tried to execute task on device. Error code: ${t.Data}`),kt.Failed;case ce.WrongData:if("DeviceNotFound"===t.Data)return kt.DeviceNotFound;break;case ce.Error:return"DeviceResponseTimeout"===t.Data?kt.DeviceResponseTimeout:(null===(a=r.Log)||void 0===a||a.Error(xo.ServiceName,`Unknown error occured when trying to execute task on device. Error code: ${t.Data}`),kt.Failed)}}catch(e){return e.message.includes("timeout")?(null===(c=r.Log)||void 0===c||c.Error(xo.ServiceName,`Failed to get controller response in time.\n${e}`),kt.ControllerResponseTimeout):(null===(u=r.Log)||void 0===u||u.Error(xo.ServiceName,`Unknown error occured when tried to execute task on device.\n${e}`),kt.Failed)}return kt.Unknown}catch(e){return null===(l=r.Log)||void 0===l||l.Error(xo.ServiceName,`Unknown error occured when tried to execute task on device.\n${e}`),kt.Failed}}))}ExecuteDevicesTasksAsync(e){return Mo(this,void 0,void 0,(function*(){var t,n,s,o;let i=[],a=[],c=0;for(const[t,n]of e){const e=this.MapDeviceTaskToDeviceTaskInfo(t,n);e.SequnceExecutionOrder=c,c++,a.push(e)}const u=new Yo(a);try{const s=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(u,12e4,!1);let o=-1;null===(n=null==s?void 0:s.Data)||void 0===n||n.forEach((t=>{var n,a;o++;let c=kt.Unknown;switch(t.Status){case ce.OK:return kt.Executed;case ce.FatalError:null===(n=r.Log)||void 0===n||n.Error(xo.ServiceName,`Fatal error occured when tried to execute task on device. Error code: ${t.Data}`),c=kt.Failed;break;case ce.WrongData:"DeviceNotFound"===t.Data&&(c=kt.DeviceNotFound);break;case ce.Error:"DeviceResponseTimeout"===t.Data?c=kt.DeviceResponseTimeout:(null===(a=r.Log)||void 0===a||a.Error(xo.ServiceName,`Unknown error occured when trying to execute task on device. Error code: ${s.Data}`),c=kt.Failed)}let u=0,l=new xt;for(const[t,n]of e){if(u==o){l.Device=t,l.Task=n,l.Channel=n.Channel,i.push(l);break}u++}}))}catch(t){if(t.message.includes("timeout")){null===(s=r.Log)||void 0===s||s.Error(xo.ServiceName,`Failed to get controller response in time.\n${t}`);for(const[t,n]of e){let e=new xt;i.push(e),e.Device=t,e.Task=n,e.Channel=n.Channel,e.Result=kt.ControllerResponseTimeout}}else{null===(o=r.Log)||void 0===o||o.Error(xo.ServiceName,`Unknown error occured when tried to execute task on device.\n${t}`);for(const[t,n]of e){let e=new xt;i.push(e),e.Device=t,e.Task=n,e.Channel=n.Channel,e.Result=kt.Failed}}}return i}))}}xo.ServiceName="DevicesService";class Fo{constructor(){this.Channel=0,this.States=[]}}class Lo extends ae{constructor(){super(),this.Resource="/devices/list",this.Method=ue.Get}}class Bo extends ae{constructor(){super(),this.Data=!1,this.Resource="/devices/channels/states",this.Method=ue.Get}}class Wo extends ae{constructor(){super(),this.Data=!1,this.Resource="/devices/channels/states/sync",this.Method=ue.Get}}class $o extends ae{constructor(){super(),this.Resource="/devices/search",this.Method=ue.Post}}class qo extends ae{constructor(){super(),this.Resource="/devices/search/stop",this.Method=ue.Post}}class Vo extends ae{constructor(){super(),this.Resource="/devices/found/list",this.Method=ue.Get}}class Ho extends ae{constructor(){super(),this.Resource="/devices/tasks",this.Method=ue.Get}}class jo extends ae{constructor(){super(),this.Resource="/devices/device/pair",this.Method=ue.Put}}class Ko extends ae{constructor(){super(),this.Resource="/devices/device/unpair",this.Method=ue.Put}}class zo extends ae{constructor(){super(),this.Resource="/devices/device/unpair/force",this.Method=ue.Put}}class Jo extends ae{constructor(e){super(),this.Resource="/devices/device/control",this.Method=ue.Post,this.Data=e}}class Yo extends ae{constructor(e){super(),this.Resource="/devices/devices/control",this.Method=ue.Post,this.Data=e}}class Xo extends ae{constructor(e){super(),this.Resource="/logic/device/used",this.Method=ue.Get,this.Data=e}}class Qo{constructor(){this.DeviceGuid="",this.Channel=0,this.ControlFeature=Gs.GetState,this.SequnceExecutionOrder=0}}class Zo extends Qo{constructor(){super(...arguments),this.R=0,this.G=0,this.B=0}}class ei extends Qo{constructor(){super(...arguments),this.FacadeAction=Is.Stop,this.Tilt=0,this.Position=0}}class ti{constructor(){this.DeviceGuid="",this.ConditionsAsCondition=[],this.ConditionsAsTask=[]}}class ni extends RangeError{paramName;constructor(e){super(`${e} was out of range. Must be non-negative and less than the size of the collection.`),this.paramName=e,this.name="ArgumentOutOfRangeException",this.stack=this.stack||(new Error).stack}}const si=Object.freeze({MoreThanOneElement:"Sequence contains more than one element",MoreThanOneMatchingElement:"Sequence contains more than one matching element",NoElements:"Sequence contains no elements",NoMatch:"Sequence contains no matching element"});class ri extends Error{constructor(e){super(e),this.name="InvalidOperationException",this.stack=this.stack||(new Error).stack}}const oi=(e,t)=>e===t;class ii{iterator;constructor(e){this.iterator=e}[Symbol.asyncIterator](){return this.iterator()}}class ai{dataFunc;constructor(e){this.dataFunc=e}[Symbol.asyncIterator](){const{dataFunc:e}=this;return async function*(){if(1===e.type)for(const t of e.generator())yield t;else for(const t of await e.generator())yield t}()}}class ci{iterator;constructor(e){this.iterator=e}[Symbol.iterator](){return this.iterator()}}class ui extends Array{}const li=(e,t,n,s)=>{if(s){if(!n)throw new ReferenceError("TAccumulate function is undefined");return gi(e,t,n,s)}return n?hi(e,t,n):di(e,t)},di=(e,t)=>{let n;for(const s of e)n=n?t(n,s):s;if(void 0===n)throw new ri(si.NoElements);return n},hi=(e,t,n)=>{let s=t;for(const t of e)s=n(s,t);return s},gi=(e,t,n,s)=>{let r=t;for(const t of e)r=n(r,t);return s(r)},pi=(e,t)=>{for(const n of e)if(!1===t(n))return!1;return!0},fi=async(e,t)=>{for(const n of e)if(!1===await t(n))return!1;return!0},vi=(e,t)=>t?yi(e,t):mi(e),mi=e=>{for(const t of e)return!0;return!1},yi=(e,t)=>{for(const n of e)if(!0===t(n))return!0;return!1},wi=async(e,t)=>{for(const n of e)if(!0===await t(n))return!0;return!1},Si=(e,t)=>new ci((function*(){yield*e,yield t})),Ai=e=>{if(Array.isArray(e)){if(0===e.length)throw new ri(si.NoElements);return new ii((async function*(){for await(const t of e)yield t}))}return new ii(e)},_i=e=>Ai((async function*(){for(const t of e)yield t})),Ci=(e,t)=>new ai({generator:t,type:e}),Ti=e=>Ci(0,(async()=>{const t=[];for(const n of e)t.push(n);return t})),Di=(e,t)=>{let n=0,s=0;if(t)for(const r of e)n+=t(r),s+=1;else for(const t of e)n+=t,s+=1;if(0===s)throw new ri(si.NoElements);return n/s},ki=async(e,t)=>{let n=0,s=0;for(const r of e)n+=await t(r),s+=1;if(0===s)throw new ri(si.NoElements);return n/s},Gi=(e,t)=>{if(t<1)throw new ni("size");return new ci((function*(){let n=[];for(const s of e)n.push(s),n.length===t&&(yield n,n=[]);n.length&&(yield n)}))},bi=(e,t)=>new ci((function*(){yield*e,yield*t})),Ni=(e,t,n=oi)=>{for(const s of e)if(n(t,s))return!0;return!1},Ei=async(e,t,n)=>{for(const s of e)if(await n(t,s))return!0;return!1},Ii=(e,t)=>t?Pi(e,t):Ri(e),Ri=e=>{let t=0;for(const n of e)t++;return t},Pi=(e,t)=>{let n=0;for(const s of e)!0===t(s)&&n++;return n},Oi=async(e,t)=>{let n=0;for(const s of e)!0===await t(s)&&n++;return n},Ui=(e,t)=>new ci((function*(){let n=!1;for(const t of e)n=!0,yield t;n||(yield t)})),Mi=(e,t=oi)=>new ci((function*(){const n=[];for(const s of e)n.find((e=>t(e,s)))||(n.push(s),yield s)})),xi=(e,t)=>Ai((async function*(){const n=[];e:for(const s of e){for(const e of n)if(await t(e,s))continue e;n.push(s),yield s}})),Fi=(e,t)=>new ci((function*(){for(const n of e)t(n),yield n})),Li=(e,t)=>Ai((async function*(){for(const n of e)await t(n),yield n})),Bi=(e,t)=>{if(t<0)throw new ni("index");let n=0;for(const s of e)if(t===n++)return s;throw new ni("index")},Wi=(e,t)=>{let n=0;for(const s of e)if(t===n++)return s;return null},$i=(e,t,n=oi)=>new ci((function*(){const s=[...t];for(const t of e){let e=!1;for(let r=0;r<s.length;r++)if(!0===n(t,s[r])){e=!0;break}!1===e&&(yield t)}})),qi=(e,t,n)=>Ai((async function*(){const s=[...t];for(const t of e){let e=!1;for(let r=0;r<s.length;r++){const o=s[r];if(!0===await n(t,o)){e=!0;break}}!1===e&&(yield t)}})),Vi=(e,t)=>t?ji(e,t):Hi(e),Hi=e=>{const t=e[Symbol.iterator]().next();if(!0===t.done)throw new ri(si.NoElements);return t.value},ji=(e,t)=>{for(const n of e)if(!0===t(n))return n;throw new ri(si.NoMatch)},Ki=async(e,t)=>{for(const n of e)if(!0===await t(n))return n;throw new ri(si.NoMatch)},zi=(e,t)=>t?Yi(e,t):Ji(e),Ji=e=>e[Symbol.iterator]().next().value??null,Yi=(e,t)=>{for(const n of e)if(!0===t(n))return n;return null},Xi=async(e,t)=>{for(const n of e)if(!0===await t(n))return n;return null};class Qi extends ui{key;constructor(e,t){super(1),this.key=e,this[0]=t}}const Zi=(e,t,n)=>{let s;return s=n?((e,t,n)=>function*(){const s=new Array;for(const r of e){const e=t(r);let o=!1;for(let t=0;t<s.length;t++){const i=s[t];if(n(i.key,e)){i.push(r),o=!0;break}}!1===o&&s.push(new Qi(e,r))}for(const e of s)yield e})(e,t,n):((e,t)=>function*(){const n={};for(const s of e){const e=t(s),r=n[e];r?r.push(s):n[e]=new Qi(e,s)}for(const e in n)yield n[e]})(e,t),new ci(s)},ea=(e,t,n)=>n?na(e,t,n):ta(e,t),ta=(e,t)=>Ai((async function*(){const n={};for(const s of e){const e=await t(s),r=n[e];r?r.push(s):n[e]=new Qi(e,s)}for(const e in n)yield n[e]})),na=(e,t,n)=>Ai((async function*(){const s=new Array;for(const r of e){const e=await t(r);let o=!1;for(let t=0;t<s.length;t++){const i=s[t];if(!0===await n(i.key,e)){i.push(r),o=!0;break}}!1===o&&s.push(new Qi(e,r))}for(const e of s)yield e})),sa=(e,t,n,s)=>s?((e,t,n,s)=>new ci((function*(){const r=new Array;for(const o of e){const e=t(o);let i=!1;for(let t=0;t<r.length;t++){const a=r[t];if(s(a.key,e)){a.push(n(o)),i=!0;break}}if(!1===i){const t=n(o);r.push(new Qi(e,t))}}for(const e of r)yield e})))(e,t,n,s):((e,t,n)=>new ci((function*(){const s={};for(const r of e){const e=t(r),o=s[e],i=n(r);o?o.push(i):s[e]=new Qi(e,i)}for(const e in s)yield s[e]})))(e,t,n),ra=(e,t,n,s,r,o)=>{const i=o?oa(e,t,n,s,r,o):ia(e,t,n,s,r);return new ci(i)},oa=(e,t,n,s,r,o)=>function*(){const i=[];for(const e of t){const t=s(e),n=i.find((e=>o(e.key,t)));n?n.values.push(e):i.push({key:t,values:[e]})}for(const t of e){const e=n(t),s=i.find((t=>o(t.key,e)))??{key:e,values:[]};yield r(t,s.values)}},ia=(e,t,n,s,r)=>function*(){const o=new Map;for(const e of t){const t=s(e),n=o.get(t);n?n.push(e):o.set(t,[e])}for(const t of e){const e=n(t),s=o.get(e)??[];yield r(t,s)}},aa=(e,t,n,s,r,o)=>{const i=o?ca(e,t,n,s,r,o):ua(e,t,n,s,r);return Ai(i)},ca=(e,t,n,s,r,o)=>async function*(){const i=[];for(const e of t){const t=await s(e),n=i.find((e=>o(e.key,t)));n?n.values.push(e):i.push({key:t,values:[e]})}for(const t of e){const e=await n(t),s=i.find((t=>o(t.key,e)))??{key:e,values:[]};yield r(t,s.values)}},ua=(e,t,n,s,r)=>async function*(){const o=new Map;for(const e of t){const t=await s(e),n=o.get(t);n?n.push(e):o.set(t,[e])}for(const t of e){const e=await n(t),s=o.get(e)??[];yield r(t,s)}},la=(e,t,n=oi)=>new ci((function*(){const s=[...e.distinct(n)];if(0===s.length)return;const r=[...t];for(let e=0;e<s.length;e++){const t=s[e];for(let e=0;e<r.length;e++)if(!0===n(t,r[e])){yield t;break}}})),da=(e,t,n)=>Ai((async function*(){const s=[];for await(const t of e.distinctAsync(n))s.push(t);if(0===s.length)return;const r=[...t];for(let e=0;e<s.length;e++){const t=s[e];for(let e=0;e<r.length;e++){const s=r[e];if(!0===await n(t,s)){yield t;break}}}})),ha=(e,t,n,s,r,o=oi)=>new ci((function*(){const i=[...t];for(const t of e){const e=n(t);for(const n of i){const i=s(n);!0===o(e,i)&&(yield r(t,n))}}})),ga=(e,t)=>t?fa(e,t):pa(e),pa=e=>{let t;for(const n of e)t=n;if(!t)throw new ri(si.NoElements);return t},fa=(e,t)=>{let n;for(const s of e)!0===t(s)&&(n=s);if(!n)throw new ri(si.NoMatch);return n},va=async(e,t)=>{let n;for(const s of e)!0===await t(s)&&(n=s);if(!n)throw new ri(si.NoMatch);return n},ma=(e,t)=>t?wa(e,t):ya(e),ya=e=>{let t=null;for(const n of e)t=n;return t},wa=(e,t)=>{let n=null;for(const s of e)!0===t(s)&&(n=s);return n},Sa=async(e,t)=>{let n=null;for(const s of e)!0===await t(s)&&(n=s);return n},Aa=(e,t)=>t?Ca(e,t):_a(e),_a=e=>{let t=null;for(const n of e)t=Math.max(t??Number.NEGATIVE_INFINITY,n);if(null===t)throw new ri(si.NoElements);return t},Ca=(e,t)=>{let n=null;for(const s of e)n=Math.max(n??Number.NEGATIVE_INFINITY,t(s));if(null===n)throw new ri(si.NoElements);return n},Ta=async(e,t)=>{let n=null;for(const s of e)n=Math.max(n??Number.NEGATIVE_INFINITY,await t(s));if(null===n)throw new ri(si.NoElements);return n},Da=(e,t)=>t?Ga(e,t):ka(e),ka=e=>{let t=null;for(const n of e)t=Math.min(t??Number.POSITIVE_INFINITY,n);if(null===t)throw new ri(si.NoElements);return t},Ga=(e,t)=>{let n=null;for(const s of e)n=Math.min(n??Number.POSITIVE_INFINITY,t(s));if(null===n)throw new ri(si.NoElements);return n},ba=async(e,t)=>{let n=null;for(const s of e)n=Math.min(n??Number.POSITIVE_INFINITY,await t(s));if(null===n)throw new ri(si.NoElements);return n},Na=(e,t)=>{const n="string"==typeof t?e=>typeof e===t:e=>e instanceof t;return new ci((function*(){for(const t of e)n(t)&&(yield t)}))};async function*Ea(e,t,n,s){const r=await(async(e,t)=>{const n=new Map;for(const s of e){const e=await t(s),r=n.get(e);r?r.push(s):n.set(e,[s])}return n})(e,t),o=[...r.keys()].sort(s||void 0);if(n)for(let e=0;e<o.length;e++)yield r.get(o[e]);else for(let e=o.length-1;e>=0;e--)yield r.get(o[e])}function*Ia(e,t,n,s){const r=((e,t)=>{const n=new Map;for(const s of e){const e=t(s),r=n.get(e);r?r.push(s):n.set(e,[s])}return n})(e,t),o=[...r.keys()].sort(s||void 0);if(n)for(let e=0;e<o.length;e++)yield r.get(o[e]);else for(let e=o.length-1;e>=0;e--)yield r.get(o[e])}class Ra extends ii{orderedPairs;constructor(e){super((async function*(){for await(const t of e())yield*t})),this.orderedPairs=e}static generateAsync(e,t,n,s){let r;return r=e instanceof Ra?async function*(){for await(const r of e.orderedPairs())yield*Ea(r,t,n,s)}:()=>async function*(e,t,n,s){const r=await(async(e,t)=>{const n=new Map;for await(const s of e){const e=await t(s),r=n.get(e);r?r.push(s):n.set(e,[s])}return n})(e,t),o=[...r.keys()].sort(s||void 0);if(n)for(let e=0;e<o.length;e++)yield r.get(o[e]);else for(let e=o.length-1;e>=0;e--)yield r.get(o[e])}(e,t,n,s),new Ra(r)}static generate(e,t,n,s){let r;return r=e instanceof Ra?async function*(){for await(const r of e.orderedPairs())yield*Ia(r,t,n,s)}:()=>async function*(e,t,n,s){const r=await(async(e,t)=>{const n=new Map;for await(const s of e){const e=t(s),r=n.get(e);r?r.push(s):n.set(e,[s])}return n})(e,t),o=[...r.keys()].sort(s||void 0);if(n)for(let e=0;e<o.length;e++)yield r.get(o[e]);else for(let e=o.length-1;e>=0;e--)yield r.get(o[e])}(e,t,n,s),new Ra(r)}thenBy(e,t){return Ra.generate(this,e,!0,t)}thenByAsync(e,t){return Ra.generateAsync(this,e,!0,t)}thenByDescending(e,t){return Ra.generate(this,e,!1,t)}thenByDescendingAsync(e,t){return Ra.generateAsync(this,e,!1,t)}}function*Pa(e,t,n,s){const r=((e,t)=>{const n=new Map;for(const s of e){const e=t(s),r=n.get(e);r?r.push(s):n.set(e,[s])}return n})(e,t),o=[...r.keys()].sort(s||void 0);if(n)for(let e=0;e<o.length;e++)yield r.get(o[e]);else for(let e=o.length-1;e>=0;e--)yield r.get(o[e])}async function*Oa(e,t,n,s){const r=await(async(e,t)=>{const n=new Map;for(const s of e){const e=await t(s),r=n.get(e);r?r.push(s):n.set(e,[s])}return n})(e,t),o=[...r.keys()].sort(s||void 0);if(n)for(let e=0;e<o.length;e++)yield r.get(o[e]);else for(let e=o.length-1;e>=0;e--)yield r.get(o[e])}class Ua extends ci{orderedPairs;constructor(e){super((function*(){for(const t of e())yield*t})),this.orderedPairs=e}static generate(e,t,n,s){let r;return r=e instanceof Ua?function*(){for(const r of e.orderedPairs())yield*Pa(r,t,n,s)}:()=>Pa(e,t,n,s),new Ua(r)}static generateAsync(e,t,n,s){let r;return r=e instanceof Ua?async function*(){for(const r of e.orderedPairs())yield*Oa(r,t,n,s)}:()=>Oa(e,t,n,s),new Ra(r)}thenBy(e,t){return Ua.generate(this,e,!0,t)}thenByAsync(e,t){return Ua.generateAsync(this,e,!0,t)}thenByDescending(e,t){return Ua.generate(this,e,!1,t)}thenByDescendingAsync(e,t){return Ua.generateAsync(this,e,!1,t)}}const Ma=(e,t)=>Ua.generate(e,(e=>e),!0,t),xa=(e,t,n)=>Ua.generate(e,t,!0,n),Fa=(e,t,n)=>Ua.generateAsync(e,t,!0,n),La=(e,t,n)=>Ua.generate(e,t,!1,n),Ba=(e,t,n)=>Ua.generateAsync(e,t,!1,n),Wa=(e,t)=>Ua.generate(e,(e=>e),!1,t),$a=(e,t)=>{const n=[],s=[];for(const r of e)!0===t(r)?s.push(r):n.push(r);return[s,n]},qa=async(e,t)=>{const n=[],s=[];for(const r of e)!0===await t(r)?s.push(r):n.push(r);return[s,n]},Va=(e,t)=>new ci((function*(){yield t,yield*e})),Ha=e=>new ci((function*(){const t=[...e];for(let e=t.length-1;e>=0;e--)yield t[e]})),ja=(e,t)=>{if("function"==typeof t){const{length:n}=t;return 1===n?Ka(e,t):za(e,t)}return Ja(e,t)},Ka=(e,t)=>new ci((function*(){for(const n of e)yield t(n)})),za=(e,t)=>new ci((function*(){let n=0;for(const s of e)yield t(s,n),n++})),Ja=(e,t)=>new ci((function*(){for(const n of e)yield n[t]})),Ya=(e,t)=>"function"==typeof t?1===t.length?Xa(e,t):Qa(e,t):Za(e,t),Xa=(e,t)=>Ai((async function*(){for(const n of e)yield t(n)})),Qa=(e,t)=>Ai((async function*(){let n=0;for(const s of e)yield t(s,n),n++})),Za=(e,t)=>Ai((async function*(){for(const n of e)yield n[t]})),ec=(e,t)=>"function"==typeof t?1===t.length?tc(e,t):nc(e,t):sc(e,t),tc=(e,t)=>new ci((function*(){for(const n of e)for(const e of t(n))yield e})),nc=(e,t)=>new ci((function*(){let n=0;for(const s of e){for(const e of t(s,n))yield e;n++}})),sc=(e,t)=>new ci((function*(){for(const n of e)for(const e of n[t])yield e})),rc=(e,t)=>1===t.length?oc(e,t):ic(e,t),oc=(e,t)=>Ai((async function*(){for(const n of e){const e=await t(n);for(const t of e)yield t}})),ic=(e,t)=>Ai((async function*(){let n=0;for(const s of e){const e=await t(s,n);for(const t of e)yield t;n++}})),ac=(e,t,n=oi)=>{const s=e[Symbol.iterator](),r=t[Symbol.iterator]();let o=s.next(),i=r.next();for(;!o.done&&!i.done;){if(!n(o.value,i.value))return!1;o=s.next(),i=r.next()}return!0===o.done&&!0===i.done},cc=async(e,t,n)=>{const s=e[Symbol.iterator](),r=t[Symbol.iterator]();let o=s.next(),i=r.next();for(;!o.done&&!i.done;){if(!1===await n(o.value,i.value))return!1;o=s.next(),i=r.next()}return!0===o.done&&!0===i.done},uc=(e,t)=>t?dc(e,t):lc(e),lc=e=>{let t=!1,n=null;for(const s of e){if(!0===t)throw new ri(si.MoreThanOneElement);t=!0,n=s}if(!1===t)throw new ri(si.NoElements);return n},dc=(e,t)=>{let n=!1,s=null;for(const r of e)if(t(r)){if(!0===n)throw new ri(si.MoreThanOneMatchingElement);n=!0,s=r}if(!1===n)throw new ri(si.NoMatch);return s},hc=async(e,t)=>{let n=!1,s=null;for(const r of e)if(await t(r)){if(!0===n)throw new ri(si.MoreThanOneMatchingElement);n=!0,s=r}if(!1===n)throw new ri(si.NoMatch);return s},gc=(e,t)=>t?fc(e,t):pc(e),pc=e=>{let t=!1,n=null;for(const s of e){if(!0===t)throw new ri(si.MoreThanOneElement);t=!0,n=s}return n},fc=(e,t)=>{let n=!1,s=null;for(const r of e)if(t(r)){if(!0===n)throw new ri(si.MoreThanOneMatchingElement);n=!0,s=r}return s},vc=async(e,t)=>{let n=!1,s=null;for(const r of e)if(await t(r)){if(!0===n)throw new ri(si.MoreThanOneElement);n=!0,s=r}return s},mc=(e,t)=>new ci((function*(){let n=0;for(const s of e)n++>=t&&(yield s)})),yc=(e,t)=>1===t.length?wc(e,t):Sc(e,t),wc=(e,t)=>new ci((function*(){let n=!0;for(const s of e)!1===n?yield s:!1===t(s)&&(n=!1,yield s)})),Sc=(e,t)=>new ci((function*(){let n=0,s=!0;for(const r of e)!1===s?yield r:!1===t(r,n)&&(s=!1,yield r),n++})),Ac=(e,t)=>1===t.length?_c(e,t):Cc(e,t),_c=(e,t)=>Ai((async function*(){let n=!0;for(const s of e)!1===n?yield s:!1===await t(s)&&(n=!1,yield s)})),Cc=(e,t)=>Ai((async function*(){let n=0,s=!0;for(const r of e)!1===s?yield r:!1===await t(r,n)&&(s=!1,yield r),n++})),Tc=(e,t)=>t?kc(e,t):Dc(e),Dc=e=>{let t=0;for(const n of e)t+=n;return t},kc=(e,t)=>{let n=0;for(const s of e)n+=t(s);return n},Gc=async(e,t)=>{let n=0;for(const s of e)n+=await t(s);return n},bc=(e,t)=>new ci((function*(){let n=t>0?t:0;for(const t of e){if(0==n--)break;yield t}})),Nc=(e,t)=>1===t.length?Ec(e,t):Ic(e,t),Ec=(e,t)=>new ci((function*(){for(const n of e){if(!t(n))break;yield n}})),Ic=(e,t)=>new ci((function*(){let n=0;for(const s of e){if(!t(s,n++))break;yield s}})),Rc=(e,t)=>1===t.length?Pc(e,t):Oc(e,t),Pc=(e,t)=>Ai((async function*(){for(const n of e){if(!await t(n))break;yield n}})),Oc=(e,t)=>Ai((async function*(){let n=0;for(const s of e){if(!await t(s,n++))break;yield s}})),Uc=e=>[...e],Mc=(e,t)=>{const n=new Map;for(const s of e){const e=t(s),r=n.get(e);void 0===r?n.set(e,[s]):r.push(s)}return n},xc=async(e,t)=>{const n=new Map;for(const s of e){const e=await t(s),r=n.get(e);void 0===r?n.set(e,[s]):r.push(s)}return n},Fc=(e,t)=>{const n={};for(const s of e)n[t(s)]=s;return n},Lc=async(e,t)=>{const n={};for(const s of e)n[await t(s)]=s;return n},Bc=e=>new Set(e),Wc=(e,t,n)=>n?qc(e,t,n):$c(e,t),$c=(e,t)=>new ci((function*(){const n=new Set;for(const t of e)!1===n.has(t)&&(yield t,n.add(t));for(const e of t)!1===n.has(e)&&(yield e,n.add(e))})),qc=(e,t,n)=>new ci((function*(){const s=[];for(const r of[e,t])for(const e of r){let t=!1;for(const r of s)if(!0===n(e,r)){t=!0;break}!1===t&&(yield e,s.push(e))}})),Vc=(e,t,n)=>Ai((async function*(){const s=[];for(const r of[e,t])for(const e of r){let t=!1;for(const r of s)if(!0===await n(e,r)){t=!0;break}!1===t&&(yield e,s.push(e))}})),Hc=(e,t)=>1===t.length?jc(e,t):Kc(e,t),jc=(e,t)=>new ci((function*(){for(const n of e)!0===t(n)&&(yield n)})),Kc=(e,t)=>new ci((function*(){let n=0;for(const s of e)!0===t(s,n++)&&(yield s)})),zc=(e,t)=>1===t.length?Jc(e,t):Yc(e,t),Jc=(e,t)=>Ai((async function*(){for(const n of e)!0===await t(n)&&(yield n)})),Yc=(e,t)=>Ai((async function*(){let n=0;for(const s of e)!0===await t(s,n++)&&(yield s)})),Xc=(e,t,n)=>n?Zc(e,t,n):Qc(e,t),Qc=(e,t)=>new ci((function*(){const n=e[Symbol.iterator](),s=t[Symbol.iterator]();for(;;){const e=n.next(),t=s.next();if(e.done||t.done)break;yield[e.value,t.value]}})),Zc=(e,t,n)=>new ci((function*(){const s=e[Symbol.iterator](),r=t[Symbol.iterator]();for(;;){const e=s.next(),t=r.next();if(e.done||t.done)break;yield n(e.value,t.value)}})),eu=(e,t,n)=>Ai((async function*(){const s=e[Symbol.iterator](),r=t[Symbol.iterator]();for(;;){const e=s.next(),t=r.next();if(e.done||t.done)break;yield n(e.value,t.value)}})),tu=e=>{const t=e.prototype,n=(e,n)=>{const s=function(...t){return e(this,...t)};Object.defineProperty(s,"length",{value:e.length-1}),t[n]=s};n(li,"aggregate"),n(pi,"all"),n(fi,"allAsync"),n(vi,"any"),n(wi,"anyAsync"),n(Si,"append"),n(_i,"asAsync"),n(Ti,"asParallel"),n(Di,"average"),n(ki,"averageAsync"),n(Gi,"chunk"),n(bi,"concatenate"),n(Ni,"contains"),n(Ei,"containsAsync"),n(Ii,"count"),n(Oi,"countAsync"),n(Ui,"defaultIfEmpty"),n(Mi,"distinct"),n(xi,"distinctAsync"),n(Fi,"each"),n(Li,"eachAsync"),n(Bi,"elementAt"),n(Wi,"elementAtOrDefault"),n($i,"except"),n(qi,"exceptAsync"),n(Vi,"first"),n(Ki,"firstAsync"),n(zi,"firstOrDefault"),n(Xi,"firstOrDefaultAsync"),n(Zi,"groupBy"),n(ea,"groupByAsync"),n(sa,"groupByWithSel"),n(ra,"groupJoin"),n(aa,"groupJoinAsync"),n(la,"intersect"),n(da,"intersectAsync"),n(ha,"joinByKey"),n(ga,"last"),n(va,"lastAsync"),n(ma,"lastOrDefault"),n(Sa,"lastOrDefaultAsync"),n(Aa,"max"),n(Ta,"maxAsync"),n(Da,"min"),n(ba,"minAsync"),n(Na,"ofType"),n(Ma,"order"),n(xa,"orderBy"),n(Fa,"orderByAsync"),n(La,"orderByDescending"),n(Ba,"orderByDescendingAsync"),n(Wa,"orderDescending"),n(Va,"prepend"),n(Ha,"reverse"),n(ja,"select"),n(Ya,"selectAsync"),n(ec,"selectMany"),n(rc,"selectManyAsync"),n(ac,"sequenceEquals"),n(cc,"sequenceEqualsAsync"),n(uc,"single"),n(hc,"singleAsync"),n(gc,"singleOrDefault"),n(vc,"singleOrDefaultAsync"),n(mc,"skip"),n(yc,"skipWhile"),n(Ac,"skipWhileAsync"),n(Tc,"sum"),n(Gc,"sumAsync"),n(bc,"take"),n(Nc,"takeWhile"),n(Rc,"takeWhileAsync"),n(Uc,"toArray"),n(Mc,"toMap"),n(xc,"toMapAsync"),n(Fc,"toObject"),n(Lc,"toObjectAsync"),n($a,"partition"),n(qa,"partitionAsync"),n(Bc,"toSet"),n(Wc,"union"),n(Vc,"unionAsync"),n(Hc,"where"),n(zc,"whereAsync"),n(Xc,"zip"),n(eu,"zipAsync")},nu=(e,t,n,s)=>{if(s){if(!n)throw new ReferenceError("TAccumulate function is undefined");return ou(e,t,n,s)}return n?ru(e,t,n):su(e,t)},su=async(e,t)=>{let n;for await(const s of e)n=n?t(n,s):s;if(void 0===n)throw new ri(si.NoElements);return n},ru=async(e,t,n)=>{let s=t;for await(const t of e)s=n(s,t);return s},ou=async(e,t,n,s)=>{let r=t;for await(const t of e)r=n(r,t);return s(r)},iu=async(e,t)=>{for await(const n of e)if(!1===t(n))return!1;return!0},au=async(e,t)=>{for await(const n of e)if(!1===await t(n))return!1;return!0},cu=(e,t)=>new ii((async function*(){yield*e,yield t})),uu=(e,t)=>t?du(e,t):lu(e),lu=async e=>{for await(const t of e)return!0;return!1},du=async(e,t)=>{for await(const n of e)if(!0===t(n))return!0;return!1},hu=async(e,t)=>{for await(const n of e)if(!0===await t(n))return!0;return!1},gu=e=>Ci(0,(async()=>{const t=[];for await(const n of e)t.push(n);return t})),pu=async(e,t)=>{let n=0,s=0;if(t)for await(const r of e)n+=t(r),s+=1;else for await(const t of e)n+=t,s+=1;if(0===s)throw new ri(si.NoElements);return n/s},fu=async(e,t)=>{let n=0,s=0;for await(const r of e)n+=await t(r),s+=1;if(0===s)throw new ri(si.NoElements);return n/s},vu=(e,t)=>{if(t<1)throw new ni("size");return new ii((async function*(){let n=[];for await(const s of e)n.push(s),n.length===t&&(yield n,n=[]);n.length&&(yield n)}))},mu=(e,t)=>new ii((async function*(){yield*e,yield*t})),yu=async(e,t,n=oi)=>{for await(const s of e)if(n(t,s))return!0;return!1},wu=async(e,t,n)=>{for await(const s of e)if(await n(t,s))return!0;return!1},Su=(e,t)=>t?_u(e,t):Au(e),Au=async e=>{let t=0;for await(const n of e)t++;return t},_u=async(e,t)=>{let n=0;for await(const s of e)!0===t(s)&&n++;return n},Cu=async(e,t)=>{let n=0;for await(const s of e)!0===await t(s)&&n++;return n},Tu=(e,t)=>new ii((async function*(){let n=!1;for await(const t of e)n=!0,yield t;n||(yield t)})),Du=(e,t=oi)=>new ii((async function*(){const n=[];for await(const s of e)n.find((e=>t(e,s)))||(n.push(s),yield s)})),ku=(e,t)=>new ii((async function*(){const n=[];e:for await(const s of e){for(const e of n)if(await t(e,s))continue e;n.push(s),yield s}})),Gu=(e,t)=>new ii((async function*(){for await(const n of e)t(n),yield n})),bu=(e,t)=>new ii((async function*(){for await(const n of e)await t(n),yield n})),Nu=async(e,t)=>{if(t<0)throw new ni("index");let n=0;for await(const s of e)if(t===n++)return s;throw new ni("index")},Eu=async(e,t)=>{let n=0;for await(const s of e)if(t===n++)return s;return null},Iu=(e,t,n=oi)=>new ii((async function*(){const s=[];for await(const e of t)s.push(e);for await(const t of e){let e=!1;for(let r=0;r<s.length;r++){const o=s[r];if(!0===n(t,o)){e=!0;break}}!1===e&&(yield t)}})),Ru=(e,t,n)=>new ii((async function*(){const s=[];for await(const e of t)s.push(e);for await(const t of e){let e=!1;for(let r=0;r<s.length;r++){const o=s[r];if(!0===await n(t,o)){e=!0;break}}!1===e&&(yield t)}})),Pu=(e,t)=>t?Uu(e,t):Ou(e),Ou=async e=>{const t=await e[Symbol.asyncIterator]().next();if(!0===t.done)throw new ri(si.NoElements);return t.value},Uu=async(e,t)=>{for await(const n of e)if(!0===t(n))return n;throw new ri(si.NoMatch)},Mu=async(e,t)=>{for await(const n of e)if(!0===await t(n))return n;throw new ri(si.NoMatch)},xu=(e,t)=>t?Lu(e,t):Fu(e),Fu=async e=>(await e[Symbol.asyncIterator]().next()).value??null,Lu=async(e,t)=>{for await(const n of e)if(!0===t(n))return n;return null},Bu=async(e,t)=>{for await(const n of e)if(!0===await t(n))return n;return null},Wu=(e,t,n)=>n?$u(e,t,n):qu(e,t),$u=(e,t,n)=>new ii((async function*(){const s=new Array;for await(const r of e){const e=t(r);let o=!1;for(let t=0;t<s.length;t++){const i=s[t];if(n(i.key,e)){i.push(r),o=!0;break}}!1===o&&s.push(new Qi(e,r))}for(const e of s)yield e})),qu=(e,t)=>new ii((async function*(){const n={};for await(const s of e){const e=t(s),r=n[e];r?r.push(s):n[e]=new Qi(e,s)}for(const e in n)yield n[e]})),Vu=(e,t,n)=>n?ju(e,t,n):Hu(e,t),Hu=(e,t)=>new ii((async function*(){const n={};for await(const s of e){const e=await t(s),r=n[e];r?r.push(s):n[e]=new Qi(e,s)}for(const e in n)yield n[e]})),ju=(e,t,n)=>new ii((async function*(){const s=new Array;for await(const r of e){const e=await t(r);let o=!1;for(let t=0;t<s.length;t++){const i=s[t];if(!0===await n(i.key,e)){i.push(r),o=!0;break}}!1===o&&s.push(new Qi(e,r))}for(const e of s)yield e})),Ku=(e,t,n,s)=>s?Ju(e,t,n,s):zu(e,t,n),zu=(e,t,n)=>new ii((async function*(){const s={};for await(const r of e){const e=t(r),o=s[e],i=n(r);o?o.push(i):s[e]=new Qi(e,i)}for(const e in s)yield s[e]})),Ju=(e,t,n,s)=>new ii((async function*(){const r=new Array;for await(const o of e){const e=t(o);let i=!1;for(let t=0;t<r.length;t++){const a=r[t];if(s(a.key,e)){a.push(n(o)),i=!0;break}}if(!1===i){const t=n(o);r.push(new Qi(e,t))}}for(const e of r)yield e})),Yu=(e,t,n,s,r,o)=>{const i=o?Xu(e,t,n,s,r,o):Qu(e,t,n,s,r);return new ii(i)},Xu=(e,t,n,s,r,o)=>async function*(){const i=[];for await(const e of t){const t=s(e),n=i.find((e=>o(e.key,t)));n?n.values.push(e):i.push({key:t,values:[e]})}for await(const t of e){const e=n(t),s=i.find((t=>o(t.key,e)))??{key:e,values:[]};yield r(t,s.values)}},Qu=(e,t,n,s,r)=>async function*(){const o=new Map;for await(const e of t){const t=s(e),n=o.get(t);n?n.push(e):o.set(t,[e])}for await(const t of e){const e=n(t),s=o.get(e)??[];yield r(t,s)}},Zu=(e,t,n,s,r,o)=>{const i=o?el(e,t,n,s,r,o):tl(e,t,n,s,r);return new ii(i)},el=(e,t,n,s,r,o)=>async function*(){const i=[];for await(const e of t){const t=await s(e),n=i.find((e=>o(e.key,t)));n?n.values.push(e):i.push({key:t,values:[e]})}for await(const t of e){const e=await n(t),s=i.find((t=>o(t.key,e)))??{key:e,values:[]};yield r(t,s.values)}},tl=(e,t,n,s,r)=>async function*(){const o=new Map;for await(const e of t){const t=await s(e),n=o.get(t);n?n.push(e):o.set(t,[e])}for await(const t of e){const e=await n(t),s=o.get(e)??[];yield r(t,s)}},nl=(e,t,n=oi)=>new ii((async function*(){const s=await e.distinct(n).toArray();if(0===s.length)return;const r=await t.toArray();for(let e=0;e<s.length;e++){const t=s[e];for(let e=0;e<r.length;e++){const s=r[e];if(!0===n(t,s)){yield t;break}}}})),sl=(e,t,n)=>new ii((async function*(){const s=await e.distinctAsync(n).toArray();if(0===s.length)return;const r=await t.toArray();for(let e=0;e<s.length;e++){const t=s[e];for(let e=0;e<r.length;e++){const s=r[e];if(!0===await n(t,s)){yield t;break}}}})),rl=(e,t,n,s,r,o=oi)=>new ii((async function*(){const i=[];for await(const e of t)i.push(e);for await(const t of e){const e=n(t);for(const n of i){const i=s(n);!0===o(e,i)&&(yield r(t,n))}}})),ol=(e,t)=>t?al(e,t):il(e),il=async e=>{let t=null;for await(const n of e)t=n;if(!t)throw new ri(si.NoElements);return t},al=async(e,t)=>{let n=null;for await(const s of e)!0===t(s)&&(n=s);if(!n)throw new ri(si.NoMatch);return n},cl=async(e,t)=>{let n=null;for await(const s of e)!0===await t(s)&&(n=s);if(!n)throw new ri(si.NoMatch);return n},ul=(e,t)=>t?dl(e,t):ll(e),ll=async e=>{let t=null;for await(const n of e)t=n;return t},dl=async(e,t)=>{let n=null;for await(const s of e)!0===t(s)&&(n=s);return n},hl=async(e,t)=>{let n=null;for await(const s of e)!0===await t(s)&&(n=s);return n},gl=(e,t)=>t?fl(e,t):pl(e),pl=async e=>{let t=null;for await(const n of e)t=Math.max(t??Number.NEGATIVE_INFINITY,n);if(null===t)throw new ri(si.NoElements);return t},fl=async(e,t)=>{let n=null;for await(const s of e)n=Math.max(n??Number.NEGATIVE_INFINITY,t(s));if(null===n)throw new ri(si.NoElements);return n},vl=async(e,t)=>{let n=null;for await(const s of e)n=Math.max(n??Number.NEGATIVE_INFINITY,await t(s));if(null===n)throw new ri(si.NoElements);return n},ml=(e,t)=>t?wl(e,t):yl(e),yl=async e=>{let t=null;for await(const n of e)t=Math.min(t??Number.POSITIVE_INFINITY,n);if(null===t)throw new ri(si.NoElements);return t},wl=async(e,t)=>{let n=null;for await(const s of e)n=Math.min(n??Number.POSITIVE_INFINITY,t(s));if(null===n)throw new ri(si.NoElements);return n},Sl=async(e,t)=>{let n=null;for await(const s of e)n=Math.min(n??Number.POSITIVE_INFINITY,await t(s));if(null===n)throw new ri(si.NoElements);return n},Al=(e,t)=>{const n="string"==typeof t?e=>typeof e===t:e=>e instanceof t;return new ii((async function*(){for await(const t of e)n(t)&&(yield t)}))},_l=(e,t)=>Ra.generate(e,(e=>e),!0,t),Cl=(e,t,n)=>Ra.generate(e,t,!0,n),Tl=(e,t,n)=>Ra.generateAsync(e,t,!0,n),Dl=(e,t,n)=>Ra.generate(e,t,!1,n),kl=(e,t,n)=>Ra.generateAsync(e,t,!1,n),Gl=(e,t)=>Ra.generate(e,(e=>e),!1,t),bl=async(e,t)=>{const n=[],s=[];for await(const r of e)!0===t(r)?s.push(r):n.push(r);return[s,n]},Nl=async(e,t)=>{const n=[],s=[];for await(const r of e)!0===await t(r)?s.push(r):n.push(r);return[s,n]},El=(e,t)=>new ii((async function*(){yield t,yield*e})),Il=e=>new ii((async function*(){const t=[];for await(const n of e)t.push(n);for(let e=t.length-1;e>=0;e--)yield t[e]})),Rl=(e,t)=>"function"==typeof t?1===t.length?Pl(e,t):Ol(e,t):Ul(e,t),Pl=(e,t)=>new ii((async function*(){for await(const n of e)yield t(n)})),Ol=(e,t)=>new ii((async function*(){let n=0;for await(const s of e)yield t(s,n),n++})),Ul=(e,t)=>new ii((async function*(){for await(const n of e)yield n[t]})),Ml=(e,t)=>"string"==typeof t?Fl(e,t):xl(e,t),xl=(e,t)=>new ii((async function*(){for await(const n of e)yield t(n)})),Fl=(e,t)=>new ii((async function*(){for await(const n of e)yield n[t]})),Ll=(e,t)=>"function"==typeof t?1===t.length?Bl(e,t):Wl(e,t):$l(e,t),Bl=(e,t)=>new ii((async function*(){for await(const n of e)for(const e of t(n))yield e})),Wl=(e,t)=>new ii((async function*(){let n=0;for await(const s of e){for(const e of t(s,n))yield e;n++}})),$l=(e,t)=>new ii((async function*(){for await(const n of e)for(const e of n[t])yield e})),ql=(e,t)=>1===t.length?new ii((async function*(){for await(const n of e){const e=await t(n);for(const t of e)yield t}})):new ii((async function*(){let n=0;for await(const s of e){const e=await t(s,n);for(const t of e)yield t;n++}})),Vl=async(e,t,n=oi)=>{const s=e[Symbol.asyncIterator](),r=t[Symbol.asyncIterator]();let o=await Promise.all([s.next(),r.next()]),i=o[0],a=o[1];for(;!i.done&&!a.done;){if(!n(i.value,a.value))return!1;o=await Promise.all([s.next(),r.next()]),i=o[0],a=o[1]}return!0===i.done&&!0===a.done},Hl=async(e,t,n)=>{const s=e[Symbol.asyncIterator](),r=t[Symbol.asyncIterator]();let o=await Promise.all([s.next(),r.next()]),i=o[0],a=o[1];for(;!i.done&&!a.done;){if(!1===await n(i.value,a.value))return!1;o=await Promise.all([s.next(),r.next()]),i=o[0],a=o[1]}return!0===i.done&&!0===a.done},jl=(e,t)=>t?zl(e,t):Kl(e),Kl=async e=>{let t=!1,n=null;for await(const s of e){if(!0===t)throw new ri(si.MoreThanOneElement);t=!0,n=s}if(!1===t)throw new ri(si.NoElements);return n},zl=async(e,t)=>{let n=!1,s=null;for await(const r of e)if(t(r)){if(!0===n)throw new ri(si.MoreThanOneMatchingElement);n=!0,s=r}if(!1===n)throw new ri(si.NoMatch);return s},Jl=async(e,t)=>{let n=!1,s=null;for await(const r of e)if(await t(r)){if(!0===n)throw new ri(si.MoreThanOneMatchingElement);n=!0,s=r}if(!1===n)throw new ri(si.NoMatch);return s},Yl=(e,t)=>t?Ql(e,t):Xl(e),Xl=async e=>{let t=!1,n=null;for await(const s of e){if(!0===t)throw new ri(si.MoreThanOneElement);t=!0,n=s}return n},Ql=async(e,t)=>{let n=!1,s=null;for await(const r of e)if(t(r)){if(!0===n)throw new ri(si.MoreThanOneMatchingElement);n=!0,s=r}return s},Zl=async(e,t)=>{let n=!1,s=null;for await(const r of e)if(await t(r)){if(!0===n)throw new ri(si.MoreThanOneMatchingElement);n=!0,s=r}return s},ed=(e,t)=>new ii((async function*(){let n=0;for await(const s of e)n++>=t&&(yield s)})),td=(e,t)=>1===t.length?nd(e,t):sd(e,t),nd=(e,t)=>new ii((async function*(){let n=!0;for await(const s of e)!1===n?yield s:!1===t(s)&&(n=!1,yield s)})),sd=(e,t)=>new ii((async function*(){let n=0,s=!0;for await(const r of e)!1===s?yield r:!1===t(r,n)&&(s=!1,yield r),n++})),rd=(e,t)=>1===t.length?od(e,t):id(e,t),od=(e,t)=>new ii((async function*(){let n=!0;for await(const s of e)!1===n?yield s:!1===await t(s)&&(n=!1,yield s)})),id=(e,t)=>new ii((async function*(){let n=0,s=!0;for await(const r of e)!1===s?yield r:!1===await t(r,n)&&(s=!1,yield r),n++})),ad=(e,t)=>t?ud(e,t):cd(e),cd=async e=>{let t=0;for await(const n of e)t+=n;return t},ud=async(e,t)=>{let n=0;for await(const s of e)n+=t(s);return n},ld=async(e,t)=>{let n=0;for await(const s of e)n+=await t(s);return n},dd=(e,t)=>new ii((async function*(){let n=t>0?t:0;for await(const t of e){if(0==n--)break;yield t}})),hd=(e,t)=>1===t.length?gd(e,t):pd(e,t),gd=(e,t)=>new ii((async function*(){for await(const n of e){if(!t(n))break;yield n}})),pd=(e,t)=>new ii((async function*(){let n=0;for await(const s of e){if(!t(s,n++))break;yield s}})),fd=(e,t)=>1===t.length?vd(e,t):md(e,t),vd=(e,t)=>new ii((async function*(){for await(const n of e){if(!await t(n))break;yield n}})),md=(e,t)=>new ii((async function*(){let n=0;for await(const s of e){if(!await t(s,n++))break;yield s}})),yd=async e=>{const t=[];for await(const n of e)t.push(n);return t},wd=async(e,t)=>{const n=new Map;for await(const s of e){const e=t(s),r=n.get(e);void 0===r?n.set(e,[s]):r.push(s)}return n},Sd=async(e,t)=>{const n=new Map;for await(const s of e){const e=await t(s),r=n.get(e);void 0===r?n.set(e,[s]):r.push(s)}return n},Ad=async(e,t)=>{const n={};for await(const s of e)n[t(s)]=s;return n},_d=async(e,t)=>{const n={};for await(const s of e)n[await t(s)]=s;return n},Cd=async e=>{const t=new Set;for await(const n of e)t.add(n);return t},Td=(e,t,n)=>n?kd(e,t,n):Dd(e,t),Dd=(e,t)=>new ii((async function*(){const n=new Set;for await(const t of e)!1===n.has(t)&&(yield t,n.add(t));for await(const e of t)!1===n.has(e)&&(yield e,n.add(e))})),kd=(e,t,n)=>new ii((async function*(){const s=[];for(const r of[e,t])for await(const e of r){let t=!1;for(const r of s)if(!0===n(e,r)){t=!0;break}!1===t&&(yield e,s.push(e))}})),Gd=(e,t,n)=>new ii((async function*(){const s=[];for(const r of[e,t])for await(const e of r){let t=!1;for(const r of s)if(!0===await n(e,r)){t=!0;break}!1===t&&(yield e,s.push(e))}})),bd=(e,t)=>1===t.length?Nd(e,t):Ed(e,t),Nd=(e,t)=>new ii((async function*(){for await(const n of e)!0===t(n)&&(yield n)})),Ed=(e,t)=>new ii((async function*(){let n=0;for await(const s of e)!0===t(s,n++)&&(yield s)})),Id=(e,t)=>1===t.length?Rd(e,t):Pd(e,t),Rd=(e,t)=>new ii((async function*(){for await(const n of e)!0===await t(n)&&(yield n)})),Pd=(e,t)=>new ii((async function*(){let n=0;for await(const s of e)!0===await t(s,n++)&&(yield s)})),Od=(e,t,n)=>n?Md(e,t,n):Ud(e,t),Ud=(e,t)=>new ii((async function*(){const n=e[Symbol.asyncIterator](),s=t[Symbol.asyncIterator]();for(;;){const[e,t]=await Promise.all([n.next(),s.next()]);if(e.done||t.done)break;yield[e.value,t.value]}})),Md=(e,t,n)=>new ii((async function*(){const s=e[Symbol.asyncIterator](),r=t[Symbol.asyncIterator]();for(;;){const[e,t]=await Promise.all([s.next(),r.next()]);if(e.done||t.done)break;yield n(e.value,t.value)}})),xd=(e,t,n)=>new ii((async function*(){const s=e[Symbol.asyncIterator](),r=t[Symbol.asyncIterator]();for(;;){const e=await Promise.all([s.next(),r.next()]),t=e[0],o=e[1];if(t.done||o.done)break;yield n(t.value,o.value)}})),Fd=(e,t,n,s)=>{if(s){if(!n)throw new ReferenceError("TAccumulate function is undefined");return Wd(e,t,n,s)}return n?Bd(e,t,n):Ld(e,t)},Ld=async(e,t)=>{let n;for await(const s of e)n=n?t(n,s):s;if(void 0===n)throw new ri(si.NoElements);return n},Bd=async(e,t,n)=>{let s=t;for await(const t of e)s=n(s,t);return s},Wd=async(e,t,n,s)=>{let r=t;for await(const t of e)r=n(r,t);return s(r)},$d=(e,t)=>{const n=e.dataFunc;switch(n.type){case 0:return{generator:()=>n.generator().then((e=>{const n=new Array(e.length);for(let s=0;s<e.length;s++)n[s]=t(e[s]);return n})),type:0};case 1:return{generator:()=>{const e=n.generator(),s=new Array(e.length);for(let n=0;n<e.length;n++)s[n]=e[n].then(t);return s},type:1};case 2:return{generator:async()=>{const e=await n.generator(),s=new Array(e.length);for(let n=0;n<e.length;n++)s[n]=e[n].then(t);return s},type:2}}},qd=(e,t)=>{const n=$d(e,(e=>{if(!t(e))throw new Error(String(!1));return!0}));switch(n.type){case 0:return n.generator().then((()=>!0),(()=>!1));case 1:return Promise.all(n.generator()).then((()=>!0),(()=>!1));case 2:return n.generator().then(Promise.all.bind(Promise)).then((()=>!0),(()=>!1))}},Vd=(e,t)=>{const n=e.dataFunc;switch(n.type){case 0:return{generator:async()=>{const e=await n.generator(),s=new Array(e.length);for(let n=0;n<e.length;n++)s[n]=t(e[n]);return s},type:2};case 1:return{generator:()=>n.generator().map((async e=>{const n=await e;return await t(n)})),type:1};case 2:return{generator:async()=>(await n.generator()).map((e=>e.then(t))),type:2}}},Hd=(e,t)=>{const n=Vd(e,(async e=>{if(!1===await t(e))throw new Error(String(!1));return!0}));switch(n.type){case 1:return Promise.all(n.generator()).then((()=>!0),(()=>!1));case 2:return n.generator().then(Promise.all.bind(Promise)).then((()=>!0),(()=>!1))}},jd=(e,t)=>{const n=e.dataFunc;switch(n.type){case 1:return new ai({generator:()=>{const e=n.generator();return e.push(Promise.resolve(t)),e},type:n.type});case 2:return new ai({generator:async()=>{const e=await n.generator();return e.push(Promise.resolve(t)),e},type:n.type});case 0:return new ai({generator:async()=>{const e=await n.generator();return e.push(t),e},type:n.type})}},Kd=(e,t)=>t?Jd(e,t):zd(e),zd=async e=>{const t=e.dataFunc;let n;switch(t.type){case 1:return n=t.generator(),0!==n.length;case 0:case 2:return n=await t.generator(),0!==n.length}},Jd=async(e,t)=>{const n=$d(e,t);let s;switch(n.type){case 0:return s=await n.generator(),s.includes(!0);case 1:return s=await Promise.all(n.generator()),s.includes(!0);case 2:return s=await Promise.all(await n.generator()),s.includes(!0)}},Yd=async(e,t)=>{const n=Vd(e,t);let s;switch(n.type){case 1:return s=n.generator(),0!==s.length&&new Promise(((e,t)=>{let n=0;for(const r of s)r.then((t=>{n++,t?e(!0):n===s.length&&e(!1)}),t)}));case 2:return s=await n.generator(),0===Promise.length?!1:(await Promise.all(s)).includes(!0)}},Xd=e=>Ai((async function*(){for await(const t of e)yield t})),Qd=async e=>{switch(e.type){case 0:return await e.generator();case 1:return await Promise.all(e.generator());case 2:const t=await e.generator();return await Promise.all(t)}},Zd=async(e,t)=>{let n;n=t?$d(e,t):e.dataFunc;const s=await Qd(n);if(0===s.length)throw new ri(si.NoElements);let r=0;for(const e of s)r+=e;return r/s.length},eh=async(e,t)=>{const n=Vd(e,t),s=await Qd(n);if(0===s.length)throw new ri(si.NoElements);let r=0;for(const e of s)r+=e;return r/s.length},th=(e,t)=>{if(t<1)throw new ni("size");let n;switch(e.dataFunc.type){case 1:const s=e.dataFunc.generator;n={type:1,generator:()=>{const e=[];let n=[];for(const r of s())n.push(r),n.length===t&&(e.push(Promise.all(n)),n=[]);return n.length&&e.push(Promise.all(n)),e}};break;case 2:const r=e.dataFunc.generator;n={type:2,generator:async()=>{const e=[];let n=[];for(const s of await r())n.push(s),n.length===t&&(e.push(Promise.all(n)),n=[]);return n.length&&e.push(Promise.all(n)),e}};break;case 0:const o=e.dataFunc.generator;n={type:0,generator:async()=>{const e=[];let n=[];for(const s of await o())n.push(s),n.length===t&&(e.push(n),n=[]);return n.length&&e.push(n),e}}}return new ai(n)},nh=(e,t)=>new ai({generator:async()=>{const[n,s]=await Promise.all([e.toArray(),t.toArray()]);return[...n,...s]},type:0}),sh=async(e,t,n=oi)=>{let s;switch(s=$d(e,n?e=>n(t,e):e=>e===t),s.type){case 0:return(await s.generator()).some((e=>e));case 1:return(await Promise.all(s.generator())).some((e=>e));case 2:return(await Promise.all(await s.generator())).some((e=>e))}},rh=async(e,t,n)=>{const s=Vd(e,(e=>n(t,e)));switch(s.type){case 1:return(await Promise.all(s.generator())).some((e=>e));case 2:return(await Promise.all(await s.generator())).some((e=>e))}},oh=(e,t)=>t?ah(e,t):ih(e),ih=async e=>{const t=e.dataFunc;switch(t.type){case 0:case 2:return(await e.toArray()).length;case 1:return t.generator().length}},ah=async(e,t)=>{const n=await e.toArray();let s=0;for(let e=0;e<n.length;e++)!0===t(n[e])&&s++;return s},ch=async(e,t)=>{const n=Vd(e,t);let s;switch(n.type){case 1:s=Promise.all(n.generator());break;case 2:s=Promise.all(await n.generator())}let r=0;for(const e of await s)e&&r++;return r},uh=(e,t)=>{const n=e.dataFunc,s=t instanceof Promise;let r;switch(n.type){case 0:r={generator:()=>n.generator().then((e=>e.length?e:s?t.then((e=>[e])):[t])),type:n.type};break;case 1:r={generator:()=>{const e=n.generator();return e.length?e:s?[t]:[Promise.resolve(t)]},type:n.type};break;case 2:r={generator:async()=>{const e=await n.generator();return e.length?e:s?[t]:[Promise.resolve(t)]},type:n.type}}return new ai(r)},lh=(e,t=oi)=>new ai({generator:async()=>{const n=[];for(const s of await e.toArray())n.find((e=>t(e,s)))||n.push(s);return n},type:0}),dh=(e,t)=>new ai({generator:async()=>{const n=[];e:for(const s of await e.toArray()){for(const e of n)if(await t(e,s))continue e;n.push(s)}return n},type:0}),hh=(e,t)=>new ai($d(e,(e=>(t(e),e)))),gh=(e,t)=>{const n=Vd(e,(async e=>(await t(e),e)));return new ai(n)},ph=async(e,t)=>{if(t<0)throw new ni("index");const n=e.dataFunc;switch(n.type){case 0:{const e=await n.generator();if(t>=e.length)throw new ni("index");return e[t]}case 1:{const e=n.generator();if(t>=e.length)throw new ni("index");return await e[t]}case 2:{const e=await n.generator();if(t>=e.length)throw new ni("index");return await e[t]}}},fh=async(e,t)=>{const n=e.dataFunc;switch(n.type){case 0:{const e=await n.generator();return t>=e.length?null:e[t]}case 1:{const e=n.generator();return t>=e.length?null:await e[t]}case 2:{const e=await n.generator();return t>=e.length?null:await e[t]}}},vh=(e,t,n=oi)=>new ai({generator:async()=>{const[s,r]=await Promise.all([e.toArray(),t.toArray()]),o=[];for(const e of s){let t=!1;for(let s=0;s<r.length;s++){const o=r[s];if(!0===n(e,o)){t=!0;break}}!1===t&&o.push(e)}return o},type:0}),mh=(e,t,n)=>new ai({generator:async()=>{const[s,r]=await Promise.all([e.toArray(),t.toArray()]),o=[];for(const e of s){let t=!1;for(let s=0;s<r.length;s++){const o=r[s];if(!0===await n(e,o)){t=!0;break}}!1===t&&o.push(e)}return o},type:0}),yh=e=>Qd(e.dataFunc),wh=(e,t)=>t?Ah(e,t):Sh(e),Sh=async e=>{const t=e.dataFunc;switch(t.type){case 0:{const e=await t.generator();if(0===e.length)throw new ri(si.NoElements);return e[0]}case 1:{const e=t.generator();if(0===e.length)throw new ri(si.NoElements);return await e[0]}case 2:{const e=await t.generator();if(0===e.length)throw new ri(si.NoElements);return await e[0]}}},Ah=async(e,t)=>{const n=await yh(e);for(const e of n)if(!0===t(e))return e;throw new ri(si.NoMatch)},_h=async(e,t)=>{const n=await yh(e);for(const e of n)if(!0===await t(e))return e;throw new ri(si.NoMatch)},Ch=(e,t)=>t?Dh(e,t):Th(e),Th=async e=>{const t=e.dataFunc;switch(t.type){case 0:{const e=await t.generator();return 0===e.length?null:e[0]}case 1:{const e=t.generator();return 0===e.length?null:await e[0]}case 2:{const e=await t.generator();return 0===e.length?null:await e[0]}}},Dh=async(e,t)=>{const n=await yh(e);for(const e of n)if(!0===t(e))return e;return null},kh=async(e,t)=>{const n=await yh(e);for(const e of n)if(!0===await t(e))return e;return null},Gh=(e,t,n)=>n?Nh(e,t,n):bh(e,t),bh=(e,t)=>new ai({generator:async()=>{const n={};for(const s of await e.toArray()){const e=t(s),r=n[e];r?r.push(s):n[e]=new Qi(e,s)}const s=new Array;for(const e in n)s.push(n[e]);return s},type:0}),Nh=(e,t,n)=>new ai({generator:async()=>{const s=new Array;for(const r of await e.toArray()){const e=t(r);let o=!1;for(let t=0;t<s.length;t++){const i=s[t];if(n(i.key,e)){i.push(r),o=!0;break}}!1===o&&s.push(new Qi(e,r))}const r=new Array;for(const e of s)r.push(e);return r},type:0}),Eh=(e,t,n)=>n?Ih(e,t,n):Rh(e,t),Ih=(e,t,n)=>new ai({generator:async()=>{const s=Vd(e,(async e=>[await t(e),e]));let r;switch(s.type){case 1:r=await Promise.all(s.generator());break;case 2:r=await Promise.all(await s.generator())}const o=new Array;for(const[e,t]of r){let s=!1;for(let r=0;r<o.length;r++){const i=o[r];if(!0===await n(i.key,e)){i.push(t),s=!0;break}}!1===s&&o.push(new Qi(e,t))}const i=new Array;for(const e of o)i.push(e);return i},type:0}),Rh=(e,t)=>new ai({generator:async()=>{const n=Vd(e,(async e=>[await t(e),e]));let s;switch(n.type){case 1:s=await Promise.all(n.generator());break;case 2:s=await Promise.all(await n.generator())}const r={};for(const[e,t]of s){const n=r[e];n?n.push(t):r[e]=new Qi(e,t)}const o=new Array;for(const e in r)o.push(r[e]);return o},type:0}),Ph=(e,t,n,s)=>s?Oh(e,t,n,s):Uh(e,t,n),Oh=(e,t,n,s)=>new ai({generator:async()=>{const r=new Array;for await(const o of e){const e=t(o);let i=!1;for(let t=0;t<r.length;t++){const a=r[t];if(s(a.key,e)){a.push(n(o)),i=!0;break}}if(!1===i){const t=n(o);r.push(new Qi(e,t))}}const o=new Array;for(const e of r)o.push(e);return o},type:0}),Uh=(e,t,n)=>new ai({generator:async()=>{const s={};for(const r of await e.toArray()){const e=t(r),o=s[e],i=n(r);o?o.push(i):s[e]=new Qi(e,i)}const r=new Array;for(const e in s)r.push(s[e]);return r},type:0}),Mh=(e,t,n,s,r,o)=>{const i=o?xh(e,t,n,s,r,o):Fh(e,t,n,s,r);return new ai({generator:i,type:0})},xh=(e,t,n,s,r,o)=>async()=>{const i=[];for await(const e of t){const t=s(e),n=i.find((e=>o(e.key,t)));n?n.values.push(e):i.push({key:t,values:[e]})}return(await e.toArray()).map((e=>{const t=n(e),s=i.find((e=>o(e.key,t)))??{key:t,values:[]};return r(e,s.values)}))},Fh=(e,t,n,s,r)=>async()=>{const o=new Map;for await(const e of t){const t=s(e),n=o.get(t);n?n.push(e):o.set(t,[e])}return(await e.toArray()).map((e=>{const t=n(e),s=o.get(t)??[];return r(e,s)}))},Lh=(e,t,n,s,r,o)=>{const i=o?Bh(e,t,n,s,r,o):Wh(e,t,n,s,r);return new ai({generator:i,type:0})},Bh=(e,t,n,s,r,o)=>async()=>{const i=[];for await(const e of t){const t=await s(e),n=i.find((e=>o(e.key,t)));n?n.values.push(e):i.push({key:t,values:[e]})}const a=(await e.toArray()).map((async e=>{const t=await n(e),s=i.find((e=>o(e.key,t)))??{key:t,values:[]};return r(e,s.values)}));return await Promise.all(a)},Wh=(e,t,n,s,r)=>async()=>{const o=new Map;for await(const e of t){const t=await s(e),n=o.get(t);n?n.push(e):o.set(t,[e])}const i=(await e.toArray()).map((async e=>{const t=await n(e),s=o.get(t)??[];return r(e,s)}));return await Promise.all(i)},$h=(e,t,n=oi)=>new ai({generator:async()=>{const s=await e.distinct(n).toArray();if(0===s.length)return[];const r=await t.toArray(),o=new Array;for(let e=0;e<s.length;e++){const t=s[e];for(let e=0;e<r.length;e++){const s=r[e];if(!0===n(t,s)){o.push(t);break}}}return o},type:0}),qh=(e,t,n)=>new ai({generator:async()=>{const s=await e.distinctAsync(n).toArray();if(0===s.length)return[];const r=await t.toArray(),o=new Array;for(let e=0;e<s.length;e++){const t=s[e];for(let e=0;e<r.length;e++){const s=r[e];if(!0===await n(t,s)){o.push(t);break}}}return o},type:0}),Vh=(e,t,n,s,r,o=oi)=>new ai({generator:async()=>{const[i,a]=await Promise.all([t.toArray(),e.toArray()]),c=new Array;for(const e of a){const t=n(e);for(const n of i){const i=s(n);!0===o(t,i)&&c.push(r(e,n))}}return c},type:0}),Hh=(e,t)=>t?Kh(e,t):jh(e),jh=async e=>{const t=e.dataFunc;switch(t.type){case 0:{const e=await t.generator();if(0===e.length)throw new ri(si.NoElements);return e[e.length-1]}case 1:{const e=t.generator();if(0===e.length)throw new ri(si.NoElements);return await e[e.length-1]}case 2:{const e=await t.generator();if(0===e.length)throw new ri(si.NoElements);return await e[e.length-1]}}},Kh=async(e,t)=>{const n=e.dataFunc;switch(n.type){case 0:{const e=await n.generator();for(let n=e.length-1;n>=0;n--){const s=e[n];if(t(s))return s}break}case 1:{const e=n.generator();for(let n=e.length-1;n>=0;n--){const s=await e[n];if(t(s))return s}break}case 2:{const e=await n.generator();for(let n=e.length-1;n>=0;n--){const s=await e[n];if(t(s))return s}break}}throw new ri(si.NoMatch)},zh=async(e,t)=>{const n=e.dataFunc;switch(n.type){case 0:{const e=await n.generator();for(let n=e.length-1;n>=0;n--){const s=e[n];if(!0===await t(s))return s}break}case 1:{const e=n.generator();for(let n=e.length-1;n>=0;n--){const s=await e[n];if(!0===await t(s))return s}break}case 2:{const e=await n.generator();for(let n=e.length-1;n>=0;n--){const s=await e[n];if(!0===await t(s))return s}break}}throw new ri(si.NoMatch)},Jh=(e,t)=>t?Xh(e,t):Yh(e),Yh=async e=>{const t=e.dataFunc;switch(t.type){case 0:{const e=await t.generator();return 0===e.length?null:e[e.length-1]}case 1:{const e=t.generator();return 0===e.length?null:await e[e.length-1]}case 2:{const e=await t.generator();return 0===e.length?null:await e[e.length-1]}}},Xh=async(e,t)=>{const n=e.dataFunc;switch(n.type){case 0:{const e=await n.generator();for(let n=e.length-1;n>=0;n--){const s=e[n];if(t(s))return s}break}case 1:{const e=n.generator();for(let n=e.length-1;n>=0;n--){const s=await e[n];if(t(s))return s}break}case 2:{const e=await n.generator();for(let n=e.length-1;n>=0;n--){const s=await e[n];if(t(s))return s}break}}return null},Qh=async(e,t)=>{const n=e.dataFunc;switch(n.type){case 0:{const e=await n.generator();for(let n=e.length-1;n>=0;n--){const s=e[n];if(!0===await t(s))return s}break}case 1:{const e=n.generator();for(let n=e.length-1;n>=0;n--){const s=await e[n];if(!0===await t(s))return s}break}case 2:{const e=await n.generator();for(let n=e.length-1;n>=0;n--){const s=await e[n];if(!0===await t(s))return s}break}}return null},Zh=async(e,t)=>{let n;n=t?$d(e,t):e.dataFunc;const s=await Qd(n);if(0===s.length)throw new ri(si.NoElements);return Math.max.apply(null,s)},eg=async(e,t)=>{const n=Vd(e,t),s=await Qd(n);if(0===s.length)throw new ri(si.NoElements);return Math.max.apply(null,s)},tg=async(e,t)=>{let n;n=t?$d(e,t):e.dataFunc;const s=await Qd(n);if(0===s.length)throw new ri(si.NoElements);return Math.min.apply(null,s)},ng=async(e,t)=>{const n=Vd(e,t),s=await Qd(n);if(0===s.length)throw new ri(si.NoElements);return Math.min.apply(null,s)},sg=(e,t)=>{const n="string"==typeof t?e=>[typeof e===t,e]:e=>[e instanceof t,e];return new ai({generator:async()=>{const t=$d(e,n),s=await Qd(t),r=[];for(const[e,t]of s)e&&r.push(t);return r},type:0})};async function*rg(e,t,n,s){const r=await(async(e,t)=>{const n=new Map;for(const s of e){const e=await t(s),r=n.get(e);r?r.push(s):n.set(e,[s])}return n})(e,t),o=[...r.keys()].sort(s||void 0);if(n)for(let e=0;e<o.length;e++)yield r.get(o[e]);else for(let e=o.length-1;e>=0;e--)yield r.get(o[e])}async function*og(e,t,n,s){const r=((e,t)=>{const n=new Map;for(const s of e){const e=t(s),r=n.get(e);r?r.push(s):n.set(e,[s])}return n})(e,t),o=[...r.keys()].sort(s||void 0);if(n)for(let e=0;e<o.length;e++)yield r.get(o[e]);else for(let e=o.length-1;e>=0;e--)yield r.get(o[e])}class ig extends ai{orderedPairs;constructor(e){super({generator:async()=>{const t=e(),n=[];for await(const e of t)n.push(...e);return n},type:0}),this.orderedPairs=e}static generateAsync(e,t,n,s){let r;return r=e instanceof ig?async function*(){for await(const r of e.orderedPairs())yield*rg(r,t,n,s)}:()=>async function*(e,t,n,s){const r=await(async(e,t)=>{const n=new Map;for await(const s of e){const e=await t(s),r=n.get(e);r?r.push(s):n.set(e,[s])}return n})(e,t),o=[...r.keys()].sort(s||void 0);if(n)for(let e=0;e<o.length;e++)yield r.get(o[e]);else for(let e=o.length-1;e>=0;e--)yield r.get(o[e])}(e,t,n,s),new ig(r)}static generate(e,t,n,s){let r;return r=e instanceof ig?async function*(){for await(const r of e.orderedPairs())yield*og(r,t,n,s)}:()=>async function*(e,t,n,s){const r=await(async(e,t)=>{const n=new Map;for await(const s of e){const e=t(s),r=n.get(e);r?r.push(s):n.set(e,[s])}return n})(e,t),o=[...r.keys()].sort(s||void 0);if(n)for(let e=0;e<o.length;e++)yield r.get(o[e]);else for(let e=o.length-1;e>=0;e--)yield r.get(o[e])}(e,t,n,s),new ig(r)}thenBy(e,t){return ig.generate(this,e,!0,t)}thenByAsync(e,t){return ig.generateAsync(this,e,!0,t)}thenByDescending(e,t){return ig.generate(this,e,!1,t)}thenByDescendingAsync(e,t){return ig.generateAsync(this,e,!1,t)}}const ag=(e,t)=>ig.generate(e,(e=>e),!0,t),cg=(e,t,n)=>ig.generate(e,t,!0,n),ug=(e,t,n)=>ig.generateAsync(e,t,!0,n),lg=(e,t,n)=>ig.generate(e,t,!1,n),dg=(e,t,n)=>ig.generateAsync(e,t,!1,n),hg=(e,t)=>ig.generate(e,(e=>e),!1,t),gg=async(e,t)=>{const n=$d(e,(e=>[t(e),e])),s=await Qd(n),r=[],o=[];for(const[e,t]of s)e?o.push(t):r.push(t);return[o,r]},pg=async(e,t)=>{const n=Vd(e,(async e=>[await t(e),e])),s=await Qd(n),r=[],o=[];for(const[e,t]of s)e?o.push(t):r.push(t);return[o,r]},fg=(e,t)=>{const n=e.dataFunc;switch(n.type){case 1:return new ai({generator:()=>{const e=n.generator();return e.unshift(Promise.resolve(t)),e},type:n.type});case 2:return new ai({generator:async()=>{const e=await n.generator();return e.unshift(Promise.resolve(t)),e},type:n.type});case 0:return new ai({generator:async()=>{const e=await n.generator();return e.unshift(t),e},type:n.type})}},vg=e=>{const t=e.dataFunc;switch(t.type){case 1:return new ai({generator:()=>t.generator().reverse(),type:t.type});case 2:case 0:return new ai({generator:async()=>(await t.generator()).reverse(),type:t.type})}},mg=(e,t)=>{const n=e.dataFunc;switch(n.type){case 0:return{generator:()=>n.generator().then((e=>{const n=new Array(e.length);for(let s=0;s<e.length;s++)n[s]=t(e[s],s);return n})),type:0};case 1:return{generator:()=>{const e=n.generator(),s=new Array(e.length);for(let n=0;n<e.length;n++)s[n]=e[n].then((e=>t(e,n)));return s},type:1};case 2:return{generator:async()=>{const e=await n.generator(),s=new Array(e.length);for(let n=0;n<e.length;n++)s[n]=e[n].then((e=>t(e,n)));return s},type:2}}},yg=(e,t)=>"function"==typeof t?1===t.length?new ai($d(e,t)):new ai(mg(e,t)):new ai($d(e,(e=>e[t]))),wg=(e,t)=>{const n=e.dataFunc;switch(n.type){case 0:return{generator:async()=>{const e=await n.generator(),s=new Array(e.length);for(let n=0;n<e.length;n++)s[n]=t(e[n],n);return s},type:2};case 1:return{generator:()=>n.generator().map(((e,n)=>e.then((e=>t(e,n))))),type:1};case 2:return{generator:async()=>(await n.generator()).map(((e,n)=>e.then((e=>t(e,n))))),type:2}}},Sg=(e,t)=>{let n;return n="function"==typeof t?1===t.length?Vd(e,t):wg(e,t):Vd(e,(e=>e[t])),new ai(n)},Ag=(e,t)=>new ai({generator:async()=>{let n;n="function"==typeof t?1===t.length?$d(e,t):mg(e,t):$d(e,(e=>e[t]));const s=[];switch(n.type){case 0:for(const e of await n.generator())for(const t of e)s.push(t);break;case 1:for(const e of n.generator())for(const t of await e)s.push(t);break;case 2:for(const e of await n.generator())for(const t of await e)s.push(t)}return s},type:0}),_g=(e,t)=>new ai({generator:async()=>{let n;n=1===t.length?Vd(e,t):wg(e,t);const s=[];switch(n.type){case 1:for(const e of n.generator())for(const t of await e)s.push(t);break;case 2:for(const e of await n.generator())for(const t of await e)s.push(t)}return s},type:0}),Cg=async(e,t,n=oi)=>{const s=await e.toArray(),r=await t.toArray();if(s.length!==r.length)return!1;for(let e=0;e<s.length;e++)if(!1===n(s[e],r[e]))return!1;return!0},Tg=async(e,t,n)=>{const s=await e.toArray(),r=await t.toArray();if(s.length!==r.length)return!1;for(let e=0;e<s.length;e++){const t=s[e],o=r[e];if(!1===await n(t,o))return!1}return!0},Dg=(e,t)=>t?Gg(e,t):kg(e),kg=async e=>{const t=e.dataFunc;switch(t.type){case 0:{const e=await t.generator();if(e.length>1)throw new ri(si.MoreThanOneElement);if(0===e.length)throw new ri(si.NoElements);return e[0]}case 1:{const e=t.generator();if(e.length>1)throw new ri(si.MoreThanOneElement);if(0===e.length)throw new ri(si.NoElements);return e[0]}case 2:{const e=await t.generator();if(e.length>1)throw new ri(si.MoreThanOneElement);if(0===e.length)throw new ri(si.NoElements);return await e[0]}}},Gg=async(e,t)=>{const n=await yh(e);let s=!1,r=null;for(const e of n)if(t(e)){if(!0===s)throw new ri(si.MoreThanOneMatchingElement);s=!0,r=e}if(!1===s)throw new ri(si.NoMatch);return r},bg=async(e,t)=>{const n=await yh(e);let s=!1,r=null;for(const e of n)if(!0===await t(e)){if(!0===s)throw new ri(si.MoreThanOneMatchingElement);s=!0,r=e}if(!1===s)throw new ri(si.NoMatch);return r},Ng=(e,t)=>t?Ig(e,t):Eg(e),Eg=async e=>{const t=e.dataFunc;switch(t.type){case 0:{const e=await t.generator();if(e.length>1)throw new ri(si.MoreThanOneElement);return 0===e.length?null:e[0]}case 1:{const e=t.generator();if(e.length>1)throw new ri(si.MoreThanOneElement);return 0===e.length?null:e[0]}case 2:{const e=await t.generator();if(e.length>1)throw new ri(si.MoreThanOneElement);return 0===e.length?null:await e[0]}}},Ig=async(e,t)=>{const n=await yh(e);let s=!1,r=null;for(const e of n)if(t(e)){if(!0===s)throw new ri(si.MoreThanOneElement);s=!0,r=e}return r},Rg=async(e,t)=>{const n=await yh(e);let s=!1,r=null;for(const e of n)if(!0===await t(e)){if(!0===s)throw new ri(si.MoreThanOneElement);s=!0,r=e}return r},Pg=(e,t)=>{const n=e.dataFunc;switch(n.type){case 0:return new ai({generator:async()=>(await n.generator()).slice(t),type:0});case 1:return new ai({generator:()=>n.generator().slice(t),type:1});case 2:return new ai({generator:async()=>(await n.generator()).slice(t),type:2})}},Og=(e,t)=>new ai({generator:async()=>{const n=await e.toArray();let s=0;for(;s<n.length;s++){const e=n[s];if(!1===t(e,s))break}const r=[];for(;s<n.length;s++)r.push(n[s]);return r},type:0}),Ug=(e,t)=>new ai({generator:async()=>{const n=await e.toArray();let s=0;for(;s<n.length;s++){const e=n[s];if(!1===await t(e,s))break}const r=[];for(;s<n.length;s++)r.push(n[s]);return r},type:0}),Mg=(e,t)=>t?Fg(e,t):xg(e),xg=async e=>{let t=0;for(const n of await e.toArray())t+=n;return t},Fg=async(e,t)=>{let n=0;for(const s of await e.toArray())n+=t(s);return n},Lg=async(e,t)=>{const n=Vd(e,t),s=await Qd(n);let r=0;for(const e of s)r+=e;return r},Bg=(e,t)=>{const n=t>0?t:0,s=e.dataFunc;switch(s.type){case 1:return new ai({generator:()=>s.generator().splice(0,n),type:1});case 2:return new ai({generator:()=>s.generator().then((e=>e.splice(0,n))),type:2});default:return new ai({generator:()=>s.generator().then((e=>e.splice(0,n))),type:0})}},Wg=(e,t)=>new ai({generator:async()=>{const n=await e.toArray(),s=new Array;if(1===t.length)for(const e of n){if(!0!==t(e))break;s.push(e)}else for(let e=0;e<n.length;e++){const r=n[e];if(!0!==t(r,e))break;s.push(r)}return s},type:0}),$g=(e,t)=>new ai({generator:async()=>{const n=await e.toArray(),s=new Array;if(1===t.length){const e=t;for(const t of n){if(!0!==await e(t))break;s.push(t)}}else for(let e=0;e<n.length;e++){const r=n[e];if(!0!==await t(r,e))break;s.push(r)}return s},type:0}),qg=async(e,t)=>{const n=new Map,s=$d(e,(e=>[t(e),e])),r=await Qd(s);for(const[e,t]of r){const s=n.get(e);void 0===s?n.set(e,[t]):s.push(t)}return n},Vg=async(e,t)=>{const n=new Map,s=Vd(e,(async e=>[await t(e),e])),r=await Qd(s);for(const[e,t]of r){const s=n.get(e);void 0===s?n.set(e,[t]):s.push(t)}return n},Hg=async(e,t)=>{const n=e.dataFunc,s=await Qd(n),r={};for(const e of s)r[t(e)]=e;return r},jg=async(e,t)=>{const n=Vd(e,(async e=>[await t(e),e])),s=await Qd(n),r={};for(const[e,t]of s)r[e]=t;return r},Kg=async e=>{const t=e.dataFunc,n=await Qd(t);return new Set(n)},zg=(e,t,n)=>n?Yg(e,t,n):Jg(e,t),Jg=(e,t)=>new ai({generator:async()=>{const n=new Set,s=t.toArray();for await(const t of e)!1===n.has(t)&&n.add(t);const r=await s;for(const e of r)!1===n.has(e)&&n.add(e);return[...n.keys()]},type:0}),Yg=(e,t,n)=>new ai({generator:async()=>{const s=[],r=await Promise.all([e.toArray(),t.toArray()]);for(const e of r)for(const t of e){let e=!1;for(const r of s)if(!0===n(t,r)){e=!0;break}!1===e&&s.push(t)}return s},type:0}),Xg=(e,t,n)=>new ai({generator:async()=>{const s=[],r=await Promise.all([e.toArray(),t.toArray()]);for(const e of r)for(const t of e){let e=!1;for(const r of s)if(!0===await n(t,r)){e=!0;break}!1===e&&s.push(t)}return s},type:0}),Qg=(e,t)=>new ai({generator:async()=>(await e.toArray()).filter(t),type:0}),Zg=(e,t)=>new ai({generator:async()=>{const n=wg(e,(async(e,n)=>[await t(e,n),e])),s=await Qd(n),r=[];for(const[e,t]of s)e&&r.push(t);return r},type:0}),ep=(e,t,n)=>n?np(e,t,n):tp(e,t),tp=(e,t)=>new ai({generator:async()=>{const[n,s]=await Promise.all([e.toArray(),t.toArray()]),r=n.length<s.length?n.length:s.length,o=new Array(r);for(let e=0;e<r;e++){const t=n[e],r=s[e];o[e]=[t,r]}return o},type:0}),np=(e,t,n)=>new ai({generator:async()=>{const[s,r]=await Promise.all([e.toArray(),t.toArray()]),o=s.length<r.length?s.length:r.length,i=new Array(o);for(let e=0;e<o;e++){const t=s[e],o=r[e];i[e]=n(t,o)}return i},type:0}),sp=(e,t,n)=>new ai({generator:async()=>{const[s,r]=await Promise.all([e.toArray(),t.toArray()]),o=s.length<r.length?s.length:r.length,i=new Array(o);for(let e=0;e<o;e++){const t=s[e],o=r[e];i[e]=n(t,o)}return Promise.all(i)},type:0}),rp=e=>{const t=ui.prototype,n=e.prototype,s=Object.getOwnPropertyNames(t);for(const e of s)n[e]=n[e]??t[e]};tu(ci),(e=>{const t=e.prototype,n=(e,n)=>{const s=function(...t){return e(this,...t)};Object.defineProperty(s,"length",{value:e.length-1}),t[n]=s};n(nu,"aggregate"),n(iu,"all"),n(au,"allAsync"),n(cu,"append"),n(uu,"any"),n(hu,"anyAsync"),n(gu,"asParallel"),n(pu,"average"),n(fu,"averageAsync"),n(vu,"chunk"),n(mu,"concatenate"),n(yu,"contains"),n(wu,"containsAsync"),n(Su,"count"),n(Cu,"countAsync"),n(Tu,"defaultIfEmpty"),n(Du,"distinct"),n(ku,"distinctAsync"),n(Gu,"each"),n(bu,"eachAsync"),n(Nu,"elementAt"),n(Eu,"elementAtOrDefault"),n(Iu,"except"),n(Ru,"exceptAsync"),n(Pu,"first"),n(Mu,"firstAsync"),n(xu,"firstOrDefault"),n(Bu,"firstOrDefaultAsync"),n(Wu,"groupBy"),n(Vu,"groupByAsync"),n(Ku,"groupByWithSel"),n(Yu,"groupJoin"),n(Zu,"groupJoinAsync"),n(nl,"intersect"),n(sl,"intersectAsync"),n(rl,"joinByKey"),n(ol,"last"),n(cl,"lastAsync"),n(ul,"lastOrDefault"),n(hl,"lastOrDefaultAsync"),n(gl,"max"),n(vl,"maxAsync"),n(ml,"min"),n(Sl,"minAsync"),n(Al,"ofType"),n(_l,"order"),n(Cl,"orderBy"),n(Tl,"orderByAsync"),n(Dl,"orderByDescending"),n(kl,"orderByDescendingAsync"),n(Gl,"orderDescending"),n(bl,"partition"),n(Nl,"partitionAsync"),n(El,"prepend"),n(Il,"reverse"),n(Rl,"select"),n(Ml,"selectAsync"),n(Ll,"selectMany"),n(ql,"selectManyAsync"),n(Vl,"sequenceEquals"),n(Hl,"sequenceEqualsAsync"),n(jl,"single"),n(Jl,"singleAsync"),n(Yl,"singleOrDefault"),n(Zl,"singleOrDefaultAsync"),n(ed,"skip"),n(td,"skipWhile"),n(rd,"skipWhileAsync"),n(ad,"sum"),n(ld,"sumAsync"),n(dd,"take"),n(hd,"takeWhile"),n(fd,"takeWhileAsync"),n(yd,"toArray"),n(wd,"toMap"),n(Sd,"toMapAsync"),n(Ad,"toObject"),n(_d,"toObjectAsync"),n(Cd,"toSet"),n(Td,"union"),n(Gd,"unionAsync"),n(bd,"where"),n(Id,"whereAsync"),n(Od,"zip"),n(xd,"zipAsync")})(ii),(e=>{const t=e.prototype,n=(e,n)=>{const s=function(...t){return e(this,...t)};Object.defineProperty(s,"length",{value:e.length-1}),t[n]=s};n(Fd,"aggregate"),n(qd,"all"),n(Hd,"allAsync"),n(jd,"append"),n(Kd,"any"),n(Yd,"anyAsync"),n(Xd,"asAsync"),n(Zd,"average"),n(eh,"averageAsync"),n(th,"chunk"),n(nh,"concatenate"),n(sh,"contains"),n(rh,"containsAsync"),n(oh,"count"),n(ch,"countAsync"),n(uh,"defaultIfEmpty"),n(lh,"distinct"),n(dh,"distinctAsync"),n(hh,"each"),n(gh,"eachAsync"),n(ph,"elementAt"),n(fh,"elementAtOrDefault"),n(vh,"except"),n(mh,"exceptAsync"),n(wh,"first"),n(_h,"firstAsync"),n(Ch,"firstOrDefault"),n(kh,"firstOrDefaultAsync"),n(Gh,"groupBy"),n(Eh,"groupByAsync"),n(Ph,"groupByWithSel"),n(Mh,"groupJoin"),n(Lh,"groupJoinAsync"),n(Mh,"groupJoin"),n(Lh,"groupJoinAsync"),n($h,"intersect"),n(qh,"intersectAsync"),n(Vh,"joinByKey"),n(Hh,"last"),n(zh,"lastAsync"),n(Jh,"lastOrDefault"),n(Qh,"lastOrDefaultAsync"),n(Zh,"max"),n(eg,"maxAsync"),n(tg,"min"),n(ng,"minAsync"),n(sg,"ofType"),n(ag,"order"),n(cg,"orderBy"),n(ug,"orderByAsync"),n(lg,"orderByDescending"),n(dg,"orderByDescendingAsync"),n(hg,"orderDescending"),n(gg,"partition"),n(pg,"partitionAsync"),n(fg,"prepend"),n(vg,"reverse"),n(yg,"select"),n(Sg,"selectAsync"),n(Ag,"selectMany"),n(_g,"selectManyAsync"),n(Cg,"sequenceEquals"),n(Tg,"sequenceEqualsAsync"),n(Dg,"single"),n(bg,"singleAsync"),n(Ng,"singleOrDefault"),n(Rg,"singleOrDefaultAsync"),n(Pg,"skip"),n(Og,"skipWhile"),n(Ug,"skipWhileAsync"),n(Mg,"sum"),n(Lg,"sumAsync"),n(Bg,"take"),n(Wg,"takeWhile"),n($g,"takeWhileAsync"),n(yh,"toArray"),n(qg,"toMap"),n(Vg,"toMapAsync"),n(Hg,"toObject"),n(jg,"toObjectAsync"),n(Kg,"toSet"),n(zg,"union"),n(Xg,"unionAsync"),n(Qg,"where"),n(Zg,"whereAsync"),n(ep,"zip"),n(sp,"zipAsync")})(ai),(()=>{const{prototype:e}=ui,t=Object.getOwnPropertyNames(ci.prototype);for(const n of t)e[n]=e[n]??ci.prototype[n];e.all=function(e){return this.every(e)},e.any=function(e){return e?this.some(e):0!==this.length},e.count=function(e){if(e){let t=0;for(let n=0;n<this.length;n++)!0===e(this[n])&&t++;return t}return this.length},e.elementAt=function(e){if(e<0||e>=this.length)throw new ni("index");return this[e]},e.elementAtOrDefault=function(e){return this[e]??null},e.first=function(e){if(e){const t=this.find(e);if(void 0===t)throw new ri(si.NoMatch);return t}if(0===this.length)throw new ri(si.NoElements);return this[0]},e.firstOrDefault=function(e){if(e){const t=this.find(e);return void 0===t?null:t}return 0===this.length?null:this[0]},e.last=function(e){if(e){for(let t=this.length-1;t>=0;t--){const n=this[t];if(!0===e(n))return n}throw new ri(si.NoMatch)}if(0===this.length)throw new ri(si.NoElements);return this[this.length-1]},e.lastOrDefault=function(e){if(e){for(let t=this.length-1;t>=0;t--){const n=this[t];if(!0===e(n))return n}return null}return 0===this.length?null:this[this.length-1]},e.max=function(e){if(0===this.length)throw new ri(si.NoElements);if(e){let t=Number.NEGATIVE_INFINITY;for(let n=0;n<this.length;n++)t=Math.max(e(this[n]),t);return t}return Math.max.apply(null,this)},e.min=function(e){if(0===this.length)throw new ri(si.NoElements);if(e){let t=Number.POSITIVE_INFINITY;for(let n=0;n<this.length;n++)t=Math.min(e(this[n]),t);return t}return Math.min.apply(null,this)},e.reverse=function(){return Array.prototype.reverse.apply(this),this}})();var op,ip;!function(e){e.Success="Success",e.GroupDoesNotExists="GroupDoesNotExists",e.ObjectDoesNotExists="ObjectDoesNotExists",e.FatalError="FatalError",e.FunctionNotSupported="FunctionNotSupported"}(op||(op={})),function(e){e.Success="Success",e.NoPermissions="NoPermissions",e.NameToShort="NameToShort",e.NameAlreadyExists="NameAlreadyExists",e.OtherError="OtherError",e.UnknownError="UnknownError"}(ip||(ip={}));class ap{constructor(){this._guid="",this._name="",this._iconName="",this._position=0,this._objectsOrder={},null==ap._devicesService&&(ap._devicesService=Ov.Get(xo.ServiceName))}GetDevicesChannelsInGroupAsync(){return e=this,t=arguments,r=function*(e=!1){let t=[],n=[];const r=yield ap._devicesService.GetDevicesAsync(e);if(void 0===this._objectsOrder||null===this._objectsOrder||0==Object.entries(this._objectsOrder).length){Ov.Get(s.ServiceName).Error("Old controller API fallback to old groups API.");for(let e of r)for(let t of e.Channels.where((e=>e.ChannelGroups.any((e=>e===this._guid)))))n.push(t);return n}const o=Object.keys(this._objectsOrder).map(Number).sort(((e,t)=>e-t));Object.values(this._objectsOrder).forEach((e=>{const n=r.select((t=>t.Channels.where((t=>t.ChannelId===e))));if(null!==n)for(let e of n)for(let n of e)t.push(n)}));for(let e of o){const s=t.firstOrDefault((t=>t.ChannelId===this._objectsOrder[e]));null!==s&&n.push(s)}return n},new((n=void 0)||(n=Promise))((function(s,o){function i(e){try{c(r.next(e))}catch(e){o(e)}}function a(e){try{c(r.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((r=r.apply(e,t||[])).next())}));var e,t,n,r}get Guid(){return this._guid}set Guid(e){this._guid=e}get Name(){return this._name}set Name(e){this._name=e}get IconName(){return this._iconName}set IconName(e){this._iconName=e}get OrderPosition(){return this._position}set OrderPosition(e){this._position=e}get ObjectsOrder(){return this._objectsOrder}set ObjectsOrder(e){this._objectsOrder=e}ChangeNameAsync(e){return Ov.Get(lp.ServiceName).ChangeGroupNameAsync(this,e)}ChangeIconNameAsync(e){return Ov.Get(lp.ServiceName).ChangeGroupIconNameAsync(this,e)}}var cp,up=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class lp{constructor(){this._connection=null,this._synchronized=!1,this._synchronizationTaskCompletionSource=null,this._groups=[],this._objectsGroupingSupported=!1,this._connection=Ov.Get(Pt.ServiceName),this._synchronizationTaskCompletionSource=new Promise((e=>{Ov.Get(Ke.ServiceName).OnUserLoggedInEvent().Subscribe((t=>up(this,void 0,void 0,(function*(){yield this.GetGroupsAsync(!0),e(),this._synchronized=!0}))))}))}SetObjectsInGroupAndOrderAsync(e,t){return up(this,void 0,void 0,(function*(){var n;let s=[],r=[];for(let e of t)if(this.IsDevice(e)){for(let t of e.Channels)s.push(`${t.ChannelId}`);r.push(`${e.Guid}`)}else{if(!this.IsDeviceChannel(e))throw new Error("Passed object is not a device or device channel!");s.push(`${e.ChannelId}`),r.push(`${e.ChannelId}`)}const o=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new gp(e,r),15e3,!1);switch(Ov.Get(Ge.ServiceName).ClearCache(),Ov.Get(rt.ServiceName).ExitConfigurationModeAsync(),yield this.GetGroupsAsync(!1),null==o?void 0:o.Status){case ce.OK:return new De(op.Success,"");case ce.NotSupportedMethod:case ce.ResourceDoesNotExists:case ce.ResourceIsNotAvailable:return new De(op.FunctionNotSupported,"");case ce.WrongData:return"GroupDoesNotExists"===o.Data?new De(op.GroupDoesNotExists,o.Data):new De(op.FatalError,o.Data);case ce.Error:case ce.FatalError:default:return new De(op.FatalError,"")}}))}IsDevice(e){return void 0!==e.Channels}IsDeviceChannel(e){return void 0!==e.GetDevice}LogGroupsOrder(e){const t=Ov.Get(s.ServiceName);e.forEach(((e,n)=>{t.Debug(lp.ServiceName,`Group ${e.Name} order position [on array]: ${n} set position: ${e.OrderPosition}`)}))}LogObjectsInGroupOrder(e,t){const n=Ov.Get(s.ServiceName);n.Debug(lp.ServiceName,`Group ${e.Name} objects order:`),t.forEach(((e,t)=>{n.Debug(lp.ServiceName,`Channel ${e.Name} order position [on array]: ${t} channelId: ${e.ChannelId}`)}));for(const[t,s]of Object.entries(e.ObjectsOrder))n.Debug(`new order [GROUP ${e.Name}] Order: [${t}] = ${s}`)}ChangeGroupsOrderAsync(e){return up(this,void 0,void 0,(function*(){var t;const n=e.select((e=>e.Guid)).toArray(),r=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new hp(n),15e3,!1);return Ov.Get(rt.ServiceName).ExitConfigurationModeAsync(),(null==r?void 0:r.Status)===ce.OK?(Ov.Get(Ge.ServiceName).ClearCache(),yield this.GetGroupsAsync(!1),ce.OK):(Ov.Get(s.ServiceName).Error(lp.ServiceName,`Failed to change groups order, controller responded with error ${null==r?void 0:r.Status} data: ${null==r?void 0:r.Data}`),this.LogGroupsOrder(e),null==r?void 0:r.Status)}))}ChangeObjectsPositionsInGroupAsync(e,t){return up(this,void 0,void 0,(function*(){var n;const r=t.select((e=>e.ChannelId)).toArray(),o=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new mp(e.Guid,r),15e3,!1);return Ov.Get(rt.ServiceName).ExitConfigurationModeAsync(),(null==o?void 0:o.Status)===ce.OK?(Ov.Get(Ge.ServiceName).ClearCache(),yield this.GetGroupsAsync(!1),yield Ov.Get(xo.ServiceName).GetDevicesAsync(),ce.OK):(Ov.Get(s.ServiceName).Error(lp.ServiceName,`Failed to change objects positions in group, controller responded with error ${null==o?void 0:o.Status} data: ${null==o?void 0:o.Data}`),this.LogObjectsInGroupOrder(e,t),null==o?void 0:o.Status)}))}IsGroupsAndObjectsOrderingAvailable(){return this._objectsGroupingSupported}MoveGroupPositionAsync(e,t){return up(this,void 0,void 0,(function*(){var n;const r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new dp(e.Guid,t),15e3,!1);return Ov.Get(rt.ServiceName).ExitConfigurationModeAsync(),(null==r?void 0:r.Status)===ce.OK?(Ov.Get(Ge.ServiceName).ClearCache(),yield this.GetGroupsAsync(!1),ce.OK):(Ov.Get(s.ServiceName).Error(lp.ServiceName,`Failed to move group position, controller responded with error ${null==r?void 0:r.Status} data: ${null==r?void 0:r.Data}`),null==r?void 0:r.Status)}))}MoveObjectInGroupPositionAsync(e,t,n){return up(this,void 0,void 0,(function*(){var r;const o=`${t.GetDevice().Guid}_${t.Number}`,i=yield null===(r=this._connection)||void 0===r?void 0:r.SendAndWaitForResponseAsync(new vp(e.Guid,o,n),15e3,!1);return Ov.Get(rt.ServiceName).ExitConfigurationModeAsync(),(null==i?void 0:i.Status)===ce.OK?(Ov.Get(Ge.ServiceName).ClearCache(),yield this.GetGroupsAsync(!1),yield Ov.Get(xo.ServiceName).GetDevicesAsync(),ce.OK):(Ov.Get(s.ServiceName).Error(lp.ServiceName,`Failed to move object in group position, controller responded with error ${null==i?void 0:i.Status} data: ${null==i?void 0:i.Data}`),null==i?void 0:i.Status)}))}AddDeviceChannelToGroupByGuidAsync(e,t){return up(this,void 0,void 0,(function*(){var n,r;const o=new Cp;if(o.Data.Channel=e.Number,null==e.GetDevice())throw new Error("Device is not set on this channel!");o.Data.DeviceGuid=null===(n=e.GetDevice())||void 0===n?void 0:n.Guid,o.Data.GroupGuid=t;const i=yield null===(r=this._connection)||void 0===r?void 0:r.SendAndWaitForResponseAsync(o,15e3,!1);return Ov.Get(rt.ServiceName).ExitConfigurationModeAsync(),null!=i&&null!=i.Status?(i.Status==ce.OK?e.ChannelGroups.push(t):Ov.Get(s.ServiceName).Error(lp.ServiceName,`Failed to add device channel ${e.Name} to group ${t}, controller responded with error ${i.Status} data: ${i.Data}`),Ov.Get(Ge.ServiceName).ClearCache(),yield this.GetGroupsAsync(!1),yield Ov.Get(xo.ServiceName).GetDevicesAsync(),i.Status):(yield this.GetGroupsAsync(),ce.Error)}))}RemoveDeviceChannelFromGroupByGuidAsync(e,t){return up(this,void 0,void 0,(function*(){var n,r;const o=new Tp;if(null==e.GetDevice())throw new Error("Device is not set on this channel!");o.Data.DeviceGuid=null===(n=e.GetDevice())||void 0===n?void 0:n.Guid,o.Data.Channel=e.Number,o.Data.GroupGuid=t;const i=yield null===(r=this._connection)||void 0===r?void 0:r.SendAndWaitForResponseAsync(o,15e3,!1);return Ov.Get(rt.ServiceName).ExitConfigurationModeAsync(),null!=i&&null!=i.Status?(i.Status==ce.OK?e.ChannelGroups=e.ChannelGroups.where((e=>e!=t)).toArray():Ov.Get(s.ServiceName).Error(lp.ServiceName,`Failed to remove device channel ${e.Name} from group ${t}, controller responded with error ${i.Status} data: ${i.Data}`),Ov.Get(Ge.ServiceName).ClearCache(),yield this.GetGroupsAsync(!1),yield Ov.Get(xo.ServiceName).GetDevicesAsync(),i.Status):(yield this.GetGroupsAsync(),ce.Error)}))}UpsertGroupWithDevicesChannelsAsync(e,t){return up(this,void 0,void 0,(function*(){if(this._groups.all((t=>t.Guid!=e.Guid))){let t=yield this.AddNewGroupWithIconAsync(e.Name,e.IconName);if(!(t instanceof ap))return t instanceof De?t:new De(ip.UnknownError,"");e=t}for(let n of t.where((t=>t.ChannelGroups.all((t=>t!==e.Guid))))){let t=yield this.AddDeviceChannelToGroupAsync(n,e);if(Ov.Get(Ge.ServiceName).ClearCache(),yield this.GetGroupsAsync(!1),yield Ov.Get(xo.ServiceName).GetDevicesAsync(),t!==ce.OK)return Ov.Get(s.ServiceName).Error(lp.ServiceName,`Failed to add device channel ${n.Name} to group ${e.Name}, controller responded with error ${t}`),new De(ip.UnknownError,`Failed to add device channel ${n.Name} to group ${e.Name}, controller responded with error ${t}`)}let n=yield Ov.Get(xo.ServiceName).GetDevicesAsync();for(let o of n)for(let n of o.Channels.except(t,((e,t)=>e.GetDevice().Guid==t.GetDevice().Guid&&e.Number==t.Number)))for(var r of n.ChannelGroups.where((t=>e.Guid==t))){let t=yield this.RemoveDeviceChannelFromGroupAsync(n,e);if(Ov.Get(Ge.ServiceName).ClearCache(),yield this.GetGroupsAsync(),t!==ce.OK)return Ov.Get(s.ServiceName).Error(lp.ServiceName,`Failed to remove device channel ${n.Name} from group ${e.Name}, controller responded with error ${t}`),Ov.Get(rt.ServiceName).ExitConfigurationModeAsync(),new De(ip.UnknownError,`Failed to remove device channel ${n.Name} from group ${e.Name}, controller responded with error ${t}`)}return Ov.Get(rt.ServiceName).ExitConfigurationModeAsync(),e}))}UpdateGroupWithDevicesChannelsAsync(e,t){return up(this,void 0,void 0,(function*(){for(let n of t.where((t=>t.ChannelGroups.all((t=>t!==e))))){let t=yield this.AddDeviceChannelToGroupByGuidAsync(n,e);if(Ov.Get(Ge.ServiceName).ClearCache(),yield this.GetGroupsAsync(),t!==ce.OK)return Ov.Get(s.ServiceName).Error(lp.ServiceName,`Failed to add device channel ${n.Name} to group ${e}, controller responded with error ${t}`),Ov.Get(rt.ServiceName).ExitConfigurationModeAsync(),ce.FatalError}let n=yield Ov.Get(xo.ServiceName).GetDevicesAsync();for(let o of n)for(let n of o.Channels.except(t,((e,t)=>e.GetDevice().Guid==t.GetDevice().Guid&&e.Number==t.Number)))for(var r of n.ChannelGroups.where((t=>e==t))){let t=yield this.RemoveDeviceChannelFromGroupByGuidAsync(n,e);if(Ov.Get(Ge.ServiceName).ClearCache(),yield this.GetGroupsAsync(!1),yield Ov.Get(xo.ServiceName).GetDevicesAsync(),t!==ce.OK)return Ov.Get(s.ServiceName).Error(lp.ServiceName,`Failed to add device channel ${n.Name} to group ${e}, controller responded with error ${t}`),Ov.Get(rt.ServiceName).ExitConfigurationModeAsync(),ce.FatalError}return Ov.Get(rt.ServiceName).ExitConfigurationModeAsync(),ce.OK}))}ChangeGroupNameByGuidAsync(e,t){return up(this,void 0,void 0,(function*(){var n,s;let r=new _p,o=new Dp,i=this._groups.first((t=>t.Guid===e));o.Guid=e,o.Name=t,o.IconName=i.IconName,null===(n=r.Data)||void 0===n||n.push(o);const a=yield null===(s=this._connection)||void 0===s?void 0:s.SendAndWaitForResponseAsync(r,15e3,!1);if(Ov.Get(Ge.ServiceName).ClearCache(),this._groups=yield this.GetGroupsAsync(),Ov.Get(rt.ServiceName).ExitConfigurationModeAsync(),null!=a&&null!=a.Status)switch(a.Status){case ce.OK:return new De(ip.Success,"");case ce.WrongData:switch(a.Data){case"NameToShort":return new De(ip.NameToShort,"At least 3 characters required");case"NameAlreadyExists":return new De(ip.NameAlreadyExists,"Group with this name already exists");default:return new De(ip.OtherError,`Response error: ${a.Status} data: ${a.Data}`)}default:return new De(ip.OtherError,`Response error: ${a.Status} data: ${a.Data}`)}return new De(ip.UnknownError,"")}))}ChangeGroupNameAndIconAsync(e,t,n){return this.ChangeGroupNameAndIconByGuidAsync(e.Guid,t,n)}ChangeGroupNameAndIconByGuidAsync(e,t,n){return up(this,void 0,void 0,(function*(){var s,r;let o=new _p,i=new Dp,a=this._groups.first((t=>t.Guid===e));i.Guid=e,i.Name=t,i.IconName=n,i.ObjectsOrder=a.ObjectsOrder,null===(s=o.Data)||void 0===s||s.push(i);const c=yield null===(r=this._connection)||void 0===r?void 0:r.SendAndWaitForResponseAsync(o,15e3,!1);if(Ov.Get(Ge.ServiceName).ClearCache(),this._groups=yield this.GetGroupsAsync(),Ov.Get(rt.ServiceName).ExitConfigurationModeAsync(),null!=c&&null!=c.Status)switch(c.Status){case ce.OK:return new De(ip.Success,"");case ce.WrongData:switch(c.Data){case"NameToShort":return new De(ip.NameToShort,"At least 3 characters required");case"NameAlreadyExists":return new De(ip.NameAlreadyExists,"Group with this name already exists");default:return new De(ip.OtherError,`Response error: ${c.Status} data: ${c.Data}`)}default:return new De(ip.OtherError,`Response error: ${c.Status} data: ${c.Data}`)}return new De(ip.UnknownError,"")}))}ChangeGroupIconNameByGuidAsync(e,t){return up(this,void 0,void 0,(function*(){var n,s;let r=new _p,o=new Dp,i=this._groups.first((t=>t.Guid===e));o.Guid=e,o.Name=i.Name,o.IconName=t,null===(n=r.Data)||void 0===n||n.push(o);const a=yield null===(s=this._connection)||void 0===s?void 0:s.SendAndWaitForResponseAsync(r,15e3,!1);if(Ov.Get(Ge.ServiceName).ClearCache(),this._groups=yield this.GetGroupsAsync(),Ov.Get(rt.ServiceName).ExitConfigurationModeAsync(),null!=a&&null!=a.Status)switch(a.Status){case ce.OK:return new De(ip.Success,"");case ce.WrongData:switch(a.Data){case"NameToShort":return new De(ip.NameToShort,"At least 3 characters required");case"NameAlreadyExists":return new De(ip.NameAlreadyExists,"Group with this name already exists");default:return new De(ip.OtherError,`Response error: ${a.Status} data: ${a.Data}`)}default:return new De(ip.OtherError,`Response error: ${a.Status} data: ${a.Data}`)}return new De(ip.UnknownError,"")}))}GetServiceName(){return lp.ServiceName}WaitForSynchronizationAsync(){return this._synchronizationTaskCompletionSource}GetGroupByGuid(e){return this._groups.first((t=>t.Guid===e))}ChangeGroupNameAsync(e,t){return this.ChangeGroupNameByGuidAsync(e.Guid,t)}ChangeGroupIconNameAsync(e,t){return this.ChangeGroupNameByGuidAsync(e.Guid,t)}RemoveGroupAsync(e){return this.RemoveGroupByGuidAsync(e.Guid)}RemoveGroupByGuidAsync(e){return up(this,void 0,void 0,(function*(){var t;let n=new Sp;n.Data=e;const s=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(n,15e3,!1);Ov.Get(Ge.ServiceName).ClearCache(),yield this.GetGroupsAsync(!1),yield Ov.Get(xo.ServiceName).GetDevicesAsync();for(let t of yield Ov.Get(xo.ServiceName).GetDevicesAsync())for(let n of t.Channels)n.ChannelGroups.any((t=>t===e))&&(n.ChannelGroups=n.ChannelGroups.except(e,((e,t)=>e===t)).toArray());return Ov.Get(rt.ServiceName).ExitConfigurationModeAsync(),null!=s&&null!=s.Status?null==s?void 0:s.Status:ce.Error}))}GetGroupsAsync(){return up(this,arguments,void 0,(function*(e=!1){var t,n;const r=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Ap,15e3,e);let o=[];if((null==r?void 0:r.Status)===ce.OK){let e=Ov.Get(s.ServiceName),t=0,i=yield Ov.Get(xo.ServiceName).GetDevicesAsync();return null===(n=r.Data)||void 0===n||n.forEach((n=>{t++;let s=new ap;if(s.Guid=n.Guid,s.Name=n.Name,s.IconName=n.IconName,s.ObjectsOrder=n.ObjectsOrder,s.OrderPosition=n.OrderPosition,null==s.OrderPosition&&(s.OrderPosition=t),null==s.ObjectsOrder){this._objectsGroupingSupported=!1,s.ObjectsOrder={};let e=i.selectMany((e=>e.Channels.where((e=>e.ChannelGroups.any((e=>e==s.Guid)))))),t=0;for(let n of e)t++,s.ObjectsOrder[t]=n.ChannelId}else this._objectsGroupingSupported=!0;e.Info(lp.ServiceName,`Got group: ${s.Name} ${s.Guid} order: ${s.OrderPosition} objects order: ${JSON.stringify(s.ObjectsOrder)}`),o.push(s)})),this._groups=o,o}throw new Error(`Failed to get groups, API responded with status ${null==r?void 0:r.Status} data: ${null==r?void 0:r.Data}`)}))}AddDeviceChannelToGroupAsync(e,t){return this.AddDeviceChannelToGroupByGuidAsync(e,t.Guid)}RemoveDeviceChannelFromGroupAsync(e,t){return this.RemoveDeviceChannelFromGroupByGuidAsync(e,t.Guid)}AddNewGroupAsync(e){return up(this,void 0,void 0,(function*(){var t,n;let r=new _p,o=new Dp;o.Name=e,null===(t=r.Data)||void 0===t||t.push(o);const i=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(r,15e3,!1);if(Ov.Get(Ge.ServiceName).ClearCache(),yield this.GetGroupsAsync(!1),yield Ov.Get(xo.ServiceName).GetDevicesAsync(),Ov.Get(rt.ServiceName).ExitConfigurationModeAsync(),null!=i&&null!=i.Status)switch(i.Status){case ce.OK:return this._groups.first((t=>t.Name===e));case ce.WrongData:switch(Ov.Get(s.ServiceName).Error(lp.ServiceName,`Failed to add new group, controller responded with error ${i.Status} data: ${i.Data}`),i.Data){case"NameToShort":return new De(ip.NameToShort,"At least 3 characters required");case"NameAlreadyExists":return new De(ip.NameAlreadyExists,"Group with this name already exists");default:return new De(ip.OtherError,`Response error: ${i.Status} data: ${i.Data}`)}default:return new De(ip.OtherError,`Response error: ${i.Status} data: ${i.Data}`)}return new De(ip.UnknownError,"")}))}AddNewGroupWithIconAsync(e,t){return up(this,void 0,void 0,(function*(){var n,r;let o=new _p,i=new Dp;i.Name=e,i.IconName=t,null===(n=o.Data)||void 0===n||n.push(i);const a=yield null===(r=this._connection)||void 0===r?void 0:r.SendAndWaitForResponseAsync(o,15e3,!1);if(Ov.Get(Ge.ServiceName).ClearCache(),yield this.GetGroupsAsync(!1),yield Ov.Get(xo.ServiceName).GetDevicesAsync(),Ov.Get(rt.ServiceName).ExitConfigurationModeAsync(),null!=a&&null!=a.Status)switch(a.Status){case ce.OK:return this._groups.first((t=>t.Name===e));case ce.WrongData:switch(Ov.Get(s.ServiceName).Error(lp.ServiceName,`Failed to add new group, controller responded with error ${a.Status} data: ${a.Data}`),a.Data){case"NameToShort":return new De(ip.NameToShort,"At least 3 characters required");case"NameAlreadyExists":return new De(ip.NameAlreadyExists,"Group with this name already exists");default:return new De(ip.OtherError,`Response error: ${a.Status} data: ${a.Data}`)}default:return new De(ip.OtherError,`Response error: ${a.Status} data: ${a.Data}`)}return new De(ip.UnknownError,"")}))}}lp.ServiceName="ChannelsGroupsService";class dp extends ae{constructor(e,t){super(),this.Resource="/devices/groups/group/move",this.Method=ue.Post,this.Data=new fp,this.Data.GroupGuid=e,this.Data.NewPosition=t}}class hp extends ae{constructor(e){super(),this.Resource="/devices/groups/move",this.Method=ue.Post,this.Data=e}}class gp extends ae{constructor(e,t){super(),this.Resource="/devices/groups/group/objects/set",this.Method=ue.Post,this.Data=new pp,this.Data.GroupGuid=e.Guid,this.Data.ObjectsIds=t}}class pp{constructor(){this.GroupGuid="",this.ObjectsIds=[]}}class fp{constructor(){this.GroupGuid="",this.NewPosition=0}}class vp extends ae{constructor(e,t,n){super(),this.Resource="/devices/groups/group/object/move",this.Method=ue.Post,this.Data=new yp,this.Data.GroupGuid=e,this.Data.NewPosition=n,this.Data.ObjectId=t}}class mp extends ae{constructor(e,t){super(),this.Resource="/devices/groups/group/objects/move",this.Method=ue.Post,this.Data=new wp,this.Data.GroupGuid=e,this.Data.OrderedObjectsIds=t}}class yp{constructor(){this.GroupGuid="",this.ObjectId="",this.NewPosition=0}}class wp{constructor(){this.GroupGuid="",this.OrderedObjectsIds=[]}}class Sp extends ae{constructor(){super(),this.Resource="/devices/groups/group",this.Method=ue.Delete}}class Ap extends ae{constructor(){super(),this.Resource="/devices/groups/",this.Method=ue.Get}}class _p extends ae{constructor(){super(),this.Resource="/devices/groups/group",this.Method=ue.Put,this.Data=[]}}class Cp extends ae{constructor(){super(),this.Resource="/devices/device/channel/groups/group/",this.Method=ue.Put,this.Data=new kp}}class Tp extends ae{constructor(){super(),this.Resource="/devices/device/channel/groups/group/",this.Method=ue.Delete,this.Data=new kp}}class Dp{constructor(){this.Id=0,this.Guid="",this.Name="",this.IconName="",this.OrderPosition=0,this.ObjectsOrder={}}}class kp{constructor(){this.GroupGuid="",this.DeviceGuid="",this.Channel=0}}class Gp{constructor(){this._promise=Promise.resolve(),this._disable=()=>{}}Lock(){this._promise=new Promise((e=>this._disable=e))}Unlock(){this._disable()}WaitForLockAsync(){return this._promise}}!function(e){e[e.Suspended=1]="Suspended",e[e.ReturnedFromSuspension=2]="ReturnedFromSuspension",e[e.EnteredLowPowerMode=3]="EnteredLowPowerMode",e[e.ExitedLowPowerMode=4]="ExitedLowPowerMode",e[e.LoggedIn=5]="LoggedIn",e[e.LoggedOut=6]="LoggedOut",e[e.Connected=7]="Connected",e[e.Disconnected=8]="Disconnected",e[e.FailedToConnect=9]="FailedToConnect",e[e.Connecting=10]="Connecting",e[e.Disconnecting=11]="Disconnecting",e[e.Reconnecting=12]="Reconnecting"}(cp||(cp={}));var bp,Np,Ep,Ip,Rp,Pp,Op,Up,Mp,xp=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class Fp{constructor(){this._syncLock=new Gp,this._isInFouces=!0,this._canHibernate=!0,this._session=null,this._connection=null,this._currentAppState=cp.Disconnected,this._returnedFromSuspension=!1,this._onReturnedFromSuspensionEvent=new Ce,this._onSuspendedEvent=new Ce,this._onEnterLowPowerModeEvent=new Ce,this._onExitLowPowerModeEvent=new Ce,this._onBackButtonPressedEvent=new Ce,this._onForwardButtonPressedEvent=new Ce,this._onAppStateChanged=new n,this.MonitorAppState(),this._onAppStateChanged.Subscribe((e=>this._currentAppState=e)),null==navigator.userAgent.match(/Safari/i)||navigator.mediaDevices?window.addEventListener("visibilitychange",(()=>xp(this,void 0,void 0,(function*(){yield this._syncLock.WaitForLockAsync(),this._syncLock.Lock(),this.IsHidden()?this.Suspend():this.ReturnFromSuspension(),this._syncLock.Unlock()})))):(window.addEventListener("onblur",(()=>{this._isInFouces&&(this._isInFouces=!1,this.Suspend())})),window.addEventListener("onfocus",(()=>{this._isInFouces||(this._isInFouces=!0,this.ReturnFromSuspension())}))),window.addEventListener("popstate",(e=>{var t,n,s,o;document.location,e.state&&("forward"==e.state.direction?(null===(t=r.Log)||void 0===t||t.Warning(Fp.ServiceName,"Forward button pressed"),null===(n=this._onForwardButtonPressedEvent)||void 0===n||n.Invoke()):(null===(s=r.Log)||void 0===s||s.Warning(Fp.ServiceName,"Back button pressed"),null===(o=this._onBackButtonPressedEvent)||void 0===o||o.Invoke()))}))}MonitorAppState(){return xp(this,void 0,void 0,(function*(){this._session=yield Ov.GetAsync("SessionService"),this._connection=yield Ov.GetAsync("ExalusConnectionService"),this._session.OnUserLoggedInEvent().Subscribe((e=>{var t;null===(t=r.Log)||void 0===t||t.Warning(Fp.ServiceName,"App state changed to: logged in"),this._onAppStateChanged.Invoke(cp.LoggedIn)})),this._session.OnUserLoggedOutEvent().Subscribe((e=>{var t;null===(t=r.Log)||void 0===t||t.Warning(Fp.ServiceName,"App state changed to: logged out"),this._onAppStateChanged.Invoke(cp.LoggedOut)})),this._connection.OnConnectionStateChangedEvent().Subscribe((e=>{var t,n,s,o,i,a;switch(e){case he.Connected:null===(t=r.Log)||void 0===t||t.Warning(Fp.ServiceName,"App state changed to: connected"),this._onAppStateChanged.Invoke(cp.Connected);break;case he.Disconnected:null===(n=r.Log)||void 0===n||n.Warning(Fp.ServiceName,"App state changed to: disconnected"),this._onAppStateChanged.Invoke(cp.Disconnected);break;case he.Connecting:null===(s=r.Log)||void 0===s||s.Warning(Fp.ServiceName,"App state changed to: connecting"),this._onAppStateChanged.Invoke(cp.Connecting);break;case he.Disconnecting:null===(o=r.Log)||void 0===o||o.Warning(Fp.ServiceName,"App state changed to: disconnecting"),this._onAppStateChanged.Invoke(cp.Disconnecting);break;case he.Reconnecting:null===(i=r.Log)||void 0===i||i.Warning(Fp.ServiceName,"App state changed to: reconnecting"),this._onAppStateChanged.Invoke(cp.Reconnecting);break;case he.Failed:null===(a=r.Log)||void 0===a||a.Warning(Fp.ServiceName,"App state changed to: failed"),this._onAppStateChanged.Invoke(cp.FailedToConnect)}}))}))}get CurrentAppState(){return this._currentAppState}OnAppStateChanged(){return this._onAppStateChanged}Suspend(){var e,t;this.IsHibernationAllowed()&&(this._returnedFromSuspension=!1,this._onSuspendedEvent.Invoke(),this._onAppStateChanged.Invoke(cp.Suspended),null===(e=r.Log)||void 0===e||e.Warning(Fp.ServiceName,"App state changed to: suspended"),null===(t=r.Log)||void 0===t||t.Warning(Fp.ServiceName,"App switched to background"))}ReturnFromSuspension(){var e,t;this.IsHibernationAllowed()&&(this._returnedFromSuspension=!0,this._onReturnedFromSuspensionEvent.Invoke(),this._onAppStateChanged.Invoke(cp.ReturnedFromSuspension),null===(e=r.Log)||void 0===e||e.Warning(Fp.ServiceName,"App state changed to: returned from suspension"),null===(t=r.Log)||void 0===t||t.Warning(Fp.ServiceName,"App switched to foreground"))}EnterLowPowerMode(){this._onEnterLowPowerModeEvent.Invoke(),this._onAppStateChanged.Invoke(cp.EnteredLowPowerMode)}ExitLowPowerMode(){this._onExitLowPowerModeEvent.Invoke(),this._onAppStateChanged.Invoke(cp.ExitedLowPowerMode)}IsWorkingInWebView(){return"file:"===window.location.protocol||null!=navigator.userAgent.match(/Safari/i)&&!navigator.mediaDevices}IsHidden(){return document.hidden}IsActive(){return!this.IsHidden()}IsInBackground(){return this.IsHidden()}ReturnedFromSuspension(){return this._returnedFromSuspension}IsHibernationAllowed(){return this._canHibernate}DisallowHibernation(){this._canHibernate=!1}AllowHibernation(){this._canHibernate=!0}OnReturnedFromSuspension(){return this._onReturnedFromSuspensionEvent}OnSuspended(){return this._onSuspendedEvent}OnEnterLowPowerMode(){return this._onEnterLowPowerModeEvent}OnExitLowPowerMode(){return this._onExitLowPowerModeEvent}OnBackButtonPressed(){return this._onBackButtonPressedEvent}OnForwardButtonPressed(){return this._onForwardButtonPressedEvent}GetServiceName(){return Fp.ServiceName}}Fp.ServiceName="AppStateService";class Lp{constructor(){this.DeviceGuid="",this.CurrentVersion="",this.NewVersion=""}}class Bp{constructor(){this.UpdatesAvailable=[],this.UpdatesNotAvailable=[]}}class Wp{constructor(){this.UpdatedResourceName=new Map,this.UpdateDescription=new Map,this.UpdateCreationTime=null,this.Version="",this.UpdateChannel=""}}class $p{constructor(){this.Resource="",this.Version="",this.Type=null}}!function(e){e[e.RadioUpdate=0]="RadioUpdate",e[e.SoftwareUpdate=1]="SoftwareUpdate"}(bp||(bp={})),function(e){e[e.DownloadingFailure=-5]="DownloadingFailure",e[e.InstallationStopped=-4]="InstallationStopped",e[e.InstallationError=-3]="InstallationError",e[e.IncompatiblePackage=-2]="IncompatiblePackage",e[e.Error=-1]="Error",e[e.OK=0]="OK",e[e.DownloadingPackage=1]="DownloadingPackage",e[e.CheckingPackage=2]="CheckingPackage",e[e.PreparingForUpgrade=3]="PreparingForUpgrade",e[e.Upgrading=4]="Upgrading",e[e.MovingData=5]="MovingData",e[e.Reloading=6]="Reloading",e[e.Upgraded=7]="Upgraded"}(Np||(Np={})),(Mp=Ep||(Ep={}))[Mp.WaitingForUser=1]="WaitingForUser",Mp[Mp.Downloading=2]="Downloading",Mp[Mp.Unpackaging=3]="Unpackaging",Mp[Mp.CheckingApplicability=4]="CheckingApplicability",Mp[Mp.MigratingData=5]="MigratingData",Mp[Mp.CreatingBackup=6]="CreatingBackup",Mp[Mp.Deploying=7]="Deploying",Mp[Mp.Installing=8]="Installing",Mp[Mp.Removing=9]="Removing",Mp[Mp.Error=10]="Error",Mp[Mp.ReadyToDownload=11]="ReadyToDownload",Mp[Mp.PreparingSystem=12]="PreparingSystem",Mp[Mp.CheckingPackageIntegrity=13]="CheckingPackageIntegrity",Mp[Mp.CheckingIntegrity=14]="CheckingIntegrity",Mp[Mp.UndoingInstallation=15]="UndoingInstallation",Mp[Mp.Installed=16]="Installed",(Up=Ip||(Ip={}))[Up.Ignore=0]="Ignore",Up[Up.Cancel=1]="Cancel",Up[Up.Install=2]="Install";class qp{constructor(){this.UpdatedResourceName=new Map,this.Percentage=0,this.PercentageTotal=0,this.Status=Np.Error,this.UpdateNumber=1,this.AvailableUpdates=1}}class Vp{constructor(){this.UpdatedResourceName=new Map,this.Percentage=0,this.PercentageTotal=0,this.SpeedMbps=0,this.CurrentTask=Rp.Unknown}}!function(e){e[e.Unknown=0]="Unknown",e[e.DownloadingUpdate=1]="DownloadingUpdate",e[e.DownloadingInstaller=2]="DownloadingInstaller",e[e.CheckingUpdate=3]="CheckingUpdate"}(Rp||(Rp={})),function(e){e[e.DeviceIsUpToDate=0]="DeviceIsUpToDate",e[e.CannotFindDevice=1]="CannotFindDevice",e[e.UnsupportedApiVersion=2]="UnsupportedApiVersion",e[e.UnsupportedDevice=3]="UnsupportedDevice",e[e.CannotGetFirmwareVersion=4]="CannotGetFirmwareVersion",e[e.CannotGetUpdates=5]="CannotGetUpdates",e[e.CannotProcessUpdate=6]="CannotProcessUpdate",e[e.UpdateActionsNotSupported=7]="UpdateActionsNotSupported",e[e.UnsupportedExtensionVersion=8]="UnsupportedExtensionVersion",e[e.UpdatesPartiallyInstalled=9]="UpdatesPartiallyInstalled",e[e.RetransmitterFound=10]="RetransmitterFound",e[e.ProtocolRadioUnsupported=11]="ProtocolRadioUnsupported",e[e.FeatureUnsupportedInCurrentVersion=12]="FeatureUnsupportedInCurrentVersion",e[e.CannotGetUpdatesBranch=13]="CannotGetUpdatesBranch",e[e.CannotSetUpdatesBranch=14]="CannotSetUpdatesBranch",e[e.UpdateAlreadyDownloaded=15]="UpdateAlreadyDownloaded",e[e.UpdateDownloadFailed=16]="UpdateDownloadFailed",e[e.UpdateAlreadyInstalled=17]="UpdateAlreadyInstalled",e[e.CannotGetCurrentControllerVersionTimeout=18]="CannotGetCurrentControllerVersionTimeout",e[e.CannotGetCurrentControllerVersion=19]="CannotGetCurrentControllerVersion"}(Pp||(Pp={})),function(e){e.Public="public",e.Beta="beta",e.Development="dev"}(Op||(Op={}));var Hp,jp,Kp,zp,Jp,Yp,Xp,Qp,Zp=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class ef{constructor(){this._controllerUpdates=[],this._updateRequestTimeout=12e4,this._oldUpdateVersion=5,this._oldUpdateBuild=56,this._updateOfflineStageTime=8.5,this._updateProviders=Ov.Get(Xr.ServiceName),this._logger=Ov.Get(s.ServiceName),this._connection=Ov.Get(Pt.ServiceName),this._appStateService=Ov.Get(Fp.ServiceName),this._extensionService=Ov.Get(Ze.ServiceName)}GetAutomaticControllerUpdateDownloadStatusAsync(){return Zp(this,void 0,void 0,(function*(){const e=yield this.getRuntimeInfoAsync();if(e instanceof De)return e;const t=parseInt(e.SoftwareVersion.toString().split(".")[0]),n=parseInt(e.SoftwareVersion.toString().split(".")[1]);if(t<=this._oldUpdateVersion&&n<=this._oldUpdateBuild)return new De(Pp.FeatureUnsupportedInCurrentVersion,`Cannot get update branch, feature unsupported in current version. Current version: ${e}`);let s=yield this._connection.SendAndWaitForResponseAsync(new ff,1e4,!1);return!(s.Status!=ce.OK||!s.Data)}))}GetServiceName(){return ef.ServiceName}CheckDeviceVersionAsync(e){return Zp(this,void 0,void 0,(function*(){var t;let n;if("string"==typeof e){const t=yield Ov.Get(xo.ServiceName).GetDevice(e);if(null==t)return new De(Pp.CannotFindDevice,`Device with specified GUID ${e} does not exists.`);n=t}else n=e;if(null==n.ProtocolGuid)return new De(Pp.UnsupportedDevice,"Device does not contains data about protocol GUID.");const s=yield null===(t=(yield this._updateProviders.GetUpdatesProvidersByProtocolAsync(n.ProtocolGuid,Nr.Device)).first())||void 0===t?void 0:t.GetSoftwareVersionAsync(n);return s.Type,s}))}CheckDeviceUpdateAsync(e){return Zp(this,void 0,void 0,(function*(){var t;let n;if("string"==typeof e){const t=yield Ov.Get(xo.ServiceName).GetDevice(e);if(null==t)return new De(Pp.CannotFindDevice,`Device with specified GUID ${e} does not exists.`);n=t}else n=e;if(null==n.ProtocolGuid)return new De(Pp.UnsupportedDevice,"Device does not contains data about protocol GUID.");const s=yield null===(t=(yield this._updateProviders.GetUpdatesProvidersByProtocolAsync(n.ProtocolGuid,Nr.Device)).first())||void 0===t?void 0:t.GetAvailableUpdateAsync(n);if(null!=s.Type)return s;const r=new sf;r.CurrentResourceVersion=s.CurrentResourceVersion,r.NewResourceVersion=s.Update.Version,r.UpdatedResourceName=s.UpdatedResourceName,r.UpdateResourceGuid=s.Update.ResourceGuid,r.UpdateDescription=new Map([["pl-PL",s.Update.Description]]);let o="n/a";try{o=(yield this._extensionService.GetProtocolInfoAsync(n.ProtocolGuid)).first().Name}catch(e){this._logger.Warning(`Cannot get protocol name! error: ${e}`)}return r.Protocol=o,r.ProtocolGuid=n.ProtocolGuid,(yield Ov.Get(xo.ServiceName).GetDevicesAsync()).any((e=>"952ddc14-76c4-4f47-b0bc-5d106c1f9b02"==e.ModelGuid))&&(r.IsUpdateSafe=!1),r}))}InstallDeviceUpdateAsync(e,t,n){return Zp(this,arguments,void 0,(function*(e,t,n,s=!1){var r;let o;if("string"==typeof e){const t=yield Ov.Get(xo.ServiceName).GetDevice(e);if(null==t)return new De(Pp.CannotFindDevice,`Device with specified GUID ${e} does not exists.`);o=t}else o=e;if(null==o.ProtocolGuid)return new De(Pp.UnsupportedDevice,"Device does not contains data about protocol GUID.");const i=yield null===(r=(yield this._updateProviders.GetUpdatesProvidersByProtocolAsync(o.ProtocolGuid,Nr.Device)).first())||void 0===r?void 0:r.GetAvailableUpdateAsync(o);if(null!=i.Type)return i;this._appStateService.DisallowHibernation();const a=yield(yield this._updateProviders.GetUpdatesProvidersByProtocolAsync(o.ProtocolGuid,Nr.Device)).first().InstallUpdateAsync(i,t,n,s);return null!=a.Type?(this._appStateService.AllowHibernation(),a):(this._appStateService.AllowHibernation(),ce.OK)}))}CheckControllerSoftwareUpdateAvailabilityAsync(){return Zp(this,void 0,void 0,(function*(){const e=Ov.Get(Ke.ServiceName).User;if(null==e)return!1;if(""==e.SoftwareVersion||null==e.SoftwareVersion)return!0;const[t,n]=e.SoftwareVersion.split(".");if(parseFloat(t)<=this._oldUpdateVersion&&parseFloat(n)<=this._oldUpdateBuild)return!0;const s=yield this._connection.SendAndWaitForResponseAsync(new df,1e4,!1);if(null==s||s.Status!=ce.OK||null==s.Data)return!1;const[r,o]=s.Data.Update.Version.ContainerSoftwareVersion.toString().split(".");return parseInt(r)>parseInt(t)||parseInt(r)==parseInt(t)&&parseInt(o)>parseInt(n)}))}CheckDevicesUpdatesAvailabilityAsync(){return Zp(this,void 0,void 0,(function*(){const e=yield this._connection.SendAndWaitForResponseAsync(new wf,1e4,!1),t=[];return null==e||(null==e?void 0:e.Status)!=ce.OK||null==(null==e?void 0:e.Data)?[]:(null==e||e.Data.forEach((e=>{if(!e.IsAvailable)return;const n=new Lp;n.DeviceGuid=e.DeviceGuid,n.CurrentVersion=e.CurrentVersion,n.NewVersion=e.NewVersion,t.push(n)})),t)}))}CheckControllerUpdatesAsync(){return Zp(this,void 0,void 0,(function*(){this._controllerUpdates=[];let e=[];const t=new Bp,n=yield this.getRuntimeInfoAsync();if(n instanceof De){const e=new tf;return e.UpdateType=bp.SoftwareUpdate,e.ResponseResult=n,t.UpdatesNotAvailable.push(e),t}const s=parseInt(n.SoftwareVersion.toString().split(".")[0]),r=parseInt(n.SoftwareVersion.toString().split(".")[1]);try{e=yield this._updateProviders.GetUpdatesProvidersAsync(Nr.Controller)}catch(e){if(!(e instanceof jr))throw e;this._logger.Warning("Cannot get update providers for controller protocols! Avaliable only controller software updates!")}for(let n=0;n<e.length;n++){const s=yield e[n].GetAvailableRadioUpdateAsync();if(null!=s.Type){const r=new tf;r.ResponseResult=s,r.UpdateType=bp.RadioUpdate;let o="n/a";try{o=(yield this._extensionService.GetProtocolInfoAsync(e[n].ProtocolGuid)).first().Name}catch(e){this._logger.Warning(`Cannot get protocol name! error: ${e}`)}r.UpdatedResourceName=new Map([["pl-PL",o],["en-US",o]]),r.CurrentResourceVersion=yield e[n].GetCurrentRadioVersionAsync(),t.UpdatesNotAvailable.push(r)}else{const r=s,o=new nf;o.UpdatedResourceName=new Map([["pl-PL",r.UpdatedResourceName],["en-US",r.UpdatedResourceName]]),o.CurrentResourceVersion=r.CurrentResourceVersion,o.NewResourceVersion=r.Update.Version,o.UpdateDescription=new Map([["pl-PL",r.Update.Description]]),o.UpdateType=bp.RadioUpdate,o.UpdateIdentifier=re.GenerateUUID(),o.UpdateIsDownloading=!1,o.DownloadProgress=100,o.UpdateCreationTime=null,t.UpdatesAvailable.push(o),this._controllerUpdates.push(Object.assign(Object.assign({},r),{UpdateIdentifier:o.UpdateIdentifier,ProviderName:e[n].GetUpdateProviderName(),UpdateType:bp.RadioUpdate}))}}let o=!0;if(s<=this._oldUpdateVersion&&r<=this._oldUpdateBuild&&(o=!1),o){const e=yield this._connection.SendAndWaitForResponseAsync(new df,15e3,!1);if(null==e||e.Status!=ce.OK&&e.Status!=ce.NoData)throw new Error(`Cannot get pending updates! Response is empty or status is not OK. Status: ${null==e?void 0:e.Status}`);if(null!=e.Data){const s=new Hr;s.CurrentResourceVersion=`${n.RuntimeVersion}.${n.SoftwareVersion}`,s.UpdateDescription=ie(e.Data.Update.UpdateDescription),s.UpdatedResourceName=ie(e.Data.Update.UpdateName).get("en-US");const r=new nf;r.UpdatedResourceName=ie(e.Data.Update.UpdateName),r.UpdateDescription=ie(e.Data.Update.UpdateDescription),r.CurrentResourceVersion=`${n.RuntimeVersion}.${n.SoftwareVersion}`,r.NewResourceVersion=`${e.Data.Update.Version.BaseRuntime}.${e.Data.Update.Version.ContainerSoftwareVersion}`,r.UpdateType=bp.SoftwareUpdate,r.UpdateIdentifier=e.Data.Update.Guid,r.UpdateIsDownloading=e.Data.UpdateStep==zp.DownloadingInstaller||e.Data.UpdateStep==zp.DownloadingUpdate||e.Data.UpdateStep==zp.CheckingUpdate,r.DownloadProgress=e.Data.DownloadProgress,r.UpdateCreationTime=e.Data.Update.Creationtime,t.UpdatesAvailable.push(r),this._controllerUpdates.push(Object.assign(Object.assign({},s),{UpdateIdentifier:r.UpdateIdentifier,ProviderName:ef.ServiceName,UpdateType:bp.SoftwareUpdate}))}else{const e=yield this._connection.SendAndWaitForResponseAsync(new hf,15e3,!1);if(null==e)throw new Error("Cannot check updates! Response is empty.");switch(e.Status){case ce.NoData:const s=new tf;s.UpdateType=bp.SoftwareUpdate,s.UpdatedResourceName=new Map([["pl-PL","Oprogramowanie kontrolera"],["en-US","Controller software"]]),s.ResponseResult=new De(Pp.DeviceIsUpToDate,"Updates not found, controller is already up-to-date."),t.UpdatesNotAvailable.push(s);break;case ce.OK:if(null==e.Data)throw new Error("Cannot check updates! Response data is empty.");const r=new Hr;r.CurrentResourceVersion=`${n.RuntimeVersion}.${n.SoftwareVersion}`,r.UpdateDescription=ie(e.Data.UpdateDescription),r.UpdatedResourceName=ie(e.Data.UpdateName).get("en-US");const o=new nf;o.UpdatedResourceName=ie(e.Data.UpdateName),o.UpdateDescription=ie(e.Data.UpdateDescription),o.CurrentResourceVersion=`${n.RuntimeVersion}.${n.SoftwareVersion}`,o.UpdateType=bp.SoftwareUpdate,o.UpdateIdentifier=e.Data.Guid,o.NewResourceVersion=`${e.Data.Version.BaseRuntime}.${e.Data.Version.ContainerSoftwareVersion}`,o.UpdateIsDownloading=!1,o.DownloadProgress=0,o.UpdateCreationTime=e.Data.Creationtime,t.UpdatesAvailable.push(o),this._controllerUpdates.push(Object.assign(Object.assign({},r),{UpdateIdentifier:o.UpdateIdentifier,ProviderName:ef.ServiceName,UpdateType:bp.SoftwareUpdate}));break;default:throw new Error(`Cannot check updates! Response status is not OK. Status: ${e.Status}`)}}}else{const e=`https://updates.tr7.pl/software/${n.UpdateChannel}/${n.RuntimeVersion}/${n.SoftwareVersion}/update.json`;try{const s=yield fetch(e);let r,o=new Hr;const i=new tf;switch(i.UpdateType=bp.SoftwareUpdate,i.UpdatedResourceName=new Map([["pl-PL","Oprogramowanie kontrolera"],["en-US","Controller software"]]),s.status){case 200:null!=s.body&&(r=yield s.json());break;case 404:i.ResponseResult=new De(Pp.DeviceIsUpToDate,"Updates not found, controller is already up-to-date."),t.UpdatesNotAvailable.push(i);break;default:i.ResponseResult=new De(Pp.CannotGetUpdates,`Response status code does not indicate success. Status: ${s.status}`),t.UpdatesNotAvailable.push(i)}if(null!=r){o.CurrentResourceVersion=`${n.RuntimeVersion}.${n.SoftwareVersion}`,o.Update=r;const e=new nf;e.UpdatedResourceName=new Map([["pl-PL","Oprogramowanie kontrolera"],["en-US","Controller software"]]),e.CurrentResourceVersion=o.CurrentResourceVersion,e.NewResourceVersion=o.Update.Version,e.UpdateDescription=new Map([["pl-PL",o.Update.Description]]),e.UpdateType=bp.SoftwareUpdate,e.UpdateIdentifier=re.GenerateUUID(),e.DownloadProgress=100,e.UpdateIsDownloading=!1,e.UpdateCreationTime=null,t.UpdatesAvailable.push(e),this._controllerUpdates.push(Object.assign(Object.assign({},o),{UpdateIdentifier:e.UpdateIdentifier,ProviderName:ef.ServiceName,UpdateType:bp.SoftwareUpdate}))}else if(200==s.status)throw new Error(`Cannot get Update Data from response. Status: ${s.status}`)}catch(e){const n=yield this.getRuntimeInfoAsync();if(n instanceof De){const e=new tf;e.UpdateType=bp.SoftwareUpdate,e.UpdatedResourceName=new Map([["pl-PL","Oprogramowanie kontrolera"],["en-US","Controller software"]]),e.ResponseResult=n,t.UpdatesNotAvailable.push(e)}else{const s=new tf;s.UpdateType=bp.SoftwareUpdate,s.UpdatedResourceName=new Map([["pl-PL","Oprogramowanie kontrolera"],["en-US","Controller software"]]),s.ResponseResult=new De(Pp.CannotGetUpdates,`Cannot get available updates! ${e}`),s.CurrentResourceVersion=`${n.RuntimeVersion}.${n.SoftwareVersion}`,t.UpdatesNotAvailable.push(s)}}}return t}))}CheckControllerVersionAsync(){return Zp(this,void 0,void 0,(function*(){const e=yield this._updateProviders.GetUpdatesProvidersAsync(Nr.Controller),t=yield this.getRuntimeInfoAsync();if(t instanceof De)return t;const n=[];let s;s=new $p,s.Resource="Controller software",s.Type=bp.SoftwareUpdate,s.Version=`${t.RuntimeVersion}.${t.SoftwareVersion}`,n.push(s);for(let t=0;t<e.length;t++){s=new $p,s.Version=yield e[t].GetCurrentRadioVersionAsync(),s.Type=bp.RadioUpdate;let r="n/a";try{r=(yield this._extensionService.GetProtocolInfoAsync(e[t].ProtocolGuid)).first().Name}catch(e){this._logger.Warning(`Cannot get protocol name! error: ${e}`)}s.Resource=r,n.push(s)}return n}))}GetControllerUpdateBranchAsync(){return Zp(this,void 0,void 0,(function*(){const e=yield this.getRuntimeInfoAsync();if(e instanceof De)return e;const t=parseInt(e.SoftwareVersion.toString().split(".")[0]),n=parseInt(e.SoftwareVersion.toString().split(".")[1]);if(t<=this._oldUpdateVersion&&n<=this._oldUpdateBuild)return new De(Pp.FeatureUnsupportedInCurrentVersion,`Cannot get update branch, feature unsupported in current version. Current version: ${e}`);const s=yield this._connection.SendAndWaitForResponseAsync(new uf,1e4,!1);if(null==s||(null==s?void 0:s.Status)!=ce.OK)return new De(Pp.CannotGetUpdatesBranch,`Cannot get update branch, response is empty or status is not OK. Status: ${null==s?void 0:s.Status}`);switch(s.Data){case 0:return Op.Public;case 1:return Op.Beta;case 2:return Op.Development;default:return new De(Pp.CannotGetUpdatesBranch,`Cannot get update branch, unknown branch number. Branch number: ${s.Data}`)}}))}SetControllerUpdateBranchAsync(e){return Zp(this,void 0,void 0,(function*(){const t=yield this.getRuntimeInfoAsync();if(t instanceof De)return t;const n=parseInt(t.SoftwareVersion.toString().split(".")[0]),s=parseInt(t.SoftwareVersion.toString().split(".")[1]);if(n<=this._oldUpdateVersion&&s<=this._oldUpdateBuild)return new De(Pp.FeatureUnsupportedInCurrentVersion,`Cannot set update branch, feature unsupported in current version. Current version: ${t}`);const r=yield this._connection.SendAndWaitForResponseAsync(new lf(e),1e4,!1);return null==r||(null==r?void 0:r.Status)!=ce.OK?new De(Pp.CannotSetUpdatesBranch,`Cannot set update branch, response is empty or status is not OK. Status: ${null==r?void 0:r.Status}`):ce.OK}))}EnableAutomaticControllerUpdateDonwloadAsync(){return Zp(this,void 0,void 0,(function*(){const e=yield this.getRuntimeInfoAsync();if(e instanceof De)return e;const t=parseInt(e.SoftwareVersion.toString().split(".")[0]),n=parseInt(e.SoftwareVersion.toString().split(".")[1]);if(t<=this._oldUpdateVersion&&n<=this._oldUpdateBuild)return new De(Pp.FeatureUnsupportedInCurrentVersion,`Cannot enable automatic updates download, feature unsupported in current version. Current version: ${e}`);const s=yield this._connection.SendAndWaitForResponseAsync(new vf,1e4,!1);return null==s||(null==s?void 0:s.Status)!=ce.OK?new De(Pp.CannotSetUpdatesBranch,`Cannot enable automatic updates download, response is empty or status is not OK. Status: ${null==s?void 0:s.Status}`):ce.OK}))}DisableAutomaticControllerUpdateDonwloadAsync(){return Zp(this,void 0,void 0,(function*(){const e=yield this.getRuntimeInfoAsync();if(e instanceof De)return e;const t=parseInt(e.SoftwareVersion.toString().split(".")[0]),n=parseInt(e.SoftwareVersion.toString().split(".")[1]);if(t<=this._oldUpdateVersion&&n<=this._oldUpdateBuild)return new De(Pp.FeatureUnsupportedInCurrentVersion,`Cannot disable automatic update download, feature unsupported in current version. Current version: ${e}`);const s=yield this._connection.SendAndWaitForResponseAsync(new mf,1e4,!1);return null==s||(null==s?void 0:s.Status)!=ce.OK?new De(Pp.CannotSetUpdatesBranch,`Cannot disable automatic update download, response is empty or status is not OK. Status: ${null==s?void 0:s.Status}`):ce.OK}))}GetControllerUpdatesHistoryAsync(){return Zp(this,void 0,void 0,(function*(){const e=yield this.getRuntimeInfoAsync();if(e instanceof De)return e;const t=parseInt(e.SoftwareVersion.toString().split(".")[0]),n=parseInt(e.SoftwareVersion.toString().split(".")[1]);if(t<=this._oldUpdateVersion&&n<=this._oldUpdateBuild)return new De(Pp.FeatureUnsupportedInCurrentVersion,`Cannot disable automatic update download, feature unsupported in current version. Current version: ${e}`);const s=yield this._connection.SendAndWaitForResponseAsync(new yf,1e4,!1);if(null==s)return new De(Pp.CannotGetUpdates,"Cannot get updates history, response is empty.");switch(s.Status){case ce.OK:return null!=s.Data?s.Data.map((e=>{const t=new Wp;return t.UpdatedResourceName=ie(e.UpdateName),t.UpdateDescription=ie(e.UpdateDescription),t.UpdateCreationTime=e.Creationtime,t.UpdateChannel=e.UpdateChannel,t.Version=`${e.Version.BaseRuntime}.${e.Version.ContainerSoftwareVersion}`,t})):new De(Pp.CannotGetUpdates,"Cannot get updates history, response data is empty.");case ce.NoData:return[];default:return new De(Pp.CannotGetUpdates,`Cannot get updates history, response status is not OK. Status: ${s.Status}`)}}))}InstallControllerUpdateAsync(e,t,n,s,r){return Zp(this,void 0,void 0,(function*(){const o=new RegExp("^[{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]?$"),i=this._controllerUpdates.length,a=yield this.getRuntimeInfoAsync();if(a instanceof De)return a;const c=parseInt(a.SoftwareVersion.toString().split(".")[0]),u=parseInt(a.SoftwareVersion.toString().split(".")[1]);if(0==this._controllerUpdates.length)return new De(Pp.CannotGetUpdates,"Cannot find any updates, make sure you check for available updates by calling CheckControllerUpdateAsync().");if("string"!=typeof n||!o.test(n)){const r=[1],o=t=>{t.UpdateNumber=r[0],t.AvailableUpdates=i,e(t)},a=e=>Zp(this,void 0,void 0,(function*(){return new Promise((t=>setTimeout(t,e)))}));let l=this._controllerUpdates.where((e=>e.UpdateType==bp.RadioUpdate)).toArray(),d=[];this._appStateService.DisallowHibernation();for(let e=0;e<l.length;e++){const t=yield(yield this._updateProviders.GetUpdatesProviderAsync(l[e].ProviderName)).InstallRadioUpdateAsync(l[e],o,n);yield a(5e3),t==ce.OK&&(this._controllerUpdates=this._controllerUpdates.filter((t=>t.UpdateIdentifier!=l[e].UpdateIdentifier))),d.push(t),r[0]++}const h=this._controllerUpdates.find((e=>e.UpdateType==bp.SoftwareUpdate));if(null!=h)if(c<=this._oldUpdateVersion&&u<=this._oldUpdateBuild){const e=yield this.UpdateControllerUsingScriptAsync(h.Update,o);e==ce.OK&&(this._controllerUpdates=this._controllerUpdates.filter((e=>e.UpdateIdentifier!=h.UpdateIdentifier))),d.push(e),r[0]++}else{const e=yield this.UpdateControllerUsingApiAsync(o,t,s);this._appStateService.AllowHibernation(),e==ce.OK&&(this._controllerUpdates=this._controllerUpdates.filter((e=>e.UpdateIdentifier!=n))),d.push(e),r[0]++}const g=d.where((e=>e instanceof De)).toArray();if(null!=g&&0!=g.length){let e="";return g.forEach((t=>e+=`${t.Type}, `)),this._appStateService.AllowHibernation(),new De(Pp.UpdatesPartiallyInstalled,`Update installation finished - not all updates were successfully installed. Installation error codes: ${e}`)}return this._appStateService.AllowHibernation(),ce.OK}{let o;const i=this._controllerUpdates.find((e=>e.UpdateIdentifier==n));if(null==i)return new De(Pp.CannotGetUpdates,`Update with requested guid (${n}) not found.`);switch(this._logger.Debug(`Installing single update type: ${i.Update.UpdateType}, resource: ${i.UpdatedResourceName}, version: ${i.Update.Version}`),this._appStateService.DisallowHibernation(),i.UpdateType){case bp.RadioUpdate:return s?new De(Pp.UpdateAlreadyDownloaded,"Update already downloaded set flag downloadOnly to false to install it."):(o=yield(yield this._updateProviders.GetUpdatesProviderAsync(i.ProviderName)).InstallRadioUpdateAsync(i,e,r),this._appStateService.AllowHibernation(),o==ce.OK&&(this._controllerUpdates=this._controllerUpdates.filter((e=>e.UpdateIdentifier!=n))),o);case bp.SoftwareUpdate:if(c<=this._oldUpdateVersion&&u<=this._oldUpdateBuild){if(s)return new De(Pp.UpdateAlreadyDownloaded,"Update already downloaded set flag downloadOnly to false to install it.");o=yield this.UpdateControllerUsingScriptAsync(i.Update,e),this._appStateService.AllowHibernation(),o==ce.OK&&(this._controllerUpdates=this._controllerUpdates.filter((e=>e.UpdateIdentifier!=n)))}else o=yield this.UpdateControllerUsingApiAsync(e,t,s),this._appStateService.AllowHibernation(),o==ce.OK&&(this._controllerUpdates=this._controllerUpdates.filter((e=>e.UpdateIdentifier!=n)));return o;default:return new De(Pp.CannotProcessUpdate,`Update with type ${i.UpdateType} is not supported by UpdateService.`)}}}))}UpdateControllerUsingScriptAsync(e,t){return Zp(this,void 0,void 0,(function*(){var n,s,r,o,i,a;switch(e.UpdateType){case Er.Container:case Er.ContainerSoftware:try{return yield null===(n=this._connection)||void 0===n?void 0:n.SendAndHandleResponseAsync(new rf(e.DownloadUri),this._updateRequestTimeout,(n=>{const s=new qp;switch(s.UpdatedResourceName=new Map([["pl-PL","Oprogramowanie kontrolera"],["en-US","Controller software"]]),n.Status){case ce.MultiDataResponseStart:s.Status=Np.PreparingForUpgrade;break;case ce.MultiDataResponse:if(null==n.Data)return void this._logger.Warning(ef.ServiceName,`Recived update response without data! URI: ${e.DownloadUri}`);switch(s.Percentage=Math.round(n.Data.Progress),n.Data.State){case Ep.CheckingApplicability:case Ep.CheckingIntegrity:case Ep.CheckingPackageIntegrity:s.Status=Np.CheckingPackage;break;case Ep.CreatingBackup:case Ep.MigratingData:case Ep.Removing:s.Status=Np.MovingData;break;case Ep.Deploying:case Ep.Installing:s.Status=Np.Upgrading;break;case Ep.Downloading:s.Status=Np.DownloadingPackage;break;case Ep.Error:s.Status=Np.Error;break;case Ep.Installed:s.Status=Np.Upgraded;break;case Ep.PreparingSystem:case Ep.ReadyToDownload:s.Status=Np.PreparingForUpgrade;break;case Ep.UndoingInstallation:s.Status=Np.InstallationStopped;break;case Ep.Unpackaging:s.Status=Np.MovingData;break;case Ep.WaitingForUser:s.Status=Np.Upgrading}break;case ce.MultiDataResponseStop:s.Status=Np.OK}t(s)}),!1),ce.OK}catch(e){return new De(Pp.CannotProcessUpdate,`Cannot process update, error: ${e}`)}case Er.RuntimeFixingScript:var c=10;let d="n/a";try{d=(yield this._extensionService.GetExtensionsInfoAsync()).first((e=>"f4f45dac-beda-441a-8d29-efc6dc977cd1"==e.ExtensionGuid)).ExtensionVersion}catch(e){this._logger.Warning(`Cannot get protocol name! error: ${e}`)}var u=d;const h=yield this.getRuntimeInfoAsync();if(h instanceof De)return h;var l=parseFloat(h.RuntimeVersion)>=2||parseFloat(u)>=1.2201125;try{c=(yield Ov.Get(xo.ServiceName).GetDevicesAsync()).length}catch(e){this._logger.Warning(ef.ServiceName,`Cannot get number of devices in system! Error: ${e}. Using default value of 10 devices.`)}if(l){let n,s=new qp;s.UpdatedResourceName=new Map([["pl-PL","Oprogramowanie kontrolera"],["en-US","Controller software"]]),s.Percentage=1,s.Status=Np.PreparingForUpgrade,t(s);let r=2;const o=Date.now(),i=900*c+8e5,a=i/100,u=o+i,l=new Promise(((o,c)=>Zp(this,void 0,void 0,(function*(){var c;try{const l=()=>{if(this._appStateService.OnReturnedFromSuspension().Unsubscribe(l),Date.now()>u)clearInterval(n),this._logger.Debug("Update already finished!"),s.Percentage=100,s.PercentageTotal=Math.round(s.Percentage),s.Status=Np.Upgraded,t(s),o(ce.OK);else{var e=u-Date.now();e<i?r=95-e/a:(clearInterval(n),n=setInterval((()=>{clearInterval(n),s.Percentage=100,s.PercentageTotal=Math.round(s.Percentage),s.Status=Np.Upgraded,t(s),o(ce.OK)}),e))}};this._appStateService.OnReturnedFromSuspension().Subscribe(l),n=setInterval((()=>{if(r>99)clearInterval(n),s.Percentage=100,s.PercentageTotal=Math.round(s.Percentage),s.Status=Np.Upgraded,t(s),o(ce.OK);else{var e=r;e<99&&(s.Percentage=Math.round(e),s.PercentageTotal=Math.round(s.Percentage),s.Status=Np.Upgrading,t(s))}r++}),a);const d=yield null===(c=this._connection)||void 0===c?void 0:c.SendAndWaitForResponseAsync(new of(e.DownloadUri),this._updateRequestTimeout,!1);d.Status!=ce.OK&&(clearInterval(n),s.Percentage=0,s.PercentageTotal=Math.round(s.Percentage),s.Status=Np.InstallationError,t(s),this._logger.Debug(ef.ServiceName,`Update failed with error. Update response status: ${d.Status}`),o(new De(Pp.CannotProcessUpdate,`Update failed with error. Update response status: ${d.Status}`)))}catch(e){this._logger.Debug(ef.ServiceName,`Update failed with error. ${e}`),s.Percentage=0,s.PercentageTotal=Math.round(s.Percentage),s.Status=Np.Error,t(s),clearInterval(n),o(new De(Pp.CannotProcessUpdate,`Update failed with error. ${e}`))}}))));return yield l}{let n=new qp;n.UpdatedResourceName=new Map([["pl-PL","Oprogramowanie kontrolera"],["en-US","Controller software"]]),n.Percentage=1,n.PercentageTotal=Math.round(n.Percentage),n.Status=Np.PreparingForUpgrade,t(n);const u=this._connection.GetAuthorizationInfo();if(null==u)return new De(Pp.CannotProcessUpdate,"Cannot process update. Cannot get current controller login credentials!");if((yield null===(s=this._connection)||void 0===s?void 0:s.SendAndWaitForResponseAsync(new af({Email:"support@support",Password:`support@${u.SerialNumber}:${u.PIN}`}),12e3,!1)).Status===ce.OK){n.Percentage=1,n.PercentageTotal=Math.round(n.Percentage),n.Status=Np.PreparingForUpgrade,t(n);let s=yield null===(r=this._connection)||void 0===r?void 0:r.SendAndWaitForResponseAsync(new cf("rm /runtime/tmp/update.sh"),12e3,!1);if(s.Status==ce.OK){if(this._logger.Debug("Removed previous script"),n.Percentage=2,n.PercentageTotal=Math.round(n.Percentage),n.Status=Np.PreparingForUpgrade,t(n),s=yield null===(o=this._connection)||void 0===o?void 0:o.SendAndWaitForResponseAsync(new cf(`wget ${e.DownloadUri} -O /runtime/tmp/update.sh --no-check-certificate`),this._updateRequestTimeout,!1),s.Status==ce.OK){this._logger.Debug("Downloaded update script"),n.Percentage=5,n.PercentageTotal=Math.round(n.Percentage),n.Status=Np.PreparingForUpgrade,t(n);try{if(s=yield null===(i=this._connection)||void 0===i?void 0:i.SendAndWaitForResponseAsync(new cf("chmod a+x /runtime/tmp/update.sh"),12e3,!1),s.Status==ce.OK){this._logger.Debug("Executed update script"),n.Percentage=5,n.PercentageTotal=Math.round(n.Percentage),n.Status=Np.Upgrading,t(n);let e,s=0;const r=.95,o=Date.now(),i=900*c+15e5,a=i/95,u=o+i,l=new Promise(((o,c)=>Zp(this,void 0,void 0,(function*(){var c;try{const l=()=>{if(this._appStateService.OnReturnedFromSuspension().Unsubscribe(l),Date.now()>u)clearInterval(e),this._logger.Debug("Update already finished!"),n.Percentage=100,n.PercentageTotal=Math.round(n.Percentage),n.Status=Np.Upgraded,t(n),o(ce.OK);else{var r=u-Date.now();r<i?s=95-r/a:(clearInterval(e),e=setInterval((()=>{clearInterval(e),n.Percentage=100,n.PercentageTotal=Math.round(n.Percentage),n.Status=Np.Upgraded,t(n),o(ce.OK)}),r))}};this._appStateService.OnReturnedFromSuspension().Subscribe(l),e=setInterval((()=>{if(s>99)clearInterval(e),n.Percentage=100,n.PercentageTotal=Math.round(n.Percentage),n.Status=Np.Upgraded,t(n),o(ce.OK);else{var i=5+s*r;i<99&&(n.Percentage=Math.round(i),n.PercentageTotal=Math.round(n.Percentage),n.Status=Np.Upgrading,t(n))}s++}),a),null===(c=this._connection)||void 0===c||c.SendAndWaitForResponseAsync(new cf("/runtime/tmp/update.sh"),12e3,!1)}catch(e){o(new De(Pp.CannotProcessUpdate,`Update failed with error. ${e}`))}}))));return yield l}return n.Percentage=0,n.PercentageTotal=Math.round(n.Percentage),n.Status=Np.InstallationError,t(n),new De(Pp.CannotProcessUpdate,"Execution failed!")}catch(e){return null===(a=this._connection)||void 0===a||a.SendAndWaitForResponseAsync(new cf("/runtime/scripts/restart_all.sh"),12e3,!1),new De(Pp.CannotProcessUpdate,`Execution failed! Error ${e}`)}}return new De(Pp.CannotProcessUpdate,"Execution failed! Cannot clear old update script!")}}return new De(Pp.CannotProcessUpdate,"Execution failed! Cannot loggin using support account!")}default:return new De(Pp.CannotProcessUpdate,`Not supported update type, type: ${e.UpdateType}`)}}))}UpdateControllerUsingApiAsync(e,t,n){return Zp(this,void 0,void 0,(function*(){const s=e=>Zp(this,void 0,void 0,(function*(){return new Promise(((s,r)=>Zp(this,void 0,void 0,(function*(){yield this._connection.SendAndHandleResponseAsync(new gf,this._updateRequestTimeout,(r=>{var o,i,a,c;const u=new Vp;switch(u.UpdatedResourceName=ie(e.Update.UpdateName),r.Status){case ce.MultiDataResponseStart:u.Percentage=0,u.SpeedMbps=0,u.PercentageTotal=0,u.CurrentTask=Rp.DownloadingInstaller,t(u);break;case ce.MultiDataResponse:if(null!=r.Data){switch(u.Percentage=r.Data.StepProgressInPercentage,u.SpeedMbps=r.Data.DownloadSpeedInMbs,u.PercentageTotal=n?Math.round(2*(null===(o=r.Data)||void 0===o?void 0:o.UpdateProgressInPercentage)):Math.round(null===(i=r.Data)||void 0===i?void 0:i.UpdateProgressInPercentage),r.Data.UpdateStep){case zp.DownloadingInstaller:u.CurrentTask=Rp.DownloadingInstaller;break;case zp.DownloadingUpdate:u.CurrentTask=Rp.DownloadingUpdate;break;default:u.CurrentTask=Rp.CheckingUpdate}t(u)}break;case ce.MultiDataResponseStop:if(null!=r.Data)switch(r.Data.UpdateStep){case zp.UpdateDownloaded:u.Percentage=100,u.PercentageTotal=n?Math.round(2*(null===(a=r.Data)||void 0===a?void 0:a.UpdateProgressInPercentage)):Math.round(null===(c=r.Data)||void 0===c?void 0:c.UpdateProgressInPercentage),u.SpeedMbps=0,u.CurrentTask=Rp.CheckingUpdate,t(u),s(ce.OK);break;case zp.UpdateDownloadFailed:u.Percentage=0,u.PercentageTotal=0,u.SpeedMbps=0,u.CurrentTask=Rp.Unknown,t(u),s(new De(Pp.UpdateDownloadFailed,"Update download failed!"))}}}),!1)}))))})),r=t=>Zp(this,void 0,void 0,(function*(){return new Promise(((n,s)=>Zp(this,void 0,void 0,(function*(){const s=60*this._updateOfflineStageTime*1e3;let r=0;yield this._connection.SendAndHandleResponseAsync(new pf,this._updateRequestTimeout,(o=>{var i,a;const c=new qp;switch(c.UpdatedResourceName=ie(t.Update.UpdateName),o.Status){case ce.MultiDataResponseStart:c.Status=Np.PreparingForUpgrade,c.Percentage=null===(i=o.Data)||void 0===i?void 0:i.StepProgressInPercentage,c.PercentageTotal=null===(a=o.Data)||void 0===a?void 0:a.UpdateProgressInPercentage,e(c);break;case ce.MultiDataResponse:null!=o.Data&&(c.Status=Np.Upgrading,c.Percentage=Math.round(o.Data.StepProgressInPercentage),c.PercentageTotal=Math.round(o.Data.UpdateProgressInPercentage),r=o.Data.StepProgressInPercentage,e(c));break;case ce.MultiDataResponseStop:if(null!=o.Data)switch(o.Data.UpdateStep){case zp.UpdateInstallationFailed:c.Status=Np.InstallationError,c.Percentage=0,c.PercentageTotal=0,e(c),n(new De(Pp.CannotProcessUpdate,"Update installation failed!"));break;case zp.OfflineUpdateStep:{c.Percentage=Math.round(o.Data.StepProgressInPercentage),c.PercentageTotal=Math.round(o.Data.UpdateProgressInPercentage);let t=(100-c.PercentageTotal)/100,i=c.PercentageTotal;const a=setInterval((()=>{r++,i+=t,i>100&&(i=100),r>=100?(c.Status=Np.Upgraded,c.Percentage=100,c.PercentageTotal=100,e(c),clearInterval(a),n(ce.OK)):(c.Status=Np.Upgrading,c.Percentage=Math.round(r),c.PercentageTotal=Math.round(i),e(c))}),s/(100-r))}}}}),!1)}))))}));if(n){const e=yield this._connection.SendAndWaitForResponseAsync(new df,1e4,!1);if(null==e||(null==e?void 0:e.Status)!=ce.OK||null==(null==e?void 0:e.Data))throw new Error(`Cannot get pending updates! Response is empty or status is not OK. Status: ${null==e?void 0:e.Status}`);switch(e.Data.UpdateStep){case zp.DownloadingInstaller:case zp.DownloadingUpdate:case zp.UpdateDownloaded:return new De(Pp.UpdateAlreadyDownloaded,"Update already downloaded, or download is in progress.");case zp.InstallingUpdate:case zp.PreparingUpdate:return new De(Pp.UpdateAlreadyInstalled,"Update already installed, or installation is in progress.");default:return yield s(e.Data)}}else{const e=yield this._connection.SendAndWaitForResponseAsync(new df,1e4,!1);if(null==e||(null==e?void 0:e.Status)!=ce.OK||null==(null==e?void 0:e.Data))throw new Error(`Cannot get pending updates! Response is empty or status is not OK. Status: ${null==e?void 0:e.Status}`);switch(e.Data.UpdateStep){case zp.DownloadingInstaller:case zp.DownloadingUpdate:return new De(Pp.UpdateAlreadyDownloaded,"Update already downloaded, or donwload in progress.");case zp.InstallingUpdate:case zp.PreparingUpdate:return new De(Pp.UpdateAlreadyInstalled,"Update already installed, or installation in progress.");case zp.UpdateDownloaded:return yield r(e.Data);default:var o=yield s(e.Data);return o!=ce.OK?o:yield r(e.Data)}}}))}getRuntimeInfoAsync(){return Zp(this,void 0,void 0,(function*(){try{return yield this._updateProviders.GetSoftwareRuntimeInfoAsync()}catch(e){return e instanceof no&&e.code==Kr.Timeout?new De(Pp.CannotGetCurrentControllerVersionTimeout,"Cannot get runtime info (current controller version), timeout error - please restart controller to fix issue."):new De(Pp.CannotGetCurrentControllerVersion,`Cannot get runtime info (current controller version), error: ${e}`)}}))}}ef.ServiceName="UpdatesService";class tf{constructor(){this.UpdatedResourceName=new Map,this.CurrentResourceVersion="",this.UpdateType=null,this.ResponseResult=null}}class nf{constructor(){this._updateIdentifier="",this._updateResourceName=new Map,this._updateType=null,this._currentResourceVersion="",this._newResourceVersion="",this._updateDescription=new Map,this._updateIsDownloading=!1,this._updateCheckDownloadProgress=0,this._updateCreationTime=null}get UpdateCreationTime(){return this._updateCreationTime}get DownloadProgress(){return this._updateCheckDownloadProgress}get UpdateDescription(){return this._updateDescription}get UpdateIdentifier(){return this._updateIdentifier}get UpdatedResourceName(){return this._updateResourceName}get UpdateType(){return this._updateType}get CurrentResourceVersion(){return this._currentResourceVersion}get NewResourceVersion(){return this._newResourceVersion}get UpdateIsDownloading(){return this._updateIsDownloading}set UpdateCreationTime(e){this._updateCreationTime=e}set DownloadProgress(e){this._updateCheckDownloadProgress=e}set UpdateDescription(e){this._updateDescription=e}set UpdateIdentifier(e){this._updateIdentifier=e}set UpdatedResourceName(e){this._updateResourceName=e}set UpdateType(e){this._updateType=e}set CurrentResourceVersion(e){this._currentResourceVersion=e}set NewResourceVersion(e){this._newResourceVersion=e}set UpdateIsDownloading(e){this._updateIsDownloading=e}}class sf{constructor(){this._updatedResourceName="",this._updateResourceGuid="",this._protocol="",this._protocolGuid="",this._currentResourceVersion="",this._newResourceVersion="",this._isUpdateSafe=!0,this._updateDescription=new Map}get UpdateDescription(){return this._updateDescription}set UpdateDescription(e){this._updateDescription=e}get UpdatedResourceName(){return this._updatedResourceName}get UpdateResourceGuid(){return this._updateResourceGuid}get Protocol(){return this._protocol}get ProtocolGuid(){return this._protocolGuid}get CurrentResourceVersion(){return this._currentResourceVersion}get NewResourceVersion(){return this._newResourceVersion}get IsUpdateSafe(){return this._isUpdateSafe}set UpdatedResourceName(e){this._updatedResourceName=e}set UpdateResourceGuid(e){this._updateResourceGuid=e}set Protocol(e){this._protocol=e}set ProtocolGuid(e){this._protocolGuid=e}set CurrentResourceVersion(e){this._currentResourceVersion=e}set NewResourceVersion(e){this._newResourceVersion=e}set IsUpdateSafe(e){this._isUpdateSafe=e}}class rf extends ae{constructor(e){super(),this.Resource="/updates/update/from/uri",this.Method=ue.Post,this.Data=e}}!function(e){e[e.Windows=0]="Windows",e[e.Linux=1]="Linux",e[e.Unix=2]="Unix",e[e.OSX=3]="OSX",e[e.Android=4]="Android",e[e.iOS=5]="iOS",e[e.WindowsMobile=6]="WindowsMobile"}(Hp||(Hp={})),function(e){e[e.Any=0]="Any",e[e.MIPS=1]="MIPS",e[e.ARM32=2]="ARM32",e[e.ARM64=3]="ARM64",e[e.IntelX86=4]="IntelX86",e[e.IntelX64=5]="IntelX64"}(jp||(jp={})),function(e){e[e.Unknown=0]="Unknown",e[e.Environment=1]="Environment",e[e.OperatingSystem=2]="OperatingSystem",e[e.Application=3]="Application",e[e.Extension=4]="Extension",e[e.HardwareFirmware=5]="HardwareFirmware",e[e.Script=6]="Script",e[e.Command=7]="Command"}(Kp||(Kp={})),function(e){e[e.InstallerFileSignCheckFailed=-5]="InstallerFileSignCheckFailed",e[e.UpdateFileSignCheckFailed=-4]="UpdateFileSignCheckFailed",e[e.UpdateInstallationFailed=-3]="UpdateInstallationFailed",e[e.UpdateDownloadFailed=-2]="UpdateDownloadFailed",e[e.UpdateFileCheckFailed=-1]="UpdateFileCheckFailed",e[e.Unknown=0]="Unknown",e[e.DownloadingUpdate=1]="DownloadingUpdate",e[e.CheckingUpdate=2]="CheckingUpdate",e[e.PreparingUpdate=3]="PreparingUpdate",e[e.InstallingUpdate=4]="InstallingUpdate",e[e.DownloadingInstaller=5]="DownloadingInstaller",e[e.UpdateDownloaded=6]="UpdateDownloaded",e[e.OfflineUpdateStep=7]="OfflineUpdateStep"}(zp||(zp={}));class of extends ae{constructor(e){super(),this.Resource="/updates/install/from/url",this.Method=ue.Put,this.Data=e}}class af extends ae{constructor(e){super(),this.Resource="/users/user/login",this.Method=ue.Put,this.Data=e}}class cf extends ae{constructor(e){super(),this.Resource="/controller/runtime/execute",this.Method=ue.Post,this.Data=e}}class uf extends ae{constructor(){super(),this.Resource="/updates/branch",this.Method=ue.Get}}class lf extends ae{constructor(e){super(),this.Resource="/updates/branch",this.Method=ue.Put,this.Data=e}}class df extends ae{constructor(){super(),this.Resource="/updates/pending",this.Method=ue.Get}}class hf extends ae{constructor(){super(),this.Resource="/updates/check",this.Method=ue.Get}}class gf extends ae{constructor(){super(),this.Resource="/updates/download",this.Method=ue.Post}}class pf extends ae{constructor(){super(),this.Resource="/updates/install",this.Method=ue.Post}}class ff extends ae{constructor(){super(),this.Resource="/updates/download/automatic/status",this.Method=ue.Get}}class vf extends ae{constructor(){super(),this.Resource="/updates/download/automatic/enable",this.Method=ue.Put}}class mf extends ae{constructor(){super(),this.Resource="/updates/download/automatic/disable",this.Method=ue.Put}}class yf extends ae{constructor(){super(),this.Resource="/updates/history",this.Method=ue.Get}}class wf extends ae{constructor(){super(),this.Resource="/updates/devices/availability",this.Method=ue.Get}}!function(e){e.CannotFindDevice="CannotFindDevice",e.ResponseTypeNotSupported="ResponseTypeNotSupported",e.InvalidChannelNumber="InvalidChannelNumber",e.IncorrectLimitValue="IncorrectLimitValue",e.IncorrectOffsetValue="IncorrectOffsetValue",e.OtherError="OtherError",e.FatalError="FatalError",e.NoData="NoData",e.FunctionalityNotSupported="FunctionalityNotSupported"}(Jp||(Jp={})),function(e){e[e.None=0]="None",e[e.DataRange=1]="DataRange",e[e.Hour=2]="Hour",e[e.Day=3]="Day",e[e.Week=4]="Week",e[e.Month=5]="Month",e[e.Year=6]="Year"}(Yp||(Yp={})),function(e){e.Min="Min",e.Max="Max",e.Avg="Avg"}(Xp||(Xp={}));class Sf{constructor(){this._objectType="Unknown",this._stateInterfaceType="Unknown"}get StateObjectType(){return this._objectType}get StateInterfaceType(){return this._stateInterfaceType}get StateResponseType(){return this._stateInterfaceType}set StateObjectType(e){this._objectType=e}set StateInterfaceType(e){this._stateInterfaceType=e}}!function(e){e[e.Unknown=-1]="Unknown",e[e.PitchBlack=0]="PitchBlack",e[e.VeryDark=1]="VeryDark",e[e.DarkIndoors=2]="DarkIndoors",e[e.DimIndoors=3]="DimIndoors",e[e.NormalIndoors=4]="NormalIndoors",e[e.BrightIndoors=5]="BrightIndoors",e[e.DimOutdoors=6]="DimOutdoors",e[e.CloudyOutdoors=7]="CloudyOutdoors",e[e.DirectSunlight=8]="DirectSunlight"}(Qp||(Qp={}));var Af,_f,Cf,Tf,Df,kf,Gf,bf=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class Nf{constructor(){this._connection=null,this._connection=Ov.Get(Pt.ServiceName)}GetServiceName(){return Nf.ServiceName}GetStatesByIntervalAsync(e,t,n,s,r,o){return bf(this,arguments,void 0,(function*(e,t,n,s,r,o,i=!1){var a;try{if(!(yield this.IsFunctionalitySupportedAsync()))return new De(Jp.FunctionalityNotSupported,"State history data is not supported with this version of controller software, update software to get this functionality.");let c;if("string"==typeof e){const t=yield Ov.Get(xo.ServiceName).GetDevice(e);if(null==t)return new De(Jp.CannotFindDevice,`Device with specified GUID ${e} does not exists.`);c=t}else c=e;if(!c.Channels.any((e=>e.Number==t)))return new De(Jp.InvalidChannelNumber,`Given channel not found in device with guid: ${c.Guid}.`);if(!c.Channels.any((e=>e.Number==t&&e.AvailableResponseTypes.any((e=>e.Type==n)))))return new De(Jp.ResponseTypeNotSupported,"Device or channel not supporting requested DeviceResponseType.");const u=new If;u.DeviceGuid=c.Guid,u.DeviceChannel=t,u.Range=s,u.StateInterfaceType=n,u.ReverseOrder=i,u.Limit=r,u.Offset=o;const l=yield null===(a=this._connection)||void 0===a?void 0:a.SendAndWaitForResponseAsync(new Ef(u),2e4,!1);if(null==l)return new De(Jp.OtherError,"Cannot get state history data - response is null.");switch(l.Status){case ce.WrongData:switch(l.Data){case"IncorrectLimitValue":return new De(Jp.IncorrectLimitValue,"Cannot get state history data - limit value is incorrect!");case"IncorrectOffsetValue":return new De(Jp.IncorrectOffsetValue,"Cannot get state history data - offset value is incorrect!");case"IncorrectArguments":return new De(Jp.OtherError,"Cannot get state history data - some parameters are incorrect!");default:return new De(Jp.OtherError,"Cannot get state history data - unknown error!")}case ce.FatalError:return new De(Jp.FatalError,"Cannot get state history data - an exception occurred in the controller while reading data!");case ce.ResourceDoesNotExists:return new De(Jp.ResponseTypeNotSupported,"Device or channel not supporting requested DeviceResponseType.");case ce.OK:if(null==l.Data)return new De(Jp.NoData,"Controller responede with status OK, but response does not contain data!");if(l.Data.AggregateDataList=l.Data.AggregateDataList.map((e=>(e.AggregateData=ie(e.AggregateData),e))),n===At.MeasuredEnergy){const e=l.Data.Data.map((e=>{const t=e;return t.Values.MeasurementAveragingParameters=ie(e.Values.MeasurementAveragingParameters),t.Values.MeasurementNonAveragingParmeters=ie(e.Values.MeasurementNonAveragingParmeters),t}));return l.Data.Data=e,l.Data}return l.Data;default:return new De(Jp.OtherError,`Cannot get state history data - controller responded with response code ${l.Status}`)}}catch(e){return new De(Jp.FatalError,`Cannot get state history data - exeption occurs! ${e}`)}}))}GetAvailableStatesAsync(){return bf(this,void 0,void 0,(function*(){var e;try{const t=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new Rf,12e3,!1);return null==t?new De(Jp.OtherError,"Cannot get available states - response is null."):t.Status!=ce.OK?new De(Jp.OtherError,`Cannot get available states - controller responded with response code ${t.Status}.`):null==t.Data?new De(Jp.NoData,"Cannot get available states - controller responede with status OK, but response does not contain data!"):t.Data.map((e=>{const t=new Sf;return t.StateInterfaceType=e.StateInterfaceType,t.StateObjectType=e.StateObjectType,t}))}catch(e){return new De(Jp.FatalError,`Cannot get available states - exeption occurs! ${e}`)}}))}IsFunctionalitySupportedAsync(){return bf(this,void 0,void 0,(function*(){return!(parseFloat((yield Ov.Get(Xr.ServiceName).GetSoftwareRuntimeInfoAsync()).SoftwareVersion)<=3.42)}))}GetAvailableStatesPerChannelAsync(e,t){return bf(this,void 0,void 0,(function*(){var n;let s;if("string"==typeof e){const t=yield Ov.Get(xo.ServiceName).GetDevice(e);if(null==t)return new De(Jp.CannotFindDevice,`Device with specified GUID ${e} does not exists.`);s=t}else s=e;const r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new Pf(new Of(s.Guid,t)),8e3,!1);if(null==r)return new De(Jp.OtherError,"Cannot get available states - response is null.");switch(r.Status){case ce.ResourceDoesNotExists:switch(r.Data){case"DeviceNotFound":return new De(Jp.CannotFindDevice,"Cannot get available states - device does not exists!");case"ChannelNotFound":return new De(Jp.InvalidChannelNumber,"Cannot get available states - wrong channel!");default:return new De(Jp.OtherError,"Cannot get available states - unknown error!")}case ce.OK:{if(null==r.Data)return new De(Jp.NoData,"Cannot get available states - controller responede with status OK, but response does not contain data!");const e=r.Data.AvailableStates.map((e=>{const t=new Sf;return t.StateInterfaceType=e.StateInterfaceType,t.StateObjectType=e.StateObjectType,t}));return r.Data.AvailableStates=e,r.Data}default:return new De(Jp.OtherError,`Cannot get available states - controller responded with response code ${r.Status}`)}}))}}Nf.ServiceName="StatesHistoryService";class Ef extends ae{constructor(e){super(),this.Resource="/statehistory/states/get/last",this.Method=ue.Get,this.Data=e}}class If{constructor(){this.DeviceGuid="",this.DeviceChannel=0,this.StateInterfaceType="",this.Range=Yp.Day,this.ReverseOrder=!1,this.Limit=0,this.Offset=0}}class Rf extends ae{constructor(){super(),this.Resource="/statehistory/states/available",this.Method=ue.Get}}class Pf extends ae{constructor(e){super(),this.Resource="/statehistory/states/available/per/channel",this.Method=ue.Get,this.Data=e}}class Of{constructor(e,t){this.DeviceGuid=e,this.Channel=t}}(Gf=Af||(Af={}))[Gf.User=0]="User",Gf[Gf.Controller=1]="Controller",Gf[Gf.Marketing=2]="Marketing",(kf=_f||(_f={}))[kf.Notification=0]="Notification",kf[kf.Message=1]="Message",kf[kf.Alarm=2]="Alarm",kf[kf.Warning=3]="Warning",kf[kf.Info=4]="Info",(Df=Cf||(Cf={}))[Df.Other=0]="Other",Df[Df.UserLoggedIn=1]="UserLoggedIn",Df[Df.UserLoggedOut=2]="UserLoggedOut",Df[Df.FoundNewDevice=3]="FoundNewDevice",Df[Df.DoorBellPress=4]="DoorBellPress",Df[Df.AddedNewDevice=5]="AddedNewDevice",Df[Df.RemovedDevice=6]="RemovedDevice",Df[Df.RegisteredNewUser=7]="RegisteredNewUser",Df[Df.GotAccessToTheInternet=8]="GotAccessToTheInternet",Df[Df.LostAccessToTheInternet=9]="LostAccessToTheInternet",Df[Df.RemovedUser=10]="RemovedUser",Df[Df.NetworkChanged=11]="NetworkChanged",function(e){e.WeatherWidget="WeatherWidget"}(Tf||(Tf={}));var Uf=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class Mf{constructor(){this._chatSubscriptions=[],this._connection=Ov.Get(Pt.ServiceName),this._connection.SubscribeTo("/homemessaging/notify/message/new",(e=>{const t=e.Data;if(null==t.RecipientUserGuid&&t.MessageType==_f.Message)return;const n=new xf;n.DateTime=t.DateTime,n.Guid=t.Guid,n.MessageSource=t.MessageSource,n.MessageText=t.MessageText,n.MessageType=t.MessageType,n.RecipientUserGuid=t.RecipientUserGuid?t.RecipientUserGuid:"n/a",n.Sender=t.Sender,n.SenderName=t.SenderName?t.SenderName:"n/a",n.SenderUserGuid=t.SenderUserGuid?t.SenderUserGuid:"n/a",n.TextToSpeechMessage=t.TextToSpeechMessage?t.TextToSpeechMessage:"";for(let[e,s]of Object.entries(t.MessageActions))n.MessageActions.set(Tf[e],s);for(let[e,s]of Object.entries(t.MessageActionsData))n.MessageActionsData.set(e,s);this._chatSubscriptions.forEach((e=>{e(n)}))}))}GetCachedMessagesAsync(){return Uf(this,void 0,void 0,(function*(){try{const e=yield this._connection.SendAndWaitForResponseAsync(new Ff,12e3,!1);if(null==e)return new De(Jf.OtherError,"Cannot get messages - response is null.");if(e.Status!=ce.OK)return new De(Jf.OtherError,`Cannot get messages - controller responded with response code ${e.Status}.`);if(null==e.Data)return new De(Jf.NoData,"Cannot get messages - controller responded with status OK, but response does not contain data!");const t=[];return e.Data.forEach((e=>{if(null==e.RecipientUserGuid&&e.MessageType==_f.Message)return;const n=new xf;n.DateTime=e.DateTime,n.Guid=e.Guid,n.MessageSource=e.MessageSource,n.MessageText=e.MessageText,n.MessageType=e.MessageType,n.RecipientUserGuid=e.RecipientUserGuid?e.RecipientUserGuid:"n/a",n.Sender=e.Sender,n.SenderName=e.SenderName?e.SenderName:"n/a",n.SenderUserGuid=e.SenderUserGuid?e.SenderUserGuid:"n/a",n.TextToSpeechMessage=e.TextToSpeechMessage?e.TextToSpeechMessage:"";for(let[t,s]of Object.entries(e.MessageActions))n.MessageActions.set(Tf[t],s);for(let[t,s]of Object.entries(e.MessageActionsData))n.MessageActionsData.set(t,s);t.push(n)})),t}catch(e){return new De(Jf.FatalError,`Cannot get messages - exception occurred ${e}`)}}))}SendMessageAsync(e){return Uf(this,void 0,void 0,(function*(){try{const t=yield this._connection.SendAndWaitForResponseAsync(new Lf(`recipient:home ${e}`),8e3,!1);return null==t||null==t.Status?ce.FatalError:t.Status}catch(e){return Ov.Get(s.ServiceName).Error(sv.ServiceName,`Cannot send message! ${e}`),ce.FatalError}}))}SubscribeToMessages(e){this._chatSubscriptions.push(e)}UnsubscribeFromMessages(e){this._chatSubscriptions&&(this._chatSubscriptions=this._chatSubscriptions.filter((t=>t!==e)))}}class xf{constructor(){this._sender=Af.Controller,this._messageType=_f.Info,this._messageSource=Cf.Other,this._senderUserGuid="",this._recipientUserGuid="",this._textToSpeechMessage="",this._messageActions=new Map,this._messageActionsData=new Map,this._guid="",this._senderName="",this._messageText="",this._dateTime=(new Date).toDateString()}get Sender(){return this._sender}get MessageType(){return this._messageType}get MessageSource(){return this._messageSource}get SenderUserGuid(){return this._senderUserGuid}get RecipientUserGuid(){return this._recipientUserGuid}get TextToSpeechMessage(){return this._textToSpeechMessage}get MessageActions(){return this._messageActions}get MessageActionsData(){return this._messageActionsData}get Guid(){return this._guid}get SenderName(){return this._senderName}get MessageText(){return this._messageText}get DateTime(){return this._dateTime}set Sender(e){this._sender=e}set MessageType(e){this._messageType=e}set MessageSource(e){this._messageSource=e}set SenderUserGuid(e){this._senderUserGuid=e}set RecipientUserGuid(e){this._recipientUserGuid=e}set TextToSpeechMessage(e){this._textToSpeechMessage=e}set MessageActions(e){this._messageActions=e}set MessageActionsData(e){this._messageActionsData=e}set Guid(e){this._guid=e}set SenderName(e){this._senderName=e}set MessageText(e){this._messageText=e}set DateTime(e){this._dateTime=e}}class Ff extends ae{constructor(){super(),this.Resource="/homemessaging/messages",this.Method=ue.Get}}class Lf extends ae{constructor(e){super(),this.Resource="/homemessaging/message",this.Method=ue.Put,this.Data=e}}var Bf,Wf,$f,qf=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class Vf{constructor(){this._chatSubscriptions=[],this._connection=Ov.Get(Pt.ServiceName),this._connection.SubscribeTo("/homemessaging/notify/message/new",(e=>{if("/homemessaging/notify/message/new"===e.Resource){const t=e.Data;if(null==t.RecipientUserGuid&&t.MessageType==_f.Message){const e=new Hf;e.DateTime=t.DateTime,e.Guid=t.Guid,e.MessageText=t.MessageText,e.SenderName=t.SenderName?t.SenderName:"n/a",this._chatSubscriptions.forEach((t=>{t(e)}))}}}))}GetCachedMessagesAsync(){return qf(this,void 0,void 0,(function*(){try{const e=yield this._connection.SendAndWaitForResponseAsync(new Kf,12e3,!1);if(null==e)return new De(Jf.OtherError,"Cannot get messages - response is null.");if(e.Status!=ce.OK)return new De(Jf.OtherError,`Cannot get messages - controller responded with response code ${e.Status}.`);if(null==e.Data)return new De(Jf.NoData,"Cannot get messages - controller responded with status OK, but response does not contain data!");const t=[];return e.Data.forEach((e=>{if(null==e.RecipientUserGuid&&e.MessageType==_f.Message){const n=new Hf;n.DateTime=e.DateTime,n.Guid=e.Guid,n.MessageText=e.MessageText,n.SenderName=e.SenderName?e.SenderName:"n/a",t.push(n)}})),t}catch(e){return new De(Jf.FatalError,`Cannot get messages - exception occurred ${e}`)}}))}SendMessageAsync(e){return qf(this,void 0,void 0,(function*(){try{const t=yield this._connection.SendAndWaitForResponseAsync(new jf(e),8e3,!1);return null==t||null==t.Status?ce.FatalError:t.Status}catch(e){return Ov.Get(s.ServiceName).Error(sv.ServiceName,`Cannot send message! ${e}`),ce.FatalError}}))}SubscribeToMessages(e){this._chatSubscriptions.push(e)}UnsubscribeFromMessages(e){this._chatSubscriptions&&(this._chatSubscriptions=this._chatSubscriptions.filter((t=>t!==e)))}}class Hf{constructor(){this._guid="",this._senderName="",this._messageText="",this._dateTime=""}get Guid(){return this._guid}get SenderName(){return this._senderName}get MessageText(){return this._messageText}get DateTime(){return this._dateTime}set Guid(e){this._guid=e}set SenderName(e){this._senderName=e}set MessageText(e){this._messageText=e}set DateTime(e){this._dateTime=e}}class jf extends ae{constructor(e){super(),this.Resource="/homemessaging/message",this.Method=ue.Put,this.Data=e}}class Kf extends ae{constructor(){super(),this.Resource="/homemessaging/messages",this.Method=ue.Get}}!function(e){e[e.None=0]="None",e[e.ChangeDeviceState=1]="ChangeDeviceState"}(Bf||(Bf={})),function(e){e.GPT3_5_TURBO="gpt-3.5-turbo",e.GPT3_5_TURBO_16K="gpt-3.5-turbo-16k",e.GPT4="gpt-4"}(Wf||(Wf={})),function(e){e[e.UnknownError=0]="UnknownError",e[e.ChatNotConfigured=1]="ChatNotConfigured",e[e.MessageNotSend=2]="MessageNotSend",e[e.InvalidMessageResponseFormat=3]="InvalidMessageResponseFormat"}($f||($f={}));var zf,Jf,Yf,Xf=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class Qf{constructor(){this._chatSubscriptions=[],this._connection=Ov.Get(Pt.ServiceName),this._connection.SubscribeTo("/homemessaging/gpt/notify/message/new",(e=>{const t=e.Data,n=new nv;if(n.DateTime=t.DateTime,n.Guid=t.Guid,n.MessageText=t.MessageText?t.MessageText:"",n.SenderName=t.SenderName?t.SenderName:"n/a",null!=t.ControllerActivities)for(let[e,s]of Object.entries(t.ControllerActivities)){const t=Bf[e],r=new Map;for(let[e,t]of Object.entries(s))r.set(e,t);n.ControllerActivities.set(t,r)}if(null!=t.Errors)for(let[e,s]of Object.entries(t.Errors))n.Errors.set($f[e],s);this._chatSubscriptions.forEach((e=>{e(n)}))}))}IsGptChatAvailableAsync(){return Xf(this,void 0,void 0,(function*(){return(yield Ov.Get(Ze.ServiceName).GetExtensionsInfoAsync()).any((e=>"80daeab9-104f-4c1b-9464-61f5fc9bf2bf"==e.ExtensionGuid))}))}GetChatConfigurationAsync(){return Xf(this,void 0,void 0,(function*(){try{const e=yield this._connection.SendAndWaitForResponseAsync(new ev,8e3,!1);return null==e||null==e.Status?new De(Jf.FatalError,"Cannot get chat configuration! No data in result"):e.Status!=ce.OK?new De(Jf.Error,`Cannot get chat configuration! Controller responded with code: ${e.Status}`):null==e.Data?new De(Jf.NoData,"Cannot get chat configuration! Controller responded with success, but no data in response!"):e.Data}catch(e){return new De(Jf.FatalError,`Cannot get chat configuration! ${e}`)}}))}SetChatConfigurationAsync(e){return Xf(this,void 0,void 0,(function*(){try{const t=yield this._connection.SendAndWaitForResponseAsync(new tv(e),8e3,!1);return null==t||null==t.Status?ce.FatalError:t.Status}catch(e){return Ov.Get(s.ServiceName).Error(sv.ServiceName,`Cannot set chat configuration! ${e}`),ce.FatalError}}))}SendMessageAsync(e){return Xf(this,void 0,void 0,(function*(){try{const t=yield this._connection.SendAndWaitForResponseAsync(new Zf(e),8e3,!1);return null==t||null==t.Status?ce.FatalError:t.Status}catch(e){return Ov.Get(s.ServiceName).Error(sv.ServiceName,`Cannot send message! ${e}`),ce.FatalError}}))}SubscribeToMessages(e){var t;null===(t=this._chatSubscriptions)||void 0===t||t.push(e)}UnsubscribeFromMessages(e){this._chatSubscriptions&&(this._chatSubscriptions=this._chatSubscriptions.filter((t=>t!==e)))}}class Zf extends ae{constructor(e){super(),this.Resource="/homemessaging/gpt/message",this.Method=ue.Put,this.Data=e}}class ev extends ae{constructor(){super(),this.Resource="/homemessaging/gpt/configuration",this.Method=ue.Get}}class tv extends ae{constructor(e){super(),this.Resource="/homemessaging/gpt/configuration",this.Method=ue.Put,this.Data=e}}class nv{constructor(){this._messageActions=new Map,this._errors=new Map,this._guid="",this._senderName="",this._messageText="",this._dateTime=""}get ControllerActivities(){return this._messageActions}get Errors(){return this._errors}get Guid(){return this._guid}get SenderName(){return this._senderName}get MessageText(){return this._messageText}get DateTime(){return this._dateTime}set ControllerActivities(e){this._messageActions=e}set Errors(e){this._errors=e}set Guid(e){this._guid=e}set SenderName(e){this._senderName=e}set MessageText(e){this._messageText=e}set DateTime(e){this._dateTime=e}}!function(e){e[e.ControllerChat=0]="ControllerChat",e[e.FamilyChat=1]="FamilyChat",e[e.GptChat=2]="GptChat"}(zf||(zf={}));class sv{constructor(){this._services={ControllerChat:new Mf,GptChat:new Qf,FamillyChat:new Vf}}GetServiceName(){return sv.ServiceName}GetChatImplementation(e){switch(e){case zf.ControllerChat:return this._services.ControllerChat;case zf.FamilyChat:return this._services.FamillyChat;case zf.GptChat:return this._services.GptChat;default:throw new rv(`Chat with type ${e} not implemented!`)}}}sv.ServiceName="ChatService",function(e){e.OtherError="OtherError",e.FatalError="FatalError",e.Error="Error",e.NoData="NoData"}(Jf||(Jf={}));class rv extends Error{constructor(e){super(e),this.message=e,this.name="ChatNotImplementedException"}}!function(e){e[e.ResourceIsNotAvailable=-11]="ResourceIsNotAvailable",e[e.AnotherAppWithGivenAccessTokenAlreadyExists=-10]="AnotherAppWithGivenAccessTokenAlreadyExists",e[e.AppGuidDoesNotExists=-7]="AppGuidDoesNotExists",e[e.AppUrlToShort=-6]="AppUrlToShort",e[e.AppUserNameToShort=-5]="AppUserNameToShort",e[e.AppUserIdToShort=-4]="AppUserIdToShort",e[e.AccessTokenToShort=-3]="AccessTokenToShort",e[e.AppNameToShort=-2]="AppNameToShort",e[e.UnkownError=0]="UnkownError",e[e.Changed=1]="Changed"}(Yf||(Yf={}));var ov=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class iv{constructor(){this._connection=Ov.Get(Pt.ServiceName),this._log=Ov.Get(s.ServiceName)}GetServiceName(){return iv.ServiceName}IsSupportedAsync(){return ov(this,void 0,void 0,(function*(){let e=yield this._connection.SendAndWaitForResponseAsync(new av,2e3,!0);return this._log.Debug(iv.ServiceName,`IsSupportedAsync: ${null==e?void 0:e.Status} resp: ${JSON.stringify(e)}`),null!=e&&e.Status==ce.WrongData}))}GetConnectedAppsAsync(){return ov(this,void 0,void 0,(function*(){let e=yield this._connection.SendAndWaitForResponseAsync(new cv,2e3,!0);return(null==e?void 0:e.Status)===ce.OK?null==e?void 0:e.Data:null==e?void 0:e.Status}))}UpsertConnectedAppAsync(e){return ov(this,void 0,void 0,(function*(){let t=yield this._connection.SendAndWaitForResponseAsync(new lv(e),2e3,!1);switch(null==t?void 0:t.Status){case ce.OK:return new De(Yf.Changed,"");case ce.WrongData:switch(t.Data){case"AccessTokenToShort":return new De(Yf.AccessTokenToShort,t.Data);case"AnotherAppWithGivenAccessTokenAlreadyExists":return new De(Yf.AnotherAppWithGivenAccessTokenAlreadyExists,t.Data);case"AppGuidDoesNotExists":return new De(Yf.AppGuidDoesNotExists,t.Data);case"AppNameToShort":return new De(Yf.AppNameToShort,t.Data);case"AppUrlToShort":return new De(Yf.AppUrlToShort,t.Data);case"AppUserIdToShort":return new De(Yf.AppUserIdToShort,t.Data);case"AppUserNameToShort":return new De(Yf.AppUserNameToShort,t.Data);default:return new De(Yf.UnkownError,t.Data)}case ce.ResourceDoesNotExists:case ce.ResourceIsNotAvailable:return new De(Yf.ResourceIsNotAvailable,t.Data);default:return new De(Yf.UnkownError,t.Data)}}))}RemoveConnectedAppAsync(e){return ov(this,void 0,void 0,(function*(){let t=yield this._connection.SendAndWaitForResponseAsync(new uv(e.Guid),2e3,!0);return null==t?void 0:t.Status}))}}iv.ServiceName="ConnectedAppsService";class av extends ae{constructor(){super(),this.Resource="/applications/app/auth",this.Method=ue.Put,this.Data=""}}class cv extends ae{constructor(){super(),this.Resource="/applications/get",this.Method=ue.Get}}class uv extends ae{constructor(e){super(),this.Resource="/applications/app/delete",this.Method=ue.Delete,this.Data=e}}class lv extends ae{constructor(e){super(),this.Resource="/applications/app/upsert",this.Method=ue.Put,this.Data=e}}var dv=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class hv{constructor(){try{const e=window.location.href,t=new URL(e),n=new URLSearchParams(t.search),s=n.get("mig_c_enc"),r=n.get("mig_controllers"),o=n.get("mig_lang");if(null!==s){const e=decodeURIComponent(this.b64DecodeUnicode(decodeURIComponent(s)));localStorage.setItem(hv.AppUserControllersKeyName,e)}null!==r&&localStorage.setItem(hv.AppUserControllersKeyName,decodeURIComponent(r)),null!==o&&localStorage.setItem(hv.AppSelectedLanguageKeyName,o)}catch(e){console.error(e)}}waitForNavigatorObject(e){return new Promise(((t,n)=>{setTimeout((()=>{n(new Error(`Timed out waiting for navigator.${e}`))}),1e4),function n(){navigator[e]?t(navigator[e]):requestAnimationFrame(n)}()}))}b64DecodeUnicode(e){return decodeURIComponent(Array.prototype.map.call(atob(e),(function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)})).join(""))}decodeUriJsonData(e){return JSON.parse(decodeURIComponent(e))}encodeUriJsonData(e){return encodeURIComponent(JSON.stringify(e))}IsExalusNativeMigrationAvailable(){return void 0!==navigator.exalusMigration}GetServiceName(){return hv.ServiceName}IsMigrationDataAvailableAsync(){return dv(this,void 0,void 0,(function*(){try{if(null!=window.webkit&&null!=window.webkit.messageHandlers){var e=yield hv.GetIosMigrationStatus();return null!==e&&e}if(!navigator.userAgent.endsWith("LavvaAndroidNative")||void 0!==navigator.exalusMigration&&null!==navigator.exalusMigration||(yield this.waitForNavigatorObject("exalusMigration")),this.IsExalusNativeMigrationAvailable()){let e=yield navigator.exalusMigration.IsMigrationDataAvailableAsync();return null!=e&&e.DataMigrated}return null!==localStorage.getItem(hv.AppSelectedLanguageKeyName)||null!==localStorage.getItem(hv.AppUserControllersKeyName)}catch(e){return console.error(e),!1}}))}GetControllersDataAsync(){return dv(this,void 0,void 0,(function*(){try{if(null!=window.webkit&&null!=window.webkit.messageHandlers){let e=yield hv.GetIosControllerList();return void 0===e?null:e}{if(this.IsExalusNativeMigrationAvailable()){let e=yield navigator.exalusMigration.GetControllersDataAsync();return void 0===e?null:e}let e=localStorage.getItem(hv.AppUserControllersKeyName);return null!==e?JSON.parse(e):null}}catch(e){return console.error(e),null}}))}GetLanguageCodeAsync(){return dv(this,void 0,void 0,(function*(){try{if(null!=window.webkit&&null!=window.webkit.messageHandlers){let e=yield hv.GetIosDefaultLanguage();return void 0===e?null:e}{if(this.IsExalusNativeMigrationAvailable()){let e=yield navigator.exalusMigration.GetLanguageCodeAsync();return void 0===e?null:e}let e=localStorage.getItem(hv.AppSelectedLanguageKeyName);return null!=e?e:null}}catch(e){return console.error(e),null}}))}static GetIosMigrationStatus(e=8e3){let t;return new Promise(((n,s)=>{t=setTimeout((()=>{s(null)}),e);try{window.nativeEvent.exalusControllerData.isMigrationAvaliable=e=>{clearTimeout(t),n(e)},window.webkit.messageHandlers.exalusControllerData.postMessage("IsMigrationAvaliable")}catch(e){s(e)}}))}static GetIosControllerList(e=8e3){let t;return new Promise(((n,s)=>{t=setTimeout((()=>{s(null)}),e);try{window.nativeEvent.exalusControllerData.handleControllers=e=>{clearTimeout(t),n(e)},window.webkit.messageHandlers.exalusControllerData.postMessage("GetControllers")}catch(e){s(e)}}))}static GetIosDefaultLanguage(e=8e3){let t;return new Promise(((n,s)=>{t=setTimeout((()=>{s(null)}),e);try{window.nativeEvent.exalusControllerData.handleLanguage=e=>{clearTimeout(t),n(e)},window.webkit.messageHandlers.exalusControllerData.postMessage("GetDefaultLanguage")}catch(e){s(e)}}))}}hv.AppSelectedLanguageKeyName="App___SelectedLanguage",hv.AppUserControllersKeyName="App___UserControllersListDatabase",hv.ServiceName="DataMigrationService";var gv=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class pv{constructor(){this._localIpAddress=null,this._publicIpAddress=null,this._gatewayIpAddress=null,this._macAddress=null,this._isInLocalNetwork=!1,this.nativeFindControllerApi=null,void 0!==navigator.findEfcController&&(this.nativeFindControllerApi=navigator.findEfcController),this._connection=Ov.Get(Pt.ServiceName),this._logger=Ov.Get(s.ServiceName),this._storage=Ov.Get(o.ServiceName),Ov.Get(Ke.ServiceName).OnUserLoggedInEvent().Subscribe((e=>gv(this,void 0,void 0,(function*(){var e;try{const t=yield this.GetControllerNetworkConfigurationAsync();if(null!=t){this._localIpAddress=t.LocalIPv4,this._publicIpAddress=t.PublicIPv4,this._gatewayIpAddress=t.GatewayIPv4,this._macAddress=t.MAC,this._storage.Save(pv.ServiceName,"LocalIpAddress",this._localIpAddress);const n=this.GetControllerHostName(this._connection.GetControllerSerialNumber());this._logger.Debug(`Looking for controller in local network with host name: ${n}`);let s=null;this.isIos()?s=yield this.getIosControllerIpAsync(n):null!==this.nativeFindControllerApi&&(s=yield null===(e=this.nativeFindControllerApi)||void 0===e?void 0:e.FindControllerAsync(n)),null!=s&&""!=s?(this._isInLocalNetwork=!0,this._logger.Debug(pv.ServiceName,`Controller found in local network with ip address: ${s}`)):(this._isInLocalNetwork=!1,this._logger.Debug(pv.ServiceName,"Controller not found in local network."))}else this._logger.Error(pv.ServiceName,"Failed to get network configuration data.")}catch(e){this._logger.Error(pv.ServiceName,`Failed to get network configuration data - ${e}`)}}))))}FindControllerInLocalNetworkAsync(e){return gv(this,void 0,void 0,(function*(){if(this.isIos()){const t=yield this.getIosControllerIpAsync(e);return""==t?null:t}return null!==this.nativeFindControllerApi?this.nativeFindControllerApi.FindControllerAsync(e):Promise.resolve(null)}))}GetLastKnownControllerLocalIpAddress(){return null!==this._localIpAddress?this._localIpAddress:this._storage.Read(pv.ServiceName,"LocalIpAddress")}GetControllerHostName(e){return`ExalusTR7-${e}`}GetMdnsHostName(){return`ExalusTR7-${this.GetControllerHostName(this._connection.GetControllerSerialNumber())}.local`.toLowerCase()}GetControllerNetworkConfigurationAsync(){return gv(this,void 0,void 0,(function*(){var e;const t=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new fv,2e4,!1);return null==t||null==t.Status||null==t.Data?(this._logger.Error(pv.ServiceName,"Failed to get network configuration data - unknow error."),null):t.Data}))}GetServiceName(){return pv.ServiceName}isIos(){return null!=window.webkit&&null!=window.webkit.messageHandlers}getIosControllerIpAsync(e,t=2e4){let n;return new Promise(((s,r)=>{n=setTimeout((()=>{this._logger.Error("Cannot find controller in local network, timeout!"),s("")}),t);try{window.nativeEvent.exalusFindController.handleFindController=e=>{clearTimeout(n),s(e)},window.webkit.messageHandlers.exalusFindController.postMessage(e)}catch(e){this._logger.Error(`Cannot find controller in local network, error: ${e}`),s("")}}))}}pv.ServiceName="FindControllerService";class fv extends ae{constructor(){super(),this.Resource="/network/lan/",this.Method=ue.Get}}var vv=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class mv{constructor(){this._errorOccuredEvent=new n,this._connectionStateChangedEvent=new n,this._dataReceivedEvent=new n,this._onMessageReceived=new n,this._log=Ov.Get(s.ServiceName),this._controllerConfiguration=null,this._cache=null,this._session=null,this._logPackets=!1,this.sockets=null,this._address=null,this._port="81",this._isOpen=!1,this._pin=null,this._serial=null,this._auth=null,this._initialized=!1}Initialize(){this._initialized||(this._initialized=!0,this._controllerConfiguration=Ov.Get(rt.ServiceName),this._cache=Ov.Get(Ge.ServiceName),this._session=Ov.Get(Ke.ServiceName))}checkIfAuthInfoIsCorrectAsync(e){return vv(this,void 0,void 0,(function*(){const t=`http://${window.location.hostname}/controller_info`;let n=yield fetch(t,{method:"GET"});return!!n.ok&&(yield n.text())===`${e.SerialNumber}:${e.PIN}`}))}SubscribeTo(e,t){let n=n=>{n.Resource===e&&t(n)};return this.OnDataReceivedEvent().Subscribe(n),()=>this.OnDataReceivedEvent().Unsubscribe(n)}SetServersBrokerAddress(e){throw new Error("Method not implemented.")}SetDefaultPacketsBrokerAddress(e){throw new Error("Method not implemented.")}GetServerAddressAsync(){return Ov.IsRunningFromLocalNetwork()&&(this._address=`${window.location.hostname}:${this._port}`),Promise.resolve(this._address)}ConnectAsync(e){var t;return this.Initialize(),null===(t=this.sockets)||void 0===t||t.close(),this.sockets=new WebSocket(`ws://${e}/api`),this._log.Debug(mv.ServiceName,`Connecting to the WebSockets server ${e}`),this.sockets.onerror=t=>{this._log.Debug(mv.ServiceName,`Error occured in the WebSockets server ${e}: ${t}`),this._errorOccuredEvent.Invoke(["WebSockets",t.toString()])},this.sockets.onopen=t=>{this._log.Debug(mv.ServiceName,`Connected to the WebSockets server ${e}`),this._isOpen=!0,this._connectionStateChangedEvent.Invoke(he.Connected)},this.sockets.onclose=t=>{this._log.Debug(mv.ServiceName,`Disconnected from the WebSockets server ${e}`),this._isOpen=!1,this._connectionStateChangedEvent.Invoke(he.Disconnected)},this.sockets.onmessage=t=>{this._log.Debug(mv.ServiceName,`Message received from the WebSockets server ${e}: ${t.data}`),this._onMessageReceived.Invoke(t.data);let n=JSON.parse(t.data);this._log.Debug(mv.ServiceName,`Received data frame: ${n.Status}`),this._dataReceivedEvent.Invoke(n)},this._connectionStateChangedEvent.Invoke(he.Connecting),Promise.resolve(de.Connected)}AuthorizeAsync(e){return vv(this,void 0,void 0,(function*(){return!!(yield this.checkIfAuthInfoIsCorrectAsync(e))&&(this._log.Debug(mv.ServiceName,`Authorization successful for controller ${e.SerialNumber}`),this._pin=e.PIN,this._serial=e.SerialNumber,this._auth=e,!0)}))}ConnectAndAuthorizeAsync(e){return vv(this,void 0,void 0,(function*(){if(this._log.Debug(mv.ServiceName,`Connecting and authorizing to the controller ${e.SerialNumber}`),!(yield this.AuthorizeAsync(e)))return de.AuthorizationFailed;let t=yield this.GetServerAddressAsync();return null==t?de.FailedToConnectToServer:yield this.ConnectAsync(t)}))}DisconnectAsync(){var e;return this._log.Debug(mv.ServiceName,`Disconnecting from the WebSockets server ${this._address}`),this._connectionStateChangedEvent.Invoke(he.Disconnecting),null===(e=this.sockets)||void 0===e||e.close(),Promise.resolve()}IsConnected(){return this._isOpen}EnablePacketsLogging(){this._log.Debug(mv.ServiceName,"Packets logging enabled"),this._logPackets=!0}DisablePacketsLogging(){this._log.Debug(mv.ServiceName,"Packets logging disabled"),this._logPackets=!1}SendData(e,t){var n;let s=JSON.stringify(e);return t&&this._log.Debug(mv.ServiceName,`Sending data frame: ${s}`),this._isOpen?null===(n=this.sockets)||void 0===n||n.send(s):this._log.Error(mv.ServiceName,`Failed to send data frame: ${s}`),Promise.resolve(this._isOpen)}SendAsync(e){return this._isOpen&&this.SendData(e,this._logPackets),Promise.resolve(this._isOpen)}SendAndWaitForResponseAsync(e,t,n,s=!0){return this.SendAndWaitForResponseWithRepeatAsync(e,t,n,s)}SendAndHandleResponseAsync(e,t,n,s){return vv(this,void 0,void 0,(function*(){var r;let o=0;const i=Date.now();if(!this.IsConnected())throw new Error("Connection is not established");return"/users/user/login"!==e.Resource&&(yield null===(r=this._session)||void 0===r?void 0:r.WaitForSessionCreationAsync()),new Promise(((r,a)=>vv(this,void 0,void 0,(function*(){const c=()=>window.setTimeout((()=>{this._dataReceivedEvent.Unsubscribe(u);let t=`Response timeout, resource: ${e.Resource} method: ${e.Method} transaction id: ${e.TransactionId}`;this._log.Error(mv.ServiceName,t),a(new Error(t))}),t);let u=l=>vv(this,void 0,void 0,(function*(){var d,h,g;if((null==l?void 0:l.TransactionId)==e.TransactionId){window.clearTimeout(o);const p=Date.now()-i;switch((s||!0===window.packets)&&this._log.Debug(mv.ServiceName,`Received response for: ${null==l?void 0:l.Resource} ${null==l?void 0:l.Method} id: ${null==l?void 0:l.TransactionId} in ${p}ms`),(null==l?void 0:l.Status)===ce.UserIsNotLoggedIn&&(this._dataReceivedEvent.Unsubscribe(u),(null===(d=this._session)||void 0===d?void 0:d.OnUserLoggedOutEvent()).Invoke(null===(h=this._session)||void 0===h?void 0:h.User),yield null===(g=this._session)||void 0===g?void 0:g.RestoreSessionAsync(),r(yield this.SendAndHandleResponseAsync(e,t,n,s))),null==l?void 0:l.Status){case ce.MultiDataResponseStart:case ce.MultiDataResponse:n(l),o=c();break;case ce.MultiDataResponseStop:n(l),this._dataReceivedEvent.Unsubscribe(u),r();break;default:let t=`Failed to process MultiDataResponse - recived incorrect response status: ${null==l?void 0:l.Status} method: ${e.Method} transaction id: ${e.TransactionId}\n make sure that the requested endpoint uses MultiDataResponse, otherwise use SendAndWaitForResponseAsync<T> method.`;a(new Error(t))}}}));if(this._dataReceivedEvent.Subscribe(u),o=c(),!this.SendData(e,s)){let t=`Failed to send request, resource: ${e.Resource} method: ${e.Method} transaction id: ${e.TransactionId}`;a(new Error(t))}}))))}))}SendAndWaitForResponseWithRepeatAsync(e,t,n){return vv(this,arguments,void 0,(function*(e,t,n,s=!0,r=!0){var o,i,a;if(e.Method===ue.Get&&n&&!(yield null===(o=this._controllerConfiguration)||void 0===o?void 0:o.DidCofigurationChangeAsync())){let t=null===(i=this._cache)||void 0===i?void 0:i.GetCache(e);if(null!==t)return Promise.resolve(t)}let c=0;const u=Date.now();if(!this.IsConnected())throw new Error("Connection is not established");return"/users/user/login"!==e.Resource&&(yield null===(a=this._session)||void 0===a?void 0:a.WaitForSessionCreationAsync()),new Promise(((o,i)=>vv(this,void 0,void 0,(function*(){let a=i=>vv(this,void 0,void 0,(function*(){var l,d,h,g;if((null==i?void 0:i.TransactionId)==e.TransactionId){window.clearTimeout(c),this._dataReceivedEvent.Unsubscribe(a);const p=Date.now()-u;r&&this._log.Debug(mv.ServiceName,`Received response for: ${null==i?void 0:i.Resource} ${null==i?void 0:i.Method} id: ${null==i?void 0:i.TransactionId} in ${p}ms`),e.Method===ue.Get&&n&&(null===(l=this._cache)||void 0===l||l.Cache(i)),!n&&(null==i?void 0:i.Status)===ce.UserIsNotLoggedIn&&s&&((null===(d=this._session)||void 0===d?void 0:d.OnUserLoggedOutEvent()).Invoke(null===(h=this._session)||void 0===h?void 0:h.User),yield null===(g=this._session)||void 0===g?void 0:g.RestoreSessionAsync(),o(yield this.SendAndWaitForResponseWithRepeatAsync(e,t,n,!1,r))),o(i)}}));if(this._dataReceivedEvent.Subscribe(a),c=window.setTimeout((()=>{this._dataReceivedEvent.Unsubscribe(a);let t=`Response timeout, resource: ${e.Resource} method: ${e.Method} transaction id: ${e.TransactionId}`;this._log.Error(mv.ServiceName,t),i(new Error(t))}),t),!this.SendData(e,r)){let t=`Failed to send request, resource: ${e.Resource} method: ${e.Method} transaction id: ${e.TransactionId}`;i(new Error(t))}}))))}))}OnDataReceivedEvent(){return this._dataReceivedEvent}OnErrorOccuredEvent(){return this._errorOccuredEvent}OnConnectionStateChangedEvent(){return this._connectionStateChangedEvent}GetAuthorizationInfo(){return this._auth}GetServiceName(){return mv.ServiceName}}mv.ServiceName="ExalusConnectionService";class yv{constructor(){var e,t;this.OnEnteredPictureInPicture=new Ce,this.OnExitedPictureInPicture=new Ce,this._nativeApi=null,this.IsSupported()?(this._nativeApi=navigator.pip,null===(e=this._nativeApi)||void 0===e||e.OnEnteredPictureInPicture.Subscribe((()=>this.OnEnteredPictureInPicture.Invoke())),null===(t=this._nativeApi)||void 0===t||t.OnExitedPictureInPicture.Subscribe((()=>this.OnExitedPictureInPicture.Invoke()))):navigator.pip=null}IsSupported(){return void 0!==navigator.pip&&null!==navigator.pip}RequestPictureInPictureAsync(){return this.IsSupported()?this._nativeApi.RequestPictureInPictureAsync():Promise.resolve(!1)}GetServiceName(){return yv.ServiceName}}yv.ServiceName="PictureInPictureService";var wv,Sv,Av;class _v{GetServiceName(){return _v.ServiceName}GetSupportedDevicesAsync(){return e=this,t=void 0,s=function*(){let e=yield fetch("https://updates.tr7.pl/supportedDevices/pl-PL.json",{method:"GET"});if(e.ok)return JSON.parse(yield e.text());throw new Error("Failed to download supported devices list!")},new((n=void 0)||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}));var e,t,n,s}}_v.ServiceName="SupportedDevicesService",(Av=wv||(wv={}))[Av.Unknown=-1]="Unknown",Av[Av.Web=0]="Web",Av[Av.Android=1]="Android",Av[Av.iOS=2]="iOS";class Cv{constructor(){this.ClientName="",this.LavvaUserName="",this.ClientType=wv.Unknown,this.TokenGuid="",this.RegistrationDate=new Date}}!function(e){e.FeatureUnsupported="FeatureUnsupported",e.UnknownError="UnknownError",e.NoData="NoData",e.IncorrectGuid="IncorrectGuid",e.IdentityIsEmpty="IdentityIsEmpty",e.DeviceTokenIsEmpty="DeviceTokenIsEmpty",e.ClientNameIsEmpty="ClientNameIsEmpty",e.LavvaUserNameIsEmpty="LavvaUserNameIsEmpty",e.TokenNotFound="TokenNotFound"}(Sv||(Sv={}));var Tv=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class Dv{constructor(){this._connection=Ov.Get(Pt.ServiceName),this._logger=Ov.Get(s.ServiceName)}GetServiceName(){return Dv.ServiceName}RegisterNotificationsClientAsync(e){return Tv(this,void 0,void 0,(function*(){var t;try{const n=new kv({ClientName:e.ClientName,DeviceToken:e.DeviceToken,LavvaUserName:e.LavvaUserName,ClientType:this.getClientType(),NotificationsEnabledForToken:e.EnableNotifications}),s=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(n,8e3,!1);if(null==s||null==s.Status)return new De(Sv.UnknownError,"Cannot register notifications client - unknown error!");switch(s.Status){case ce.WrongData:{const e=this.isValidErrorCode(s.Data)?s.Data:Sv.UnknownError;return new De(e,"Cannot register notifications client - wrong data!")}case ce.ResourceDoesNotExists:return new De(Sv.FeatureUnsupported,"Notifications feature not supported in controller!");case ce.OK:return"string"==typeof s.Data?s.Data:new De(Sv.NoData,"Cannot register notifications client - result status is OK, but no token guid presented in paylode, unknown error!");default:return new De(Sv.UnknownError,"Cannot register notifications client - unknown error!")}}catch(e){return new De(Sv.UnknownError,`Cannot register notifications client - error: ${e}`)}}))}UpdateNotificationsClientAsync(e,t){return Tv(this,void 0,void 0,(function*(){var n;try{const s=new Gv({ClientName:t.ClientName,DeviceToken:t.DeviceToken,LavvaUserName:t.LavvaUserName,ClientType:this.getClientType(),NotificationsEnabledForToken:t.EnableNotifications,Guid:e}),r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(s,8e3,!1);if(null==r||null==r.Status)return new De(Sv.UnknownError,"Cannot update notifications client - unknown error!");switch(r.Status){case ce.WrongData:{const e=this.isValidErrorCode(r.Data)?r.Data:Sv.UnknownError;return new De(e,"Cannot update notifications client - wrong data!")}case ce.ResourceDoesNotExists:return new De(Sv.FeatureUnsupported,"Notifications feature not supported in controller!");case ce.OK:return"string"==typeof r.Data?r.Data==e?ce.OK:new De(Sv.UnknownError,`Cannot update notifications client - result status is OK, but token guid is different! request guid ${e}, response guid: ${r.Data}`):new De(Sv.NoData,"Cannot update notifications client - result status is OK, but no token guid presented in paylode, unknown error!");default:return new De(Sv.UnknownError,"Cannot update notifications client - unknown error!")}}catch(e){return this._logger.Error(`Cannot update notifications client - error: ${e}`),new De(Sv.UnknownError,`Cannot update notifications client - error: ${e}`)}}))}GetRegisteredNotificationsClientsMetadataAsync(){return Tv(this,void 0,void 0,(function*(){var e;try{const t=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new bv,8e3,!1);return null==t||null==t.Status?new De(Sv.UnknownError,"Cannot get notifications clients metadata - unknown error!"):t.Status==ce.ResourceDoesNotExists?new De(Sv.FeatureUnsupported,"Notifications feature not supported in controller!"):t.Status!=ce.OK?new De(Sv.UnknownError,`Cannot get notifications clients metadata - response status: ${t.Status}}`):null==t.Data?new De(Sv.NoData,"Cannot get notifications clients metadata - response status is OK, but no data!"):t.Data.map((e=>{const t=new Cv;return t.ClientName=e.ClientName,t.LavvaUserName=e.LavvaUserName,t.ClientType=e.ClientType,t.TokenGuid=e.TokenGuid,t.RegistrationDate=new Date(e.RegistrationDate),t}))}catch(e){return this._logger.Error(`Cannot get notifications clients metadata - error: ${e}`),new De(Sv.UnknownError,`Cannot get notifications clients metadata - error: ${e}`)}}))}IsNotifiacationsEnabledAsync(e){return Tv(this,void 0,void 0,(function*(){var t;try{const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Nv(e),8e3,!1);if(null==n||null==n.Status)return new De(Sv.UnknownError,"Cannot get notifications status - unknown error!");switch(n.Status){case ce.ResourceDoesNotExists:if(null==n.Data)return new De(Sv.FeatureUnsupported,"Notifications feature not supported in controller!");{const e=this.isValidErrorCode(n.Data)?n.Data:Sv.UnknownError;return new De(e,"Cannot get notifications status - resource not exists!")}case ce.OK:return"boolean"==typeof n.Data?n.Data:new De(Sv.NoData,"Cannot get notifications status - result status is OK, but no data, or data type is wrong!");default:return new De(Sv.UnknownError,`Cannot get notifications - response code ${n.Status}}!`)}}catch(e){return this._logger.Error(`Cannot get notifications status - error: ${e}`),new De(Sv.UnknownError,`Cannot get notifications status - error: ${e}`)}}))}EnableNotificationsAsync(e){return Tv(this,void 0,void 0,(function*(){var t;try{let n=null;null!=e&&""!=e&&(n=e);const s=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Ev(n),8e3,!1);if(null==s||null==s.Status)return new De(Sv.UnknownError,"Cannot enable notifications - unknown error!");switch(s.Status){case ce.ResourceDoesNotExists:if(null==s.Data)return new De(Sv.FeatureUnsupported,"Notifications feature not supported in controller!");{const e=this.isValidErrorCode(s.Data)?s.Data:Sv.UnknownError;return new De(e,"Cannot enable notifications - resource not exists!")}case ce.OK:return ce.OK;default:return new De(Sv.UnknownError,`Cannot enable notifications - response code ${s.Status}}!`)}}catch(e){return this._logger.Error(`Cannot enable notifications - error: ${e}`),new De(Sv.UnknownError,`Cannot enable notifications - error: ${e}`)}}))}DisableNotificationsAsync(e){return Tv(this,void 0,void 0,(function*(){var t;try{let n=null;null!=e&&""!=e&&(n=e);const s=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Iv(n),8e3,!1);if(null==s||null==s.Status)return new De(Sv.UnknownError,"Cannot disable notifications - unknown error!");switch(s.Status){case ce.ResourceDoesNotExists:if(null==s.Data)return new De(Sv.FeatureUnsupported,"Notifications feature not supported in controller!");{const e=this.isValidErrorCode(s.Data)?s.Data:Sv.UnknownError;return new De(e,"Cannot disable notifications - resource not exists!")}case ce.OK:return ce.OK;default:return new De(Sv.UnknownError,`Cannot disable notifications - response code ${s.Status}!`)}}catch(e){return this._logger.Error(`Cannot disable notifications - error: ${e}`),new De(Sv.UnknownError,`Cannot disable notifications - error: ${e}`)}}))}getClientType(){return null!=window.webkit&&null!=window.webkit.messageHandlers?wv.iOS:navigator.userAgent.endsWith("LavvaAndroidNative")?wv.Android:wv.Web}isValidErrorCode(e){return Object.values(Sv).includes(e)}}Dv.ServiceName="NotificationsService";class kv extends ae{constructor(e){super(),this.Resource="/notifications/token",this.Method=ue.Post,this.Data=e}}class Gv extends ae{constructor(e){super(),this.Resource="/notifications/token",this.Method=ue.Put,this.Data=e}}class bv extends ae{constructor(){super(),this.Resource="/notifications/tokens/metadata",this.Method=ue.Get}}class Nv extends ae{constructor(e){super(),this.Resource="/notifications/status",this.Method=ue.Get,this.Data={TokenIdentity:e}}}class Ev extends ae{constructor(e){super(),this.Resource="/notifications/enabl",this.Method=ue.Post,this.Data=e}}class Iv extends ae{constructor(e){super(),this.Resource="/notifications/disable",this.Method=ue.Post,this.Data=e}}class Rv{CheckLocationPermissionAsync(){return this.IsAndroidLocationAvailable()?navigator.AndroidLocation.CheckNotificationPermissionAsync():Promise.resolve(!1)}RequestLocationPermissionAsync(){return this.IsAndroidLocationAvailable()?navigator.AndroidNotifications.RequestLocationPermissionAsync():Promise.resolve(!1)}IsAndroidLocationAvailable(){return void 0!==navigator.AndroidLocation}GetServiceName(){return Rv.ServiceName}}Rv.ServiceName="AndroidLocationService";class Pv{IsAndroidNotificationsAvailable(){return void 0!==navigator.AndroidNotifications}CheckNotificationPermissionAsync(){return this.IsAndroidNotificationsAvailable()?navigator.AndroidNotifications.CheckNotificationPermissionAsync():Promise.resolve(!1)}RequestNotificationPermissionAsync(){return this.IsAndroidNotificationsAvailable()?navigator.AndroidNotifications.RequestNotificationPermissionAsync():Promise.resolve(!1)}GetServiceName(){return Pv.ServiceName}}Pv.ServiceName="AndroidNotificationsService",tu(Map),tu(Set),(()=>{const e=String.prototype,t=Object.getOwnPropertyNames(ci.prototype);for(const n of t)e[n]=e[n]??ci.prototype[n];e.first=function(e){if(e){for(let t=0;t<this.length;t++){const n=this[t];if(!0===e(n))return n}throw new ri(si.NoMatch)}if(0===this.length)throw new ri(si.NoElements);return this[0]},e.firstOrDefault=function(e){if(e){for(let t=0;t<this.length;t++){const n=this[t];if(!0===e(n))return n}return null}return 0===this.length?null:this[0]},e.count=function(e){if(e){let t=0;for(let n=0;n<this.length;n++)!0===e(this[n])&&t++;return t}return this.length},e.elementAt=function(e){if(e<0||e>=this.length)throw new ni("index");return this[e]},e.elementAtOrDefault=function(e){return this[e]||null},e.last=function(e){if(e){for(let t=this.length-1;t>=0;t--){const n=this[t];if(!0===e(n))return n}throw new ri(si.NoMatch)}if(0===this.length)throw new ri(si.NoElements);return this[this.length-1]},e.lastOrDefault=function(e){if(e){for(let t=this.length-1;t>=0;t--){const n=this[t];if(!0===e(n))return n}return null}return 0===this.length?null:this[this.length-1]},e.reverse=function(){const e=this;return new ci((function*(){for(let t=e.length-1;t>=0;t--)yield e[t]}))}})(),rp(Array),rp(Int8Array),rp(Int16Array),rp(Int32Array),rp(Uint8Array),rp(Uint8ClampedArray),rp(Uint16Array),rp(Uint32Array),rp(Float32Array),rp(Float64Array);class Ov{static Init(){if(r.IsInitialized)return;let e=r.Instance;try{e.RegisterService(new hv),e.RegisterService(new o),e.RegisterService(new Fp),e.RegisterService(new Ge),e.RegisterService(new Ke),e.RegisterService(new yv),Ov.IsRunningFromLocalNetwork()?(console.log("\n\nRunning from local network!\n\n"),e.RegisterService(new mv)):e.RegisterService(new Pt),e.RegisterService(new Rv),e.RegisterService(new Pv),e.RegisterService(new dr),e.RegisterService(new _v),e.RegisterService(new dr),e.RegisterService(new Ur),e.RegisterService(new rt),e.RegisterService(new pv),e.RegisterService(new ar),e.RegisterService(new Ze),e.RegisterService(new Ne),e.RegisterService(new Le),e.RegisterService(new xo),e.RegisterService(new lp),e.RegisterService(new Xr),e.RegisterService(new ef),e.RegisterService(new iv),e.RegisterService(new Nf),e.RegisterService(new Do),e.RegisterService(new sv),e.RegisterService(new Dv)}catch(e){console.error(e)}}static IsAppServedFromControllerAsync(){const e=`http://${window.location.hostname}/controller_info`;return fetch(e,{method:"GET"}).then((e=>!!e.ok)).catch((e=>!1))}static IsRunningFromLocalNetwork(e=window.location.hostname){return e.startsWith("192.168.")||e.startsWith("10.")}static GetAsync(e,t){return r.Instance.GetServiceAsync(e,t)}static GetWithTimeoutAsync(e,t){return r.Instance.GetServiceWithTimeoutAsync(e,t)}static Get(e){return r.Instance.GetService(e)}static SleepForAsync(e){return new Promise((t=>setTimeout(t,e)))}static ExportStringAsFileToDownload(e,t){const n=new Blob([t],{type:"text/plain"}),s=document.createElement("a"),r=window.URL.createObjectURL(n);return s.href=r,s.download=e,s}}Ov.WorksInContextOf="",Ov.Version=1})();
|
|
1
|
+
(()=>{"use strict";var e,t={d:(e,n)=>{for(var s in n)t.o(n,s)&&!t.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:n[s]})}};t.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),t.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),t.d({},{j:()=>Fv});class n{constructor(){this.handlers=[]}Subscribe(e){this.handlers.push(e)}Unsubscribe(e){this.handlers=this.handlers.filter((t=>t!==e))}Invoke(e){this.handlers.slice(0).forEach((t=>{var n;try{t(e)}catch(e){null===(n=r.Log)||void 0===n||n.Error(e)}}))}}!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warning=2]="Warning",e[e.Error=3]="Error",e[e.None=4]="None"}(e||(e={}));class s{constructor(){this._blockedServices=[],this._logLevel=e.Debug,void 0!==window.loglevel&&null!==window.loglevel&&(this._logLevel=window.loglevel),window.logger=this}EnableStackTrace(){s.DoesThrowStackTrace=!0}DisableStackTrace(){s.DoesThrowStackTrace=!1}IsBlocked(e){return void 0!==e&&this._blockedServices.any((t=>t==e))}DisableLogsFrom(e){this._blockedServices.all((t=>t!=e))&&this._blockedServices.push(e),this.Debug(s.ServiceName,`Disabling logs from ${e}`)}EnableLogsFrom(e){this._blockedServices.any((t=>t==e))&&(this._blockedServices=this._blockedServices.where((t=>t!=e)).toArray()),this.Debug(s.ServiceName,`Enaabling logs from ${e}`)}get LogLevel(){return this._logLevel}set LogLevel(e){this._logLevel=e}GetServiceName(){return s.ServiceName}GetTimeStamp(){const e=new Date;return`${e.getHours()}:${e.getMinutes()}:${e.getSeconds()}.${e.getMilliseconds()} | `}Warning(t,n){switch(this._logLevel){case e.Warning:case e.Info:case e.Debug:break;case e.None:default:return}void 0===t||this.IsBlocked(t)||null!=t&&(null==n?console.warn(`${this.GetTimeStamp()}[WARN] ${t}`):console.warn(`${this.GetTimeStamp()}[WARN] [${t}] ${n}`))}Error(t,n){switch(this._logLevel){case e.Warning:case e.Info:case e.Debug:case e.Error:break;case e.None:default:return}null!=t&&(null==n?console.error(`${this.GetTimeStamp()}[ERROR] ${t}`):console.error(`${this.GetTimeStamp()}[ERROR] [${t}] ${n}`))}Info(t,n){switch(this._logLevel){case e.Info:case e.Debug:break;case e.None:default:return}void 0===t||this.IsBlocked(t)||null!=t&&(null==n?console.info(`${this.GetTimeStamp()}[INFO] ${t}`):console.info(`${this.GetTimeStamp()}[INFO] [${t}] ${n}`))}Debug(t,n){switch(this._logLevel){case e.Debug:break;case e.None:default:return}void 0===t||this.IsBlocked(t)||null!=t&&(null==n?console.debug(`${this.GetTimeStamp()}[DEBUG] ${t}`):s.DoesThrowStackTrace||!0===window.stacktrace?console.debug(`${this.GetTimeStamp()}[DEBUG] [${t}] ${n} \nstack:\n${(new Error).stack}}`):console.debug(`${this.GetTimeStamp()}[DEBUG] [${t}] ${n}`))}Log(t,n){this._logLevel!==e.None&&(void 0===t||this.IsBlocked(t)||null!=t&&(null==n?console.log(`${this.GetTimeStamp()}[LOG] ${t}`):console.log(`${this.GetTimeStamp()}[LOG] [${t}] ${n}`)))}}s.ServiceName="LoggerService",s.DoesThrowStackTrace=!1;class r{constructor(){this._services={},this._serviceRegistrationEvent=new n}static get Instance(){return null!=r._instance||(r._instance=new r,this.Log=new s,this.Log.Warning("Initializing DependencyContainer"),r._instance.RegisterService(this.Log),this.IsInitialized=!0,window.services=this),r._instance}RegisterService(e){var t;null===(t=r.Log)||void 0===t||t.Debug("DependencyContainer",`Registering new service: ${e.GetServiceName()}`),this._services[e.GetServiceName()]=e,this._serviceRegistrationEvent.Invoke(e)}GetService(e){var t;return null===(t=r.Log)||void 0===t||t.Debug("DependencyContainer",`Getting service [${e}] by GetService<T>()`),this._services[e]}GetServiceAsync(e,t){var n,s;return null===(n=r.Log)||void 0===n||n.Debug("DependencyContainer",`Waiting for service availability [${e}] by GetServiceAsync<T>()`),this._services.hasOwnProperty(e)?(null===(s=r.Log)||void 0===s||s.Debug("DependencyContainer",`Got service [${e}] by GetServiceAsync<T>()`),Promise.resolve(this._services[e])):new Promise(((n,s)=>{var o=t=>{var s;(null==t?void 0:t.GetServiceName())===e&&(null===(s=r.Log)||void 0===s||s.Debug("DependencyContainer",`Got service [${e}] by GetServiceAsync<T>()`),this._serviceRegistrationEvent.Unsubscribe(o),n(t))},i=()=>{var n;null===(n=r.Log)||void 0===n||n.Debug("DependencyContainer",`Cancelled service [${e}] retrieval by GetServiceAsync<T>()`),this._serviceRegistrationEvent.Unsubscribe(o),null==t||t.CancellationEvent.Unsubscribe(i),s(new Error("Operation cancelled!"))};null==t||t.CancellationEvent.Subscribe(i),this._serviceRegistrationEvent.Subscribe(o)}))}GetServiceWithTimeoutAsync(e,t){var n,s;return null===(n=r.Log)||void 0===n||n.Debug("DependencyContainer",`Waiting for service[${e}] availability by GetServiceWithTimeoutAsync<T>()`),this._services.hasOwnProperty(e)?(null===(s=r.Log)||void 0===s||s.Debug("DependencyContainer",`Got service [${e}] by GetServiceWithTimeoutAsync<T>()`),Promise.resolve(this._services[e])):new Promise(((n,s)=>{let o=0,i=e=>{var t;(null==e?void 0:e.GetClassName())===e&&(null===(t=r.Log)||void 0===t||t.Debug("DependencyContainer",`Got service [${e}] by GetServiceWithTimeoutAsync<T>()`),window.clearTimeout(o),this._serviceRegistrationEvent.Unsubscribe(i),n(e))};o=window.setTimeout((()=>{var t;window.clearTimeout(o),this._serviceRegistrationEvent.Unsubscribe(i),null===(t=r.Log)||void 0===t||t.Error("DependencyContainer",`Failed to get service [${e}] in time by GetServiceWithTimeoutAsync<T>()`),s(new Error("Operation cancelled!"))}),t),this._serviceRegistrationEvent.Subscribe(i)}))}}r.IsInitialized=!1;class o{GetServiceName(){return o.ServiceName}GetResourceName(e,t){return`_exalus_${Fv.WorksInContextOf}_${e}_${t}`}Remove(e,t){localStorage.removeItem(this.GetResourceName(e,t))}DropStorage(e){let t=`_exalus_${e}`;for(const e in localStorage)(null==e?void 0:e.startsWith(t))&&localStorage.removeItem(e)}Save(e,t,n){localStorage.setItem(this.GetResourceName(e,t),JSON.stringify(n))}Read(e,t){var n;try{let n=this.GetResourceName(e,t),s=localStorage.getItem(n);return null==s?null:JSON.parse(s)}catch(s){return null===(n=r.Log)||void 0===n||n.Error(o.ServiceName,`Exception has occurred while reading ${this.GetResourceName(e,t)}`),null}}}o.ServiceName="LocalStorageService";const i=[0,2e3,1e4,3e4,null];class a{constructor(e){this._retryDelays=void 0!==e?[...e,null]:i}nextRetryDelayInMilliseconds(e){return this._retryDelays[e.previousRetryCount]}}class c{}c.Authorization="Authorization",c.Cookie="Cookie";class u{constructor(e,t,n){this.statusCode=e,this.statusText=t,this.content=n}}class l{get(e,t){return this.send({...t,method:"GET",url:e})}post(e,t){return this.send({...t,method:"POST",url:e})}delete(e,t){return this.send({...t,method:"DELETE",url:e})}getCookieString(e){return""}}class d extends l{constructor(e,t){super(),this._innerClient=e,this._accessTokenFactory=t}async send(e){let t=!0;this._accessTokenFactory&&(!this._accessToken||e.url&&e.url.indexOf("/negotiate?")>0)&&(t=!1,this._accessToken=await this._accessTokenFactory()),this._setAuthorizationHeader(e);const n=await this._innerClient.send(e);return t&&401===n.statusCode&&this._accessTokenFactory?(this._accessToken=await this._accessTokenFactory(),this._setAuthorizationHeader(e),await this._innerClient.send(e)):n}_setAuthorizationHeader(e){e.headers||(e.headers={}),this._accessToken?e.headers[c.Authorization]=`Bearer ${this._accessToken}`:this._accessTokenFactory&&e.headers[c.Authorization]&&delete e.headers[c.Authorization]}getCookieString(e){return this._innerClient.getCookieString(e)}}class h extends Error{constructor(e,t){const n=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=n}}class p extends Error{constructor(e="A timeout occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class g extends Error{constructor(e="An abort occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class f extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="UnsupportedTransportError",this.__proto__=n}}class v extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="DisabledTransportError",this.__proto__=n}}class m extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="FailedToStartTransportError",this.__proto__=n}}class y extends Error{constructor(e){const t=new.target.prototype;super(e),this.errorType="FailedToNegotiateWithServerError",this.__proto__=t}}class w extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.innerErrors=t,this.__proto__=n}}var S,A,_,C,T;!function(e){e[e.Trace=0]="Trace",e[e.Debug=1]="Debug",e[e.Information=2]="Information",e[e.Warning=3]="Warning",e[e.Error=4]="Error",e[e.Critical=5]="Critical",e[e.None=6]="None"}(S||(S={}));class D{constructor(){}log(e,t){}}D.instance=new D;class k{static isRequired(e,t){if(null==e)throw new Error(`The '${t}' argument is required.`)}static isNotEmpty(e,t){if(!e||e.match(/^\s*$/))throw new Error(`The '${t}' argument should not be empty.`)}static isIn(e,t,n){if(!(e in t))throw new Error(`Unknown ${n} value: ${e}.`)}}class G{static get isBrowser(){return!G.isNode&&"object"==typeof window&&"object"==typeof window.document}static get isWebWorker(){return!G.isNode&&"object"==typeof self&&"importScripts"in self}static get isReactNative(){return!G.isNode&&"object"==typeof window&&void 0===window.document}static get isNode(){return"undefined"!=typeof process&&process.release&&"node"===process.release.name}}function b(e,t){let n="";return N(e)?(n=`Binary data of length ${e.byteLength}`,t&&(n+=`. Content: '${function(e){const t=new Uint8Array(e);let n="";return t.forEach((e=>{n+=`0x${e<16?"0":""}${e.toString(16)} `})),n.substr(0,n.length-1)}(e)}'`)):"string"==typeof e&&(n=`String data of length ${e.length}`,t&&(n+=`. Content: '${e}'`)),n}function N(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function E(e,t,n,s,r,o){const i={},[a,c]=P();i[a]=c,e.log(S.Trace,`(${t} transport) sending data. ${b(r,o.logMessageContent)}.`);const u=N(r)?"arraybuffer":"text",l=await n.post(s,{content:r,headers:{...i,...o.headers},responseType:u,timeout:o.timeout,withCredentials:o.withCredentials});e.log(S.Trace,`(${t} transport) request complete. Response status: ${l.statusCode}.`)}class I{constructor(e,t){this._subject=e,this._observer=t}dispose(){const e=this._subject.observers.indexOf(this._observer);e>-1&&this._subject.observers.splice(e,1),0===this._subject.observers.length&&this._subject.cancelCallback&&this._subject.cancelCallback().catch((e=>{}))}}class R{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const n=`[${(new Date).toISOString()}] ${S[e]}: ${t}`;switch(e){case S.Critical:case S.Error:this.out.error(n);break;case S.Warning:this.out.warn(n);break;case S.Information:this.out.info(n);break;default:this.out.log(n)}}}}function P(){let e="X-SignalR-User-Agent";return G.isNode&&(e="User-Agent"),[e,O("8.0.7",U(),G.isNode?"NodeJS":"Browser",M())]}function O(e,t,n,s){let r="Microsoft SignalR/";const o=e.split(".");return r+=`${o[0]}.${o[1]}`,r+=` (${e}; `,r+=t&&""!==t?`${t}; `:"Unknown OS; ",r+=`${n}`,r+=s?`; ${s}`:"; Unknown Runtime Version",r+=")",r}function U(){if(!G.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function M(){if(G.isNode)return process.versions.node}function x(e){return e.stack?e.stack:e.message?e.message:`${e}`}class F extends l{constructor(e){if(super(),this._logger=e,"undefined"==typeof fetch||G.isNode){const e=require;this._jar=new(e("tough-cookie").CookieJar),"undefined"==typeof fetch?this._fetchType=e("node-fetch"):this._fetchType=fetch,this._fetchType=e("fetch-cookie")(this._fetchType,this._jar)}else this._fetchType=fetch.bind(function(){if("undefined"!=typeof globalThis)return globalThis;if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==t.g)return t.g;throw new Error("could not find global")}());if("undefined"==typeof AbortController){const e=require;this._abortControllerType=e("abort-controller")}else this._abortControllerType=AbortController}async send(e){if(e.abortSignal&&e.abortSignal.aborted)throw new g;if(!e.method)throw new Error("No method defined.");if(!e.url)throw new Error("No url defined.");const t=new this._abortControllerType;let n;e.abortSignal&&(e.abortSignal.onabort=()=>{t.abort(),n=new g});let s,r=null;if(e.timeout){const s=e.timeout;r=setTimeout((()=>{t.abort(),this._logger.log(S.Warning,"Timeout from HTTP request."),n=new p}),s)}""===e.content&&(e.content=void 0),e.content&&(e.headers=e.headers||{},N(e.content)?e.headers["Content-Type"]="application/octet-stream":e.headers["Content-Type"]="text/plain;charset=UTF-8");try{s=await this._fetchType(e.url,{body:e.content,cache:"no-cache",credentials:!0===e.withCredentials?"include":"same-origin",headers:{"X-Requested-With":"XMLHttpRequest",...e.headers},method:e.method,mode:"cors",redirect:"follow",signal:t.signal})}catch(e){if(n)throw n;throw this._logger.log(S.Warning,`Error from HTTP request. ${e}.`),e}finally{r&&clearTimeout(r),e.abortSignal&&(e.abortSignal.onabort=null)}if(!s.ok){const e=await L(s,"text");throw new h(e||s.statusText,s.status)}const o=L(s,e.responseType),i=await o;return new u(s.status,s.statusText,i)}getCookieString(e){let t="";return G.isNode&&this._jar&&this._jar.getCookies(e,((e,n)=>t=n.join("; "))),t}}function L(e,t){let n;switch(t){case"arraybuffer":n=e.arrayBuffer();break;case"text":default:n=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`)}return n}class B extends l{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new g):e.method?e.url?new Promise(((t,n)=>{const s=new XMLHttpRequest;s.open(e.method,e.url,!0),s.withCredentials=void 0===e.withCredentials||e.withCredentials,s.setRequestHeader("X-Requested-With","XMLHttpRequest"),""===e.content&&(e.content=void 0),e.content&&(N(e.content)?s.setRequestHeader("Content-Type","application/octet-stream"):s.setRequestHeader("Content-Type","text/plain;charset=UTF-8"));const r=e.headers;r&&Object.keys(r).forEach((e=>{s.setRequestHeader(e,r[e])})),e.responseType&&(s.responseType=e.responseType),e.abortSignal&&(e.abortSignal.onabort=()=>{s.abort(),n(new g)}),e.timeout&&(s.timeout=e.timeout),s.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),s.status>=200&&s.status<300?t(new u(s.status,s.statusText,s.response||s.responseText)):n(new h(s.response||s.responseText||s.statusText,s.status))},s.onerror=()=>{this._logger.log(S.Warning,`Error from HTTP request. ${s.status}: ${s.statusText}.`),n(new h(s.statusText,s.status))},s.ontimeout=()=>{this._logger.log(S.Warning,"Timeout from HTTP request."),n(new p)},s.send(e.content)})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class W extends l{constructor(e){if(super(),"undefined"!=typeof fetch||G.isNode)this._httpClient=new F(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new B(e)}}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new g):e.method?e.url?this._httpClient.send(e):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}getCookieString(e){return this._httpClient.getCookieString(e)}}!function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(A||(A={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(_||(_={}));class ${constructor(){this._isAborted=!1,this.onabort=null}abort(){this._isAborted||(this._isAborted=!0,this.onabort&&this.onabort())}get signal(){return this}get aborted(){return this._isAborted}}class q{get pollAborted(){return this._pollAbort.aborted}constructor(e,t,n){this._httpClient=e,this._logger=t,this._pollAbort=new $,this._options=n,this._running=!1,this.onreceive=null,this.onclose=null}async connect(e,t){if(k.isRequired(e,"url"),k.isRequired(t,"transferFormat"),k.isIn(t,_,"transferFormat"),this._url=e,this._logger.log(S.Trace,"(LongPolling transport) Connecting."),t===_.Binary&&"undefined"!=typeof XMLHttpRequest&&"string"!=typeof(new XMLHttpRequest).responseType)throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported.");const[n,s]=P(),r={[n]:s,...this._options.headers},o={abortSignal:this._pollAbort.signal,headers:r,timeout:1e5,withCredentials:this._options.withCredentials};t===_.Binary&&(o.responseType="arraybuffer");const i=`${e}&_=${Date.now()}`;this._logger.log(S.Trace,`(LongPolling transport) polling: ${i}.`);const a=await this._httpClient.get(i,o);200!==a.statusCode?(this._logger.log(S.Error,`(LongPolling transport) Unexpected response code: ${a.statusCode}.`),this._closeError=new h(a.statusText||"",a.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,o)}async _poll(e,t){try{for(;this._running;)try{const n=`${e}&_=${Date.now()}`;this._logger.log(S.Trace,`(LongPolling transport) polling: ${n}.`);const s=await this._httpClient.get(n,t);204===s.statusCode?(this._logger.log(S.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==s.statusCode?(this._logger.log(S.Error,`(LongPolling transport) Unexpected response code: ${s.statusCode}.`),this._closeError=new h(s.statusText||"",s.statusCode),this._running=!1):s.content?(this._logger.log(S.Trace,`(LongPolling transport) data received. ${b(s.content,this._options.logMessageContent)}.`),this.onreceive&&this.onreceive(s.content)):this._logger.log(S.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof p?this._logger.log(S.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(S.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}finally{this._logger.log(S.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?E(this._logger,"LongPolling",this._httpClient,this._url,e,this._options):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(S.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(S.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,n]=P();e[t]=n;const s={headers:{...e,...this._options.headers},timeout:this._options.timeout,withCredentials:this._options.withCredentials};let r;try{await this._httpClient.delete(this._url,s)}catch(e){r=e}r?r instanceof h&&(404===r.statusCode?this._logger.log(S.Trace,"(LongPolling transport) A 404 response was returned from sending a DELETE request."):this._logger.log(S.Trace,`(LongPolling transport) Error sending a DELETE request: ${r}`)):this._logger.log(S.Trace,"(LongPolling transport) DELETE request accepted.")}finally{this._logger.log(S.Trace,"(LongPolling transport) Stop finished."),this._raiseOnClose()}}_raiseOnClose(){if(this.onclose){let e="(LongPolling transport) Firing onclose event.";this._closeError&&(e+=" Error: "+this._closeError),this._logger.log(S.Trace,e),this.onclose(this._closeError)}}}class V{constructor(e,t,n,s){this._httpClient=e,this._accessToken=t,this._logger=n,this._options=s,this.onreceive=null,this.onclose=null}async connect(e,t){return k.isRequired(e,"url"),k.isRequired(t,"transferFormat"),k.isIn(t,_,"transferFormat"),this._logger.log(S.Trace,"(SSE transport) Connecting."),this._url=e,this._accessToken&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(this._accessToken)}`),new Promise(((n,s)=>{let r,o=!1;if(t===_.Text){if(G.isBrowser||G.isWebWorker)r=new this._options.EventSource(e,{withCredentials:this._options.withCredentials});else{const t=this._httpClient.getCookieString(e),n={};n.Cookie=t;const[s,o]=P();n[s]=o,r=new this._options.EventSource(e,{withCredentials:this._options.withCredentials,headers:{...n,...this._options.headers}})}try{r.onmessage=e=>{if(this.onreceive)try{this._logger.log(S.Trace,`(SSE transport) data received. ${b(e.data,this._options.logMessageContent)}.`),this.onreceive(e.data)}catch(e){return void this._close(e)}},r.onerror=e=>{o?this._close():s(new Error("EventSource failed to connect. The connection could not be found on the server, either the connection ID is not present on the server, or a proxy is refusing/buffering the connection. If you have multiple servers check that sticky sessions are enabled."))},r.onopen=()=>{this._logger.log(S.Information,`SSE connected to ${this._url}`),this._eventSource=r,o=!0,n()}}catch(e){return void s(e)}}else s(new Error("The Server-Sent Events transport only supports the 'Text' transfer format"))}))}async send(e){return this._eventSource?E(this._logger,"SSE",this._httpClient,this._url,e,this._options):Promise.reject(new Error("Cannot send until the transport is connected"))}stop(){return this._close(),Promise.resolve()}_close(e){this._eventSource&&(this._eventSource.close(),this._eventSource=void 0,this.onclose&&this.onclose(e))}}class H{constructor(e,t,n,s,r,o){this._logger=n,this._accessTokenFactory=t,this._logMessageContent=s,this._webSocketConstructor=r,this._httpClient=e,this.onreceive=null,this.onclose=null,this._headers=o}async connect(e,t){let n;return k.isRequired(e,"url"),k.isRequired(t,"transferFormat"),k.isIn(t,_,"transferFormat"),this._logger.log(S.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory&&(n=await this._accessTokenFactory()),new Promise(((s,r)=>{let o;e=e.replace(/^http/,"ws");const i=this._httpClient.getCookieString(e);let a=!1;if(G.isNode||G.isReactNative){const t={},[s,r]=P();t[s]=r,n&&(t[c.Authorization]=`Bearer ${n}`),i&&(t[c.Cookie]=i),o=new this._webSocketConstructor(e,void 0,{headers:{...t,...this._headers}})}else n&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(n)}`);o||(o=new this._webSocketConstructor(e)),t===_.Binary&&(o.binaryType="arraybuffer"),o.onopen=t=>{this._logger.log(S.Information,`WebSocket connected to ${e}.`),this._webSocket=o,a=!0,s()},o.onerror=e=>{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"There was an error with the transport",this._logger.log(S.Information,`(WebSockets transport) ${t}.`)},o.onmessage=e=>{if(this._logger.log(S.Trace,`(WebSockets transport) data received. ${b(e.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(e.data)}catch(e){return void this._close(e)}},o.onclose=e=>{if(a)this._close(e);else{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"WebSocket failed to connect. The connection could not be found on the server, either the endpoint may not be a SignalR endpoint, the connection ID is not present on the server, or there is a proxy blocking WebSockets. If you have multiple servers check that sticky sessions are enabled.",r(new Error(t))}}}))}send(e){return this._webSocket&&this._webSocket.readyState===this._webSocketConstructor.OPEN?(this._logger.log(S.Trace,`(WebSockets transport) sending data. ${b(e,this._logMessageContent)}.`),this._webSocket.send(e),Promise.resolve()):Promise.reject("WebSocket is not in the OPEN state")}stop(){return this._webSocket&&this._close(void 0),Promise.resolve()}_close(e){this._webSocket&&(this._webSocket.onclose=()=>{},this._webSocket.onmessage=()=>{},this._webSocket.onerror=()=>{},this._webSocket.close(),this._webSocket=void 0),this._logger.log(S.Trace,"(WebSockets transport) socket closed."),this.onclose&&(!this._isCloseEvent(e)||!1!==e.wasClean&&1e3===e.code?e instanceof Error?this.onclose(e):this.onclose():this.onclose(new Error(`WebSocket closed with status code: ${e.code} (${e.reason||"no reason given"}).`)))}_isCloseEvent(e){return e&&"boolean"==typeof e.wasClean&&"number"==typeof e.code}}class j{constructor(e,t={}){var n;if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,k.isRequired(e,"url"),this._logger=void 0===(n=t.logger)?new R(S.Information):null===n?D.instance:void 0!==n.log?n:new R(n),this.baseUrl=this._resolveUrl(e),(t=t||{}).logMessageContent=void 0!==t.logMessageContent&&t.logMessageContent,"boolean"!=typeof t.withCredentials&&void 0!==t.withCredentials)throw new Error("withCredentials option was not a 'boolean' or 'undefined' value");t.withCredentials=void 0===t.withCredentials||t.withCredentials,t.timeout=void 0===t.timeout?1e5:t.timeout;let s=null,r=null;if(G.isNode){const e=require;s=e("ws"),r=e("eventsource")}G.isNode||"undefined"==typeof WebSocket||t.WebSocket?G.isNode&&!t.WebSocket&&s&&(t.WebSocket=s):t.WebSocket=WebSocket,G.isNode||"undefined"==typeof EventSource||t.EventSource?G.isNode&&!t.EventSource&&void 0!==r&&(t.EventSource=r):t.EventSource=EventSource,this._httpClient=new d(t.httpClient||new W(this._logger),t.accessTokenFactory),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=t,this.onreceive=null,this.onclose=null}async start(e){if(e=e||_.Binary,k.isIn(e,_,"transferFormat"),this._logger.log(S.Debug,`Starting connection with transfer format '${_[e]}'.`),"Disconnected"!==this._connectionState)return Promise.reject(new Error("Cannot start an HttpConnection that is not in the 'Disconnected' state."));if(this._connectionState="Connecting",this._startInternalPromise=this._startInternal(e),await this._startInternalPromise,"Disconnecting"===this._connectionState){const e="Failed to start the HttpConnection before stop() was called.";return this._logger.log(S.Error,e),await this._stopPromise,Promise.reject(new g(e))}if("Connected"!==this._connectionState){const e="HttpConnection.startInternal completed gracefully but didn't enter the connection into the connected state!";return this._logger.log(S.Error,e),Promise.reject(new g(e))}this._connectionStarted=!0}send(e){return"Connected"!==this._connectionState?Promise.reject(new Error("Cannot send data if the connection is not in the 'Connected' State.")):(this._sendQueue||(this._sendQueue=new K(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(S.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(S.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState="Disconnecting",this._stopPromise=new Promise((e=>{this._stopPromiseResolver=e})),await this._stopInternal(e),void await this._stopPromise)}async _stopInternal(e){this._stopError=e;try{await this._startInternalPromise}catch(e){}if(this.transport){try{await this.transport.stop()}catch(e){this._logger.log(S.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(S.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let t=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory,this._httpClient._accessTokenFactory=this._accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==A.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(A.WebSockets),await this._startTransport(t,e)}else{let n=null,s=0;do{if(n=await this._getNegotiationResponse(t),"Disconnecting"===this._connectionState||"Disconnected"===this._connectionState)throw new g("The connection was stopped during negotiation.");if(n.error)throw new Error(n.error);if(n.ProtocolVersion)throw new Error("Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server. See https://aka.ms/signalr-core-differences for details.");if(n.url&&(t=n.url),n.accessToken){const e=n.accessToken;this._accessTokenFactory=()=>e,this._httpClient._accessToken=e,this._httpClient._accessTokenFactory=void 0}s++}while(n.url&&s<100);if(100===s&&n.url)throw new Error("Negotiate redirection limit exceeded.");await this._createTransport(t,this._options.transport,n,e)}this.transport instanceof q&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(S.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(S.Error,"Failed to start the connection: "+e),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(e)}}async _getNegotiationResponse(e){const t={},[n,s]=P();t[n]=s;const r=this._resolveNegotiateUrl(e);this._logger.log(S.Debug,`Sending negotiation request: ${r}.`);try{const e=await this._httpClient.post(r,{content:"",headers:{...t,...this._options.headers},timeout:this._options.timeout,withCredentials:this._options.withCredentials});if(200!==e.statusCode)return Promise.reject(new Error(`Unexpected status code returned from negotiate '${e.statusCode}'`));const n=JSON.parse(e.content);return(!n.negotiateVersion||n.negotiateVersion<1)&&(n.connectionToken=n.connectionId),n.useStatefulReconnect&&!0!==this._options._useStatefulReconnect?Promise.reject(new y("Client didn't negotiate Stateful Reconnect but the server did.")):n}catch(e){let t="Failed to complete negotiation with the server: "+e;return e instanceof h&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(S.Error,t),Promise.reject(new y(t))}}_createConnectUrl(e,t){return t?e+(-1===e.indexOf("?")?"?":"&")+`id=${t}`:e}async _createTransport(e,t,n,s){let r=this._createConnectUrl(e,n.connectionToken);if(this._isITransport(t))return this._logger.log(S.Debug,"Connection was provided an instance of ITransport, using that directly."),this.transport=t,await this._startTransport(r,s),void(this.connectionId=n.connectionId);const o=[],i=n.availableTransports||[];let a=n;for(const n of i){const i=this._resolveTransportOrError(n,t,s,!0===(null==a?void 0:a.useStatefulReconnect));if(i instanceof Error)o.push(`${n.transport} failed:`),o.push(i);else if(this._isITransport(i)){if(this.transport=i,!a){try{a=await this._getNegotiationResponse(e)}catch(e){return Promise.reject(e)}r=this._createConnectUrl(e,a.connectionToken)}try{return await this._startTransport(r,s),void(this.connectionId=a.connectionId)}catch(e){if(this._logger.log(S.Error,`Failed to start the transport '${n.transport}': ${e}`),a=void 0,o.push(new m(`${n.transport} failed: ${e}`,A[n.transport])),"Connecting"!==this._connectionState){const e="Failed to select transport before stop() was called.";return this._logger.log(S.Debug,e),Promise.reject(new g(e))}}}}return o.length>0?Promise.reject(new w(`Unable to connect to the server with any of the available transports. ${o.join(" ")}`,o)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(e){switch(e){case A.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new H(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent,this._options.WebSocket,this._options.headers||{});case A.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new V(this._httpClient,this._httpClient._accessToken,this._logger,this._options);case A.LongPolling:return new q(this._httpClient,this._logger,this._options);default:throw new Error(`Unknown transport: ${e}.`)}}_startTransport(e,t){return this.transport.onreceive=this.onreceive,this.features.reconnect?this.transport.onclose=async n=>{let s=!1;if(this.features.reconnect){try{this.features.disconnected(),await this.transport.connect(e,t),await this.features.resend()}catch{s=!0}s&&this._stopConnection(n)}else this._stopConnection(n)}:this.transport.onclose=e=>this._stopConnection(e),this.transport.connect(e,t)}_resolveTransportOrError(e,t,n,s){const r=A[e.transport];if(null==r)return this._logger.log(S.Debug,`Skipping transport '${e.transport}' because it is not supported by this client.`),new Error(`Skipping transport '${e.transport}' because it is not supported by this client.`);if(!function(e,t){return!e||!!(t&e)}(t,r))return this._logger.log(S.Debug,`Skipping transport '${A[r]}' because it was disabled by the client.`),new v(`'${A[r]}' is disabled by the client.`,r);if(!(e.transferFormats.map((e=>_[e])).indexOf(n)>=0))return this._logger.log(S.Debug,`Skipping transport '${A[r]}' because it does not support the requested transfer format '${_[n]}'.`),new Error(`'${A[r]}' does not support ${_[n]}.`);if(r===A.WebSockets&&!this._options.WebSocket||r===A.ServerSentEvents&&!this._options.EventSource)return this._logger.log(S.Debug,`Skipping transport '${A[r]}' because it is not supported in your environment.'`),new f(`'${A[r]}' is not supported in your environment.`,r);this._logger.log(S.Debug,`Selecting transport '${A[r]}'.`);try{return this.features.reconnect=r===A.WebSockets?s:void 0,this._constructTransport(r)}catch(e){return e}}_isITransport(e){return e&&"object"==typeof e&&"connect"in e}_stopConnection(e){if(this._logger.log(S.Debug,`HttpConnection.stopConnection(${e}) called while in state ${this._connectionState}.`),this.transport=void 0,e=this._stopError||e,this._stopError=void 0,"Disconnected"!==this._connectionState){if("Connecting"===this._connectionState)throw this._logger.log(S.Warning,`Call to HttpConnection.stopConnection(${e}) was ignored because the connection is still in the connecting state.`),new Error(`HttpConnection.stopConnection(${e}) was called while the connection is still in the connecting state.`);if("Disconnecting"===this._connectionState&&this._stopPromiseResolver(),e?this._logger.log(S.Error,`Connection disconnected with error '${e}'.`):this._logger.log(S.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch((e=>{this._logger.log(S.Error,`TransportSendQueue.stop() threw error '${e}'.`)})),this._sendQueue=void 0),this.connectionId=void 0,this._connectionState="Disconnected",this._connectionStarted){this._connectionStarted=!1;try{this.onclose&&this.onclose(e)}catch(t){this._logger.log(S.Error,`HttpConnection.onclose(${e}) threw error '${t}'.`)}}}else this._logger.log(S.Debug,`Call to HttpConnection.stopConnection(${e}) was ignored because the connection is already in the disconnected state.`)}_resolveUrl(e){if(0===e.lastIndexOf("https://",0)||0===e.lastIndexOf("http://",0))return e;if(!G.isBrowser)throw new Error(`Cannot resolve '${e}'.`);const t=window.document.createElement("a");return t.href=e,this._logger.log(S.Information,`Normalizing '${e}' to '${t.href}'.`),t.href}_resolveNegotiateUrl(e){const t=new URL(e);t.pathname.endsWith("/")?t.pathname+="negotiate":t.pathname+="/negotiate";const n=new URLSearchParams(t.searchParams);return n.has("negotiateVersion")||n.append("negotiateVersion",this._negotiateVersion.toString()),n.has("useStatefulReconnect")?"true"===n.get("useStatefulReconnect")&&(this._options._useStatefulReconnect=!0):!0===this._options._useStatefulReconnect&&n.append("useStatefulReconnect","true"),t.search=n.toString(),t.toString()}}class K{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new z,this._transportResult=new z,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new z),this._transportResult.promise}stop(){return this._executing=!1,this._sendBufferedData.resolve(),this._sendLoopPromise}_bufferData(e){if(this._buffer.length&&typeof this._buffer[0]!=typeof e)throw new Error(`Expected data to be of type ${typeof this._buffer} but was of type ${typeof e}`);this._buffer.push(e),this._sendBufferedData.resolve()}async _sendLoop(){for(;;){if(await this._sendBufferedData.promise,!this._executing){this._transportResult&&this._transportResult.reject("Connection stopped.");break}this._sendBufferedData=new z;const e=this._transportResult;this._transportResult=void 0;const t="string"==typeof this._buffer[0]?this._buffer.join(""):K._concatBuffers(this._buffer);this._buffer.length=0;try{await this._transport.send(t),e.resolve()}catch(t){e.reject(t)}}}static _concatBuffers(e){const t=e.map((e=>e.byteLength)).reduce(((e,t)=>e+t)),n=new Uint8Array(t);let s=0;for(const t of e)n.set(new Uint8Array(t),s),s+=t.byteLength;return n.buffer}}class z{constructor(){this.promise=new Promise(((e,t)=>[this._resolver,this._rejecter]=[e,t]))}resolve(){this._resolver()}reject(e){this._rejecter(e)}}class J{static write(e){return`${e}${J.RecordSeparator}`}static parse(e){if(e[e.length-1]!==J.RecordSeparator)throw new Error("Message is incomplete.");const t=e.split(J.RecordSeparator);return t.pop(),t}}J.RecordSeparatorCode=30,J.RecordSeparator=String.fromCharCode(J.RecordSeparatorCode);class Y{writeHandshakeRequest(e){return J.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,n;if(N(e)){const s=new Uint8Array(e),r=s.indexOf(J.RecordSeparatorCode);if(-1===r)throw new Error("Message is incomplete.");const o=r+1;t=String.fromCharCode.apply(null,Array.prototype.slice.call(s.slice(0,o))),n=s.byteLength>o?s.slice(o).buffer:null}else{const s=e,r=s.indexOf(J.RecordSeparator);if(-1===r)throw new Error("Message is incomplete.");const o=r+1;t=s.substring(0,o),n=s.length>o?s.substring(o):null}const s=J.parse(t),r=JSON.parse(s[0]);if(r.type)throw new Error("Expected a handshake response from the server.");return[n,r]}}!function(e){e[e.Invocation=1]="Invocation",e[e.StreamItem=2]="StreamItem",e[e.Completion=3]="Completion",e[e.StreamInvocation=4]="StreamInvocation",e[e.CancelInvocation=5]="CancelInvocation",e[e.Ping=6]="Ping",e[e.Close=7]="Close",e[e.Ack=8]="Ack",e[e.Sequence=9]="Sequence"}(C||(C={}));class X{constructor(){this.observers=[]}next(e){for(const t of this.observers)t.next(e)}error(e){for(const t of this.observers)t.error&&t.error(e)}complete(){for(const e of this.observers)e.complete&&e.complete()}subscribe(e){return this.observers.push(e),new I(this,e)}}class Q{constructor(e,t,n){this._bufferSize=1e5,this._messages=[],this._totalMessageCount=0,this._waitForSequenceMessage=!1,this._nextReceivingSequenceId=1,this._latestReceivedSequenceId=0,this._bufferedByteCount=0,this._reconnectInProgress=!1,this._protocol=e,this._connection=t,this._bufferSize=n}async _send(e){const t=this._protocol.writeMessage(e);let n=Promise.resolve();if(this._isInvocationMessage(e)){this._totalMessageCount++;let e=()=>{},s=()=>{};N(t)?this._bufferedByteCount+=t.byteLength:this._bufferedByteCount+=t.length,this._bufferedByteCount>=this._bufferSize&&(n=new Promise(((t,n)=>{e=t,s=n}))),this._messages.push(new Z(t,this._totalMessageCount,e,s))}try{this._reconnectInProgress||await this._connection.send(t)}catch{this._disconnected()}await n}_ack(e){let t=-1;for(let n=0;n<this._messages.length;n++){const s=this._messages[n];if(s._id<=e.sequenceId)t=n,N(s._message)?this._bufferedByteCount-=s._message.byteLength:this._bufferedByteCount-=s._message.length,s._resolver();else{if(!(this._bufferedByteCount<this._bufferSize))break;s._resolver()}}-1!==t&&(this._messages=this._messages.slice(t+1))}_shouldProcessMessage(e){if(this._waitForSequenceMessage)return e.type===C.Sequence&&(this._waitForSequenceMessage=!1,!0);if(!this._isInvocationMessage(e))return!0;const t=this._nextReceivingSequenceId;return this._nextReceivingSequenceId++,t<=this._latestReceivedSequenceId?(t===this._latestReceivedSequenceId&&this._ackTimer(),!1):(this._latestReceivedSequenceId=t,this._ackTimer(),!0)}_resetSequence(e){e.sequenceId>this._nextReceivingSequenceId?this._connection.stop(new Error("Sequence ID greater than amount of messages we've received.")):this._nextReceivingSequenceId=e.sequenceId}_disconnected(){this._reconnectInProgress=!0,this._waitForSequenceMessage=!0}async _resend(){const e=0!==this._messages.length?this._messages[0]._id:this._totalMessageCount+1;await this._connection.send(this._protocol.writeMessage({type:C.Sequence,sequenceId:e}));const t=this._messages;for(const e of t)await this._connection.send(e._message);this._reconnectInProgress=!1}_dispose(e){null!=e||(e=new Error("Unable to reconnect to server."));for(const t of this._messages)t._rejector(e)}_isInvocationMessage(e){switch(e.type){case C.Invocation:case C.StreamItem:case C.Completion:case C.StreamInvocation:case C.CancelInvocation:return!0;case C.Close:case C.Sequence:case C.Ping:case C.Ack:return!1}}_ackTimer(){void 0===this._ackTimerHandle&&(this._ackTimerHandle=setTimeout((async()=>{try{this._reconnectInProgress||await this._connection.send(this._protocol.writeMessage({type:C.Ack,sequenceId:this._latestReceivedSequenceId}))}catch{}clearTimeout(this._ackTimerHandle),this._ackTimerHandle=void 0}),1e3))}}class Z{constructor(e,t,n,s){this._message=e,this._id=t,this._resolver=n,this._rejector=s}}!function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"}(T||(T={}));class ee{static create(e,t,n,s,r,o,i){return new ee(e,t,n,s,r,o,i)}constructor(e,t,n,s,r,o,i){this._nextKeepAlive=0,this._freezeEventListener=()=>{this._logger.log(S.Warning,"The page is being frozen, this will likely lead to the connection being closed and messages being lost. For more information see the docs at https://learn.microsoft.com/aspnet/core/signalr/javascript-client#bsleep")},k.isRequired(e,"connection"),k.isRequired(t,"logger"),k.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=null!=r?r:3e4,this.keepAliveIntervalInMilliseconds=null!=o?o:15e3,this._statefulReconnectBufferSize=null!=i?i:1e5,this._logger=t,this._protocol=n,this.connection=e,this._reconnectPolicy=s,this._handshakeProtocol=new Y,this.connection.onreceive=e=>this._processIncomingData(e),this.connection.onclose=e=>this._connectionClosed(e),this._callbacks={},this._methods={},this._closedCallbacks=[],this._reconnectingCallbacks=[],this._reconnectedCallbacks=[],this._invocationId=0,this._receivedHandshakeResponse=!1,this._connectionState=T.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:C.Ping})}get state(){return this._connectionState}get connectionId(){return this.connection&&this.connection.connectionId||null}get baseUrl(){return this.connection.baseUrl||""}set baseUrl(e){if(this._connectionState!==T.Disconnected&&this._connectionState!==T.Reconnecting)throw new Error("The HubConnection must be in the Disconnected or Reconnecting state to change the url.");if(!e)throw new Error("The HubConnection url must be a valid url.");this.connection.baseUrl=e}start(){return this._startPromise=this._startWithStateTransitions(),this._startPromise}async _startWithStateTransitions(){if(this._connectionState!==T.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=T.Connecting,this._logger.log(S.Debug,"Starting HubConnection.");try{await this._startInternal(),G.isBrowser&&window.document.addEventListener("freeze",this._freezeEventListener),this._connectionState=T.Connected,this._connectionStarted=!0,this._logger.log(S.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=T.Disconnected,this._logger.log(S.Debug,`HubConnection failed to start successfully because of error '${e}'.`),Promise.reject(e)}}async _startInternal(){this._stopDuringStartError=void 0,this._receivedHandshakeResponse=!1;const e=new Promise(((e,t)=>{this._handshakeResolver=e,this._handshakeRejecter=t}));await this.connection.start(this._protocol.transferFormat);try{let t=this._protocol.version;this.connection.features.reconnect||(t=1);const n={protocol:this._protocol.name,version:t};if(this._logger.log(S.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(n)),this._logger.log(S.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await e,this._stopDuringStartError)throw this._stopDuringStartError;!!this.connection.features.reconnect&&(this._messageBuffer=new Q(this._protocol,this.connection,this._statefulReconnectBufferSize),this.connection.features.disconnected=this._messageBuffer._disconnected.bind(this._messageBuffer),this.connection.features.resend=()=>{if(this._messageBuffer)return this._messageBuffer._resend()}),this.connection.features.inherentKeepAlive||await this._sendMessage(this._cachedPingMessage)}catch(e){throw this._logger.log(S.Debug,`Hub handshake failed with error '${e}' during start(). Stopping HubConnection.`),this._cleanupTimeout(),this._cleanupPingTimer(),await this.connection.stop(e),e}}async stop(){const e=this._startPromise;this.connection.features.reconnect=!1,this._stopPromise=this._stopInternal(),await this._stopPromise;try{await e}catch(e){}}_stopInternal(e){if(this._connectionState===T.Disconnected)return this._logger.log(S.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve();if(this._connectionState===T.Disconnecting)return this._logger.log(S.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise;const t=this._connectionState;return this._connectionState=T.Disconnecting,this._logger.log(S.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(S.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(t===T.Connected&&this._sendCloseMessage(),this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new g("The connection was stopped before the hub handshake could complete."),this.connection.stop(e))}async _sendCloseMessage(){try{await this._sendWithProtocol(this._createCloseMessage())}catch{}}stream(e,...t){const[n,s]=this._replaceStreamingParams(t),r=this._createStreamInvocation(e,t,s);let o;const i=new X;return i.cancelCallback=()=>{const e=this._createCancelInvocation(r.invocationId);return delete this._callbacks[r.invocationId],o.then((()=>this._sendWithProtocol(e)))},this._callbacks[r.invocationId]=(e,t)=>{t?i.error(t):e&&(e.type===C.Completion?e.error?i.error(new Error(e.error)):i.complete():i.next(e.item))},o=this._sendWithProtocol(r).catch((e=>{i.error(e),delete this._callbacks[r.invocationId]})),this._launchStreams(n,o),i}_sendMessage(e){return this._resetKeepAliveInterval(),this.connection.send(e)}_sendWithProtocol(e){return this._messageBuffer?this._messageBuffer._send(e):this._sendMessage(this._protocol.writeMessage(e))}send(e,...t){const[n,s]=this._replaceStreamingParams(t),r=this._sendWithProtocol(this._createInvocation(e,t,!0,s));return this._launchStreams(n,r),r}invoke(e,...t){const[n,s]=this._replaceStreamingParams(t),r=this._createInvocation(e,t,!1,s);return new Promise(((e,t)=>{this._callbacks[r.invocationId]=(n,s)=>{s?t(s):n&&(n.type===C.Completion?n.error?t(new Error(n.error)):e(n.result):t(new Error(`Unexpected message type: ${n.type}`)))};const s=this._sendWithProtocol(r).catch((e=>{t(e),delete this._callbacks[r.invocationId]}));this._launchStreams(n,s)}))}on(e,t){e&&t&&(e=e.toLowerCase(),this._methods[e]||(this._methods[e]=[]),-1===this._methods[e].indexOf(t)&&this._methods[e].push(t))}off(e,t){if(!e)return;e=e.toLowerCase();const n=this._methods[e];if(n)if(t){const s=n.indexOf(t);-1!==s&&(n.splice(s,1),0===n.length&&delete this._methods[e])}else delete this._methods[e]}onclose(e){e&&this._closedCallbacks.push(e)}onreconnecting(e){e&&this._reconnectingCallbacks.push(e)}onreconnected(e){e&&this._reconnectedCallbacks.push(e)}_processIncomingData(e){if(this._cleanupTimeout(),this._receivedHandshakeResponse||(e=this._processHandshakeResponse(e),this._receivedHandshakeResponse=!0),e){const t=this._protocol.parseMessages(e,this._logger);for(const e of t)if(!this._messageBuffer||this._messageBuffer._shouldProcessMessage(e))switch(e.type){case C.Invocation:this._invokeClientMethod(e).catch((e=>{this._logger.log(S.Error,`Invoke client method threw error: ${x(e)}`)}));break;case C.StreamItem:case C.Completion:{const t=this._callbacks[e.invocationId];if(t){e.type===C.Completion&&delete this._callbacks[e.invocationId];try{t(e)}catch(e){this._logger.log(S.Error,`Stream callback threw error: ${x(e)}`)}}break}case C.Ping:break;case C.Close:{this._logger.log(S.Information,"Close message received from server.");const t=e.error?new Error("Server returned an error on close: "+e.error):void 0;!0===e.allowReconnect?this.connection.stop(t):this._stopPromise=this._stopInternal(t);break}case C.Ack:this._messageBuffer&&this._messageBuffer._ack(e);break;case C.Sequence:this._messageBuffer&&this._messageBuffer._resetSequence(e);break;default:this._logger.log(S.Warning,`Invalid message type: ${e.type}.`)}}this._resetTimeoutPeriod()}_processHandshakeResponse(e){let t,n;try{[n,t]=this._handshakeProtocol.parseHandshakeResponse(e)}catch(e){const t="Error parsing handshake response: "+e;this._logger.log(S.Error,t);const n=new Error(t);throw this._handshakeRejecter(n),n}if(t.error){const e="Server returned handshake error: "+t.error;this._logger.log(S.Error,e);const n=new Error(e);throw this._handshakeRejecter(n),n}return this._logger.log(S.Debug,"Server handshake complete."),this._handshakeResolver(),n}_resetKeepAliveInterval(){this.connection.features.inherentKeepAlive||(this._nextKeepAlive=(new Date).getTime()+this.keepAliveIntervalInMilliseconds,this._cleanupPingTimer())}_resetTimeoutPeriod(){if(!(this.connection.features&&this.connection.features.inherentKeepAlive||(this._timeoutHandle=setTimeout((()=>this.serverTimeout()),this.serverTimeoutInMilliseconds),void 0!==this._pingServerHandle))){let e=this._nextKeepAlive-(new Date).getTime();e<0&&(e=0),this._pingServerHandle=setTimeout((async()=>{if(this._connectionState===T.Connected)try{await this._sendMessage(this._cachedPingMessage)}catch{this._cleanupPingTimer()}}),e)}}serverTimeout(){this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server."))}async _invokeClientMethod(e){const t=e.target.toLowerCase(),n=this._methods[t];if(!n)return this._logger.log(S.Warning,`No client method with the name '${t}' found.`),void(e.invocationId&&(this._logger.log(S.Warning,`No result given for '${t}' method and invocation ID '${e.invocationId}'.`),await this._sendWithProtocol(this._createCompletionMessage(e.invocationId,"Client didn't provide a result.",null))));const s=n.slice(),r=!!e.invocationId;let o,i,a;for(const n of s)try{const s=o;o=await n.apply(this,e.arguments),r&&o&&s&&(this._logger.log(S.Error,`Multiple results provided for '${t}'. Sending error to server.`),a=this._createCompletionMessage(e.invocationId,"Client provided multiple results.",null)),i=void 0}catch(e){i=e,this._logger.log(S.Error,`A callback for the method '${t}' threw error '${e}'.`)}a?await this._sendWithProtocol(a):r?(i?a=this._createCompletionMessage(e.invocationId,`${i}`,null):void 0!==o?a=this._createCompletionMessage(e.invocationId,null,o):(this._logger.log(S.Warning,`No result given for '${t}' method and invocation ID '${e.invocationId}'.`),a=this._createCompletionMessage(e.invocationId,"Client didn't provide a result.",null)),await this._sendWithProtocol(a)):o&&this._logger.log(S.Error,`Result given for '${t}' method but server is not expecting a result.`)}_connectionClosed(e){this._logger.log(S.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new g("The underlying connection was closed before the hub handshake could complete."),this._handshakeResolver&&this._handshakeResolver(),this._cancelCallbacksWithError(e||new Error("Invocation canceled due to the underlying connection being closed.")),this._cleanupTimeout(),this._cleanupPingTimer(),this._connectionState===T.Disconnecting?this._completeClose(e):this._connectionState===T.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===T.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=T.Disconnected,this._connectionStarted=!1,this._messageBuffer&&(this._messageBuffer._dispose(null!=e?e:new Error("Connection closed.")),this._messageBuffer=void 0),G.isBrowser&&window.document.removeEventListener("freeze",this._freezeEventListener);try{this._closedCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(S.Error,`An onclose callback called with error '${e}' threw error '${t}'.`)}}}async _reconnect(e){const t=Date.now();let n=0,s=void 0!==e?e:new Error("Attempting to reconnect due to a unknown error."),r=this._getNextRetryDelay(n++,0,s);if(null===r)return this._logger.log(S.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=T.Reconnecting,e?this._logger.log(S.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(S.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(S.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==T.Reconnecting)return void this._logger.log(S.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==r;){if(this._logger.log(S.Information,`Reconnect attempt number ${n} will start in ${r} ms.`),await new Promise((e=>{this._reconnectDelayHandle=setTimeout(e,r)})),this._reconnectDelayHandle=void 0,this._connectionState!==T.Reconnecting)return void this._logger.log(S.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=T.Connected,this._logger.log(S.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((e=>e.apply(this,[this.connection.connectionId])))}catch(e){this._logger.log(S.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(S.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==T.Reconnecting)return this._logger.log(S.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===T.Disconnecting&&this._completeClose());s=e instanceof Error?e:new Error(e.toString()),r=this._getNextRetryDelay(n++,Date.now()-t,s)}}this._logger.log(S.Information,`Reconnect retries have been exhausted after ${Date.now()-t} ms and ${n} failed attempts. Connection disconnecting.`),this._completeClose()}_getNextRetryDelay(e,t,n){try{return this._reconnectPolicy.nextRetryDelayInMilliseconds({elapsedMilliseconds:t,previousRetryCount:e,retryReason:n})}catch(n){return this._logger.log(S.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${n}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach((n=>{const s=t[n];try{s(null,e)}catch(t){this._logger.log(S.Error,`Stream 'error' callback called with '${e}' threw error: ${x(t)}`)}}))}_cleanupPingTimer(){this._pingServerHandle&&(clearTimeout(this._pingServerHandle),this._pingServerHandle=void 0)}_cleanupTimeout(){this._timeoutHandle&&clearTimeout(this._timeoutHandle)}_createInvocation(e,t,n,s){if(n)return 0!==s.length?{arguments:t,streamIds:s,target:e,type:C.Invocation}:{arguments:t,target:e,type:C.Invocation};{const n=this._invocationId;return this._invocationId++,0!==s.length?{arguments:t,invocationId:n.toString(),streamIds:s,target:e,type:C.Invocation}:{arguments:t,invocationId:n.toString(),target:e,type:C.Invocation}}}_launchStreams(e,t){if(0!==e.length){t||(t=Promise.resolve());for(const n in e)e[n].subscribe({complete:()=>{t=t.then((()=>this._sendWithProtocol(this._createCompletionMessage(n))))},error:e=>{let s;s=e instanceof Error?e.message:e&&e.toString?e.toString():"Unknown error",t=t.then((()=>this._sendWithProtocol(this._createCompletionMessage(n,s))))},next:e=>{t=t.then((()=>this._sendWithProtocol(this._createStreamItemMessage(n,e))))}})}}_replaceStreamingParams(e){const t=[],n=[];for(let s=0;s<e.length;s++){const r=e[s];if(this._isObservable(r)){const o=this._invocationId;this._invocationId++,t[o]=r,n.push(o.toString()),e.splice(s,1)}}return[t,n]}_isObservable(e){return e&&e.subscribe&&"function"==typeof e.subscribe}_createStreamInvocation(e,t,n){const s=this._invocationId;return this._invocationId++,0!==n.length?{arguments:t,invocationId:s.toString(),streamIds:n,target:e,type:C.StreamInvocation}:{arguments:t,invocationId:s.toString(),target:e,type:C.StreamInvocation}}_createCancelInvocation(e){return{invocationId:e,type:C.CancelInvocation}}_createStreamItemMessage(e,t){return{invocationId:e,item:t,type:C.StreamItem}}_createCompletionMessage(e,t,n){return t?{error:t,invocationId:e,type:C.Completion}:{invocationId:e,result:n,type:C.Completion}}_createCloseMessage(){return{type:C.Close}}}class te{constructor(){this.name="json",this.version=2,this.transferFormat=_.Text}parseMessages(e,t){if("string"!=typeof e)throw new Error("Invalid input for JSON hub protocol. Expected a string.");if(!e)return[];null===t&&(t=D.instance);const n=J.parse(e),s=[];for(const e of n){const n=JSON.parse(e);if("number"!=typeof n.type)throw new Error("Invalid payload.");switch(n.type){case C.Invocation:this._isInvocationMessage(n);break;case C.StreamItem:this._isStreamItemMessage(n);break;case C.Completion:this._isCompletionMessage(n);break;case C.Ping:case C.Close:break;case C.Ack:this._isAckMessage(n);break;case C.Sequence:this._isSequenceMessage(n);break;default:t.log(S.Information,"Unknown message type '"+n.type+"' ignored.");continue}s.push(n)}return s}writeMessage(e){return J.write(JSON.stringify(e))}_isInvocationMessage(e){this._assertNotEmptyString(e.target,"Invalid payload for Invocation message."),void 0!==e.invocationId&&this._assertNotEmptyString(e.invocationId,"Invalid payload for Invocation message.")}_isStreamItemMessage(e){if(this._assertNotEmptyString(e.invocationId,"Invalid payload for StreamItem message."),void 0===e.item)throw new Error("Invalid payload for StreamItem message.")}_isCompletionMessage(e){if(e.result&&e.error)throw new Error("Invalid payload for Completion message.");!e.result&&e.error&&this._assertNotEmptyString(e.error,"Invalid payload for Completion message."),this._assertNotEmptyString(e.invocationId,"Invalid payload for Completion message.")}_isAckMessage(e){if("number"!=typeof e.sequenceId)throw new Error("Invalid SequenceId for Ack message.")}_isSequenceMessage(e){if("number"!=typeof e.sequenceId)throw new Error("Invalid SequenceId for Sequence message.")}_assertNotEmptyString(e,t){if("string"!=typeof e||""===e)throw new Error(t)}}const ne={trace:S.Trace,debug:S.Debug,info:S.Information,information:S.Information,warn:S.Warning,warning:S.Warning,error:S.Error,critical:S.Critical,none:S.None};class se{configureLogging(e){if(k.isRequired(e,"logging"),void 0!==e.log)this.logger=e;else if("string"==typeof e){const t=function(e){const t=ne[e.toLowerCase()];if(void 0!==t)return t;throw new Error(`Unknown log level: ${e}`)}(e);this.logger=new R(t)}else this.logger=new R(e);return this}withUrl(e,t){return k.isRequired(e,"url"),k.isNotEmpty(e,"url"),this.url=e,this.httpConnectionOptions="object"==typeof t?{...this.httpConnectionOptions,...t}:{...this.httpConnectionOptions,transport:t},this}withHubProtocol(e){return k.isRequired(e,"protocol"),this.protocol=e,this}withAutomaticReconnect(e){if(this.reconnectPolicy)throw new Error("A reconnectPolicy has already been set.");return e?Array.isArray(e)?this.reconnectPolicy=new a(e):this.reconnectPolicy=e:this.reconnectPolicy=new a,this}withServerTimeout(e){return k.isRequired(e,"milliseconds"),this._serverTimeoutInMilliseconds=e,this}withKeepAliveInterval(e){return k.isRequired(e,"milliseconds"),this._keepAliveIntervalInMilliseconds=e,this}withStatefulReconnect(e){return void 0===this.httpConnectionOptions&&(this.httpConnectionOptions={}),this.httpConnectionOptions._useStatefulReconnect=!0,this._statefulReconnectBufferSize=null==e?void 0:e.bufferSize,this}build(){const e=this.httpConnectionOptions||{};if(void 0===e.logger&&(e.logger=this.logger),!this.url)throw new Error("The 'HubConnectionBuilder.withUrl' method must be called before building the connection.");const t=new j(this.url,e);return ee.create(t,this.logger||D.instance,this.protocol||new te,this.reconnectPolicy,this._serverTimeoutInMilliseconds,this._keepAliveIntervalInMilliseconds,this._statefulReconnectBufferSize)}}class re{static GenerateUUID(){var e=(new Date).getTime(),t="undefined"!=typeof performance&&performance.now&&1e3*performance.now()||0;return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(n){var s=16*Math.random();return e>0?(s=(e+s)%16|0,e=Math.floor(e/16)):(s=(t+s)%16|0,t=Math.floor(t/16)),("x"===n?s:3&s|8).toString(16)}))}static GenerateMd5(e){let t="0123456789abcdef";function n(e){let n,s="";for(n=0;n<=3;n++)s+=t.charAt(e>>8*n+4&15)+t.charAt(e>>8*n&15);return s}function s(e,t){let n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}function r(e,t,n,r,o,i){return s(function(e,t){return e<<t|e>>>32-t}(s(s(t,e),s(r,i)),o),n)}function o(e,t,n,s,o,i,a){return r(t&n|~t&s,e,t,o,i,a)}function i(e,t,n,s,o,i,a){return r(t&s|n&~s,e,t,o,i,a)}function a(e,t,n,s,o,i,a){return r(t^n^s,e,t,o,i,a)}function c(e,t,n,s,o,i,a){return r(n^(t|~s),e,t,o,i,a)}let u,l,d,h,p,g=function(e){let t,n=1+(e.length+8>>6),s=new Array(16*n);for(t=0;t<16*n;t++)s[t]=0;for(t=0;t<e.length;t++)s[t>>2]|=e.charCodeAt(t)<<t%4*8;return s[t>>2]|=128<<t%4*8,s[16*n-2]=8*e.length,s}(""+e),f=1732584193,v=-271733879,m=-1732584194,y=271733878;for(u=0;u<g.length;u+=16)l=f,d=v,h=m,p=y,f=o(f,v,m,y,g[u+0],7,-680876936),y=o(y,f,v,m,g[u+1],12,-389564586),m=o(m,y,f,v,g[u+2],17,606105819),v=o(v,m,y,f,g[u+3],22,-1044525330),f=o(f,v,m,y,g[u+4],7,-176418897),y=o(y,f,v,m,g[u+5],12,1200080426),m=o(m,y,f,v,g[u+6],17,-1473231341),v=o(v,m,y,f,g[u+7],22,-45705983),f=o(f,v,m,y,g[u+8],7,1770035416),y=o(y,f,v,m,g[u+9],12,-1958414417),m=o(m,y,f,v,g[u+10],17,-42063),v=o(v,m,y,f,g[u+11],22,-1990404162),f=o(f,v,m,y,g[u+12],7,1804603682),y=o(y,f,v,m,g[u+13],12,-40341101),m=o(m,y,f,v,g[u+14],17,-1502002290),v=o(v,m,y,f,g[u+15],22,1236535329),f=i(f,v,m,y,g[u+1],5,-165796510),y=i(y,f,v,m,g[u+6],9,-1069501632),m=i(m,y,f,v,g[u+11],14,643717713),v=i(v,m,y,f,g[u+0],20,-373897302),f=i(f,v,m,y,g[u+5],5,-701558691),y=i(y,f,v,m,g[u+10],9,38016083),m=i(m,y,f,v,g[u+15],14,-660478335),v=i(v,m,y,f,g[u+4],20,-405537848),f=i(f,v,m,y,g[u+9],5,568446438),y=i(y,f,v,m,g[u+14],9,-1019803690),m=i(m,y,f,v,g[u+3],14,-187363961),v=i(v,m,y,f,g[u+8],20,1163531501),f=i(f,v,m,y,g[u+13],5,-1444681467),y=i(y,f,v,m,g[u+2],9,-51403784),m=i(m,y,f,v,g[u+7],14,1735328473),v=i(v,m,y,f,g[u+12],20,-1926607734),f=a(f,v,m,y,g[u+5],4,-378558),y=a(y,f,v,m,g[u+8],11,-2022574463),m=a(m,y,f,v,g[u+11],16,1839030562),v=a(v,m,y,f,g[u+14],23,-35309556),f=a(f,v,m,y,g[u+1],4,-1530992060),y=a(y,f,v,m,g[u+4],11,1272893353),m=a(m,y,f,v,g[u+7],16,-155497632),v=a(v,m,y,f,g[u+10],23,-1094730640),f=a(f,v,m,y,g[u+13],4,681279174),y=a(y,f,v,m,g[u+0],11,-358537222),m=a(m,y,f,v,g[u+3],16,-722521979),v=a(v,m,y,f,g[u+6],23,76029189),f=a(f,v,m,y,g[u+9],4,-640364487),y=a(y,f,v,m,g[u+12],11,-421815835),m=a(m,y,f,v,g[u+15],16,530742520),v=a(v,m,y,f,g[u+2],23,-995338651),f=c(f,v,m,y,g[u+0],6,-198630844),y=c(y,f,v,m,g[u+7],10,1126891415),m=c(m,y,f,v,g[u+14],15,-1416354905),v=c(v,m,y,f,g[u+5],21,-57434055),f=c(f,v,m,y,g[u+12],6,1700485571),y=c(y,f,v,m,g[u+3],10,-1894986606),m=c(m,y,f,v,g[u+10],15,-1051523),v=c(v,m,y,f,g[u+1],21,-2054922799),f=c(f,v,m,y,g[u+8],6,1873313359),y=c(y,f,v,m,g[u+15],10,-30611744),m=c(m,y,f,v,g[u+6],15,-1560198380),v=c(v,m,y,f,g[u+13],21,1309151649),f=c(f,v,m,y,g[u+4],6,-145523070),y=c(y,f,v,m,g[u+11],10,-1120210379),m=c(m,y,f,v,g[u+2],15,718787259),v=c(v,m,y,f,g[u+9],21,-343485551),f=s(f,l),v=s(v,d),m=s(m,h),y=s(y,p);return n(f)+n(v)+n(m)+n(y)}}class oe{static Delay(e){return new Promise((t=>setTimeout(t,e)))}}function ie(e){return new Map(Object.entries(e))}class ae{constructor(){this.TransactionId=re.GenerateUUID()}}var ce,ue,le,de,he,pe,ge,fe,ve,me,ye,we,Se,Ae;(we=ce||(ce={}))[we.OK=0]="OK",we[we.UnknownError=1]="UnknownError",we[we.FatalError=2]="FatalError",we[we.WrongData=3]="WrongData",we[we.ResourceDoesNotExists=4]="ResourceDoesNotExists",we[we.NoPermissionToPerformThisOperation=5]="NoPermissionToPerformThisOperation",we[we.SessionHasAlreadyLoggedOnUser=6]="SessionHasAlreadyLoggedOnUser",we[we.OperationNotPermitted=7]="OperationNotPermitted",we[we.NoPermissionsToCallGivenResource=8]="NoPermissionsToCallGivenResource",we[we.ResourceIsNotAvailable=9]="ResourceIsNotAvailable",we[we.Error=10]="Error",we[we.NoData=11]="NoData",we[we.NotSupportedMethod=12]="NotSupportedMethod",we[we.UserIsNotLoggedIn=13]="UserIsNotLoggedIn",we[we.MultiDataResponseStart=14]="MultiDataResponseStart",we[we.MultiDataResponse=15]="MultiDataResponse",we[we.MultiDataResponseStop=16]="MultiDataResponseStop",function(e){e[e.Get=0]="Get",e[e.Post=1]="Post",e[e.Delete=2]="Delete",e[e.Put=3]="Put",e[e.Options=4]="Options",e[e.Head=5]="Head"}(ue||(ue={}));class _e{constructor(e,t){this.serialNumber=e,this.pin=t,this.SerialNumber=e,this.PIN=t}}!function(e){e[e.ByCloud=0]="ByCloud",e[e.LocalNetwork=1]="LocalNetwork",e[e.P2P=2]="P2P"}(le||(le={})),function(e){e[e.FailedToConnect=0]="FailedToConnect",e[e.AuthorizationFailed=1]="AuthorizationFailed",e[e.FailedToConnectToServer=2]="FailedToConnectToServer",e[e.Connected=3]="Connected",e[e.ControllerIsNotConnected=4]="ControllerIsNotConnected"}(de||(de={})),function(e){e[e.Disconnected=0]="Disconnected",e[e.Connecting=1]="Connecting",e[e.Connected=3]="Connected",e[e.Disconnecting=4]="Disconnecting",e[e.Failed=5]="Failed",e[e.Reconnecting=6]="Reconnecting"}(he||(he={}));class Ce{constructor(){this._log=Fv.Get(s.ServiceName),this.handlers=[]}Subscribe(e){this.handlers.push(e)}Unsubscribe(e){this.handlers=this.handlers.filter((t=>t!==e))}Invoke(){this.handlers.slice(0).forEach((e=>{try{e()}catch(e){this._log.Error(e)}}))}}(Ae=pe||(pe={}))[Ae.Any=0]="Any",Ae[Ae.Guest=10]="Guest",Ae[Ae.Standard=20]="Standard",Ae[Ae.Admin=30]="Admin",Ae[Ae.Installator=40]="Installator",Ae[Ae.Support=50]="Support",(Se=ge||(ge={}))[Se.Unknown=0]="Unknown",Se[Se.Men=1]="Men",Se[Se.Woman=2]="Woman",Se[Se.Other=3]="Other",function(e){e[e.En_Us=0]="En_Us",e[e.Pl_Pl=1]="Pl_Pl"}(fe||(fe={})),function(e){e[e.Unknown=0]="Unknown",e[e.WrongAuthData=1]="WrongAuthData",e[e.NoResponseFromController=2]="NoResponseFromController",e[e.AuthDisabled=3]="AuthDisabled",e[e.MethodNotSupported=4]="MethodNotSupported"}(ve||(ve={}));class Te{constructor(e,t){this._type=me.Unknown,this._data="",this._type=e,this._data=t}get Type(){return this._type}set Type(e){this._type=e}get Data(){return this._data}set Data(e){this._data=e}}class De{constructor(e,t){this._type=null,this._data="",this._type=e,this._data=t}get Type(){return this._type}set Type(e){this._type=e}get Data(){return this._data}set Data(e){this._data=e}}!function(e){e[e.ResourceDoesNotExists=-6]="ResourceDoesNotExists",e[e.UnknownError=-5]="UnknownError",e[e.NoPermissions=-4]="NoPermissions",e[e.WrongData=-3]="WrongData",e[e.ControllerResponseTimeout=-2]="ControllerResponseTimeout",e[e.Failed=-1]="Failed",e[e.Unknown=0]="Unknown",e[e.Changed=1]="Changed"}(me||(me={})),function(e){e[e.Device=1]="Device",e[e.Person=2]="Person",e[e.DevicesGroups=3]="DevicesGroups"}(ye||(ye={}));class ke{constructor(){this._guid="",this._ownerGuid="",this._ownerIdentity="",this._base64Image="",this._imageType=ye.Device,this._dateTime=""}get Guid(){return this._guid}get OwnerGuid(){return this._ownerGuid}get OwnerIdentity(){return this._ownerIdentity}get Base64Image(){return this._base64Image}get ImageType(){return this._imageType}get DateTime(){return this._dateTime}set Base64Image(e){this._base64Image=e}set Guid(e){this._guid=e}set OwnerGuid(e){this._ownerGuid=e}set OwnerIdentity(e){this._ownerIdentity=e}set ImageType(e){this._imageType=e}}class Ge{constructor(){this._log=Fv.Get(s.ServiceName),Ge._localStorageService=Fv.Get(o.ServiceName)}GetServiceName(){return Ge.ServiceName}GetResourceName(e){return`${e.Resource}_${e.Method}`}Cache(e){var t;e.Status===ce.OK&&(this._log.Debug(Ge.ServiceName,`Caching request: ${e.Resource} ${e.Method}`),null===(t=Ge._localStorageService)||void 0===t||t.Save(this.GetServiceName(),this.GetResourceName(e),e))}GetCache(e){var t;let n=null===(t=Ge._localStorageService)||void 0===t?void 0:t.Read(this.GetServiceName(),this.GetResourceName(e));return null!=n&&this._log.Debug(Ge.ServiceName,`Got request response from cache: ${e.Resource} ${e.Method}`),n}ClearCache(){var e;null===(e=Ge._localStorageService)||void 0===e||e.DropStorage(this.GetServiceName()),this._log.Debug(Ge.ServiceName,`Clearing cache for ${this.GetServiceName()}`)}Remove(e){var t;null===(t=Ge._localStorageService)||void 0===t||t.Remove(this.GetServiceName(),this.GetResourceName(e)),this._log.Debug(Ge.ServiceName,`Clearing cache for cache: ${e.Resource} ${e.Method}`)}}Ge._localStorageService=null,Ge.ServiceName="WebApiCacheService";var be=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class Ne{constructor(){this._imageExistsCaseNumber=0,this._connection=Fv.Get(Pt.ServiceName),this._logger=Fv.Get(s.ServiceName)}GetServiceName(){return Ne.ServiceName}AddPictureAsync(e){return be(this,void 0,void 0,(function*(){var t,n;try{if(e.Base64Image.length*(3/4)>=512e3)return this._logger.Error(Ne.ServiceName,"Cannot add picture - Base64Imgae size exceeded."),ce.WrongData;let s=new Image;const r=new Promise(((t,n)=>{s.src=e.Base64Image,s.onload=function(){t(!0)},setTimeout((()=>t(!1)),5e3)}));if(!(yield r))return this._logger.Error(Ne.ServiceName,"Cannot add picture - cannot load image - ensure that given base64 string is an image!"),ce.WrongData;if(0===s.height||0===s.width)return this._logger.Error(Ne.ServiceName,"Cannot add picture - cannot read width/height of image - ensure that given base64 string is an image!"),ce.WrongData;if(null!=e.Guid&&""!=e.Guid)return this._logger.Error(Ne.ServiceName,"Cannot add picture - Guid must be empty."),ce.WrongData;const o=new Ie;o.Guid=re.GenerateUUID(),o.DateTime=(new Date).toISOString(),o.ImageType=e.ImageType,o.OwnerGuid=`${e.OwnerGuid}_${e.OwnerIdentity}`,o.Base64Image=e.Base64Image;const i=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Pe(o.Guid),8e3,!1);if(null==i||null==i.Status)return this._logger.Error(Ne.ServiceName,"Cannot add picture - unknown error!"),ce.UnknownError;if(i.Status==ce.ResourceDoesNotExists){const e=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new Me(o),8e3,!1);return null==e||null==e.Status?(this._logger.Error(Ne.ServiceName,"Cannot add picture - unknown error!"),ce.UnknownError):e.Status}return i.Status==ce.OK?(this._logger.Warning(Ne.ServiceName,"Cannot add picture - picture already exists, trying to add with regenerated GUID."),this._imageExistsCaseNumber<2?(this._imageExistsCaseNumber++,this.AddPictureAsync(e)):ce.UnknownError):(this._logger.Error(Ne.ServiceName,"Cannot add picture - cannot get current picture status."),ce.Error)}catch(e){return this._logger.Error(Ne.ServiceName,`Cannot add picture! ${e}`),ce.FatalError}}))}EditPictureAsync(e){return be(this,void 0,void 0,(function*(){var t,n;try{if(""==e.Guid||null==e.Guid)return this._logger.Error(Ne.ServiceName,"Cannot edit picture - guid is empty."),ce.WrongData;if(e.Base64Image.length*(3/4)>=512e3)return this._logger.Error(Ne.ServiceName,"Cannot edit picture - Base64Imgae size exceeded."),ce.WrongData;let s=new Image;const r=new Promise(((t,n)=>{s.src=e.Base64Image,s.onload=function(){t(!0)},setTimeout((()=>t(!1)),5e3)}));if(!(yield r))return this._logger.Error(Ne.ServiceName,"Cannot edit picture - cannot load image - ensure that given base64 string is an image!"),ce.WrongData;if(0===s.height||0===s.width)return this._logger.Error(Ne.ServiceName,"Cannot edit picture - cannot read width/height of image - ensure that given base64 string is an image!"),ce.WrongData;const o=new Ie;o.DateTime=(new Date).toISOString(),o.ImageType=e.ImageType,o.Base64Image=e.Base64Image,o.Guid=e.Guid,e.Guid.includes("profilePicture")||e.Guid.includes("devices_group")?o.OwnerGuid=e.OwnerGuid:o.OwnerGuid=`${e.OwnerGuid}_${e.OwnerIdentity}`;const i=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Pe(o.Guid),8e3,!1);if(Fv.Get(Ge.ServiceName).ClearCache(),Fv.Get(rt.ServiceName).ExitConfigurationModeAsync(),null==i||null==i.Status)return this._logger.Error(Ne.ServiceName,"Cannot edit picture - unknown error!"),ce.UnknownError;if(i.Status==ce.ResourceDoesNotExists)return this._logger.Error(Ne.ServiceName,"Cannot edit picture - picture not exists."),ce.OperationNotPermitted;if(i.Status==ce.OK){const e=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new Me(o),8e3,!1);return Fv.Get(Ge.ServiceName).ClearCache(),Fv.Get(rt.ServiceName).ExitConfigurationModeAsync(),null==e||null==e.Status?(this._logger.Error(Ne.ServiceName,"Cannot edit picture - unknown error!"),ce.UnknownError):e.Status}return this._logger.Error(Ne.ServiceName,"Cannot edit picture - cannot get current picture status."),ce.Error}catch(e){return this._logger.Error(Ne.ServiceName,`Cannot edit picture! ${e}`),ce.FatalError}}))}DeletePictureAsync(e){return be(this,void 0,void 0,(function*(){var t;try{if(""==e.Guid||null==e.Guid)return this._logger.Error(Ne.ServiceName,"Cannot delete picture - guid is empty."),ce.WrongData;const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new xe(e.Guid),8e3,!1);return Fv.Get(Ge.ServiceName).ClearCache(),Fv.Get(rt.ServiceName).ExitConfigurationModeAsync(),null==n||null==n.Status?(this._logger.Error(Ne.ServiceName,"Cannot edit picture - unknown error!"),ce.UnknownError):n.Status}catch(e){return this._logger.Error(Ne.ServiceName,`Cannot delete picture! ${e}`),ce.FatalError}}))}GetPicturesInfoAsync(){return be(this,void 0,void 0,(function*(){var e;try{const t=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new Oe,8e3,!1);return null==t||null==t.Status?(this._logger.Error(Ne.ServiceName,"Cannot get pictures info - unknown error!"),new De(ce.UnknownError,"NoDataInResult")):t.Status!=ce.OK?(this._logger.Error(Ne.ServiceName,`Cannot get pictures info - controler responded with status ${t.Status}.`),new De(t.Status,"UnknownReason")):null==t.Data?(this._logger.Error(Ne.ServiceName,"Cannot get pictures info - controler responded with OK, but no data in result.}."),new De(ce.UnknownError,"NoDataInResult")):t.Data.map((e=>{const t=new Re;return t.DateTime=e.DateTime,t.Guid=e.Guid,t.OwnerGuid=e.OwnerGuid,-1!=e.OwnerGuid.indexOf("_")?(t.OwnerGuid=e.OwnerGuid.substring(0,e.OwnerGuid.indexOf("_")),t.OwnerIdentity=e.OwnerGuid.substring(e.OwnerGuid.indexOf("_")+1)):e.Guid.includes("profilePicture")?(t.OwnerIdentity=e.Guid.substring(e.Guid.indexOf("_")+1),t.OwnerGuid=e.OwnerGuid):e.Guid.includes("devices_group")?(t.OwnerIdentity=e.Guid.substring(0,e.Guid.lastIndexOf("_")),t.OwnerGuid=e.OwnerGuid):(t.OwnerGuid=e.OwnerGuid,t.OwnerIdentity=""),t}))}catch(e){return this._logger.Error(Ne.ServiceName,`Cannot get picture info! ${e}`),new De(ce.FatalError,"ExceptionOccurred")}}))}GetPictureAsync(e){return be(this,void 0,void 0,(function*(){var t;try{const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Pe(e),8e3,!1);if(null==n||null==n.Status)return this._logger.Error(Ne.ServiceName,"Cannot get picture - unknown error!"),new De(ce.UnknownError,"NoDataInResult");switch(n.Status){case ce.ResourceDoesNotExists:return new De(ce.ResourceDoesNotExists,"PictureNotFound");case ce.OK:if(null==n.Data)return new De(ce.Error,"RespondedWithOKButNoData");const e=new Ee;return e.Base64Image=n.Data.Base64Image,e.DateTime=n.Data.DateTime,e.ImageType=n.Data.ImageType,e.Guid=n.Data.Guid,-1!=n.Data.OwnerGuid.indexOf("_")?(e.OwnerGuid=n.Data.OwnerGuid.substring(0,n.Data.OwnerGuid.indexOf("_")),e.OwnerIdentity=n.Data.OwnerGuid.substring(n.Data.OwnerGuid.indexOf("_")+1)):n.Data.Guid.includes("profilePicture")?(e.OwnerIdentity=n.Data.Guid.substring(n.Data.Guid.indexOf("_")+1),e.OwnerGuid=n.Data.OwnerGuid):n.Data.Guid.includes("devices_group")?(e.OwnerIdentity=n.Data.Guid.substring(0,n.Data.Guid.lastIndexOf("_")),e.OwnerGuid=n.Data.OwnerGuid):(e.OwnerGuid=n.Data.OwnerGuid,e.OwnerIdentity=""),e;default:return new De(n.Status,"UnknownReason")}}catch(e){return this._logger.Error(Ne.ServiceName,`Cannot get picture! ${e}`),new De(ce.FatalError,"ExceptionOccurred")}}))}GetPicturesListAsync(){return be(this,void 0,void 0,(function*(){var e;try{const t=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new Ue,8e3,!1);return null==t||null==t.Status?(this._logger.Error(Ne.ServiceName,"Cannot get pictures - unknown error!"),new De(ce.UnknownError,"NoDataInResult")):t.Status!=ce.OK?(this._logger.Error(Ne.ServiceName,`Cannot get pictures - controler responded with status ${t.Status}.`),new De(t.Status,"UnknownReason")):null==t.Data?(this._logger.Error(Ne.ServiceName,"Cannot get pictures - controler responded with OK, but no data in result.}."),new De(ce.UnknownError,"NoDataInResult")):t.Data.map((e=>{const t=new Ee;return t.Base64Image=e.Base64Image,t.DateTime=e.DateTime,t.Guid=e.Guid,t.ImageType=e.ImageType,-1!=e.OwnerGuid.indexOf("_")?(t.OwnerGuid=e.OwnerGuid.substring(0,e.OwnerGuid.indexOf("_")),t.OwnerIdentity=e.OwnerGuid.substring(e.OwnerGuid.indexOf("_")+1)):e.Guid.includes("profilePicture")?(t.OwnerIdentity=e.Guid.substring(e.Guid.indexOf("_")+1),t.OwnerGuid=e.OwnerGuid):e.Guid.includes("devices_group")?(t.OwnerIdentity=e.Guid.substring(0,e.Guid.lastIndexOf("_")),t.OwnerGuid=e.OwnerGuid):(t.OwnerGuid=e.OwnerGuid,t.OwnerIdentity=""),t}))}catch(e){return this._logger.Error(Ne.ServiceName,`Cannot get pictures! ${e}`),new De(ce.FatalError,"ExceptionOccurred")}}))}}Ne.ServiceName="PictureService";class Ee extends ke{set DateTime(e){this._dateTime=e}}class Ie{constructor(){this.Guid="",this.OwnerGuid="",this.Base64Image="",this.ImageType=ye.Device,this.DateTime=""}}class Re{constructor(){this._guid="",this._dateTime="",this._ownerGuid="",this._ownerIdentity=""}get Guid(){return this._guid}get DateTime(){return this._dateTime}get OwnerGuid(){return this._ownerGuid}get OwnerIdentity(){return this._ownerIdentity}set Guid(e){this._guid=e}set DateTime(e){this._dateTime=e}set OwnerGuid(e){this._ownerGuid=e}set OwnerIdentity(e){this._ownerIdentity=e}}class Pe extends ae{constructor(e){super(),this.Resource="/pictures/picture",this.Method=ue.Get,this.Data=e}}class Oe extends ae{constructor(){super(),this.Resource="/pictures/info",this.Method=ue.Get}}class Ue extends ae{constructor(){super(),this.Resource="/pictures/list",this.Method=ue.Get}}class Me extends ae{constructor(e){super(),this.Resource="/pictures/picture",this.Method=ue.Put,this.Data=e}}class xe extends ae{constructor(e){super(),this.Resource="/pictures/picture",this.Method=ue.Delete,this.Data=e}}var Fe=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class Le{constructor(){this._connection=null,this._connection=Fv.Get(Pt.ServiceName),this._pictureService=Fv.Get(Ne.ServiceName),this._sessionService=Fv.Get(Ke.ServiceName)}CanEditUser(e){const t=this._sessionService.User;return e.Guid===(null==t?void 0:t.Guid)||this.CanEditUsersOfAccessLevel(e.AccessLevel)}CanEditUsersOfAccessLevel(e){var t;const n=null===(t=this._sessionService.User)||void 0===t?void 0:t.AccessLevel;if(void 0===n)return!1;switch(e){case pe.Support:return n===pe.Support;case pe.Installator:return n>=pe.Installator;case pe.Admin:default:return n>=pe.Admin}}GetServiceName(){return Le.ServiceName}GetUsersAsync(){return Fe(this,void 0,void 0,(function*(){var e,t;const n=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new qe,2e4,!1);if(null==n)return Promise.resolve([]);if((null==n?void 0:n.Status)==ce.OK){if(null!=n.Data){const e=[];return n.Data.forEach((t=>{var n=new He;n.AccessLevel=t.AccessLevel,n.Email=t.Email,n.Gender=t.Gender,n.Guid=t.Guid,n.IsAccountOnline=t.IsAccountOnline,n.Name=t.Name,n.IsActive=t.IsActive,n.IsBanned=t.IsBanned,n.Phone=t.Phone,n.Surname=t.Surname,e.push(n)})),e}return Promise.resolve([])}if((null==n?void 0:n.Status)==ce.NoData)return Promise.resolve([]);throw null===(t=r.Log)||void 0===t||t.Debug(Le.ServiceName,`Failed to retrieve users, error: ${n.Status}`),new Error(`Failed to retrieve users, error: ${n.Status}`)}))}GetUserAsync(e){return Fe(this,void 0,void 0,(function*(){var t,n;if(""===e)return Promise.resolve(null);null==e&&(e="");const s=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Be(e),2e4,!1);if(null==s||null==s.Data)return Promise.resolve(null);if(s.Status!=ce.OK)return null===(n=r.Log)||void 0===n||n.Debug(Le.ServiceName,`Failed to retrieve user, error: ${s.Status}`),Promise.resolve(null);const o=new He;return o.AccessLevel=s.Data.AccessLevel,o.Email=s.Data.Email,o.Gender=s.Data.Gender,o.Guid=s.Data.Guid,o.IsAccountOnline=s.Data.IsAccountOnline,o.Name=s.Data.Name,o.IsActive=s.Data.IsActive,o.IsBanned=s.Data.IsBanned,o.Phone=s.Data.Phone,o.Surname=s.Data.Surname,o}))}CreateUserAsync(e,t){return Fe(this,void 0,void 0,(function*(){var n;if(null!=e.Guid&&""!=e.Guid)return new De(ce.WrongData,"GuidMustBeEmpty");const s=new We;s.Name=e.Name.trim(),s.Surname=e.Surname.trim(),s.Email=e.Email.trim(),s.Password=t.trim(),s.Phone=e.Phone.trim(),s.Gender=e.Gender,s.AccessLevel=e.AccessLevel;const r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new $e(s),2e4,!1);return Fv.Get(Ge.ServiceName).ClearCache(),null==r||null==r.Status?new De(ce.FatalError,"UnknownError"):(null==r.Data&&(r.Data=""),new De(r.Status,r.Data))}))}UpdateUserAsync(e){return Fe(this,void 0,void 0,(function*(){var t;if(null==e.Guid||""==e.Guid)return new De(ce.WrongData,"GuidCannotBeEmpty");const n=new We;n.Guid=e.Guid,n.Name=e.Name.trim(),n.Surname=e.Surname.trim(),n.Email=e.Email.trim(),n.Phone=e.Phone.trim(),n.Gender=e.Gender,n.AccessLevel=e.AccessLevel;const s=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new $e(n),2e4,!1);return Fv.Get(Ge.ServiceName).ClearCache(),null==s||null==s.Status?new De(ce.FatalError,"UnknownError"):(null==s.Data&&(s.Data=""),new De(s.Status,s.Data))}))}ChangePasswordAsync(e,t){return Fe(this,void 0,void 0,(function*(){var n;if(null==e.Guid||""==e.Guid)return new De(ce.WrongData,"GuidCannotBeEmpty");const s=yield this.GetUserAsync(e.Guid);if(null==s)return new De(ce.ResourceIsNotAvailable,"CannotGetUser");const r=new We;r.Guid=e.Guid,r.Password=t,r.AccessLevel=s.AccessLevel,r.Email=s.Email;const o=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new $e(r),2e4,!1);return null==o||null==o.Status?new De(ce.FatalError,"UnknownError"):(null==o.Data&&(o.Data=""),new De(o.Status,o.Data))}))}DeleteUserAsync(e){return Fe(this,void 0,void 0,(function*(){var t,n;if(""===e)return ce.WrongData;null==e&&(e="");const s=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Ve(e),2e4,!1);return Fv.Get(Ge.ServiceName).ClearCache(),null==s||null==s.Status?ce.FatalError:(s.Status!=ce.OK&&(null===(n=r.Log)||void 0===n||n.Debug(Le.ServiceName,`Failed to delete user, error: ${s.Status}`)),s.Status)}))}GetUserProfilePictureAsync(e){return Fe(this,void 0,void 0,(function*(){if(null==e.Guid||""==e.Guid)return new De(ce.WrongData,"GuidCannotBeEmpty");const t=yield this._pictureService.GetPicturesInfoAsync();if(null!=t.Type)return t;const n=t.find((t=>"profilePicture"==t.OwnerIdentity&&t.OwnerGuid==e.Guid));if(null!=n){const e=yield this._pictureService.GetPictureAsync(n.Guid);return Fv.Get(Ge.ServiceName).ClearCache(),null!=e.Type?t:e}return new De(ce.ResourceDoesNotExists,"PictureNotFound")}))}SetUserProfilePictureAsync(e,t){return Fe(this,void 0,void 0,(function*(){if(null==e.Guid||""==e.Guid)return new De(ce.WrongData,"GuidCannotBeEmpty");let n=new ke;n.ImageType=ye.Person,n.OwnerGuid=e.Guid,n.OwnerIdentity="profilePicture",n.Base64Image=t;const s=yield this.GetUserProfilePictureAsync(e);if(Fv.Get(Ge.ServiceName).ClearCache(),s.Type==ce.ResourceDoesNotExists){const e=yield this._pictureService.AddPictureAsync(n);return e===ce.OK?new De(ce.OK,"PictureSet"):new De(e,"PictureServiceError")}if(null!=s.Type)return new De(ce.Error,"ErrorWhenTryingToCheckIfCurrentProfilePictureExists");{n.Guid=s.Guid,n.OwnerGuid=s.OwnerGuid;const e=yield this._pictureService.EditPictureAsync(n);return e===ce.OK?new De(ce.OK,"PictureSet"):new De(e,"PictureServiceError")}}))}}Le.ServiceName="UsersService";class Be extends ae{constructor(e){super(),this.Resource="/users/user",this.Method=ue.Get,this.Data=e}}class We{constructor(){this.Guid="",this.Name="",this.Surname="",this.Email="",this.Password="",this.Phone="",this.Gender=ge.Unknown,this.AccessLevel=pe.Any}}class $e extends ae{constructor(e){super(),this.Resource="/users/user",this.Method=ue.Put,this.Data=e}}class qe extends ae{constructor(){super(),this.Resource="/users/list",this.Method=ue.Get}}class Ve extends ae{constructor(e){super(),this.Resource="/users/user",this.Method=ue.Delete,this.Data=e}}class He{constructor(){this._guid="",this._cloudGuid="",this._name="",this._surname="",this._phone="",this._email="",this._isAccountOnline=!0,this._isAccountActive=!0,this._isAccountBanned=!0,this._notificationChannels=[],this._gender=ge.Unknown,this._accessLevel=pe.Any,this._localization=fe.En_Us,this._softwareVersion=""}get Guid(){return this._guid}set Guid(e){this._guid=e}get CloudGuid(){return this._cloudGuid}set CloudGuid(e){this._cloudGuid=e}get Name(){return this._name}set Name(e){this._name=e}get Surname(){return this._surname}set Surname(e){this._surname=e}get Phone(){return this._phone}set Phone(e){this._phone=e}get AccessLevel(){return this._accessLevel}set AccessLevel(e){this._accessLevel=e}get Email(){return this._email}set Email(e){this._email=e}get IsAccountOnline(){return this._isAccountOnline}set IsAccountOnline(e){this._isAccountOnline=e}get IsActive(){return this._isAccountActive}set IsActive(e){this._isAccountActive=e}get IsBanned(){return this._isAccountBanned}set IsBanned(e){this._isAccountBanned=e}get NotificationChannels(){return this._notificationChannels}set NotificationChannels(e){this._notificationChannels=e}get Gender(){return this._gender}set Gender(e){this._gender=e}get Localization(){return this._localization}set Localization(e){this._localization=e}get SoftwareVersion(){return this._softwareVersion}set SoftwareVersion(e){this._softwareVersion=e}GetUserProfilePictureAsync(){return Fv.Get(Le.ServiceName).GetUserProfilePictureAsync({Guid:this._guid})}SetUserProfilePictureAsync(e){return Fv.Get(Le.ServiceName).SetUserProfilePictureAsync({Guid:this._guid},e)}}var je=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class Ke{constructor(){this._onUserLoggedInEvent=new n,this._onUserLoggedOutEvent=new n,this._email="",this._password="",this._authToken="",this._loginTaskCompletionSource=this.CreateSessionCompletionSourceAsync(),this._alreadySubsribedToNetworkEvents=!1,this._user=null}CreateSessionCompletionSourceAsync(){return je(this,void 0,void 0,(function*(){var e;null===(e=r.Log)||void 0===e||e.Debug(Ke.ServiceName,"Creating _loginTaskCompletionSource"),this._loginTaskCompletionSource=new Promise((e=>{let t=n=>{var s;null===(s=r.Log)||void 0===s||s.Debug(Ke.ServiceName,`Logged in as ${n.Name}, completing CreateSessionCompletionSourceAsync()`),e(),this.OnUserLoggedInEvent().Unsubscribe(t)};this.OnUserLoggedInEvent().Subscribe(t)}))}))}RestoreSessionAsync(){return je(this,void 0,void 0,(function*(){var e;null===(e=r.Log)||void 0===e||e.Debug(Ke.ServiceName,`Creating RestoreSessionAsync ${this._email} ${this._password}`),void 0!==this._user&&null!==this._user&&(yield this.UserLogInAsync(this._email,this._password))}))}WaitForSessionCreationAsync(){return je(this,void 0,void 0,(function*(){return this._loginTaskCompletionSource}))}OnUserLoggedInEvent(){return this._onUserLoggedInEvent}OnUserLoggedOutEvent(){return this._onUserLoggedOutEvent}get User(){return this._user}UserLogOutAsync(){return je(this,void 0,void 0,(function*(){var e,t,n=new ae;n.Resource="/users/user/logout",n.Method=ue.Put,this._email="",this._password="",(yield Fv.Get(Pt.ServiceName).SendAndWaitForResponseAsync(n,2e4,!1)).Status==ce.OK?(this._onUserLoggedOutEvent.Invoke(this._user),null===(e=r.Log)||void 0===e||e.Debug(Ke.ServiceName,"User has been logged out.")):null===(t=r.Log)||void 0===t||t.Debug(Ke.ServiceName,"Failed to logout user!")}))}OnConnectionStateChanged(e){return je(this,void 0,void 0,(function*(){switch(e){case he.Disconnected:case he.Failed:break;case he.Connected:Fv.Get(Ke.ServiceName).RestoreSessionAsync()}}))}AuthorizeAppAsync(e){return je(this,void 0,void 0,(function*(){var t,n,s,o,i=Fv.Get(Pt.ServiceName);const a=yield i.SendAndWaitForResponseAsync(new Je(e),2e4,!1);if(a.Status==ce.OK&&null!=a.Data){this._authToken=e;var c=new He;return this._user=c,c.AccessLevel=a.Data.AccessLevel,c.Email=a.Data.Email,this._email=a.Data.Email,c.Gender=a.Data.Gender,c.Guid=a.Data.Guid,c.IsAccountOnline=a.Data.IsAccountOnline,c.Name=a.Data.Name,c.IsActive=a.Data.IsActive,c.IsBanned=a.Data.IsBanned,c.Phone=a.Data.Phone,c.Surname=a.Data.Surname,c.SoftwareVersion=a.Data.SoftwareVersion,this._alreadySubsribedToNetworkEvents||(this._alreadySubsribedToNetworkEvents=!0,i.OnConnectionStateChangedEvent().Subscribe(this.OnConnectionStateChanged)),null===(t=r.Log)||void 0===t||t.Debug(Ke.ServiceName,`Did logging in succeded?: ${a.Status==ce.OK}`),this._onUserLoggedInEvent.Invoke(this._user),c}return a.Status===ce.OperationNotPermitted?(null===(n=r.Log)||void 0===n||n.Debug(Ke.ServiceName,`App login response: ${a.Data}`),ve.AuthDisabled):a.Status===ce.ResourceDoesNotExists?(null===(s=r.Log)||void 0===s||s.Debug(Ke.ServiceName,`App login response: ${a.Data}`),ve.MethodNotSupported):(null===(o=r.Log)||void 0===o||o.Debug(Ke.ServiceName,`App login response: ${a.Data}`),ve.WrongAuthData)}))}UserLogInAsync(e,t){return je(this,void 0,void 0,(function*(){var n,s,o=Fv.Get(Pt.ServiceName);const i=yield o.SendAndWaitForResponseAsync(new Ye(e,t),2e4,!1);if(i.Status==ce.OK&&null!=i.Data){this._email=e,this._password=t;var a=new He;return this._user=a,a.AccessLevel=i.Data.AccessLevel,a.Email=i.Data.Email,a.Gender=i.Data.Gender,a.Guid=i.Data.Guid,a.IsAccountOnline=i.Data.IsAccountOnline,a.Name=i.Data.Name,a.IsActive=i.Data.IsActive,a.IsBanned=i.Data.IsBanned,a.Phone=i.Data.Phone,a.Surname=i.Data.Surname,a.SoftwareVersion=i.Data.SoftwareVersion,this._alreadySubsribedToNetworkEvents||(this._alreadySubsribedToNetworkEvents=!0,o.OnConnectionStateChangedEvent().Subscribe(this.OnConnectionStateChanged)),null===(n=r.Log)||void 0===n||n.Debug(Ke.ServiceName,`Did logging in succeded?: ${i.Status==ce.OK}`),this._onUserLoggedInEvent.Invoke(this._user),a}return null===(s=r.Log)||void 0===s||s.Debug(Ke.ServiceName,`User login response: ${i.Data}`),ve.WrongAuthData}))}GetServiceName(){return Ke.ServiceName}}Ke.ServiceName="SessionService";class ze{constructor(e,t){this.Email="",this.Password="",this.Email=e,this.Password=t}}class Je extends ae{constructor(e){super(),this.Data=e,this.Resource="/applications/app/auth",this.Method=ue.Put}}class Ye extends ae{constructor(e,t){super(),this.Data=new ze(e,t),this.Resource="/users/user/login",this.Method=ue.Put}}class Xe{constructor(e){if(this.initialCount=e,this._running=0,this._waiting=[],this.Take=()=>{if(this._waiting.length>0&&this._running<this.initialCount){this._running++;const e=this._waiting.shift();null==e||e.Resolve({Release:this.Release})}},this.AcquireAsync=()=>this._running<this.initialCount?(this._running++,Promise.resolve({Release:this.Release})):new Promise(((e,t)=>{this._waiting.push({Resolve:e,Reject:t})})),this.Release=()=>{this._running--,this.Take()},this.Purge=()=>{this._waiting.forEach((e=>{e.Reject(new Error("The semaphore was purged and as a result this task has been cancelled"))})),this._running=0,this._waiting=[]},e<1)throw new Error(`The semaphore was created with a max value of ${e} but the max value cannot be less than 1`)}}var Qe=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class Ze{constructor(){this._extensionInfoCache=new Map,this._protocolInfoCache=new Map,this._isExtensionInfoInitialized=!1,this._semaphore=new Xe(1)}GetServiceName(){return Ze.ServiceName}GetExtensionsInfoAsync(e){return Qe(this,arguments,void 0,(function*(e,t=!1){Fv.Get(s.ServiceName).Debug(Ze.ServiceName,`Getting ExtensionsInfo, data loaded from cache: ${!t}`);var n=yield this._semaphore.AcquireAsync();if(this._isExtensionInfoInitialized&&!t||(yield this.GetExtensionInfoFromControllerAsync()),n.Release(),0==[...this._extensionInfoCache.values()].length)return[];if(null!=e){const t=this._extensionInfoCache.get(e);if(null==t)throw new nt("Cannot get ExtensionsInfo, extension not found.");return[t]}return[...this._extensionInfoCache.values()]}))}GetProtocolInfoAsync(e){return Qe(this,arguments,void 0,(function*(e,t=!1,n=!1){if(Fv.Get(s.ServiceName).Debug(Ze.ServiceName,`Getting ProtocolInfo, data loaded from cache: ${!t}`),t&&(yield this.GetProtocolExtensionInfoFromControllerAsync()),0!=[...this._protocolInfoCache.values()].length||n){if(0==[...this._protocolInfoCache.values()].length)throw new nt("Cannot get ProtocolInfo, controler may return empty list of Extensions or other unknown error occurs!")}else yield this.GetProtocolInfoAsync(e,!0,!0);if(null!=e){const t=this._protocolInfoCache.get(e);if(null==t)throw new nt("Cannot get ProtocolInfo, extension not found.");return[t]}return[...this._protocolInfoCache.values()]}))}GetExtensionInfoFromControllerAsync(){return Qe(this,void 0,void 0,(function*(){const e=new et,t=yield Fv.Get(Pt.ServiceName).SendAndWaitForResponseAsync(e,16e3,!1);if(null==t||null==t.Status)throw new nt("Cannot get ExtensionsInfo from controller, controller response does not contain data!");if(t.Status!=ce.OK)throw new nt(`Cannot get ExtensionsInfo from controller! Response status: ${t.Status}`);if(null==t.Data)throw new nt("Cannot get ExtensionsInfo from controller, controller response does not contain data!");t.Data.forEach((e=>{this._extensionInfoCache.set(e.ExtensionGuid,e)})),0!=[...this._extensionInfoCache.values()].length&&(this._isExtensionInfoInitialized=!0)}))}GetProtocolExtensionInfoFromControllerAsync(){return Qe(this,void 0,void 0,(function*(){const e=new tt,t=yield Fv.Get(Pt.ServiceName).SendAndWaitForResponseAsync(e,16e3,!1);if(null==t||null==t.Status)throw new nt("Cannot get ProtocolInfo from controller, controller response does not contain data!");switch(t.Status){case ce.OK:if(null==t.Data)throw new nt("Cannot get ProtocolInfo from controller, controller response does not contain data!");t.Data.forEach((e=>{this._protocolInfoCache.set(e.PublicGuid,e)}));break;case ce.ResourceDoesNotExists:Fv.Get(s.ServiceName).Debug(Ze.ServiceName,"Cannot get ProtocolInfo from controller, controller software does not implement this yet, update controller to the newest software!");break;default:throw new nt(`Cannot get ProtocolInfo from controller! Response status: ${t.Status}`)}}))}}Ze.ServiceName="StatisticsInfoService";class et extends ae{constructor(){super(),this.Resource="/controller/extensions/",this.Method=ue.Get}}class tt extends ae{constructor(){super(),this.Resource="/controller/protocols/",this.Method=ue.Get}}class nt extends Error{constructor(e){super(e),this.message=e,this.name="CannotGetExtensions"}}var st=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class rt{GetServiceName(){return rt.ServiceName}constructor(){this._connection=null,this._session=null,this._localStorage=null,this._onEnteredConfigurationEvent=new Ce,this._onExitedConfigurationEvent=new Ce,this._onConfigurationTimeCheckedEvent=new n,this._configurationTime=new Date,this._appEnteredConfigurationMode=!1,this._didConfigurationChange=!1,this._synchronizationTaskCompletionSource=new Promise((e=>{Fv.Get(Ke.ServiceName).OnUserLoggedInEvent().Subscribe((t=>st(this,void 0,void 0,(function*(){this._didConfigurationChange=yield this.CheckIfConfigurationHasChangedAsync(),this._didConfigurationChange&&Fv.Get(Ge.ServiceName).ClearCache(),e()}))))})),this._connection=Fv.Get(Pt.ServiceName),this._session=Fv.Get(Ke.ServiceName),this._localStorage=Fv.Get(o.ServiceName),this._connection.SubscribeTo("/info/configuration/mode/entry",(e=>{Fv.Get(Ge.ServiceName).ClearCache(),this._appEnteredConfigurationMode||this._onEnteredConfigurationEvent.Invoke()})),this._connection.SubscribeTo("/info/configuration/mode/exit",(e=>{Fv.Get(Ge.ServiceName).ClearCache(),this._appEnteredConfigurationMode||this._onExitedConfigurationEvent.Invoke()}))}ImportControllerConfigurationAsync(e){return st(this,void 0,void 0,(function*(){var t,n,s;let r=yield e.text(),o=this.SplitStringBySize(r),i=new ot("");i.Status=ce.MultiDataResponseStart;let a=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(i,6e3,!1);if(void 0===a||(null==a?void 0:a.Status)!=ce.OK)return ce.Error;for(const e of o){let t=new ot(e);t.Status=ce.MultiDataResponse;let s=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(t,6e3,!1);if(void 0===s||(null==s?void 0:s.Status)!=ce.OK)return ce.Error}i.Status=ce.MultiDataResponseStop;let c=yield null===(s=this._connection)||void 0===s?void 0:s.SendAndWaitForResponseAsync(i,12e4,!1);return void 0===c||(null==c?void 0:c.Status)!=ce.OK?ce.Error:ce.OK}))}SplitStringBySize(e,t=1e5){const n=Math.floor(t/2),s=[];let r=0;for(;r<e.length;){let o=e.slice(r,r+n);for(;new Blob([o]).size>t;)o=o.slice(0,-1);s.push(o),r+=o.length}return s}GetControllerSystemTimeAsync(){return st(this,void 0,void 0,(function*(){var e;try{var t=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new pt,8e3,!1);return null==t||null==t.Status?ce.Error:t.Status!=ce.OK?t.Status:null==t.Data?ce.ResourceIsNotAvailable:new Date(t.Data)}catch(e){return Fv.Get(s.ServiceName).Error(rt.ServiceName,`Cannot get current controller time! ${e}`),ce.FatalError}}))}SetControllerSystemTimeAsync(e){return st(this,void 0,void 0,(function*(){var t;try{var n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new gt(e.toISOString()),8e3,!1);return null==n||null==n.Status?ce.Error:n.Status}catch(e){return Fv.Get(s.ServiceName).Error(rt.ServiceName,`Cannot set current controller time! ${e}`),ce.FatalError}}))}StartNtpTimeSynchronizationAsync(){return st(this,void 0,void 0,(function*(){var e;try{var t=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new ft,8e3,!1);return null==t||null==t.Status?ce.Error:t.Status}catch(e){return Fv.Get(s.ServiceName).Error(rt.ServiceName,`Cannot set current controller time! ${e}`),ce.FatalError}}))}FactoryResetAsync(e){return st(this,void 0,void 0,(function*(){var t,n;try{Fv.Get(Ge.ServiceName).ClearCache();var s=null===(n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new ct,2e3,!1))||void 0===n?void 0:n.Status;if(s==ce.OK){let t=300,n=0,s=100/t,r=setInterval((()=>{n+=s,e(parseFloat(n.toPrecision(1)))}),1e3);return yield oe.Delay(1e3*t),Fv.Get(Ge.ServiceName).ClearCache(),clearInterval(r),ce.OK}return s}catch(e){return ce.FatalError}}))}RollbackLastUpdateAsync(e){return st(this,void 0,void 0,(function*(){var t,n;try{Fv.Get(Ge.ServiceName).ClearCache();var s=null===(n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new ut,2e3,!1))||void 0===n?void 0:n.Status;if(s==ce.OK){let t=420,n=0,s=100/t,r=setInterval((()=>{n+=s,e(parseFloat(n.toPrecision(1)))}),1e3);return yield oe.Delay(1e3*t),Fv.Get(Ge.ServiceName).ClearCache(),clearInterval(r),ce.OK}return s}catch(e){return ce.FatalError}}))}RestartControllerAsync(e){return st(this,void 0,void 0,(function*(){var t,n;try{Fv.Get(Ge.ServiceName).ClearCache();var s=null===(n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new at,2e3,!1))||void 0===n?void 0:n.Status;if(s==ce.OK){let t=240,n=0,s=100/t,r=setInterval((()=>{n+=s,e(parseFloat(n.toPrecision(1)))}),1e3);return yield oe.Delay(1e3*t),Fv.Get(Ge.ServiceName).ClearCache(),clearInterval(r),ce.OK}return s}catch(e){return ce.FatalError}}))}DidCofigurationChangeAsync(){return st(this,void 0,void 0,(function*(){return yield this._synchronizationTaskCompletionSource,Promise.resolve(this._didConfigurationChange)}))}GetLastKnownConfigurationChangeTime(){var e;const t=null===(e=this._localStorage)||void 0===e?void 0:e.Read(this.GetServiceName(),"last_configuration_time");return null!=t?new Date(t):new Date}SaveLastConfigurationChangeTime(e){var t;null===(t=this._localStorage)||void 0===t||t.Save(this.GetServiceName(),"last_configuration_time",e.toString())}EnterConfigurationModeAsync(){return st(this,void 0,void 0,(function*(){var e;this._appEnteredConfigurationMode=!0,Fv.Get(Ge.ServiceName).ClearCache(),yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new lt,2e4,!1)}))}ExitConfigurationModeAsync(){return st(this,void 0,void 0,(function*(){var e;this._appEnteredConfigurationMode=!0,Fv.Get(Ge.ServiceName).ClearCache(),yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new dt,2e4,!1),Fv.Get(Ge.ServiceName).ClearCache(),this._appEnteredConfigurationMode=!1}))}OnEnteredConfigurationEvent(){return this._onEnteredConfigurationEvent}OnExitedConfigurationEvent(){return this._onExitedConfigurationEvent}OnConfigurationTimeCheckedEvent(){return this._onConfigurationTimeCheckedEvent}GetLastConfigurationChangeTimeAsync(){return st(this,void 0,void 0,(function*(){var e;const t=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new ht,2e4,!1);if(null==t||(null==t?void 0:t.Status)!=ce.OK)throw new Error("Failed to get last configuration change time");return this._configurationTime=new Date(t.Data),this._configurationTime}))}CheckIfConfigurationHasChangedAsync(){return st(this,void 0,void 0,(function*(){const e=yield this.GetLastConfigurationChangeTimeAsync();return this.GetLastKnownConfigurationChangeTime().toString()!=e.toString()&&(this.SaveLastConfigurationChangeTime(e),this._onConfigurationTimeCheckedEvent.Invoke(e),Fv.Get(Ge.ServiceName).ClearCache(),!0)}))}CanExportOrImportControllerConfigurationAsync(){return st(this,void 0,void 0,(function*(){try{let e=yield Fv.Get(Ze.ServiceName).GetExtensionsInfoAsync(),t=Fv.Get(Ke.ServiceName).User;return null!=t&&null!=t.AccessLevel&&t.AccessLevel>=pe.Admin&&e.any((e=>"f4f0f066-7c43-46c6-a0bd-aedf93903dc0"==e.ExtensionGuid))}catch(e){return!1}}))}ExportControllerConfigurationAsync(){return st(this,void 0,void 0,(function*(){var e;let t=[];yield null===(e=this._connection)||void 0===e?void 0:e.SendAndHandleResponseAsync(new it,3e4,(e=>{switch(e.Status){case ce.MultiDataResponseStart:break;case ce.MultiDataResponse:null!=e.Data&&void 0!==e.Data&&t.push(e.Data);case ce.MultiDataResponseStop:}}),!0);let n=JSON.stringify(JSON.parse(t.join("")),null,2);return console.log(n),Fv.ExportStringAsFileToDownload(this.GetCurrentTimestampedFilename(),n)}))}GetCurrentTimestampedFilename(){var e,t;const n=new Date,s=n.getHours().toString().padStart(2,"0"),r=n.getMinutes().toString().padStart(2,"0"),o=n.getDate().toString().padStart(2,"0"),i=(n.getMonth()+1).toString().padStart(2,"0"),a=n.getFullYear().toString();return`${null===(t=null===(e=this._connection)||void 0===e?void 0:e.GetAuthorizationInfo())||void 0===t?void 0:t.SerialNumber}_${s}-${r}-${o}-${i}-${a}-config.cexp`}}rt.ServiceName="ControllerConfigurationService";class ot extends ae{constructor(e){super(),this.Resource="/configuration/backup/import",this.Method=ue.Put,this.Data=e}}class it extends ae{constructor(){super(),this.Resource="/configuration/backup/export",this.Method=ue.Get}}class at extends ae{constructor(){super(),this.Resource="/controller/restart",this.Method=ue.Post}}class ct extends ae{constructor(){super(),this.Resource="/controller/factory_reset",this.Method=ue.Post}}class ut extends ae{constructor(){super(),this.Resource="/controller/backups/restore/previous",this.Method=ue.Post}}class lt extends ae{constructor(){super(),this.Resource="/system/configuration/mode/entry",this.Method=ue.Put}}class dt extends ae{constructor(){super(),this.Resource="/system/configuration/mode/exit",this.Method=ue.Put}}class ht extends ae{constructor(){super(),this.Resource="/system/configuration/change/time",this.Method=ue.Get}}class pt extends ae{constructor(){super(),this.Resource="/system/time",this.Method=ue.Get}}class gt extends ae{constructor(e){super(),this.Resource="/system/time",this.Method=ue.Put,this.Data=e}}class ft extends ae{constructor(){super(),this.Resource="/system/time/ntp/update",this.Method=ue.Put}}var vt,mt,yt,wt,St,At,_t,Ct,Tt,Dt,kt,Gt,bt,Nt,Et,It,Rt=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class Pt{constructor(){this._logPackets=!1,this._pingInterval=5e3,this._disconnectedOnPurpose=!1,this._defaultPacketsBrokerAddress="br1.tr7.pl",this._serversBrokerAddress="https://broker.tr7.pl",this._serversBrokerAddressList=["https://broker.tr7.pl","https://dev-brokers.lavva.tech"],this._allBrokersChecked=!1,this._address="br1.tr7.pl",this._isEstabilished=!1,this._timeout=1e4,this._dataReceivedEvent=new n,this._pongReceivedEvent=new Ce,this._authorizationReceivedEvent=new n,this._registrationReceivedEvent=new n,this._connectionStateChangedEvent=new n,this._errorOccuredEvent=new n,this._log=Fv.Get(s.ServiceName),this._controllerConfiguration=null,this._cache=null,this._session=null,this._packetsBrokerServers=["br1.tr7.pl","br1.exala.pl"],this._lastReceivedPacketTime=Date.now(),this._connectedAtLeastOnce=!1}SubscribeTo(e,t){let n=n=>{n.Resource===e&&t(n)};return this.OnDataReceivedEvent().Subscribe(n),()=>this.OnDataReceivedEvent().Unsubscribe(n)}GetControllerSerialNumber(){return this._serialId}GetControllerPin(){return this._PIN}GetServiceName(){return Pt.ServiceName}EnablePacketsLogging(){this._logPackets=!0}DisablePacketsLogging(){this._logPackets=!1}InitializeConnection(){if(this._controllerConfiguration=Fv.Get(rt.ServiceName),this._cache=Fv.Get(Ge.ServiceName),this._session=Fv.Get(Ke.ServiceName),this._connection){try{this._connection.stop()}catch(e){}this._connection=void 0}if(!this._address)throw new Error("Domain is not set");if(!this._serialId)throw new Error("SerialId is not set");if(!this._PIN)throw new Error("PIN is not set");this._connection=(new se).withUrl(`https://${this._address}/broker`).build(),this._dataReceivedEvent.Subscribe((e=>{this._lastReceivedPacketTime=Date.now()})),setInterval((()=>Rt(this,void 0,void 0,(function*(){yield this.PingControllerAsync()}))),this._pingInterval)}GetAuthorizationInfo(){return null!=this._serialId&&null!=this._PIN?new _e(this._serialId,this._PIN):null}SetServersBrokerAddress(e){this._serversBrokerAddress=e}SetDefaultPacketsBrokerAddress(e){this._defaultPacketsBrokerAddress=e,this._address=e}GetServerAddressAsync(){return Rt(this,void 0,void 0,(function*(){try{let e=yield fetch(`${this._serversBrokerAddress}/api/connections/broker/whichserver/${this._serialId}`);if(200===e.status){let t=yield e.text();return t?(this._log.Debug(Pt.ServiceName,`Got server address: ${t}`),t):(this._log.Error(Pt.ServiceName,`Failed to get server address, status: ${e.status}`),null)}return this._allBrokersChecked?(this._allBrokersChecked=!1,null):204===e.status?(this.swapBrokersAsync(!1),this.GetServerAddressAsync()):(this._log.Error(Pt.ServiceName,`Failed to get server address, status: ${e.status}`),null)}catch(e){return this._log.Error(Pt.ServiceName,e),null}}))}ConnectAsync(e){return Rt(this,void 0,void 0,(function*(){return this._connectedAtLeastOnce=!1,this._address=e,yield this.connectAsync()}))}AuthorizeAsync(e){return new Promise(((t,n)=>Rt(this,void 0,void 0,(function*(){var n;let s=0,r=e=>{window.clearTimeout(s),this._log.Debug(Pt.ServiceName,`Got authorization result: ${e}`),this._connectedAtLeastOnce=!0,t(e)};s=window.setTimeout((()=>{window.clearTimeout(s),this._authorizationReceivedEvent.Unsubscribe(r),t(!1)}),2e3),this._log.Debug(Pt.ServiceName,`Authorizing to cloud using: ${e.SerialNumber} PIN: ${e.PIN}`),this._authorizationReceivedEvent.Subscribe(r),yield null===(n=this._connection)||void 0===n?void 0:n.send("AuthorizeTo",e.SerialNumber,e.PIN)}))))}ConnectAndAuthorizeAsync(e){return Rt(this,void 0,void 0,(function*(){this._connectedAtLeastOnce=!1,Fv.WorksInContextOf=e.SerialNumber,this._serialId=e.SerialNumber,this._PIN=e.PIN;var t=yield this.GetServerAddressAsync();if(t&&null!=t){this._log.Debug(Pt.ServiceName,`Got packets broker address: ${t}`),this.SetDefaultPacketsBrokerAddress(t);let s=yield this.connectAsync();if(s!=de.Connected)return s;var n=yield this.AuthorizeAsync(e);if(!n){if(this._connectedAtLeastOnce=!1,yield this.swapBrokersAsync(),!this._allBrokersChecked)return this.ConnectAndAuthorizeAsync(e);this._allBrokersChecked=!1}return n&&(this._connectedAtLeastOnce=!0),n?de.Connected:de.AuthorizationFailed}{let t=de.ControllerIsNotConnected;this._log.Warning(Pt.ServiceName,"Server did not return packets broker address, trying to connect to known brokers.");for(let n of this._packetsBrokerServers){this._log.Warning(Pt.ServiceName,`Testing connection to ${n}`),this.SetDefaultPacketsBrokerAddress(n);try{yield this.DisconnectAsync()}catch(e){}this._log.Warning(Pt.ServiceName,`Connecting to server: ${n}`);let s=yield this.connectAsync();if(this._log.Warning(Pt.ServiceName,`Connection result: ${s}`),s==de.Connected){if(yield this.AuthorizeAsync(e))return t=de.Connected,this._connectedAtLeastOnce=!0,t;this._log.Warning(Pt.ServiceName,`Failed to authorize in ${n}`)}}return t}}))}swapBrokersAsync(){return Rt(this,arguments,void 0,(function*(e=!0){e&&(yield this.DisconnectAsync());var t=this._serversBrokerAddressList.lastIndexOf(this._serversBrokerAddress);t+1<this._serversBrokerAddressList.length?(this._serversBrokerAddress=this._serversBrokerAddressList[t+1],this._log.Debug(`Changing address of next broker from: ${this._serversBrokerAddressList[t]} to: ${this._serversBrokerAddressList[t+1]}`)):(this._log.Debug(`All brokers checked, changing address to first one: ${this._serversBrokerAddressList[0]}`),this._allBrokersChecked=!0,this._serversBrokerAddress=this._serversBrokerAddressList[0])}))}connectAsync(){return Rt(this,void 0,void 0,(function*(){var e,t,n,s,r,o,i,a,c;if(de.FailedToConnect,!this._address)return Promise.resolve(de.ControllerIsNotConnected);this._disconnectedOnPurpose&&(this._disconnectedOnPurpose=!1),this._connectionStateChangedEvent,this.InitializeConnection(),null===(e=this._connection)||void 0===e||e.onclose((()=>Rt(this,void 0,void 0,(function*(){var e,t;if(this._disconnectedOnPurpose?this._log.Info(Pt.ServiceName,"Connection closed on demand."):this._log.Error(Pt.ServiceName,"Connection closed"),Fv.Get(Ke.ServiceName).CreateSessionCompletionSourceAsync(),this.FireConnectionStateChanged(),(null===(e=this._connection)||void 0===e?void 0:e.state)===T.Disconnected&&!this._disconnectedOnPurpose)return yield null===(t=this._connection)||void 0===t?void 0:t.start(),null!=this._connection&&(yield this.AuthorizeAsync(new _e(this._serialId,this._PIN)))?(this._log.Info(Pt.ServiceName,"Reconnected from onClose"),this.FireConnectionStateChanged()):de.FailedToConnect})))),null===(t=this._connection)||void 0===t||t.onreconnected((()=>Rt(this,void 0,void 0,(function*(){if(yield this.AuthorizeAsync(new _e(this._serialId,this._PIN)))return this._log.Info(Pt.ServiceName,"Reconnected from onreconnected"),this.FireConnectionStateChanged()})))),null===(n=this._connection)||void 0===n||n.onreconnecting((()=>(this._log.Warning(Pt.ServiceName,"Reconnecting..."),this.FireConnectionStateChanged()))),yield null===(s=this._connection)||void 0===s?void 0:s.start(),null===(r=this._connection)||void 0===r||r.on("Pong",(()=>{this._log.Debug(Pt.ServiceName,"Pong received <-"),this._pongReceivedEvent.Invoke()})),null===(o=this._connection)||void 0===o||o.on("Registration",(e=>{var t;null===(t=this._registrationReceivedEvent)||void 0===t||t.Invoke(e)})),null===(i=this._connection)||void 0===i||i.on("Authorization",(e=>{var t;null===(t=this._authorizationReceivedEvent)||void 0===t||t.Invoke(e)})),null===(a=this._connection)||void 0===a||a.on("SendError",((e,t)=>Rt(this,void 0,void 0,(function*(){e.startsWith("NotAuthorized:")?(this._log.Error(Pt.ServiceName,"Failed to authorize!"),yield this.AuthorizeAsync(new _e(this._serialId,this._PIN))):(this._log.Error(Pt.ServiceName,`Server returned error: ${e} ${t}`),this._errorOccuredEvent.Invoke([e,t]))}))));let u=this._dataReceivedEvent;return null===(c=this._connection)||void 0===c||c.on("Data",((e,t)=>{const n=JSON.parse(t);(this._logPackets||!0===window.packets)&&this._log.Debug(Pt.ServiceName,`Received data:\n${JSON.stringify(n,null,2)}`),u.Invoke(n)})),null!=this._connection?this.FireConnectionStateChanged():de.FailedToConnect}))}FireConnectionStateChanged(){var e;const t=this._connectionStateChangedEvent;switch(null===(e=this._connection)||void 0===e?void 0:e.state){case T.Connected:return t.Invoke(he.Connected),de.Connected;case T.Connecting:return t.Invoke(he.Connecting),de.Connected;case T.Disconnected:if(this._connectedAtLeastOnce)return t.Invoke(he.Disconnected),de.FailedToConnect;break;case T.Disconnecting:if(this._connectedAtLeastOnce)return t.Invoke(he.Disconnecting),de.FailedToConnect;break;case T.Reconnecting:return t.Invoke(he.Reconnecting),de.FailedToConnect}return de.FailedToConnect}DisconnectAsync(){return Rt(this,void 0,void 0,(function*(){var e;this._disconnectedOnPurpose=!0,yield null===(e=this._connection)||void 0===e?void 0:e.stop()}))}IsConnected(){var e;return(null===(e=this._connection)||void 0===e?void 0:e.state)===T.Connected}SendAndWaitForResponseAsync(e,t,n,s=!0){return this.SendAndWaitForResponseWithRepeatAsync(e,t,n,s)}SendAndWaitForResponseWithRepeatAsync(e,t,n){return Rt(this,arguments,void 0,(function*(e,t,n,s=!0,r=!0){var o,i,a;if(e.Method===ue.Get&&n&&!(yield null===(o=this._controllerConfiguration)||void 0===o?void 0:o.DidCofigurationChangeAsync())){let t=null===(i=this._cache)||void 0===i?void 0:i.GetCache(e);if(null!==t)return Promise.resolve(t)}let c=0;const u=Date.now();if(!this.IsConnected())throw new Error("Connection is not established");return"/users/user/login"!==e.Resource&&(yield null===(a=this._session)||void 0===a?void 0:a.WaitForSessionCreationAsync()),new Promise(((o,i)=>Rt(this,void 0,void 0,(function*(){let a=i=>Rt(this,void 0,void 0,(function*(){var l,d,h,p;if((null==i?void 0:i.TransactionId)==e.TransactionId){window.clearTimeout(c),this._dataReceivedEvent.Unsubscribe(a);const g=Date.now()-u;r&&this._log.Debug(Pt.ServiceName,`Received response for: ${null==i?void 0:i.Resource} ${null==i?void 0:i.Method} id: ${null==i?void 0:i.TransactionId} in ${g}ms`),e.Method===ue.Get&&n&&(null===(l=this._cache)||void 0===l||l.Cache(i)),!n&&(null==i?void 0:i.Status)===ce.UserIsNotLoggedIn&&s&&((null===(d=this._session)||void 0===d?void 0:d.OnUserLoggedOutEvent()).Invoke(null===(h=this._session)||void 0===h?void 0:h.User),yield null===(p=this._session)||void 0===p?void 0:p.RestoreSessionAsync(),o(yield this.SendAndWaitForResponseWithRepeatAsync(e,t,n,!1,r))),o(i)}}));if(this._dataReceivedEvent.Subscribe(a),c=window.setTimeout((()=>{this._dataReceivedEvent.Unsubscribe(a);let t=`Response timeout, resource: ${e.Resource} method: ${e.Method} transaction id: ${e.TransactionId}`;this._log.Error(Pt.ServiceName,t),i(new p(t))}),t),!(yield this.SendAsync(e,r))){let t=`Failed to send request, resource: ${e.Resource} method: ${e.Method} transaction id: ${e.TransactionId}`;i(new Error(t))}}))))}))}SendAndHandleResponseAsync(e,t,n){return Rt(this,arguments,void 0,(function*(e,t,n,s=!0){var r;let o=0;const i=Date.now();if(!this.IsConnected())throw new Error("Connection is not established");return"/users/user/login"!==e.Resource&&(yield null===(r=this._session)||void 0===r?void 0:r.WaitForSessionCreationAsync()),new Promise(((r,a)=>Rt(this,void 0,void 0,(function*(){const c=()=>window.setTimeout((()=>{this._dataReceivedEvent.Unsubscribe(u);let t=`Response timeout, resource: ${e.Resource} method: ${e.Method} transaction id: ${e.TransactionId}`;this._log.Error(Pt.ServiceName,t),a(new p(t))}),t);let u=l=>Rt(this,void 0,void 0,(function*(){var d,h,p;if((null==l?void 0:l.TransactionId)==e.TransactionId){window.clearTimeout(o);const g=Date.now()-i;switch((s||!0===window.packets)&&this._log.Debug(Pt.ServiceName,`Received response for: ${null==l?void 0:l.Resource} ${null==l?void 0:l.Method} id: ${null==l?void 0:l.TransactionId} in ${g}ms`),(null==l?void 0:l.Status)===ce.UserIsNotLoggedIn&&(this._dataReceivedEvent.Unsubscribe(u),(null===(d=this._session)||void 0===d?void 0:d.OnUserLoggedOutEvent()).Invoke(null===(h=this._session)||void 0===h?void 0:h.User),yield null===(p=this._session)||void 0===p?void 0:p.RestoreSessionAsync(),r(yield this.SendAndHandleResponseAsync(e,t,n,s))),null==l?void 0:l.Status){case ce.MultiDataResponseStart:case ce.MultiDataResponse:n(l),o=c();break;case ce.MultiDataResponseStop:n(l),this._dataReceivedEvent.Unsubscribe(u),r();break;default:let t=`Failed to process MultiDataResponse - recived incorrect response status: ${null==l?void 0:l.Status} method: ${e.Method} transaction id: ${e.TransactionId}\n make sure that the requested endpoint uses MultiDataResponse, otherwise use SendAndWaitForResponseAsync<T> method.`;a(new Error(t))}}}));if(this._dataReceivedEvent.Subscribe(u),o=c(),!(yield this.SendAsync(e,s))){let t=`Failed to send request, resource: ${e.Resource} method: ${e.Method} transaction id: ${e.TransactionId}`;a(new Error(t))}}))))}))}PingControllerAsync(){return Rt(this,void 0,void 0,(function*(){var e;if((null===(e=this._connection)||void 0===e?void 0:e.state)!==T.Connected)return!1;if(null!==this._lastReceivedPacketTime&&Date.now()-this._lastReceivedPacketTime<this._pingInterval)return!1;let t=new ae;return t.Resource="/system/ping",t.Method=ue.Get,yield this.SendAndWaitForResponseAsync(t,2e3,!1,!1).then((()=>!0)).catch((()=>!1))}))}SendAsync(e,t=!1){if(!this.IsConnected())throw new Error("Connection is not established");return new Promise((n=>{var s;this._logPackets||!0===window.packets?this._log.Debug(Pt.ServiceName,`Sent DataFrame ${e.Resource} ${e.Method} transaction id: ${e.TransactionId} data:\n${JSON.stringify(e,null,2)}`):t&&this._log.Debug(Pt.ServiceName,`Sent DataFrame ${e.Resource} ${e.Method} transaction id: ${e.TransactionId}`),null===(s=this._connection)||void 0===s||s.invoke("SendTo",this._serialId,e).then((()=>{n(!0)})).catch((e=>{this._log.Error(Pt.ServiceName,`${e}`),n(!1)}))}))}OnDataReceivedEvent(){return this._dataReceivedEvent}OnConnectionStateChangedEvent(){return this._connectionStateChangedEvent}OnErrorOccuredEvent(){return this._errorOccuredEvent}}Pt.ServiceName="ExalusConnectionService",function(e){e[e.NoTasksExecuting=0]="NoTasksExecuting",e[e.ExecutingTasks=1]="ExecutingTasks"}(vt||(vt={})),(Gt=mt||(mt={}))[Gt.Default=0]="Default",Gt[Gt.Monostable=1]="Monostable",Gt[Gt.Bistable=2]="Bistable",Gt[Gt.Gate=3]="Gate",Gt[Gt.Gateway=4]="Gateway",function(e){e[e.None=0]="None",e[e.OnOff=1]="OnOff",e[e.OnOffLights=2]="OnOffLights",e[e.OnOffWithDelay=3]="OnOffWithDelay",e[e.GateSwitchState=4]="GateSwitchState",e[e.GatePulse=5]="GatePulse",e[e.GateOpenClose=6]="GateOpenClose",e[e.GatewayOpenClose=7]="GatewayOpenClose",e[e.GatewayPulse=8]="GatewayPulse",e[e.Monostable=9]="Monostable",e[e.Dimmer=10]="Dimmer",e[e.Blind=11]="Blind",e[e.Roller=12]="Roller",e[e.TemperatureSensor=13]="TemperatureSensor",e[e.BrightnessSensor=14]="BrightnessSensor",e[e.HumiditySensor=15]="HumiditySensor",e[e.PowerMeter=16]="PowerMeter",e[e.RGBLight=17]="RGBLight",e[e.RGBWLight=18]="RGBWLight",e[e.LightsWarmth=19]="LightsWarmth",e[e.TemperatureControl=20]="TemperatureControl",e[e.BlindsWithPrecisePosition=21]="BlindsWithPrecisePosition",e[e.MovementSensor=21]="MovementSensor",e[e.SimpleRemote=22]="SimpleRemote",e[e.BlindsRemote=23]="BlindsRemote",e[e.DistanceSensor=24]="DistanceSensor",e[e.Multisensor=25]="Multisensor",e[e.IOTransmitter=26]="IOTransmitter",e[e.DoorOpenClose=27]="DoorOpenClose",e[e.WindSensor=28]="WindSensor",e[e.BatterySensor=29]="BatterySensor",e[e.PressureSensor=30]="PressureSensor"}(yt||(yt={}));class Ot{constructor(){this._type=St.Unknown,this._interfaceType=""}get Type(){return this._type}get InterfaceType(){return this._interfaceType}set InterfaceType(e){this._interfaceType=e,this._type=e}}(bt=wt||(wt={}))[bt.Unknown=0]="Unknown",bt[bt.BlindMotor=1]="BlindMotor",bt[bt.DinModule=2]="DinModule",bt[bt.DinModuleWithAntenna=3]="DinModuleWithAntenna",bt[bt.Remote=4]="Remote",bt[bt.RemoteForBlinds=5]="RemoteForBlinds",bt[bt.RemoteForFacadeBlinds=6]="RemoteForFacadeBlinds",bt[bt.MovementSensor=7]="MovementSensor",bt[bt.TemperatureSensor=8]="TemperatureSensor",bt[bt.HumiditySensor=9]="HumiditySensor",bt[bt.DinPowerMeter=10]="DinPowerMeter",bt[bt.Intercom=11]="Intercom",bt[bt.SecurityCamera=12]="SecurityCamera",bt[bt.Multisensor=13]="Multisensor",bt[bt.FloodSensor=14]="FloodSensor",bt[bt.FlushMountedReceiver=15]="FlushMountedReceiver",bt[bt.FlushMountedBlindController=16]="FlushMountedBlindController",bt[bt.FlushMountedDimmer=17]="FlushMountedDimmer",bt[bt.FlushMountedRelay=18]="FlushMountedRelay",bt[bt.FlushMountedGateController=19]="FlushMountedGateController",bt[bt.WindSensor=20]="WindSensor",bt[bt.FlushMountedGateAndGatewayController=21]="FlushMountedGateAndGatewayController",bt[bt.AirPressureSensor=22]="AirPressureSensor",bt[bt.LightBrightnessSensor=23]="LightBrightnessSensor",bt[bt.ReedSensor=24]="ReedSensor",bt[bt.FlushMountedTransceiver=25]="FlushMountedTransceiver",bt[bt.FlushMountedRGBLightController=26]="FlushMountedRGBLightController",bt[bt.WallMountedThermoregulator=27]="WallMountedThermoregulator",bt[bt.ImpulseCounter=28]="ImpulseCounter",bt[bt.FlushMountedFacadeController=29]="FlushMountedFacadeController",bt[bt.WallMountedGateController=30]="WallMountedGateController",bt[bt.WallMountedRGBLightController=31]="WallMountedRGBLightController",bt[bt.WallMountedDimmer=32]="WallMountedDimmer",bt[bt.WallMountedRemote=33]="WallMountedRemote",bt[bt.DinRelay=34]="DinRelay",bt[bt.DinReceiver=35]="DinReceiver",bt[bt.DinBlindController=36]="DinBlindController",bt[bt.DinTransceiver=37]="DinTransceiver",bt[bt.SocketPlugIn=38]="SocketPlugIn",bt[bt.WallMountedRelay=39]="WallMountedRelay",bt[bt.Retransmitter=40]="Retransmitter",function(e){e.Unknown="Unknown",e.SetBlindPosition="IBlindPosition",e.SetBlindPositionSimple="IBlindPositionSimple",e.SetBlindMicroventilation="IMicroventilation",e.TurnOff="IChannelOff",e.TurnOn="IChannelOn",e.TurnOnWithTime="IChannelOnWithTime",e.TogleState="IChannelSwitchState",e.SetLightBrightnessDynamicly="IDynamicLightBrightness",e.SetLightBrightness="ILightBrightness",e.SetLightColor="ILightColor",e.SetLightTemperature="ILightTemperature",e.PairDevice="IPair",e.UnpairDevice="IUnpair",e.IdentifyDevice="IIdentifyDevice",e.GetChannelsState="IGetDeviceState",e.GetPowerMeasurements="IGetPowerMeasurements",e.GetAvailableData="IGetAvailableData",e.MultipleDataRequest="IMultipleDataRequest",e.SetBlindOpenCloseTime="ISetBlindOpenCloseTime",e.SetTemperature="IChangeTemperature",e.SetGatePosition="IGatePosition",e.SetGatewayPosition="IGatewayPosition",e.ChangeGatePositionPulse="IGatePulse",e.ChangeGatewayPositionPulse="IGatewayPulse",e.SetFacadePosition="IFacadePosition",e.GetFacadeType="IGetFacadeType",e.LightRGBW="ILightRGBW",e.PreciseGateControl="IPreciseGateControl"}(St||(St={}));class Ut{constructor(){this._type=At.Unknown,this._interfaceType=""}get Type(){return this._type}get InterfaceType(){return this._interfaceType}set InterfaceType(e){this._interfaceType=e,this._type=e}}!function(e){e.Unknown="Unknown",e.BatteryState="IBatteryState",e.BinarySensorState="IBinarySensor",e.BlindOpenCloseTime="IBlindOpenCloseTime",e.BlindPosition="IBlindPosition",e.BlindRemoteButtonState="IBlindsControlButton",e.BlindErrorState="IBlindError",e.MeasuredBrightness="IBrightness",e.RemoteButtonState="IButtonState",e.ChannelOnOffState="IChannelOnOff",e.IntercomState="IIntercom",e.DoorBellState="IDoorBell",e.FacadeRemoteButtonState="IFacadeControlButton",e.FacadePosition="IFacadeState",e.FacadeType="IFacadeType",e.FloodSensorState="IFloodSensor",e.GatePosition="IGatePosition",e.GatewayPosition="IGatewayPosition",e.GateControllerHealth="IGateControllerHealth",e.HumiditySensorState="IHumiditySensor",e.LightBrightness="ILightBrightness",e.LightColor="ILightColor",e.LightWarmth="ILightTemperature",e.LightTreshold="ILightTreshold",e.MovementSensorState="IMovementSensor",e.OnlineCamera="IOnlineCamera",e.OvercurrentProtectionState="IOvercurrentProtection",e.OvercurrentProtectionThreshold="IOvercurrentProtectionThreshold",e.ReedState="IReedState",e.SignalStrength="ISignalStrength",e.SmokeSensorState="ISmokeSensor",e.MeasuredTemperature="ITemperature",e.VibrationSensorState="IVibrationSensor",e.MeasuredWindSpeed="IWindSpeed",e.WindThreshold="IWindThreshold",e.MeasuredEnergy="IEnergy",e.MeasuredDistance="DistanceSensor",e.BlindCalibration="BlindCalibration",e.ConfigurationState="ConfigurationState",e.CurrentWindThreshold="CurrentWindThreshold",e.CurrentLightThreshold="CurrentLightThreshold",e.WindSpeedState="WindSpeed",e.TamperProtectionState="ITamperProtection",e.PressureSensorState="IPressureSensor",e.LightRGBWState="ILightRGBW"}(At||(At={})),(It=_t||(_t={}))[It.NotResponding=0]="NotResponding",It[It.Working=1]="Working",It[It.Broken=2]="Broken",It[It.FirmareUpgradeMode=3]="FirmareUpgradeMode",(Et=Ct||(Ct={}))[Et.TwoWay=1]="TwoWay",Et[Et.OneWay=2]="OneWay",Et[Et.ConditionalTwoWay=3]="ConditionalTwoWay",(Nt=Tt||(Tt={}))[Nt.Unknown=-1]="Unknown",Nt[Nt.Multipurpose=0]="Multipurpose",Nt[Nt.Controller=1]="Controller",Nt[Nt.Driver=2]="Driver",Nt[Nt.Receiver=3]="Receiver",Nt[Nt.Remote=4]="Remote",Nt[Nt.Sensor=5]="Sensor",Nt[Nt.Scene=6]="Scene";class Mt{constructor(){this.DeviceGuid="",this.Channel=0,this.Status=vt.NoTasksExecuting}}!function(e){e[e.Unknown=0]="Unknown",e[e.Executed=1]="Executed",e[e.ResponseTimeout=2]="ResponseTimeout",e[e.TaskRepeatedAndExecuted=3]="TaskRepeatedAndExecuted",e[e.TaskRepeatedResponseTimeout=4]="TaskRepeatedResponseTimeout",e[e.FlowControlNotAvailable=5]="FlowControlNotAvailable",e[e.ExecutionError=6]="ExecutionError"}(Dt||(Dt={})),function(e){e[e.ControllerResponseTimeout=-4]="ControllerResponseTimeout",e[e.DeviceNotFound=-3]="DeviceNotFound",e[e.DeviceResponseTimeout=-2]="DeviceResponseTimeout",e[e.Failed=-1]="Failed",e[e.Unknown=0]="Unknown",e[e.Executed=1]="Executed"}(kt||(kt={}));class xt{constructor(){this.Device=null,this.Channel=0,this.Task=null,this.Result=kt.Unknown}}var Ft,Lt,Bt,Wt,$t,qt,Vt,Ht,jt,Kt,zt,Jt,Yt,Xt,Qt,Zt,en,tn,nn,sn,rn,on,an,cn,un,ln,dn,hn,pn,gn,fn;class vn{constructor(){this._type="",this._data=null,this._typeAsEnum=At.Unknown,this._serializedDataWithoutTime=""}get Data(){return this._data}set Data(e){this._data=e;let{Time:t}=e,n=function(e,t){var n={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(n[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(s=Object.getOwnPropertySymbols(e);r<s.length;r++)t.indexOf(s[r])<0&&Object.prototype.propertyIsEnumerable.call(e,s[r])&&(n[s[r]]=e[s[r]])}return n}(e,["Time"]);this._serializedDataWithoutTime=JSON.stringify(n)}get Type(){return this._type}set Type(e){this._type=e}get TypeAsEnum(){return this._typeAsEnum}set TypeAsEnum(e){this._typeAsEnum=e}get StatesComparisonData(){return this._serializedDataWithoutTime}}(fn=Ft||(Ft={}))[fn.Confident=0]="Confident",fn[fn.Unconfident=1]="Unconfident";class mn extends vn{constructor(e){super(),this.TypeAsEnum=At.ChannelOnOffState,this.Type="ChannelOnOffState",this.Data=e.state}}class yn{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.State=Lt.Unknown,this.Time=""}}!function(e){e[e.On=0]="On",e[e.Off=1]="Off",e[e.Unknown=2]="Unknown"}(Lt||(Lt={})),function(e){e[e.Idle=0]="Idle",e[e.IncomingCall=1]="IncomingCall",e[e.AnsweringCall=2]="AnsweringCall",e[e.Busy=3]="Busy",e[e.NoAnswerToCall=4]="NoAnswerToCall",e[e.Unknown=5]="Unknown"}(Bt||(Bt={}));class wn extends vn{constructor(e){super(),this.TypeAsEnum=At.OnlineCamera,this.Type="OnlineCameraState",this.Data=e.state}}class Sn extends vn{constructor(e){super(),this.TypeAsEnum=At.DoorBellState,this.Type="DoorBellState",this.Data=e.state}}class An{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.State=Wt.Relased,this.Time=""}}!function(e){e[e.Pressed=0]="Pressed",e[e.Relased=1]="Relased",e[e.PressedAndRelased=2]="PressedAndRelased"}(Wt||(Wt={}));class _n extends vn{constructor(e){super(),this.TypeAsEnum=At.ReedState,this.Type="ReedState",this.Data=e.state}}class Cn{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.State=!1,this.Time=""}}class Tn extends vn{constructor(e){super(),this.TypeAsEnum=At.BlindPosition,this.Type="BlindPostionState",this.Data=e.state}GetBlindStatus(){switch(this.Data.Position){case 200:return $t.UnableToMove;case 201:return $t.MotorOverheatedPleaseWait;default:return $t.Working}}}!function(e){e[e.Unknown=0]="Unknown",e[e.Working=1]="Working",e[e.UnableToMove=200]="UnableToMove",e[e.MotorOverheatedPleaseWait=201]="MotorOverheatedPleaseWait"}($t||($t={}));class Dn{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.Position=0,this.RawPosition=0,this.Time=""}}class kn extends vn{constructor(e){super(),this.TypeAsEnum=At.RemoteButtonState,this.Type="RemoteButtonState",this.Data=e.state}}class Gn{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.State=qt.Relased,this.Time=""}}!function(e){e[e.Pressed=1]="Pressed",e[e.Relased=2]="Relased",e[e.PressedAndRelased=3]="PressedAndRelased"}(qt||(qt={}));class bn extends vn{constructor(e){super(),this.TypeAsEnum=At.LightColor,this.Type="LightColorState",this.Data=e.state}}class Nn{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.R=0,this.G=0,this.B=0,this.Time=""}}class En extends vn{constructor(e){super(),this.TypeAsEnum=At.LightWarmth,this.Type="LightWarmthState",this.Data=e.state}}class In{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.Temperature=0,this.Time=""}}class Rn extends vn{constructor(e){super(),this.TypeAsEnum=At.LightBrightness,this.Type="LightBrightnessState",this.Data=e.state}}class Pn{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.Brightness=0,this.Time=""}}class On extends vn{constructor(e){super(),this.TypeAsEnum=At.MeasuredTemperature,this.Type="MeasuredTemperatureState",this.Data=e.state}}class Un{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.Temperature=0,this.Type=Vt.InsideTemperature,this.Time=""}}!function(e){e[e.AirTemperature=0]="AirTemperature",e[e.InsideTemperature=1]="InsideTemperature",e[e.OutsideTemperature=2]="OutsideTemperature",e[e.FloorTemperature=3]="FloorTemperature",e[e.SafetyTemperature=4]="SafetyTemperature",e[e.SetTemperature=5]="SetTemperature"}(Vt||(Vt={}));class Mn extends vn{constructor(e){super(),this.TypeAsEnum=At.BatteryState,this.Type="BatteryState",this.Data=e.state}}class xn{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.State=Ht.Half,this.Percentage=-1,this.Time=""}}!function(e){e[e.Unknown=-1]="Unknown",e[e.Full=0]="Full",e[e.Empty=1]="Empty",e[e.Half=2]="Half",e[e.Percentage=3]="Percentage",e[e.Low=4]="Low",e[e.ExternalPower=5]="ExternalPower"}(Ht||(Ht={}));class Fn extends vn{constructor(e){super(),this.TypeAsEnum=At.MeasuredBrightness,this.Type="MeasuredBrightnessState",this.Data=e.state}}class Ln{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.Brightness=0,this.Time=""}}class Bn extends vn{constructor(e){super(),this.TypeAsEnum=At.MeasuredEnergy,this.Type="MeasuredEnergyState",this.Data=e.state,this.Data.MeasurementParameters=new Map(Object.entries(e.state.MeasurementParameters))}}class Wn{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.Time="",this.MeasurementParameters=new Map}}!function(e){e.Voltage="Voltage",e.Current="Current",e.PhaseShift="PhaseShift",e.ActivePower="ActivePower",e.ReactivePower="ReactivePower",e.ApparentPower="ApparentPower",e.PowerFactor="PowerFactor",e.ActiveForwardEnergy="ActiveForwardEnergy",e.ActiveReverseEnergy="ActiveReverseEnergy",e.ApparentEnergy="ApparentEnergy",e.ReactiveForwardEnergy="ReactiveForwardEnergy",e.ReactiveReverseEnergy="ReactiveReverseEnergy",e.Frequency="Frequency",e.SPIErrorRate="SPIErrorRate",e.CRCErrorRate="CRCErrorRate",e.Timestamp="Timestamp",e.FailedMeasurementsRate="FailedMeasurementsRate",e.FundamentalActivePower="FundamentalActivePower",e.HarmonicActivePower="HarmonicActivePower"}(jt||(jt={}));class $n extends vn{constructor(e){super(),this.TypeAsEnum=At.MeasuredDistance,this.Type="MeasuredDistanceState",this.Data=e.state}}!function(e){e[e.No=0]="No",e[e.Yes=1]="Yes"}(Kt||(Kt={}));class qn extends vn{constructor(e){super(),this.TypeAsEnum=At.MovementSensorState,this.Type="MovementSensorState",this.Data=e.state}}class Vn{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.Intensity=0,this.Movement=zt.No,this.Time=""}}!function(e){e[e.No=0]="No",e[e.Yes=1]="Yes"}(zt||(zt={}));class Hn extends vn{constructor(e){super(),this.TypeAsEnum=At.BlindRemoteButtonState,this.Type="BlindRemoteButtonState",this.Data=e.state}}class jn{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.State=Jt.StopReleased,this.Time=""}}!function(e){e[e.OpenPressed=1]="OpenPressed",e[e.OpenReleased=2]="OpenReleased",e[e.StopPressed=3]="StopPressed",e[e.StopReleased=4]="StopReleased",e[e.ClosePressed=5]="ClosePressed",e[e.CloseReleased=6]="CloseReleased"}(Jt||(Jt={}));class Kn extends vn{constructor(e){super(),this.TypeAsEnum=At.FacadeRemoteButtonState,this.Type="FacadeRemoteButtonState",this.Data=e.state}}class zn{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.State=Yt.StopReleased,this.Time=""}}!function(e){e[e.OpenPressed=1]="OpenPressed",e[e.OpenReleased=2]="OpenReleased",e[e.StopPressed=3]="StopPressed",e[e.StopReleased=4]="StopReleased",e[e.ClosePressed=5]="ClosePressed",e[e.CloseReleased=6]="CloseReleased"}(Yt||(Yt={}));class Jn extends vn{constructor(e){super(),this.TypeAsEnum=At.SignalStrength,this.Type="SignalStrenghtState",this.Data=e.state}}!function(e){e[e.Unknown=0]="Unknown",e[e.Excellent=1]="Excellent",e[e.Good=2]="Good",e[e.Acceptable=3]="Acceptable",e[e.Low=4]="Low",e[e.Terrible=5]="Terrible",e[e.NoLink=6]="NoLink"}(Xt||(Xt={}));class Yn extends vn{constructor(e){super(),this.TypeAsEnum=At.GatePosition,this.Type="GatePositionState",this.Data=e.state}}class Xn{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.PositionType=Qt.Unknown,this.Position=0,this.Time=""}}!function(e){e[e.Unknown=0]="Unknown",e[e.Open=1]="Open",e[e.PartiallyOpen=2]="PartiallyOpen",e[e.Close=3]="Close",e[e.On=4]="On",e[e.Off=5]="Off",e[e.Percentage=6]="Percentage"}(Qt||(Qt={}));class Qn extends vn{constructor(e){super(),this.TypeAsEnum=At.GatewayPosition,this.Type="GatewayPositionState",this.Data=e.state}}!function(e){e[e.Unknown=0]="Unknown",e[e.Open=1]="Open",e[e.PartiallyOpen=2]="PartiallyOpen",e[e.Close=3]="Close",e[e.On=4]="On",e[e.Off=5]="Off"}(Zt||(Zt={}));class Zn extends vn{constructor(e){super(),this.TypeAsEnum=At.GateControllerHealth,this.Type="GateControllerHealthState",this.Data=e.state}}!function(e){e[e.Unknown=-1]="Unknown",e[e.Inactive=0]="Inactive",e[e.Active=1]="Active",e[e.UnconnectedOrMalfunction=2]="UnconnectedOrMalfunction"}(en||(en={}));class es extends vn{constructor(e){super(),this.TypeAsEnum=At.BlindCalibration,this.Type="BlindCalibrationState",this.Data=e.state}}!function(e){e[e.AutoLernIdle=0]="AutoLernIdle",e[e.AutoLernInProgress=1]="AutoLernInProgress",e[e.AutoLernSuccessfull=2]="AutoLernSuccessfull",e[e.AutoLernCancelled=4]="AutoLernCancelled"}(tn||(tn={}));class ts extends vn{constructor(e){super(),this.TypeAsEnum=At.HumiditySensorState,this.Type="HumiditySensorState",this.Data=e.state}}class ns{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.Type=nn.AirHumidity,this.Humidity=0,this.Time=""}}!function(e){e[e.AirHumidity=0]="AirHumidity",e[e.InsideHumidity=1]="InsideHumidity",e[e.OutsideHumidity=2]="OutsideHumidity",e[e.SafetyHumidity=3]="SafetyHumidity",e[e.SetHumidity=4]="SetHumidity"}(nn||(nn={}));class ss extends vn{constructor(e){super(),this.TypeAsEnum=At.VibrationSensorState,this.Type="VibrationSensorState",this.Data=e.state}}!function(e){e[e.No=0]="No",e[e.Yes=1]="Yes"}(sn||(sn={}));class rs extends vn{constructor(e){super(),this.TypeAsEnum=At.BinarySensorState,this.Type="BinarySensorState",this.Data=e.state}}class os{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.State=rn.Low,this.Time=""}}!function(e){e[e.High=1]="High",e[e.Low=0]="Low"}(rn||(rn={}));class is extends vn{constructor(e){super(),this.TypeAsEnum=At.ConfigurationState,this.Type="ConfigurationState",this.Data=e.state}}!function(e){e[e.Unknown=0]="Unknown",e[e.OngoingConfiguration=1]="OngoingConfiguration",e[e.NotConfigured=2]="NotConfigured",e[e.Configured=3]="Configured",e[e.PartiallyConfigured=4]="PartiallyConfigured"}(on||(on={}));class as extends vn{constructor(e){super(),this.TypeAsEnum=At.BlindOpenCloseTime,this.Type="BlindOpenCloseTimeState",this.Data=e.state}}class cs extends vn{constructor(e){super(),this.TypeAsEnum=At.OvercurrentProtectionState,this.Type="OvercurrentProtectionState",this.Data=e.state}}class us extends vn{constructor(e){super(),this.TypeAsEnum=At.OvercurrentProtectionThreshold,this.Type="OvercurrentProtectionThresholdState",this.Data=e.state}}class ls extends vn{constructor(e){super(),this.TypeAsEnum=At.FacadePosition,this.Type="FacadePositionState",this.Data=e.state}}class ds extends vn{constructor(e){super(),this.TypeAsEnum=At.FacadeType,this.Type="FacadeTypeState",this.Data=e.state}}class hs extends vn{constructor(e){super(),this.TypeAsEnum=At.CurrentWindThreshold,this.Type="CurrentWindThresholdState",this.Data=e.state}}class ps{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.WindThreshold=an.Unknown,this.Time=""}}!function(e){e[e.Unknown=0]="Unknown",e[e.Below=1]="Below",e[e.Exceeded=2]="Exceeded",e[e.Inactive=3]="Inactive"}(an||(an={}));class gs extends vn{constructor(e){super(),this.TypeAsEnum=At.CurrentLightThreshold,this.Type="CurrentLightThresholdState",this.Data=e.state}}!function(e){e[e.Unknown=0]="Unknown",e[e.Below=1]="Below",e[e.Exceeded=2]="Exceeded"}(cn||(cn={}));class fs extends vn{constructor(e){super(),this.TypeAsEnum=At.WindSpeedState,this.Type="WindSpeedState",this.Data=e.state}}class vs{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.Value=0,this.Time=""}}class ms extends vn{constructor(e){super(),this.TypeAsEnum=At.FloodSensorState,this.Type="FloodSensorState",this.Data=e.state}}class ys{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.State=un.NoFloodDetected,this.Time=""}}!function(e){e[e.FloodDetected=1]="FloodDetected",e[e.NoFloodDetected=0]="NoFloodDetected"}(un||(un={})),function(e){e[e.AirHumidity=0]="AirHumidity",e[e.InsideHumidity=1]="InsideHumidity",e[e.OutsideHumidity=2]="OutsideHumidity",e[e.SafetyHumidity=3]="SafetyHumidity",e[e.SetHumidity=4]="SetHumidity"}(ln||(ln={}));class ws extends vn{constructor(e){super(),this.TypeAsEnum=At.PressureSensorState,this.Type="PressureSensorState",this.Data=e.state}}class Ss{constructor(){this.Channel=0,this.StateReliability=Ft.Unconfident,this.Pressure=0,this.Time="",this.PressureType=dn.OutsidePressure}}!function(e){e[e.InsidePressure=0]="InsidePressure",e[e.OutsidePressure=1]="OutsidePressure",e[e.SetPressure=2]="SetPressure"}(dn||(dn={})),function(e){e[e.Facade90=0]="Facade90",e[e.Facade180=1]="Facade180"}(hn||(hn={}));class As extends vn{constructor(e){super(),this.TypeAsEnum=At.TamperProtectionState,this.Type="TamperProtection",this.Data=e.state}}!function(e){e[e.OK=0]="OK",e[e.Breach=1]="Breach"}(pn||(pn={}));class _s extends vn{constructor(e){super(),this.TypeAsEnum=At.LightRGBWState,this.Type="LightRGBW",this.Data=e.state}}class Cs extends vn{constructor(e){super(),this.TypeAsEnum=At.BlindErrorState,this.Type="BlindError",this.Data=e.state}}!function(e){e[e.Unknown=0]="Unknown",e[e.ObstacleDetected=1]="ObstacleDetected",e[e.MotorFailure=2]="MotorFailure"}(gn||(gn={}));class Ts{constructor(){this._onDeviceStateChangedEvent=new n,this._onDeviceStateRefreshedOrChangedEvent=new n,this._onDeviceTasksExecutionChangedOnChannelsEvent=new n,this._onDeviceFirmwareVersionChangedEvent=new n,this._iconType=wt.Unknown,this._serialNumber=null,this._model=null,this._modelGuid=null,this._manufacturerGuid=null,this._isVirtual=!1,this._isEnabled=!1,this._deviceState=_t.Working,this._deviceType=Tt.Unknown,this._communicationWay=Ct.OneWay,this._availableTasksTypes=[],this._availableResponseTypes=[],this._channels=[],this._protocolGuid=null,this._softwareVersion=null,null==Ts._devicesService&&(Ts._devicesService=Fv.Get(Fo.ServiceName));const e=this._onDeviceStateChangedEvent,t=this._onDeviceTasksExecutionChangedOnChannelsEvent;Ts._devicesService.OnDeviceStateChangedEvent().Subscribe((t=>{t.Device.Guid==this._guid&&e.Invoke(t.State)})),Ts._devicesService.OnDeviceStateRefreshedOrChangedEvent().Subscribe((e=>{e.Device.Guid==this._guid&&this._onDeviceStateRefreshedOrChangedEvent.Invoke(e.State)})),Ts._devicesService.OnDevicesTasksExecutionChangeEvent().Subscribe((e=>{t.Invoke(e.filter((e=>e.DeviceGuid==this._guid)).map((e=>e.Channel)))}))}OnDeviceFirmwareVersionChangedEvent(){return this._onDeviceFirmwareVersionChangedEvent}OnDeviceStateRefreshedOrChangedEvent(){return this._onDeviceStateRefreshedOrChangedEvent}get ShouldChannelsBeGrouped(){if(this._deviceType===Tt.Remote)switch(this._modelGuid){case"afea26ac-d5de-4aa9-8e74-ff69679d097b":case"908a71ec-ca46-4431-9504-05b7801e77f8":case"d8fea502-541e-42d9-8ece-a1bcfaaa93f9":return!1;default:return this._availableTasksTypes.all((e=>e.Type!==St.SetBlindPositionSimple))}return!1}get States(){return s.DoesThrowStackTrace?Fv.Get(Fo.ServiceName).GetDeviceStates(this).selectMany((e=>e.States)).toArray():Ts._devicesService.GetDeviceStates(this).selectMany((e=>e.States)).toArray()}RemoveDeviceAsync(){return Ts._devicesService.RemoveDeviceAsync(this)}ExecuteDeviceTaskAsync(e){return Ts._devicesService.ExecuteDeviceTaskAsync(this,e)}OnDeviceTasksExecutionChangedOnChannelsEvent(){return this._onDeviceTasksExecutionChangedOnChannelsEvent}OnDeviceStateChangedEvent(){return this._onDeviceStateChangedEvent}get Guid(){return null==this._guid?"":this._guid}set Guid(e){this._guid=e}get IconType(){return this._iconType}set IconType(e){this._iconType=e}get Name(){return null==this._name?"":this._name}set Name(e){this._name=e}set SoftwareVersion(e){this._softwareVersion=e}get SoftwareVersion(){return this._softwareVersion}get ChannelsAmount(){return null==this._channelsAmount?0:this._channelsAmount}set ChannelsAmount(e){this._channelsAmount=e}get SerialNumber(){return this._serialNumber}set SerialNumber(e){this._serialNumber=e}get Model(){return this._model}set Model(e){this._model=e}get ModelGuid(){return this._modelGuid}set ModelGuid(e){this._modelGuid=e}get ManufacturerGuid(){return this._manufacturerGuid}set ManufacturerGuid(e){this._manufacturerGuid=e}get IsVirtual(){return this._isVirtual}set IsVirtual(e){this._isVirtual=e}get IsEnabled(){return this._isEnabled}set IsEnabled(e){this._isEnabled=e}get DeviceState(){return this._deviceState}set DeviceState(e){this._deviceState=e}get DeviceType(){return this._deviceType}set DeviceType(e){this._deviceType=e}get CommunicationWay(){return this._communicationWay}set CommunicationWay(e){this._communicationWay=e}get AvailableTaskTypes(){return this._availableTasksTypes}set AvailableTaskTypes(e){this._availableTasksTypes=e}get AvailableResponseTypes(){return this._availableResponseTypes}set AvailableResponseTypes(e){this._availableResponseTypes=e}get Channels(){return this._channels}get ProtocolGuid(){return this._protocolGuid}set ProtocolGuid(e){this._protocolGuid=e}ChangeDeviceNameAsync(e){return t=this,n=void 0,r=function*(){try{const t=yield Fv.Get(Pt.ServiceName).SendAndWaitForResponseAsync(new Ds(this,e),2e4,!1);switch(t.Status){case ce.OK:return this._name=e,Fv.Get(Ge.ServiceName).ClearCache(),Fv.Get(rt.ServiceName).ExitConfigurationModeAsync(),new Te(me.Changed,"");case ce.WrongData:if("DeviceNotFound"==t.Data)return new Te(me.Failed,"DeviceNotFound");break;case ce.NoPermissionsToCallGivenResource:return new Te(me.NoPermissions,"")}}catch(e){return e.message.includes("timeout")?new Te(me.ControllerResponseTimeout,""):new Te(me.UnknownError,"")}return new Te(me.Unknown,"")},new((s=void 0)||(s=Promise))((function(e,o){function i(e){try{c(r.next(e))}catch(e){o(e)}}function a(e){try{c(r.throw(e))}catch(e){o(e)}}function c(t){var n;t.done?e(t.value):(n=t.value,n instanceof s?n:new s((function(e){e(n)}))).then(i,a)}c((r=r.apply(t,n||[])).next())}));var t,n,s,r}ExecuteTaskAsync(e){return Ts._devicesService.ExecuteDeviceTaskAsync(this,e)}}class Ds extends ae{constructor(e,t){super(),this.Resource="/devices/device/name",this.Method=ue.Put;const n=new ks;n.DeviceGuid=e.Guid,n.Name=t,this.Data=n}}class ks{constructor(){this.DeviceGuid="",this.Name=""}}var Gs,bs,Ns,Es,Is,Rs=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class Ps{constructor(){this._device=new Ts,this._number=0,this._name="",this._iconName="",this._channelId="",this._mode=mt.Default,this._channelGroups=[],this._isHidden=!1,this._availableTasksTypes=[],this._availableResponseTypes=[],this._customData={},this._roles=[],this._configurations={},this.CustomDataAndRolesSupported=!1,this._onTasksExecutionChangedEvent=new n,this._onChannelStateChangedEvent=new n,this._onChannelStateRefreshedOrChangedEvent=new n,null==Ps._devicesService&&(Ps._devicesService=Fv.Get(Fo.ServiceName))}OnChannelStateChangedEvent(){return this._onChannelStateChangedEvent}OnChannelStateRefreshedOrChangedEvent(){return this._onChannelStateRefreshedOrChangedEvent}get Configurations(){return this._configurations}set Configurations(e){this._configurations=e}IsCustomDataAndRolesSupported(){return this.CustomDataAndRolesSupported}get CustomData(){return this._customData}set CustomData(e){this._customData=e}get Roles(){return this._roles}set Roles(e){this._roles=e}get ChannelId(){return this._channelId}SetDevice(e){this._device=e,this._channelId=`${e.Guid}_${this.Number}`,this._device.OnDeviceStateChangedEvent().Subscribe((e=>{e.Data.Channel==this.Number&&this._onChannelStateChangedEvent.Invoke(e)})),this._device.OnDeviceStateRefreshedOrChangedEvent().Subscribe((e=>{e.Data.Channel==this.Number&&this._onChannelStateRefreshedOrChangedEvent.Invoke(e)}))}GetDevice(){return this._device}SetCustomDataAsync(e,t){return Rs(this,void 0,void 0,(function*(){const n=this.GetChannelConfigurationData();n.CustomData[e]=t,this._customData[e]=t;const s=new Os;return s.DeviceGuid=this._device.Guid,s.ChannelConfiguration=n,this.ChangeConfigurationAsync(s)}))}RemoveCustomDataAsync(e){const t=this.GetChannelConfigurationData();delete t.CustomData[e],delete this._customData[e];const n=new Os;return n.DeviceGuid=this._device.Guid,n.ChannelConfiguration=t,this.ChangeConfigurationAsync(n)}GetChannelConfigurationData(){const e=new Us;return e.Channel=this._number,e.ChannelName=this._name,e.Configuration=this._mode,e.CustomData=this._customData,e.GroupsGuids=this._channelGroups,e.Hidden=this._isHidden,e.IconName=this._iconName,e}HideAsync(){const e=this.GetChannelConfigurationData();this._isHidden=!0,e.Hidden=!0;const t=new Os;return t.DeviceGuid=this._device.Guid,t.ChannelConfiguration=e,this.ChangeConfigurationAsync(t)}ShowAsync(){const e=this.GetChannelConfigurationData();e.Hidden=!1,this._isHidden=!1;const t=new Os;return t.DeviceGuid=this._device.Guid,t.ChannelConfiguration=e,this.ChangeConfigurationAsync(t)}ChangeNameAsync(e){const t=this.GetChannelConfigurationData(),n=new Os;return n.DeviceGuid=this._device.Guid,n.ChannelConfiguration=t,t.ChannelName=e,this._name=e,this.ChangeConfigurationAsync(n)}ChangeIconNameAsync(e){const t=this.GetChannelConfigurationData();t.IconName=e;const n=new Os;return n.DeviceGuid=this._device.Guid,n.ChannelConfiguration=t,this._iconName=e,this.ChangeConfigurationAsync(n)}ChangeGroupsAsync(e){const t=this.GetChannelConfigurationData();t.GroupsGuids=e;const n=new Os;return n.DeviceGuid=this._device.Guid,n.ChannelConfiguration=t,this._channelGroups=e,this.ChangeConfigurationAsync(n)}ChangeConfigurationAsync(e){return Rs(this,void 0,void 0,(function*(){var t;try{const n=yield Fv.Get(Pt.ServiceName).SendAndWaitForResponseAsync(new Ms(e),2e4,!1);switch(Fv.Get(Ge.ServiceName).ClearCache(),yield Fv.Get(rt.ServiceName).ExitConfigurationModeAsync(),n.Status){case ce.OK:return this._name=e.ChannelConfiguration.ChannelName,this._iconName=e.ChannelConfiguration.IconName,this._channelGroups=e.ChannelConfiguration.GroupsGuids,this._isHidden=e.ChannelConfiguration.Hidden,this._mode=e.ChannelConfiguration.Configuration,this._customData=e.ChannelConfiguration.CustomData,this._roles=e.ChannelConfiguration.Roles,this._configurations=e.ChannelConfiguration.Configurations,new Te(me.Changed,"");case ce.WrongData:if("DeviceNotFound"===n.Data)return null===(t=r.Log)||void 0===t||t.Error("Failed to change channel configuration, referenced device does not exist!"),new Te(me.WrongData,"DeviceNotFound");break;case ce.FatalError:return new Te(me.UnknownError,"")}}catch(e){if(e.message.includes("timeout"))return new Te(me.ControllerResponseTimeout,"")}return new Te(me.Unknown,"")}))}get Number(){return this._number}set Number(e){this._number=e}get Name(){return this._name}set Name(e){this._name=e}get IconName(){return this._iconName}set IconName(e){this._iconName=e}get States(){return s.DoesThrowStackTrace?Fv.Get(Fo.ServiceName).GetDeviceStates(this.GetDevice()).where((e=>e.Channel==this.Number)).selectMany((e=>e.States)).toArray():Ps._devicesService.GetDeviceStates(this.GetDevice()).where((e=>e.Channel==this.Number)).selectMany((e=>e.States)).toArray()}get Mode(){return this._mode}set Mode(e){this._mode=e}get ChannelGroups(){return this._channelGroups}set ChannelGroups(e){this._channelGroups=e}get IsHidden(){return this._isHidden}set IsHidden(e){this._isHidden=e}get AvailableTaskTypes(){return this._availableTasksTypes}set AvailableTaskTypes(e){this._availableTasksTypes=e}get AvailableResponseTypes(){return this._availableResponseTypes}set AvailableResponseTypes(e){this._availableResponseTypes=e}OnTasksExecutionChangeEvent(){return this._onTasksExecutionChangedEvent}ExecuteTaskAsync(e){return null!=this._device?(e.Channel=this.Number,e.DeviceGuid=this._device.Guid,Ps._devicesService.ExecuteDeviceTaskAsync(this._device,e)):Promise.resolve(kt.Failed)}}Ps._devicesService=null;class Os{constructor(){this.DeviceGuid="",this.ChannelConfiguration=new Us}}class Us{constructor(){this.Channel=0,this.ChannelName="",this.Configuration=mt.Default,this.GroupsGuids=[],this.IconName="",this.Hidden=!1,this.Configurations={},this.CustomData={},this.Roles=[]}}class Ms extends ae{constructor(e){super(),this.Resource="/devices/device/channel/configuration",this.Method=ue.Put,this.Data=e}}!function(e){e[e.TurnOn=0]="TurnOn",e[e.TurnOff=1]="TurnOff",e[e.ToggleState=2]="ToggleState",e[e.SetBlindPosition=3]="SetBlindPosition",e[e.SetLightColor=4]="SetLightColor",e[e.SetLightTemperature=5]="SetLightTemperature",e[e.SetLightBrightness=6]="SetLightBrightness",e[e.SetTemperature=7]="SetTemperature",e[e.GetState=8]="GetState",e[e.TurnOnWithTimeout=9]="TurnOnWithTimeout",e[e.SetLightBrightnessDynamicly=10]="SetLightBrightnessDynamicly",e[e.IdentifyDevice=11]="IdentifyDevice",e[e.SetBlindOpenCloseTime=12]="SetBlindOpenCloseTime",e[e.SetBlindMicroventilation=13]="SetBlindMicroventilation",e[e.GatewayPulse=25]="GatewayPulse",e[e.GatePulse=26]="GatePulse",e[e.SetFacadePositionAndTilt=29]="SetFacadePositionAndTilt",e[e.GetFacadeType=30]="GetFacadeType",e[e.LightRGBW=31]="LightRGBW",e[e.SetGatePositionPrecise=32]="SetGatePositionPrecise"}(Gs||(Gs={}));class xs{static NewGuid(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))}}class Fs{constructor(){this._taskType=St.GetChannelsState,this._featureType=Gs.GetState,this._channel=0,this._guid=xs.NewGuid(),this._deviceGuid=""}get TaskType(){return this._taskType}set TaskType(e){this._taskType=e}get FeatureType(){return this._featureType}set FeatureType(e){this._featureType=e}get Guid(){return this._guid}set Guid(e){this._guid=e}get DeviceGuid(){return this._deviceGuid}set DeviceGuid(e){this._deviceGuid=e}get Channel(){return this._channel}set Channel(e){this._channel=e}}class Ls extends Fs{constructor(){super(),this.Temperature=0,this.FeatureType=Gs.SetTemperature,this.TaskType=St.SetTemperature}}class Bs extends Fs{constructor(){super(),this.FeatureType=Gs.TurnOff,this.TaskType=St.TurnOff}}class Ws extends Fs{constructor(){super(),this.FeatureType=Gs.TurnOn,this.TaskType=St.TurnOn}}class $s extends Fs{constructor(){super(),this.SwitchOffDelaySeconds=0,this.FeatureType=Gs.TurnOnWithTimeout,this.TaskType=St.TurnOnWithTime}}class qs extends Fs{constructor(){super(),this.Brightness=0,this.FeatureType=Gs.SetLightBrightness,this.TaskType=St.SetLightBrightness}}class Vs extends Fs{constructor(){super(),this.FeatureType=Gs.ToggleState,this.TaskType=St.TogleState}}class Hs extends Fs{constructor(){super(),this.R=0,this.G=0,this.B=0,this.FeatureType=Gs.SetLightColor,this.TaskType=St.SetLightColor}}class js extends Fs{constructor(){super(),this.Temperature=0,this.FeatureType=Gs.SetLightTemperature,this.TaskType=St.SetLightTemperature}}class Ks extends Fs{constructor(){super(),this.Action=bs.Stop,this.Position=0,this.FeatureType=Gs.SetBlindPosition,this.TaskType=St.SetBlindPosition}}!function(e){e[e.Open=0]="Open",e[e.Close=1]="Close",e[e.Stop=2]="Stop",e[e.Percentage=3]="Percentage"}(bs||(bs={})),function(e){e[e.Open=0]="Open",e[e.Close=1]="Close",e[e.Stop=2]="Stop",e[e.Percentage=3]="Percentage"}(Ns||(Ns={}));class zs extends Fs{constructor(){super(),this.Action=Es.Stop,this.Position=0,this.FeatureType=Gs.SetBlindPosition,this.TaskType=St.SetBlindPositionSimple}}!function(e){e[e.Open=0]="Open",e[e.Close=1]="Close",e[e.Stop=2]="Stop"}(Es||(Es={}));class Js extends Fs{constructor(){super(),this.Brightness=0,this.FeatureType=Gs.SetLightBrightnessDynamicly,this.TaskType=St.SetLightBrightnessDynamicly}}class Ys extends Fs{constructor(){super(),this.FeatureType=Gs.IdentifyDevice,this.TaskType=St.IdentifyDevice}}class Xs extends Fs{constructor(){super(),this.Data=new Qs,this.FeatureType=Gs.SetBlindOpenCloseTime,this.TaskType=St.SetBlindOpenCloseTime}}class Qs{constructor(){this.Channel=0,this.CloseTime=0,this.OpenTime=0}}class Zs extends Fs{constructor(){super(),this.FeatureType=Gs.GetState,this.TaskType=St.GetChannelsState}}class er extends Fs{constructor(){super(),this.Position=0,this.FeatureType=Gs.SetBlindMicroventilation,this.TaskType=St.SetBlindMicroventilation}}class tr extends Fs{constructor(){super(),this.FeatureType=Gs.GatePulse,this.TaskType=St.ChangeGatewayPositionPulse}}class nr extends Fs{constructor(){super(),this.FeatureType=Gs.GatewayPulse,this.TaskType=St.ChangeGatewayPositionPulse}}class sr extends Fs{constructor(){super(),this.FacadeAction=Is.Stop,this.Tilt=0,this.Position=0,this.FeatureType=Gs.SetFacadePositionAndTilt,this.TaskType=St.SetFacadePosition}}class rr extends Fs{constructor(){super(),this.FeatureType=Gs.GetFacadeType,this.TaskType=St.GetFacadeType}}!function(e){e[e.Open=0]="Open",e[e.Close=1]="Close",e[e.Stop=2]="Stop",e[e.Percentage=3]="Percentage",e[e.Tilt=4]="Tilt",e[e.TiltAndPercentage=5]="TiltAndPercentage"}(Is||(Is={}));class or{constructor(){this.R=0,this.G=0,this.B=0,this.W=0,this.Brightness=0,this.Channel=0}}class ir extends Fs{constructor(){super(),this.Data=new or,this.FeatureType=Gs.LightRGBW,this.TaskType=St.LightRGBW}}var ar=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class cr{constructor(){this._manualDeviceProtocolServices=new Map}GetServiceName(){return cr.ServiceName}RegisterManuallyPairedDevicesProtocol(e){Fv.Get(s.ServiceName).Debug(cr.ServiceName,`Registering new manual device protocol service: ${e.GetServiceName()}`),Fv.Get(Ge.ServiceName).ClearCache(),Fv.Get(rt.ServiceName).ExitConfigurationModeAsync(),this._manualDeviceProtocolServices.set(e.GetServiceName(),e)}GetDevicesForManualPairingAsync(e){return ar(this,void 0,void 0,(function*(){const t=[...this._manualDeviceProtocolServices.values()],n=[];if(null!=e)if(Array.isArray(e))for(let s=0;s<t.length;s++)e.any((e=>e==t[s].ProtocolExtensionGuid))&&n.push(...yield t[s].GetDevicesForManualPairingAsync());else{const s=t.find((t=>t.ProtocolExtensionGuid==e));null!=s&&n.push(...yield s.GetDevicesForManualPairingAsync())}else for(let e=0;e<t.length;e++)n.push(...yield t[e].GetDevicesForManualPairingAsync());return n}))}AddManuallyPairedDeviceAsync(e){return ar(this,void 0,void 0,(function*(){const t=[...this._manualDeviceProtocolServices.values()].find((t=>t.ProtocolExtensionGuid==e.ProtocolExtensionGuid));return null!=t?t.AddManuallyPairedDeviceAsync(e):(Fv.Get(Ge.ServiceName).ClearCache(),Fv.Get(rt.ServiceName).ExitConfigurationModeAsync(),kt.Failed)}))}GetRegisteredProtocolGuids(){return[...this._manualDeviceProtocolServices.values()].map((e=>e.ProtocolExtensionGuid))}}cr.ServiceName="ManualDeviceService";class ur{constructor(){this.ResourceGuid="",this.Data=null,this.IsGlobal=!1,this.InsertTime=new Date}}var lr,dr=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class hr{constructor(){this._connection=null,this._localDb=null,this._connection=Fv.Get(Pt.ServiceName),this._localDb=Fv.Get(o.ServiceName)}GetLocalDbName(e,t){return`${e}_${t}`}SaveAsync(e,t,n){return dr(this,void 0,void 0,(function*(){let s=new pr(e,t,n),r=yield this._connection.SendAndWaitForResponseAsync(s,35e3,!1);if(r.Status===ce.OK){const s=new vr;s.ResourceGuid=e,s.Data=JSON.stringify(n),s.IsGlobal=t,this._localDb.Save(hr.ServiceName,this.GetLocalDbName(e,t),s)}return r.Status}))}ReadAsync(e,t,n){return dr(this,void 0,void 0,(function*(){let s=new gr(e,t);if(!n){const n=this._localDb.Read(hr.ServiceName,this.GetLocalDbName(e,t));if(null!=n){const e=n,t=new ur;return t.Data=JSON.parse(e.Data),t.IsGlobal=e.IsGlobal,t.ResourceGuid=e.ResourceGuid,t}}let r=yield this._connection.SendAndWaitForResponseAsync(s,35e3,!1);if(r.Status===ce.OK){const e=new ur;return e.ResourceGuid=r.ResourceGuid,e.Data=JSON.parse(r.Data),e.IsGlobal=r.IsGlobal,e}return r.Status}))}RemoveAsync(e,t){return dr(this,void 0,void 0,(function*(){let n=new fr(e,t);return(yield this._connection.SendAndWaitForResponseAsync(n,35e3,!1)).Status}))}GetServiceName(){return hr.ServiceName}}hr.ServiceName="RemoteStorageService";class pr extends ae{constructor(e,t,n){super(),this.ResourceGuid="",this.Global=!1,this.Resource="/sync/config/",this.Method=ue.Put,this.ResourceGuid=e,this.Global=t,this.Data=JSON.stringify(n)}}class gr extends ae{constructor(e,t){super(),this.ResourceGuid="",this.Global=!1,this.Resource="/sync/config/",this.Method=ue.Get,this.ResourceGuid=e,this.Global=t}}class fr extends ae{constructor(e,t){super(),this.ResourceGuid="",this.Global=!1,this.Resource="/sync/config/",this.Method=ue.Delete,this.ResourceGuid=e,this.Global=t}}class vr extends ae{constructor(){super(...arguments),this.ResourceGuid="",this.Data="",this.IsGlobal=!1,this.InsertTime=new Date}}class mr{constructor(){this.Longitude=0,this.Latitude=0}}class yr{constructor(){this.Longitude=0,this.Latitude=0,this.IsNetworkBased=!1}}!function(e){e[e.OK=0]="OK",e[e.NoPermissions=1]="NoPermissions",e[e.UserIsNotLoggedIn=2]="UserIsNotLoggedIn",e[e.UnknownError=3]="UnknownError"}(lr||(lr={}));var wr,Sr,Ar,_r,Cr,Tr,Dr,kr,Gr,br,Nr,Er,Ir,Rr,Pr,Or,Ur=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class Mr{IsControllerGeolocationSetAsync(){return Ur(this,void 0,void 0,(function*(){let e=new xr,t=yield Fv.Get(Pt.ServiceName).SendAndWaitForResponseAsync(e,15e3,!0);return(null==t?void 0:t.Status)===ce.OK?null==t?void 0:t.Data:null==t?void 0:t.Status}))}GetCurrentGeolocationAsync(){return Ur(this,void 0,void 0,(function*(){return new Promise(((e,t)=>Ur(this,void 0,void 0,(function*(){window.navigator.geolocation.getCurrentPosition((t=>{e(t)}),(t=>{e(t)}))}))))}))}SetControllerGeolocationAsync(e){return Ur(this,void 0,void 0,(function*(){var t,n;let s=new Lr;s.Data.Latitude=e.Latitude,s.Data.Longitude=e.Longitude,null===(t=r.Log)||void 0===t||t.Warning(Mr.ServiceName,`SetControllerGeolocationAsync() ${JSON.stringify(s)}`);let o=yield Fv.Get(Pt.ServiceName).SendAndWaitForResponseAsync(s,15e3,!1);switch(null===(n=r.Log)||void 0===n||n.Warning(Mr.ServiceName,`${JSON.stringify(o)}`),Fv.Get(Ge.ServiceName).ClearCache(),Fv.Get(rt.ServiceName).ExitConfigurationModeAsync(),null==o?void 0:o.Status){case ce.OK:return new De(lr.OK,"");case ce.NoPermissionToPerformThisOperation:case ce.NoPermissionsToCallGivenResource:return new De(lr.NoPermissions,"");case ce.UserIsNotLoggedIn:return new De(lr.UserIsNotLoggedIn,"");default:return new De(lr.UnknownError,"")}}))}GetControlllerGeolocationAsync(){return Ur(this,void 0,void 0,(function*(){var e,t;let n=new Fr;null===(e=r.Log)||void 0===e||e.Warning(Mr.ServiceName,`GetControlllerGeolocationAsync(): ${JSON.stringify(n)}`);let s=yield Fv.Get(Pt.ServiceName).SendAndWaitForResponseAsync(n,15e3,!0);if(null===(t=r.Log)||void 0===t||t.Warning(Mr.ServiceName,`${JSON.stringify(s)}`),(null==s?void 0:s.Status)===ce.OK){let e=new yr;return e.IsNetworkBased=(null==s?void 0:s.Data).IsNetworkBased,e.Latitude=(null==s?void 0:s.Data).Latitude,e.Longitude=(null==s?void 0:s.Data).Longitude,e}return null==s?void 0:s.Status}))}GetServiceName(){return Mr.ServiceName}}Mr.ServiceName="GeolocationService";class xr extends ae{constructor(){super(),this.Resource="/geolocation/isset",this.Method=ue.Get}}class Fr extends ae{constructor(){super(),this.Resource="/geolocation/get",this.Method=ue.Get}}class Lr extends ae{constructor(){super(),this.Data=new mr,this.Resource="/geolocation/save",this.Method=ue.Put}}!function(e){e.OtherError="OtherError",e.FatalError="FatalError",e.NoData="NoData",e.InvalidSceneGuid="InvalidSceneGuid"}(wr||(wr={}));class Br{constructor(){this._comparisonParams=new Map,this.Type=At.Unknown,this.DeviceGuid="",this.ComparisonMethod=Sr.Default}GetCheckDeviceState(){return this._checkDeviceState}SetCheckDeviceState(e){this._checkDeviceState=e,e instanceof xn&&(this.Type=At.BatteryState),e instanceof os&&(this.Type=At.BinarySensorState),e instanceof Dn&&(this.Type=At.BlindPosition),e instanceof Pn&&(this.Type=At.LightBrightness),e instanceof Ln&&(this.Type=At.MeasuredBrightness),e instanceof Gn&&(this.Type=At.RemoteButtonState),e instanceof yn&&(this.Type=At.ChannelOnOffState),e instanceof An&&(this.Type=At.DoorBellState),e instanceof Wn&&(this.Type=At.MeasuredEnergy),e instanceof ys&&(this.Type=At.FloodSensorState),e instanceof Xn&&(this.Type=At.GatePosition),e instanceof Nn&&(this.Type=At.LightColor),e instanceof In&&(this.Type=At.LightWarmth),e instanceof Cn&&(this.Type=At.ReedState),e instanceof Un&&(this.Type=At.MeasuredTemperature),e instanceof ns&&(this.Type=At.HumiditySensorState),e instanceof jn&&(this.Type=At.BlindRemoteButtonState),e instanceof zn&&(this.Type=At.FacadeRemoteButtonState),e instanceof Vn&&(this.Type=At.MovementSensorState),e instanceof Wn&&(this.Type=At.MeasuredEnergy),e instanceof Ss&&(this.Type=At.PressureSensorState),e instanceof vs&&(this.Type=At.WindSpeedState),e instanceof ps&&(this.Type=At.CurrentWindThreshold)}GetComparisonParam(e){return this._comparisonParams.get(e)}GetComparisonParams(){return this._comparisonParams}SetComparisonParam(e,t){this._comparisonParams.set(e,t)}}class Wr{constructor(e){this._value=e}get Value(){return this._value}set Value(e){this._value=e}}class $r{constructor(...e){this._value="00:00:00",e.length>1?this.SetTimeSpan(e[0],e[1],e[2],e[3]):this._value=e[0]}SetTimeSpan(e,t,n,s){this._value=s<=0?`${n.toString().padStart(2,"0")}:${t.toString().padStart(2,"0")}:${e.toString().padStart(2,"0")}`:`${s}.${n.toString().padStart(2,"0")}:${t.toString().padStart(2,"0")}:${e.toString().padStart(2,"0")}`}get Value(){return this._value}}!function(e){e[e.Default=0]="Default",e[e.Delta=1]="Delta",e[e.StateRepeat=2]="StateRepeat"}(Sr||(Sr={})),function(e){e[e.DeltaValue=0]="DeltaValue",e[e.DeltaCalculationTimeRange=1]="DeltaCalculationTimeRange",e[e.StateRepeatCount=2]="StateRepeatCount",e[e.StateRepeatTimeRange=3]="StateRepeatTimeRange"}(Ar||(Ar={})),function(e){e[e.SunRise=1]="SunRise",e[e.SunSet=2]="SunSet"}(_r||(_r={}));class qr{constructor(){this.DeviceGuid=""}}!function(e){e[e.Unknown=-1]="Unknown",e[e.DeviceTask=0]="DeviceTask",e[e.DelayTask=1]="DelayTask",e[e.NotifyTask=2]="NotifyTask",e[e.LockExecution=3]="LockExecution"}(Cr||(Cr={})),function(e){e.Unknown="Unknown",e.DeviceTask="DeviceTask",e.DelayTask="DelayTask",e.NotifyTask="NotifyTask",e.LockExecution="LockExecution"}(Tr||(Tr={})),(Or=Dr||(Dr={}))[Or.Unknown=0]="Unknown",Or[Or.Second=1]="Second",Or[Or.Minute=2]="Minute",Or[Or.Hour=3]="Hour",Or[Or.Day=4]="Day",Or[Or.DayOfWeek=5]="DayOfWeek",Or[Or.Month=6]="Month",Or[Or.Year=7]="Year",Or[Or.Date=8]="Date",Or[Or.Time=9]="Time",Or[Or.WeatherType=11]="WeatherType",Or[Or.CompareNumbers=12]="CompareNumbers",Or[Or.CompareBooleans=13]="CompareBooleans",Or[Or.DeviceState=14]="DeviceState",Or[Or.Timer=15]="Timer",Or[Or.Temperature=17]="Temperature",Or[Or.DaysOfWeek=18]="DaysOfWeek",Or[Or.AstronomicalClockWithOffset=19]="AstronomicalClockWithOffset",Or[Or.SceneExecuted=20]="SceneExecuted",(Pr=kr||(kr={}))[Pr.Unknown=0]="Unknown",Pr[Pr.Equal=1]="Equal",Pr[Pr.NotEqueal=2]="NotEqueal",Pr[Pr.BiggerThan=3]="BiggerThan",Pr[Pr.SmallerThan=4]="SmallerThan",Pr[Pr.BiggerThanOrEqual=5]="BiggerThanOrEqual",Pr[Pr.SmallerThanOrEqual=6]="SmallerThanOrEqual",Pr[Pr.OneOfBothIsTrue=7]="OneOfBothIsTrue",Pr[Pr.BothAreTrue=8]="BothAreTrue",function(e){e[e.Unknown=0]="Unknown",e[e.BatteryState=1]="BatteryState",e[e.BinarySensor=2]="BinarySensor",e[e.BlindPosition=3]="BlindPosition",e[e.Brightness=4]="Brightness",e[e.ButtonState=5]="ButtonState",e[e.ChannelOnOff=6]="ChannelOnOff",e[e.DoorBell=7]="DoorBell",e[e.Energy=8]="Energy",e[e.FloodSensor=9]="FloodSensor",e[e.GatePosition=10]="GatePosition",e[e.HeatSensor=11]="HeatSensor",e[e.LightBrightness=12]="LightBrightness",e[e.LightColor=13]="LightColor",e[e.LightTemperature=14]="LightTemperature",e[e.MeasuredCurrent=15]="MeasuredCurrent",e[e.MeasuredPower=16]="MeasuredPower",e[e.MeasuredVoltage=17]="MeasuredVoltage",e[e.ReedState=18]="ReedState",e[e.SmokeSensor=19]="SmokeSensor",e[e.Temperature=20]="Temperature",e[e.BlindsControlButton=21]="BlindsControlButton",e[e.Movement=22]="Movement",e[e.WindSpeed=24]="WindSpeed",e[e.Humidity=25]="Humidity",e[e.AirPressure=26]="AirPressure",e[e.WindThreshold=31]="WindThreshold",e[e.FacadeControlButton=36]="FacadeControlButton"}(Gr||(Gr={})),function(e){e[e.Null=0]="Null",e[e.Condition=1]="Condition",e[e.ConditionGroup=2]="ConditionGroup",e[e.ArgumentAsInt=3]="ArgumentAsInt",e[e.ArgumentAsTimeSpan=4]="ArgumentAsTimeSpan",e[e.ArgumentAsBoolean=5]="ArgumentAsBoolean",e[e.ArgumentAsTimeout=6]="ArgumentAsTimeout",e[e.ArgumentAsDayOfWeek=7]="ArgumentAsDayOfWeek",e[e.ArgumentAsDaysOfWeek=8]="ArgumentAsDaysOfWeek",e[e.ArgumentAsAstronomicalClock=9]="ArgumentAsAstronomicalClock",e[e.ArgumentAsTime=10]="ArgumentAsTime",e[e.ArgumentAsDeviceState=11]="ArgumentAsDeviceState",e[e.ArgumentAsNumber=12]="ArgumentAsNumber",e[e.ArgumentAsAstronomicalClockWithOffset=13]="ArgumentAsAstronomicalClockWithOffset",e[e.ArgumentAsConditionInfo=14]="ArgumentAsConditionInfo"}(br||(br={})),(Rr=Nr||(Nr={})).Null="Null",Rr.Condition="Condition",Rr.ConditionGroup="ConditionGroup",Rr.ArgumentAsInt="ArgumentAsInt",Rr.ArgumentAsTimeSpan="ArgumentAsTimeSpan",Rr.ArgumentAsBoolean="ArgumentAsBoolean",Rr.ArgumentAsTimeout="ArgumentAsTimeout",Rr.ArgumentAsDayOfWeek="ArgumentAsDayOfWeek",Rr.ArgumentAsDaysOfWeek="ArgumentAsDaysOfWeek",Rr.ArgumentAsAstronomicalClock="ArgumentAsAstronomicalClock",Rr.ArgumentAsTime="ArgumentAsTime",Rr.ArgumentAsDeviceState="ArgumentAsDeviceState",Rr.ArgumentAsNumber="ArgumentAsNumber",Rr.ArgumentAsAstronomicalClockWithOffset="ArgumentAsAstronomicalClockWithOffset",Rr.ArgumentAsConditionInfo="ArgumentAsConditionInfo";class Vr extends Error{constructor(e){super(e),this.message=e,this.name="UnsupportedScenesDeviceState"}}!function(e){e[e.Device=0]="Device",e[e.Controller=1]="Controller"}(Er||(Er={}));class Hr{constructor(){this.UpdateGuid="",this.Channel="",this.Version="",this.CurrentVersion="",this.DownloadUri="",this.Download="",this.Name="",this.Description="",this.UpdateType=Ir.Unknown,this.ResourceGuid=""}}class jr{constructor(){this.UpdateDescription=new Map,this.Update=new Hr,this.UpdatedResourceName="",this.CurrentResourceVersion=""}}!function(e){e[e.Unknown=0]="Unknown",e[e.Container=1]="Container",e[e.RadioFirmware=2]="RadioFirmware",e[e.DeviceFirmware=3]="DeviceFirmware",e[e.Configuration=4]="Configuration",e[e.ContainerScript=5]="ContainerScript",e[e.ContainerSoftware=6]="ContainerSoftware",e[e.RuntimeSoftware=7]="RuntimeSoftware",e[e.RuntimeScript=8]="RuntimeScript",e[e.RuntimeFixingScript=9]="RuntimeFixingScript"}(Ir||(Ir={}));class Kr extends Error{constructor(e){super(e),this.message=e,this.name="UpdateProviderNotFound"}}var zr,Jr,Yr,Xr=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class Qr{constructor(){this._services=new Map,this._runtimeInfo=new Zr,this._hardwareInfo=new to,this._semaphore=new Xe(1),this._isRuntimeInfoInitialized=!1,this._isHardwareInfoInitialized=!1}GetServiceName(){return Qr.ServiceName}RegisterUpdatesProvider(e){Fv.Get(s.ServiceName).Debug(Qr.ServiceName,`Registering new update provider: ${e.GetUpdateProviderName()}`),this._services.set(e.GetUpdateProviderName(),e)}GetUpdatesProviderAsync(e){return Xr(this,void 0,void 0,(function*(){Fv.Get(s.ServiceName).Debug(Qr.ServiceName,`Getting update provider [${e}] by GetUpdateProviderAsync<T>()`);const t=this._services.get(e);if(null==t)throw new Kr("Cannot get update provider! Requested update provider has not been registered.");return t}))}GetUpdatesProvidersAsync(e){return Xr(this,void 0,void 0,(function*(){Fv.Get(s.ServiceName).Debug(Qr.ServiceName,`Getting update providers with type ${e} by GetUpdateProvidersAsync<T>()`);let t=[];if(t=[...this._services.values()].filter((t=>t.ProviderType==e)),0==t.length)throw new Kr("Cannot get update providers! Requested update providers has not been registered.");return t}))}GetUpdatesProvidersByProtocolAsync(e,t,n){return Xr(this,void 0,void 0,(function*(){if(new RegExp("^[{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]?$").test(e)){Fv.Get(s.ServiceName).Debug(Qr.ServiceName,`Getting update providers with protocol guid: [${e}] by GetUpdateProvidersByProtocolAsync<T>()`);let r=[];if(r=null!=n?[...this._services.values()].filter((s=>s.ProtocolGuid==e&&s.ProviderType==t&&s.AvailableExtensionVersion==n)):[...this._services.values()].filter((n=>n.ProtocolGuid==e&&n.ProviderType==t)),0==r.length)throw new Kr("Cannot get update providers! Requested update providers has not been registered.");return r}throw new Kr("Cannot get update providers! Bad parameters.")}))}GetUpdatesProvidersByExtensionAsync(e,t,n){return Xr(this,void 0,void 0,(function*(){if(new RegExp("^[{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]?$").test(e)){Fv.Get(s.ServiceName).Debug(Qr.ServiceName,`Getting update providers with extension guid: [${e}] by GetUpdateProvidersByExtensionAsync<T>()`);let r=[];if(r=null!=n?[...this._services.values()].filter((s=>s.ExtensionGuid==e&&s.ProviderType==t&&s.AvailableExtensionVersion==n)):[...this._services.values()].filter((n=>n.ExtensionGuid==e&&n.ProviderType==t)),0==r.length)throw new Kr("Cannot get update providers! Requested update providers has not been registered.");return r}throw new Kr("Cannot get update providers! Bad parameters.")}))}GetSoftwareRuntimeInfoAsync(){return Xr(this,arguments,void 0,(function*(e=!1){var t=yield this._semaphore.AcquireAsync();return!this._isRuntimeInfoInitialized||e?(yield this.GetRuntimeControllerInfoAsync(),t.Release(),this._runtimeInfo):(t.Release(),this._runtimeInfo)}))}GetRuntimeControllerInfoAsync(){return Xr(this,void 0,void 0,(function*(){Fv.Get(s.ServiceName).Debug(Qr.ServiceName,"Getting runtime version info from controller.");try{const e=yield Fv.Get(Pt.ServiceName).SendAndWaitForResponseAsync(new eo,16e3,!1);if(null==e||null==e.Status)throw new so('Cannot get runtime info, controller response result is empty."',zr.EmptyResponse);if(e.Status!=ce.OK)throw new so(`Cannot get runtime info, controller responded with status ${e.Status}.`,zr.WrongResponseStatus);if(null==e.Data)throw new so("Cannot get runtime info, controller responded with status OK but response does not contains data.",zr.NoDataInResponse);this._runtimeInfo=e.Data,this._isRuntimeInfoInitialized=!0}catch(e){throw e instanceof p?new so("Cannot get runtime info, controller response timeout.",zr.Timeout):e}}))}GetHardwareInfoAsync(){return Xr(this,arguments,void 0,(function*(e=!1){return!this._isHardwareInfoInitialized||e?(yield this.GetHardwareControllerInfoAsync(),this._hardwareInfo):this._hardwareInfo}))}GetHardwareControllerInfoAsync(){return Xr(this,void 0,void 0,(function*(){Fv.Get(s.ServiceName).Debug(Qr.ServiceName,"Getting hardware info from controller.");const e=yield Fv.Get(Pt.ServiceName).SendAndWaitForResponseAsync(new no,8e3,!1);if(null==e||null==e.Status)throw new so('Cannot get hardware info, controller response result is empty."',zr.EmptyResponse);if(e.Status!=ce.OK)throw new so(`Cannot get hardware info, controller responded with status ${e.Status}.`,zr.WrongResponseStatus);if(null==e.Data)throw new so("Cannot get hardware info, controller responded with status OK but response does not contains data.",zr.NoDataInResponse);this._hardwareInfo=e.Data,this._isRuntimeInfoInitialized=!0}))}}Qr.ServiceName="UpdateProvider";class Zr{constructor(){this.BaseLinuxVersion="",this.BaseMonoVersion="",this.RuntimeVersion="",this.UpdateChannel="",this.SoftwareVersion=""}}class eo extends ae{constructor(){super(),this.Resource="/controller/software/info",this.Method=ue.Get}}class to{constructor(){this.GetControllerHardwareVersion=0,this.DevicePIN="",this.GetControllerSerialNumber="",this.HostnamePrefix="",this.DefaultStaticIpAddress="",this.GetAvailableHardware=[],this.ControllerSecret=""}}class no extends ae{constructor(){super(),this.Resource="/controller/hardware/info",this.Method=ue.Get}}class so extends Error{constructor(e,t){super(e),this.message=e,this.code=0,this.name="CannotGetRuntimeInfo",this.code=t}}!function(e){e[e.Unknown=0]="Unknown",e[e.EmptyResponse=1]="EmptyResponse",e[e.NoDataInResponse=2]="NoDataInResponse",e[e.WrongResponseStatus=3]="WrongResponseStatus",e[e.Timeout=4]="Timeout"}(zr||(zr={})),function(e){e[e.None=0]="None",e[e.AppNotification=1]="AppNotification",e[e.Email=2]="Email"}(Jr||(Jr={})),function(e){e[e.Timeout=0]="Timeout",e[e.TimeRange=1]="TimeRange"}(Yr||(Yr={}));var ro,oo,io,ao;class co{constructor(e,t="Cube"){this._result=null,this._tmp=new uo,this._tmpTask=null,this._prevSeqGuid="",this._currentSeqGuid="",this._editingExistingSequence=!1,this._rawExistingSequenceTasks=null,this._sequenceName="",this._sequenceIcon="",this._service=Fv.Get(ko.ServiceName),e&&(this._sequenceName=e,this._sequenceIcon=t,this._tmp.Guid=xs.NewGuid())}SetSequenceName(e){this._sequenceName=e,this._editingExistingSequence&&null!=this._result&&(this._result.Name=e)}SetSequenceIcon(e){this._sequenceIcon=e,this._editingExistingSequence&&null!=this._result&&(this._result.Icon=e)}GetNext(){if(null==this._result)return null;if(""==this._currentSeqGuid)return this._currentSeqGuid=this._result.Guid,this._service.MapSequence(JSON.parse(JSON.stringify(this._result)),!0);{const e=this.FindArgumentWithGuid(this._result,this._currentSeqGuid);return null==e?null:e.RightArgumentType==ao.Condition?(this._prevSeqGuid=this._currentSeqGuid,this._currentSeqGuid=e.RightArgument.Guid,this._service.MapSequence(JSON.parse(JSON.stringify(e.RightArgument)),!0)):null}}CloneCurrentBuilder(){var e=new co;return e._currentSeqGuid="",e._prevSeqGuid="",e._editingExistingSequence=structuredClone(this._editingExistingSequence),e._rawExistingSequenceTasks=structuredClone(this._rawExistingSequenceTasks),e._result=structuredClone(this._result),e._sequenceIcon=structuredClone(this._sequenceIcon),e._sequenceName=structuredClone(this._sequenceName),e._tmp=structuredClone(this._tmp),(e=>{const t=e=>{e.Guid=xs.NewGuid(),e.RightArgumentType==ao.Condition&&t(e.RightArgument)};null!=e._result&&t(e._result),null!=this._tmp&&(this._tmp.Guid=xs.NewGuid())})(e),e}GetPrevious(){let e="";const t=(n,s)=>n.Guid==s?{sequence:n,prevGuid:e}:n.RightArgumentType==ao.Condition?(e=n.Guid,t(n.RightArgument,s)):null;if(null==this._result)return null;if(""==this._currentSeqGuid||""==this._prevSeqGuid)return null;const n=t(this._result,this._prevSeqGuid);return null==n?null:(this._currentSeqGuid=n.sequence.Guid,this._prevSeqGuid=n.prevGuid,this._service.MapSequence(JSON.parse(JSON.stringify(n.sequence)),!0))}GetByGuid(e){if(null==this._result)return null;const t=this.FindArgumentWithGuid(this._result,e);return null==t?null:this._service.MapSequence(t)}EditCurrentSequence(e){const t=e=>{if(e.RightArgumentType!=ao.Null)return t(e.RightArgument);this._rawExistingSequenceTasks=JSON.parse(JSON.stringify(e.Tasks))};return this._editingExistingSequence=!0,t(e._rawRequestData),Object.hasOwn(e._rawRequestData,"Condition")?this._result=e._rawRequestData.Condition:this._result=e._rawRequestData,{GetNext:()=>this.GetNext(),GetPrevious:()=>this.GetPrevious(),GetByGuid:e=>this.GetByGuid(e),GetAllowedArguments:()=>this.GetAllowedArguments(),RemoveSequence:e=>this.RemoveSequenceByGuid(e),ArgumentAsAstronomicalClockWithOffset:(e,t,n)=>this.ArgumentAsAstronomicalClockWithOffset(e,t,n),ArgumentAsDaysOfWeek:(e,t,n)=>this.ArgumentAsDaysOfWeek(e,t,n),ArgumentAsDeviceState:(e,t,n,s=kr.Equal)=>this.ArgumentAsDeviceState(e,t,n,s),ArgumentAsTime:(e,t,n=kr.Equal)=>this.ArgumentAsTime(e,t,n),ArgumentAsTimeSpan:(e,t)=>this.ArgumentAsTimeSpan(e,t),ArgumentAsSceneExecuted:e=>this.ArgumentAsSceneExecuted(e),RemoveTask:e=>this.RemoveTask(e)}}ArgumentAsAstronomicalClockWithOffset(e,t,n){if(this._tmp.Guid=xs.NewGuid(),this._tmp.HandledType=Dr.AstronomicalClockWithOffset,this._tmp.LeftArgumentType=ao.ArgumentAsAstronomicalClockWithOffset,this._tmp.AtMeetCondition=t,t&&null!=n&&n!=kr.Equal)throw new So("AtmeetCondition supports only comparation type 'Equal'.");if(e.Offset<-3600||e.Offset>3600)throw new So("Offset must be in range between -3600 and 3600 seconds.");if(t)this._tmp.ConditionType=kr.Equal;else{if(null==n)throw new So("Comparasion type must be provided if atMeetCondition is false!");this._tmp.ConditionType=n}return this._tmp.LeftArgument.Argument=e,this._tmp.LeftArgument.HandledType=ao.ArgumentAsAstronomicalClockWithOffset,{AddArgument:()=>this.AddSequence(),EditArgument:e=>this.EditSequence(e)}}ArgumentAsActionWithEmptyCondition(){return this._tmp.Guid=xs.NewGuid(),this._tmp.HandledType=Dr.Unknown,this._tmp.LeftArgumentType=ao.Null,this._tmp.ConditionType=kr.Equal,this._tmp.LeftArgument.Argument=null,this._tmp.LeftArgument.HandledType=ao.Null,this._tmp.Name=this._sequenceName,this._tmp.Icon=this._sequenceIcon,this._tmp.AtMeetCondition=!1,{AddArgument:()=>this.AddSequence(),EditArgument:e=>this.EditSequence(e)}}ArgumentAsDaysOfWeek(e,t,n=kr.Equal){return this._tmp.Guid=xs.NewGuid(),this._tmp.HandledType=Dr.DaysOfWeek,this._tmp.LeftArgumentType=ao.ArgumentAsDaysOfWeek,this._tmp.ConditionType=n,this._tmp.LeftArgument.Argument=e,this._tmp.LeftArgument.HandledType=ao.ArgumentAsDaysOfWeek,this._tmp.AtMeetCondition=t,{AddArgument:()=>this.AddSequence(),EditArgument:e=>this.EditSequence(e)}}ArgumentAsTimeSpan(e,t=kr.Equal){return this._tmp.Guid=xs.NewGuid(),this._tmp.HandledType=Dr.Timer,this._tmp.LeftArgumentType=ao.ArgumentAsTimeSpan,this._tmp.ConditionType=t,this._tmp.AtMeetCondition=!0,this._tmp.LeftArgument.Argument=e,this._tmp.LeftArgument.HandledType=ao.ArgumentAsTimeSpan,{AddArgument:()=>this.AddSequence(),EditArgument:e=>this.EditSequence(e)}}ArgumentAsTime(e,t,n=kr.Equal){return this._tmp.Guid=xs.NewGuid(),this._tmp.HandledType=Dr.Time,this._tmp.LeftArgumentType=ao.ArgumentAsTime,this._tmp.ConditionType=n,this._tmp.AtMeetCondition=t,this._tmp.LeftArgument.Argument=e,this._tmp.LeftArgument.HandledType=ao.ArgumentAsTime,{AddArgument:()=>this.AddSequence(),EditArgument:e=>this.EditSequence(e)}}ArgumentAsDeviceState(e,t,n,s=kr.Equal){return this._tmp.Guid=xs.NewGuid(),this._tmp.HandledType=Dr.DeviceState,this._tmp.LeftArgumentType=ao.ArgumentAsDeviceState,this._tmp.ConditionType=s,this._tmp.AtMeetCondition=t,this._tmp.ConditionTimeout=n,this._tmp.LeftArgument.Argument=this.GenerateDeviceStateArgument(e),this._tmp.LeftArgument.HandledType=ao.ArgumentAsDeviceState,{AddArgument:()=>this.AddSequence(),EditArgument:e=>this.EditSequence(e)}}ArgumentAsSceneExecuted(e){this._tmp.Guid=xs.NewGuid(),this._tmp.HandledType=Dr.SceneExecuted,this._tmp.LeftArgumentType=ao.ArgumentAsConditionInfo,this._tmp.ConditionType=kr.Equal,this._tmp.AtMeetCondition=!0;const t=new qr;return t.DeviceGuid=e.DeviceGuid,this._tmp.LeftArgument.Argument=t,this._tmp.LeftArgument.HandledType=ao.ArgumentAsConditionInfo,{AddArgument:()=>this.AddSequence(),EditArgument:e=>this.EditSequence(e)}}GenerateDeviceStateArgument(e){const t=new po;t.Channel=e.GetCheckDeviceState().Channel,t.ComparisonMethod=e.ComparisonMethod;let n={},s=e.GetComparisonParams().entries();for(const[e,t]of s)n=Object.assign(Object.assign({},n),{[Ar[e]]:t.Value});switch(t.ComparisonParams=n,t.DeviceGuid=e.DeviceGuid,t.DeviceStateType=this.MapResponseTypeToDeviceStateType(e.Type),e.Type){case At.BatteryState:t.CheckedDeviceState.State=e.GetCheckDeviceState().State,t.CheckedDeviceState.Percentage=e.GetCheckDeviceState().Percentage;break;case At.BinarySensorState:t.CheckedDeviceState.State=e.GetCheckDeviceState().State;break;case At.BlindPosition:t.CheckedDeviceState.Position=e.GetCheckDeviceState().Position;break;case At.LightBrightness:case At.MeasuredBrightness:t.CheckedDeviceState.Brightness=e.GetCheckDeviceState().Brightness;break;case At.RemoteButtonState:case At.ChannelOnOffState:case At.DoorBellState:t.CheckedDeviceState.State=e.GetCheckDeviceState().State;break;case At.MeasuredEnergy:{let n={},s=e.GetCheckDeviceState().MeasurementParameters.entries();for(const[e,t]of s)n=Object.assign(Object.assign({},n),{[jt[e]]:t});t.CheckedDeviceState.MeasurementParameters=n;break}case At.FloodSensorState:t.CheckedDeviceState.State=e.GetCheckDeviceState().State;break;case At.GatePosition:t.CheckedDeviceState.Position=e.GetCheckDeviceState().Position,t.CheckedDeviceState.PositionType=e.GetCheckDeviceState().PositionType;break;case At.LightColor:{const n=e.GetCheckDeviceState();t.CheckedDeviceState.R=n.R,t.CheckedDeviceState.G=n.G,t.CheckedDeviceState.B=n.B;break}case At.LightWarmth:t.CheckedDeviceState.Temperature=e.GetCheckDeviceState().Temperature;break;case At.ReedState:t.CheckedDeviceState.State=e.GetCheckDeviceState().State;break;case At.SmokeSensorState:throw new Vr("Unsupported device state!");case At.MeasuredTemperature:t.CheckedDeviceState.Temperature=e.GetCheckDeviceState().Temperature;break;case At.HumiditySensorState:t.CheckedDeviceState.Humidity=e.GetCheckDeviceState().Humidity;break;case At.BlindRemoteButtonState:t.CheckedDeviceState.State=e.GetCheckDeviceState().State;break;case At.LightRGBWState:{let n=e.GetCheckDeviceState();t.CheckedDeviceState.R=n.R,t.CheckedDeviceState.G=n.G,t.CheckedDeviceState.B=n.B,t.CheckedDeviceState.W=n.W;break}case At.FacadeRemoteButtonState:t.CheckedDeviceState.State=e.GetCheckDeviceState().State;break;case At.MovementSensorState:{let n=e.GetCheckDeviceState();t.CheckedDeviceState.Movement=n.Movement,t.CheckedDeviceState.Intensity=n.Intensity;break}case At.PressureSensorState:t.CheckedDeviceState.Pressure=e.GetCheckDeviceState().Pressure,t.CheckedDeviceState.PressureType=e.GetCheckDeviceState().PressureType;break;case At.WindSpeedState:t.CheckedDeviceState.Value=e.GetCheckDeviceState().Value;break;case At.CurrentWindThreshold:t.CheckedDeviceState.WindThreshold=e.GetCheckDeviceState().WindThreshold;break;case At.Unknown:t.CheckedDeviceState={};break;default:throw new Vr("Unsupported device state!")}return t}MapResponseTypeToDeviceStateType(e){switch(e){case At.BatteryState:return Gr.BatteryState;case At.BinarySensorState:return Gr.BinarySensor;case At.BlindPosition:return Gr.BlindPosition;case At.LightBrightness:return Gr.LightBrightness;case At.RemoteButtonState:return Gr.ButtonState;case At.ChannelOnOffState:return Gr.ChannelOnOff;case At.DoorBellState:return Gr.DoorBell;case At.MeasuredEnergy:return Gr.Energy;case At.FloodSensorState:return Gr.FloodSensor;case At.GatePosition:return Gr.GatePosition;case At.MeasuredBrightness:return Gr.Brightness;case At.LightColor:return Gr.LightColor;case At.LightWarmth:return Gr.LightTemperature;case At.ReedState:return Gr.ReedState;case At.SmokeSensorState:return Gr.SmokeSensor;case At.MeasuredTemperature:return Gr.Temperature;case At.HumiditySensorState:return Gr.Humidity;case At.BlindRemoteButtonState:return Gr.BlindsControlButton;case At.FacadeRemoteButtonState:return Gr.FacadeControlButton;case At.MovementSensorState:return Gr.Movement;case At.PressureSensorState:return Gr.AirPressure;case At.WindSpeedState:return Gr.WindSpeed;case At.CurrentWindThreshold:return Gr.WindThreshold;default:return Gr.Unknown}}AddSequence(){const e=(t,n)=>{if(t.RightArgumentType!=ao.Null)return e(t.RightArgument,n);t.RightArgumentType=ao.Condition,t.RightArgument=n,this._editingExistingSequence&&null!=this._rawExistingSequenceTasks&&(n.Tasks=JSON.parse(JSON.stringify(this._rawExistingSequenceTasks)),t.Tasks=new go)};null==this._result?(this._tmp.Name=this._sequenceName,this._tmp.Icon=this._sequenceIcon,this._result=this._tmp,this._result.AtMeetCondition=!0):e(this._result,this._tmp);const t=this._service.MapSequence(JSON.parse(JSON.stringify(this._tmp)));return this._tmp=new uo,{GetNext:()=>this.GetNext(),GetPrevious:()=>this.GetPrevious(),GetByGuid:e=>this.GetByGuid(e),GetAllowedArguments:()=>this.GetAllowedArguments(),RemoveSequenceByGuid:e=>this.RemoveSequenceByGuid(e),Commit:()=>this.Commit(),ArgumentAsActionWithEmptyCondition:()=>this.ArgumentAsActionWithEmptyCondition(),ArgumentAsAstronomicalClockWithOffset:(e,t,n)=>this.ArgumentAsAstronomicalClockWithOffset(e,t,n),ArgumentAsDaysOfWeek:(e,t,n)=>this.ArgumentAsDaysOfWeek(e,t,n),ArgumentAsDeviceState:(e,t,n,s=kr.Equal)=>this.ArgumentAsDeviceState(e,t,n,s),ArgumentAsTime:(e,t,n=kr.Equal)=>this.ArgumentAsTime(e,t,n),ArgumentAsTimeSpan:(e,t)=>this.ArgumentAsTimeSpan(e,t),ArgumentAsSceneExecuted:e=>this.ArgumentAsSceneExecuted(e),SequenceData:t}}EditSequence(e){const t=(n,s)=>{if(n.Guid!=e||n.ObjectType!=ao.Condition){if(n.RightArgumentType==ao.Condition)return t(n.RightArgument,s);throw new Ao(`Cannot edit sequence with given GUID ${e} - sequence not foud in chain`)}n.AtMeetCondition=s.AtMeetCondition,n.ConditionTimeout=s.ConditionTimeout,n.ConditionType=s.ConditionType,n.ExecuteOnce=s.ExecuteOnce,n.HandledType=s.HandledType,n.IsDisabled=s.IsDisabled,n.LeftArgument=s.LeftArgument,n.LeftArgumentType=s.LeftArgumentType,n.ObjectType=s.ObjectType,n.Tasks=s.Tasks,s.Guid=n.Guid,s.Icon=n.Icon,s.Name=n.Name};if(null==this._result)throw new Ao(`Cannot edit sequence with given GUID ${e} - sequence not initialized (no root element)`);t(this._result,this._tmp);const n=this._service.MapSequence(JSON.parse(JSON.stringify(this._tmp)));return this._tmp=new uo,console.log(`new tmp guid: ${this._tmp.Guid}`),this._result.AtMeetCondition||(this._result.AtMeetCondition=!0),{GetNext:()=>this.GetNext(),GetPrevious:()=>this.GetPrevious(),GetByGuid:e=>this.GetByGuid(e),GetAllowedArguments:()=>this.GetAllowedArguments(),RemoveSequenceByGuid:e=>this.RemoveSequenceByGuid(e),Commit:()=>this.Commit(),ArgumentAsActionWithEmptyCondition:()=>this.ArgumentAsActionWithEmptyCondition(),ArgumentAsAstronomicalClockWithOffset:(e,t,n)=>this.ArgumentAsAstronomicalClockWithOffset(e,t,n),ArgumentAsDaysOfWeek:(e,t,n)=>this.ArgumentAsDaysOfWeek(e,t,n),ArgumentAsDeviceState:(e,t,n,s=kr.Equal)=>this.ArgumentAsDeviceState(e,t,n,s),ArgumentAsTime:(e,t,n=kr.Equal)=>this.ArgumentAsTime(e,t,n),ArgumentAsTimeSpan:(e,t)=>this.ArgumentAsTimeSpan(e,t),ArgumentAsSceneExecuted:e=>this.ArgumentAsSceneExecuted(e),SequenceData:n}}RemoveSequenceByGuid(e){let t;const n=(e,n)=>{""==this._currentSeqGuid&&""==this._prevSeqGuid||(this._currentSeqGuid==n?(this._currentSeqGuid=e.RightArgumentType==ao.Condition?e.RightArgument.Guid:"",this._prevSeqGuid=null!=t?t.Guid:""):this._prevSeqGuid==n&&(this._prevSeqGuid=null!=t?t.Guid:""))},s=(e,r)=>{if(e.Guid!=r){if(t=e,e.RightArgumentType==ao.Null)throw new Ao(`Cannot remove sequence, sequence with given guid ${r} not found!`);return s(e.RightArgument,r)}null==t?this._result=null:(t.RightArgument=e.RightArgument,t.RightArgumentType=e.RightArgumentType),n(e,r)};if(null==this._result)throw new Ao("Cannot remove sequence, sequence not configured!");return this._result.Guid==e&&this._result.RightArgumentType!=ao.Null?(this._result.RightArgument.Name=this._result.Name,this._result.RightArgument.Icon=this._result.Icon,this._result.RightArgument.Guid=this._result.Guid,this._result=this._result.RightArgument,this._result.AtMeetCondition=!0,n(this._result,e)):s(this._result,e),{GetNext:()=>this.GetNext(),GetPrevious:()=>this.GetPrevious(),GetByGuid:e=>this.GetByGuid(e),GetAllowedArguments:()=>this.GetAllowedArguments(),RemoveSequenceByGuid:e=>this.RemoveSequenceByGuid(e),Commit:()=>this.Commit(),ArgumentAsActionWithEmptyCondition:()=>this.ArgumentAsActionWithEmptyCondition(),ArgumentAsAstronomicalClockWithOffset:(e,t,n)=>this.ArgumentAsAstronomicalClockWithOffset(e,t,n),ArgumentAsDaysOfWeek:(e,t,n)=>this.ArgumentAsDaysOfWeek(e,t,n),ArgumentAsDeviceState:(e,t,n,s=kr.Equal)=>this.ArgumentAsDeviceState(e,t,n,s),ArgumentAsTime:(e,t,n=kr.Equal)=>this.ArgumentAsTime(e,t,n),ArgumentAsTimeSpan:(e,t)=>this.ArgumentAsTimeSpan(e,t),ArgumentAsSceneExecuted:e=>this.ArgumentAsSceneExecuted(e),SequenceData:null}}Commit(){const e=t=>{if(t.RightArgumentType!=ao.Null)return e(t.RightArgument);null!=this._rawExistingSequenceTasks&&(t.Tasks=this._rawExistingSequenceTasks)};if(null==this._result)throw new Ao("Sequence are not initialized! Not found root sequence.");return this._editingExistingSequence&&e(this._result),{GetSupportedTypesOfTasks:()=>this.GetSupportedTaskTypesAsync(),DeviceTask:e=>this.DeviceTask(e),DelayTask:e=>this.DelayTask(e),NotifyTask:(e,t)=>this.NotifyTask(e,t),LockExecutionTask:e=>this.LockExecutionTask(e),RemoveTask:e=>this.RemoveTask(e),Build:()=>this.Build(),BuildToISequence:()=>this._service.MapSequence(JSON.parse(JSON.stringify(this._result))),ValidateScene:()=>this.ValidateScene()}}DeviceTask(e){if(this._tmpTask=this.ParseDeviceTask(e),null==this._result)throw new Error("No context!");return{AddTask:()=>this.AddTask(),EditTask:e=>this.EditTask(e),TaskId:re.GenerateMd5(JSON.stringify(this._tmpTask))}}ParseDeviceTask(e){const t=new vo;return t.Channel=e.Channel,t.DeviceGuid=e.DeviceGuid,t.ControlFeature=this.MapTaskTypeToControlFeature(e.TaskType),t.Data={},t.Data.Channel=e.Channel,e.TaskType==St.SetBlindPosition||e instanceof Ks?(t.Data.Position=e.Position,t.Data.Action=e.Action):e.TaskType==St.SetBlindPositionSimple||e instanceof zs?t.Data.Action=e.Action:e.TaskType==St.SetLightColor||e instanceof Hs?(t.Data.R=e.R,t.Data.G=e.G,t.Data.B=e.B):e.TaskType==St.SetLightTemperature||e instanceof js?t.Data.Temperature=e.Temperature:e.TaskType==St.SetLightBrightness||e instanceof qs?t.Data.Brightness=e.Brightness:e.TaskType==St.SetTemperature||e instanceof Ls?t.Data.Temperature=e.Temperature:e.TaskType==St.TurnOnWithTime||e instanceof $s?t.Data.SwitchOffDelaySeconds=e.SwitchOffDelaySeconds:e.TaskType==St.SetLightBrightnessDynamicly||e instanceof Js?t.Data.Brightness=e.Brightness:e.TaskType==St.SetBlindOpenCloseTime||e instanceof Xs?(t.Data.CloseTime=e.Data.CloseTime,t.Data.OpenTime=e.Data.OpenTime):e.TaskType==St.SetBlindMicroventilation||e instanceof er?t.Data.Position=e.Position:e.TaskType==St.SetFacadePosition||e instanceof sr?(t.Data.FacadeAction=e.FacadeAction,t.Data.Position=e.Position,t.Data.Tilt=e.Tilt):(e.TaskType==St.LightRGBW||e instanceof ir)&&(t.Data.R=e.Data.R,t.Data.G=e.Data.G,t.Data.B=e.Data.B,t.Data.W=e.Data.W,t.Data.Brightness=e.Data.Brightness),t}DelayTask(e){const t=new mo;if(t.Delay=e.Delay.Value,this._tmpTask=t,null==this._result)throw new Error("No context!");return{AddTask:()=>this.AddTask(),EditTask:e=>this.EditTask(e),TaskId:re.GenerateMd5(JSON.stringify(t))}}NotifyTask(e,t){if(e.NotifyType==Jr.Email)throw new Co("NotifyType 'Email' is not supported!");if(e.NotifyType==Jr.None)throw new Error("NotifyType mus be set!");if(""==e.Message)throw new So("Message must be set!");if(e.Message.length>1e3)throw new So("Message is too long! Max length is 1000 characters.");const n=new wo;if(n.NotifyType=e.NotifyType,n.Message=e.Message,n.Title=this._sequenceName,null!=t&&t.length>0&&(n.NotificationClients=t),this._tmpTask=n,null==this._result)throw new Error("No context!");return{AddTask:()=>this.AddTask(),EditTask:e=>this.EditTask(e),TaskId:re.GenerateMd5(JSON.stringify(n))}}LockExecutionTask(e){const t=new yo;if(t.LockType=e.LockType,t.LockType==Yr.Timeout&&"00:00:00"!=t.LockEndHour)throw new Co("Parameter LockEndHour at lock type `Timeout` must be default!");if(t.LockStartHour=e.LockStartHour.Value,t.LockEndHour=e.LockEndHour.Value,t.ResetLockScenesGuids=e.ResetLockScenesGuids,this._tmpTask=t,null==this._result)throw new Error("No context!");return{AddTask:()=>this.AddTask(),EditTask:e=>this.EditTask(e),TaskId:re.GenerateMd5(JSON.stringify(t))}}AddTask(){const e=t=>{if(t.RightArgumentType!=ao.Null)return e(t.RightArgument);if(null==this._tmpTask)throw Error("No task context!");void 0!==t.Tasks.DevicesTasks&&null!==t.Tasks.DevicesTasks||(t.Tasks.DevicesTasks=[]),this._tmpTask instanceof vo&&t.Tasks.DevicesTasks.push(structuredClone(this._tmpTask)),t.Tasks.ControllerTasks.push(structuredClone(this._tmpTask)),this._tmpTask=null,Fv.Get(s.ServiceName).Debug(`Task added to sequence: \n${JSON.stringify(this._tmpTask)} \ntasks on a list: \n${JSON.stringify(t.Tasks)}`)};if(null==this._result)throw new Error("No context!");return e(this._result),{GetSupportedTypesOfTasks:()=>this.GetSupportedTaskTypesAsync(),DeviceTask:e=>this.DeviceTask(e),DelayTask:e=>this.DelayTask(e),NotifyTask:(e,t)=>this.NotifyTask(e,t),LockExecutionTask:e=>this.LockExecutionTask(e),RemoveTask:e=>this.RemoveTask(e),Build:()=>this.Build(),BuildToISequence:()=>this._service.MapSequence(JSON.parse(JSON.stringify(this._result))),ValidateScene:()=>this.ValidateScene()}}EditTask(e){const t=n=>{if(n.RightArgumentType!=ao.Null)return t(n.RightArgument);if(null==this._tmpTask)throw Error("No task context!");if(null==n.Tasks.ControllerTasks||0==n.Tasks.ControllerTasks.length)throw new _o("Task not found, cannot edit!");this._tmpTask instanceof vo&&null!=n.Tasks.DevicesTasks&&(n.Tasks.DevicesTasks=n.Tasks.DevicesTasks.map((t=>re.GenerateMd5(JSON.stringify(t))==e?structuredClone(this._tmpTask):t))),n.Tasks.ControllerTasks=n.Tasks.ControllerTasks.map((t=>re.GenerateMd5(JSON.stringify(t))==e?structuredClone(this._tmpTask):t)),this._tmpTask=null,Fv.Get(s.ServiceName).Debug(`Task edited in sequence: \n${JSON.stringify(this._tmpTask)} \ntasks on a list: \n${JSON.stringify(n.Tasks)}`)};if(null==this._result)throw new Error("No context!");return t(this._result),{GetSupportedTypesOfTasks:()=>this.GetSupportedTaskTypesAsync(),DeviceTask:e=>this.DeviceTask(e),DelayTask:e=>this.DelayTask(e),NotifyTask:(e,t)=>this.NotifyTask(e,t),LockExecutionTask:e=>this.LockExecutionTask(e),RemoveTask:e=>this.RemoveTask(e),Build:()=>this.Build(),BuildToISequence:()=>this._service.MapSequence(JSON.parse(JSON.stringify(this._result))),ValidateScene:()=>this.ValidateScene()}}RemoveTask(e){const t=(e,n)=>{if(e.RightArgumentType!=ao.Null)return t(e.RightArgument,n);{const t=e.Tasks.ControllerTasks.filter((e=>re.GenerateMd5(JSON.stringify(e))!=n));if(e.Tasks.ControllerTasks=null==t?[]:t,e.Tasks.DevicesTasks.any()){const t=e.Tasks.DevicesTasks.filter((e=>re.GenerateMd5(JSON.stringify(e))!=n));e.Tasks.DevicesTasks=null==t?[]:t}}};if(null==this._result)throw Error("Cannot remove task, sequence not configured!");t(this._result,e)}MapTaskTypeToControlFeature(e){switch(e){case St.Unknown:throw new So("Unsupported task type!");case St.SetBlindPosition:case St.SetBlindPositionSimple:return Gs.SetBlindPosition;case St.SetBlindMicroventilation:return Gs.SetBlindMicroventilation;case St.TurnOff:return Gs.TurnOff;case St.TurnOn:return Gs.TurnOn;case St.TurnOnWithTime:return Gs.TurnOnWithTimeout;case St.TogleState:return Gs.ToggleState;case St.SetLightBrightnessDynamicly:return Gs.SetLightBrightnessDynamicly;case St.SetLightBrightness:return Gs.SetLightBrightness;case St.SetLightColor:return Gs.SetLightColor;case St.SetLightTemperature:return Gs.SetLightTemperature;case St.PairDevice:case St.UnpairDevice:throw new So("Unsupported task type!");case St.IdentifyDevice:return Gs.IdentifyDevice;case St.GetChannelsState:return Gs.GetState;case St.GetPowerMeasurements:case St.GetAvailableData:case St.MultipleDataRequest:throw new So("Unsupported task type!");case St.SetBlindOpenCloseTime:return Gs.SetBlindOpenCloseTime;case St.SetTemperature:return Gs.SetTemperature;case St.ChangeGatePositionPulse:return Gs.GatePulse;case St.ChangeGatewayPositionPulse:return Gs.GatewayPulse;case St.SetFacadePosition:case St.GetFacadeType:return Gs.SetFacadePositionAndTilt;case St.LightRGBW:return Gs.LightRGBW;default:throw new So("Unsupported task type!")}}GetSupportedTaskTypesAsync(){return e=this,t=void 0,s=function*(){const e=yield Fv.Get(Qr.ServiceName).GetSoftwareRuntimeInfoAsync(),[t,n]=e.SoftwareVersion.split(".").map((e=>parseInt(e))),s=[oo.DeviceTask];return t>=5&&n>=27&&s.push(oo.DelayTask),t>=5&&n>=37&&s.push(oo.LockExecutionTask),t>=5&&n>=106&&s.push(oo.NotifyTaskAppNotify),s},new((n=void 0)||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}));var e,t,n,s}Build(){const e=t=>{if(t.RightArgumentType!=ao.Null)return e(t.RightArgument);t.Tasks.ControllerTasks=t.Tasks.ControllerTasks.map((e=>(Object.hasOwn(e,"_taskGuid")&&delete e._taskGuid,e)))};if(null!=this._result)return e(this._result),this._result;throw Error("Cannot build sequence, sequence not configured!")}FindArgumentWithGuid(e,t){return e.Guid==t?e:e.RightArgumentType==ao.Condition?this.FindArgumentWithGuid(e.RightArgument,t):null}GetAllowedArguments(){const e=[];return null==this._result?(e.push({ArgumentType:io.ArgumentAsAstronomicalClockWithOffset,InitialAtMeetConditionValue:!0,ChangableAtMeetCondition:!1}),e.push({ArgumentType:io.ArgumentAsDaysOfWeek,InitialAtMeetConditionValue:!0,ChangableAtMeetCondition:!1}),e.push({ArgumentType:io.ArgumentAsDeviceState,InitialAtMeetConditionValue:!0,ChangableAtMeetCondition:!1}),e.push({ArgumentType:io.ArgumentAsSceneExecuted,InitialAtMeetConditionValue:!0,ChangableAtMeetCondition:!1}),e.push({ArgumentType:io.ArgumentAsTime,InitialAtMeetConditionValue:!0,ChangableAtMeetCondition:!1}),e.push({ArgumentType:io.ArgumentAsTimeSpan,InitialAtMeetConditionValue:!0,ChangableAtMeetCondition:!1})):null!=this._result&&(null==this._result.RightArgument||this._result.RightArgument instanceof lo)&&(this._result.LeftArgumentType==ao.ArgumentAsDaysOfWeek&&(e.push({ArgumentType:io.ArgumentAsTime,InitialAtMeetConditionValue:!0,ChangableAtMeetCondition:!0}),e.push({ArgumentType:io.ArgumentAsAstronomicalClockWithOffset,InitialAtMeetConditionValue:!0,ChangableAtMeetCondition:!0})),this._result.LeftArgumentType==ao.ArgumentAsTime&&e.push({ArgumentType:io.ArgumentAsDaysOfWeek,InitialAtMeetConditionValue:!1,ChangableAtMeetCondition:!1}),this._result.LeftArgumentType==ao.ArgumentAsAstronomicalClockWithOffset&&e.push({ArgumentType:io.ArgumentAsDaysOfWeek,InitialAtMeetConditionValue:!1,ChangableAtMeetCondition:!1})),0==e.any((e=>e.ArgumentType==io.ArgumentAsAstronomicalClockWithOffset))&&e.push({ArgumentType:io.ArgumentAsAstronomicalClockWithOffset,InitialAtMeetConditionValue:!1,ChangableAtMeetCondition:!0}),0==e.any((e=>e.ArgumentType==io.ArgumentAsDaysOfWeek))&&e.push({ArgumentType:io.ArgumentAsDaysOfWeek,InitialAtMeetConditionValue:!1,ChangableAtMeetCondition:!0}),0==e.any((e=>e.ArgumentType==io.ArgumentAsDeviceState))&&e.push({ArgumentType:io.ArgumentAsDeviceState,InitialAtMeetConditionValue:!0,ChangableAtMeetCondition:!0}),0==e.any((e=>e.ArgumentType==io.ArgumentAsSceneExecuted))&&e.push({ArgumentType:io.ArgumentAsSceneExecuted,InitialAtMeetConditionValue:!0,ChangableAtMeetCondition:!1}),0==e.any((e=>e.ArgumentType==io.ArgumentAsTime))&&e.push({ArgumentType:io.ArgumentAsTime,InitialAtMeetConditionValue:!1,ChangableAtMeetCondition:!0}),0==e.any((e=>e.ArgumentType==io.ArgumentAsTimeSpan))&&e.push({ArgumentType:io.ArgumentAsTimeSpan,InitialAtMeetConditionValue:!0,ChangableAtMeetCondition:!1}),e}ValidateScene(){var e,t,n,s;if(null==this._result)throw new Error("No context!");const r=[],o=(e,t,n)=>e.RightArgumentType==ao.Null?e.LeftArgumentType==t&&e.AtMeetCondition==n?e:null:e.LeftArgumentType==t&&e.AtMeetCondition==n?e:o(e.RightArgument,t,n),i=o(this._result,ao.ArgumentAsDaysOfWeek,!0);null!=i&&((null===(e=i.RightArgument)||void 0===e?void 0:e.LeftArgumentType)==ao.ArgumentAsTime||(null===(t=i.RightArgument)||void 0===t?void 0:t.LeftArgumentType)==ao.ArgumentAsAstronomicalClockWithOffset)&&r.push(ro.OptimizeDayOfWeekArgument);const a=o(this._result,ao.ArgumentAsTime,!0);return null!=a&&(null===(n=a.RightArgument)||void 0===n?void 0:n.LeftArgumentType)==ao.ArgumentAsDaysOfWeek&&(null===(s=a.RightArgument)||void 0===s?void 0:s.AtMeetCondition)&&r.push(ro.OptimizeAtInDayOfWeekArgument),{IsValid:0==r.length,Errors:r,TryFix:()=>this.TryFix(r),Ignore:()=>this.Commit()}}TryFix(e){if(null==this._result)throw new Error("No context!");if(e.includes(ro.OptimizeDayOfWeekArgument)){const e=t=>{var n,s;return t.LeftArgumentType==ao.ArgumentAsDaysOfWeek?(null===(n=t.RightArgument)||void 0===n?void 0:n.LeftArgumentType)==ao.ArgumentAsTime||(null===(s=t.RightArgument)||void 0===s?void 0:s.LeftArgumentType)==ao.ArgumentAsAstronomicalClockWithOffset?t:e(t.RightArgument):t.RightArgumentType==ao.Null?null:e(t.RightArgument)},t=e(this._result);if(null==t)throw new Error("Something wrong! Cannot find 'days of week' argument! Cannot fix!");const n=structuredClone(t),s=t.RightArgument;t.LeftArgument=s.LeftArgument,t.LeftArgumentType=s.LeftArgumentType,t.HandledType=s.HandledType,s.LeftArgument=n.LeftArgument,s.LeftArgumentType=n.LeftArgumentType,s.HandledType=n.HandledType,s.AtMeetCondition=!1}if(e.includes(ro.OptimizeAtInDayOfWeekArgument)){const e=t=>{var n,s;return t.LeftArgumentType==ao.ArgumentAsTime?(null===(n=t.RightArgument)||void 0===n?void 0:n.LeftArgumentType)==ao.ArgumentAsDaysOfWeek&&(null===(s=t.RightArgument)||void 0===s?void 0:s.AtMeetCondition)?t:e(t.RightArgument):t.RightArgumentType==ao.Null?null:e(t.RightArgument)},t=e(this._result);if(null==t)throw new Error("Something wrong! Cannot find 'time' argument! Cannot fix!");t.RightArgument.AtMeetCondition=!1}return this.Commit()}}!function(e){e.OptimizeDayOfWeekArgument="OptimizeDayOfWeekArgument",e.OptimizeAtInDayOfWeekArgument="OptimizeAtInDayOfWeekArgument"}(ro||(ro={})),function(e){e.DeviceTask="DeviceTask",e.DelayTask="DelayTask",e.LockExecutionTask="LockExecutionTask",e.NotifyTaskAppNotify="NotifyTaskAppNotify",e.NotifyTaskEmailNotify="NotifyTaskEmailNotify"}(oo||(oo={})),function(e){e.Unknown="Unknown",e.ArgumentAsAstronomicalClockWithOffset="ArgumentAsAstronomicalClockWithOffset",e.ArgumentAsDaysOfWeek="ArgumentAsDaysOfWeek",e.ArgumentAsTimeSpan="ArgumentAsTimeSpan",e.ArgumentAsTime="ArgumentAsTime",e.ArgumentAsDeviceState="ArgumentAsDeviceState",e.ArgumentAsSceneExecuted="ArgumentAsSceneExecuted"}(io||(io={}));class uo{constructor(){this.Tasks=new go,this.Guid="",this.ObjectType=1,this.Name="",this.Icon="",this.AtMeetCondition=!1,this.ExecuteOnce=!1,this.IsDisabled=!1,this.HandledType=Dr.Unknown,this.ConditionType=kr.Unknown,this.ConditionTimeout=0,this.LeftArgumentType=ao.Null,this.RightArgumentType=ao.Null,this.LeftArgument=new ho({},ao.Null),this.RightArgument=new lo}}class lo{constructor(){this.HandledType=0,this.Argument=null}}class ho{constructor(e,t){this.Argument=e,this.HandledType=t}}class po{constructor(){this.DeviceStateType=Gr.Unknown,this.Channel=0,this.DeviceGuid="",this.ComparisonMethod=Sr.Default,this.ComparisonParams=null,this.CheckedDeviceState={}}}class go{constructor(){this.ControllerTasks=[],this.DevicesTasks=[]}}class fo{constructor(){this.RunParallel=!1,this.TaskType=Cr.Unknown}}class vo extends fo{constructor(){super(...arguments),this.TaskType=Cr.DeviceTask,this.DeviceGuid="",this.Channel=0,this.ControlFeature=Gs.TurnOn}}class mo extends fo{constructor(){super(...arguments),this.TaskType=Cr.DelayTask,this.Delay="00:00:00"}}class yo extends fo{constructor(){super(...arguments),this.TaskType=Cr.LockExecution,this.LockType=Yr.Timeout,this.LockStartHour="00:00:00",this.LockEndHour="00:00:00",this.ResetLockScenesGuids=[]}}class wo extends fo{constructor(){super(...arguments),this.TaskType=Cr.NotifyTask,this.Title="",this.Message="",this.NotifyType=Jr.None,this.NotificationClients=[]}}!function(e){e[e.Null=0]="Null",e[e.Condition=1]="Condition",e[e.ConditionGroup=2]="ConditionGroup",e[e.ArgumentAsInt=3]="ArgumentAsInt",e[e.ArgumentAsTimeSpan=4]="ArgumentAsTimeSpan",e[e.ArgumentAsBoolean=5]="ArgumentAsBoolean",e[e.ArgumentAsTimeout=6]="ArgumentAsTimeout",e[e.ArgumentAsDayOfWeek=7]="ArgumentAsDayOfWeek",e[e.ArgumentAsDaysOfWeek=8]="ArgumentAsDaysOfWeek",e[e.ArgumentAsAstronomicalClock=9]="ArgumentAsAstronomicalClock",e[e.ArgumentAsTime=10]="ArgumentAsTime",e[e.ArgumentAsDeviceState=11]="ArgumentAsDeviceState",e[e.ArgumentAsNumber=12]="ArgumentAsNumber",e[e.ArgumentAsAstronomicalClockWithOffset=13]="ArgumentAsAstronomicalClockWithOffset",e[e.ArgumentAsConditionInfo=14]="ArgumentAsConditionInfo"}(ao||(ao={}));class So extends Error{constructor(e){super(e),this.message=e,this.name="BadParametersScenesBuilderException"}}class Ao extends Error{constructor(e){super(e),this.message=e,this.name="SequenceNotFoundScenesBuilderException"}}class _o extends Error{constructor(e){super(e),this.message=e,this.name="TaskNotFoundScenesBuilderException"}}class Co extends Error{constructor(e){super(e),this.message=e,this.name="UnsupportedArgumentScenesBuilderException"}}var To,Do=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class ko{constructor(){this._connection=Fv.Get(Pt.ServiceName),this._configurationService=Fv.Get(rt.ServiceName)}GetServiceName(){return ko.ServiceName}GetSequencesListAsync(){return Do(this,void 0,void 0,(function*(){var e;const t=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new Go,12e3,!1);return Fv.Get(s.ServiceName).Debug(`GetSequencesListAsync result:\n ${JSON.stringify(t)}}`),null==t?new De(wr.OtherError,"Cannot get sequences list - response is null."):t.Status!=ce.OK?new De(wr.OtherError,`Cannot get sequences list - controller responded with response code ${t.Status}.`):null==t.Data?new De(wr.NoData,"Cannot get sequences list - controller responded with status OK, but response does not contain data!"):t.Data}))}GetSequenceAsync(e){return Do(this,void 0,void 0,(function*(){var t;let n="";n="string"==typeof e?e:e.Guid;const s=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new bo(n),12e3,!1);if(null==s)return new De(wr.OtherError,"Cannot get sequence - response is null.");if(s.Status!=ce.OK)return new De(wr.OtherError,`Cannot get sequence - controller responded with response code ${s.Status}.`);if(null==s.Data)return new De(wr.NoData,"Cannot get sequence - controller responded with status OK, but response does not contain data!");const r=s.Data;return this.MapSequence(r)}))}GetSequenceBuilder(e,t){return new co(e,t)}CreateSequenceAsync(e){return Do(this,void 0,void 0,(function*(){var t;try{yield this._configurationService.EnterConfigurationModeAsync(),Fv.Get(s.ServiceName).Debug(`Creating sequence ${e.Name} json: \n${JSON.stringify(e)}`);const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Ro(e),2e4,!1);return null==n||null==n.Status?ce.Error:n.Status}catch(t){return Fv.Get(s.ServiceName).Error(`Creating sequence ${e.Name} error: ${t}`),ce.FatalError}finally{yield this._configurationService.ExitConfigurationModeAsync()}}))}CheckIfSequenceIsUsedInAnotherSequenceAsync(e){return Do(this,void 0,void 0,(function*(){var t;try{let n="";n="string"==typeof e?e:e.Guid;const s=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new No(n),12e3,!1);if(null==s)return new De(wr.OtherError,"Cannot get sequence - response is null.");switch(s.Status){case ce.WrongData:return new De(wr.InvalidSceneGuid,"Cannot check if sequence is used in another sequence! Sequence not found, invalid sequence guid!");case ce.OK:return null==s.Data?new De(wr.NoData,"Cannot get sequence - controller responded with status OK, but response does not contain data!"):s.Data;default:return new De(wr.OtherError,`Cannot check if sequence is used in another sequence! Controller responded with code: ${s.Status}`)}}catch(e){return new De(wr.FatalError,`Cannot check if sequence is used in another sequence! Fatal error! ${e}`)}}))}DeleteSequenceAsync(e){return Do(this,void 0,void 0,(function*(){var t;try{let n="";n="string"==typeof e?e:e.Guid,yield this._configurationService.EnterConfigurationModeAsync();const s=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Oo(n),12e3,!1);return null==s||null==s.Status?ce.Error:s.Status}catch(e){return ce.FatalError}finally{yield this._configurationService.ExitConfigurationModeAsync()}}))}EditSequenceAsync(e){return Do(this,void 0,void 0,(function*(){var t;try{const n={Guid:e.Guid,Icon:e.Icon,Name:e.Name,Condition:e};yield this._configurationService.EnterConfigurationModeAsync();const s=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Po(n),2e4,!1);return null==s||null==s.Status?ce.Error:s.Status}catch(t){return Fv.Get(s.ServiceName).Error(`Editing sequence ${e.Name} error: ${t}`),ce.FatalError}finally{yield this._configurationService.ExitConfigurationModeAsync()}}))}EnableSequenceAsync(e){return Do(this,void 0,void 0,(function*(){var t;let n="";n="string"==typeof e?e:e.Guid;const s=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Uo(n),12e3,!1);return null==s||null==s.Status?ce.Error:s.Status}))}DisableSequenceAsync(e){return Do(this,void 0,void 0,(function*(){var t;let n="";n="string"==typeof e?e:e.Guid;const s=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Mo(n),12e3,!1);return null==s||null==s.Status?ce.Error:s.Status}))}RunSequenceAsync(e){return Do(this,void 0,void 0,(function*(){let t="";if("string"==typeof e){const n=yield this.GetSequencesListAsync();if(null!=n.Type)return ce.Error;{const s=n.find((t=>t.Guid==e));if(!s)return ce.Error;t=s.DeviceGuid}}else t=e.DeviceGuid;const n=new Ws;switch(n.Channel=1,n.DeviceGuid=t,yield Fv.Get(Fo.ServiceName).ExecuteDeviceTaskAsync({Guid:t},n)){case kt.Executed:return ce.OK;case kt.DeviceNotFound:return ce.WrongData;default:return ce.Error}}))}GetUtilsAsync(){return Do(this,void 0,void 0,(function*(){const e=yield this.SunCalculatorAsync();return{GetSunRiseTime:e.GetSunRiseTime,GetSunSetTime:e.GetSunSetTime,ParseLinearScaleToLux:this._parseLinearScaleToLux,ParseLuxToLinearScale:this._parseLuxToLinearScale}}))}_parseLinearScaleToLux(e){if(!(e<0||e>1))return Math.round(Math.pow(10,5*e))}_parseLuxToLinearScale(e){if(e<=0)return 0;const t=Math.log10(e)/5;return t>1?1:t}SunCalculatorAsync(){return Do(this,void 0,void 0,(function*(){const e=Fv.Get(Mr.ServiceName),t=new mr;let n=!1;t.Latitude=49.9958888026741,t.Longitude=18.9172596008914;try{if(yield e.IsControllerGeolocationSetAsync()){const n=yield e.GetControlllerGeolocationAsync();n instanceof yr&&(t.Latitude=n.Latitude,t.Longitude=n.Longitude)}}catch(e){Fv.Get(s.ServiceName).Warning(`Cannot get localization data, using default values: 49.9958888026741, 18.9172596008914. Error: ${e}`)}const r=e=>{let n=7.95204*Math.sin(.01768*e+3.03217)+9.98906*Math.sin(.03383*e+3.4687)+4*(t.Longitude-15*Math.round(t.Longitude/15));return((e=new Date)=>{const t=new Date(e.getFullYear(),0,1).getTimezoneOffset(),n=new Date(e.getFullYear(),6,1).getTimezoneOffset();return Math.max(t,n)!==e.getTimezoneOffset()})()&&(n-=60),n},o=e=>Math.asin(-.39795*Math.cos(2*Math.PI*(e+10)/365)),i=e=>{const n=t.Latitude*Math.PI/180;let s=Math.sin(n)*Math.sin(e)/(Math.cos(n)*Math.cos(e));return s=(e=>(e<-1&&(e=-1),e>1&&(e=1),e))(s),s},a=e=>{const t=Math.ceil(e/60),n=e-60*t,s=new Date;return new Date(s.getFullYear(),s.getMonth(),s.getDate(),t,n)},c=e=>{const t=new Date;t.setDate(t.getDate()+e);const s=(u=t,Math.floor((u.valueOf()-new Date(u.getFullYear(),0,0).valueOf())/1e3/60/60/24));var u;const l=r(s),d=o(s),h=((e,t)=>{let n=720-720/Math.PI*Math.acos(-e)-t;return n<0&&(n+=1440),n})(i(d),l),p=a(h);return new Date>p&&!n?(n=!0,c(1)):(n=!1,new Date(t.getFullYear(),t.getMonth(),t.getDate(),p.getHours(),p.getMinutes()))},u=e=>{const t=new Date;t.setDate(t.getDate()+e);const s=(c=t,Math.floor((c.valueOf()-new Date(c.getFullYear(),0,0).valueOf())/1e3/60/60/24));var c;const l=r(s),d=o(s),h=i(d),p=Math.floor(((e,t)=>{let n=720+720/Math.PI*Math.acos(-e)-t;return n>1439&&(n-=1439),n})(h,l)),g=a(p);return new Date>g&&!n?(n=!0,u(1)):(n=!1,new Date(t.getFullYear(),t.getMonth(),t.getDate(),g.getHours(),g.getMinutes()))};return{GetSunRiseTime:()=>c(0),GetSunSetTime:()=>u(0)}}))}MapSequence(e,t=!1){const n=Object.assign({},e),s=e=>{if(e.RightArgumentType!=To.Null)return!Object.hasOwn(e.Tasks,"ControllerTasks")&&Object.hasOwn(e.Tasks,"DevicesTasks")&&delete Object.assign(e.Tasks,{ControllerTasks:e.Tasks.DevicesTasks}).DevicesTasks,s(e.RightArgument);!Object.hasOwn(e.Tasks,"ControllerTasks")&&Object.hasOwn(e.Tasks,"DevicesTasks")&&(delete Object.assign(e.Tasks,{ControllerTasks:e.Tasks.DevicesTasks}).DevicesTasks,e.Tasks.ControllerTasks.map((e=>{e.TaskType=Cr.DeviceTask,e.RunParallel=!1})))};return s(e),n._rawRequestData=JSON.parse(JSON.stringify(e)),t?(n.RightArgument=null,n.RightArgumentType=Nr.Null):(n.RightArgumentType=this.MapArgumentType(e.RightArgumentType),n.RightArgument=this.MapRightArgument(e.RightArgument,n.RightArgumentType)),n.LeftArgumentType=this.MapArgumentType(e.LeftArgumentType),n.LeftArgument=this.MapLeftArgument(e.LeftArgument,n.LeftArgumentType),n.Tasks.ControllerTasks=this.MapControllerTasks(e.Tasks.ControllerTasks),void 0===n.DoesHaveTriggers&&(n.DoesHaveTriggers=n.LeftArgumentType==Nr.Null),n}MapRightArgument(e,t){return 0==e.HandledType||(e.LeftArgumentType=this.MapArgumentType(e.LeftArgumentType),e.LeftArgument=this.MapLeftArgument(e.LeftArgument,e.LeftArgumentType),e.Tasks.ControllerTasks=this.MapControllerTasks(e.Tasks.ControllerTasks),Object.hasOwn(e.Tasks,"DevicesTasks")&&delete e.Tasks.DevicesTasks,t===Nr.Condition&&(e.RightArgumentType=this.MapArgumentType(e.RightArgumentType),e.RightArgument=this.MapRightArgument(e.RightArgument,e.RightArgumentType))),e}MapLeftArgument(e,t){let n=new Eo;switch(n.HandledType=e.HandledType,t){case Nr.ArgumentAsAstronomicalClock:n.Argument.ArgumentAsAstronomicalClock={Position:e.Argument};break;case Nr.ArgumentAsAstronomicalClockWithOffset:n.Argument.ArgumentAsAstronomicalClockWithOffset={Offset:e.Argument.Offset,Position:e.Argument.Position};break;case Nr.ArgumentAsBoolean:n.Argument.ArgumentAsBoolean=e.Argument;break;case Nr.ArgumentAsDayOfWeek:n.Argument.ArgumentAsDayOfWeek=e.Argument;break;case Nr.ArgumentAsDaysOfWeek:n.Argument.ArgumentAsDaysOfWeek=e.Argument;break;case Nr.ArgumentAsInt:n.Argument.ArgumentAsInt=e.Argument;break;case Nr.ArgumentAsTimeout:n.Argument.ArgumentAsTimeout=e.Argument;break;case Nr.ArgumentAsTimeSpan:n.Argument.ArgumentAsTimeSpan={days:e.Argument.days,hours:e.Argument.hours,minutes:e.Argument.minutes,seconds:e.Argument.seconds};break;case Nr.ArgumentAsTime:n.Argument.ArgumentAsTime={Hour:e.Argument.Hour,Minute:e.Argument.Minute,Second:e.Argument.Second};break;case Nr.ArgumentAsDeviceState:{const t=new Br;t.Type=this.MapDeviceStateTypeToResponseType(e.Argument.DeviceStateType),t.SetCheckDeviceState(this.CreateDeviceState(e.Argument.CheckedDeviceState,e.Argument.Channel,t.Type)),t.DeviceGuid=e.Argument.DeviceGuid,t.ComparisonMethod=null==e.Argument.ComparisonMethod?Sr.Default:e.Argument.ComparisonMethod,null!=e.Argument.ComparisonParams&&Object.entries(e.Argument.ComparisonParams).forEach((e=>{switch(e[0]){case"DeltaValue":case"StateRepeatCount":t.SetComparisonParam(Ar[e[0]],new Wr(e[1]));break;case"DeltaCalculationTimeRange":case"StateRepeatTimeRange":t.SetComparisonParam(Ar[e[0]],new $r(e[1]))}})),n.Argument.ArgumentAsDeviceState=t;break}case Nr.ArgumentAsConditionInfo:n.Argument.ArgumentAsConditionInfo={DeviceGuid:e.Argument.DeviceGuid}}return n}MapArgumentType(e){return Nr[To[e]]}MapDeviceStateTypeToResponseType(e){switch(e){case Gr.BatteryState:return At.BatteryState;case Gr.BinarySensor:return At.BinarySensorState;case Gr.BlindPosition:return At.BlindPosition;case Gr.Brightness:return At.MeasuredBrightness;case Gr.ButtonState:return At.RemoteButtonState;case Gr.ChannelOnOff:return At.ChannelOnOffState;case Gr.DoorBell:return At.DoorBellState;case Gr.Energy:return At.MeasuredEnergy;case Gr.FloodSensor:return At.FloodSensorState;case Gr.GatePosition:return At.GatePosition;case Gr.LightBrightness:return At.LightBrightness;case Gr.LightColor:return At.LightColor;case Gr.LightTemperature:return At.LightWarmth;case Gr.ReedState:return At.ReedState;case Gr.SmokeSensor:return At.SmokeSensorState;case Gr.Temperature:return At.MeasuredTemperature;case Gr.Humidity:return At.HumiditySensorState;case Gr.BlindsControlButton:return At.BlindRemoteButtonState;case Gr.FacadeControlButton:return At.FacadeRemoteButtonState;case Gr.Movement:return At.MovementSensorState;case Gr.AirPressure:return At.PressureSensorState;case Gr.WindSpeed:return At.WindSpeedState;case Gr.WindThreshold:return At.CurrentWindThreshold;default:return At.Unknown}}CreateDeviceState(e,t,n){switch(n){case At.BatteryState:return{Channel:t,StateReliability:Ft.Unconfident,Percentage:e.Percentage,State:e.State,Time:""};case At.BinarySensorState:return{Channel:t,StateReliability:Ft.Unconfident,State:e.State,Time:""};case At.BlindPosition:return{Channel:t,StateReliability:Ft.Unconfident,Position:e.Position,RawPosition:e.RawPosition,Time:""};case At.LightBrightness:case At.MeasuredBrightness:return{Channel:t,StateReliability:Ft.Unconfident,Brightness:e.Brightness,Time:""};case At.RemoteButtonState:case At.ChannelOnOffState:case At.DoorBellState:return{Channel:t,StateReliability:Ft.Unconfident,State:e.State,Time:""};case At.MeasuredEnergy:{const n=new Map;for(let[t,s]of Object.entries(e.MeasurementParameters))n.set(jt[t],s);return{Channel:t,StateReliability:Ft.Unconfident,MeasurementParameters:n,Time:""}}case At.FloodSensorState:return{Channel:t,StateReliability:Ft.Unconfident,State:e.State,Time:""};case At.GatePosition:return{Channel:t,StateReliability:Ft.Unconfident,Position:e.Position,PositionType:e.PositionType,Time:""};case At.LightColor:return{Channel:t,StateReliability:Ft.Unconfident,R:e.R,G:e.G,B:e.B,Time:""};case At.LightWarmth:return{Channel:t,StateReliability:Ft.Unconfident,Temperature:e.Temperature,Time:""};case At.ReedState:return{Channel:t,StateReliability:Ft.Unconfident,State:e.State,Time:""};case At.SmokeSensorState:throw new Vr("Unsupported device state!");case At.MeasuredTemperature:return{Channel:t,StateReliability:Ft.Unconfident,Temperature:e.Temperature,Time:"",Type:e.Type};case At.HumiditySensorState:return{Channel:t,StateReliability:Ft.Unconfident,Humidity:e.Humidity,Time:"",Type:e.Type};case At.BlindRemoteButtonState:return{Channel:t,StateReliability:Ft.Unconfident,State:e.State,Time:""};case At.LightRGBWState:return{StateReliability:Ft.Unconfident,Channel:t,Time:"",Brightness:100,R:e.R,G:e.G,B:e.B,W:e.W};case At.FacadeRemoteButtonState:return{Channel:t,Time:"",StateReliability:Ft.Unconfident,State:e.State};case At.MovementSensorState:return{Channel:t,Time:"",StateReliability:Ft.Unconfident,Movement:e.Movement,Intensity:e.Intensity};case At.PressureSensorState:return{Channel:t,Time:"",StateReliability:Ft.Unconfident,Pressure:e.Pressure,PressureType:e.PressureType};case At.WindSpeedState:return{Channel:t,Time:"",StateReliability:Ft.Unconfident,Value:e.Value};case At.CurrentWindThreshold:return{Channel:t,Time:"",StateReliability:Ft.Unconfident,WindThreshold:e.WindThreshold};case At.Unknown:return new vn;default:throw new Vr("Unsupported device state!")}}MapDeviceTask(e){let t=new Fs,n=e;switch(Fv.Get(s.ServiceName).Debug(`[TASK] object: ${JSON.stringify(n)}`),n.ControlFeature){case Gs.TurnOn:t=new Ws,t.TaskType=St.TurnOn;break;case Gs.TurnOff:t=new Bs,t.TaskType=St.TurnOff;break;case Gs.ToggleState:t=new Vs,t.TaskType=St.TogleState;break;case Gs.SetBlindPosition:{const e=Fv.Get(Fo.ServiceName).GetDevice(n.DeviceGuid);(null==e?void 0:e.AvailableTaskTypes.any((e=>"IBlindPositionSimple"==e.InterfaceType)))?(t=new zs,t.TaskType=St.SetBlindPositionSimple,t.Action=n.Data.Action):(t=new Ks,t.TaskType=St.SetBlindPosition,t.Action=n.Data.Action,t.Position=n.Data.Position);break}case Gs.SetLightColor:t=new Hs,t.TaskType=St.SetLightColor,t.R=n.Data.R,t.G=n.Data.G,t.B=n.Data.B;break;case Gs.SetLightTemperature:t=new js,t.TaskType=St.SetLightTemperature,t.Temperature=n.Data.Temperature;break;case Gs.SetLightBrightness:t=new qs,t.TaskType=St.SetLightBrightness,t.Brightness=n.Data.Brightness;break;case Gs.SetTemperature:t=new Ls,t.TaskType=St.SetTemperature,t.Temperature=n.Data.Temperature;break;case Gs.GetState:t=new Zs,t.TaskType=St.GetChannelsState;break;case Gs.TurnOnWithTimeout:t=new $s,t.TaskType=St.TurnOnWithTime,t.SwitchOffDelaySeconds=n.Data.SwitchOffDelaySeconds;break;case Gs.SetLightBrightnessDynamicly:t=new Js,t.TaskType=St.SetLightBrightnessDynamicly,t.Brightness=n.Data.Brightness;break;case Gs.IdentifyDevice:t=new Ys,t.TaskType=St.IdentifyDevice;break;case Gs.SetBlindOpenCloseTime:t=new Xs,t.TaskType=St.SetBlindOpenCloseTime,t.Data.CloseTime=n.Data;break;case Gs.SetBlindMicroventilation:t=new er,t.TaskType=St.SetBlindMicroventilation,t.Position=n.Data.Position;break;case Gs.GatewayPulse:t=new nr,t.TaskType=St.ChangeGatewayPositionPulse;break;case Gs.GatePulse:t=new tr,t.TaskType=St.ChangeGatePositionPulse;break;case Gs.SetFacadePositionAndTilt:t=new sr,t.TaskType=St.SetFacadePosition,t.Position=n.Data.Position,t.Tilt=n.Data.Tilt,t.FacadeAction=Is.TiltAndPercentage;break;case Gs.GetFacadeType:t=new rr,t.TaskType=St.GetFacadeType;break;case Gs.LightRGBW:t=new ir,t.TaskType=St.LightRGBW,t.Data=n.Data}return t.Channel=n.Channel,t.DeviceGuid=n.DeviceGuid,t.FeatureType=n.ControlFeature,t.Guid=xs.NewGuid(),t}MapControllerTasks(e){const t=[];Fv.Get(s.ServiceName).Debug(`[TASKS] received tasks object: ${JSON.stringify(e)}`);for(let n of e){const e=new Io;switch(e.TaskId=re.GenerateMd5(JSON.stringify(n)),n.TaskType){case Cr.DeviceTask:e.TaskType=Tr.DeviceTask,e.Task.DeviceTask=this.MapDeviceTask(n);break;case Cr.DelayTask:e.TaskType=Tr.DelayTask,e.Task.DelayTask={Delay:new $r(n.Delay)};break;case Cr.NotifyTask:e.TaskType=Tr.NotifyTask,e.Task.NotifyTask={Message:n.Message,NotifyType:n.NotifyType};break;case Cr.LockExecution:case Cr.LockExecution:e.TaskType=Tr.LockExecution,Fv.Get(s.ServiceName).Debug(`[TASKS] received task LockExecution object: ${JSON.stringify(n)}`),e.Task.LockExecution={LockStartHour:new $r(n.LockStartHour),LockEndHour:new $r(n.LockEndHour),LockType:n.LockType,ResetLockScenesGuids:n.ResetLockScenesGuids};case Cr.Unknown:}t.push(e)}return t}}ko.ServiceName="ScenesService";class Go extends ae{constructor(){super(),this.Resource="/logic/sequences/list",this.Method=ue.Get}}class bo extends ae{constructor(e){super(),this.Resource="/logic/sequence",this.Method=ue.Get,this.Data=e}}class No extends ae{constructor(e){super(),this.Resource="/logic/sequences/used",this.Method=ue.Get,this.Data=e}}class Eo{constructor(){this.HandledType=To.Null,this.Argument={}}}!function(e){e[e.Null=0]="Null",e[e.Condition=1]="Condition",e[e.ConditionGroup=2]="ConditionGroup",e[e.ArgumentAsInt=3]="ArgumentAsInt",e[e.ArgumentAsTimeSpan=4]="ArgumentAsTimeSpan",e[e.ArgumentAsBoolean=5]="ArgumentAsBoolean",e[e.ArgumentAsTimeout=6]="ArgumentAsTimeout",e[e.ArgumentAsDayOfWeek=7]="ArgumentAsDayOfWeek",e[e.ArgumentAsDaysOfWeek=8]="ArgumentAsDaysOfWeek",e[e.ArgumentAsAstronomicalClock=9]="ArgumentAsAstronomicalClock",e[e.ArgumentAsTime=10]="ArgumentAsTime",e[e.ArgumentAsDeviceState=11]="ArgumentAsDeviceState",e[e.ArgumentAsNumber=12]="ArgumentAsNumber",e[e.ArgumentAsAstronomicalClockWithOffset=13]="ArgumentAsAstronomicalClockWithOffset",e[e.ArgumentAsConditionInfo=14]="ArgumentAsConditionInfo"}(To||(To={}));class Io{constructor(){this.TaskId="",this.TaskType=Tr.Unknown,this.Task={}}}class Ro extends ae{constructor(e){super(),this.Resource="/logic/sequence",this.Method=ue.Put,this.Data=e}}class Po extends ae{constructor(e){super(),this.Resource="/logic/sequence/edit",this.Method=ue.Put,this.Data=e}}class Oo extends ae{constructor(e){super(),this.Resource="/logic/sequence",this.Method=ue.Delete,this.Data=e}}class Uo extends ae{constructor(e){super(),this.Resource="/logic/sequence/enable",this.Method=ue.Post,this.Data=e}}class Mo extends ae{constructor(e){super(),this.Resource="/logic/sequence/disable",this.Method=ue.Post,this.Data=e}}var xo=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class Fo{constructor(){this._devices=[],this._onDevicesTasksChangedEvent=new n,this._onDeviceFoundEvent=new n,this._onDeviceRegisteredEvent=new n,this._onDeviceRemovedEvent=new n,this._onDeviceFirmwareVersionChangedEvent=new n,this._onDeviceStateChangedEvent=new n,this._onDeviceStateRefreshedOrChangedEvent=new n,this._connection=null,this._session=null,this._controllerConfiguration=null,this._synchronized=!1,this._synchronizedDevicesStates=!1,this._devicesChannelsStates=[],this._synchronizationTaskCompletionSource=null,this._deviceStatesSynchronizationTaskCompletionSource=null,this._connection=Fv.Get(Pt.ServiceName),this._session=Fv.Get(Ke.ServiceName),this._controllerConfiguration=Fv.Get(rt.ServiceName),this._onDeviceStateChangedEvent.Subscribe((e=>xo(this,void 0,void 0,(function*(){return this.PutDeviceStateOnList(e.Device,e.State)})))),this._synchronizationTaskCompletionSource=new Promise((e=>{var t;null===(t=this._session)||void 0===t||t.OnUserLoggedInEvent().Subscribe((t=>xo(this,void 0,void 0,(function*(){var t;try{this._devices=yield this.GetPairedDevicesAsync()}catch(e){null===(t=r.Log)||void 0===t||t.Error(Fo.ServiceName,`Failed to get paired devices: ${e}`)}this._synchronized=!0,e()}))))})),this._deviceStatesSynchronizationTaskCompletionSource=new Promise((e=>{var t;null===(t=this._session)||void 0===t||t.OnUserLoggedInEvent().Subscribe((t=>xo(this,void 0,void 0,(function*(){var t;try{yield this.WaitForSynchronizationAsync(),yield this.SyncDevicesStatesAsync()}catch(e){null===(t=r.Log)||void 0===t||t.Error(Fo.ServiceName,`Failed to sync devices states: ${e}`)}this._synchronizedDevicesStates=!0,e()}))))})),this._connection.SubscribeTo("/info/devices/tasks",(e=>{this.ParseDeviceTaskInfo(e.Data)})),this._connection.SubscribeTo("/info/devices/device/found",(e=>{this.MapApiDevices(e.Data).forEach((e=>{var t;e.DeviceType!=Tt.Scene&&(null===(t=r.Log)||void 0===t||t.Debug(Fo.ServiceName,`Found device: ${e.Name} guid: ${e.Guid}`),this._onDeviceFoundEvent.Invoke(e))}))})),this._connection.SubscribeTo("/info/devices/device/firmware/updated",(e=>{const t=e.Data.DeviceGuid,n=e.Data.Version,s=this._devices.find((e=>e.Guid==t));void 0!==s&&(this._onDeviceFirmwareVersionChangedEvent.Invoke({Device:s,FirmwareVersion:n}),s.SoftwareVersion=n,s.OnDeviceFirmwareVersionChangedEvent().Invoke({FirmwareVersion:n}))})),this._connection.SubscribeTo("/devices/blinds/times",(e=>{})),this._connection.SubscribeTo("/info/devices/device/state/changed",(e=>{var t;const n=e.Data,s=this._devices.filter((e=>e.Guid==n.DeviceGuid));if(s.length>0){const e=s[0],r=this.MapApiDeviceStateToDeviceState(e,n);if(null!=r){this._onDeviceStateRefreshedOrChangedEvent.Invoke({Device:e,State:r}),r.TypeAsEnum==At.SignalStrength?e.Channels.forEach((t=>{let s=new Jn(Object.assign({},n));s.Data.Channel=t.Number,this._onDeviceStateRefreshedOrChangedEvent.Invoke({Device:e,State:s})})):r.TypeAsEnum==At.BatteryState&&e.Channels.forEach((t=>{let s=new Mn(Object.assign({},n));s.Data.Channel=t.Number,this._onDeviceStateRefreshedOrChangedEvent.Invoke({Device:e,State:s})}));let s=e.States.find((e=>e.TypeAsEnum===r.TypeAsEnum&&e.Data.Channel===r.Data.Channel));if(s){let o=s.StatesComparisonData;if(r.TypeAsEnum==At.BlindErrorState&&(null===(t=r.Data)||void 0===t?void 0:t.ErrorCode)!=s.Data.ErrorCode)return void this._onDeviceStateChangedEvent.Invoke({Device:e,State:r});s.Data=r.Data,o!==r.StatesComparisonData&&(this._onDeviceStateChangedEvent.Invoke({Device:e,State:r}),r.TypeAsEnum==At.SignalStrength?e.Channels.forEach((t=>{let s=new Jn(Object.assign({},n));s.Data.Channel=t.Number,this._onDeviceStateChangedEvent.Invoke({Device:e,State:s})})):r.TypeAsEnum==At.BatteryState&&e.Channels.forEach((t=>{let s=new Mn(Object.assign({},n));s.Data.Channel=t.Number,this._onDeviceStateChangedEvent.Invoke({Device:e,State:s})})))}else e.States.push(r),this._onDeviceStateChangedEvent.Invoke({Device:e,State:r}),r.TypeAsEnum==At.SignalStrength?e.Channels.forEach((t=>{let s=new Jn(Object.assign({},n));s.Data.Channel=t.Number,this._onDeviceStateChangedEvent.Invoke({Device:e,State:s})})):r.TypeAsEnum==At.BatteryState&&e.Channels.forEach((t=>{let s=new Mn(Object.assign({},n));s.Data.Channel=t.Number,this._onDeviceStateChangedEvent.Invoke({Device:e,State:s})}))}}})),this._connection.SubscribeTo("/info/devices/devices/registered",(e=>{Fv.Get(Ge.ServiceName).ClearCache(),this.MapApiDevices(e.Data).forEach((e=>{var t;null===(t=r.Log)||void 0===t||t.Debug(Fo.ServiceName,`Registered device: ${e.Name} guid: ${e.Guid}`),this._devices.push(e),this._onDeviceRegisteredEvent.Invoke(e)}))})),this._connection.SubscribeTo("/info/devices/devices/removed",(e=>{Fv.Get(Ge.ServiceName).ClearCache(),this.MapApiDevices(e.Data).forEach((e=>{var t;null===(t=r.Log)||void 0===t||t.Debug(Fo.ServiceName,`Removed device: ${e.Name} guid: ${e.Guid}`),this._devices=this._devices.filter((t=>t.Guid!=e.Guid)),this._onDeviceRemovedEvent.Invoke(e)}))}))}ProtocolGuidToProtocolName(e){switch(e){case"1fca7e8a-a2dc-4883-bd94-4e9b2012f685":return"ExtaLife";case"cd25bdff-628c-4dbc-a16a-648c96a819d4":return"Portos 433MHz";case"634c2bb2-1a4f-4db6-8dd4-d5fbaf92678e":return"Supla";case"194aeb81-990c-4a02-9236-59e902958fda":return"RTSP";case"b3e4644e-ab5b-494e-b3c5-66fabe7fff64":return"Wekta";case"247198e1-e360-4355-9886-232ac1456eea":return"Lavva Wi-Fi";default:return null}}CheckIfDeviceUsedInScenesAsync(e){return xo(this,void 0,void 0,(function*(){var t,n,s,o,i,a;try{let a;if("string"==typeof e){const n=this.GetDevice(e);if(null==n)return null===(t=r.Log)||void 0===t||t.Error("Cannot check if device is used in scenes! Device with given guid not exists"),ce.ResourceDoesNotExists;a=n}else a=e;const u=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new Qo(a.Guid),2e4,!1);if(null==u||null==u.Status)return null===(s=r.Log)||void 0===s||s.Error("Cannot check if device is used in scenes! Response or status is null!"),ce.FatalError;if(u.Status!=ce.OK)return u.Status;if(null==u.Data)return null===(o=r.Log)||void 0===o||o.Error("Cannot check if device is used in scenes! No data!"),ce.FatalError;var c=yield Fv.Get(ko.ServiceName).GetSequencesListAsync();if(c instanceof De)return null===(i=r.Log)||void 0===i||i.Error(`Cannot check if device is used in scenes! Cannot get sequence list, ScenesServiceErrorCode: ${c.Type}`),ce.Error;const l=new ni;return l.DeviceGuid=a.Guid,u.Data.ConditionsAsCondition.forEach((e=>{const t=c.find((t=>t.Guid==e));t&&l.ConditionsAsCondition.push(t)})),u.Data.ConditionsAsTask.forEach((e=>{const t=c.find((t=>t.Guid==e));t&&l.ConditionsAsCondition.push(t)})),l}catch(e){return null===(a=r.Log)||void 0===a||a.Error(`Cannot check if device is used in scenes! ${e}`),ce.FatalError}}))}CanEditDevicesInfo(){var e,t;return null!==this._session&&void 0!==this._session&&null!==this._session.User&&void 0!==this._session.User&&(null===(t=null===(e=this._session)||void 0===e?void 0:e.User)||void 0===t?void 0:t.AccessLevel)>=pe.Admin}CanAddAndRemoveAndConfigureDevices(){var e,t;return null!==this._session&&void 0!==this._session&&null!==this._session.User&&void 0!==this._session.User&&(null===(t=null===(e=this._session)||void 0===e?void 0:e.User)||void 0===t?void 0:t.AccessLevel)>=pe.Installator}GetDeviceChannelByChannelId(e){return this._devices.firstOrDefault((t=>t.Channels.any((t=>t.ChannelId==e)))).Channels.firstOrDefault((t=>t.ChannelId==e))}EnableFastStatesSyncAsync(){return xo(this,void 0,void 0,(function*(){const e=Fv.Get(hr.ServiceName).SaveAsync("FastDevicesSync",!1,!0);return yield Fv.Get(rt.ServiceName).ExitConfigurationModeAsync(),e}))}DisableFastStatesSyncAsync(){return xo(this,void 0,void 0,(function*(){const e=Fv.Get(hr.ServiceName).SaveAsync("FastDevicesSync",!1,!1);return yield Fv.Get(rt.ServiceName).ExitConfigurationModeAsync(),e}))}IsFastStatesSyncEnabledAsync(){return xo(this,void 0,void 0,(function*(){const e=yield Fv.Get(hr.ServiceName).ReadAsync("FastDevicesSync",!1,!1);return e instanceof ur?e.Data:e!=ce.ResourceDoesNotExists&&e}))}GetDevicesForManualPairingAsync(e){return xo(this,void 0,void 0,(function*(){let t=Fv.Get(cr.ServiceName);const n=new RegExp("^[{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]?$");return Array.isArray(e)||n.test(e)?yield t.GetDevicesForManualPairingAsync(e):yield t.GetDevicesForManualPairingAsync()}))}AddManuallyPairedDevice(e){return xo(this,void 0,void 0,(function*(){var t=yield Fv.Get(cr.ServiceName).AddManuallyPairedDeviceAsync(e);return yield Fv.Get(rt.ServiceName).ExitConfigurationModeAsync(),t}))}GetDeviceChannelStates(e,t){var n,s;return null!==(s=null===(n=this._devicesChannelsStates.firstOrDefault((t=>t.DeviceGuid==e.Guid)))||void 0===n?void 0:n.ChannelsStates.filter((e=>e.Channel==t)))&&void 0!==s?s:[]}GetDeviceStates(e){var t,n;return null!==(n=null===(t=this._devicesChannelsStates.firstOrDefault((t=>t.DeviceGuid==e.Guid)))||void 0===t?void 0:t.ChannelsStates)&&void 0!==n?n:[]}PutDeviceStateOnList(e,t){let n=this._devicesChannelsStates.firstOrDefault((t=>t.DeviceGuid==e.Guid));if(null==n){let s=new Lo;s.Channel=t.Data.Channel,s.States=[t],n={DeviceGuid:e.Guid,ChannelsStates:[s]},this._devicesChannelsStates.push(n)}else{let e=n.ChannelsStates.firstOrDefault((e=>e.Channel==t.Data.Channel));if(null==e)e=new Lo,e.Channel=t.Data.Channel,e.States=[t],n.ChannelsStates.push(e);else{let n=e.States.firstOrDefault((e=>e.TypeAsEnum==t.TypeAsEnum));null!=n&&(n.TypeAsEnum==At.BlindErrorState?e.States=e.States.where((e=>e.Data.ErrorCode!=t.Data.ErrorCode)).toArray():e.States=e.States.where((e=>e.TypeAsEnum!=t.TypeAsEnum)).toArray()),e.States.push(t)}}}WaitForSynchronizationAsync(){return this._synchronizationTaskCompletionSource}WaitForDevicesStatesSynchronizationAsync(){return this._deviceStatesSynchronizationTaskCompletionSource}GetCurrentlyRunningTaksAsync(){return xo(this,void 0,void 0,(function*(){var e;const t=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new jo,15e3,!1);(null==t?void 0:t.Status)==ce.OK&&null!=t.Data&&this.ParseDeviceTaskInfo(t.Data)}))}ParseDeviceTaskInfo(e){const t=[];e.forEach((e=>{var n;const s=e.split(";"),o=new Mt;o.DeviceGuid=s[0],o.Channel=Number(s[1]),o.Status=vt.ExecutingTasks,t.push(o),null===(n=r.Log)||void 0===n||n.Debug(Fo.ServiceName,`Device ${o.DeviceGuid} has task on channel ${o.Channel}`)})),this._onDevicesTasksChangedEvent.Invoke(t)}MapApiDeviceStateToDeviceState(e,t){var n;switch(t.state,t.DataType){case"ChannelOnOff":return new mn(t);case"DoorBell":return new Sn(t);case"ReedPosition":return new _n(t);case"BlindPosition":return new Tn(t);case"ButtonState":return new kn(t);case"LightColor":return new bn(t);case"LightTemperature":return new En(t);case"LightBrightness":return new Rn(t);case"TemperatureSensor":case"TemperatureState":case"MeasuredTemperature":return new On(t);case"BatteryState":return new Mn(t);case"MeasuredBrightness":case"DeviceBrightnessState":return new Fn(t);case"EnergyMeasuredPower":case"EnergyMeasuredCurrent":case"EnergyMeasuredVoltage":break;case"IEnergy":case"Energy":return new Bn(t);case"DistanceSensor":return new $n(t);case"MovementSensor":return new qn(t);case"BlindsControlButton":return new Hn(t);case"FacadeControlButton":return new Kn(t);case"SignalStrength":return new Jn(t);case"GatePosition":return new Yn(t);case"GatewayPosition":return new Qn(t);case"GateControllerHealth":return new Zn(t);case"IBlindCalibrationStatus":case"BlindCalibration":return new es(t);case"HumiditySensor":case"HumidityState":return new ts(t);case"VibrationSensor":return new ss(t);case"DigitalInputSensor":return new rs(t);case"ConfigurationState":return new is(t);case"BlindOpenCloseTime":case"IBlindOpenCloseTime":return new as(t);case"IOvercurrentProtection":case"OvercurrentProtection":return new cs(t);case"IOvercurrentProtectionThreshold":case"OvercurrentProtectionThreshold":return new us(t);case"FacadePosition":case"FacadeState":return new ls(t);case"FacadeTypeState":return new ds(t);case"CurrentWindThreshold":return new hs(t);case"CurrentLightThreshold":return new gs(t);case"WindSpeed":return new fs(t);case"FloodSensor":return new ms(t);case"PressureState":return new ws(t);case"ITamperProtection":case"TamperProtection":return new As(t);case"ILightRGBW":case"LightRGBW":return new _s(t);case"OnlineCamera":case"IOnlineCamera":return new wn(t);case"BlindError":case"IBlindError":return t.state.ErrorData=ie(t.state.ErrorData),new Cs(t);default:null===(n=r.Log)||void 0===n||n.Debug(Fo.ServiceName,`Not supported device state ${t.DataType}`)}return null}GetServiceName(){return Fo.ServiceName}SyncDevicesStatesAsync(){return xo(this,arguments,void 0,(function*(e=!1){var t,n,s;const r=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Wo,15e3,!1);if(yield this.IsFastStatesSyncEnabledAsync()){if(e){let e=new $o;e.Data=!0;const t=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(e,35e3,!1);return(null==t?void 0:t.Status)==ce.OK}return(null==r?void 0:r.Status)==ce.OK}{let e=new $o;e.Data=!0;const t=yield null===(s=this._connection)||void 0===s?void 0:s.SendAndWaitForResponseAsync(e,35e3,!1);return(null==t?void 0:t.Status)==ce.OK}}))}OnDevicesTasksExecutionChangeEvent(){return this._onDevicesTasksChangedEvent}OnDeviceStateChangedEvent(){return this._onDeviceStateChangedEvent}OnDeviceStateRefreshedOrChangedEvent(){return this._onDeviceStateRefreshedOrChangedEvent}OnDeviceRegisteredEvent(){return this._onDeviceRegisteredEvent}OnDeviceRemovedEvent(){return this._onDeviceRemovedEvent}OnDeviceFoundEvent(){return this._onDeviceFoundEvent}MapApiDevices(e){const t=[];return null==e?[]:(e.forEach((e=>{var n,s,o,i,a=new Ts;a.Guid=e.Guid,a.Name=e.DeviceName,a.ChannelsAmount=e.ChannelsNumber,a.DeviceType=e.DeviceType,a.CommunicationWay=e.CommunicationWay,a.DeviceState=e.DeviceState,a.IsEnabled=e.IsEnabled,a.IsVirtual=e.IsVirtual,a.SerialNumber=e.DeviceSerialNumber,a.ManufacturerGuid=e.ManufacturerGuid,a.ModelGuid=e.DeviceModelGuid,a.Model=e.DeviceModel,a.Name=e.DeviceName,a.ProtocolGuid=e.ProtocolGuid,void 0!==e.IconType&&null!==e.IconType?a.IconType=e.IconType:a.IconType=wt.Unknown;try{null===(n=e.AvailableTasks)||void 0===n||n.forEach((e=>{var t=new Ot;if(a.CommunicationWay==Ct.OneWay)"IBlindPosition"===e&&(t.InterfaceType="IBlindPositionSimple");else switch(e){case"IGatePosition":t.InterfaceType="IGatePulse";break;case"IGatewayPosition":t.InterfaceType="IGatewayPulse";break;default:t.InterfaceType=e}a.AvailableTaskTypes.push(t)})),null===(s=e.AvailableResponses)||void 0===s||s.forEach((e=>{var t=new Ut;t.InterfaceType=e,a.AvailableResponseTypes.push(t)})),null===(o=e.ChannelsConfiguration)||void 0===o||o.forEach((e=>{var t,n,s;try{var o=new Ps;o.Number=e.Channel,a.Channels.push(o),o.SetDevice(a),o.Name=e.ChannelName,o.ChannelGroups=e.GroupsGuids,o.IconName=e.IconName,o.IsHidden=e.Hidden,o.Configurations=e.Configurations,o.CustomDataAndRolesSupported=void 0!==e.CustomData&&null!==e.CustomData,void 0!==e.CustomData&&null!==e.CustomData&&(o.CustomData=e.CustomData),void 0!==e.Roles&&null!==e.Roles&&(o.Roles=e.Roles),null===(t=e.AvailableResponses)||void 0===t||t.forEach((e=>{var t=new Ut;t.InterfaceType=e,o.AvailableResponseTypes.push(t)})),null===(n=e.AvailableTasks)||void 0===n||n.forEach((e=>{var t=new Ot;a.AvailableTaskTypes.any((e=>"IBlindPositionSimple"==e.InterfaceType))?"IBlindPosition"==e&&(t.InterfaceType="IBlindPositionSimple"):t.InterfaceType=e,o.AvailableTaskTypes.push(t)}))}catch(e){null===(s=r.Log)||void 0===s||s.Error(e)}}))}catch(e){null===(i=r.Log)||void 0===i||i.Error(e)}t.push(a)})),t)}GetPairedDevicesAsync(){return xo(this,arguments,void 0,(function*(e=!1){var t,n,s;if(this._synchronized&&!(yield null===(t=this._controllerConfiguration)||void 0===t?void 0:t.DidCofigurationChangeAsync()))return Promise.resolve(this._devices);const o=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new Bo,15e3,!0);return null==o||void 0===o?[]:o.Status==ce.OK&&null!=o.Data?e?this.MapApiDevices(o.Data):this.MapApiDevices(o.Data.filter((e=>e.DeviceType!=Tt.Scene))):(null===(s=r.Log)||void 0===s||s.Error(Fo.ServiceName,`Failed to get devices. ${o.Status} ${o.Data}`),[])}))}GetDevicesAsync(){return xo(this,arguments,void 0,(function*(e=!1){return yield this.WaitForSynchronizationAsync(),this.GetPairedDevicesAsync(e)}))}GetFoundDevicesAsync(){return xo(this,void 0,void 0,(function*(){var e,t;const n=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new Ho,15e3,!1);return null==n?[]:n.Status==ce.OK&&null!=n.Data?this.MapApiDevices(n.Data).where((e=>e.DeviceType!==Tt.Scene)).toArray():(null===(t=r.Log)||void 0===t||t.Error(Fo.ServiceName,`Failed to get found devices. ${n.Status} ${n.Data}`),[])}))}GetDevice(e){return this._devices.find((t=>t.Guid===e))}FindDevicesAsync(){return xo(this,void 0,void 0,(function*(){var e;Fv.Get(Ge.ServiceName).ClearCache(),yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new qo,35e3,!1)}))}StopSearchingForDevices(){return xo(this,void 0,void 0,(function*(){var e;yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new Vo,2e4,!1)}))}RegisterDeviceAsync(e){return xo(this,void 0,void 0,(function*(){var t,n;try{const n=new Ko;n.Data=e.Guid;const s=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(n,2e4,!1);return Fv.Get(Ge.ServiceName).ClearCache(),Fv.Get(rt.ServiceName).ExitConfigurationModeAsync(),(null==s?void 0:s.Status)==ce.OK?(this._devices.any((t=>t.Guid==e.Guid))||this._devices.push(e),this._onDeviceRegisteredEvent.Invoke(e),kt.Executed):kt.Failed}catch(e){return null===(n=r.Log)||void 0===n||n.Error(Fo.ServiceName,`Failed to paired devices: ${e}`),kt.ControllerResponseTimeout}}))}RemoveDeviceAsync(e){return xo(this,arguments,void 0,(function*(e,t=!1){var n,s=new zo;t&&(s=new Jo),s.Data=e.Guid;const r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(s,35e3,!1);return Fv.Get(Ge.ServiceName).ClearCache(),Fv.Get(rt.ServiceName).ExitConfigurationModeAsync(),(null==r?void 0:r.Status)==ce.OK?(this._devices=this._devices.where((t=>t.Guid!=e.Guid)).toArray(),this._onDeviceRemovedEvent.Invoke(e),kt.Executed):kt.Failed}))}MapDeviceTaskToDeviceTaskInfo(e,t){let n=new Zo;const s=t;switch(s.FeatureType){case Gs.SetTemperature:n.Data=s.Temperature;break;case Gs.SetLightBrightness:n.Data=s.Brightness;break;case Gs.SetLightColor:n=new ei;const e=s;n.R=e.R,n.G=e.G,n.B=e.B;break;case Gs.SetLightTemperature:n.Data=s.Temperature;break;case Gs.SetGatePositionPrecise:switch(s.GateControlAction){case Ns.Open:n.Data=101;break;case Ns.Close:n.Data=102;break;case Ns.Stop:n.Data=103;break;case Ns.Percentage:n.Data=s.Position}break;case Gs.SetBlindPosition:switch(s.Action){case bs.Open:n.Data=101;break;case bs.Close:n.Data=102;break;case bs.Stop:n.Data=103;break;case bs.Percentage:n.Data=s.Position}break;case Gs.SetLightBrightnessDynamicly:n.Data=s.Brightness;break;case Gs.SetBlindOpenCloseTime:n.Data=s.Data;break;case Gs.SetBlindMicroventilation:n.Data=s.Position;break;case Gs.SetFacadePositionAndTilt:n=new ti;const t=s;n.FacadeAction=t.FacadeAction,n.Tilt=t.Tilt,n.Position=t.Position;break;case Gs.LightRGBW:n.Data=s.Data;break;case Gs.GatePulse:case Gs.GatewayPulse:n.Data=0;break;case Gs.TurnOnWithTimeout:n.Data=s.SwitchOffDelaySeconds}return n.Channel=s.Channel,n.DeviceGuid=e.Guid,n.ControlFeature=s.FeatureType,n}ExecuteDeviceTaskAsync(e,t){return xo(this,void 0,void 0,(function*(){var n,s,o,i,a,c,u,l;try{null===(n=r.Log)||void 0===n||n.Debug(Fo.ServiceName,`Preparing device task execution, device: ${e.Guid} task: ${t.TaskType} channel: ${t.Channel}`);let l=this.MapDeviceTaskToDeviceTaskInfo(e,t);try{const e=new Yo(l);null===(s=r.Log)||void 0===s||s.Debug(Fo.ServiceName,`Sending device task for execution, device: ${l.DeviceGuid} task: ${l.ControlFeature} channel: ${l.Channel} request: ${JSON.stringify(e)}`);const t=yield null===(o=this._connection)||void 0===o?void 0:o.SendAndWaitForResponseAsync(e,15e3,!1);switch(null==t?void 0:t.Status){case ce.OK:return kt.Executed;case ce.FatalError:return null===(i=r.Log)||void 0===i||i.Error(Fo.ServiceName,`Fatal error occured when tried to execute task on device. Error code: ${t.Data}`),kt.Failed;case ce.WrongData:if("DeviceNotFound"===t.Data)return kt.DeviceNotFound;break;case ce.Error:return"DeviceResponseTimeout"===t.Data?kt.DeviceResponseTimeout:(null===(a=r.Log)||void 0===a||a.Error(Fo.ServiceName,`Unknown error occured when trying to execute task on device. Error code: ${t.Data}`),kt.Failed)}}catch(e){return e.message.includes("timeout")?(null===(c=r.Log)||void 0===c||c.Error(Fo.ServiceName,`Failed to get controller response in time.\n${e}`),kt.ControllerResponseTimeout):(null===(u=r.Log)||void 0===u||u.Error(Fo.ServiceName,`Unknown error occured when tried to execute task on device.\n${e}`),kt.Failed)}return kt.Unknown}catch(e){return null===(l=r.Log)||void 0===l||l.Error(Fo.ServiceName,`Unknown error occured when tried to execute task on device.\n${e}`),kt.Failed}}))}ExecuteDevicesTasksAsync(e){return xo(this,void 0,void 0,(function*(){var t,n,s,o;let i=[],a=[],c=0;for(const[t,n]of e){const e=this.MapDeviceTaskToDeviceTaskInfo(t,n);e.SequnceExecutionOrder=c,c++,a.push(e)}const u=new Xo(a);try{const s=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(u,12e4,!1);let o=-1;null===(n=null==s?void 0:s.Data)||void 0===n||n.forEach((t=>{var n,a;o++;let c=kt.Unknown;switch(t.Status){case ce.OK:return kt.Executed;case ce.FatalError:null===(n=r.Log)||void 0===n||n.Error(Fo.ServiceName,`Fatal error occured when tried to execute task on device. Error code: ${t.Data}`),c=kt.Failed;break;case ce.WrongData:"DeviceNotFound"===t.Data&&(c=kt.DeviceNotFound);break;case ce.Error:"DeviceResponseTimeout"===t.Data?c=kt.DeviceResponseTimeout:(null===(a=r.Log)||void 0===a||a.Error(Fo.ServiceName,`Unknown error occured when trying to execute task on device. Error code: ${s.Data}`),c=kt.Failed)}let u=0,l=new xt;for(const[t,n]of e){if(u==o){l.Device=t,l.Task=n,l.Channel=n.Channel,i.push(l);break}u++}}))}catch(t){if(t.message.includes("timeout")){null===(s=r.Log)||void 0===s||s.Error(Fo.ServiceName,`Failed to get controller response in time.\n${t}`);for(const[t,n]of e){let e=new xt;i.push(e),e.Device=t,e.Task=n,e.Channel=n.Channel,e.Result=kt.ControllerResponseTimeout}}else{null===(o=r.Log)||void 0===o||o.Error(Fo.ServiceName,`Unknown error occured when tried to execute task on device.\n${t}`);for(const[t,n]of e){let e=new xt;i.push(e),e.Device=t,e.Task=n,e.Channel=n.Channel,e.Result=kt.Failed}}}return i}))}}Fo.ServiceName="DevicesService";class Lo{constructor(){this.Channel=0,this.States=[]}}class Bo extends ae{constructor(){super(),this.Resource="/devices/list",this.Method=ue.Get}}class Wo extends ae{constructor(){super(),this.Data=!1,this.Resource="/devices/channels/states",this.Method=ue.Get}}class $o extends ae{constructor(){super(),this.Data=!1,this.Resource="/devices/channels/states/sync",this.Method=ue.Get}}class qo extends ae{constructor(){super(),this.Resource="/devices/search",this.Method=ue.Post}}class Vo extends ae{constructor(){super(),this.Resource="/devices/search/stop",this.Method=ue.Post}}class Ho extends ae{constructor(){super(),this.Resource="/devices/found/list",this.Method=ue.Get}}class jo extends ae{constructor(){super(),this.Resource="/devices/tasks",this.Method=ue.Get}}class Ko extends ae{constructor(){super(),this.Resource="/devices/device/pair",this.Method=ue.Put}}class zo extends ae{constructor(){super(),this.Resource="/devices/device/unpair",this.Method=ue.Put}}class Jo extends ae{constructor(){super(),this.Resource="/devices/device/unpair/force",this.Method=ue.Put}}class Yo extends ae{constructor(e){super(),this.Resource="/devices/device/control",this.Method=ue.Post,this.Data=e}}class Xo extends ae{constructor(e){super(),this.Resource="/devices/devices/control",this.Method=ue.Post,this.Data=e}}class Qo extends ae{constructor(e){super(),this.Resource="/logic/device/used",this.Method=ue.Get,this.Data=e}}class Zo{constructor(){this.DeviceGuid="",this.Channel=0,this.ControlFeature=Gs.GetState,this.SequnceExecutionOrder=0}}class ei extends Zo{constructor(){super(...arguments),this.R=0,this.G=0,this.B=0}}class ti extends Zo{constructor(){super(...arguments),this.FacadeAction=Is.Stop,this.Tilt=0,this.Position=0}}class ni{constructor(){this.DeviceGuid="",this.ConditionsAsCondition=[],this.ConditionsAsTask=[]}}class si extends RangeError{paramName;constructor(e){super(`${e} was out of range. Must be non-negative and less than the size of the collection.`),this.paramName=e,this.name="ArgumentOutOfRangeException",this.stack=this.stack||(new Error).stack}}const ri=Object.freeze({MoreThanOneElement:"Sequence contains more than one element",MoreThanOneMatchingElement:"Sequence contains more than one matching element",NoElements:"Sequence contains no elements",NoMatch:"Sequence contains no matching element"});class oi extends Error{constructor(e){super(e),this.name="InvalidOperationException",this.stack=this.stack||(new Error).stack}}const ii=(e,t)=>e===t;class ai{iterator;constructor(e){this.iterator=e}[Symbol.asyncIterator](){return this.iterator()}}class ci{dataFunc;constructor(e){this.dataFunc=e}[Symbol.asyncIterator](){const{dataFunc:e}=this;return async function*(){if(1===e.type)for(const t of e.generator())yield t;else for(const t of await e.generator())yield t}()}}class ui{iterator;constructor(e){this.iterator=e}[Symbol.iterator](){return this.iterator()}}class li extends Array{}const di=(e,t,n,s)=>{if(s){if(!n)throw new ReferenceError("TAccumulate function is undefined");return gi(e,t,n,s)}return n?pi(e,t,n):hi(e,t)},hi=(e,t)=>{let n;for(const s of e)n=n?t(n,s):s;if(void 0===n)throw new oi(ri.NoElements);return n},pi=(e,t,n)=>{let s=t;for(const t of e)s=n(s,t);return s},gi=(e,t,n,s)=>{let r=t;for(const t of e)r=n(r,t);return s(r)},fi=(e,t)=>{for(const n of e)if(!1===t(n))return!1;return!0},vi=async(e,t)=>{for(const n of e)if(!1===await t(n))return!1;return!0},mi=(e,t)=>t?wi(e,t):yi(e),yi=e=>{for(const t of e)return!0;return!1},wi=(e,t)=>{for(const n of e)if(!0===t(n))return!0;return!1},Si=async(e,t)=>{for(const n of e)if(!0===await t(n))return!0;return!1},Ai=(e,t)=>new ui((function*(){yield*e,yield t})),_i=e=>{if(Array.isArray(e)){if(0===e.length)throw new oi(ri.NoElements);return new ai((async function*(){for await(const t of e)yield t}))}return new ai(e)},Ci=e=>_i((async function*(){for(const t of e)yield t})),Ti=(e,t)=>new ci({generator:t,type:e}),Di=e=>Ti(0,(async()=>{const t=[];for(const n of e)t.push(n);return t})),ki=(e,t)=>{let n=0,s=0;if(t)for(const r of e)n+=t(r),s+=1;else for(const t of e)n+=t,s+=1;if(0===s)throw new oi(ri.NoElements);return n/s},Gi=async(e,t)=>{let n=0,s=0;for(const r of e)n+=await t(r),s+=1;if(0===s)throw new oi(ri.NoElements);return n/s},bi=(e,t)=>{if(t<1)throw new si("size");return new ui((function*(){let n=[];for(const s of e)n.push(s),n.length===t&&(yield n,n=[]);n.length&&(yield n)}))},Ni=(e,t)=>new ui((function*(){yield*e,yield*t})),Ei=(e,t,n=ii)=>{for(const s of e)if(n(t,s))return!0;return!1},Ii=async(e,t,n)=>{for(const s of e)if(await n(t,s))return!0;return!1},Ri=(e,t)=>t?Oi(e,t):Pi(e),Pi=e=>{let t=0;for(const n of e)t++;return t},Oi=(e,t)=>{let n=0;for(const s of e)!0===t(s)&&n++;return n},Ui=async(e,t)=>{let n=0;for(const s of e)!0===await t(s)&&n++;return n},Mi=(e,t)=>new ui((function*(){let n=!1;for(const t of e)n=!0,yield t;n||(yield t)})),xi=(e,t=ii)=>new ui((function*(){const n=[];for(const s of e)n.find((e=>t(e,s)))||(n.push(s),yield s)})),Fi=(e,t)=>_i((async function*(){const n=[];e:for(const s of e){for(const e of n)if(await t(e,s))continue e;n.push(s),yield s}})),Li=(e,t)=>new ui((function*(){for(const n of e)t(n),yield n})),Bi=(e,t)=>_i((async function*(){for(const n of e)await t(n),yield n})),Wi=(e,t)=>{if(t<0)throw new si("index");let n=0;for(const s of e)if(t===n++)return s;throw new si("index")},$i=(e,t)=>{let n=0;for(const s of e)if(t===n++)return s;return null},qi=(e,t,n=ii)=>new ui((function*(){const s=[...t];for(const t of e){let e=!1;for(let r=0;r<s.length;r++)if(!0===n(t,s[r])){e=!0;break}!1===e&&(yield t)}})),Vi=(e,t,n)=>_i((async function*(){const s=[...t];for(const t of e){let e=!1;for(let r=0;r<s.length;r++){const o=s[r];if(!0===await n(t,o)){e=!0;break}}!1===e&&(yield t)}})),Hi=(e,t)=>t?Ki(e,t):ji(e),ji=e=>{const t=e[Symbol.iterator]().next();if(!0===t.done)throw new oi(ri.NoElements);return t.value},Ki=(e,t)=>{for(const n of e)if(!0===t(n))return n;throw new oi(ri.NoMatch)},zi=async(e,t)=>{for(const n of e)if(!0===await t(n))return n;throw new oi(ri.NoMatch)},Ji=(e,t)=>t?Xi(e,t):Yi(e),Yi=e=>e[Symbol.iterator]().next().value??null,Xi=(e,t)=>{for(const n of e)if(!0===t(n))return n;return null},Qi=async(e,t)=>{for(const n of e)if(!0===await t(n))return n;return null};class Zi extends li{key;constructor(e,t){super(1),this.key=e,this[0]=t}}const ea=(e,t,n)=>{let s;return s=n?((e,t,n)=>function*(){const s=new Array;for(const r of e){const e=t(r);let o=!1;for(let t=0;t<s.length;t++){const i=s[t];if(n(i.key,e)){i.push(r),o=!0;break}}!1===o&&s.push(new Zi(e,r))}for(const e of s)yield e})(e,t,n):((e,t)=>function*(){const n={};for(const s of e){const e=t(s),r=n[e];r?r.push(s):n[e]=new Zi(e,s)}for(const e in n)yield n[e]})(e,t),new ui(s)},ta=(e,t,n)=>n?sa(e,t,n):na(e,t),na=(e,t)=>_i((async function*(){const n={};for(const s of e){const e=await t(s),r=n[e];r?r.push(s):n[e]=new Zi(e,s)}for(const e in n)yield n[e]})),sa=(e,t,n)=>_i((async function*(){const s=new Array;for(const r of e){const e=await t(r);let o=!1;for(let t=0;t<s.length;t++){const i=s[t];if(!0===await n(i.key,e)){i.push(r),o=!0;break}}!1===o&&s.push(new Zi(e,r))}for(const e of s)yield e})),ra=(e,t,n,s)=>s?((e,t,n,s)=>new ui((function*(){const r=new Array;for(const o of e){const e=t(o);let i=!1;for(let t=0;t<r.length;t++){const a=r[t];if(s(a.key,e)){a.push(n(o)),i=!0;break}}if(!1===i){const t=n(o);r.push(new Zi(e,t))}}for(const e of r)yield e})))(e,t,n,s):((e,t,n)=>new ui((function*(){const s={};for(const r of e){const e=t(r),o=s[e],i=n(r);o?o.push(i):s[e]=new Zi(e,i)}for(const e in s)yield s[e]})))(e,t,n),oa=(e,t,n,s,r,o)=>{const i=o?ia(e,t,n,s,r,o):aa(e,t,n,s,r);return new ui(i)},ia=(e,t,n,s,r,o)=>function*(){const i=[];for(const e of t){const t=s(e),n=i.find((e=>o(e.key,t)));n?n.values.push(e):i.push({key:t,values:[e]})}for(const t of e){const e=n(t),s=i.find((t=>o(t.key,e)))??{key:e,values:[]};yield r(t,s.values)}},aa=(e,t,n,s,r)=>function*(){const o=new Map;for(const e of t){const t=s(e),n=o.get(t);n?n.push(e):o.set(t,[e])}for(const t of e){const e=n(t),s=o.get(e)??[];yield r(t,s)}},ca=(e,t,n,s,r,o)=>{const i=o?ua(e,t,n,s,r,o):la(e,t,n,s,r);return _i(i)},ua=(e,t,n,s,r,o)=>async function*(){const i=[];for(const e of t){const t=await s(e),n=i.find((e=>o(e.key,t)));n?n.values.push(e):i.push({key:t,values:[e]})}for(const t of e){const e=await n(t),s=i.find((t=>o(t.key,e)))??{key:e,values:[]};yield r(t,s.values)}},la=(e,t,n,s,r)=>async function*(){const o=new Map;for(const e of t){const t=await s(e),n=o.get(t);n?n.push(e):o.set(t,[e])}for(const t of e){const e=await n(t),s=o.get(e)??[];yield r(t,s)}},da=(e,t,n=ii)=>new ui((function*(){const s=[...e.distinct(n)];if(0===s.length)return;const r=[...t];for(let e=0;e<s.length;e++){const t=s[e];for(let e=0;e<r.length;e++)if(!0===n(t,r[e])){yield t;break}}})),ha=(e,t,n)=>_i((async function*(){const s=[];for await(const t of e.distinctAsync(n))s.push(t);if(0===s.length)return;const r=[...t];for(let e=0;e<s.length;e++){const t=s[e];for(let e=0;e<r.length;e++){const s=r[e];if(!0===await n(t,s)){yield t;break}}}})),pa=(e,t,n,s,r,o=ii)=>new ui((function*(){const i=[...t];for(const t of e){const e=n(t);for(const n of i){const i=s(n);!0===o(e,i)&&(yield r(t,n))}}})),ga=(e,t)=>t?va(e,t):fa(e),fa=e=>{let t;for(const n of e)t=n;if(!t)throw new oi(ri.NoElements);return t},va=(e,t)=>{let n;for(const s of e)!0===t(s)&&(n=s);if(!n)throw new oi(ri.NoMatch);return n},ma=async(e,t)=>{let n;for(const s of e)!0===await t(s)&&(n=s);if(!n)throw new oi(ri.NoMatch);return n},ya=(e,t)=>t?Sa(e,t):wa(e),wa=e=>{let t=null;for(const n of e)t=n;return t},Sa=(e,t)=>{let n=null;for(const s of e)!0===t(s)&&(n=s);return n},Aa=async(e,t)=>{let n=null;for(const s of e)!0===await t(s)&&(n=s);return n},_a=(e,t)=>t?Ta(e,t):Ca(e),Ca=e=>{let t=null;for(const n of e)t=Math.max(t??Number.NEGATIVE_INFINITY,n);if(null===t)throw new oi(ri.NoElements);return t},Ta=(e,t)=>{let n=null;for(const s of e)n=Math.max(n??Number.NEGATIVE_INFINITY,t(s));if(null===n)throw new oi(ri.NoElements);return n},Da=async(e,t)=>{let n=null;for(const s of e)n=Math.max(n??Number.NEGATIVE_INFINITY,await t(s));if(null===n)throw new oi(ri.NoElements);return n},ka=(e,t)=>t?ba(e,t):Ga(e),Ga=e=>{let t=null;for(const n of e)t=Math.min(t??Number.POSITIVE_INFINITY,n);if(null===t)throw new oi(ri.NoElements);return t},ba=(e,t)=>{let n=null;for(const s of e)n=Math.min(n??Number.POSITIVE_INFINITY,t(s));if(null===n)throw new oi(ri.NoElements);return n},Na=async(e,t)=>{let n=null;for(const s of e)n=Math.min(n??Number.POSITIVE_INFINITY,await t(s));if(null===n)throw new oi(ri.NoElements);return n},Ea=(e,t)=>{const n="string"==typeof t?e=>typeof e===t:e=>e instanceof t;return new ui((function*(){for(const t of e)n(t)&&(yield t)}))};async function*Ia(e,t,n,s){const r=await(async(e,t)=>{const n=new Map;for(const s of e){const e=await t(s),r=n.get(e);r?r.push(s):n.set(e,[s])}return n})(e,t),o=[...r.keys()].sort(s||void 0);if(n)for(let e=0;e<o.length;e++)yield r.get(o[e]);else for(let e=o.length-1;e>=0;e--)yield r.get(o[e])}function*Ra(e,t,n,s){const r=((e,t)=>{const n=new Map;for(const s of e){const e=t(s),r=n.get(e);r?r.push(s):n.set(e,[s])}return n})(e,t),o=[...r.keys()].sort(s||void 0);if(n)for(let e=0;e<o.length;e++)yield r.get(o[e]);else for(let e=o.length-1;e>=0;e--)yield r.get(o[e])}class Pa extends ai{orderedPairs;constructor(e){super((async function*(){for await(const t of e())yield*t})),this.orderedPairs=e}static generateAsync(e,t,n,s){let r;return r=e instanceof Pa?async function*(){for await(const r of e.orderedPairs())yield*Ia(r,t,n,s)}:()=>async function*(e,t,n,s){const r=await(async(e,t)=>{const n=new Map;for await(const s of e){const e=await t(s),r=n.get(e);r?r.push(s):n.set(e,[s])}return n})(e,t),o=[...r.keys()].sort(s||void 0);if(n)for(let e=0;e<o.length;e++)yield r.get(o[e]);else for(let e=o.length-1;e>=0;e--)yield r.get(o[e])}(e,t,n,s),new Pa(r)}static generate(e,t,n,s){let r;return r=e instanceof Pa?async function*(){for await(const r of e.orderedPairs())yield*Ra(r,t,n,s)}:()=>async function*(e,t,n,s){const r=await(async(e,t)=>{const n=new Map;for await(const s of e){const e=t(s),r=n.get(e);r?r.push(s):n.set(e,[s])}return n})(e,t),o=[...r.keys()].sort(s||void 0);if(n)for(let e=0;e<o.length;e++)yield r.get(o[e]);else for(let e=o.length-1;e>=0;e--)yield r.get(o[e])}(e,t,n,s),new Pa(r)}thenBy(e,t){return Pa.generate(this,e,!0,t)}thenByAsync(e,t){return Pa.generateAsync(this,e,!0,t)}thenByDescending(e,t){return Pa.generate(this,e,!1,t)}thenByDescendingAsync(e,t){return Pa.generateAsync(this,e,!1,t)}}function*Oa(e,t,n,s){const r=((e,t)=>{const n=new Map;for(const s of e){const e=t(s),r=n.get(e);r?r.push(s):n.set(e,[s])}return n})(e,t),o=[...r.keys()].sort(s||void 0);if(n)for(let e=0;e<o.length;e++)yield r.get(o[e]);else for(let e=o.length-1;e>=0;e--)yield r.get(o[e])}async function*Ua(e,t,n,s){const r=await(async(e,t)=>{const n=new Map;for(const s of e){const e=await t(s),r=n.get(e);r?r.push(s):n.set(e,[s])}return n})(e,t),o=[...r.keys()].sort(s||void 0);if(n)for(let e=0;e<o.length;e++)yield r.get(o[e]);else for(let e=o.length-1;e>=0;e--)yield r.get(o[e])}class Ma extends ui{orderedPairs;constructor(e){super((function*(){for(const t of e())yield*t})),this.orderedPairs=e}static generate(e,t,n,s){let r;return r=e instanceof Ma?function*(){for(const r of e.orderedPairs())yield*Oa(r,t,n,s)}:()=>Oa(e,t,n,s),new Ma(r)}static generateAsync(e,t,n,s){let r;return r=e instanceof Ma?async function*(){for(const r of e.orderedPairs())yield*Ua(r,t,n,s)}:()=>Ua(e,t,n,s),new Pa(r)}thenBy(e,t){return Ma.generate(this,e,!0,t)}thenByAsync(e,t){return Ma.generateAsync(this,e,!0,t)}thenByDescending(e,t){return Ma.generate(this,e,!1,t)}thenByDescendingAsync(e,t){return Ma.generateAsync(this,e,!1,t)}}const xa=(e,t)=>Ma.generate(e,(e=>e),!0,t),Fa=(e,t,n)=>Ma.generate(e,t,!0,n),La=(e,t,n)=>Ma.generateAsync(e,t,!0,n),Ba=(e,t,n)=>Ma.generate(e,t,!1,n),Wa=(e,t,n)=>Ma.generateAsync(e,t,!1,n),$a=(e,t)=>Ma.generate(e,(e=>e),!1,t),qa=(e,t)=>{const n=[],s=[];for(const r of e)!0===t(r)?s.push(r):n.push(r);return[s,n]},Va=async(e,t)=>{const n=[],s=[];for(const r of e)!0===await t(r)?s.push(r):n.push(r);return[s,n]},Ha=(e,t)=>new ui((function*(){yield t,yield*e})),ja=e=>new ui((function*(){const t=[...e];for(let e=t.length-1;e>=0;e--)yield t[e]})),Ka=(e,t)=>{if("function"==typeof t){const{length:n}=t;return 1===n?za(e,t):Ja(e,t)}return Ya(e,t)},za=(e,t)=>new ui((function*(){for(const n of e)yield t(n)})),Ja=(e,t)=>new ui((function*(){let n=0;for(const s of e)yield t(s,n),n++})),Ya=(e,t)=>new ui((function*(){for(const n of e)yield n[t]})),Xa=(e,t)=>"function"==typeof t?1===t.length?Qa(e,t):Za(e,t):ec(e,t),Qa=(e,t)=>_i((async function*(){for(const n of e)yield t(n)})),Za=(e,t)=>_i((async function*(){let n=0;for(const s of e)yield t(s,n),n++})),ec=(e,t)=>_i((async function*(){for(const n of e)yield n[t]})),tc=(e,t)=>"function"==typeof t?1===t.length?nc(e,t):sc(e,t):rc(e,t),nc=(e,t)=>new ui((function*(){for(const n of e)for(const e of t(n))yield e})),sc=(e,t)=>new ui((function*(){let n=0;for(const s of e){for(const e of t(s,n))yield e;n++}})),rc=(e,t)=>new ui((function*(){for(const n of e)for(const e of n[t])yield e})),oc=(e,t)=>1===t.length?ic(e,t):ac(e,t),ic=(e,t)=>_i((async function*(){for(const n of e){const e=await t(n);for(const t of e)yield t}})),ac=(e,t)=>_i((async function*(){let n=0;for(const s of e){const e=await t(s,n);for(const t of e)yield t;n++}})),cc=(e,t,n=ii)=>{const s=e[Symbol.iterator](),r=t[Symbol.iterator]();let o=s.next(),i=r.next();for(;!o.done&&!i.done;){if(!n(o.value,i.value))return!1;o=s.next(),i=r.next()}return!0===o.done&&!0===i.done},uc=async(e,t,n)=>{const s=e[Symbol.iterator](),r=t[Symbol.iterator]();let o=s.next(),i=r.next();for(;!o.done&&!i.done;){if(!1===await n(o.value,i.value))return!1;o=s.next(),i=r.next()}return!0===o.done&&!0===i.done},lc=(e,t)=>t?hc(e,t):dc(e),dc=e=>{let t=!1,n=null;for(const s of e){if(!0===t)throw new oi(ri.MoreThanOneElement);t=!0,n=s}if(!1===t)throw new oi(ri.NoElements);return n},hc=(e,t)=>{let n=!1,s=null;for(const r of e)if(t(r)){if(!0===n)throw new oi(ri.MoreThanOneMatchingElement);n=!0,s=r}if(!1===n)throw new oi(ri.NoMatch);return s},pc=async(e,t)=>{let n=!1,s=null;for(const r of e)if(await t(r)){if(!0===n)throw new oi(ri.MoreThanOneMatchingElement);n=!0,s=r}if(!1===n)throw new oi(ri.NoMatch);return s},gc=(e,t)=>t?vc(e,t):fc(e),fc=e=>{let t=!1,n=null;for(const s of e){if(!0===t)throw new oi(ri.MoreThanOneElement);t=!0,n=s}return n},vc=(e,t)=>{let n=!1,s=null;for(const r of e)if(t(r)){if(!0===n)throw new oi(ri.MoreThanOneMatchingElement);n=!0,s=r}return s},mc=async(e,t)=>{let n=!1,s=null;for(const r of e)if(await t(r)){if(!0===n)throw new oi(ri.MoreThanOneElement);n=!0,s=r}return s},yc=(e,t)=>new ui((function*(){let n=0;for(const s of e)n++>=t&&(yield s)})),wc=(e,t)=>1===t.length?Sc(e,t):Ac(e,t),Sc=(e,t)=>new ui((function*(){let n=!0;for(const s of e)!1===n?yield s:!1===t(s)&&(n=!1,yield s)})),Ac=(e,t)=>new ui((function*(){let n=0,s=!0;for(const r of e)!1===s?yield r:!1===t(r,n)&&(s=!1,yield r),n++})),_c=(e,t)=>1===t.length?Cc(e,t):Tc(e,t),Cc=(e,t)=>_i((async function*(){let n=!0;for(const s of e)!1===n?yield s:!1===await t(s)&&(n=!1,yield s)})),Tc=(e,t)=>_i((async function*(){let n=0,s=!0;for(const r of e)!1===s?yield r:!1===await t(r,n)&&(s=!1,yield r),n++})),Dc=(e,t)=>t?Gc(e,t):kc(e),kc=e=>{let t=0;for(const n of e)t+=n;return t},Gc=(e,t)=>{let n=0;for(const s of e)n+=t(s);return n},bc=async(e,t)=>{let n=0;for(const s of e)n+=await t(s);return n},Nc=(e,t)=>new ui((function*(){let n=t>0?t:0;for(const t of e){if(0==n--)break;yield t}})),Ec=(e,t)=>1===t.length?Ic(e,t):Rc(e,t),Ic=(e,t)=>new ui((function*(){for(const n of e){if(!t(n))break;yield n}})),Rc=(e,t)=>new ui((function*(){let n=0;for(const s of e){if(!t(s,n++))break;yield s}})),Pc=(e,t)=>1===t.length?Oc(e,t):Uc(e,t),Oc=(e,t)=>_i((async function*(){for(const n of e){if(!await t(n))break;yield n}})),Uc=(e,t)=>_i((async function*(){let n=0;for(const s of e){if(!await t(s,n++))break;yield s}})),Mc=e=>[...e],xc=(e,t)=>{const n=new Map;for(const s of e){const e=t(s),r=n.get(e);void 0===r?n.set(e,[s]):r.push(s)}return n},Fc=async(e,t)=>{const n=new Map;for(const s of e){const e=await t(s),r=n.get(e);void 0===r?n.set(e,[s]):r.push(s)}return n},Lc=(e,t)=>{const n={};for(const s of e)n[t(s)]=s;return n},Bc=async(e,t)=>{const n={};for(const s of e)n[await t(s)]=s;return n},Wc=e=>new Set(e),$c=(e,t,n)=>n?Vc(e,t,n):qc(e,t),qc=(e,t)=>new ui((function*(){const n=new Set;for(const t of e)!1===n.has(t)&&(yield t,n.add(t));for(const e of t)!1===n.has(e)&&(yield e,n.add(e))})),Vc=(e,t,n)=>new ui((function*(){const s=[];for(const r of[e,t])for(const e of r){let t=!1;for(const r of s)if(!0===n(e,r)){t=!0;break}!1===t&&(yield e,s.push(e))}})),Hc=(e,t,n)=>_i((async function*(){const s=[];for(const r of[e,t])for(const e of r){let t=!1;for(const r of s)if(!0===await n(e,r)){t=!0;break}!1===t&&(yield e,s.push(e))}})),jc=(e,t)=>1===t.length?Kc(e,t):zc(e,t),Kc=(e,t)=>new ui((function*(){for(const n of e)!0===t(n)&&(yield n)})),zc=(e,t)=>new ui((function*(){let n=0;for(const s of e)!0===t(s,n++)&&(yield s)})),Jc=(e,t)=>1===t.length?Yc(e,t):Xc(e,t),Yc=(e,t)=>_i((async function*(){for(const n of e)!0===await t(n)&&(yield n)})),Xc=(e,t)=>_i((async function*(){let n=0;for(const s of e)!0===await t(s,n++)&&(yield s)})),Qc=(e,t,n)=>n?eu(e,t,n):Zc(e,t),Zc=(e,t)=>new ui((function*(){const n=e[Symbol.iterator](),s=t[Symbol.iterator]();for(;;){const e=n.next(),t=s.next();if(e.done||t.done)break;yield[e.value,t.value]}})),eu=(e,t,n)=>new ui((function*(){const s=e[Symbol.iterator](),r=t[Symbol.iterator]();for(;;){const e=s.next(),t=r.next();if(e.done||t.done)break;yield n(e.value,t.value)}})),tu=(e,t,n)=>_i((async function*(){const s=e[Symbol.iterator](),r=t[Symbol.iterator]();for(;;){const e=s.next(),t=r.next();if(e.done||t.done)break;yield n(e.value,t.value)}})),nu=e=>{const t=e.prototype,n=(e,n)=>{const s=function(...t){return e(this,...t)};Object.defineProperty(s,"length",{value:e.length-1}),t[n]=s};n(di,"aggregate"),n(fi,"all"),n(vi,"allAsync"),n(mi,"any"),n(Si,"anyAsync"),n(Ai,"append"),n(Ci,"asAsync"),n(Di,"asParallel"),n(ki,"average"),n(Gi,"averageAsync"),n(bi,"chunk"),n(Ni,"concatenate"),n(Ei,"contains"),n(Ii,"containsAsync"),n(Ri,"count"),n(Ui,"countAsync"),n(Mi,"defaultIfEmpty"),n(xi,"distinct"),n(Fi,"distinctAsync"),n(Li,"each"),n(Bi,"eachAsync"),n(Wi,"elementAt"),n($i,"elementAtOrDefault"),n(qi,"except"),n(Vi,"exceptAsync"),n(Hi,"first"),n(zi,"firstAsync"),n(Ji,"firstOrDefault"),n(Qi,"firstOrDefaultAsync"),n(ea,"groupBy"),n(ta,"groupByAsync"),n(ra,"groupByWithSel"),n(oa,"groupJoin"),n(ca,"groupJoinAsync"),n(da,"intersect"),n(ha,"intersectAsync"),n(pa,"joinByKey"),n(ga,"last"),n(ma,"lastAsync"),n(ya,"lastOrDefault"),n(Aa,"lastOrDefaultAsync"),n(_a,"max"),n(Da,"maxAsync"),n(ka,"min"),n(Na,"minAsync"),n(Ea,"ofType"),n(xa,"order"),n(Fa,"orderBy"),n(La,"orderByAsync"),n(Ba,"orderByDescending"),n(Wa,"orderByDescendingAsync"),n($a,"orderDescending"),n(Ha,"prepend"),n(ja,"reverse"),n(Ka,"select"),n(Xa,"selectAsync"),n(tc,"selectMany"),n(oc,"selectManyAsync"),n(cc,"sequenceEquals"),n(uc,"sequenceEqualsAsync"),n(lc,"single"),n(pc,"singleAsync"),n(gc,"singleOrDefault"),n(mc,"singleOrDefaultAsync"),n(yc,"skip"),n(wc,"skipWhile"),n(_c,"skipWhileAsync"),n(Dc,"sum"),n(bc,"sumAsync"),n(Nc,"take"),n(Ec,"takeWhile"),n(Pc,"takeWhileAsync"),n(Mc,"toArray"),n(xc,"toMap"),n(Fc,"toMapAsync"),n(Lc,"toObject"),n(Bc,"toObjectAsync"),n(qa,"partition"),n(Va,"partitionAsync"),n(Wc,"toSet"),n($c,"union"),n(Hc,"unionAsync"),n(jc,"where"),n(Jc,"whereAsync"),n(Qc,"zip"),n(tu,"zipAsync")},su=(e,t,n,s)=>{if(s){if(!n)throw new ReferenceError("TAccumulate function is undefined");return iu(e,t,n,s)}return n?ou(e,t,n):ru(e,t)},ru=async(e,t)=>{let n;for await(const s of e)n=n?t(n,s):s;if(void 0===n)throw new oi(ri.NoElements);return n},ou=async(e,t,n)=>{let s=t;for await(const t of e)s=n(s,t);return s},iu=async(e,t,n,s)=>{let r=t;for await(const t of e)r=n(r,t);return s(r)},au=async(e,t)=>{for await(const n of e)if(!1===t(n))return!1;return!0},cu=async(e,t)=>{for await(const n of e)if(!1===await t(n))return!1;return!0},uu=(e,t)=>new ai((async function*(){yield*e,yield t})),lu=(e,t)=>t?hu(e,t):du(e),du=async e=>{for await(const t of e)return!0;return!1},hu=async(e,t)=>{for await(const n of e)if(!0===t(n))return!0;return!1},pu=async(e,t)=>{for await(const n of e)if(!0===await t(n))return!0;return!1},gu=e=>Ti(0,(async()=>{const t=[];for await(const n of e)t.push(n);return t})),fu=async(e,t)=>{let n=0,s=0;if(t)for await(const r of e)n+=t(r),s+=1;else for await(const t of e)n+=t,s+=1;if(0===s)throw new oi(ri.NoElements);return n/s},vu=async(e,t)=>{let n=0,s=0;for await(const r of e)n+=await t(r),s+=1;if(0===s)throw new oi(ri.NoElements);return n/s},mu=(e,t)=>{if(t<1)throw new si("size");return new ai((async function*(){let n=[];for await(const s of e)n.push(s),n.length===t&&(yield n,n=[]);n.length&&(yield n)}))},yu=(e,t)=>new ai((async function*(){yield*e,yield*t})),wu=async(e,t,n=ii)=>{for await(const s of e)if(n(t,s))return!0;return!1},Su=async(e,t,n)=>{for await(const s of e)if(await n(t,s))return!0;return!1},Au=(e,t)=>t?Cu(e,t):_u(e),_u=async e=>{let t=0;for await(const n of e)t++;return t},Cu=async(e,t)=>{let n=0;for await(const s of e)!0===t(s)&&n++;return n},Tu=async(e,t)=>{let n=0;for await(const s of e)!0===await t(s)&&n++;return n},Du=(e,t)=>new ai((async function*(){let n=!1;for await(const t of e)n=!0,yield t;n||(yield t)})),ku=(e,t=ii)=>new ai((async function*(){const n=[];for await(const s of e)n.find((e=>t(e,s)))||(n.push(s),yield s)})),Gu=(e,t)=>new ai((async function*(){const n=[];e:for await(const s of e){for(const e of n)if(await t(e,s))continue e;n.push(s),yield s}})),bu=(e,t)=>new ai((async function*(){for await(const n of e)t(n),yield n})),Nu=(e,t)=>new ai((async function*(){for await(const n of e)await t(n),yield n})),Eu=async(e,t)=>{if(t<0)throw new si("index");let n=0;for await(const s of e)if(t===n++)return s;throw new si("index")},Iu=async(e,t)=>{let n=0;for await(const s of e)if(t===n++)return s;return null},Ru=(e,t,n=ii)=>new ai((async function*(){const s=[];for await(const e of t)s.push(e);for await(const t of e){let e=!1;for(let r=0;r<s.length;r++){const o=s[r];if(!0===n(t,o)){e=!0;break}}!1===e&&(yield t)}})),Pu=(e,t,n)=>new ai((async function*(){const s=[];for await(const e of t)s.push(e);for await(const t of e){let e=!1;for(let r=0;r<s.length;r++){const o=s[r];if(!0===await n(t,o)){e=!0;break}}!1===e&&(yield t)}})),Ou=(e,t)=>t?Mu(e,t):Uu(e),Uu=async e=>{const t=await e[Symbol.asyncIterator]().next();if(!0===t.done)throw new oi(ri.NoElements);return t.value},Mu=async(e,t)=>{for await(const n of e)if(!0===t(n))return n;throw new oi(ri.NoMatch)},xu=async(e,t)=>{for await(const n of e)if(!0===await t(n))return n;throw new oi(ri.NoMatch)},Fu=(e,t)=>t?Bu(e,t):Lu(e),Lu=async e=>(await e[Symbol.asyncIterator]().next()).value??null,Bu=async(e,t)=>{for await(const n of e)if(!0===t(n))return n;return null},Wu=async(e,t)=>{for await(const n of e)if(!0===await t(n))return n;return null},$u=(e,t,n)=>n?qu(e,t,n):Vu(e,t),qu=(e,t,n)=>new ai((async function*(){const s=new Array;for await(const r of e){const e=t(r);let o=!1;for(let t=0;t<s.length;t++){const i=s[t];if(n(i.key,e)){i.push(r),o=!0;break}}!1===o&&s.push(new Zi(e,r))}for(const e of s)yield e})),Vu=(e,t)=>new ai((async function*(){const n={};for await(const s of e){const e=t(s),r=n[e];r?r.push(s):n[e]=new Zi(e,s)}for(const e in n)yield n[e]})),Hu=(e,t,n)=>n?Ku(e,t,n):ju(e,t),ju=(e,t)=>new ai((async function*(){const n={};for await(const s of e){const e=await t(s),r=n[e];r?r.push(s):n[e]=new Zi(e,s)}for(const e in n)yield n[e]})),Ku=(e,t,n)=>new ai((async function*(){const s=new Array;for await(const r of e){const e=await t(r);let o=!1;for(let t=0;t<s.length;t++){const i=s[t];if(!0===await n(i.key,e)){i.push(r),o=!0;break}}!1===o&&s.push(new Zi(e,r))}for(const e of s)yield e})),zu=(e,t,n,s)=>s?Yu(e,t,n,s):Ju(e,t,n),Ju=(e,t,n)=>new ai((async function*(){const s={};for await(const r of e){const e=t(r),o=s[e],i=n(r);o?o.push(i):s[e]=new Zi(e,i)}for(const e in s)yield s[e]})),Yu=(e,t,n,s)=>new ai((async function*(){const r=new Array;for await(const o of e){const e=t(o);let i=!1;for(let t=0;t<r.length;t++){const a=r[t];if(s(a.key,e)){a.push(n(o)),i=!0;break}}if(!1===i){const t=n(o);r.push(new Zi(e,t))}}for(const e of r)yield e})),Xu=(e,t,n,s,r,o)=>{const i=o?Qu(e,t,n,s,r,o):Zu(e,t,n,s,r);return new ai(i)},Qu=(e,t,n,s,r,o)=>async function*(){const i=[];for await(const e of t){const t=s(e),n=i.find((e=>o(e.key,t)));n?n.values.push(e):i.push({key:t,values:[e]})}for await(const t of e){const e=n(t),s=i.find((t=>o(t.key,e)))??{key:e,values:[]};yield r(t,s.values)}},Zu=(e,t,n,s,r)=>async function*(){const o=new Map;for await(const e of t){const t=s(e),n=o.get(t);n?n.push(e):o.set(t,[e])}for await(const t of e){const e=n(t),s=o.get(e)??[];yield r(t,s)}},el=(e,t,n,s,r,o)=>{const i=o?tl(e,t,n,s,r,o):nl(e,t,n,s,r);return new ai(i)},tl=(e,t,n,s,r,o)=>async function*(){const i=[];for await(const e of t){const t=await s(e),n=i.find((e=>o(e.key,t)));n?n.values.push(e):i.push({key:t,values:[e]})}for await(const t of e){const e=await n(t),s=i.find((t=>o(t.key,e)))??{key:e,values:[]};yield r(t,s.values)}},nl=(e,t,n,s,r)=>async function*(){const o=new Map;for await(const e of t){const t=await s(e),n=o.get(t);n?n.push(e):o.set(t,[e])}for await(const t of e){const e=await n(t),s=o.get(e)??[];yield r(t,s)}},sl=(e,t,n=ii)=>new ai((async function*(){const s=await e.distinct(n).toArray();if(0===s.length)return;const r=await t.toArray();for(let e=0;e<s.length;e++){const t=s[e];for(let e=0;e<r.length;e++){const s=r[e];if(!0===n(t,s)){yield t;break}}}})),rl=(e,t,n)=>new ai((async function*(){const s=await e.distinctAsync(n).toArray();if(0===s.length)return;const r=await t.toArray();for(let e=0;e<s.length;e++){const t=s[e];for(let e=0;e<r.length;e++){const s=r[e];if(!0===await n(t,s)){yield t;break}}}})),ol=(e,t,n,s,r,o=ii)=>new ai((async function*(){const i=[];for await(const e of t)i.push(e);for await(const t of e){const e=n(t);for(const n of i){const i=s(n);!0===o(e,i)&&(yield r(t,n))}}})),il=(e,t)=>t?cl(e,t):al(e),al=async e=>{let t=null;for await(const n of e)t=n;if(!t)throw new oi(ri.NoElements);return t},cl=async(e,t)=>{let n=null;for await(const s of e)!0===t(s)&&(n=s);if(!n)throw new oi(ri.NoMatch);return n},ul=async(e,t)=>{let n=null;for await(const s of e)!0===await t(s)&&(n=s);if(!n)throw new oi(ri.NoMatch);return n},ll=(e,t)=>t?hl(e,t):dl(e),dl=async e=>{let t=null;for await(const n of e)t=n;return t},hl=async(e,t)=>{let n=null;for await(const s of e)!0===t(s)&&(n=s);return n},pl=async(e,t)=>{let n=null;for await(const s of e)!0===await t(s)&&(n=s);return n},gl=(e,t)=>t?vl(e,t):fl(e),fl=async e=>{let t=null;for await(const n of e)t=Math.max(t??Number.NEGATIVE_INFINITY,n);if(null===t)throw new oi(ri.NoElements);return t},vl=async(e,t)=>{let n=null;for await(const s of e)n=Math.max(n??Number.NEGATIVE_INFINITY,t(s));if(null===n)throw new oi(ri.NoElements);return n},ml=async(e,t)=>{let n=null;for await(const s of e)n=Math.max(n??Number.NEGATIVE_INFINITY,await t(s));if(null===n)throw new oi(ri.NoElements);return n},yl=(e,t)=>t?Sl(e,t):wl(e),wl=async e=>{let t=null;for await(const n of e)t=Math.min(t??Number.POSITIVE_INFINITY,n);if(null===t)throw new oi(ri.NoElements);return t},Sl=async(e,t)=>{let n=null;for await(const s of e)n=Math.min(n??Number.POSITIVE_INFINITY,t(s));if(null===n)throw new oi(ri.NoElements);return n},Al=async(e,t)=>{let n=null;for await(const s of e)n=Math.min(n??Number.POSITIVE_INFINITY,await t(s));if(null===n)throw new oi(ri.NoElements);return n},_l=(e,t)=>{const n="string"==typeof t?e=>typeof e===t:e=>e instanceof t;return new ai((async function*(){for await(const t of e)n(t)&&(yield t)}))},Cl=(e,t)=>Pa.generate(e,(e=>e),!0,t),Tl=(e,t,n)=>Pa.generate(e,t,!0,n),Dl=(e,t,n)=>Pa.generateAsync(e,t,!0,n),kl=(e,t,n)=>Pa.generate(e,t,!1,n),Gl=(e,t,n)=>Pa.generateAsync(e,t,!1,n),bl=(e,t)=>Pa.generate(e,(e=>e),!1,t),Nl=async(e,t)=>{const n=[],s=[];for await(const r of e)!0===t(r)?s.push(r):n.push(r);return[s,n]},El=async(e,t)=>{const n=[],s=[];for await(const r of e)!0===await t(r)?s.push(r):n.push(r);return[s,n]},Il=(e,t)=>new ai((async function*(){yield t,yield*e})),Rl=e=>new ai((async function*(){const t=[];for await(const n of e)t.push(n);for(let e=t.length-1;e>=0;e--)yield t[e]})),Pl=(e,t)=>"function"==typeof t?1===t.length?Ol(e,t):Ul(e,t):Ml(e,t),Ol=(e,t)=>new ai((async function*(){for await(const n of e)yield t(n)})),Ul=(e,t)=>new ai((async function*(){let n=0;for await(const s of e)yield t(s,n),n++})),Ml=(e,t)=>new ai((async function*(){for await(const n of e)yield n[t]})),xl=(e,t)=>"string"==typeof t?Ll(e,t):Fl(e,t),Fl=(e,t)=>new ai((async function*(){for await(const n of e)yield t(n)})),Ll=(e,t)=>new ai((async function*(){for await(const n of e)yield n[t]})),Bl=(e,t)=>"function"==typeof t?1===t.length?Wl(e,t):$l(e,t):ql(e,t),Wl=(e,t)=>new ai((async function*(){for await(const n of e)for(const e of t(n))yield e})),$l=(e,t)=>new ai((async function*(){let n=0;for await(const s of e){for(const e of t(s,n))yield e;n++}})),ql=(e,t)=>new ai((async function*(){for await(const n of e)for(const e of n[t])yield e})),Vl=(e,t)=>1===t.length?new ai((async function*(){for await(const n of e){const e=await t(n);for(const t of e)yield t}})):new ai((async function*(){let n=0;for await(const s of e){const e=await t(s,n);for(const t of e)yield t;n++}})),Hl=async(e,t,n=ii)=>{const s=e[Symbol.asyncIterator](),r=t[Symbol.asyncIterator]();let o=await Promise.all([s.next(),r.next()]),i=o[0],a=o[1];for(;!i.done&&!a.done;){if(!n(i.value,a.value))return!1;o=await Promise.all([s.next(),r.next()]),i=o[0],a=o[1]}return!0===i.done&&!0===a.done},jl=async(e,t,n)=>{const s=e[Symbol.asyncIterator](),r=t[Symbol.asyncIterator]();let o=await Promise.all([s.next(),r.next()]),i=o[0],a=o[1];for(;!i.done&&!a.done;){if(!1===await n(i.value,a.value))return!1;o=await Promise.all([s.next(),r.next()]),i=o[0],a=o[1]}return!0===i.done&&!0===a.done},Kl=(e,t)=>t?Jl(e,t):zl(e),zl=async e=>{let t=!1,n=null;for await(const s of e){if(!0===t)throw new oi(ri.MoreThanOneElement);t=!0,n=s}if(!1===t)throw new oi(ri.NoElements);return n},Jl=async(e,t)=>{let n=!1,s=null;for await(const r of e)if(t(r)){if(!0===n)throw new oi(ri.MoreThanOneMatchingElement);n=!0,s=r}if(!1===n)throw new oi(ri.NoMatch);return s},Yl=async(e,t)=>{let n=!1,s=null;for await(const r of e)if(await t(r)){if(!0===n)throw new oi(ri.MoreThanOneMatchingElement);n=!0,s=r}if(!1===n)throw new oi(ri.NoMatch);return s},Xl=(e,t)=>t?Zl(e,t):Ql(e),Ql=async e=>{let t=!1,n=null;for await(const s of e){if(!0===t)throw new oi(ri.MoreThanOneElement);t=!0,n=s}return n},Zl=async(e,t)=>{let n=!1,s=null;for await(const r of e)if(t(r)){if(!0===n)throw new oi(ri.MoreThanOneMatchingElement);n=!0,s=r}return s},ed=async(e,t)=>{let n=!1,s=null;for await(const r of e)if(await t(r)){if(!0===n)throw new oi(ri.MoreThanOneMatchingElement);n=!0,s=r}return s},td=(e,t)=>new ai((async function*(){let n=0;for await(const s of e)n++>=t&&(yield s)})),nd=(e,t)=>1===t.length?sd(e,t):rd(e,t),sd=(e,t)=>new ai((async function*(){let n=!0;for await(const s of e)!1===n?yield s:!1===t(s)&&(n=!1,yield s)})),rd=(e,t)=>new ai((async function*(){let n=0,s=!0;for await(const r of e)!1===s?yield r:!1===t(r,n)&&(s=!1,yield r),n++})),od=(e,t)=>1===t.length?id(e,t):ad(e,t),id=(e,t)=>new ai((async function*(){let n=!0;for await(const s of e)!1===n?yield s:!1===await t(s)&&(n=!1,yield s)})),ad=(e,t)=>new ai((async function*(){let n=0,s=!0;for await(const r of e)!1===s?yield r:!1===await t(r,n)&&(s=!1,yield r),n++})),cd=(e,t)=>t?ld(e,t):ud(e),ud=async e=>{let t=0;for await(const n of e)t+=n;return t},ld=async(e,t)=>{let n=0;for await(const s of e)n+=t(s);return n},dd=async(e,t)=>{let n=0;for await(const s of e)n+=await t(s);return n},hd=(e,t)=>new ai((async function*(){let n=t>0?t:0;for await(const t of e){if(0==n--)break;yield t}})),pd=(e,t)=>1===t.length?gd(e,t):fd(e,t),gd=(e,t)=>new ai((async function*(){for await(const n of e){if(!t(n))break;yield n}})),fd=(e,t)=>new ai((async function*(){let n=0;for await(const s of e){if(!t(s,n++))break;yield s}})),vd=(e,t)=>1===t.length?md(e,t):yd(e,t),md=(e,t)=>new ai((async function*(){for await(const n of e){if(!await t(n))break;yield n}})),yd=(e,t)=>new ai((async function*(){let n=0;for await(const s of e){if(!await t(s,n++))break;yield s}})),wd=async e=>{const t=[];for await(const n of e)t.push(n);return t},Sd=async(e,t)=>{const n=new Map;for await(const s of e){const e=t(s),r=n.get(e);void 0===r?n.set(e,[s]):r.push(s)}return n},Ad=async(e,t)=>{const n=new Map;for await(const s of e){const e=await t(s),r=n.get(e);void 0===r?n.set(e,[s]):r.push(s)}return n},_d=async(e,t)=>{const n={};for await(const s of e)n[t(s)]=s;return n},Cd=async(e,t)=>{const n={};for await(const s of e)n[await t(s)]=s;return n},Td=async e=>{const t=new Set;for await(const n of e)t.add(n);return t},Dd=(e,t,n)=>n?Gd(e,t,n):kd(e,t),kd=(e,t)=>new ai((async function*(){const n=new Set;for await(const t of e)!1===n.has(t)&&(yield t,n.add(t));for await(const e of t)!1===n.has(e)&&(yield e,n.add(e))})),Gd=(e,t,n)=>new ai((async function*(){const s=[];for(const r of[e,t])for await(const e of r){let t=!1;for(const r of s)if(!0===n(e,r)){t=!0;break}!1===t&&(yield e,s.push(e))}})),bd=(e,t,n)=>new ai((async function*(){const s=[];for(const r of[e,t])for await(const e of r){let t=!1;for(const r of s)if(!0===await n(e,r)){t=!0;break}!1===t&&(yield e,s.push(e))}})),Nd=(e,t)=>1===t.length?Ed(e,t):Id(e,t),Ed=(e,t)=>new ai((async function*(){for await(const n of e)!0===t(n)&&(yield n)})),Id=(e,t)=>new ai((async function*(){let n=0;for await(const s of e)!0===t(s,n++)&&(yield s)})),Rd=(e,t)=>1===t.length?Pd(e,t):Od(e,t),Pd=(e,t)=>new ai((async function*(){for await(const n of e)!0===await t(n)&&(yield n)})),Od=(e,t)=>new ai((async function*(){let n=0;for await(const s of e)!0===await t(s,n++)&&(yield s)})),Ud=(e,t,n)=>n?xd(e,t,n):Md(e,t),Md=(e,t)=>new ai((async function*(){const n=e[Symbol.asyncIterator](),s=t[Symbol.asyncIterator]();for(;;){const[e,t]=await Promise.all([n.next(),s.next()]);if(e.done||t.done)break;yield[e.value,t.value]}})),xd=(e,t,n)=>new ai((async function*(){const s=e[Symbol.asyncIterator](),r=t[Symbol.asyncIterator]();for(;;){const[e,t]=await Promise.all([s.next(),r.next()]);if(e.done||t.done)break;yield n(e.value,t.value)}})),Fd=(e,t,n)=>new ai((async function*(){const s=e[Symbol.asyncIterator](),r=t[Symbol.asyncIterator]();for(;;){const e=await Promise.all([s.next(),r.next()]),t=e[0],o=e[1];if(t.done||o.done)break;yield n(t.value,o.value)}})),Ld=(e,t,n,s)=>{if(s){if(!n)throw new ReferenceError("TAccumulate function is undefined");return $d(e,t,n,s)}return n?Wd(e,t,n):Bd(e,t)},Bd=async(e,t)=>{let n;for await(const s of e)n=n?t(n,s):s;if(void 0===n)throw new oi(ri.NoElements);return n},Wd=async(e,t,n)=>{let s=t;for await(const t of e)s=n(s,t);return s},$d=async(e,t,n,s)=>{let r=t;for await(const t of e)r=n(r,t);return s(r)},qd=(e,t)=>{const n=e.dataFunc;switch(n.type){case 0:return{generator:()=>n.generator().then((e=>{const n=new Array(e.length);for(let s=0;s<e.length;s++)n[s]=t(e[s]);return n})),type:0};case 1:return{generator:()=>{const e=n.generator(),s=new Array(e.length);for(let n=0;n<e.length;n++)s[n]=e[n].then(t);return s},type:1};case 2:return{generator:async()=>{const e=await n.generator(),s=new Array(e.length);for(let n=0;n<e.length;n++)s[n]=e[n].then(t);return s},type:2}}},Vd=(e,t)=>{const n=qd(e,(e=>{if(!t(e))throw new Error(String(!1));return!0}));switch(n.type){case 0:return n.generator().then((()=>!0),(()=>!1));case 1:return Promise.all(n.generator()).then((()=>!0),(()=>!1));case 2:return n.generator().then(Promise.all.bind(Promise)).then((()=>!0),(()=>!1))}},Hd=(e,t)=>{const n=e.dataFunc;switch(n.type){case 0:return{generator:async()=>{const e=await n.generator(),s=new Array(e.length);for(let n=0;n<e.length;n++)s[n]=t(e[n]);return s},type:2};case 1:return{generator:()=>n.generator().map((async e=>{const n=await e;return await t(n)})),type:1};case 2:return{generator:async()=>(await n.generator()).map((e=>e.then(t))),type:2}}},jd=(e,t)=>{const n=Hd(e,(async e=>{if(!1===await t(e))throw new Error(String(!1));return!0}));switch(n.type){case 1:return Promise.all(n.generator()).then((()=>!0),(()=>!1));case 2:return n.generator().then(Promise.all.bind(Promise)).then((()=>!0),(()=>!1))}},Kd=(e,t)=>{const n=e.dataFunc;switch(n.type){case 1:return new ci({generator:()=>{const e=n.generator();return e.push(Promise.resolve(t)),e},type:n.type});case 2:return new ci({generator:async()=>{const e=await n.generator();return e.push(Promise.resolve(t)),e},type:n.type});case 0:return new ci({generator:async()=>{const e=await n.generator();return e.push(t),e},type:n.type})}},zd=(e,t)=>t?Yd(e,t):Jd(e),Jd=async e=>{const t=e.dataFunc;let n;switch(t.type){case 1:return n=t.generator(),0!==n.length;case 0:case 2:return n=await t.generator(),0!==n.length}},Yd=async(e,t)=>{const n=qd(e,t);let s;switch(n.type){case 0:return s=await n.generator(),s.includes(!0);case 1:return s=await Promise.all(n.generator()),s.includes(!0);case 2:return s=await Promise.all(await n.generator()),s.includes(!0)}},Xd=async(e,t)=>{const n=Hd(e,t);let s;switch(n.type){case 1:return s=n.generator(),0!==s.length&&new Promise(((e,t)=>{let n=0;for(const r of s)r.then((t=>{n++,t?e(!0):n===s.length&&e(!1)}),t)}));case 2:return s=await n.generator(),0===Promise.length?!1:(await Promise.all(s)).includes(!0)}},Qd=e=>_i((async function*(){for await(const t of e)yield t})),Zd=async e=>{switch(e.type){case 0:return await e.generator();case 1:return await Promise.all(e.generator());case 2:const t=await e.generator();return await Promise.all(t)}},eh=async(e,t)=>{let n;n=t?qd(e,t):e.dataFunc;const s=await Zd(n);if(0===s.length)throw new oi(ri.NoElements);let r=0;for(const e of s)r+=e;return r/s.length},th=async(e,t)=>{const n=Hd(e,t),s=await Zd(n);if(0===s.length)throw new oi(ri.NoElements);let r=0;for(const e of s)r+=e;return r/s.length},nh=(e,t)=>{if(t<1)throw new si("size");let n;switch(e.dataFunc.type){case 1:const s=e.dataFunc.generator;n={type:1,generator:()=>{const e=[];let n=[];for(const r of s())n.push(r),n.length===t&&(e.push(Promise.all(n)),n=[]);return n.length&&e.push(Promise.all(n)),e}};break;case 2:const r=e.dataFunc.generator;n={type:2,generator:async()=>{const e=[];let n=[];for(const s of await r())n.push(s),n.length===t&&(e.push(Promise.all(n)),n=[]);return n.length&&e.push(Promise.all(n)),e}};break;case 0:const o=e.dataFunc.generator;n={type:0,generator:async()=>{const e=[];let n=[];for(const s of await o())n.push(s),n.length===t&&(e.push(n),n=[]);return n.length&&e.push(n),e}}}return new ci(n)},sh=(e,t)=>new ci({generator:async()=>{const[n,s]=await Promise.all([e.toArray(),t.toArray()]);return[...n,...s]},type:0}),rh=async(e,t,n=ii)=>{let s;switch(s=qd(e,n?e=>n(t,e):e=>e===t),s.type){case 0:return(await s.generator()).some((e=>e));case 1:return(await Promise.all(s.generator())).some((e=>e));case 2:return(await Promise.all(await s.generator())).some((e=>e))}},oh=async(e,t,n)=>{const s=Hd(e,(e=>n(t,e)));switch(s.type){case 1:return(await Promise.all(s.generator())).some((e=>e));case 2:return(await Promise.all(await s.generator())).some((e=>e))}},ih=(e,t)=>t?ch(e,t):ah(e),ah=async e=>{const t=e.dataFunc;switch(t.type){case 0:case 2:return(await e.toArray()).length;case 1:return t.generator().length}},ch=async(e,t)=>{const n=await e.toArray();let s=0;for(let e=0;e<n.length;e++)!0===t(n[e])&&s++;return s},uh=async(e,t)=>{const n=Hd(e,t);let s;switch(n.type){case 1:s=Promise.all(n.generator());break;case 2:s=Promise.all(await n.generator())}let r=0;for(const e of await s)e&&r++;return r},lh=(e,t)=>{const n=e.dataFunc,s=t instanceof Promise;let r;switch(n.type){case 0:r={generator:()=>n.generator().then((e=>e.length?e:s?t.then((e=>[e])):[t])),type:n.type};break;case 1:r={generator:()=>{const e=n.generator();return e.length?e:s?[t]:[Promise.resolve(t)]},type:n.type};break;case 2:r={generator:async()=>{const e=await n.generator();return e.length?e:s?[t]:[Promise.resolve(t)]},type:n.type}}return new ci(r)},dh=(e,t=ii)=>new ci({generator:async()=>{const n=[];for(const s of await e.toArray())n.find((e=>t(e,s)))||n.push(s);return n},type:0}),hh=(e,t)=>new ci({generator:async()=>{const n=[];e:for(const s of await e.toArray()){for(const e of n)if(await t(e,s))continue e;n.push(s)}return n},type:0}),ph=(e,t)=>new ci(qd(e,(e=>(t(e),e)))),gh=(e,t)=>{const n=Hd(e,(async e=>(await t(e),e)));return new ci(n)},fh=async(e,t)=>{if(t<0)throw new si("index");const n=e.dataFunc;switch(n.type){case 0:{const e=await n.generator();if(t>=e.length)throw new si("index");return e[t]}case 1:{const e=n.generator();if(t>=e.length)throw new si("index");return await e[t]}case 2:{const e=await n.generator();if(t>=e.length)throw new si("index");return await e[t]}}},vh=async(e,t)=>{const n=e.dataFunc;switch(n.type){case 0:{const e=await n.generator();return t>=e.length?null:e[t]}case 1:{const e=n.generator();return t>=e.length?null:await e[t]}case 2:{const e=await n.generator();return t>=e.length?null:await e[t]}}},mh=(e,t,n=ii)=>new ci({generator:async()=>{const[s,r]=await Promise.all([e.toArray(),t.toArray()]),o=[];for(const e of s){let t=!1;for(let s=0;s<r.length;s++){const o=r[s];if(!0===n(e,o)){t=!0;break}}!1===t&&o.push(e)}return o},type:0}),yh=(e,t,n)=>new ci({generator:async()=>{const[s,r]=await Promise.all([e.toArray(),t.toArray()]),o=[];for(const e of s){let t=!1;for(let s=0;s<r.length;s++){const o=r[s];if(!0===await n(e,o)){t=!0;break}}!1===t&&o.push(e)}return o},type:0}),wh=e=>Zd(e.dataFunc),Sh=(e,t)=>t?_h(e,t):Ah(e),Ah=async e=>{const t=e.dataFunc;switch(t.type){case 0:{const e=await t.generator();if(0===e.length)throw new oi(ri.NoElements);return e[0]}case 1:{const e=t.generator();if(0===e.length)throw new oi(ri.NoElements);return await e[0]}case 2:{const e=await t.generator();if(0===e.length)throw new oi(ri.NoElements);return await e[0]}}},_h=async(e,t)=>{const n=await wh(e);for(const e of n)if(!0===t(e))return e;throw new oi(ri.NoMatch)},Ch=async(e,t)=>{const n=await wh(e);for(const e of n)if(!0===await t(e))return e;throw new oi(ri.NoMatch)},Th=(e,t)=>t?kh(e,t):Dh(e),Dh=async e=>{const t=e.dataFunc;switch(t.type){case 0:{const e=await t.generator();return 0===e.length?null:e[0]}case 1:{const e=t.generator();return 0===e.length?null:await e[0]}case 2:{const e=await t.generator();return 0===e.length?null:await e[0]}}},kh=async(e,t)=>{const n=await wh(e);for(const e of n)if(!0===t(e))return e;return null},Gh=async(e,t)=>{const n=await wh(e);for(const e of n)if(!0===await t(e))return e;return null},bh=(e,t,n)=>n?Eh(e,t,n):Nh(e,t),Nh=(e,t)=>new ci({generator:async()=>{const n={};for(const s of await e.toArray()){const e=t(s),r=n[e];r?r.push(s):n[e]=new Zi(e,s)}const s=new Array;for(const e in n)s.push(n[e]);return s},type:0}),Eh=(e,t,n)=>new ci({generator:async()=>{const s=new Array;for(const r of await e.toArray()){const e=t(r);let o=!1;for(let t=0;t<s.length;t++){const i=s[t];if(n(i.key,e)){i.push(r),o=!0;break}}!1===o&&s.push(new Zi(e,r))}const r=new Array;for(const e of s)r.push(e);return r},type:0}),Ih=(e,t,n)=>n?Rh(e,t,n):Ph(e,t),Rh=(e,t,n)=>new ci({generator:async()=>{const s=Hd(e,(async e=>[await t(e),e]));let r;switch(s.type){case 1:r=await Promise.all(s.generator());break;case 2:r=await Promise.all(await s.generator())}const o=new Array;for(const[e,t]of r){let s=!1;for(let r=0;r<o.length;r++){const i=o[r];if(!0===await n(i.key,e)){i.push(t),s=!0;break}}!1===s&&o.push(new Zi(e,t))}const i=new Array;for(const e of o)i.push(e);return i},type:0}),Ph=(e,t)=>new ci({generator:async()=>{const n=Hd(e,(async e=>[await t(e),e]));let s;switch(n.type){case 1:s=await Promise.all(n.generator());break;case 2:s=await Promise.all(await n.generator())}const r={};for(const[e,t]of s){const n=r[e];n?n.push(t):r[e]=new Zi(e,t)}const o=new Array;for(const e in r)o.push(r[e]);return o},type:0}),Oh=(e,t,n,s)=>s?Uh(e,t,n,s):Mh(e,t,n),Uh=(e,t,n,s)=>new ci({generator:async()=>{const r=new Array;for await(const o of e){const e=t(o);let i=!1;for(let t=0;t<r.length;t++){const a=r[t];if(s(a.key,e)){a.push(n(o)),i=!0;break}}if(!1===i){const t=n(o);r.push(new Zi(e,t))}}const o=new Array;for(const e of r)o.push(e);return o},type:0}),Mh=(e,t,n)=>new ci({generator:async()=>{const s={};for(const r of await e.toArray()){const e=t(r),o=s[e],i=n(r);o?o.push(i):s[e]=new Zi(e,i)}const r=new Array;for(const e in s)r.push(s[e]);return r},type:0}),xh=(e,t,n,s,r,o)=>{const i=o?Fh(e,t,n,s,r,o):Lh(e,t,n,s,r);return new ci({generator:i,type:0})},Fh=(e,t,n,s,r,o)=>async()=>{const i=[];for await(const e of t){const t=s(e),n=i.find((e=>o(e.key,t)));n?n.values.push(e):i.push({key:t,values:[e]})}return(await e.toArray()).map((e=>{const t=n(e),s=i.find((e=>o(e.key,t)))??{key:t,values:[]};return r(e,s.values)}))},Lh=(e,t,n,s,r)=>async()=>{const o=new Map;for await(const e of t){const t=s(e),n=o.get(t);n?n.push(e):o.set(t,[e])}return(await e.toArray()).map((e=>{const t=n(e),s=o.get(t)??[];return r(e,s)}))},Bh=(e,t,n,s,r,o)=>{const i=o?Wh(e,t,n,s,r,o):$h(e,t,n,s,r);return new ci({generator:i,type:0})},Wh=(e,t,n,s,r,o)=>async()=>{const i=[];for await(const e of t){const t=await s(e),n=i.find((e=>o(e.key,t)));n?n.values.push(e):i.push({key:t,values:[e]})}const a=(await e.toArray()).map((async e=>{const t=await n(e),s=i.find((e=>o(e.key,t)))??{key:t,values:[]};return r(e,s.values)}));return await Promise.all(a)},$h=(e,t,n,s,r)=>async()=>{const o=new Map;for await(const e of t){const t=await s(e),n=o.get(t);n?n.push(e):o.set(t,[e])}const i=(await e.toArray()).map((async e=>{const t=await n(e),s=o.get(t)??[];return r(e,s)}));return await Promise.all(i)},qh=(e,t,n=ii)=>new ci({generator:async()=>{const s=await e.distinct(n).toArray();if(0===s.length)return[];const r=await t.toArray(),o=new Array;for(let e=0;e<s.length;e++){const t=s[e];for(let e=0;e<r.length;e++){const s=r[e];if(!0===n(t,s)){o.push(t);break}}}return o},type:0}),Vh=(e,t,n)=>new ci({generator:async()=>{const s=await e.distinctAsync(n).toArray();if(0===s.length)return[];const r=await t.toArray(),o=new Array;for(let e=0;e<s.length;e++){const t=s[e];for(let e=0;e<r.length;e++){const s=r[e];if(!0===await n(t,s)){o.push(t);break}}}return o},type:0}),Hh=(e,t,n,s,r,o=ii)=>new ci({generator:async()=>{const[i,a]=await Promise.all([t.toArray(),e.toArray()]),c=new Array;for(const e of a){const t=n(e);for(const n of i){const i=s(n);!0===o(t,i)&&c.push(r(e,n))}}return c},type:0}),jh=(e,t)=>t?zh(e,t):Kh(e),Kh=async e=>{const t=e.dataFunc;switch(t.type){case 0:{const e=await t.generator();if(0===e.length)throw new oi(ri.NoElements);return e[e.length-1]}case 1:{const e=t.generator();if(0===e.length)throw new oi(ri.NoElements);return await e[e.length-1]}case 2:{const e=await t.generator();if(0===e.length)throw new oi(ri.NoElements);return await e[e.length-1]}}},zh=async(e,t)=>{const n=e.dataFunc;switch(n.type){case 0:{const e=await n.generator();for(let n=e.length-1;n>=0;n--){const s=e[n];if(t(s))return s}break}case 1:{const e=n.generator();for(let n=e.length-1;n>=0;n--){const s=await e[n];if(t(s))return s}break}case 2:{const e=await n.generator();for(let n=e.length-1;n>=0;n--){const s=await e[n];if(t(s))return s}break}}throw new oi(ri.NoMatch)},Jh=async(e,t)=>{const n=e.dataFunc;switch(n.type){case 0:{const e=await n.generator();for(let n=e.length-1;n>=0;n--){const s=e[n];if(!0===await t(s))return s}break}case 1:{const e=n.generator();for(let n=e.length-1;n>=0;n--){const s=await e[n];if(!0===await t(s))return s}break}case 2:{const e=await n.generator();for(let n=e.length-1;n>=0;n--){const s=await e[n];if(!0===await t(s))return s}break}}throw new oi(ri.NoMatch)},Yh=(e,t)=>t?Qh(e,t):Xh(e),Xh=async e=>{const t=e.dataFunc;switch(t.type){case 0:{const e=await t.generator();return 0===e.length?null:e[e.length-1]}case 1:{const e=t.generator();return 0===e.length?null:await e[e.length-1]}case 2:{const e=await t.generator();return 0===e.length?null:await e[e.length-1]}}},Qh=async(e,t)=>{const n=e.dataFunc;switch(n.type){case 0:{const e=await n.generator();for(let n=e.length-1;n>=0;n--){const s=e[n];if(t(s))return s}break}case 1:{const e=n.generator();for(let n=e.length-1;n>=0;n--){const s=await e[n];if(t(s))return s}break}case 2:{const e=await n.generator();for(let n=e.length-1;n>=0;n--){const s=await e[n];if(t(s))return s}break}}return null},Zh=async(e,t)=>{const n=e.dataFunc;switch(n.type){case 0:{const e=await n.generator();for(let n=e.length-1;n>=0;n--){const s=e[n];if(!0===await t(s))return s}break}case 1:{const e=n.generator();for(let n=e.length-1;n>=0;n--){const s=await e[n];if(!0===await t(s))return s}break}case 2:{const e=await n.generator();for(let n=e.length-1;n>=0;n--){const s=await e[n];if(!0===await t(s))return s}break}}return null},ep=async(e,t)=>{let n;n=t?qd(e,t):e.dataFunc;const s=await Zd(n);if(0===s.length)throw new oi(ri.NoElements);return Math.max.apply(null,s)},tp=async(e,t)=>{const n=Hd(e,t),s=await Zd(n);if(0===s.length)throw new oi(ri.NoElements);return Math.max.apply(null,s)},np=async(e,t)=>{let n;n=t?qd(e,t):e.dataFunc;const s=await Zd(n);if(0===s.length)throw new oi(ri.NoElements);return Math.min.apply(null,s)},sp=async(e,t)=>{const n=Hd(e,t),s=await Zd(n);if(0===s.length)throw new oi(ri.NoElements);return Math.min.apply(null,s)},rp=(e,t)=>{const n="string"==typeof t?e=>[typeof e===t,e]:e=>[e instanceof t,e];return new ci({generator:async()=>{const t=qd(e,n),s=await Zd(t),r=[];for(const[e,t]of s)e&&r.push(t);return r},type:0})};async function*op(e,t,n,s){const r=await(async(e,t)=>{const n=new Map;for(const s of e){const e=await t(s),r=n.get(e);r?r.push(s):n.set(e,[s])}return n})(e,t),o=[...r.keys()].sort(s||void 0);if(n)for(let e=0;e<o.length;e++)yield r.get(o[e]);else for(let e=o.length-1;e>=0;e--)yield r.get(o[e])}async function*ip(e,t,n,s){const r=((e,t)=>{const n=new Map;for(const s of e){const e=t(s),r=n.get(e);r?r.push(s):n.set(e,[s])}return n})(e,t),o=[...r.keys()].sort(s||void 0);if(n)for(let e=0;e<o.length;e++)yield r.get(o[e]);else for(let e=o.length-1;e>=0;e--)yield r.get(o[e])}class ap extends ci{orderedPairs;constructor(e){super({generator:async()=>{const t=e(),n=[];for await(const e of t)n.push(...e);return n},type:0}),this.orderedPairs=e}static generateAsync(e,t,n,s){let r;return r=e instanceof ap?async function*(){for await(const r of e.orderedPairs())yield*op(r,t,n,s)}:()=>async function*(e,t,n,s){const r=await(async(e,t)=>{const n=new Map;for await(const s of e){const e=await t(s),r=n.get(e);r?r.push(s):n.set(e,[s])}return n})(e,t),o=[...r.keys()].sort(s||void 0);if(n)for(let e=0;e<o.length;e++)yield r.get(o[e]);else for(let e=o.length-1;e>=0;e--)yield r.get(o[e])}(e,t,n,s),new ap(r)}static generate(e,t,n,s){let r;return r=e instanceof ap?async function*(){for await(const r of e.orderedPairs())yield*ip(r,t,n,s)}:()=>async function*(e,t,n,s){const r=await(async(e,t)=>{const n=new Map;for await(const s of e){const e=t(s),r=n.get(e);r?r.push(s):n.set(e,[s])}return n})(e,t),o=[...r.keys()].sort(s||void 0);if(n)for(let e=0;e<o.length;e++)yield r.get(o[e]);else for(let e=o.length-1;e>=0;e--)yield r.get(o[e])}(e,t,n,s),new ap(r)}thenBy(e,t){return ap.generate(this,e,!0,t)}thenByAsync(e,t){return ap.generateAsync(this,e,!0,t)}thenByDescending(e,t){return ap.generate(this,e,!1,t)}thenByDescendingAsync(e,t){return ap.generateAsync(this,e,!1,t)}}const cp=(e,t)=>ap.generate(e,(e=>e),!0,t),up=(e,t,n)=>ap.generate(e,t,!0,n),lp=(e,t,n)=>ap.generateAsync(e,t,!0,n),dp=(e,t,n)=>ap.generate(e,t,!1,n),hp=(e,t,n)=>ap.generateAsync(e,t,!1,n),pp=(e,t)=>ap.generate(e,(e=>e),!1,t),gp=async(e,t)=>{const n=qd(e,(e=>[t(e),e])),s=await Zd(n),r=[],o=[];for(const[e,t]of s)e?o.push(t):r.push(t);return[o,r]},fp=async(e,t)=>{const n=Hd(e,(async e=>[await t(e),e])),s=await Zd(n),r=[],o=[];for(const[e,t]of s)e?o.push(t):r.push(t);return[o,r]},vp=(e,t)=>{const n=e.dataFunc;switch(n.type){case 1:return new ci({generator:()=>{const e=n.generator();return e.unshift(Promise.resolve(t)),e},type:n.type});case 2:return new ci({generator:async()=>{const e=await n.generator();return e.unshift(Promise.resolve(t)),e},type:n.type});case 0:return new ci({generator:async()=>{const e=await n.generator();return e.unshift(t),e},type:n.type})}},mp=e=>{const t=e.dataFunc;switch(t.type){case 1:return new ci({generator:()=>t.generator().reverse(),type:t.type});case 2:case 0:return new ci({generator:async()=>(await t.generator()).reverse(),type:t.type})}},yp=(e,t)=>{const n=e.dataFunc;switch(n.type){case 0:return{generator:()=>n.generator().then((e=>{const n=new Array(e.length);for(let s=0;s<e.length;s++)n[s]=t(e[s],s);return n})),type:0};case 1:return{generator:()=>{const e=n.generator(),s=new Array(e.length);for(let n=0;n<e.length;n++)s[n]=e[n].then((e=>t(e,n)));return s},type:1};case 2:return{generator:async()=>{const e=await n.generator(),s=new Array(e.length);for(let n=0;n<e.length;n++)s[n]=e[n].then((e=>t(e,n)));return s},type:2}}},wp=(e,t)=>"function"==typeof t?1===t.length?new ci(qd(e,t)):new ci(yp(e,t)):new ci(qd(e,(e=>e[t]))),Sp=(e,t)=>{const n=e.dataFunc;switch(n.type){case 0:return{generator:async()=>{const e=await n.generator(),s=new Array(e.length);for(let n=0;n<e.length;n++)s[n]=t(e[n],n);return s},type:2};case 1:return{generator:()=>n.generator().map(((e,n)=>e.then((e=>t(e,n))))),type:1};case 2:return{generator:async()=>(await n.generator()).map(((e,n)=>e.then((e=>t(e,n))))),type:2}}},Ap=(e,t)=>{let n;return n="function"==typeof t?1===t.length?Hd(e,t):Sp(e,t):Hd(e,(e=>e[t])),new ci(n)},_p=(e,t)=>new ci({generator:async()=>{let n;n="function"==typeof t?1===t.length?qd(e,t):yp(e,t):qd(e,(e=>e[t]));const s=[];switch(n.type){case 0:for(const e of await n.generator())for(const t of e)s.push(t);break;case 1:for(const e of n.generator())for(const t of await e)s.push(t);break;case 2:for(const e of await n.generator())for(const t of await e)s.push(t)}return s},type:0}),Cp=(e,t)=>new ci({generator:async()=>{let n;n=1===t.length?Hd(e,t):Sp(e,t);const s=[];switch(n.type){case 1:for(const e of n.generator())for(const t of await e)s.push(t);break;case 2:for(const e of await n.generator())for(const t of await e)s.push(t)}return s},type:0}),Tp=async(e,t,n=ii)=>{const s=await e.toArray(),r=await t.toArray();if(s.length!==r.length)return!1;for(let e=0;e<s.length;e++)if(!1===n(s[e],r[e]))return!1;return!0},Dp=async(e,t,n)=>{const s=await e.toArray(),r=await t.toArray();if(s.length!==r.length)return!1;for(let e=0;e<s.length;e++){const t=s[e],o=r[e];if(!1===await n(t,o))return!1}return!0},kp=(e,t)=>t?bp(e,t):Gp(e),Gp=async e=>{const t=e.dataFunc;switch(t.type){case 0:{const e=await t.generator();if(e.length>1)throw new oi(ri.MoreThanOneElement);if(0===e.length)throw new oi(ri.NoElements);return e[0]}case 1:{const e=t.generator();if(e.length>1)throw new oi(ri.MoreThanOneElement);if(0===e.length)throw new oi(ri.NoElements);return e[0]}case 2:{const e=await t.generator();if(e.length>1)throw new oi(ri.MoreThanOneElement);if(0===e.length)throw new oi(ri.NoElements);return await e[0]}}},bp=async(e,t)=>{const n=await wh(e);let s=!1,r=null;for(const e of n)if(t(e)){if(!0===s)throw new oi(ri.MoreThanOneMatchingElement);s=!0,r=e}if(!1===s)throw new oi(ri.NoMatch);return r},Np=async(e,t)=>{const n=await wh(e);let s=!1,r=null;for(const e of n)if(!0===await t(e)){if(!0===s)throw new oi(ri.MoreThanOneMatchingElement);s=!0,r=e}if(!1===s)throw new oi(ri.NoMatch);return r},Ep=(e,t)=>t?Rp(e,t):Ip(e),Ip=async e=>{const t=e.dataFunc;switch(t.type){case 0:{const e=await t.generator();if(e.length>1)throw new oi(ri.MoreThanOneElement);return 0===e.length?null:e[0]}case 1:{const e=t.generator();if(e.length>1)throw new oi(ri.MoreThanOneElement);return 0===e.length?null:e[0]}case 2:{const e=await t.generator();if(e.length>1)throw new oi(ri.MoreThanOneElement);return 0===e.length?null:await e[0]}}},Rp=async(e,t)=>{const n=await wh(e);let s=!1,r=null;for(const e of n)if(t(e)){if(!0===s)throw new oi(ri.MoreThanOneElement);s=!0,r=e}return r},Pp=async(e,t)=>{const n=await wh(e);let s=!1,r=null;for(const e of n)if(!0===await t(e)){if(!0===s)throw new oi(ri.MoreThanOneElement);s=!0,r=e}return r},Op=(e,t)=>{const n=e.dataFunc;switch(n.type){case 0:return new ci({generator:async()=>(await n.generator()).slice(t),type:0});case 1:return new ci({generator:()=>n.generator().slice(t),type:1});case 2:return new ci({generator:async()=>(await n.generator()).slice(t),type:2})}},Up=(e,t)=>new ci({generator:async()=>{const n=await e.toArray();let s=0;for(;s<n.length;s++){const e=n[s];if(!1===t(e,s))break}const r=[];for(;s<n.length;s++)r.push(n[s]);return r},type:0}),Mp=(e,t)=>new ci({generator:async()=>{const n=await e.toArray();let s=0;for(;s<n.length;s++){const e=n[s];if(!1===await t(e,s))break}const r=[];for(;s<n.length;s++)r.push(n[s]);return r},type:0}),xp=(e,t)=>t?Lp(e,t):Fp(e),Fp=async e=>{let t=0;for(const n of await e.toArray())t+=n;return t},Lp=async(e,t)=>{let n=0;for(const s of await e.toArray())n+=t(s);return n},Bp=async(e,t)=>{const n=Hd(e,t),s=await Zd(n);let r=0;for(const e of s)r+=e;return r},Wp=(e,t)=>{const n=t>0?t:0,s=e.dataFunc;switch(s.type){case 1:return new ci({generator:()=>s.generator().splice(0,n),type:1});case 2:return new ci({generator:()=>s.generator().then((e=>e.splice(0,n))),type:2});default:return new ci({generator:()=>s.generator().then((e=>e.splice(0,n))),type:0})}},$p=(e,t)=>new ci({generator:async()=>{const n=await e.toArray(),s=new Array;if(1===t.length)for(const e of n){if(!0!==t(e))break;s.push(e)}else for(let e=0;e<n.length;e++){const r=n[e];if(!0!==t(r,e))break;s.push(r)}return s},type:0}),qp=(e,t)=>new ci({generator:async()=>{const n=await e.toArray(),s=new Array;if(1===t.length){const e=t;for(const t of n){if(!0!==await e(t))break;s.push(t)}}else for(let e=0;e<n.length;e++){const r=n[e];if(!0!==await t(r,e))break;s.push(r)}return s},type:0}),Vp=async(e,t)=>{const n=new Map,s=qd(e,(e=>[t(e),e])),r=await Zd(s);for(const[e,t]of r){const s=n.get(e);void 0===s?n.set(e,[t]):s.push(t)}return n},Hp=async(e,t)=>{const n=new Map,s=Hd(e,(async e=>[await t(e),e])),r=await Zd(s);for(const[e,t]of r){const s=n.get(e);void 0===s?n.set(e,[t]):s.push(t)}return n},jp=async(e,t)=>{const n=e.dataFunc,s=await Zd(n),r={};for(const e of s)r[t(e)]=e;return r},Kp=async(e,t)=>{const n=Hd(e,(async e=>[await t(e),e])),s=await Zd(n),r={};for(const[e,t]of s)r[e]=t;return r},zp=async e=>{const t=e.dataFunc,n=await Zd(t);return new Set(n)},Jp=(e,t,n)=>n?Xp(e,t,n):Yp(e,t),Yp=(e,t)=>new ci({generator:async()=>{const n=new Set,s=t.toArray();for await(const t of e)!1===n.has(t)&&n.add(t);const r=await s;for(const e of r)!1===n.has(e)&&n.add(e);return[...n.keys()]},type:0}),Xp=(e,t,n)=>new ci({generator:async()=>{const s=[],r=await Promise.all([e.toArray(),t.toArray()]);for(const e of r)for(const t of e){let e=!1;for(const r of s)if(!0===n(t,r)){e=!0;break}!1===e&&s.push(t)}return s},type:0}),Qp=(e,t,n)=>new ci({generator:async()=>{const s=[],r=await Promise.all([e.toArray(),t.toArray()]);for(const e of r)for(const t of e){let e=!1;for(const r of s)if(!0===await n(t,r)){e=!0;break}!1===e&&s.push(t)}return s},type:0}),Zp=(e,t)=>new ci({generator:async()=>(await e.toArray()).filter(t),type:0}),eg=(e,t)=>new ci({generator:async()=>{const n=Sp(e,(async(e,n)=>[await t(e,n),e])),s=await Zd(n),r=[];for(const[e,t]of s)e&&r.push(t);return r},type:0}),tg=(e,t,n)=>n?sg(e,t,n):ng(e,t),ng=(e,t)=>new ci({generator:async()=>{const[n,s]=await Promise.all([e.toArray(),t.toArray()]),r=n.length<s.length?n.length:s.length,o=new Array(r);for(let e=0;e<r;e++){const t=n[e],r=s[e];o[e]=[t,r]}return o},type:0}),sg=(e,t,n)=>new ci({generator:async()=>{const[s,r]=await Promise.all([e.toArray(),t.toArray()]),o=s.length<r.length?s.length:r.length,i=new Array(o);for(let e=0;e<o;e++){const t=s[e],o=r[e];i[e]=n(t,o)}return i},type:0}),rg=(e,t,n)=>new ci({generator:async()=>{const[s,r]=await Promise.all([e.toArray(),t.toArray()]),o=s.length<r.length?s.length:r.length,i=new Array(o);for(let e=0;e<o;e++){const t=s[e],o=r[e];i[e]=n(t,o)}return Promise.all(i)},type:0}),og=e=>{const t=li.prototype,n=e.prototype,s=Object.getOwnPropertyNames(t);for(const e of s)n[e]=n[e]??t[e]};nu(ui),(e=>{const t=e.prototype,n=(e,n)=>{const s=function(...t){return e(this,...t)};Object.defineProperty(s,"length",{value:e.length-1}),t[n]=s};n(su,"aggregate"),n(au,"all"),n(cu,"allAsync"),n(uu,"append"),n(lu,"any"),n(pu,"anyAsync"),n(gu,"asParallel"),n(fu,"average"),n(vu,"averageAsync"),n(mu,"chunk"),n(yu,"concatenate"),n(wu,"contains"),n(Su,"containsAsync"),n(Au,"count"),n(Tu,"countAsync"),n(Du,"defaultIfEmpty"),n(ku,"distinct"),n(Gu,"distinctAsync"),n(bu,"each"),n(Nu,"eachAsync"),n(Eu,"elementAt"),n(Iu,"elementAtOrDefault"),n(Ru,"except"),n(Pu,"exceptAsync"),n(Ou,"first"),n(xu,"firstAsync"),n(Fu,"firstOrDefault"),n(Wu,"firstOrDefaultAsync"),n($u,"groupBy"),n(Hu,"groupByAsync"),n(zu,"groupByWithSel"),n(Xu,"groupJoin"),n(el,"groupJoinAsync"),n(sl,"intersect"),n(rl,"intersectAsync"),n(ol,"joinByKey"),n(il,"last"),n(ul,"lastAsync"),n(ll,"lastOrDefault"),n(pl,"lastOrDefaultAsync"),n(gl,"max"),n(ml,"maxAsync"),n(yl,"min"),n(Al,"minAsync"),n(_l,"ofType"),n(Cl,"order"),n(Tl,"orderBy"),n(Dl,"orderByAsync"),n(kl,"orderByDescending"),n(Gl,"orderByDescendingAsync"),n(bl,"orderDescending"),n(Nl,"partition"),n(El,"partitionAsync"),n(Il,"prepend"),n(Rl,"reverse"),n(Pl,"select"),n(xl,"selectAsync"),n(Bl,"selectMany"),n(Vl,"selectManyAsync"),n(Hl,"sequenceEquals"),n(jl,"sequenceEqualsAsync"),n(Kl,"single"),n(Yl,"singleAsync"),n(Xl,"singleOrDefault"),n(ed,"singleOrDefaultAsync"),n(td,"skip"),n(nd,"skipWhile"),n(od,"skipWhileAsync"),n(cd,"sum"),n(dd,"sumAsync"),n(hd,"take"),n(pd,"takeWhile"),n(vd,"takeWhileAsync"),n(wd,"toArray"),n(Sd,"toMap"),n(Ad,"toMapAsync"),n(_d,"toObject"),n(Cd,"toObjectAsync"),n(Td,"toSet"),n(Dd,"union"),n(bd,"unionAsync"),n(Nd,"where"),n(Rd,"whereAsync"),n(Ud,"zip"),n(Fd,"zipAsync")})(ai),(e=>{const t=e.prototype,n=(e,n)=>{const s=function(...t){return e(this,...t)};Object.defineProperty(s,"length",{value:e.length-1}),t[n]=s};n(Ld,"aggregate"),n(Vd,"all"),n(jd,"allAsync"),n(Kd,"append"),n(zd,"any"),n(Xd,"anyAsync"),n(Qd,"asAsync"),n(eh,"average"),n(th,"averageAsync"),n(nh,"chunk"),n(sh,"concatenate"),n(rh,"contains"),n(oh,"containsAsync"),n(ih,"count"),n(uh,"countAsync"),n(lh,"defaultIfEmpty"),n(dh,"distinct"),n(hh,"distinctAsync"),n(ph,"each"),n(gh,"eachAsync"),n(fh,"elementAt"),n(vh,"elementAtOrDefault"),n(mh,"except"),n(yh,"exceptAsync"),n(Sh,"first"),n(Ch,"firstAsync"),n(Th,"firstOrDefault"),n(Gh,"firstOrDefaultAsync"),n(bh,"groupBy"),n(Ih,"groupByAsync"),n(Oh,"groupByWithSel"),n(xh,"groupJoin"),n(Bh,"groupJoinAsync"),n(xh,"groupJoin"),n(Bh,"groupJoinAsync"),n(qh,"intersect"),n(Vh,"intersectAsync"),n(Hh,"joinByKey"),n(jh,"last"),n(Jh,"lastAsync"),n(Yh,"lastOrDefault"),n(Zh,"lastOrDefaultAsync"),n(ep,"max"),n(tp,"maxAsync"),n(np,"min"),n(sp,"minAsync"),n(rp,"ofType"),n(cp,"order"),n(up,"orderBy"),n(lp,"orderByAsync"),n(dp,"orderByDescending"),n(hp,"orderByDescendingAsync"),n(pp,"orderDescending"),n(gp,"partition"),n(fp,"partitionAsync"),n(vp,"prepend"),n(mp,"reverse"),n(wp,"select"),n(Ap,"selectAsync"),n(_p,"selectMany"),n(Cp,"selectManyAsync"),n(Tp,"sequenceEquals"),n(Dp,"sequenceEqualsAsync"),n(kp,"single"),n(Np,"singleAsync"),n(Ep,"singleOrDefault"),n(Pp,"singleOrDefaultAsync"),n(Op,"skip"),n(Up,"skipWhile"),n(Mp,"skipWhileAsync"),n(xp,"sum"),n(Bp,"sumAsync"),n(Wp,"take"),n($p,"takeWhile"),n(qp,"takeWhileAsync"),n(wh,"toArray"),n(Vp,"toMap"),n(Hp,"toMapAsync"),n(jp,"toObject"),n(Kp,"toObjectAsync"),n(zp,"toSet"),n(Jp,"union"),n(Qp,"unionAsync"),n(Zp,"where"),n(eg,"whereAsync"),n(tg,"zip"),n(rg,"zipAsync")})(ci),(()=>{const{prototype:e}=li,t=Object.getOwnPropertyNames(ui.prototype);for(const n of t)e[n]=e[n]??ui.prototype[n];e.all=function(e){return this.every(e)},e.any=function(e){return e?this.some(e):0!==this.length},e.count=function(e){if(e){let t=0;for(let n=0;n<this.length;n++)!0===e(this[n])&&t++;return t}return this.length},e.elementAt=function(e){if(e<0||e>=this.length)throw new si("index");return this[e]},e.elementAtOrDefault=function(e){return this[e]??null},e.first=function(e){if(e){const t=this.find(e);if(void 0===t)throw new oi(ri.NoMatch);return t}if(0===this.length)throw new oi(ri.NoElements);return this[0]},e.firstOrDefault=function(e){if(e){const t=this.find(e);return void 0===t?null:t}return 0===this.length?null:this[0]},e.last=function(e){if(e){for(let t=this.length-1;t>=0;t--){const n=this[t];if(!0===e(n))return n}throw new oi(ri.NoMatch)}if(0===this.length)throw new oi(ri.NoElements);return this[this.length-1]},e.lastOrDefault=function(e){if(e){for(let t=this.length-1;t>=0;t--){const n=this[t];if(!0===e(n))return n}return null}return 0===this.length?null:this[this.length-1]},e.max=function(e){if(0===this.length)throw new oi(ri.NoElements);if(e){let t=Number.NEGATIVE_INFINITY;for(let n=0;n<this.length;n++)t=Math.max(e(this[n]),t);return t}return Math.max.apply(null,this)},e.min=function(e){if(0===this.length)throw new oi(ri.NoElements);if(e){let t=Number.POSITIVE_INFINITY;for(let n=0;n<this.length;n++)t=Math.min(e(this[n]),t);return t}return Math.min.apply(null,this)},e.reverse=function(){return Array.prototype.reverse.apply(this),this}})();var ig,ag;!function(e){e.Success="Success",e.GroupDoesNotExists="GroupDoesNotExists",e.ObjectDoesNotExists="ObjectDoesNotExists",e.FatalError="FatalError",e.FunctionNotSupported="FunctionNotSupported"}(ig||(ig={})),function(e){e.Success="Success",e.NoPermissions="NoPermissions",e.NameToShort="NameToShort",e.NameAlreadyExists="NameAlreadyExists",e.OtherError="OtherError",e.UnknownError="UnknownError"}(ag||(ag={}));class cg{constructor(){this._guid="",this._name="",this._iconName="",this._position=0,this._objectsOrder={},null==cg._devicesService&&(cg._devicesService=Fv.Get(Fo.ServiceName))}GetDevicesChannelsInGroupAsync(){return e=this,t=arguments,r=function*(e=!1){let t=[],n=[];const r=yield cg._devicesService.GetDevicesAsync(e);if(void 0===this._objectsOrder||null===this._objectsOrder||0==Object.entries(this._objectsOrder).length){Fv.Get(s.ServiceName).Error("Old controller API fallback to old groups API.");for(let e of r)for(let t of e.Channels.where((e=>e.ChannelGroups.any((e=>e===this._guid)))))n.push(t);return n}const o=Object.keys(this._objectsOrder).map(Number).sort(((e,t)=>e-t));Object.values(this._objectsOrder).forEach((e=>{const n=r.select((t=>t.Channels.where((t=>t.ChannelId===e))));if(null!==n)for(let e of n)for(let n of e)t.push(n)}));for(let e of o){const s=t.firstOrDefault((t=>t.ChannelId===this._objectsOrder[e]));null!==s&&n.push(s)}return n},new((n=void 0)||(n=Promise))((function(s,o){function i(e){try{c(r.next(e))}catch(e){o(e)}}function a(e){try{c(r.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((r=r.apply(e,t||[])).next())}));var e,t,n,r}get Guid(){return this._guid}set Guid(e){this._guid=e}get Name(){return this._name}set Name(e){this._name=e}get IconName(){return this._iconName}set IconName(e){this._iconName=e}get OrderPosition(){return this._position}set OrderPosition(e){this._position=e}get ObjectsOrder(){return this._objectsOrder}set ObjectsOrder(e){this._objectsOrder=e}ChangeNameAsync(e){return Fv.Get(dg.ServiceName).ChangeGroupNameAsync(this,e)}ChangeIconNameAsync(e){return Fv.Get(dg.ServiceName).ChangeGroupIconNameAsync(this,e)}}var ug,lg=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class dg{constructor(){this._connection=null,this._synchronized=!1,this._synchronizationTaskCompletionSource=null,this._groups=[],this._objectsGroupingSupported=!1,this._connection=Fv.Get(Pt.ServiceName),this._synchronizationTaskCompletionSource=new Promise((e=>{Fv.Get(Ke.ServiceName).OnUserLoggedInEvent().Subscribe((t=>lg(this,void 0,void 0,(function*(){yield this.GetGroupsAsync(!0),e(),this._synchronized=!0}))))}))}SetObjectsInGroupAndOrderAsync(e,t){return lg(this,void 0,void 0,(function*(){var n;let s=[],r=[];for(let e of t)if(this.IsDevice(e)){for(let t of e.Channels)s.push(`${t.ChannelId}`);r.push(`${e.Guid}`)}else{if(!this.IsDeviceChannel(e))throw new Error("Passed object is not a device or device channel!");s.push(`${e.ChannelId}`),r.push(`${e.ChannelId}`)}const o=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new gg(e,r),15e3,!1);switch(Fv.Get(Ge.ServiceName).ClearCache(),Fv.Get(rt.ServiceName).ExitConfigurationModeAsync(),yield this.GetGroupsAsync(!1),null==o?void 0:o.Status){case ce.OK:return new De(ig.Success,"");case ce.NotSupportedMethod:case ce.ResourceDoesNotExists:case ce.ResourceIsNotAvailable:return new De(ig.FunctionNotSupported,"");case ce.WrongData:return"GroupDoesNotExists"===o.Data?new De(ig.GroupDoesNotExists,o.Data):new De(ig.FatalError,o.Data);case ce.Error:case ce.FatalError:default:return new De(ig.FatalError,"")}}))}IsDevice(e){return void 0!==e.Channels}IsDeviceChannel(e){return void 0!==e.GetDevice}LogGroupsOrder(e){const t=Fv.Get(s.ServiceName);e.forEach(((e,n)=>{t.Debug(dg.ServiceName,`Group ${e.Name} order position [on array]: ${n} set position: ${e.OrderPosition}`)}))}LogObjectsInGroupOrder(e,t){const n=Fv.Get(s.ServiceName);n.Debug(dg.ServiceName,`Group ${e.Name} objects order:`),t.forEach(((e,t)=>{n.Debug(dg.ServiceName,`Channel ${e.Name} order position [on array]: ${t} channelId: ${e.ChannelId}`)}));for(const[t,s]of Object.entries(e.ObjectsOrder))n.Debug(`new order [GROUP ${e.Name}] Order: [${t}] = ${s}`)}ChangeGroupsOrderAsync(e){return lg(this,void 0,void 0,(function*(){var t;const n=e.select((e=>e.Guid)).toArray(),r=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new pg(n),15e3,!1);return Fv.Get(rt.ServiceName).ExitConfigurationModeAsync(),(null==r?void 0:r.Status)===ce.OK?(Fv.Get(Ge.ServiceName).ClearCache(),yield this.GetGroupsAsync(!1),ce.OK):(Fv.Get(s.ServiceName).Error(dg.ServiceName,`Failed to change groups order, controller responded with error ${null==r?void 0:r.Status} data: ${null==r?void 0:r.Data}`),this.LogGroupsOrder(e),null==r?void 0:r.Status)}))}ChangeObjectsPositionsInGroupAsync(e,t){return lg(this,void 0,void 0,(function*(){var n;const r=t.select((e=>e.ChannelId)).toArray(),o=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new yg(e.Guid,r),15e3,!1);return Fv.Get(rt.ServiceName).ExitConfigurationModeAsync(),(null==o?void 0:o.Status)===ce.OK?(Fv.Get(Ge.ServiceName).ClearCache(),yield this.GetGroupsAsync(!1),yield Fv.Get(Fo.ServiceName).GetDevicesAsync(),ce.OK):(Fv.Get(s.ServiceName).Error(dg.ServiceName,`Failed to change objects positions in group, controller responded with error ${null==o?void 0:o.Status} data: ${null==o?void 0:o.Data}`),this.LogObjectsInGroupOrder(e,t),null==o?void 0:o.Status)}))}IsGroupsAndObjectsOrderingAvailable(){return this._objectsGroupingSupported}MoveGroupPositionAsync(e,t){return lg(this,void 0,void 0,(function*(){var n;const r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new hg(e.Guid,t),15e3,!1);return Fv.Get(rt.ServiceName).ExitConfigurationModeAsync(),(null==r?void 0:r.Status)===ce.OK?(Fv.Get(Ge.ServiceName).ClearCache(),yield this.GetGroupsAsync(!1),ce.OK):(Fv.Get(s.ServiceName).Error(dg.ServiceName,`Failed to move group position, controller responded with error ${null==r?void 0:r.Status} data: ${null==r?void 0:r.Data}`),null==r?void 0:r.Status)}))}MoveObjectInGroupPositionAsync(e,t,n){return lg(this,void 0,void 0,(function*(){var r;const o=`${t.GetDevice().Guid}_${t.Number}`,i=yield null===(r=this._connection)||void 0===r?void 0:r.SendAndWaitForResponseAsync(new mg(e.Guid,o,n),15e3,!1);return Fv.Get(rt.ServiceName).ExitConfigurationModeAsync(),(null==i?void 0:i.Status)===ce.OK?(Fv.Get(Ge.ServiceName).ClearCache(),yield this.GetGroupsAsync(!1),yield Fv.Get(Fo.ServiceName).GetDevicesAsync(),ce.OK):(Fv.Get(s.ServiceName).Error(dg.ServiceName,`Failed to move object in group position, controller responded with error ${null==i?void 0:i.Status} data: ${null==i?void 0:i.Data}`),null==i?void 0:i.Status)}))}AddDeviceChannelToGroupByGuidAsync(e,t){return lg(this,void 0,void 0,(function*(){var n,r;const o=new Tg;if(o.Data.Channel=e.Number,null==e.GetDevice())throw new Error("Device is not set on this channel!");o.Data.DeviceGuid=null===(n=e.GetDevice())||void 0===n?void 0:n.Guid,o.Data.GroupGuid=t;const i=yield null===(r=this._connection)||void 0===r?void 0:r.SendAndWaitForResponseAsync(o,15e3,!1);return Fv.Get(rt.ServiceName).ExitConfigurationModeAsync(),null!=i&&null!=i.Status?(i.Status==ce.OK?e.ChannelGroups.push(t):Fv.Get(s.ServiceName).Error(dg.ServiceName,`Failed to add device channel ${e.Name} to group ${t}, controller responded with error ${i.Status} data: ${i.Data}`),Fv.Get(Ge.ServiceName).ClearCache(),yield this.GetGroupsAsync(!1),yield Fv.Get(Fo.ServiceName).GetDevicesAsync(),i.Status):(yield this.GetGroupsAsync(),ce.Error)}))}RemoveDeviceChannelFromGroupByGuidAsync(e,t){return lg(this,void 0,void 0,(function*(){var n,r;const o=new Dg;if(null==e.GetDevice())throw new Error("Device is not set on this channel!");o.Data.DeviceGuid=null===(n=e.GetDevice())||void 0===n?void 0:n.Guid,o.Data.Channel=e.Number,o.Data.GroupGuid=t;const i=yield null===(r=this._connection)||void 0===r?void 0:r.SendAndWaitForResponseAsync(o,15e3,!1);return Fv.Get(rt.ServiceName).ExitConfigurationModeAsync(),null!=i&&null!=i.Status?(i.Status==ce.OK?e.ChannelGroups=e.ChannelGroups.where((e=>e!=t)).toArray():Fv.Get(s.ServiceName).Error(dg.ServiceName,`Failed to remove device channel ${e.Name} from group ${t}, controller responded with error ${i.Status} data: ${i.Data}`),Fv.Get(Ge.ServiceName).ClearCache(),yield this.GetGroupsAsync(!1),yield Fv.Get(Fo.ServiceName).GetDevicesAsync(),i.Status):(yield this.GetGroupsAsync(),ce.Error)}))}UpsertGroupWithDevicesChannelsAsync(e,t){return lg(this,void 0,void 0,(function*(){if(this._groups.all((t=>t.Guid!=e.Guid))){let t=yield this.AddNewGroupWithIconAsync(e.Name,e.IconName);if(!(t instanceof cg))return t instanceof De?t:new De(ag.UnknownError,"");e=t}for(let n of t.where((t=>t.ChannelGroups.all((t=>t!==e.Guid))))){let t=yield this.AddDeviceChannelToGroupAsync(n,e);if(Fv.Get(Ge.ServiceName).ClearCache(),yield this.GetGroupsAsync(!1),yield Fv.Get(Fo.ServiceName).GetDevicesAsync(),t!==ce.OK)return Fv.Get(s.ServiceName).Error(dg.ServiceName,`Failed to add device channel ${n.Name} to group ${e.Name}, controller responded with error ${t}`),new De(ag.UnknownError,`Failed to add device channel ${n.Name} to group ${e.Name}, controller responded with error ${t}`)}let n=yield Fv.Get(Fo.ServiceName).GetDevicesAsync();for(let o of n)for(let n of o.Channels.except(t,((e,t)=>e.GetDevice().Guid==t.GetDevice().Guid&&e.Number==t.Number)))for(var r of n.ChannelGroups.where((t=>e.Guid==t))){let t=yield this.RemoveDeviceChannelFromGroupAsync(n,e);if(Fv.Get(Ge.ServiceName).ClearCache(),yield this.GetGroupsAsync(),t!==ce.OK)return Fv.Get(s.ServiceName).Error(dg.ServiceName,`Failed to remove device channel ${n.Name} from group ${e.Name}, controller responded with error ${t}`),Fv.Get(rt.ServiceName).ExitConfigurationModeAsync(),new De(ag.UnknownError,`Failed to remove device channel ${n.Name} from group ${e.Name}, controller responded with error ${t}`)}return Fv.Get(rt.ServiceName).ExitConfigurationModeAsync(),e}))}UpdateGroupWithDevicesChannelsAsync(e,t){return lg(this,void 0,void 0,(function*(){for(let n of t.where((t=>t.ChannelGroups.all((t=>t!==e))))){let t=yield this.AddDeviceChannelToGroupByGuidAsync(n,e);if(Fv.Get(Ge.ServiceName).ClearCache(),yield this.GetGroupsAsync(),t!==ce.OK)return Fv.Get(s.ServiceName).Error(dg.ServiceName,`Failed to add device channel ${n.Name} to group ${e}, controller responded with error ${t}`),Fv.Get(rt.ServiceName).ExitConfigurationModeAsync(),ce.FatalError}let n=yield Fv.Get(Fo.ServiceName).GetDevicesAsync();for(let o of n)for(let n of o.Channels.except(t,((e,t)=>e.GetDevice().Guid==t.GetDevice().Guid&&e.Number==t.Number)))for(var r of n.ChannelGroups.where((t=>e==t))){let t=yield this.RemoveDeviceChannelFromGroupByGuidAsync(n,e);if(Fv.Get(Ge.ServiceName).ClearCache(),yield this.GetGroupsAsync(!1),yield Fv.Get(Fo.ServiceName).GetDevicesAsync(),t!==ce.OK)return Fv.Get(s.ServiceName).Error(dg.ServiceName,`Failed to add device channel ${n.Name} to group ${e}, controller responded with error ${t}`),Fv.Get(rt.ServiceName).ExitConfigurationModeAsync(),ce.FatalError}return Fv.Get(rt.ServiceName).ExitConfigurationModeAsync(),ce.OK}))}ChangeGroupNameByGuidAsync(e,t){return lg(this,void 0,void 0,(function*(){var n,s;let r=new Cg,o=new kg,i=this._groups.first((t=>t.Guid===e));o.Guid=e,o.Name=t,o.IconName=i.IconName,null===(n=r.Data)||void 0===n||n.push(o);const a=yield null===(s=this._connection)||void 0===s?void 0:s.SendAndWaitForResponseAsync(r,15e3,!1);if(Fv.Get(Ge.ServiceName).ClearCache(),this._groups=yield this.GetGroupsAsync(),Fv.Get(rt.ServiceName).ExitConfigurationModeAsync(),null!=a&&null!=a.Status)switch(a.Status){case ce.OK:return new De(ag.Success,"");case ce.WrongData:switch(a.Data){case"NameToShort":return new De(ag.NameToShort,"At least 3 characters required");case"NameAlreadyExists":return new De(ag.NameAlreadyExists,"Group with this name already exists");default:return new De(ag.OtherError,`Response error: ${a.Status} data: ${a.Data}`)}default:return new De(ag.OtherError,`Response error: ${a.Status} data: ${a.Data}`)}return new De(ag.UnknownError,"")}))}ChangeGroupNameAndIconAsync(e,t,n){return this.ChangeGroupNameAndIconByGuidAsync(e.Guid,t,n)}ChangeGroupNameAndIconByGuidAsync(e,t,n){return lg(this,void 0,void 0,(function*(){var s,r;let o=new Cg,i=new kg,a=this._groups.first((t=>t.Guid===e));i.Guid=e,i.Name=t,i.IconName=n,i.ObjectsOrder=a.ObjectsOrder,null===(s=o.Data)||void 0===s||s.push(i);const c=yield null===(r=this._connection)||void 0===r?void 0:r.SendAndWaitForResponseAsync(o,15e3,!1);if(Fv.Get(Ge.ServiceName).ClearCache(),this._groups=yield this.GetGroupsAsync(),Fv.Get(rt.ServiceName).ExitConfigurationModeAsync(),null!=c&&null!=c.Status)switch(c.Status){case ce.OK:return new De(ag.Success,"");case ce.WrongData:switch(c.Data){case"NameToShort":return new De(ag.NameToShort,"At least 3 characters required");case"NameAlreadyExists":return new De(ag.NameAlreadyExists,"Group with this name already exists");default:return new De(ag.OtherError,`Response error: ${c.Status} data: ${c.Data}`)}default:return new De(ag.OtherError,`Response error: ${c.Status} data: ${c.Data}`)}return new De(ag.UnknownError,"")}))}ChangeGroupIconNameByGuidAsync(e,t){return lg(this,void 0,void 0,(function*(){var n,s;let r=new Cg,o=new kg,i=this._groups.first((t=>t.Guid===e));o.Guid=e,o.Name=i.Name,o.IconName=t,null===(n=r.Data)||void 0===n||n.push(o);const a=yield null===(s=this._connection)||void 0===s?void 0:s.SendAndWaitForResponseAsync(r,15e3,!1);if(Fv.Get(Ge.ServiceName).ClearCache(),this._groups=yield this.GetGroupsAsync(),Fv.Get(rt.ServiceName).ExitConfigurationModeAsync(),null!=a&&null!=a.Status)switch(a.Status){case ce.OK:return new De(ag.Success,"");case ce.WrongData:switch(a.Data){case"NameToShort":return new De(ag.NameToShort,"At least 3 characters required");case"NameAlreadyExists":return new De(ag.NameAlreadyExists,"Group with this name already exists");default:return new De(ag.OtherError,`Response error: ${a.Status} data: ${a.Data}`)}default:return new De(ag.OtherError,`Response error: ${a.Status} data: ${a.Data}`)}return new De(ag.UnknownError,"")}))}GetServiceName(){return dg.ServiceName}WaitForSynchronizationAsync(){return this._synchronizationTaskCompletionSource}GetGroupByGuid(e){return this._groups.first((t=>t.Guid===e))}ChangeGroupNameAsync(e,t){return this.ChangeGroupNameByGuidAsync(e.Guid,t)}ChangeGroupIconNameAsync(e,t){return this.ChangeGroupNameByGuidAsync(e.Guid,t)}RemoveGroupAsync(e){return this.RemoveGroupByGuidAsync(e.Guid)}RemoveGroupByGuidAsync(e){return lg(this,void 0,void 0,(function*(){var t;let n=new Ag;n.Data=e;const s=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(n,15e3,!1);Fv.Get(Ge.ServiceName).ClearCache(),yield this.GetGroupsAsync(!1),yield Fv.Get(Fo.ServiceName).GetDevicesAsync();for(let t of yield Fv.Get(Fo.ServiceName).GetDevicesAsync())for(let n of t.Channels)n.ChannelGroups.any((t=>t===e))&&(n.ChannelGroups=n.ChannelGroups.except(e,((e,t)=>e===t)).toArray());return Fv.Get(rt.ServiceName).ExitConfigurationModeAsync(),null!=s&&null!=s.Status?null==s?void 0:s.Status:ce.Error}))}GetGroupsAsync(){return lg(this,arguments,void 0,(function*(e=!1){var t,n;const r=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new _g,15e3,e);let o=[];if((null==r?void 0:r.Status)===ce.OK){let e=Fv.Get(s.ServiceName),t=0,i=yield Fv.Get(Fo.ServiceName).GetDevicesAsync();return null===(n=r.Data)||void 0===n||n.forEach((n=>{t++;let s=new cg;if(s.Guid=n.Guid,s.Name=n.Name,s.IconName=n.IconName,s.ObjectsOrder=n.ObjectsOrder,s.OrderPosition=n.OrderPosition,null==s.OrderPosition&&(s.OrderPosition=t),null==s.ObjectsOrder){this._objectsGroupingSupported=!1,s.ObjectsOrder={};let e=i.selectMany((e=>e.Channels.where((e=>e.ChannelGroups.any((e=>e==s.Guid)))))),t=0;for(let n of e)t++,s.ObjectsOrder[t]=n.ChannelId}else this._objectsGroupingSupported=!0;e.Info(dg.ServiceName,`Got group: ${s.Name} ${s.Guid} order: ${s.OrderPosition} objects order: ${JSON.stringify(s.ObjectsOrder)}`),o.push(s)})),this._groups=o,o}throw new Error(`Failed to get groups, API responded with status ${null==r?void 0:r.Status} data: ${null==r?void 0:r.Data}`)}))}AddDeviceChannelToGroupAsync(e,t){return this.AddDeviceChannelToGroupByGuidAsync(e,t.Guid)}RemoveDeviceChannelFromGroupAsync(e,t){return this.RemoveDeviceChannelFromGroupByGuidAsync(e,t.Guid)}AddNewGroupAsync(e){return lg(this,void 0,void 0,(function*(){var t,n;let r=new Cg,o=new kg;o.Name=e,null===(t=r.Data)||void 0===t||t.push(o);const i=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(r,15e3,!1);if(Fv.Get(Ge.ServiceName).ClearCache(),yield this.GetGroupsAsync(!1),yield Fv.Get(Fo.ServiceName).GetDevicesAsync(),Fv.Get(rt.ServiceName).ExitConfigurationModeAsync(),null!=i&&null!=i.Status)switch(i.Status){case ce.OK:return this._groups.first((t=>t.Name===e));case ce.WrongData:switch(Fv.Get(s.ServiceName).Error(dg.ServiceName,`Failed to add new group, controller responded with error ${i.Status} data: ${i.Data}`),i.Data){case"NameToShort":return new De(ag.NameToShort,"At least 3 characters required");case"NameAlreadyExists":return new De(ag.NameAlreadyExists,"Group with this name already exists");default:return new De(ag.OtherError,`Response error: ${i.Status} data: ${i.Data}`)}default:return new De(ag.OtherError,`Response error: ${i.Status} data: ${i.Data}`)}return new De(ag.UnknownError,"")}))}AddNewGroupWithIconAsync(e,t){return lg(this,void 0,void 0,(function*(){var n,r;let o=new Cg,i=new kg;i.Name=e,i.IconName=t,null===(n=o.Data)||void 0===n||n.push(i);const a=yield null===(r=this._connection)||void 0===r?void 0:r.SendAndWaitForResponseAsync(o,15e3,!1);if(Fv.Get(Ge.ServiceName).ClearCache(),yield this.GetGroupsAsync(!1),yield Fv.Get(Fo.ServiceName).GetDevicesAsync(),Fv.Get(rt.ServiceName).ExitConfigurationModeAsync(),null!=a&&null!=a.Status)switch(a.Status){case ce.OK:return this._groups.first((t=>t.Name===e));case ce.WrongData:switch(Fv.Get(s.ServiceName).Error(dg.ServiceName,`Failed to add new group, controller responded with error ${a.Status} data: ${a.Data}`),a.Data){case"NameToShort":return new De(ag.NameToShort,"At least 3 characters required");case"NameAlreadyExists":return new De(ag.NameAlreadyExists,"Group with this name already exists");default:return new De(ag.OtherError,`Response error: ${a.Status} data: ${a.Data}`)}default:return new De(ag.OtherError,`Response error: ${a.Status} data: ${a.Data}`)}return new De(ag.UnknownError,"")}))}}dg.ServiceName="ChannelsGroupsService";class hg extends ae{constructor(e,t){super(),this.Resource="/devices/groups/group/move",this.Method=ue.Post,this.Data=new vg,this.Data.GroupGuid=e,this.Data.NewPosition=t}}class pg extends ae{constructor(e){super(),this.Resource="/devices/groups/move",this.Method=ue.Post,this.Data=e}}class gg extends ae{constructor(e,t){super(),this.Resource="/devices/groups/group/objects/set",this.Method=ue.Post,this.Data=new fg,this.Data.GroupGuid=e.Guid,this.Data.ObjectsIds=t}}class fg{constructor(){this.GroupGuid="",this.ObjectsIds=[]}}class vg{constructor(){this.GroupGuid="",this.NewPosition=0}}class mg extends ae{constructor(e,t,n){super(),this.Resource="/devices/groups/group/object/move",this.Method=ue.Post,this.Data=new wg,this.Data.GroupGuid=e,this.Data.NewPosition=n,this.Data.ObjectId=t}}class yg extends ae{constructor(e,t){super(),this.Resource="/devices/groups/group/objects/move",this.Method=ue.Post,this.Data=new Sg,this.Data.GroupGuid=e,this.Data.OrderedObjectsIds=t}}class wg{constructor(){this.GroupGuid="",this.ObjectId="",this.NewPosition=0}}class Sg{constructor(){this.GroupGuid="",this.OrderedObjectsIds=[]}}class Ag extends ae{constructor(){super(),this.Resource="/devices/groups/group",this.Method=ue.Delete}}class _g extends ae{constructor(){super(),this.Resource="/devices/groups/",this.Method=ue.Get}}class Cg extends ae{constructor(){super(),this.Resource="/devices/groups/group",this.Method=ue.Put,this.Data=[]}}class Tg extends ae{constructor(){super(),this.Resource="/devices/device/channel/groups/group/",this.Method=ue.Put,this.Data=new Gg}}class Dg extends ae{constructor(){super(),this.Resource="/devices/device/channel/groups/group/",this.Method=ue.Delete,this.Data=new Gg}}class kg{constructor(){this.Id=0,this.Guid="",this.Name="",this.IconName="",this.OrderPosition=0,this.ObjectsOrder={}}}class Gg{constructor(){this.GroupGuid="",this.DeviceGuid="",this.Channel=0}}class bg{constructor(){this._promise=Promise.resolve(),this._disable=()=>{}}Lock(){this._promise=new Promise((e=>this._disable=e))}Unlock(){this._disable()}WaitForLockAsync(){return this._promise}}!function(e){e[e.Suspended=1]="Suspended",e[e.ReturnedFromSuspension=2]="ReturnedFromSuspension",e[e.EnteredLowPowerMode=3]="EnteredLowPowerMode",e[e.ExitedLowPowerMode=4]="ExitedLowPowerMode",e[e.LoggedIn=5]="LoggedIn",e[e.LoggedOut=6]="LoggedOut",e[e.Connected=7]="Connected",e[e.Disconnected=8]="Disconnected",e[e.FailedToConnect=9]="FailedToConnect",e[e.Connecting=10]="Connecting",e[e.Disconnecting=11]="Disconnecting",e[e.Reconnecting=12]="Reconnecting"}(ug||(ug={}));var Ng,Eg,Ig,Rg,Pg,Og,Ug,Mg,xg,Fg,Lg,Bg=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class Wg{constructor(){this._syncLock=new bg,this._isInFouces=!0,this._canHibernate=!0,this._session=null,this._connection=null,this._currentAppState=ug.Disconnected,this._returnedFromSuspension=!1,this._onReturnedFromSuspensionEvent=new Ce,this._onSuspendedEvent=new Ce,this._onEnterLowPowerModeEvent=new Ce,this._onExitLowPowerModeEvent=new Ce,this._onBackButtonPressedEvent=new Ce,this._onForwardButtonPressedEvent=new Ce,this._onAppStateChanged=new n,this.MonitorAppState(),this._onAppStateChanged.Subscribe((e=>this._currentAppState=e)),null==navigator.userAgent.match(/Safari/i)||navigator.mediaDevices?window.addEventListener("visibilitychange",(()=>Bg(this,void 0,void 0,(function*(){yield this._syncLock.WaitForLockAsync(),this._syncLock.Lock(),this.IsHidden()?this.Suspend():this.ReturnFromSuspension(),this._syncLock.Unlock()})))):(window.addEventListener("onblur",(()=>{this._isInFouces&&(this._isInFouces=!1,this.Suspend())})),window.addEventListener("onfocus",(()=>{this._isInFouces||(this._isInFouces=!0,this.ReturnFromSuspension())}))),window.addEventListener("popstate",(e=>{var t,n,s,o;document.location,e.state&&("forward"==e.state.direction?(null===(t=r.Log)||void 0===t||t.Warning(Wg.ServiceName,"Forward button pressed"),null===(n=this._onForwardButtonPressedEvent)||void 0===n||n.Invoke()):(null===(s=r.Log)||void 0===s||s.Warning(Wg.ServiceName,"Back button pressed"),null===(o=this._onBackButtonPressedEvent)||void 0===o||o.Invoke()))}))}MonitorAppState(){return Bg(this,void 0,void 0,(function*(){this._session=yield Fv.GetAsync("SessionService"),this._connection=yield Fv.GetAsync("ExalusConnectionService"),this._session.OnUserLoggedInEvent().Subscribe((e=>{var t;null===(t=r.Log)||void 0===t||t.Warning(Wg.ServiceName,"App state changed to: logged in"),this._onAppStateChanged.Invoke(ug.LoggedIn)})),this._session.OnUserLoggedOutEvent().Subscribe((e=>{var t;null===(t=r.Log)||void 0===t||t.Warning(Wg.ServiceName,"App state changed to: logged out"),this._onAppStateChanged.Invoke(ug.LoggedOut)})),this._connection.OnConnectionStateChangedEvent().Subscribe((e=>{var t,n,s,o,i,a;switch(e){case he.Connected:null===(t=r.Log)||void 0===t||t.Warning(Wg.ServiceName,"App state changed to: connected"),this._onAppStateChanged.Invoke(ug.Connected);break;case he.Disconnected:null===(n=r.Log)||void 0===n||n.Warning(Wg.ServiceName,"App state changed to: disconnected"),this._onAppStateChanged.Invoke(ug.Disconnected);break;case he.Connecting:null===(s=r.Log)||void 0===s||s.Warning(Wg.ServiceName,"App state changed to: connecting"),this._onAppStateChanged.Invoke(ug.Connecting);break;case he.Disconnecting:null===(o=r.Log)||void 0===o||o.Warning(Wg.ServiceName,"App state changed to: disconnecting"),this._onAppStateChanged.Invoke(ug.Disconnecting);break;case he.Reconnecting:null===(i=r.Log)||void 0===i||i.Warning(Wg.ServiceName,"App state changed to: reconnecting"),this._onAppStateChanged.Invoke(ug.Reconnecting);break;case he.Failed:null===(a=r.Log)||void 0===a||a.Warning(Wg.ServiceName,"App state changed to: failed"),this._onAppStateChanged.Invoke(ug.FailedToConnect)}}))}))}get CurrentAppState(){return this._currentAppState}OnAppStateChanged(){return this._onAppStateChanged}Suspend(){var e,t;this.IsHibernationAllowed()&&(this._returnedFromSuspension=!1,this._onSuspendedEvent.Invoke(),this._onAppStateChanged.Invoke(ug.Suspended),null===(e=r.Log)||void 0===e||e.Warning(Wg.ServiceName,"App state changed to: suspended"),null===(t=r.Log)||void 0===t||t.Warning(Wg.ServiceName,"App switched to background"))}ReturnFromSuspension(){var e,t;this.IsHibernationAllowed()&&(this._returnedFromSuspension=!0,this._onReturnedFromSuspensionEvent.Invoke(),this._onAppStateChanged.Invoke(ug.ReturnedFromSuspension),null===(e=r.Log)||void 0===e||e.Warning(Wg.ServiceName,"App state changed to: returned from suspension"),null===(t=r.Log)||void 0===t||t.Warning(Wg.ServiceName,"App switched to foreground"))}EnterLowPowerMode(){this._onEnterLowPowerModeEvent.Invoke(),this._onAppStateChanged.Invoke(ug.EnteredLowPowerMode)}ExitLowPowerMode(){this._onExitLowPowerModeEvent.Invoke(),this._onAppStateChanged.Invoke(ug.ExitedLowPowerMode)}IsWorkingInWebView(){return"file:"===window.location.protocol||null!=navigator.userAgent.match(/Safari/i)&&!navigator.mediaDevices}IsHidden(){return document.hidden}IsActive(){return!this.IsHidden()}IsInBackground(){return this.IsHidden()}ReturnedFromSuspension(){return this._returnedFromSuspension}IsHibernationAllowed(){return this._canHibernate}DisallowHibernation(){this._canHibernate=!1}AllowHibernation(){this._canHibernate=!0}OnReturnedFromSuspension(){return this._onReturnedFromSuspensionEvent}OnSuspended(){return this._onSuspendedEvent}OnEnterLowPowerMode(){return this._onEnterLowPowerModeEvent}OnExitLowPowerMode(){return this._onExitLowPowerModeEvent}OnBackButtonPressed(){return this._onBackButtonPressedEvent}OnForwardButtonPressed(){return this._onForwardButtonPressedEvent}GetServiceName(){return Wg.ServiceName}}Wg.ServiceName="AppStateService";class $g{constructor(){this.DeviceGuid="",this.CurrentVersion="",this.NewVersion=""}}class qg{constructor(){this.UpdatesAvailable=[],this.UpdatesNotAvailable=[]}}class Vg{constructor(){this.UpdatedResourceName=new Map,this.UpdateDescription=new Map,this.UpdateCreationTime=null,this.Version="",this.UpdateChannel=""}}class Hg{constructor(){this.Resource="",this.Version="",this.Type=null}}!function(e){e[e.RadioUpdate=0]="RadioUpdate",e[e.SoftwareUpdate=1]="SoftwareUpdate"}(Ng||(Ng={})),function(e){e[e.DownloadingFailure=-5]="DownloadingFailure",e[e.InstallationStopped=-4]="InstallationStopped",e[e.InstallationError=-3]="InstallationError",e[e.IncompatiblePackage=-2]="IncompatiblePackage",e[e.Error=-1]="Error",e[e.OK=0]="OK",e[e.DownloadingPackage=1]="DownloadingPackage",e[e.CheckingPackage=2]="CheckingPackage",e[e.PreparingForUpgrade=3]="PreparingForUpgrade",e[e.Upgrading=4]="Upgrading",e[e.MovingData=5]="MovingData",e[e.Reloading=6]="Reloading",e[e.Upgraded=7]="Upgraded"}(Eg||(Eg={})),(Lg=Ig||(Ig={}))[Lg.WaitingForUser=1]="WaitingForUser",Lg[Lg.Downloading=2]="Downloading",Lg[Lg.Unpackaging=3]="Unpackaging",Lg[Lg.CheckingApplicability=4]="CheckingApplicability",Lg[Lg.MigratingData=5]="MigratingData",Lg[Lg.CreatingBackup=6]="CreatingBackup",Lg[Lg.Deploying=7]="Deploying",Lg[Lg.Installing=8]="Installing",Lg[Lg.Removing=9]="Removing",Lg[Lg.Error=10]="Error",Lg[Lg.ReadyToDownload=11]="ReadyToDownload",Lg[Lg.PreparingSystem=12]="PreparingSystem",Lg[Lg.CheckingPackageIntegrity=13]="CheckingPackageIntegrity",Lg[Lg.CheckingIntegrity=14]="CheckingIntegrity",Lg[Lg.UndoingInstallation=15]="UndoingInstallation",Lg[Lg.Installed=16]="Installed",(Fg=Rg||(Rg={}))[Fg.Ignore=0]="Ignore",Fg[Fg.Cancel=1]="Cancel",Fg[Fg.Install=2]="Install";class jg{constructor(){this.UpdatedResourceName=new Map,this.Percentage=0,this.PercentageTotal=0,this.Status=Eg.Error,this.UpdateNumber=1,this.AvailableUpdates=1}}class Kg{constructor(){this.UpdatedResourceName=new Map,this.Percentage=0,this.PercentageTotal=0,this.SpeedMbps=0,this.CurrentTask=Ug.Unknown}}class zg{constructor(){this.BulkUpdateStatus=Pg.Success,this.DevicesUpdateResults=new Map}}!function(e){e[e.Success=0]="Success",e[e.PartialSuccess=1]="PartialSuccess",e[e.UpdatesNotFound=2]="UpdatesNotFound",e[e.CannotUnpairRetransmitters=3]="CannotUnpairRetransmitters",e[e.CannotPairRetransmitters=4]="CannotPairRetransmitters"}(Pg||(Pg={})),function(e){e[e.Unknown=0]="Unknown",e[e.Updated=1]="Updated",e[e.InsufficientConnection=2]="InsufficientConnection",e[e.Error=3]="Error",e[e.UnknownError=4]="UnknownError",e[e.ControllerSoftwareTooOld=5]="ControllerSoftwareTooOld"}(Og||(Og={})),function(e){e[e.Unknown=0]="Unknown",e[e.DownloadingUpdate=1]="DownloadingUpdate",e[e.DownloadingInstaller=2]="DownloadingInstaller",e[e.CheckingUpdate=3]="CheckingUpdate"}(Ug||(Ug={})),function(e){e[e.DeviceIsUpToDate=0]="DeviceIsUpToDate",e[e.CannotFindDevice=1]="CannotFindDevice",e[e.UnsupportedApiVersion=2]="UnsupportedApiVersion",e[e.UnsupportedDevice=3]="UnsupportedDevice",e[e.CannotGetFirmwareVersion=4]="CannotGetFirmwareVersion",e[e.CannotGetUpdates=5]="CannotGetUpdates",e[e.CannotProcessUpdate=6]="CannotProcessUpdate",e[e.UpdateActionsNotSupported=7]="UpdateActionsNotSupported",e[e.UnsupportedExtensionVersion=8]="UnsupportedExtensionVersion",e[e.UpdatesPartiallyInstalled=9]="UpdatesPartiallyInstalled",e[e.RetransmitterFound=10]="RetransmitterFound",e[e.ProtocolRadioUnsupported=11]="ProtocolRadioUnsupported",e[e.FeatureUnsupportedInCurrentVersion=12]="FeatureUnsupportedInCurrentVersion",e[e.CannotGetUpdatesBranch=13]="CannotGetUpdatesBranch",e[e.CannotSetUpdatesBranch=14]="CannotSetUpdatesBranch",e[e.UpdateAlreadyDownloaded=15]="UpdateAlreadyDownloaded",e[e.UpdateDownloadFailed=16]="UpdateDownloadFailed",e[e.UpdateAlreadyInstalled=17]="UpdateAlreadyInstalled",e[e.CannotGetCurrentControllerVersionTimeout=18]="CannotGetCurrentControllerVersionTimeout",e[e.CannotGetCurrentControllerVersion=19]="CannotGetCurrentControllerVersion"}(Mg||(Mg={})),function(e){e.Public="public",e.Beta="beta",e.Development="dev"}(xg||(xg={}));var Jg,Yg,Xg,Qg,Zg,ef,tf,nf,sf=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class rf{constructor(){this._controllerUpdates=[],this._updateRequestTimeout=12e4,this._oldUpdateVersion=5,this._oldUpdateBuild=56,this._updateOfflineStageTime=8.5,this._updateProviders=Fv.Get(Qr.ServiceName),this._logger=Fv.Get(s.ServiceName),this._connection=Fv.Get(Pt.ServiceName),this._appStateService=Fv.Get(Wg.ServiceName),this._extensionService=Fv.Get(Ze.ServiceName)}GetAutomaticControllerUpdateDownloadStatusAsync(){return sf(this,void 0,void 0,(function*(){const e=yield this.getRuntimeInfoAsync();if(e instanceof De)return e;const t=parseInt(e.SoftwareVersion.toString().split(".")[0]),n=parseInt(e.SoftwareVersion.toString().split(".")[1]);if(t<=this._oldUpdateVersion&&n<=this._oldUpdateBuild)return new De(Mg.FeatureUnsupportedInCurrentVersion,`Cannot get update branch, feature unsupported in current version. Current version: ${e}`);let s=yield this._connection.SendAndWaitForResponseAsync(new wf,1e4,!1);return!(s.Status!=ce.OK||!s.Data)}))}GetServiceName(){return rf.ServiceName}CheckDeviceVersionAsync(e){return sf(this,void 0,void 0,(function*(){var t;let n;if("string"==typeof e){const t=yield Fv.Get(Fo.ServiceName).GetDevice(e);if(null==t)return new De(Mg.CannotFindDevice,`Device with specified GUID ${e} does not exists.`);n=t}else n=e;if(null==n.ProtocolGuid)return new De(Mg.UnsupportedDevice,"Device does not contains data about protocol GUID.");const s=yield null===(t=(yield this._updateProviders.GetUpdatesProvidersByProtocolAsync(n.ProtocolGuid,Er.Device)).first())||void 0===t?void 0:t.GetSoftwareVersionAsync(n);return s.Type,s}))}CheckDeviceUpdateAsync(e){return sf(this,void 0,void 0,(function*(){var t;let n;if("string"==typeof e){const t=yield Fv.Get(Fo.ServiceName).GetDevice(e);if(null==t)return new De(Mg.CannotFindDevice,`Device with specified GUID ${e} does not exists.`);n=t}else n=e;if(null==n.ProtocolGuid)return new De(Mg.UnsupportedDevice,"Device does not contains data about protocol GUID.");const s=yield null===(t=(yield this._updateProviders.GetUpdatesProvidersByProtocolAsync(n.ProtocolGuid,Er.Device)).first())||void 0===t?void 0:t.GetAvailableUpdateAsync(n);if(null!=s.Type)return s;const r=new cf;r.CurrentResourceVersion=s.CurrentResourceVersion,r.NewResourceVersion=s.Update.Version,r.UpdatedResourceName=s.UpdatedResourceName,r.UpdateResourceGuid=s.Update.ResourceGuid,r.UpdateDescription=new Map([["pl-PL",s.Update.Description]]);let o="n/a";try{o=(yield this._extensionService.GetProtocolInfoAsync(n.ProtocolGuid)).first().Name}catch(e){this._logger.Warning(`Cannot get protocol name! error: ${e}`)}return r.Protocol=o,r.ProtocolGuid=n.ProtocolGuid,(yield Fv.Get(Fo.ServiceName).GetDevicesAsync()).any((e=>"952ddc14-76c4-4f47-b0bc-5d106c1f9b02"==e.ModelGuid))&&(r.IsUpdateSafe=!1),r}))}CheckDeviceUpdatesBulkAsync(e){return sf(this,void 0,void 0,(function*(){const t=yield yield this._updateProviders.GetUpdatesProvidersAsync(Er.Device),n=[];for(var s of t){const t=yield s.CheckUpdateBulkAsync(e);if(t instanceof De)return t;t.map((e=>sf(this,void 0,void 0,(function*(){const t=new cf;t.CurrentResourceVersion=e.CurrentResourceVersion,t.NewResourceVersion=e.Update.Version,t.UpdatedResourceName=e.UpdatedResourceName,t.UpdateDescription=e.UpdateDescription,t.IsUpdateSafe=!0;let r="n/a";try{r=(yield this._extensionService.GetProtocolInfoAsync(s.ProtocolGuid)).first().Name}catch(e){this._logger.Warning(`Cannot get protocol name! error: ${e}`)}t.Protocol=r,t.ProtocolGuid=s.ProtocolGuid,t.UpdateResourceGuid=e.Update.ResourceGuid,n.push(t)}))))}return n}))}InstallDeviceUpdateAsync(e,t,n){return sf(this,arguments,void 0,(function*(e,t,n,s=!1){var r;let o;if("string"==typeof e){const t=yield Fv.Get(Fo.ServiceName).GetDevice(e);if(null==t)return new De(Mg.CannotFindDevice,`Device with specified GUID ${e} does not exists.`);o=t}else o=e;if(null==o.ProtocolGuid)return new De(Mg.UnsupportedDevice,"Device does not contains data about protocol GUID.");const i=yield null===(r=(yield this._updateProviders.GetUpdatesProvidersByProtocolAsync(o.ProtocolGuid,Er.Device)).first())||void 0===r?void 0:r.GetAvailableUpdateAsync(o);if(null!=i.Type)return i;this._appStateService.DisallowHibernation();const a=yield(yield this._updateProviders.GetUpdatesProvidersByProtocolAsync(o.ProtocolGuid,Er.Device)).first().InstallUpdateAsync(i,t,n,s);return null!=a.Type?(this._appStateService.AllowHibernation(),a):(this._appStateService.AllowHibernation(),ce.OK)}))}InstallDevicesUpdateBulkAsync(e,t,n){return sf(this,void 0,void 0,(function*(){const s=(yield Fv.Get(Fo.ServiceName).GetDevicesAsync()).where((t=>e.includes(t.Guid))).groupBy((e=>e.ProtocolGuid)),r=[],o=s.count();for(let e=0;e<o;e++){const i=s.elementAt(e),a=e*(100/o),c=(e+1)*(100/o),u=e=>{e.PercentageTotal=Math.floor(e.PercentageTotal/100*(c-a)+a),t(e)},l=yield yield this._updateProviders.GetUpdatesProvidersByProtocolAsync(i.key,Er.Device),d=yield l.first().InstalUpdateBulkAsync(i.select((e=>e.Guid)).toArray(),u,n);if(d instanceof De)return d;r.push(d)}if(1==r.length)return r[0];{const e=new zg;r.some((e=>e.DevicesUpdateResults.count()>0))&&r.any((e=>e.BulkUpdateStatus!=Pg.Success))?e.BulkUpdateStatus=Pg.PartialSuccess:r.any((e=>e.BulkUpdateStatus!=Pg.Success))?e.BulkUpdateStatus=r.first().BulkUpdateStatus:e.BulkUpdateStatus=Pg.Success;for(const t of r)t.DevicesUpdateResults.forEach(((t,n)=>{e.DevicesUpdateResults.set(n,t)}));return e}}))}CheckControllerSoftwareUpdateAvailabilityAsync(){return sf(this,void 0,void 0,(function*(){const e=Fv.Get(Ke.ServiceName).User;if(null==e)return!1;if(""==e.SoftwareVersion||null==e.SoftwareVersion)return!0;const[t,n]=e.SoftwareVersion.split(".");if(parseFloat(t)<=this._oldUpdateVersion&&parseFloat(n)<=this._oldUpdateBuild)return!0;const s=yield this._connection.SendAndWaitForResponseAsync(new ff,1e4,!1);if(null==s||s.Status!=ce.OK||null==s.Data)return!1;const[r,o]=s.Data.Update.Version.ContainerSoftwareVersion.toString().split(".");return parseInt(r)>parseInt(t)||parseInt(r)==parseInt(t)&&parseInt(o)>parseInt(n)}))}CheckDevicesUpdatesAvailabilityAsync(){return sf(this,void 0,void 0,(function*(){const e=yield this._connection.SendAndWaitForResponseAsync(new Cf,1e4,!1),t=[];return null==e||(null==e?void 0:e.Status)!=ce.OK||null==(null==e?void 0:e.Data)?[]:(null==e||e.Data.forEach((e=>{if(!e.IsAvailable)return;const n=new $g;n.DeviceGuid=e.DeviceGuid,n.CurrentVersion=e.CurrentVersion,n.NewVersion=e.NewVersion,t.push(n)})),t)}))}CheckControllerUpdatesAsync(){return sf(this,void 0,void 0,(function*(){this._controllerUpdates=[];let e=[];const t=new qg,n=yield this.getRuntimeInfoAsync();if(n instanceof De){const e=new of;return e.UpdateType=Ng.SoftwareUpdate,e.ResponseResult=n,t.UpdatesNotAvailable.push(e),t}const s=parseInt(n.SoftwareVersion.toString().split(".")[0]),r=parseInt(n.SoftwareVersion.toString().split(".")[1]);try{e=yield this._updateProviders.GetUpdatesProvidersAsync(Er.Controller)}catch(e){if(!(e instanceof Kr))throw e;this._logger.Warning("Cannot get update providers for controller protocols! Avaliable only controller software updates!")}for(let n=0;n<e.length;n++){const s=yield e[n].GetAvailableRadioUpdateAsync();if(null!=s.Type){const r=new of;r.ResponseResult=s,r.UpdateType=Ng.RadioUpdate;let o="n/a";try{o=(yield this._extensionService.GetProtocolInfoAsync(e[n].ProtocolGuid)).first().Name}catch(e){this._logger.Warning(`Cannot get protocol name! error: ${e}`)}r.UpdatedResourceName=new Map([["pl-PL",o],["en-US",o]]),r.CurrentResourceVersion=yield e[n].GetCurrentRadioVersionAsync(),t.UpdatesNotAvailable.push(r)}else{const r=s,o=new af;o.UpdatedResourceName=new Map([["pl-PL",r.UpdatedResourceName],["en-US",r.UpdatedResourceName]]),o.CurrentResourceVersion=r.CurrentResourceVersion,o.NewResourceVersion=r.Update.Version,o.UpdateDescription=new Map([["pl-PL",r.Update.Description]]),o.UpdateType=Ng.RadioUpdate,o.UpdateIdentifier=re.GenerateUUID(),o.UpdateIsDownloading=!1,o.DownloadProgress=100,o.UpdateCreationTime=null,t.UpdatesAvailable.push(o),this._controllerUpdates.push(Object.assign(Object.assign({},r),{UpdateIdentifier:o.UpdateIdentifier,ProviderName:e[n].GetUpdateProviderName(),UpdateType:Ng.RadioUpdate}))}}let o=!0;if(s<=this._oldUpdateVersion&&r<=this._oldUpdateBuild&&(o=!1),o){const e=yield this._connection.SendAndWaitForResponseAsync(new ff,15e3,!1);if(null==e||e.Status!=ce.OK&&e.Status!=ce.NoData)throw new Error(`Cannot get pending updates! Response is empty or status is not OK. Status: ${null==e?void 0:e.Status}`);if(null!=e.Data){const s=new jr;s.CurrentResourceVersion=`${n.RuntimeVersion}.${n.SoftwareVersion}`,s.UpdateDescription=ie(e.Data.Update.UpdateDescription),s.UpdatedResourceName=ie(e.Data.Update.UpdateName).get("en-US");const r=new af;r.UpdatedResourceName=ie(e.Data.Update.UpdateName),r.UpdateDescription=ie(e.Data.Update.UpdateDescription),r.CurrentResourceVersion=`${n.RuntimeVersion}.${n.SoftwareVersion}`,r.NewResourceVersion=`${e.Data.Update.Version.BaseRuntime}.${e.Data.Update.Version.ContainerSoftwareVersion}`,r.UpdateType=Ng.SoftwareUpdate,r.UpdateIdentifier=e.Data.Update.Guid,r.UpdateIsDownloading=e.Data.UpdateStep==Qg.DownloadingInstaller||e.Data.UpdateStep==Qg.DownloadingUpdate||e.Data.UpdateStep==Qg.CheckingUpdate,r.DownloadProgress=e.Data.DownloadProgress,r.UpdateCreationTime=e.Data.Update.Creationtime,t.UpdatesAvailable.push(r),this._controllerUpdates.push(Object.assign(Object.assign({},s),{UpdateIdentifier:r.UpdateIdentifier,ProviderName:rf.ServiceName,UpdateType:Ng.SoftwareUpdate}))}else{const e=yield this._connection.SendAndWaitForResponseAsync(new vf,15e3,!1);if(null==e)throw new Error("Cannot check updates! Response is empty.");switch(e.Status){case ce.NoData:const s=new of;s.UpdateType=Ng.SoftwareUpdate,s.UpdatedResourceName=new Map([["pl-PL","Oprogramowanie kontrolera"],["en-US","Controller software"]]),s.ResponseResult=new De(Mg.DeviceIsUpToDate,"Updates not found, controller is already up-to-date."),t.UpdatesNotAvailable.push(s);break;case ce.OK:if(null==e.Data)throw new Error("Cannot check updates! Response data is empty.");const r=new jr;r.CurrentResourceVersion=`${n.RuntimeVersion}.${n.SoftwareVersion}`,r.UpdateDescription=ie(e.Data.UpdateDescription),r.UpdatedResourceName=ie(e.Data.UpdateName).get("en-US");const o=new af;o.UpdatedResourceName=ie(e.Data.UpdateName),o.UpdateDescription=ie(e.Data.UpdateDescription),o.CurrentResourceVersion=`${n.RuntimeVersion}.${n.SoftwareVersion}`,o.UpdateType=Ng.SoftwareUpdate,o.UpdateIdentifier=e.Data.Guid,o.NewResourceVersion=`${e.Data.Version.BaseRuntime}.${e.Data.Version.ContainerSoftwareVersion}`,o.UpdateIsDownloading=!1,o.DownloadProgress=0,o.UpdateCreationTime=e.Data.Creationtime,t.UpdatesAvailable.push(o),this._controllerUpdates.push(Object.assign(Object.assign({},r),{UpdateIdentifier:o.UpdateIdentifier,ProviderName:rf.ServiceName,UpdateType:Ng.SoftwareUpdate}));break;default:throw new Error(`Cannot check updates! Response status is not OK. Status: ${e.Status}`)}}}else{const e=`https://updates.tr7.pl/software/${n.UpdateChannel}/${n.RuntimeVersion}/${n.SoftwareVersion}/update.json`;try{const s=yield fetch(e);let r,o=new jr;const i=new of;switch(i.UpdateType=Ng.SoftwareUpdate,i.UpdatedResourceName=new Map([["pl-PL","Oprogramowanie kontrolera"],["en-US","Controller software"]]),s.status){case 200:null!=s.body&&(r=yield s.json());break;case 404:i.ResponseResult=new De(Mg.DeviceIsUpToDate,"Updates not found, controller is already up-to-date."),t.UpdatesNotAvailable.push(i);break;default:i.ResponseResult=new De(Mg.CannotGetUpdates,`Response status code does not indicate success. Status: ${s.status}`),t.UpdatesNotAvailable.push(i)}if(null!=r){o.CurrentResourceVersion=`${n.RuntimeVersion}.${n.SoftwareVersion}`,o.Update=r;const e=new af;e.UpdatedResourceName=new Map([["pl-PL","Oprogramowanie kontrolera"],["en-US","Controller software"]]),e.CurrentResourceVersion=o.CurrentResourceVersion,e.NewResourceVersion=o.Update.Version,e.UpdateDescription=new Map([["pl-PL",o.Update.Description]]),e.UpdateType=Ng.SoftwareUpdate,e.UpdateIdentifier=re.GenerateUUID(),e.DownloadProgress=100,e.UpdateIsDownloading=!1,e.UpdateCreationTime=null,t.UpdatesAvailable.push(e),this._controllerUpdates.push(Object.assign(Object.assign({},o),{UpdateIdentifier:e.UpdateIdentifier,ProviderName:rf.ServiceName,UpdateType:Ng.SoftwareUpdate}))}else if(200==s.status)throw new Error(`Cannot get Update Data from response. Status: ${s.status}`)}catch(e){const n=yield this.getRuntimeInfoAsync();if(n instanceof De){const e=new of;e.UpdateType=Ng.SoftwareUpdate,e.UpdatedResourceName=new Map([["pl-PL","Oprogramowanie kontrolera"],["en-US","Controller software"]]),e.ResponseResult=n,t.UpdatesNotAvailable.push(e)}else{const s=new of;s.UpdateType=Ng.SoftwareUpdate,s.UpdatedResourceName=new Map([["pl-PL","Oprogramowanie kontrolera"],["en-US","Controller software"]]),s.ResponseResult=new De(Mg.CannotGetUpdates,`Cannot get available updates! ${e}`),s.CurrentResourceVersion=`${n.RuntimeVersion}.${n.SoftwareVersion}`,t.UpdatesNotAvailable.push(s)}}}return t}))}CheckControllerVersionAsync(){return sf(this,void 0,void 0,(function*(){const e=yield this._updateProviders.GetUpdatesProvidersAsync(Er.Controller),t=yield this.getRuntimeInfoAsync();if(t instanceof De)return t;const n=[];let s;s=new Hg,s.Resource="Controller software",s.Type=Ng.SoftwareUpdate,s.Version=`${t.RuntimeVersion}.${t.SoftwareVersion}`,n.push(s);for(let t=0;t<e.length;t++){s=new Hg,s.Version=yield e[t].GetCurrentRadioVersionAsync(),s.Type=Ng.RadioUpdate;let r="n/a";try{r=(yield this._extensionService.GetProtocolInfoAsync(e[t].ProtocolGuid)).first().Name}catch(e){this._logger.Warning(`Cannot get protocol name! error: ${e}`)}s.Resource=r,n.push(s)}return n}))}GetControllerUpdateBranchAsync(){return sf(this,void 0,void 0,(function*(){const e=yield this.getRuntimeInfoAsync();if(e instanceof De)return e;const t=parseInt(e.SoftwareVersion.toString().split(".")[0]),n=parseInt(e.SoftwareVersion.toString().split(".")[1]);if(t<=this._oldUpdateVersion&&n<=this._oldUpdateBuild)return new De(Mg.FeatureUnsupportedInCurrentVersion,`Cannot get update branch, feature unsupported in current version. Current version: ${e}`);const s=yield this._connection.SendAndWaitForResponseAsync(new pf,1e4,!1);if(null==s||(null==s?void 0:s.Status)!=ce.OK)return new De(Mg.CannotGetUpdatesBranch,`Cannot get update branch, response is empty or status is not OK. Status: ${null==s?void 0:s.Status}`);switch(s.Data){case 0:return xg.Public;case 1:return xg.Beta;case 2:return xg.Development;default:return new De(Mg.CannotGetUpdatesBranch,`Cannot get update branch, unknown branch number. Branch number: ${s.Data}`)}}))}SetControllerUpdateBranchAsync(e){return sf(this,void 0,void 0,(function*(){const t=yield this.getRuntimeInfoAsync();if(t instanceof De)return t;const n=parseInt(t.SoftwareVersion.toString().split(".")[0]),s=parseInt(t.SoftwareVersion.toString().split(".")[1]);if(n<=this._oldUpdateVersion&&s<=this._oldUpdateBuild)return new De(Mg.FeatureUnsupportedInCurrentVersion,`Cannot set update branch, feature unsupported in current version. Current version: ${t}`);const r=yield this._connection.SendAndWaitForResponseAsync(new gf(e),1e4,!1);return null==r||(null==r?void 0:r.Status)!=ce.OK?new De(Mg.CannotSetUpdatesBranch,`Cannot set update branch, response is empty or status is not OK. Status: ${null==r?void 0:r.Status}`):ce.OK}))}EnableAutomaticControllerUpdateDonwloadAsync(){return sf(this,void 0,void 0,(function*(){const e=yield this.getRuntimeInfoAsync();if(e instanceof De)return e;const t=parseInt(e.SoftwareVersion.toString().split(".")[0]),n=parseInt(e.SoftwareVersion.toString().split(".")[1]);if(t<=this._oldUpdateVersion&&n<=this._oldUpdateBuild)return new De(Mg.FeatureUnsupportedInCurrentVersion,`Cannot enable automatic updates download, feature unsupported in current version. Current version: ${e}`);const s=yield this._connection.SendAndWaitForResponseAsync(new Sf,1e4,!1);return null==s||(null==s?void 0:s.Status)!=ce.OK?new De(Mg.CannotSetUpdatesBranch,`Cannot enable automatic updates download, response is empty or status is not OK. Status: ${null==s?void 0:s.Status}`):ce.OK}))}DisableAutomaticControllerUpdateDonwloadAsync(){return sf(this,void 0,void 0,(function*(){const e=yield this.getRuntimeInfoAsync();if(e instanceof De)return e;const t=parseInt(e.SoftwareVersion.toString().split(".")[0]),n=parseInt(e.SoftwareVersion.toString().split(".")[1]);if(t<=this._oldUpdateVersion&&n<=this._oldUpdateBuild)return new De(Mg.FeatureUnsupportedInCurrentVersion,`Cannot disable automatic update download, feature unsupported in current version. Current version: ${e}`);const s=yield this._connection.SendAndWaitForResponseAsync(new Af,1e4,!1);return null==s||(null==s?void 0:s.Status)!=ce.OK?new De(Mg.CannotSetUpdatesBranch,`Cannot disable automatic update download, response is empty or status is not OK. Status: ${null==s?void 0:s.Status}`):ce.OK}))}GetControllerUpdatesHistoryAsync(){return sf(this,void 0,void 0,(function*(){const e=yield this.getRuntimeInfoAsync();if(e instanceof De)return e;const t=parseInt(e.SoftwareVersion.toString().split(".")[0]),n=parseInt(e.SoftwareVersion.toString().split(".")[1]);if(t<=this._oldUpdateVersion&&n<=this._oldUpdateBuild)return new De(Mg.FeatureUnsupportedInCurrentVersion,`Cannot disable automatic update download, feature unsupported in current version. Current version: ${e}`);const s=yield this._connection.SendAndWaitForResponseAsync(new _f,1e4,!1);if(null==s)return new De(Mg.CannotGetUpdates,"Cannot get updates history, response is empty.");switch(s.Status){case ce.OK:return null!=s.Data?s.Data.map((e=>{const t=new Vg;return t.UpdatedResourceName=ie(e.UpdateName),t.UpdateDescription=ie(e.UpdateDescription),t.UpdateCreationTime=e.Creationtime,t.UpdateChannel=e.UpdateChannel,t.Version=`${e.Version.BaseRuntime}.${e.Version.ContainerSoftwareVersion}`,t})):new De(Mg.CannotGetUpdates,"Cannot get updates history, response data is empty.");case ce.NoData:return[];default:return new De(Mg.CannotGetUpdates,`Cannot get updates history, response status is not OK. Status: ${s.Status}`)}}))}InstallControllerUpdateAsync(e,t,n,s,r){return sf(this,void 0,void 0,(function*(){const o=new RegExp("^[{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]?$"),i=this._controllerUpdates.length,a=yield this.getRuntimeInfoAsync();if(a instanceof De)return a;const c=parseInt(a.SoftwareVersion.toString().split(".")[0]),u=parseInt(a.SoftwareVersion.toString().split(".")[1]);if(0==this._controllerUpdates.length)return new De(Mg.CannotGetUpdates,"Cannot find any updates, make sure you check for available updates by calling CheckControllerUpdateAsync().");if("string"!=typeof n||!o.test(n)){const r=[1],o=t=>{t.UpdateNumber=r[0],t.AvailableUpdates=i,e(t)},a=e=>sf(this,void 0,void 0,(function*(){return new Promise((t=>setTimeout(t,e)))}));let l=this._controllerUpdates.where((e=>e.UpdateType==Ng.RadioUpdate)).toArray(),d=[];this._appStateService.DisallowHibernation();for(let e=0;e<l.length;e++){const t=yield(yield this._updateProviders.GetUpdatesProviderAsync(l[e].ProviderName)).InstallRadioUpdateAsync(l[e],o,n);yield a(5e3),t==ce.OK&&(this._controllerUpdates=this._controllerUpdates.filter((t=>t.UpdateIdentifier!=l[e].UpdateIdentifier))),d.push(t),r[0]++}const h=this._controllerUpdates.find((e=>e.UpdateType==Ng.SoftwareUpdate));if(null!=h)if(c<=this._oldUpdateVersion&&u<=this._oldUpdateBuild){const e=yield this.UpdateControllerUsingScriptAsync(h.Update,o);e==ce.OK&&(this._controllerUpdates=this._controllerUpdates.filter((e=>e.UpdateIdentifier!=h.UpdateIdentifier))),d.push(e),r[0]++}else{const e=yield this.UpdateControllerUsingApiAsync(o,t,s);this._appStateService.AllowHibernation(),e==ce.OK&&(this._controllerUpdates=this._controllerUpdates.filter((e=>e.UpdateIdentifier!=n))),d.push(e),r[0]++}const p=d.where((e=>e instanceof De)).toArray();if(null!=p&&0!=p.length){let e="";return p.forEach((t=>e+=`${t.Type}, `)),this._appStateService.AllowHibernation(),new De(Mg.UpdatesPartiallyInstalled,`Update installation finished - not all updates were successfully installed. Installation error codes: ${e}`)}return this._appStateService.AllowHibernation(),ce.OK}{let o;const i=this._controllerUpdates.find((e=>e.UpdateIdentifier==n));if(null==i)return new De(Mg.CannotGetUpdates,`Update with requested guid (${n}) not found.`);switch(this._logger.Debug(`Installing single update type: ${i.Update.UpdateType}, resource: ${i.UpdatedResourceName}, version: ${i.Update.Version}`),this._appStateService.DisallowHibernation(),i.UpdateType){case Ng.RadioUpdate:return s?new De(Mg.UpdateAlreadyDownloaded,"Update already downloaded set flag downloadOnly to false to install it."):(o=yield(yield this._updateProviders.GetUpdatesProviderAsync(i.ProviderName)).InstallRadioUpdateAsync(i,e,r),this._appStateService.AllowHibernation(),o==ce.OK&&(this._controllerUpdates=this._controllerUpdates.filter((e=>e.UpdateIdentifier!=n))),o);case Ng.SoftwareUpdate:if(c<=this._oldUpdateVersion&&u<=this._oldUpdateBuild){if(s)return new De(Mg.UpdateAlreadyDownloaded,"Update already downloaded set flag downloadOnly to false to install it.");o=yield this.UpdateControllerUsingScriptAsync(i.Update,e),this._appStateService.AllowHibernation(),o==ce.OK&&(this._controllerUpdates=this._controllerUpdates.filter((e=>e.UpdateIdentifier!=n)))}else o=yield this.UpdateControllerUsingApiAsync(e,t,s),this._appStateService.AllowHibernation(),o==ce.OK&&(this._controllerUpdates=this._controllerUpdates.filter((e=>e.UpdateIdentifier!=n)));return o;default:return new De(Mg.CannotProcessUpdate,`Update with type ${i.UpdateType} is not supported by UpdateService.`)}}}))}UpdateControllerUsingScriptAsync(e,t){return sf(this,void 0,void 0,(function*(){var n,s,r,o,i,a;switch(e.UpdateType){case Ir.Container:case Ir.ContainerSoftware:try{return yield null===(n=this._connection)||void 0===n?void 0:n.SendAndHandleResponseAsync(new uf(e.DownloadUri),this._updateRequestTimeout,(n=>{const s=new jg;switch(s.UpdatedResourceName=new Map([["pl-PL","Oprogramowanie kontrolera"],["en-US","Controller software"]]),n.Status){case ce.MultiDataResponseStart:s.Status=Eg.PreparingForUpgrade;break;case ce.MultiDataResponse:if(null==n.Data)return void this._logger.Warning(rf.ServiceName,`Recived update response without data! URI: ${e.DownloadUri}`);switch(s.Percentage=Math.round(n.Data.Progress),n.Data.State){case Ig.CheckingApplicability:case Ig.CheckingIntegrity:case Ig.CheckingPackageIntegrity:s.Status=Eg.CheckingPackage;break;case Ig.CreatingBackup:case Ig.MigratingData:case Ig.Removing:s.Status=Eg.MovingData;break;case Ig.Deploying:case Ig.Installing:s.Status=Eg.Upgrading;break;case Ig.Downloading:s.Status=Eg.DownloadingPackage;break;case Ig.Error:s.Status=Eg.Error;break;case Ig.Installed:s.Status=Eg.Upgraded;break;case Ig.PreparingSystem:case Ig.ReadyToDownload:s.Status=Eg.PreparingForUpgrade;break;case Ig.UndoingInstallation:s.Status=Eg.InstallationStopped;break;case Ig.Unpackaging:s.Status=Eg.MovingData;break;case Ig.WaitingForUser:s.Status=Eg.Upgrading}break;case ce.MultiDataResponseStop:s.Status=Eg.OK}t(s)}),!1),ce.OK}catch(e){return new De(Mg.CannotProcessUpdate,`Cannot process update, error: ${e}`)}case Ir.RuntimeFixingScript:var c=10;let d="n/a";try{d=(yield this._extensionService.GetExtensionsInfoAsync()).first((e=>"f4f45dac-beda-441a-8d29-efc6dc977cd1"==e.ExtensionGuid)).ExtensionVersion}catch(e){this._logger.Warning(`Cannot get protocol name! error: ${e}`)}var u=d;const h=yield this.getRuntimeInfoAsync();if(h instanceof De)return h;var l=parseFloat(h.RuntimeVersion)>=2||parseFloat(u)>=1.2201125;try{c=(yield Fv.Get(Fo.ServiceName).GetDevicesAsync()).length}catch(e){this._logger.Warning(rf.ServiceName,`Cannot get number of devices in system! Error: ${e}. Using default value of 10 devices.`)}if(l){let n,s=new jg;s.UpdatedResourceName=new Map([["pl-PL","Oprogramowanie kontrolera"],["en-US","Controller software"]]),s.Percentage=1,s.Status=Eg.PreparingForUpgrade,t(s);let r=2;const o=Date.now(),i=900*c+8e5,a=i/100,u=o+i,l=new Promise(((o,c)=>sf(this,void 0,void 0,(function*(){var c;try{const l=()=>{if(this._appStateService.OnReturnedFromSuspension().Unsubscribe(l),Date.now()>u)clearInterval(n),this._logger.Debug("Update already finished!"),s.Percentage=100,s.PercentageTotal=Math.round(s.Percentage),s.Status=Eg.Upgraded,t(s),o(ce.OK);else{var e=u-Date.now();e<i?r=95-e/a:(clearInterval(n),n=setInterval((()=>{clearInterval(n),s.Percentage=100,s.PercentageTotal=Math.round(s.Percentage),s.Status=Eg.Upgraded,t(s),o(ce.OK)}),e))}};this._appStateService.OnReturnedFromSuspension().Subscribe(l),n=setInterval((()=>{if(r>99)clearInterval(n),s.Percentage=100,s.PercentageTotal=Math.round(s.Percentage),s.Status=Eg.Upgraded,t(s),o(ce.OK);else{var e=r;e<99&&(s.Percentage=Math.round(e),s.PercentageTotal=Math.round(s.Percentage),s.Status=Eg.Upgrading,t(s))}r++}),a);const d=yield null===(c=this._connection)||void 0===c?void 0:c.SendAndWaitForResponseAsync(new lf(e.DownloadUri),this._updateRequestTimeout,!1);d.Status!=ce.OK&&(clearInterval(n),s.Percentage=0,s.PercentageTotal=Math.round(s.Percentage),s.Status=Eg.InstallationError,t(s),this._logger.Debug(rf.ServiceName,`Update failed with error. Update response status: ${d.Status}`),o(new De(Mg.CannotProcessUpdate,`Update failed with error. Update response status: ${d.Status}`)))}catch(e){this._logger.Debug(rf.ServiceName,`Update failed with error. ${e}`),s.Percentage=0,s.PercentageTotal=Math.round(s.Percentage),s.Status=Eg.Error,t(s),clearInterval(n),o(new De(Mg.CannotProcessUpdate,`Update failed with error. ${e}`))}}))));return yield l}{let n=new jg;n.UpdatedResourceName=new Map([["pl-PL","Oprogramowanie kontrolera"],["en-US","Controller software"]]),n.Percentage=1,n.PercentageTotal=Math.round(n.Percentage),n.Status=Eg.PreparingForUpgrade,t(n);const u=this._connection.GetAuthorizationInfo();if(null==u)return new De(Mg.CannotProcessUpdate,"Cannot process update. Cannot get current controller login credentials!");if((yield null===(s=this._connection)||void 0===s?void 0:s.SendAndWaitForResponseAsync(new df({Email:"support@support",Password:`support@${u.SerialNumber}:${u.PIN}`}),12e3,!1)).Status===ce.OK){n.Percentage=1,n.PercentageTotal=Math.round(n.Percentage),n.Status=Eg.PreparingForUpgrade,t(n);let s=yield null===(r=this._connection)||void 0===r?void 0:r.SendAndWaitForResponseAsync(new hf("rm /runtime/tmp/update.sh"),12e3,!1);if(s.Status==ce.OK){if(this._logger.Debug("Removed previous script"),n.Percentage=2,n.PercentageTotal=Math.round(n.Percentage),n.Status=Eg.PreparingForUpgrade,t(n),s=yield null===(o=this._connection)||void 0===o?void 0:o.SendAndWaitForResponseAsync(new hf(`wget ${e.DownloadUri} -O /runtime/tmp/update.sh --no-check-certificate`),this._updateRequestTimeout,!1),s.Status==ce.OK){this._logger.Debug("Downloaded update script"),n.Percentage=5,n.PercentageTotal=Math.round(n.Percentage),n.Status=Eg.PreparingForUpgrade,t(n);try{if(s=yield null===(i=this._connection)||void 0===i?void 0:i.SendAndWaitForResponseAsync(new hf("chmod a+x /runtime/tmp/update.sh"),12e3,!1),s.Status==ce.OK){this._logger.Debug("Executed update script"),n.Percentage=5,n.PercentageTotal=Math.round(n.Percentage),n.Status=Eg.Upgrading,t(n);let e,s=0;const r=.95,o=Date.now(),i=900*c+15e5,a=i/95,u=o+i,l=new Promise(((o,c)=>sf(this,void 0,void 0,(function*(){var c;try{const l=()=>{if(this._appStateService.OnReturnedFromSuspension().Unsubscribe(l),Date.now()>u)clearInterval(e),this._logger.Debug("Update already finished!"),n.Percentage=100,n.PercentageTotal=Math.round(n.Percentage),n.Status=Eg.Upgraded,t(n),o(ce.OK);else{var r=u-Date.now();r<i?s=95-r/a:(clearInterval(e),e=setInterval((()=>{clearInterval(e),n.Percentage=100,n.PercentageTotal=Math.round(n.Percentage),n.Status=Eg.Upgraded,t(n),o(ce.OK)}),r))}};this._appStateService.OnReturnedFromSuspension().Subscribe(l),e=setInterval((()=>{if(s>99)clearInterval(e),n.Percentage=100,n.PercentageTotal=Math.round(n.Percentage),n.Status=Eg.Upgraded,t(n),o(ce.OK);else{var i=5+s*r;i<99&&(n.Percentage=Math.round(i),n.PercentageTotal=Math.round(n.Percentage),n.Status=Eg.Upgrading,t(n))}s++}),a),null===(c=this._connection)||void 0===c||c.SendAndWaitForResponseAsync(new hf("/runtime/tmp/update.sh"),12e3,!1)}catch(e){o(new De(Mg.CannotProcessUpdate,`Update failed with error. ${e}`))}}))));return yield l}return n.Percentage=0,n.PercentageTotal=Math.round(n.Percentage),n.Status=Eg.InstallationError,t(n),new De(Mg.CannotProcessUpdate,"Execution failed!")}catch(e){return null===(a=this._connection)||void 0===a||a.SendAndWaitForResponseAsync(new hf("/runtime/scripts/restart_all.sh"),12e3,!1),new De(Mg.CannotProcessUpdate,`Execution failed! Error ${e}`)}}return new De(Mg.CannotProcessUpdate,"Execution failed! Cannot clear old update script!")}}return new De(Mg.CannotProcessUpdate,"Execution failed! Cannot loggin using support account!")}default:return new De(Mg.CannotProcessUpdate,`Not supported update type, type: ${e.UpdateType}`)}}))}UpdateControllerUsingApiAsync(e,t,n){return sf(this,void 0,void 0,(function*(){const s=e=>sf(this,void 0,void 0,(function*(){return new Promise(((s,r)=>sf(this,void 0,void 0,(function*(){yield this._connection.SendAndHandleResponseAsync(new mf,this._updateRequestTimeout,(r=>{var o,i,a,c;const u=new Kg;switch(u.UpdatedResourceName=ie(e.Update.UpdateName),r.Status){case ce.MultiDataResponseStart:u.Percentage=0,u.SpeedMbps=0,u.PercentageTotal=0,u.CurrentTask=Ug.DownloadingInstaller,t(u);break;case ce.MultiDataResponse:if(null!=r.Data){switch(u.Percentage=r.Data.StepProgressInPercentage,u.SpeedMbps=r.Data.DownloadSpeedInMbs,u.PercentageTotal=n?Math.round(2*(null===(o=r.Data)||void 0===o?void 0:o.UpdateProgressInPercentage)):Math.round(null===(i=r.Data)||void 0===i?void 0:i.UpdateProgressInPercentage),r.Data.UpdateStep){case Qg.DownloadingInstaller:u.CurrentTask=Ug.DownloadingInstaller;break;case Qg.DownloadingUpdate:u.CurrentTask=Ug.DownloadingUpdate;break;default:u.CurrentTask=Ug.CheckingUpdate}t(u)}break;case ce.MultiDataResponseStop:if(null!=r.Data)switch(r.Data.UpdateStep){case Qg.UpdateDownloaded:u.Percentage=100,u.PercentageTotal=n?Math.round(2*(null===(a=r.Data)||void 0===a?void 0:a.UpdateProgressInPercentage)):Math.round(null===(c=r.Data)||void 0===c?void 0:c.UpdateProgressInPercentage),u.SpeedMbps=0,u.CurrentTask=Ug.CheckingUpdate,t(u),s(ce.OK);break;case Qg.UpdateDownloadFailed:u.Percentage=0,u.PercentageTotal=0,u.SpeedMbps=0,u.CurrentTask=Ug.Unknown,t(u),s(new De(Mg.UpdateDownloadFailed,"Update download failed!"))}}}),!1)}))))})),r=t=>sf(this,void 0,void 0,(function*(){return new Promise(((n,s)=>sf(this,void 0,void 0,(function*(){const s=60*this._updateOfflineStageTime*1e3;let r=0;yield this._connection.SendAndHandleResponseAsync(new yf,this._updateRequestTimeout,(o=>{var i,a;const c=new jg;switch(c.UpdatedResourceName=ie(t.Update.UpdateName),o.Status){case ce.MultiDataResponseStart:c.Status=Eg.PreparingForUpgrade,c.Percentage=null===(i=o.Data)||void 0===i?void 0:i.StepProgressInPercentage,c.PercentageTotal=null===(a=o.Data)||void 0===a?void 0:a.UpdateProgressInPercentage,e(c);break;case ce.MultiDataResponse:null!=o.Data&&(c.Status=Eg.Upgrading,c.Percentage=Math.round(o.Data.StepProgressInPercentage),c.PercentageTotal=Math.round(o.Data.UpdateProgressInPercentage),r=o.Data.StepProgressInPercentage,e(c));break;case ce.MultiDataResponseStop:if(null!=o.Data)switch(o.Data.UpdateStep){case Qg.UpdateInstallationFailed:c.Status=Eg.InstallationError,c.Percentage=0,c.PercentageTotal=0,e(c),n(new De(Mg.CannotProcessUpdate,"Update installation failed!"));break;case Qg.OfflineUpdateStep:{c.Percentage=Math.round(o.Data.StepProgressInPercentage),c.PercentageTotal=Math.round(o.Data.UpdateProgressInPercentage);let t=(100-c.PercentageTotal)/100,i=c.PercentageTotal;const a=setInterval((()=>{r++,i+=t,i>100&&(i=100),r>=100?(c.Status=Eg.Upgraded,c.Percentage=100,c.PercentageTotal=100,e(c),clearInterval(a),n(ce.OK)):(c.Status=Eg.Upgrading,c.Percentage=Math.round(r),c.PercentageTotal=Math.round(i),e(c))}),s/(100-r))}}}}),!1)}))))}));if(n){const e=yield this._connection.SendAndWaitForResponseAsync(new ff,1e4,!1);if(null==e||(null==e?void 0:e.Status)!=ce.OK||null==(null==e?void 0:e.Data))throw new Error(`Cannot get pending updates! Response is empty or status is not OK. Status: ${null==e?void 0:e.Status}`);switch(e.Data.UpdateStep){case Qg.DownloadingInstaller:case Qg.DownloadingUpdate:case Qg.UpdateDownloaded:return new De(Mg.UpdateAlreadyDownloaded,"Update already downloaded, or download is in progress.");case Qg.InstallingUpdate:case Qg.PreparingUpdate:return new De(Mg.UpdateAlreadyInstalled,"Update already installed, or installation is in progress.");default:return yield s(e.Data)}}else{const e=yield this._connection.SendAndWaitForResponseAsync(new ff,1e4,!1);if(null==e||(null==e?void 0:e.Status)!=ce.OK||null==(null==e?void 0:e.Data))throw new Error(`Cannot get pending updates! Response is empty or status is not OK. Status: ${null==e?void 0:e.Status}`);switch(e.Data.UpdateStep){case Qg.DownloadingInstaller:case Qg.DownloadingUpdate:return new De(Mg.UpdateAlreadyDownloaded,"Update already downloaded, or donwload in progress.");case Qg.InstallingUpdate:case Qg.PreparingUpdate:return new De(Mg.UpdateAlreadyInstalled,"Update already installed, or installation in progress.");case Qg.UpdateDownloaded:return yield r(e.Data);default:var o=yield s(e.Data);return o!=ce.OK?o:yield r(e.Data)}}}))}getRuntimeInfoAsync(){return sf(this,void 0,void 0,(function*(){try{return yield this._updateProviders.GetSoftwareRuntimeInfoAsync()}catch(e){return e instanceof so&&e.code==zr.Timeout?new De(Mg.CannotGetCurrentControllerVersionTimeout,"Cannot get runtime info (current controller version), timeout error - please restart controller to fix issue."):new De(Mg.CannotGetCurrentControllerVersion,`Cannot get runtime info (current controller version), error: ${e}`)}}))}}rf.ServiceName="UpdatesService";class of{constructor(){this.UpdatedResourceName=new Map,this.CurrentResourceVersion="",this.UpdateType=null,this.ResponseResult=null}}class af{constructor(){this._updateIdentifier="",this._updateResourceName=new Map,this._updateType=null,this._currentResourceVersion="",this._newResourceVersion="",this._updateDescription=new Map,this._updateIsDownloading=!1,this._updateCheckDownloadProgress=0,this._updateCreationTime=null}get UpdateCreationTime(){return this._updateCreationTime}get DownloadProgress(){return this._updateCheckDownloadProgress}get UpdateDescription(){return this._updateDescription}get UpdateIdentifier(){return this._updateIdentifier}get UpdatedResourceName(){return this._updateResourceName}get UpdateType(){return this._updateType}get CurrentResourceVersion(){return this._currentResourceVersion}get NewResourceVersion(){return this._newResourceVersion}get UpdateIsDownloading(){return this._updateIsDownloading}set UpdateCreationTime(e){this._updateCreationTime=e}set DownloadProgress(e){this._updateCheckDownloadProgress=e}set UpdateDescription(e){this._updateDescription=e}set UpdateIdentifier(e){this._updateIdentifier=e}set UpdatedResourceName(e){this._updateResourceName=e}set UpdateType(e){this._updateType=e}set CurrentResourceVersion(e){this._currentResourceVersion=e}set NewResourceVersion(e){this._newResourceVersion=e}set UpdateIsDownloading(e){this._updateIsDownloading=e}}class cf{constructor(){this._updatedResourceName="",this._updateResourceGuid="",this._protocol="",this._protocolGuid="",this._currentResourceVersion="",this._newResourceVersion="",this._isUpdateSafe=!0,this._updateDescription=new Map}get UpdateDescription(){return this._updateDescription}set UpdateDescription(e){this._updateDescription=e}get UpdatedResourceName(){return this._updatedResourceName}get UpdateResourceGuid(){return this._updateResourceGuid}get Protocol(){return this._protocol}get ProtocolGuid(){return this._protocolGuid}get CurrentResourceVersion(){return this._currentResourceVersion}get NewResourceVersion(){return this._newResourceVersion}get IsUpdateSafe(){return this._isUpdateSafe}set UpdatedResourceName(e){this._updatedResourceName=e}set UpdateResourceGuid(e){this._updateResourceGuid=e}set Protocol(e){this._protocol=e}set ProtocolGuid(e){this._protocolGuid=e}set CurrentResourceVersion(e){this._currentResourceVersion=e}set NewResourceVersion(e){this._newResourceVersion=e}set IsUpdateSafe(e){this._isUpdateSafe=e}}class uf extends ae{constructor(e){super(),this.Resource="/updates/update/from/uri",this.Method=ue.Post,this.Data=e}}!function(e){e[e.Windows=0]="Windows",e[e.Linux=1]="Linux",e[e.Unix=2]="Unix",e[e.OSX=3]="OSX",e[e.Android=4]="Android",e[e.iOS=5]="iOS",e[e.WindowsMobile=6]="WindowsMobile"}(Jg||(Jg={})),function(e){e[e.Any=0]="Any",e[e.MIPS=1]="MIPS",e[e.ARM32=2]="ARM32",e[e.ARM64=3]="ARM64",e[e.IntelX86=4]="IntelX86",e[e.IntelX64=5]="IntelX64"}(Yg||(Yg={})),function(e){e[e.Unknown=0]="Unknown",e[e.Environment=1]="Environment",e[e.OperatingSystem=2]="OperatingSystem",e[e.Application=3]="Application",e[e.Extension=4]="Extension",e[e.HardwareFirmware=5]="HardwareFirmware",e[e.Script=6]="Script",e[e.Command=7]="Command"}(Xg||(Xg={})),function(e){e[e.InstallerFileSignCheckFailed=-5]="InstallerFileSignCheckFailed",e[e.UpdateFileSignCheckFailed=-4]="UpdateFileSignCheckFailed",e[e.UpdateInstallationFailed=-3]="UpdateInstallationFailed",e[e.UpdateDownloadFailed=-2]="UpdateDownloadFailed",e[e.UpdateFileCheckFailed=-1]="UpdateFileCheckFailed",e[e.Unknown=0]="Unknown",e[e.DownloadingUpdate=1]="DownloadingUpdate",e[e.CheckingUpdate=2]="CheckingUpdate",e[e.PreparingUpdate=3]="PreparingUpdate",e[e.InstallingUpdate=4]="InstallingUpdate",e[e.DownloadingInstaller=5]="DownloadingInstaller",e[e.UpdateDownloaded=6]="UpdateDownloaded",e[e.OfflineUpdateStep=7]="OfflineUpdateStep"}(Qg||(Qg={}));class lf extends ae{constructor(e){super(),this.Resource="/updates/install/from/url",this.Method=ue.Put,this.Data=e}}class df extends ae{constructor(e){super(),this.Resource="/users/user/login",this.Method=ue.Put,this.Data=e}}class hf extends ae{constructor(e){super(),this.Resource="/controller/runtime/execute",this.Method=ue.Post,this.Data=e}}class pf extends ae{constructor(){super(),this.Resource="/updates/branch",this.Method=ue.Get}}class gf extends ae{constructor(e){super(),this.Resource="/updates/branch",this.Method=ue.Put,this.Data=e}}class ff extends ae{constructor(){super(),this.Resource="/updates/pending",this.Method=ue.Get}}class vf extends ae{constructor(){super(),this.Resource="/updates/check",this.Method=ue.Get}}class mf extends ae{constructor(){super(),this.Resource="/updates/download",this.Method=ue.Post}}class yf extends ae{constructor(){super(),this.Resource="/updates/install",this.Method=ue.Post}}class wf extends ae{constructor(){super(),this.Resource="/updates/download/automatic/status",this.Method=ue.Get}}class Sf extends ae{constructor(){super(),this.Resource="/updates/download/automatic/enable",this.Method=ue.Put}}class Af extends ae{constructor(){super(),this.Resource="/updates/download/automatic/disable",this.Method=ue.Put}}class _f extends ae{constructor(){super(),this.Resource="/updates/history",this.Method=ue.Get}}class Cf extends ae{constructor(){super(),this.Resource="/updates/devices/availability",this.Method=ue.Get}}!function(e){e.CannotFindDevice="CannotFindDevice",e.ResponseTypeNotSupported="ResponseTypeNotSupported",e.InvalidChannelNumber="InvalidChannelNumber",e.IncorrectLimitValue="IncorrectLimitValue",e.IncorrectOffsetValue="IncorrectOffsetValue",e.OtherError="OtherError",e.FatalError="FatalError",e.NoData="NoData",e.FunctionalityNotSupported="FunctionalityNotSupported"}(Zg||(Zg={})),function(e){e[e.None=0]="None",e[e.DataRange=1]="DataRange",e[e.Hour=2]="Hour",e[e.Day=3]="Day",e[e.Week=4]="Week",e[e.Month=5]="Month",e[e.Year=6]="Year"}(ef||(ef={})),function(e){e.Min="Min",e.Max="Max",e.Avg="Avg"}(tf||(tf={}));class Tf{constructor(){this._objectType="Unknown",this._stateInterfaceType="Unknown"}get StateObjectType(){return this._objectType}get StateInterfaceType(){return this._stateInterfaceType}get StateResponseType(){return this._stateInterfaceType}set StateObjectType(e){this._objectType=e}set StateInterfaceType(e){this._stateInterfaceType=e}}!function(e){e[e.Unknown=-1]="Unknown",e[e.PitchBlack=0]="PitchBlack",e[e.VeryDark=1]="VeryDark",e[e.DarkIndoors=2]="DarkIndoors",e[e.DimIndoors=3]="DimIndoors",e[e.NormalIndoors=4]="NormalIndoors",e[e.BrightIndoors=5]="BrightIndoors",e[e.DimOutdoors=6]="DimOutdoors",e[e.CloudyOutdoors=7]="CloudyOutdoors",e[e.DirectSunlight=8]="DirectSunlight"}(nf||(nf={}));var Df,kf,Gf,bf,Nf,Ef,If,Rf=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class Pf{constructor(){this._connection=null,this._connection=Fv.Get(Pt.ServiceName)}GetServiceName(){return Pf.ServiceName}GetStatesByIntervalAsync(e,t,n,s,r,o){return Rf(this,arguments,void 0,(function*(e,t,n,s,r,o,i=!1){var a;try{if(!(yield this.IsFunctionalitySupportedAsync()))return new De(Zg.FunctionalityNotSupported,"State history data is not supported with this version of controller software, update software to get this functionality.");let c;if("string"==typeof e){const t=yield Fv.Get(Fo.ServiceName).GetDevice(e);if(null==t)return new De(Zg.CannotFindDevice,`Device with specified GUID ${e} does not exists.`);c=t}else c=e;if(!c.Channels.any((e=>e.Number==t)))return new De(Zg.InvalidChannelNumber,`Given channel not found in device with guid: ${c.Guid}.`);if(!c.Channels.any((e=>e.Number==t&&e.AvailableResponseTypes.any((e=>e.Type==n)))))return new De(Zg.ResponseTypeNotSupported,"Device or channel not supporting requested DeviceResponseType.");const u=new Uf;u.DeviceGuid=c.Guid,u.DeviceChannel=t,u.Range=s,u.StateInterfaceType=n,u.ReverseOrder=i,u.Limit=r,u.Offset=o;const l=yield null===(a=this._connection)||void 0===a?void 0:a.SendAndWaitForResponseAsync(new Of(u),2e4,!1);if(null==l)return new De(Zg.OtherError,"Cannot get state history data - response is null.");switch(l.Status){case ce.WrongData:switch(l.Data){case"IncorrectLimitValue":return new De(Zg.IncorrectLimitValue,"Cannot get state history data - limit value is incorrect!");case"IncorrectOffsetValue":return new De(Zg.IncorrectOffsetValue,"Cannot get state history data - offset value is incorrect!");case"IncorrectArguments":return new De(Zg.OtherError,"Cannot get state history data - some parameters are incorrect!");default:return new De(Zg.OtherError,"Cannot get state history data - unknown error!")}case ce.FatalError:return new De(Zg.FatalError,"Cannot get state history data - an exception occurred in the controller while reading data!");case ce.ResourceDoesNotExists:return new De(Zg.ResponseTypeNotSupported,"Device or channel not supporting requested DeviceResponseType.");case ce.OK:if(null==l.Data)return new De(Zg.NoData,"Controller responede with status OK, but response does not contain data!");if(l.Data.AggregateDataList=l.Data.AggregateDataList.map((e=>(e.AggregateData=ie(e.AggregateData),e))),n===At.MeasuredEnergy){const e=l.Data.Data.map((e=>{const t=e;return t.Values.MeasurementAveragingParameters=ie(e.Values.MeasurementAveragingParameters),t.Values.MeasurementNonAveragingParmeters=ie(e.Values.MeasurementNonAveragingParmeters),t}));return l.Data.Data=e,l.Data}return l.Data;default:return new De(Zg.OtherError,`Cannot get state history data - controller responded with response code ${l.Status}`)}}catch(e){return new De(Zg.FatalError,`Cannot get state history data - exeption occurs! ${e}`)}}))}GetAvailableStatesAsync(){return Rf(this,void 0,void 0,(function*(){var e;try{const t=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new Mf,12e3,!1);return null==t?new De(Zg.OtherError,"Cannot get available states - response is null."):t.Status!=ce.OK?new De(Zg.OtherError,`Cannot get available states - controller responded with response code ${t.Status}.`):null==t.Data?new De(Zg.NoData,"Cannot get available states - controller responede with status OK, but response does not contain data!"):t.Data.map((e=>{const t=new Tf;return t.StateInterfaceType=e.StateInterfaceType,t.StateObjectType=e.StateObjectType,t}))}catch(e){return new De(Zg.FatalError,`Cannot get available states - exeption occurs! ${e}`)}}))}IsFunctionalitySupportedAsync(){return Rf(this,void 0,void 0,(function*(){return!(parseFloat((yield Fv.Get(Qr.ServiceName).GetSoftwareRuntimeInfoAsync()).SoftwareVersion)<=3.42)}))}GetAvailableStatesPerChannelAsync(e,t){return Rf(this,void 0,void 0,(function*(){var n;let s;if("string"==typeof e){const t=yield Fv.Get(Fo.ServiceName).GetDevice(e);if(null==t)return new De(Zg.CannotFindDevice,`Device with specified GUID ${e} does not exists.`);s=t}else s=e;const r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new xf(new Ff(s.Guid,t)),8e3,!1);if(null==r)return new De(Zg.OtherError,"Cannot get available states - response is null.");switch(r.Status){case ce.ResourceDoesNotExists:switch(r.Data){case"DeviceNotFound":return new De(Zg.CannotFindDevice,"Cannot get available states - device does not exists!");case"ChannelNotFound":return new De(Zg.InvalidChannelNumber,"Cannot get available states - wrong channel!");default:return new De(Zg.OtherError,"Cannot get available states - unknown error!")}case ce.OK:{if(null==r.Data)return new De(Zg.NoData,"Cannot get available states - controller responede with status OK, but response does not contain data!");const e=r.Data.AvailableStates.map((e=>{const t=new Tf;return t.StateInterfaceType=e.StateInterfaceType,t.StateObjectType=e.StateObjectType,t}));return r.Data.AvailableStates=e,r.Data}default:return new De(Zg.OtherError,`Cannot get available states - controller responded with response code ${r.Status}`)}}))}}Pf.ServiceName="StatesHistoryService";class Of extends ae{constructor(e){super(),this.Resource="/statehistory/states/get/last",this.Method=ue.Get,this.Data=e}}class Uf{constructor(){this.DeviceGuid="",this.DeviceChannel=0,this.StateInterfaceType="",this.Range=ef.Day,this.ReverseOrder=!1,this.Limit=0,this.Offset=0}}class Mf extends ae{constructor(){super(),this.Resource="/statehistory/states/available",this.Method=ue.Get}}class xf extends ae{constructor(e){super(),this.Resource="/statehistory/states/available/per/channel",this.Method=ue.Get,this.Data=e}}class Ff{constructor(e,t){this.DeviceGuid=e,this.Channel=t}}(If=Df||(Df={}))[If.User=0]="User",If[If.Controller=1]="Controller",If[If.Marketing=2]="Marketing",(Ef=kf||(kf={}))[Ef.Notification=0]="Notification",Ef[Ef.Message=1]="Message",Ef[Ef.Alarm=2]="Alarm",Ef[Ef.Warning=3]="Warning",Ef[Ef.Info=4]="Info",(Nf=Gf||(Gf={}))[Nf.Other=0]="Other",Nf[Nf.UserLoggedIn=1]="UserLoggedIn",Nf[Nf.UserLoggedOut=2]="UserLoggedOut",Nf[Nf.FoundNewDevice=3]="FoundNewDevice",Nf[Nf.DoorBellPress=4]="DoorBellPress",Nf[Nf.AddedNewDevice=5]="AddedNewDevice",Nf[Nf.RemovedDevice=6]="RemovedDevice",Nf[Nf.RegisteredNewUser=7]="RegisteredNewUser",Nf[Nf.GotAccessToTheInternet=8]="GotAccessToTheInternet",Nf[Nf.LostAccessToTheInternet=9]="LostAccessToTheInternet",Nf[Nf.RemovedUser=10]="RemovedUser",Nf[Nf.NetworkChanged=11]="NetworkChanged",function(e){e.WeatherWidget="WeatherWidget"}(bf||(bf={}));var Lf=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class Bf{constructor(){this._chatSubscriptions=[],this._connection=Fv.Get(Pt.ServiceName),this._connection.SubscribeTo("/homemessaging/notify/message/new",(e=>{const t=e.Data;if(null==t.RecipientUserGuid&&t.MessageType==kf.Message)return;const n=new Wf;n.DateTime=t.DateTime,n.Guid=t.Guid,n.MessageSource=t.MessageSource,n.MessageText=t.MessageText,n.MessageType=t.MessageType,n.RecipientUserGuid=t.RecipientUserGuid?t.RecipientUserGuid:"n/a",n.Sender=t.Sender,n.SenderName=t.SenderName?t.SenderName:"n/a",n.SenderUserGuid=t.SenderUserGuid?t.SenderUserGuid:"n/a",n.TextToSpeechMessage=t.TextToSpeechMessage?t.TextToSpeechMessage:"";for(let[e,s]of Object.entries(t.MessageActions))n.MessageActions.set(bf[e],s);for(let[e,s]of Object.entries(t.MessageActionsData))n.MessageActionsData.set(e,s);this._chatSubscriptions.forEach((e=>{e(n)}))}))}GetCachedMessagesAsync(){return Lf(this,void 0,void 0,(function*(){try{const e=yield this._connection.SendAndWaitForResponseAsync(new $f,12e3,!1);if(null==e)return new De(Zf.OtherError,"Cannot get messages - response is null.");if(e.Status!=ce.OK)return new De(Zf.OtherError,`Cannot get messages - controller responded with response code ${e.Status}.`);if(null==e.Data)return new De(Zf.NoData,"Cannot get messages - controller responded with status OK, but response does not contain data!");const t=[];return e.Data.forEach((e=>{if(null==e.RecipientUserGuid&&e.MessageType==kf.Message)return;const n=new Wf;n.DateTime=e.DateTime,n.Guid=e.Guid,n.MessageSource=e.MessageSource,n.MessageText=e.MessageText,n.MessageType=e.MessageType,n.RecipientUserGuid=e.RecipientUserGuid?e.RecipientUserGuid:"n/a",n.Sender=e.Sender,n.SenderName=e.SenderName?e.SenderName:"n/a",n.SenderUserGuid=e.SenderUserGuid?e.SenderUserGuid:"n/a",n.TextToSpeechMessage=e.TextToSpeechMessage?e.TextToSpeechMessage:"";for(let[t,s]of Object.entries(e.MessageActions))n.MessageActions.set(bf[t],s);for(let[t,s]of Object.entries(e.MessageActionsData))n.MessageActionsData.set(t,s);t.push(n)})),t}catch(e){return new De(Zf.FatalError,`Cannot get messages - exception occurred ${e}`)}}))}SendMessageAsync(e){return Lf(this,void 0,void 0,(function*(){try{const t=yield this._connection.SendAndWaitForResponseAsync(new qf(`recipient:home ${e}`),8e3,!1);return null==t||null==t.Status?ce.FatalError:t.Status}catch(e){return Fv.Get(s.ServiceName).Error(av.ServiceName,`Cannot send message! ${e}`),ce.FatalError}}))}SubscribeToMessages(e){this._chatSubscriptions.push(e)}UnsubscribeFromMessages(e){this._chatSubscriptions&&(this._chatSubscriptions=this._chatSubscriptions.filter((t=>t!==e)))}}class Wf{constructor(){this._sender=Df.Controller,this._messageType=kf.Info,this._messageSource=Gf.Other,this._senderUserGuid="",this._recipientUserGuid="",this._textToSpeechMessage="",this._messageActions=new Map,this._messageActionsData=new Map,this._guid="",this._senderName="",this._messageText="",this._dateTime=(new Date).toDateString()}get Sender(){return this._sender}get MessageType(){return this._messageType}get MessageSource(){return this._messageSource}get SenderUserGuid(){return this._senderUserGuid}get RecipientUserGuid(){return this._recipientUserGuid}get TextToSpeechMessage(){return this._textToSpeechMessage}get MessageActions(){return this._messageActions}get MessageActionsData(){return this._messageActionsData}get Guid(){return this._guid}get SenderName(){return this._senderName}get MessageText(){return this._messageText}get DateTime(){return this._dateTime}set Sender(e){this._sender=e}set MessageType(e){this._messageType=e}set MessageSource(e){this._messageSource=e}set SenderUserGuid(e){this._senderUserGuid=e}set RecipientUserGuid(e){this._recipientUserGuid=e}set TextToSpeechMessage(e){this._textToSpeechMessage=e}set MessageActions(e){this._messageActions=e}set MessageActionsData(e){this._messageActionsData=e}set Guid(e){this._guid=e}set SenderName(e){this._senderName=e}set MessageText(e){this._messageText=e}set DateTime(e){this._dateTime=e}}class $f extends ae{constructor(){super(),this.Resource="/homemessaging/messages",this.Method=ue.Get}}class qf extends ae{constructor(e){super(),this.Resource="/homemessaging/message",this.Method=ue.Put,this.Data=e}}var Vf,Hf,jf,Kf=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class zf{constructor(){this._chatSubscriptions=[],this._connection=Fv.Get(Pt.ServiceName),this._connection.SubscribeTo("/homemessaging/notify/message/new",(e=>{if("/homemessaging/notify/message/new"===e.Resource){const t=e.Data;if(null==t.RecipientUserGuid&&t.MessageType==kf.Message){const e=new Jf;e.DateTime=t.DateTime,e.Guid=t.Guid,e.MessageText=t.MessageText,e.SenderName=t.SenderName?t.SenderName:"n/a",this._chatSubscriptions.forEach((t=>{t(e)}))}}}))}GetCachedMessagesAsync(){return Kf(this,void 0,void 0,(function*(){try{const e=yield this._connection.SendAndWaitForResponseAsync(new Xf,12e3,!1);if(null==e)return new De(Zf.OtherError,"Cannot get messages - response is null.");if(e.Status!=ce.OK)return new De(Zf.OtherError,`Cannot get messages - controller responded with response code ${e.Status}.`);if(null==e.Data)return new De(Zf.NoData,"Cannot get messages - controller responded with status OK, but response does not contain data!");const t=[];return e.Data.forEach((e=>{if(null==e.RecipientUserGuid&&e.MessageType==kf.Message){const n=new Jf;n.DateTime=e.DateTime,n.Guid=e.Guid,n.MessageText=e.MessageText,n.SenderName=e.SenderName?e.SenderName:"n/a",t.push(n)}})),t}catch(e){return new De(Zf.FatalError,`Cannot get messages - exception occurred ${e}`)}}))}SendMessageAsync(e){return Kf(this,void 0,void 0,(function*(){try{const t=yield this._connection.SendAndWaitForResponseAsync(new Yf(e),8e3,!1);return null==t||null==t.Status?ce.FatalError:t.Status}catch(e){return Fv.Get(s.ServiceName).Error(av.ServiceName,`Cannot send message! ${e}`),ce.FatalError}}))}SubscribeToMessages(e){this._chatSubscriptions.push(e)}UnsubscribeFromMessages(e){this._chatSubscriptions&&(this._chatSubscriptions=this._chatSubscriptions.filter((t=>t!==e)))}}class Jf{constructor(){this._guid="",this._senderName="",this._messageText="",this._dateTime=""}get Guid(){return this._guid}get SenderName(){return this._senderName}get MessageText(){return this._messageText}get DateTime(){return this._dateTime}set Guid(e){this._guid=e}set SenderName(e){this._senderName=e}set MessageText(e){this._messageText=e}set DateTime(e){this._dateTime=e}}class Yf extends ae{constructor(e){super(),this.Resource="/homemessaging/message",this.Method=ue.Put,this.Data=e}}class Xf extends ae{constructor(){super(),this.Resource="/homemessaging/messages",this.Method=ue.Get}}!function(e){e[e.None=0]="None",e[e.ChangeDeviceState=1]="ChangeDeviceState"}(Vf||(Vf={})),function(e){e.GPT3_5_TURBO="gpt-3.5-turbo",e.GPT3_5_TURBO_16K="gpt-3.5-turbo-16k",e.GPT4="gpt-4"}(Hf||(Hf={})),function(e){e[e.UnknownError=0]="UnknownError",e[e.ChatNotConfigured=1]="ChatNotConfigured",e[e.MessageNotSend=2]="MessageNotSend",e[e.InvalidMessageResponseFormat=3]="InvalidMessageResponseFormat"}(jf||(jf={}));var Qf,Zf,ev,tv=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class nv{constructor(){this._chatSubscriptions=[],this._connection=Fv.Get(Pt.ServiceName),this._connection.SubscribeTo("/homemessaging/gpt/notify/message/new",(e=>{const t=e.Data,n=new iv;if(n.DateTime=t.DateTime,n.Guid=t.Guid,n.MessageText=t.MessageText?t.MessageText:"",n.SenderName=t.SenderName?t.SenderName:"n/a",null!=t.ControllerActivities)for(let[e,s]of Object.entries(t.ControllerActivities)){const t=Vf[e],r=new Map;for(let[e,t]of Object.entries(s))r.set(e,t);n.ControllerActivities.set(t,r)}if(null!=t.Errors)for(let[e,s]of Object.entries(t.Errors))n.Errors.set(jf[e],s);this._chatSubscriptions.forEach((e=>{e(n)}))}))}IsGptChatAvailableAsync(){return tv(this,void 0,void 0,(function*(){return(yield Fv.Get(Ze.ServiceName).GetExtensionsInfoAsync()).any((e=>"80daeab9-104f-4c1b-9464-61f5fc9bf2bf"==e.ExtensionGuid))}))}GetChatConfigurationAsync(){return tv(this,void 0,void 0,(function*(){try{const e=yield this._connection.SendAndWaitForResponseAsync(new rv,8e3,!1);return null==e||null==e.Status?new De(Zf.FatalError,"Cannot get chat configuration! No data in result"):e.Status!=ce.OK?new De(Zf.Error,`Cannot get chat configuration! Controller responded with code: ${e.Status}`):null==e.Data?new De(Zf.NoData,"Cannot get chat configuration! Controller responded with success, but no data in response!"):e.Data}catch(e){return new De(Zf.FatalError,`Cannot get chat configuration! ${e}`)}}))}SetChatConfigurationAsync(e){return tv(this,void 0,void 0,(function*(){try{const t=yield this._connection.SendAndWaitForResponseAsync(new ov(e),8e3,!1);return null==t||null==t.Status?ce.FatalError:t.Status}catch(e){return Fv.Get(s.ServiceName).Error(av.ServiceName,`Cannot set chat configuration! ${e}`),ce.FatalError}}))}SendMessageAsync(e){return tv(this,void 0,void 0,(function*(){try{const t=yield this._connection.SendAndWaitForResponseAsync(new sv(e),8e3,!1);return null==t||null==t.Status?ce.FatalError:t.Status}catch(e){return Fv.Get(s.ServiceName).Error(av.ServiceName,`Cannot send message! ${e}`),ce.FatalError}}))}SubscribeToMessages(e){var t;null===(t=this._chatSubscriptions)||void 0===t||t.push(e)}UnsubscribeFromMessages(e){this._chatSubscriptions&&(this._chatSubscriptions=this._chatSubscriptions.filter((t=>t!==e)))}}class sv extends ae{constructor(e){super(),this.Resource="/homemessaging/gpt/message",this.Method=ue.Put,this.Data=e}}class rv extends ae{constructor(){super(),this.Resource="/homemessaging/gpt/configuration",this.Method=ue.Get}}class ov extends ae{constructor(e){super(),this.Resource="/homemessaging/gpt/configuration",this.Method=ue.Put,this.Data=e}}class iv{constructor(){this._messageActions=new Map,this._errors=new Map,this._guid="",this._senderName="",this._messageText="",this._dateTime=""}get ControllerActivities(){return this._messageActions}get Errors(){return this._errors}get Guid(){return this._guid}get SenderName(){return this._senderName}get MessageText(){return this._messageText}get DateTime(){return this._dateTime}set ControllerActivities(e){this._messageActions=e}set Errors(e){this._errors=e}set Guid(e){this._guid=e}set SenderName(e){this._senderName=e}set MessageText(e){this._messageText=e}set DateTime(e){this._dateTime=e}}!function(e){e[e.ControllerChat=0]="ControllerChat",e[e.FamilyChat=1]="FamilyChat",e[e.GptChat=2]="GptChat"}(Qf||(Qf={}));class av{constructor(){this._services={ControllerChat:new Bf,GptChat:new nv,FamillyChat:new zf}}GetServiceName(){return av.ServiceName}GetChatImplementation(e){switch(e){case Qf.ControllerChat:return this._services.ControllerChat;case Qf.FamilyChat:return this._services.FamillyChat;case Qf.GptChat:return this._services.GptChat;default:throw new cv(`Chat with type ${e} not implemented!`)}}}av.ServiceName="ChatService",function(e){e.OtherError="OtherError",e.FatalError="FatalError",e.Error="Error",e.NoData="NoData"}(Zf||(Zf={}));class cv extends Error{constructor(e){super(e),this.message=e,this.name="ChatNotImplementedException"}}!function(e){e[e.ResourceIsNotAvailable=-11]="ResourceIsNotAvailable",e[e.AnotherAppWithGivenAccessTokenAlreadyExists=-10]="AnotherAppWithGivenAccessTokenAlreadyExists",e[e.AppGuidDoesNotExists=-7]="AppGuidDoesNotExists",e[e.AppUrlToShort=-6]="AppUrlToShort",e[e.AppUserNameToShort=-5]="AppUserNameToShort",e[e.AppUserIdToShort=-4]="AppUserIdToShort",e[e.AccessTokenToShort=-3]="AccessTokenToShort",e[e.AppNameToShort=-2]="AppNameToShort",e[e.UnkownError=0]="UnkownError",e[e.Changed=1]="Changed"}(ev||(ev={}));var uv=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class lv{constructor(){this._connection=Fv.Get(Pt.ServiceName),this._log=Fv.Get(s.ServiceName)}GetServiceName(){return lv.ServiceName}IsSupportedAsync(){return uv(this,void 0,void 0,(function*(){let e=yield this._connection.SendAndWaitForResponseAsync(new dv,2e3,!0);return this._log.Debug(lv.ServiceName,`IsSupportedAsync: ${null==e?void 0:e.Status} resp: ${JSON.stringify(e)}`),null!=e&&e.Status==ce.WrongData}))}GetConnectedAppsAsync(){return uv(this,void 0,void 0,(function*(){let e=yield this._connection.SendAndWaitForResponseAsync(new hv,2e3,!0);return(null==e?void 0:e.Status)===ce.OK?null==e?void 0:e.Data:null==e?void 0:e.Status}))}UpsertConnectedAppAsync(e){return uv(this,void 0,void 0,(function*(){let t=yield this._connection.SendAndWaitForResponseAsync(new gv(e),2e3,!1);switch(null==t?void 0:t.Status){case ce.OK:return new De(ev.Changed,"");case ce.WrongData:switch(t.Data){case"AccessTokenToShort":return new De(ev.AccessTokenToShort,t.Data);case"AnotherAppWithGivenAccessTokenAlreadyExists":return new De(ev.AnotherAppWithGivenAccessTokenAlreadyExists,t.Data);case"AppGuidDoesNotExists":return new De(ev.AppGuidDoesNotExists,t.Data);case"AppNameToShort":return new De(ev.AppNameToShort,t.Data);case"AppUrlToShort":return new De(ev.AppUrlToShort,t.Data);case"AppUserIdToShort":return new De(ev.AppUserIdToShort,t.Data);case"AppUserNameToShort":return new De(ev.AppUserNameToShort,t.Data);default:return new De(ev.UnkownError,t.Data)}case ce.ResourceDoesNotExists:case ce.ResourceIsNotAvailable:return new De(ev.ResourceIsNotAvailable,t.Data);default:return new De(ev.UnkownError,t.Data)}}))}RemoveConnectedAppAsync(e){return uv(this,void 0,void 0,(function*(){let t=yield this._connection.SendAndWaitForResponseAsync(new pv(e.Guid),2e3,!0);return null==t?void 0:t.Status}))}}lv.ServiceName="ConnectedAppsService";class dv extends ae{constructor(){super(),this.Resource="/applications/app/auth",this.Method=ue.Put,this.Data=""}}class hv extends ae{constructor(){super(),this.Resource="/applications/get",this.Method=ue.Get}}class pv extends ae{constructor(e){super(),this.Resource="/applications/app/delete",this.Method=ue.Delete,this.Data=e}}class gv extends ae{constructor(e){super(),this.Resource="/applications/app/upsert",this.Method=ue.Put,this.Data=e}}var fv=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class vv{constructor(){try{const e=window.location.href,t=new URL(e),n=new URLSearchParams(t.search),s=n.get("mig_c_enc"),r=n.get("mig_controllers"),o=n.get("mig_lang");if(null!==s){const e=decodeURIComponent(this.b64DecodeUnicode(decodeURIComponent(s)));localStorage.setItem(vv.AppUserControllersKeyName,e)}null!==r&&localStorage.setItem(vv.AppUserControllersKeyName,decodeURIComponent(r)),null!==o&&localStorage.setItem(vv.AppSelectedLanguageKeyName,o)}catch(e){console.error(e)}}waitForNavigatorObject(e){return new Promise(((t,n)=>{setTimeout((()=>{n(new Error(`Timed out waiting for navigator.${e}`))}),1e4),function n(){navigator[e]?t(navigator[e]):requestAnimationFrame(n)}()}))}b64DecodeUnicode(e){return decodeURIComponent(Array.prototype.map.call(atob(e),(function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)})).join(""))}decodeUriJsonData(e){return JSON.parse(decodeURIComponent(e))}encodeUriJsonData(e){return encodeURIComponent(JSON.stringify(e))}IsExalusNativeMigrationAvailable(){return void 0!==navigator.exalusMigration}GetServiceName(){return vv.ServiceName}IsMigrationDataAvailableAsync(){return fv(this,void 0,void 0,(function*(){try{if(null!=window.webkit&&null!=window.webkit.messageHandlers){var e=yield vv.GetIosMigrationStatus();return null!==e&&e}if(!navigator.userAgent.endsWith("LavvaAndroidNative")||void 0!==navigator.exalusMigration&&null!==navigator.exalusMigration||(yield this.waitForNavigatorObject("exalusMigration")),this.IsExalusNativeMigrationAvailable()){let e=yield navigator.exalusMigration.IsMigrationDataAvailableAsync();return null!=e&&e.DataMigrated}return null!==localStorage.getItem(vv.AppSelectedLanguageKeyName)||null!==localStorage.getItem(vv.AppUserControllersKeyName)}catch(e){return console.error(e),!1}}))}GetControllersDataAsync(){return fv(this,void 0,void 0,(function*(){try{if(null!=window.webkit&&null!=window.webkit.messageHandlers){let e=yield vv.GetIosControllerList();return void 0===e?null:e}{if(this.IsExalusNativeMigrationAvailable()){let e=yield navigator.exalusMigration.GetControllersDataAsync();return void 0===e?null:e}let e=localStorage.getItem(vv.AppUserControllersKeyName);return null!==e?JSON.parse(e):null}}catch(e){return console.error(e),null}}))}GetLanguageCodeAsync(){return fv(this,void 0,void 0,(function*(){try{if(null!=window.webkit&&null!=window.webkit.messageHandlers){let e=yield vv.GetIosDefaultLanguage();return void 0===e?null:e}{if(this.IsExalusNativeMigrationAvailable()){let e=yield navigator.exalusMigration.GetLanguageCodeAsync();return void 0===e?null:e}let e=localStorage.getItem(vv.AppSelectedLanguageKeyName);return null!=e?e:null}}catch(e){return console.error(e),null}}))}static GetIosMigrationStatus(e=8e3){let t;return new Promise(((n,s)=>{t=setTimeout((()=>{s(null)}),e);try{window.nativeEvent.exalusControllerData.isMigrationAvaliable=e=>{clearTimeout(t),n(e)},window.webkit.messageHandlers.exalusControllerData.postMessage("IsMigrationAvaliable")}catch(e){s(e)}}))}static GetIosControllerList(e=8e3){let t;return new Promise(((n,s)=>{t=setTimeout((()=>{s(null)}),e);try{window.nativeEvent.exalusControllerData.handleControllers=e=>{clearTimeout(t),n(e)},window.webkit.messageHandlers.exalusControllerData.postMessage("GetControllers")}catch(e){s(e)}}))}static GetIosDefaultLanguage(e=8e3){let t;return new Promise(((n,s)=>{t=setTimeout((()=>{s(null)}),e);try{window.nativeEvent.exalusControllerData.handleLanguage=e=>{clearTimeout(t),n(e)},window.webkit.messageHandlers.exalusControllerData.postMessage("GetDefaultLanguage")}catch(e){s(e)}}))}}vv.AppSelectedLanguageKeyName="App___SelectedLanguage",vv.AppUserControllersKeyName="App___UserControllersListDatabase",vv.ServiceName="DataMigrationService";var mv=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class yv{constructor(){this._localIpAddress=null,this._publicIpAddress=null,this._gatewayIpAddress=null,this._macAddress=null,this._isInLocalNetwork=!1,this.nativeFindControllerApi=null,void 0!==navigator.findEfcController&&(this.nativeFindControllerApi=navigator.findEfcController),this._connection=Fv.Get(Pt.ServiceName),this._logger=Fv.Get(s.ServiceName),this._storage=Fv.Get(o.ServiceName),Fv.Get(Ke.ServiceName).OnUserLoggedInEvent().Subscribe((e=>mv(this,void 0,void 0,(function*(){var e;try{const t=yield this.GetControllerNetworkConfigurationAsync();if(null!=t){this._localIpAddress=t.LocalIPv4,this._publicIpAddress=t.PublicIPv4,this._gatewayIpAddress=t.GatewayIPv4,this._macAddress=t.MAC,this._storage.Save(yv.ServiceName,"LocalIpAddress",this._localIpAddress);const n=this.GetControllerHostName(this._connection.GetControllerSerialNumber());this._logger.Debug(`Looking for controller in local network with host name: ${n}`);let s=null;this.isIos()?s=yield this.getIosControllerIpAsync(n):null!==this.nativeFindControllerApi&&(s=yield null===(e=this.nativeFindControllerApi)||void 0===e?void 0:e.FindControllerAsync(n)),null!=s&&""!=s?(this._isInLocalNetwork=!0,this._logger.Debug(yv.ServiceName,`Controller found in local network with ip address: ${s}`)):(this._isInLocalNetwork=!1,this._logger.Debug(yv.ServiceName,"Controller not found in local network."))}else this._logger.Error(yv.ServiceName,"Failed to get network configuration data.")}catch(e){this._logger.Error(yv.ServiceName,`Failed to get network configuration data - ${e}`)}}))))}FindControllerInLocalNetworkAsync(e){return mv(this,void 0,void 0,(function*(){if(this.isIos()){const t=yield this.getIosControllerIpAsync(e);return""==t?null:t}return null!==this.nativeFindControllerApi?this.nativeFindControllerApi.FindControllerAsync(e):Promise.resolve(null)}))}GetLastKnownControllerLocalIpAddress(){return null!==this._localIpAddress?this._localIpAddress:this._storage.Read(yv.ServiceName,"LocalIpAddress")}GetControllerHostName(e){return`ExalusTR7-${e}`}GetMdnsHostName(){return`ExalusTR7-${this.GetControllerHostName(this._connection.GetControllerSerialNumber())}.local`.toLowerCase()}GetControllerNetworkConfigurationAsync(){return mv(this,void 0,void 0,(function*(){var e;const t=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new wv,2e4,!1);return null==t||null==t.Status||null==t.Data?(this._logger.Error(yv.ServiceName,"Failed to get network configuration data - unknow error."),null):t.Data}))}GetServiceName(){return yv.ServiceName}isIos(){return null!=window.webkit&&null!=window.webkit.messageHandlers}getIosControllerIpAsync(e,t=2e4){let n;return new Promise(((s,r)=>{n=setTimeout((()=>{this._logger.Error("Cannot find controller in local network, timeout!"),s("")}),t);try{window.nativeEvent.exalusFindController.handleFindController=e=>{clearTimeout(n),s(e)},window.webkit.messageHandlers.exalusFindController.postMessage(e)}catch(e){this._logger.Error(`Cannot find controller in local network, error: ${e}`),s("")}}))}}yv.ServiceName="FindControllerService";class wv extends ae{constructor(){super(),this.Resource="/network/lan/",this.Method=ue.Get}}var Sv=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class Av{constructor(){this._errorOccuredEvent=new n,this._connectionStateChangedEvent=new n,this._dataReceivedEvent=new n,this._onMessageReceived=new n,this._log=Fv.Get(s.ServiceName),this._controllerConfiguration=null,this._cache=null,this._session=null,this._logPackets=!1,this.sockets=null,this._address=null,this._port="81",this._isOpen=!1,this._pin=null,this._serial=null,this._auth=null,this._initialized=!1}Initialize(){this._initialized||(this._initialized=!0,this._controllerConfiguration=Fv.Get(rt.ServiceName),this._cache=Fv.Get(Ge.ServiceName),this._session=Fv.Get(Ke.ServiceName))}checkIfAuthInfoIsCorrectAsync(e){return Sv(this,void 0,void 0,(function*(){const t=`http://${window.location.hostname}/controller_info`;let n=yield fetch(t,{method:"GET"});return!!n.ok&&(yield n.text())===`${e.SerialNumber}:${e.PIN}`}))}SubscribeTo(e,t){let n=n=>{n.Resource===e&&t(n)};return this.OnDataReceivedEvent().Subscribe(n),()=>this.OnDataReceivedEvent().Unsubscribe(n)}SetServersBrokerAddress(e){throw new Error("Method not implemented.")}SetDefaultPacketsBrokerAddress(e){throw new Error("Method not implemented.")}GetServerAddressAsync(){return Fv.IsRunningFromLocalNetwork()&&(this._address=`${window.location.hostname}:${this._port}`),Promise.resolve(this._address)}ConnectAsync(e){var t;return this.Initialize(),null===(t=this.sockets)||void 0===t||t.close(),this.sockets=new WebSocket(`ws://${e}/api`),this._log.Debug(Av.ServiceName,`Connecting to the WebSockets server ${e}`),this.sockets.onerror=t=>{this._log.Debug(Av.ServiceName,`Error occured in the WebSockets server ${e}: ${t}`),this._errorOccuredEvent.Invoke(["WebSockets",t.toString()])},this.sockets.onopen=t=>{this._log.Debug(Av.ServiceName,`Connected to the WebSockets server ${e}`),this._isOpen=!0,this._connectionStateChangedEvent.Invoke(he.Connected)},this.sockets.onclose=t=>{this._log.Debug(Av.ServiceName,`Disconnected from the WebSockets server ${e}`),this._isOpen=!1,this._connectionStateChangedEvent.Invoke(he.Disconnected)},this.sockets.onmessage=t=>{this._log.Debug(Av.ServiceName,`Message received from the WebSockets server ${e}: ${t.data}`),this._onMessageReceived.Invoke(t.data);let n=JSON.parse(t.data);this._log.Debug(Av.ServiceName,`Received data frame: ${n.Status}`),this._dataReceivedEvent.Invoke(n)},this._connectionStateChangedEvent.Invoke(he.Connecting),Promise.resolve(de.Connected)}AuthorizeAsync(e){return Sv(this,void 0,void 0,(function*(){return!!(yield this.checkIfAuthInfoIsCorrectAsync(e))&&(this._log.Debug(Av.ServiceName,`Authorization successful for controller ${e.SerialNumber}`),this._pin=e.PIN,this._serial=e.SerialNumber,this._auth=e,!0)}))}ConnectAndAuthorizeAsync(e){return Sv(this,void 0,void 0,(function*(){if(this._log.Debug(Av.ServiceName,`Connecting and authorizing to the controller ${e.SerialNumber}`),!(yield this.AuthorizeAsync(e)))return de.AuthorizationFailed;let t=yield this.GetServerAddressAsync();return null==t?de.FailedToConnectToServer:yield this.ConnectAsync(t)}))}DisconnectAsync(){var e;return this._log.Debug(Av.ServiceName,`Disconnecting from the WebSockets server ${this._address}`),this._connectionStateChangedEvent.Invoke(he.Disconnecting),null===(e=this.sockets)||void 0===e||e.close(),Promise.resolve()}IsConnected(){return this._isOpen}EnablePacketsLogging(){this._log.Debug(Av.ServiceName,"Packets logging enabled"),this._logPackets=!0}DisablePacketsLogging(){this._log.Debug(Av.ServiceName,"Packets logging disabled"),this._logPackets=!1}SendData(e,t){var n;let s=JSON.stringify(e);return t&&this._log.Debug(Av.ServiceName,`Sending data frame: ${s}`),this._isOpen?null===(n=this.sockets)||void 0===n||n.send(s):this._log.Error(Av.ServiceName,`Failed to send data frame: ${s}`),Promise.resolve(this._isOpen)}SendAsync(e){return this._isOpen&&this.SendData(e,this._logPackets),Promise.resolve(this._isOpen)}SendAndWaitForResponseAsync(e,t,n,s=!0){return this.SendAndWaitForResponseWithRepeatAsync(e,t,n,s)}SendAndHandleResponseAsync(e,t,n,s){return Sv(this,void 0,void 0,(function*(){var r;let o=0;const i=Date.now();if(!this.IsConnected())throw new Error("Connection is not established");return"/users/user/login"!==e.Resource&&(yield null===(r=this._session)||void 0===r?void 0:r.WaitForSessionCreationAsync()),new Promise(((r,a)=>Sv(this,void 0,void 0,(function*(){const c=()=>window.setTimeout((()=>{this._dataReceivedEvent.Unsubscribe(u);let t=`Response timeout, resource: ${e.Resource} method: ${e.Method} transaction id: ${e.TransactionId}`;this._log.Error(Av.ServiceName,t),a(new Error(t))}),t);let u=l=>Sv(this,void 0,void 0,(function*(){var d,h,p;if((null==l?void 0:l.TransactionId)==e.TransactionId){window.clearTimeout(o);const g=Date.now()-i;switch((s||!0===window.packets)&&this._log.Debug(Av.ServiceName,`Received response for: ${null==l?void 0:l.Resource} ${null==l?void 0:l.Method} id: ${null==l?void 0:l.TransactionId} in ${g}ms`),(null==l?void 0:l.Status)===ce.UserIsNotLoggedIn&&(this._dataReceivedEvent.Unsubscribe(u),(null===(d=this._session)||void 0===d?void 0:d.OnUserLoggedOutEvent()).Invoke(null===(h=this._session)||void 0===h?void 0:h.User),yield null===(p=this._session)||void 0===p?void 0:p.RestoreSessionAsync(),r(yield this.SendAndHandleResponseAsync(e,t,n,s))),null==l?void 0:l.Status){case ce.MultiDataResponseStart:case ce.MultiDataResponse:n(l),o=c();break;case ce.MultiDataResponseStop:n(l),this._dataReceivedEvent.Unsubscribe(u),r();break;default:let t=`Failed to process MultiDataResponse - recived incorrect response status: ${null==l?void 0:l.Status} method: ${e.Method} transaction id: ${e.TransactionId}\n make sure that the requested endpoint uses MultiDataResponse, otherwise use SendAndWaitForResponseAsync<T> method.`;a(new Error(t))}}}));if(this._dataReceivedEvent.Subscribe(u),o=c(),!this.SendData(e,s)){let t=`Failed to send request, resource: ${e.Resource} method: ${e.Method} transaction id: ${e.TransactionId}`;a(new Error(t))}}))))}))}SendAndWaitForResponseWithRepeatAsync(e,t,n){return Sv(this,arguments,void 0,(function*(e,t,n,s=!0,r=!0){var o,i,a;if(e.Method===ue.Get&&n&&!(yield null===(o=this._controllerConfiguration)||void 0===o?void 0:o.DidCofigurationChangeAsync())){let t=null===(i=this._cache)||void 0===i?void 0:i.GetCache(e);if(null!==t)return Promise.resolve(t)}let c=0;const u=Date.now();if(!this.IsConnected())throw new Error("Connection is not established");return"/users/user/login"!==e.Resource&&(yield null===(a=this._session)||void 0===a?void 0:a.WaitForSessionCreationAsync()),new Promise(((o,i)=>Sv(this,void 0,void 0,(function*(){let a=i=>Sv(this,void 0,void 0,(function*(){var l,d,h,p;if((null==i?void 0:i.TransactionId)==e.TransactionId){window.clearTimeout(c),this._dataReceivedEvent.Unsubscribe(a);const g=Date.now()-u;r&&this._log.Debug(Av.ServiceName,`Received response for: ${null==i?void 0:i.Resource} ${null==i?void 0:i.Method} id: ${null==i?void 0:i.TransactionId} in ${g}ms`),e.Method===ue.Get&&n&&(null===(l=this._cache)||void 0===l||l.Cache(i)),!n&&(null==i?void 0:i.Status)===ce.UserIsNotLoggedIn&&s&&((null===(d=this._session)||void 0===d?void 0:d.OnUserLoggedOutEvent()).Invoke(null===(h=this._session)||void 0===h?void 0:h.User),yield null===(p=this._session)||void 0===p?void 0:p.RestoreSessionAsync(),o(yield this.SendAndWaitForResponseWithRepeatAsync(e,t,n,!1,r))),o(i)}}));if(this._dataReceivedEvent.Subscribe(a),c=window.setTimeout((()=>{this._dataReceivedEvent.Unsubscribe(a);let t=`Response timeout, resource: ${e.Resource} method: ${e.Method} transaction id: ${e.TransactionId}`;this._log.Error(Av.ServiceName,t),i(new Error(t))}),t),!this.SendData(e,r)){let t=`Failed to send request, resource: ${e.Resource} method: ${e.Method} transaction id: ${e.TransactionId}`;i(new Error(t))}}))))}))}OnDataReceivedEvent(){return this._dataReceivedEvent}OnErrorOccuredEvent(){return this._errorOccuredEvent}OnConnectionStateChangedEvent(){return this._connectionStateChangedEvent}GetAuthorizationInfo(){return this._auth}GetServiceName(){return Av.ServiceName}}Av.ServiceName="ExalusConnectionService";class _v{constructor(){var e,t;this.OnEnteredPictureInPicture=new Ce,this.OnExitedPictureInPicture=new Ce,this._nativeApi=null,this.IsSupported()?(this._nativeApi=navigator.pip,null===(e=this._nativeApi)||void 0===e||e.OnEnteredPictureInPicture.Subscribe((()=>this.OnEnteredPictureInPicture.Invoke())),null===(t=this._nativeApi)||void 0===t||t.OnExitedPictureInPicture.Subscribe((()=>this.OnExitedPictureInPicture.Invoke()))):navigator.pip=null}IsSupported(){return void 0!==navigator.pip&&null!==navigator.pip}RequestPictureInPictureAsync(){return this.IsSupported()?this._nativeApi.RequestPictureInPictureAsync():Promise.resolve(!1)}GetServiceName(){return _v.ServiceName}}_v.ServiceName="PictureInPictureService";var Cv,Tv,Dv;class kv{GetServiceName(){return kv.ServiceName}GetSupportedDevicesAsync(){return e=this,t=void 0,s=function*(){let e=yield fetch("https://updates.tr7.pl/supportedDevices/pl-PL.json",{method:"GET"});if(e.ok)return JSON.parse(yield e.text());throw new Error("Failed to download supported devices list!")},new((n=void 0)||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}));var e,t,n,s}}kv.ServiceName="SupportedDevicesService",(Dv=Cv||(Cv={}))[Dv.Unknown=-1]="Unknown",Dv[Dv.Web=0]="Web",Dv[Dv.Android=1]="Android",Dv[Dv.iOS=2]="iOS";class Gv{constructor(){this.ClientName="",this.LavvaUserName="",this.ClientType=Cv.Unknown,this.TokenGuid="",this.RegistrationDate=new Date}}!function(e){e.FeatureUnsupported="FeatureUnsupported",e.UnknownError="UnknownError",e.NoData="NoData",e.IncorrectGuid="IncorrectGuid",e.IdentityIsEmpty="IdentityIsEmpty",e.DeviceTokenIsEmpty="DeviceTokenIsEmpty",e.ClientNameIsEmpty="ClientNameIsEmpty",e.LavvaUserNameIsEmpty="LavvaUserNameIsEmpty",e.TokenNotFound="TokenNotFound"}(Tv||(Tv={}));var bv=function(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((s=s.apply(e,t||[])).next())}))};class Nv{constructor(){this._connection=Fv.Get(Pt.ServiceName),this._logger=Fv.Get(s.ServiceName)}GetServiceName(){return Nv.ServiceName}RegisterNotificationsClientAsync(e){return bv(this,void 0,void 0,(function*(){var t;try{const n=new Ev({ClientName:e.ClientName,DeviceToken:e.DeviceToken,LavvaUserName:e.LavvaUserName,ClientType:this.getClientType(),NotificationsEnabledForToken:e.EnableNotifications}),s=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(n,8e3,!1);if(null==s||null==s.Status)return new De(Tv.UnknownError,"Cannot register notifications client - unknown error!");switch(s.Status){case ce.WrongData:{const e=this.isValidErrorCode(s.Data)?s.Data:Tv.UnknownError;return new De(e,"Cannot register notifications client - wrong data!")}case ce.ResourceDoesNotExists:return new De(Tv.FeatureUnsupported,"Notifications feature not supported in controller!");case ce.OK:return"string"==typeof s.Data?s.Data:new De(Tv.NoData,"Cannot register notifications client - result status is OK, but no token guid presented in paylode, unknown error!");default:return new De(Tv.UnknownError,"Cannot register notifications client - unknown error!")}}catch(e){return new De(Tv.UnknownError,`Cannot register notifications client - error: ${e}`)}}))}UpdateNotificationsClientAsync(e,t){return bv(this,void 0,void 0,(function*(){var n;try{const s=new Iv({ClientName:t.ClientName,DeviceToken:t.DeviceToken,LavvaUserName:t.LavvaUserName,ClientType:this.getClientType(),NotificationsEnabledForToken:t.EnableNotifications,Guid:e}),r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(s,8e3,!1);if(null==r||null==r.Status)return new De(Tv.UnknownError,"Cannot update notifications client - unknown error!");switch(r.Status){case ce.WrongData:{const e=this.isValidErrorCode(r.Data)?r.Data:Tv.UnknownError;return new De(e,"Cannot update notifications client - wrong data!")}case ce.ResourceDoesNotExists:return new De(Tv.FeatureUnsupported,"Notifications feature not supported in controller!");case ce.OK:return"string"==typeof r.Data?r.Data==e?ce.OK:new De(Tv.UnknownError,`Cannot update notifications client - result status is OK, but token guid is different! request guid ${e}, response guid: ${r.Data}`):new De(Tv.NoData,"Cannot update notifications client - result status is OK, but no token guid presented in paylode, unknown error!");default:return new De(Tv.UnknownError,"Cannot update notifications client - unknown error!")}}catch(e){return this._logger.Error(`Cannot update notifications client - error: ${e}`),new De(Tv.UnknownError,`Cannot update notifications client - error: ${e}`)}}))}GetRegisteredNotificationsClientsMetadataAsync(){return bv(this,void 0,void 0,(function*(){var e;try{const t=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new Rv,8e3,!1);return null==t||null==t.Status?new De(Tv.UnknownError,"Cannot get notifications clients metadata - unknown error!"):t.Status==ce.ResourceDoesNotExists?new De(Tv.FeatureUnsupported,"Notifications feature not supported in controller!"):t.Status!=ce.OK?new De(Tv.UnknownError,`Cannot get notifications clients metadata - response status: ${t.Status}}`):null==t.Data?new De(Tv.NoData,"Cannot get notifications clients metadata - response status is OK, but no data!"):t.Data.map((e=>{const t=new Gv;return t.ClientName=e.ClientName,t.LavvaUserName=e.LavvaUserName,t.ClientType=e.ClientType,t.TokenGuid=e.TokenGuid,t.RegistrationDate=new Date(e.RegistrationDate),t}))}catch(e){return this._logger.Error(`Cannot get notifications clients metadata - error: ${e}`),new De(Tv.UnknownError,`Cannot get notifications clients metadata - error: ${e}`)}}))}IsNotifiacationsEnabledAsync(e){return bv(this,void 0,void 0,(function*(){var t;try{const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Pv(e),8e3,!1);if(null==n||null==n.Status)return new De(Tv.UnknownError,"Cannot get notifications status - unknown error!");switch(n.Status){case ce.ResourceDoesNotExists:if(null==n.Data)return new De(Tv.FeatureUnsupported,"Notifications feature not supported in controller!");{const e=this.isValidErrorCode(n.Data)?n.Data:Tv.UnknownError;return new De(e,"Cannot get notifications status - resource not exists!")}case ce.OK:return"boolean"==typeof n.Data?n.Data:new De(Tv.NoData,"Cannot get notifications status - result status is OK, but no data, or data type is wrong!");default:return new De(Tv.UnknownError,`Cannot get notifications - response code ${n.Status}}!`)}}catch(e){return this._logger.Error(`Cannot get notifications status - error: ${e}`),new De(Tv.UnknownError,`Cannot get notifications status - error: ${e}`)}}))}EnableNotificationsAsync(e){return bv(this,void 0,void 0,(function*(){var t;try{let n=null;null!=e&&""!=e&&(n=e);const s=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Ov(n),8e3,!1);if(null==s||null==s.Status)return new De(Tv.UnknownError,"Cannot enable notifications - unknown error!");switch(s.Status){case ce.ResourceDoesNotExists:if(null==s.Data)return new De(Tv.FeatureUnsupported,"Notifications feature not supported in controller!");{const e=this.isValidErrorCode(s.Data)?s.Data:Tv.UnknownError;return new De(e,"Cannot enable notifications - resource not exists!")}case ce.OK:return ce.OK;default:return new De(Tv.UnknownError,`Cannot enable notifications - response code ${s.Status}}!`)}}catch(e){return this._logger.Error(`Cannot enable notifications - error: ${e}`),new De(Tv.UnknownError,`Cannot enable notifications - error: ${e}`)}}))}DisableNotificationsAsync(e){return bv(this,void 0,void 0,(function*(){var t;try{let n=null;null!=e&&""!=e&&(n=e);const s=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Uv(n),8e3,!1);if(null==s||null==s.Status)return new De(Tv.UnknownError,"Cannot disable notifications - unknown error!");switch(s.Status){case ce.ResourceDoesNotExists:if(null==s.Data)return new De(Tv.FeatureUnsupported,"Notifications feature not supported in controller!");{const e=this.isValidErrorCode(s.Data)?s.Data:Tv.UnknownError;return new De(e,"Cannot disable notifications - resource not exists!")}case ce.OK:return ce.OK;default:return new De(Tv.UnknownError,`Cannot disable notifications - response code ${s.Status}!`)}}catch(e){return this._logger.Error(`Cannot disable notifications - error: ${e}`),new De(Tv.UnknownError,`Cannot disable notifications - error: ${e}`)}}))}getClientType(){return null!=window.webkit&&null!=window.webkit.messageHandlers?Cv.iOS:navigator.userAgent.endsWith("LavvaAndroidNative")?Cv.Android:Cv.Web}isValidErrorCode(e){return Object.values(Tv).includes(e)}}Nv.ServiceName="NotificationsService";class Ev extends ae{constructor(e){super(),this.Resource="/notifications/token",this.Method=ue.Post,this.Data=e}}class Iv extends ae{constructor(e){super(),this.Resource="/notifications/token",this.Method=ue.Put,this.Data=e}}class Rv extends ae{constructor(){super(),this.Resource="/notifications/tokens/metadata",this.Method=ue.Get}}class Pv extends ae{constructor(e){super(),this.Resource="/notifications/status",this.Method=ue.Get,this.Data={TokenIdentity:e}}}class Ov extends ae{constructor(e){super(),this.Resource="/notifications/enabl",this.Method=ue.Post,this.Data=e}}class Uv extends ae{constructor(e){super(),this.Resource="/notifications/disable",this.Method=ue.Post,this.Data=e}}class Mv{CheckLocationPermissionAsync(){return this.IsAndroidLocationAvailable()?navigator.AndroidLocation.CheckNotificationPermissionAsync():Promise.resolve(!1)}RequestLocationPermissionAsync(){return this.IsAndroidLocationAvailable()?navigator.AndroidNotifications.RequestLocationPermissionAsync():Promise.resolve(!1)}IsAndroidLocationAvailable(){return void 0!==navigator.AndroidLocation}GetServiceName(){return Mv.ServiceName}}Mv.ServiceName="AndroidLocationService";class xv{IsAndroidNotificationsAvailable(){return void 0!==navigator.AndroidNotifications}CheckNotificationPermissionAsync(){return this.IsAndroidNotificationsAvailable()?navigator.AndroidNotifications.CheckNotificationPermissionAsync():Promise.resolve(!1)}RequestNotificationPermissionAsync(){return this.IsAndroidNotificationsAvailable()?navigator.AndroidNotifications.RequestNotificationPermissionAsync():Promise.resolve(!1)}GetServiceName(){return xv.ServiceName}}xv.ServiceName="AndroidNotificationsService",nu(Map),nu(Set),(()=>{const e=String.prototype,t=Object.getOwnPropertyNames(ui.prototype);for(const n of t)e[n]=e[n]??ui.prototype[n];e.first=function(e){if(e){for(let t=0;t<this.length;t++){const n=this[t];if(!0===e(n))return n}throw new oi(ri.NoMatch)}if(0===this.length)throw new oi(ri.NoElements);return this[0]},e.firstOrDefault=function(e){if(e){for(let t=0;t<this.length;t++){const n=this[t];if(!0===e(n))return n}return null}return 0===this.length?null:this[0]},e.count=function(e){if(e){let t=0;for(let n=0;n<this.length;n++)!0===e(this[n])&&t++;return t}return this.length},e.elementAt=function(e){if(e<0||e>=this.length)throw new si("index");return this[e]},e.elementAtOrDefault=function(e){return this[e]||null},e.last=function(e){if(e){for(let t=this.length-1;t>=0;t--){const n=this[t];if(!0===e(n))return n}throw new oi(ri.NoMatch)}if(0===this.length)throw new oi(ri.NoElements);return this[this.length-1]},e.lastOrDefault=function(e){if(e){for(let t=this.length-1;t>=0;t--){const n=this[t];if(!0===e(n))return n}return null}return 0===this.length?null:this[this.length-1]},e.reverse=function(){const e=this;return new ui((function*(){for(let t=e.length-1;t>=0;t--)yield e[t]}))}})(),og(Array),og(Int8Array),og(Int16Array),og(Int32Array),og(Uint8Array),og(Uint8ClampedArray),og(Uint16Array),og(Uint32Array),og(Float32Array),og(Float64Array);class Fv{static Init(){if(r.IsInitialized)return;let e=r.Instance;try{e.RegisterService(new vv),e.RegisterService(new o),e.RegisterService(new Wg),e.RegisterService(new Ge),e.RegisterService(new Ke),e.RegisterService(new _v),Fv.IsRunningFromLocalNetwork()?(console.log("\n\nRunning from local network!\n\n"),e.RegisterService(new Av)):e.RegisterService(new Pt),e.RegisterService(new Mv),e.RegisterService(new xv),e.RegisterService(new hr),e.RegisterService(new kv),e.RegisterService(new hr),e.RegisterService(new Mr),e.RegisterService(new rt),e.RegisterService(new yv),e.RegisterService(new cr),e.RegisterService(new Ze),e.RegisterService(new Ne),e.RegisterService(new Le),e.RegisterService(new Fo),e.RegisterService(new dg),e.RegisterService(new Qr),e.RegisterService(new rf),e.RegisterService(new lv),e.RegisterService(new Pf),e.RegisterService(new ko),e.RegisterService(new av),e.RegisterService(new Nv)}catch(e){console.error(e)}}static IsAppServedFromControllerAsync(){const e=`http://${window.location.hostname}/controller_info`;return fetch(e,{method:"GET"}).then((e=>!!e.ok)).catch((e=>!1))}static IsRunningFromLocalNetwork(e=window.location.hostname){return e.startsWith("192.168.")||e.startsWith("10.")}static GetAsync(e,t){return r.Instance.GetServiceAsync(e,t)}static GetWithTimeoutAsync(e,t){return r.Instance.GetServiceWithTimeoutAsync(e,t)}static Get(e){return r.Instance.GetService(e)}static SleepForAsync(e){return new Promise((t=>setTimeout(t,e)))}static ExportStringAsFileToDownload(e,t){const n=new Blob([t],{type:"text/plain"}),s=document.createElement("a"),r=window.URL.createObjectURL(n);return s.href=r,s.download=e,s}}Fv.WorksInContextOf="",Fv.Version=1})();
|
|
2
2
|
//# sourceMappingURL=exalushome-library-bundle.js.map
|