@mxtommy/kip 3.10.3 → 3.10.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -1
- package/package.json +1 -1
- package/public/{chunk-AREYGJLO.js → chunk-2MAVQD65.js} +1 -1
- package/public/{chunk-X45MUE6N.js → chunk-66OJ5PZF.js} +1 -1
- package/public/{chunk-2XB2ZNXV.js → chunk-6NRGS3BZ.js} +1 -1
- package/public/{chunk-DSWRNQDG.js → chunk-ANRGX57I.js} +11 -11
- package/public/{chunk-HHR4WMHS.js → chunk-CS5U3NWY.js} +1 -1
- package/public/{chunk-4N6AW5Y5.js → chunk-EJ4JM3HG.js} +1 -1
- package/public/{chunk-RJDZKEUA.js → chunk-F4VOQO2M.js} +1 -1
- package/public/{chunk-JDDRJMPN.js → chunk-FFE275CO.js} +1 -1
- package/public/{chunk-SVI34QP4.js → chunk-FPMCI7XZ.js} +1 -1
- package/public/{chunk-KABAIECE.js → chunk-G4B4D3XR.js} +1 -1
- package/public/{chunk-ZOYXBB55.js → chunk-GIZH6HIB.js} +1 -1
- package/public/{chunk-LYPFRDZT.js → chunk-GMZROOAF.js} +1 -1
- package/public/{chunk-B6IRZFL5.js → chunk-I6UWIF55.js} +1 -1
- package/public/{chunk-O2GGGUBC.js → chunk-IZAPOSYM.js} +1 -1
- package/public/{chunk-JHI7SSDT.js → chunk-KPOCVRYH.js} +1 -1
- package/public/{chunk-MRF22PVK.js → chunk-OX4U3HT6.js} +1 -1
- package/public/{chunk-DSBAZLLN.js → chunk-PYBIMDD3.js} +1 -1
- package/public/{chunk-QZO4362R.js → chunk-TARCFDF4.js} +1 -1
- package/public/{chunk-5NKFZDV5.js → chunk-TIXQ3FAF.js} +1 -1
- package/public/{chunk-EOXCM3IV.js → chunk-VZ77T3BF.js} +1 -1
- package/public/{chunk-4APSKT6I.js → chunk-X5HFS54R.js} +1 -1
- package/public/{chunk-ZGO25KK6.js → chunk-XE352AKG.js} +1 -1
- package/public/{chunk-WUFURHSA.js → chunk-XFU5YJJP.js} +1 -1
- package/public/{chunk-RNSD64U3.js → chunk-Z4FDWG2W.js} +1 -1
- package/public/index.html +1 -1
- package/public/{main-5QLZ4ZUU.js → main-ASCSBNAW.js} +11 -11
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{A as Ye,C as Qe,F as Xe,G as I,H as et,Hb as ke,Ia as Ae,Ja as c,Jc as U,O as tt,Oc as q,Pa as ae,Qa as d,Sa as f,W as it,Wa as k,Xb as v,Z as nt,Za as rt,a as y,aa as oe,ab as G,b as S,ba as m,ca as g,da as se,dc as T,ea as N,ec as P,f as C,ga as _,j as ie,l as h,oc as ot,p as Ze,qc as Me,r as Te,ra as A,t as b,tb as B,ua as R,v as ne,va as w,vc as Ee,w as re,wa as Ve}from"./chunk-DSWRNQDG.js";var l=(function(n){return n.Disconnected="Disconnected",n.HTTPDiscovering="HTTPDiscovering",n.HTTPConnected="HTTPConnected",n.HTTPError="HTTPError",n.HTTPRetrying="HTTPRetrying",n.WebSocketConnecting="WebSocketConnecting",n.Connected="Connected",n.WebSocketError="WebSocketError",n.WebSocketRetrying="WebSocketRetrying",n.PermanentFailure="PermanentFailure",n})(l||{}),st=(()=>{class n{config={httpRetryCount:3,webSocketRetryCount:5,retryIntervals:[2e3,3e3,5e3],notificationDebounceMs:0};_currentState$=new h(l.Disconnected);_status$=new h(this.createStatus(l.Disconnected,"Not connected"));_httpRetryCount=0;_webSocketRetryCount=0;_retryTimeout=null;_notificationTimeout=null;_httpRetryCallback=null;_webSocketRetryCallback=null;_isInitializationMode=!0;constructor(){console.log("[ConnectionStateMachine] Service initialized")}get state$(){return this._currentState$.asObservable()}get status$(){return this._status$.asObservable()}get currentState(){return this._currentState$.getValue()}enableWebSocketMode(){this._isInitializationMode=!1,console.log("[ConnectionStateMachine] WebSocket mode enabled");let e=this._status$.getValue();console.log(`[ConnectionStateMachine] Current status when enabling WebSocket mode: ${e.state} - ${e.message}`),this._status$.next(e)}setHTTPRetryCallback(e){this._httpRetryCallback=e}setWebSocketRetryCallback(e){this._webSocketRetryCallback=e}startHTTPDiscovery(e="Connection request"){console.log(`[ConnectionStateMachine] Starting HTTP discovery: ${e}`),this._httpRetryCount=0,this.setState(l.HTTPDiscovering,"Discovering Signal K server...")}onHTTPDiscoverySuccess(){console.log("[ConnectionStateMachine] HTTP discovery successful"),this._httpRetryCount=0,this.setState(l.HTTPConnected,"Signal K server discovered"),this._isInitializationMode||this.startWebSocketConnection()}onHTTPDiscoveryError(e){console.log(`[ConnectionStateMachine] HTTP discovery failed: ${e}`),this._httpRetryCount<this.config.httpRetryCount?(this._httpRetryCount++,this.setState(l.HTTPRetrying,`HTTP connection failed. Retrying (${this._httpRetryCount}/${this.config.httpRetryCount})...`,this._httpRetryCount,this.config.httpRetryCount),this.scheduleHTTPRetry()):this.setState(l.PermanentFailure,`HTTP connection failed after ${this.config.httpRetryCount} attempts. Check server URL.`,this.config.httpRetryCount,this.config.httpRetryCount)}startWebSocketConnection(){if(!(this.currentState===l.HTTPConnected||this.currentState===l.WebSocketRetrying||this.currentState===l.WebSocketConnecting||this.currentState===l.Connected))return this.currentState===l.HTTPDiscovering,void 0;console.log("[ConnectionStateMachine] Starting WebSocket connection"),this._webSocketRetryCount=0,this.setState(l.WebSocketConnecting,"Connecting to Signal K Websocket...")}onWebSocketConnected(){console.log("[ConnectionStateMachine] WebSocket connected"),this._webSocketRetryCount=0,this.setState(l.Connected,"Connected to Signal K server")}onWebSocketError(e){if(console.log(`[ConnectionStateMachine] WebSocket error: ${e}`),this.currentState!==l.HTTPConnected&&this.currentState!==l.WebSocketConnecting&&this.currentState!==l.Connected&&this.currentState!==l.WebSocketRetrying){console.log("[ConnectionStateMachine] HTTP connection lost, restarting HTTP discovery"),this.startHTTPDiscovery("HTTP connection lost during WebSocket operation");return}this._webSocketRetryCount++,this.setState(l.WebSocketRetrying,`WebSocket connection failed. Retry attempt ${this._webSocketRetryCount}...`,this._webSocketRetryCount,this.config.webSocketRetryCount),this.scheduleWebSocketRetry()}shutdown(e="App shutdown"){console.log(`[ConnectionStateMachine] Shutting down all connections: ${e}`),this.clearRetryTimer(),this.clearNotificationTimeout(),this._httpRetryCount=0,this._webSocketRetryCount=0,this.setState(l.Disconnected,"Application restarting...")}isHTTPConnected(){return this.currentState===l.HTTPConnected||this.currentState===l.WebSocketConnecting||this.currentState===l.Connected||this.currentState===l.WebSocketRetrying}isFullyConnected(){return this.currentState===l.Connected}setState(e,i,r,o){this._currentState$.next(e);let s=this.createStatus(e,i,r,o);e===l.HTTPDiscovering||e===l.WebSocketConnecting?this._status$.next(s):e===l.Connected?(this.clearNotificationTimeout(),this._notificationTimeout=setTimeout(()=>{this._status$.next(s)},this.config.notificationDebounceMs)):(this.clearNotificationTimeout(),this._status$.next(s))}createStatus(e,i,r,o){return{state:e,operation:this.stateToOperationCode(e),message:i,retryCount:r||0,maxRetries:o||0,timestamp:new Date}}stateToOperationCode(e){switch(e){case l.Disconnected:return 0;case l.HTTPDiscovering:case l.WebSocketConnecting:return 1;case l.Connected:return 2;case l.HTTPError:case l.WebSocketError:case l.HTTPRetrying:case l.WebSocketRetrying:return 3;case l.HTTPConnected:return 2;case l.PermanentFailure:return 5;default:return 0}}scheduleHTTPRetry(){this.clearRetryTimer();let e=Math.min(this._httpRetryCount-1,this.config.retryIntervals.length-1),i=this.config.retryIntervals[e];console.log(`[ConnectionStateMachine] Scheduling HTTP retry in ${i}ms`),this._retryTimeout=setTimeout(()=>{this._httpRetryCallback?(console.log(`[ConnectionStateMachine] Executing HTTP retry ${this._httpRetryCount}/${this.config.httpRetryCount}`),this._httpRetryCallback()):(console.error("[ConnectionStateMachine] No HTTP retry callback set!"),this.setState(l.Disconnected,"HTTP retry callback not configured"))},i)}scheduleWebSocketRetry(){this.clearRetryTimer(),console.log(`[ConnectionStateMachine] Scheduling WebSocket retry in ${this.config.retryIntervals[1]}ms`),this._retryTimeout=setTimeout(()=>{this._webSocketRetryCallback?(console.log(`[ConnectionStateMachine] Executing WebSocket retry ${this._webSocketRetryCount}/${this.config.webSocketRetryCount}`),this._webSocketRetryCallback()):(console.log("[ConnectionStateMachine] No WebSocket retry callback - using state change method"),this.setState(l.WebSocketConnecting,`Retrying WebSocket connection (${this._webSocketRetryCount}/${this.config.webSocketRetryCount})...`,this._webSocketRetryCount,this.config.webSocketRetryCount))},this.config.retryIntervals[1])}clearRetryTimer(){this._retryTimeout&&(clearTimeout(this._retryTimeout),this._retryTimeout=null)}clearNotificationTimeout(){this._notificationTimeout&&(clearTimeout(this._notificationTimeout),this._notificationTimeout=null)}ngOnDestroy(){this.clearRetryTimer(),this.clearNotificationTimeout(),this._httpRetryCallback=null,this._webSocketRetryCallback=null,this._currentState$?.complete(),this._status$?.complete()}static \u0275fac=function(i){return new(i||n)};static \u0275prov=g({token:n,factory:n.\u0275fac,providedIn:"root"})}return n})();var le=(()=>{class n{TIMEOUT_DURATION=1e4;connectionStateMachine=_(st);constructor(){this.connectionStateMachine.setHTTPRetryCallback(()=>{console.log("[SignalKConnectionService] Executing HTTP retry via callback"),this.retryCurrentConnection()})}serverServiceEndpoint$=new h({operation:0,message:"Not connected",serverDescription:null,httpServiceUrl:null,WsServiceUrl:null});signalKURL;serverName;serverVersion$=new h(null);serverRoles=[];http=_(U);currentProxyEnabled;currentSubscribeAll;validateSignalKUrl(e){return C(this,null,function*(){if(!e)throw new Error("Please enter a server URL");try{let r=new URL(e);if(!["http:","https:"].includes(r.protocol))throw new Error("URL must start with http:// or https://")}catch{throw new Error("Invalid URL format - please check for typos and ensure it starts with http:// or https://")}let i=e;i.endsWith("signalk/")||(i+="/signalk/"),console.log(`[Connection Service] Validating Signal K server at: ${e}`);try{if(!(yield b(this.http.get(i,{observe:"response"}).pipe(ne(5e3),I(o=>{throw console.error("[Connection Service] HTTP Error details:",o),o.name==="TimeoutError"?(console.error("[Connection Service] Validation timed out after 5000ms"),new Error("Server is not responding - check if the URL is correct and the server is running")):o.status===0||o.status===void 0?new Error("Cannot connect to server - check the URL format and ensure the server is accessible"):o.status===404?new Error("Server found but no Signal K service detected - verify this is a Signal K server"):o.status===403?new Error("Server refused connection - check if the server allows connections from this browser"):o.status>=500?new Error(`Server error (${o.status}) - the Signal K server may be having issues`):new Error(`Connection failed (${o.status}) - ${o.statusText||"please check the server URL"}`)})))).body?.endpoints?.v1)throw new Error("Server responded but doesn't appear to be a Signal K server - missing required endpoints");console.log(`[Connection Service] Validation successful for: ${e}`)}catch(r){throw console.error(`[Connection Service] Validation failed for ${e}:`,r.message),r}})}initializeConnection(e,i,r){return C(this,null,function*(){if(!e.url){console.log("[Connection Service] Connection initialization called with null or empty URL value");return}this.currentProxyEnabled=i,this.currentSubscribeAll=r;let o={operation:1,message:"Connecting...",serverDescription:null,httpServiceUrl:null,WsServiceUrl:null};this.signalKURL=e,this.serverServiceEndpoint$.next(o),this.connectionStateMachine.startHTTPDiscovery(`Connecting to ${e.url}`);let s=this.signalKURL.url;s.endsWith("signalk/")||(s+="/signalk/");try{console.log("[Connection Service] Connecting to: "+this.signalKURL.url);let a=yield b(this.http.get(s,{observe:"response"}).pipe(ne(this.TIMEOUT_DURATION),I(u=>(u.name==="TimeoutError"&&console.error("[Connection Service] Connection request timed out after "+this.TIMEOUT_DURATION+"ms"),Te(u)))));Object.assign(o,this.processEndpointResponse(a,i,r)),this.connectionStateMachine.onHTTPDiscoverySuccess()}catch(a){o.operation=3,o.message=a.message,this.connectionStateMachine.onHTTPDiscoveryError(a.message),this.handleError(a)}finally{o.subscribeAll=!!r,this.serverServiceEndpoint$.next(o)}})}retryCurrentConnection(){if(!this.signalKURL?.url){console.error("[SignalKConnectionService] Cannot retry - no current URL stored");return}console.log(`[SignalKConnectionService] Retrying connection to ${this.signalKURL.url}`),this.performHTTPDiscovery()}performHTTPDiscovery(){return C(this,null,function*(){if(!this.signalKURL?.url){console.error("[SignalKConnectionService] No URL available for HTTP discovery");return}let e=this.signalKURL.url;e.endsWith("signalk/")||(e+="/signalk/");try{console.log("[Connection Service] Connecting to: "+this.signalKURL.url);let i=yield b(this.http.get(e,{observe:"response"}).pipe(ne(this.TIMEOUT_DURATION),I(o=>(o.name==="TimeoutError"&&console.error("[Connection Service] Connection request timed out after "+this.TIMEOUT_DURATION+"ms"),Te(o))))),r=this.processEndpointResponse(i,this.currentProxyEnabled,this.currentSubscribeAll);this.connectionStateMachine.onHTTPDiscoverySuccess(),this.serverServiceEndpoint$.next(r)}catch(i){let r={operation:3,message:i.message,serverDescription:null,httpServiceUrl:null,WsServiceUrl:null};this.connectionStateMachine.onHTTPDiscoveryError(i.message),this.serverServiceEndpoint$.next(r),this.handleError(i)}})}processEndpointResponse(e,i,r){console.debug("[Connection Service] Signal K HTTP Endpoints retrieved"),this.serverVersion$.next(e.body.server.version);let o=e.body.endpoints.v1["signalk-http"],s=e.body.endpoints.v1["signalk-ws"],a={operation:2,message:e.status?.toString()||"Connected",serverDescription:`${e.body.server.id} ${e.body.server.version}`,httpServiceUrl:null,WsServiceUrl:null};if(i)console.debug("[Connection Service] Proxy Mode Enabled"),a.httpServiceUrl=window.location.origin+new URL(o).pathname,a.WsServiceUrl=window.location.protocol.replace("http","ws")+"//"+window.location.host+new URL(s).pathname;else{a.httpServiceUrl=o;let u=window.location.protocol==="https:";a.WsServiceUrl=u?s.replace("ws://","wss://"):s}return console.debug("[Connection Service] HTTP URI: "+a.httpServiceUrl),console.debug("[Connection Service] WebSocket URI: "+a.WsServiceUrl),a.subscribeAll=!!r,a}handleError(e){let i=e.status===0?`[Connection Service] ${e.name}: ${e.message}`:`[Connection Service] Backend returned code ${e.status}, body was: ${e.error}`;throw console.error(i),e}getServiceEndpointStatusAsO(){return this.serverServiceEndpoint$.asObservable()}setServerInfo(e,i,r){this.serverName=e,this.serverRoles=r,console.log(`[Connection Service] Server Name: ${e}, Version: ${i}, Roles: ${JSON.stringify(r)}`)}get skServerName(){return this.serverName}get skServerVersion(){return this.serverVersion$.getValue()}get skServerRoles(){return this.serverRoles}static \u0275fac=function(i){return new(i||n)};static \u0275prov=g({token:n,factory:n.\u0275fac,providedIn:"root"})}return n})();var ti="/signalk/v1/",at="auth/login",ii="auth/logout",ni="auth/validate",ri=60,lt=(()=>{class n{http=_(U);conn=_(le);_IsLoggedIn$=new h(!1);isLoggedIn$=this._IsLoggedIn$.asObservable();_authToken$=new h(null);authToken$=this._authToken$.asObservable();connectionEndpointSubscription=null;authTokenSubscription=null;isRenewingToken=!1;loginUrl=null;logoutUrl=null;validateTokenUrl=null;constructor(){let e=JSON.parse(localStorage.getItem("authorization_token"));e&&(e.isDeviceAccessToken?e.expiry===null?(console.log("[Authentication Service] Device Access Token found with expiry: NEVER"),this._authToken$.next(e)):this.isTokenExpired(e.expiry)?(console.log("[Authentication Service] Device Access Token expired. Deleting token"),localStorage.removeItem("authorization_token")):(console.log("[Authentication Service] Device Access Token found in Local Storage"),this._authToken$.next(e)):(console.log("[Authentication Service] User session token found in Local Storage"),console.log("[Authentication Service] Deleting user session token"),localStorage.removeItem("authorization_token"))),this.authTokenSubscription=this._authToken$.pipe(Xe(i=>!!i&&i.expiry!==null),tt((i,r)=>i.expiry===r.expiry),re(i=>{let r=this.getTokenExpirationDate(i.expiry,ri),o=r.getTime()-Date.now();return console.log(`[Authentication Service] Token refresh timer set for ${o} ms (Token Expiry: ${r.toISOString()})`),Math.max(o,0)}),it(i=>Qe(i))).subscribe(()=>{this.handleTokenRenewal()}),this.connectionEndpointSubscription=this.conn.serverServiceEndpoint$.subscribe(i=>{if(i.operation===2){let r=i.httpServiceUrl.substring(0,i.httpServiceUrl.length-4);this.loginUrl=r+at,this.logoutUrl=r+ii,this.validateTokenUrl=r+ni}})}handleTokenRenewal(){if(this.isRenewingToken){console.warn("[Authentication Service] Token renewal already in progress.");return}this.isRenewingToken=!0;let e=JSON.parse(localStorage.getItem("authorization_token"));if(!e){console.warn("[Authentication Service] No token found in local storage. Cannot renew."),this.isRenewingToken=!1;return}if(e.isDeviceAccessToken)console.warn("[Authentication Service] Device Access Token expired. Manual renewal required."),this.isRenewingToken=!1;else if(this.isTokenExpired(e.expiry))console.log("[Authentication Service] User session Token expired. Cannot renew."),this.isRenewingToken=!1;else{console.log("[Authentication Service] User session Token expires soon. Renewing token...");let i=JSON.parse(localStorage.getItem("connectionConfig"));this.login({usr:i.loginName,pwd:i.loginPassword}).then(()=>{console.log("[Authentication Service] Token successfully renewed.")}).catch(r=>{console.error("[Authentication Service] Token renewal failed. Server returned:",r.error)}).finally(()=>{this.isRenewingToken=!1})}}login(o){return C(this,arguments,function*({usr:e,pwd:i,newUrl:r}){let s;if(r?s=r.replace(/\/+$/,"")+ti+at:s=this.loginUrl,this._IsLoggedIn$.getValue()&&(yield this.logout(!0)),!s)throw console.error("[Authentication Service] Login URL is not set. Cannot perform login."),this.deleteToken(),new Error("Login URL is not set.");yield b(this.http.post(s,{username:e,password:i},{observe:"response"})).then(a=>{console.log("[Authentication Service] User "+e+" login successful"),this.setSession(a.body.token)}).catch(a=>{this.deleteToken(),this.handleError(a)})})}handleError(e){throw e.status===0&&this.deleteToken(),e}setSession(e){if(e){let i=JSON.parse(atob(e.split(".")[1])).exp,r={token:null,expiry:null,isDeviceAccessToken:!1};i===void 0?(r.token=e,console.log("[Authentication Service] User Session Token received. Token Expiration: NEVER"),this._IsLoggedIn$.next(!0),this._authToken$.next(r),localStorage.setItem("authorization_token",JSON.stringify(r))):this.isTokenExpired(i)?console.log("[Authentication Service] Received expired Session Token from server"):(r.token=e,r.expiry=i,console.log("[Authentication Service] Session Authorization Token received. Token Expiration: "+this.getTokenExpirationDate(r.expiry)),this._IsLoggedIn$.next(!0),this._authToken$.next(r),localStorage.setItem("authorization_token",JSON.stringify(r)))}}isTokenExpired(e){return Math.floor(new Date().getTime()/1e3)>=e}getTokenExpirationDate(e,i){let r=new Date(0);if(i){let o=new Date(0);o.setUTCSeconds(e-i),r=o}else r.setUTCSeconds(e);return r}renewToken(){return this.http.post(this.validateTokenUrl,null,{observe:"response"})}logout(e){return C(this,null,function*(){localStorage.removeItem("authorization_token"),yield b(this.http.put(this.logoutUrl,null)).then(()=>{this._IsLoggedIn$.next(!1),e||this._authToken$.next(null),console.log("[Authentication Service] User logged out")}).catch(i=>{console.error(i)})})}deleteToken(){this._authToken$&&(console.log("[Authentication Service] Deleting Authorization token"),localStorage.removeItem("authorization_token"),this._IsLoggedIn$.next(!1),this._authToken$.next(null))}setDeviceAccessToken(e){if(e){let i=JSON.parse(atob(e.split(".")[1])).exp,r={token:null,expiry:null,isDeviceAccessToken:!0};i===void 0?(r.token=e,console.log("[Authentication Service] Device Access Token received. Token Expiration: NEVER"),this._IsLoggedIn$.next(!1),this._authToken$.next(r),localStorage.setItem("authorization_token",JSON.stringify(r))):this.isTokenExpired(i)?console.log("[Authentication Service] Received expired Device Access Token from server"):(r.token=e,r.expiry=i,console.log("[Authentication Service] Device Access Token received. Token Expiration: "+this.getTokenExpirationDate(r.expiry)),this._IsLoggedIn$.next(!1),this._authToken$.next(r),localStorage.setItem("authorization_token",JSON.stringify(r)))}}ngOnDestroy(){this.connectionEndpointSubscription?.unsubscribe(),this.authTokenSubscription?.unsubscribe()}static \u0275fac=function(i){return new(i||n)};static \u0275prov=g({token:n,factory:n.\u0275fac,providedIn:"root"})}return n})();var oi=/^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i,Ne=n=>{if(typeof n!="string")throw new TypeError("Invalid argument expected string");let t=n.match(oi);if(!t)throw new Error(`Invalid argument not valid semver ('${n}' received)`);return t.shift(),t},ct=n=>n==="*"||n==="x"||n==="X",ut=n=>{let t=parseInt(n,10);return isNaN(t)?n:t},si=(n,t)=>typeof n!=typeof t?[String(n),String(t)]:[n,t],ai=(n,t)=>{if(ct(n)||ct(t))return 0;let[e,i]=si(ut(n),ut(t));return e>i?1:e<i?-1:0},xe=(n,t)=>{for(let e=0;e<Math.max(n.length,t.length);e++){let i=ai(n[e]||"0",t[e]||"0");if(i!==0)return i}return 0};var dt=(n,t)=>{let e=Ne(n),i=Ne(t),r=e.pop(),o=i.pop(),s=xe(e,i);return s!==0?s:r&&o?xe(r.split("."),o.split(".")):r||o?r?-1:1:0};var Fe=(n,t,e)=>{li(e);let i=dt(n,t);return ft[e].includes(i)},ft={">":[1],">=":[0,1],"=":[0],"<=":[-1,0],"<":[-1],"!=":[-1,1]},ht=Object.keys(ft),li=n=>{if(typeof n!="string")throw new TypeError(`Invalid operator type, expected string but got ${typeof n}`);if(ht.indexOf(n)===-1)throw new Error(`Invalid operator, expected one of ${ht.join("|")}`)};var gt=(()=>{class n{server=_(le);http=_(U);_auth=_(lt);serverEndpoint=null;isAppDataSupported=!1;configFileVersion=null;sharedConfigName;InitConfig=null;storageServiceReady$=new h(!1);_isLoggedIn=!1;_networkStatus=void 0;patchQueue$=new ie;patch=function(e){return this.http.post(e.url,e.document).pipe(nt(()=>console.log("[Storage Service] Remote config patch request completed successfully")),I(i=>this.handleError(i)))};constructor(){let e=this.server;this._auth.isLoggedIn$.pipe(q()).subscribe(i=>{this._isLoggedIn=i,this.isStorageServiceReady()}),e.serverServiceEndpoint$.pipe(q()).subscribe(i=>{this._networkStatus=i,this.isStorageServiceReady()}),e.serverVersion$.pipe(q()).subscribe(i=>{i&&(this.isAppDataSupported=Fe(i,"1.27.0",">="))}),this.patchQueue$.pipe(et(i=>this.patch(i)),q()).subscribe(()=>{})}isStorageServiceReady(){this._networkStatus?.httpServiceUrl&&(this.serverEndpoint=this._networkStatus.httpServiceUrl.substring(0,this._networkStatus.httpServiceUrl.length-4)+"applicationData/"),this._networkStatus?.operation===2&&this._isLoggedIn&&this.serverEndpoint?(this.storageServiceReady$.next(!0),console.log(`[Remote Storage Service] Authenticated ${this._isLoggedIn} ,AppData API: ${this.serverEndpoint}`)):this.storageServiceReady$.next(!1)}ensureReady(){if(!this.storageServiceReady$.getValue())throw new Error("[StorageService] Not ready: storageServiceReady is false")}listConfigs(e){return C(this,null,function*(){this.ensureReady();let i=[];if(!this.serverEndpoint)return console.warn("[Storage Service] No server endpoint set. Cannot retrieve config list"),null;let r=this.serverEndpoint,o=r+"global/kip/"+this.configFileVersion+"/?keys=true",s=r+"user/kip/"+this.configFileVersion+"/?keys=true";return e&&(o=r+"global/kip/"+e+"/?keys=true",s=r+"user/kip/"+e+"/?keys=true"),yield b(this.http.get(o)).then(a=>{for(let u of a)i.push({scope:"global",name:u});console.log("[Storage Service] Retrieved Global config list")}).catch(a=>{this.handleError(a)}),yield b(this.http.get(s)).then(a=>{for(let u of a)i.push({scope:"user",name:u});console.log("[Storage Service] Retrieved User config list")}).catch(a=>{this.handleError(a)}),i})}getConfig(e,i,r,o){return C(this,null,function*(){this.ensureReady();let s=null,a=this.serverEndpoint+e+"/kip/"+this.configFileVersion+"/"+i;return r&&(a=this.serverEndpoint+e+"/kip/"+r+"/"+i),yield b(this.http.get(a)).then(u=>{s=u,console.log(`[Storage Service] Retrieved config [${i}] from [${e}] scope`),o&&(this.InitConfig=u)}).catch(u=>{this.handleError(u)}),s})}setConfig(e,i,r,o){return C(this,null,function*(){this.ensureReady();let s=this.serverEndpoint+e+"/kip/"+this.configFileVersion+"/"+i,a=null;return o&&(s=this.serverEndpoint+e+"/kip/"+o+"/"+i),yield b(this.http.post(s,r)).then(u=>{console.log(`[Storage Service] Saved config [${i}] to [${e}] scope`),a=u}).catch(u=>{this.handleError(u)}),a})}patchConfig(e,i,r){this.ensureReady();let o=this.serverEndpoint+"user/kip/"+this.configFileVersion,s;switch(r&&(o=this.serverEndpoint+"user/kip/"+r),e){case"IAppConfig":s=[{op:"replace",path:`/${this.sharedConfigName}/app`,value:i}];break;case"IThemeConfig":s=[{op:"replace",path:`/${this.sharedConfigName}/theme/themeName`,value:i.themeName}];break;case"IWidgetConfig":s=[{op:"replace",path:`/${this.sharedConfigName}/widget`,value:i}];break;case"ILayoutConfig":s=[{op:"replace",path:`/${this.sharedConfigName}/layout`,value:i}];break;case"Dashboards":s=[{op:"replace",path:`/${this.sharedConfigName}/dashboards`,value:i}];break;case"Array<IUnitDefaults>":s=[{op:"replace",path:`/${this.sharedConfigName}/app/unitDefaults`,value:i}];break;case"Array<IDatasetDef>":s=[{op:"replace",path:`/${this.sharedConfigName}/app/dataSets`,value:i}];break;case"INotificationConfig":s=[{op:"replace",path:`/${this.sharedConfigName}/app/notificationConfig`,value:i}];break;default:console.warn("[Storage Service] JSON Patch request type unknown");break}let a={url:o,document:s};this.patchQueue$.next(a)}patchGlobal(e,i,r,o,s){this.ensureReady();let a=this.serverEndpoint+i+"/kip/"+this.configFileVersion;s&&(a=this.serverEndpoint+i+"/kip/"+s);let u;switch(o){case"add":u=[{op:"add",path:`/${e}`,value:r}];break;case"replace":u=[{op:"replace",path:`/${e}`,value:r}];break;case"remove":u=[{op:"remove",path:`/${e}`,value:r}];break;default:console.warn("[Storage Service] JSON Patch operation request type unknown");break}let ei={url:a,document:u};this.patchQueue$.next(ei)}removeItem(e,i,r){this.ensureReady();let o=this.serverEndpoint+e+"/kip/"+this.configFileVersion;r&&(o=this.serverEndpoint+e+"/kip/"+r);let s=[{op:"remove",path:`/${i}`}],a={url:o,document:s};this.patchQueue$.next(a)}clear(){this.ensureReady()}set activeConfigFileVersion(e){this.configFileVersion=e}handleError(e){throw e.status===0?console.error("[Storage Service] An error occurred:",e.error):console.error("[Storage Service] Backend returned error: ",e.message),e}get initConfig(){return this.InitConfig}static \u0275fac=function(i){return new(i||n)};static \u0275prov=g({token:n,factory:n.\u0275fac,providedIn:"root"})}return n})();var M=class{static create(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){let e=Math.random()*16|0;return(t=="x"?e:e&3|8).toString(16)})}};var K={disableNotifications:!1,menuGrouping:!0,security:{disableSecurity:!0},devices:{disableDevices:!1,showNormalState:!1,showNominalState:!1},sound:{disableSound:!1,muteNormal:!0,muteNominal:!0,muteWarn:!0,muteAlert:!1,muteAlarm:!1,muteEmergency:!1}};var ce={Unitless:"unitless",Speed:"knots",Flow:"l/h",Temperature:"celsius",Length:"m",Volume:"liter",Current:"A",Potential:"V",Charge:"C",Power:"W",Energy:"J",Pressure:"mmHg","Fuel Distance":"nm/l","Energy Distance":"nm/kWh",Density:"kg/m3",Time:"Hours","Angular Velocity":"deg/min",Angle:"deg",Frequency:"Hz",Ratio:"ratio",Resistance:"ohm"};var pt={configVersion:11,autoNightMode:!0,redNightMode:!1,nightModeBrightness:.27,isRemoteControl:!1,instanceName:"",dataSets:[],unitDefaults:ce,notificationConfig:K},mt={themeName:""};var vt={configVersion:11,kipUUID:M.create(),signalKUrl:null,proxyEnabled:!1,signalKSubscribeAll:!1,useDeviceToken:!1,loginName:null,loginPassword:null,useSharedConfig:!1,sharedConfigName:"default"};var Ie={configVersion:11,autoNightMode:!1,redNightMode:!1,nightModeBrightness:.27,isRemoteControl:!1,instanceName:"",dataSets:[{uuid:"afbe4e41-26f5-404f-a55d-9f7b9b76fbd1",path:"self.environment.wind.speedApparent",pathSource:"default",period:1,baseUnit:"m/s",label:"self.environment.wind.speedApparent, Source: default, Scale: minute, Period: 1",timeScaleFormat:"minute"}],unitDefaults:{Unitless:"unitless",Speed:"knots",Flow:"l/h",Temperature:"celsius",Length:"m",Volume:"liter",Current:"A",Potential:"V",Charge:"C",Power:"W",Energy:"J",Pressure:"mmHg","Fuel Distance":"nm/l","Energy Distance":"nm/kWh",Density:"kg/m3",Time:"Hours","Angular Velocity":"deg/min",Angle:"deg",Frequency:"Hz",Ratio:"ratio",Resistance:"ohm"},notificationConfig:{disableNotifications:!1,menuGrouping:!0,security:{disableSecurity:!0},devices:{disableDevices:!1,showNormalState:!1,showNominalState:!1},sound:{disableSound:!1,muteNormal:!0,muteNominal:!0,muteWarn:!0,muteAlert:!1,muteAlarm:!1,muteEmergency:!1}}},Re=[{id:"3e0825ee-95fd-4ad4-8802-e0507845b668",name:"Sailing",icon:"dashboard-sailing",configuration:[{w:3,h:4,id:"339698a7-2cff-4ab9-9b50-d8056f971471",selector:"widget-numeric",input:{widgetProperties:{type:"widget-numeric",uuid:"339698a7-2cff-4ab9-9b50-d8056f971471",config:{displayName:"Depth",filterSelfPaths:!0,paths:{numericPath:{description:"Numeric Data",path:"self.environment.depth.belowTransducer",source:"default",pathType:"number",isPathConfigurable:!0,convertUnitTo:"m",showPathSkUnitsFilter:!0,pathSkUnitsFilter:null,sampleTime:500}},showMax:!1,showMin:!1,numDecimal:1,showMiniChart:!0,yScaleMin:0,yScaleMax:100,inverseYAxis:!1,verticalChart:!1,color:"blue",enableTimeout:!1,dataTimeout:5,ignoreZones:!1}}},x:0,y:0},{w:5,h:10,id:"a44028e0-dfee-4492-895b-2b03a60f3a69",selector:"widget-wind-steer",input:{widgetProperties:{type:"widget-wind-steer",uuid:"a44028e0-dfee-4492-895b-2b03a60f3a69",config:{filterSelfPaths:!0,paths:{headingPath:{description:"True Heading",path:"self.navigation.headingTrue",source:"default",pathType:"number",isPathConfigurable:!0,pathRequired:!0,showPathSkUnitsFilter:!1,pathSkUnitsFilter:"rad",convertUnitTo:"deg",showConvertUnitTo:!1,sampleTime:500},appWindAngle:{description:"Apparent Wind Angle",path:"self.environment.wind.angleApparent",source:"default",pathType:"number",isPathConfigurable:!0,pathRequired:!0,showPathSkUnitsFilter:!1,pathSkUnitsFilter:"rad",convertUnitTo:"deg",showConvertUnitTo:!1,sampleTime:500},appWindSpeed:{description:"Apparent Wind Speed",path:"self.environment.wind.speedApparent",source:"default",pathType:"number",isPathConfigurable:!0,pathRequired:!0,showPathSkUnitsFilter:!1,pathSkUnitsFilter:"m/s",convertUnitTo:"knots",sampleTime:500},trueWindAngle:{description:"True Wind Angle",path:"self.environment.wind.angleTrueWater",source:"default",pathType:"number",isPathConfigurable:!0,pathRequired:!1,showPathSkUnitsFilter:!1,pathSkUnitsFilter:"rad",convertUnitTo:"deg",showConvertUnitTo:!1,sampleTime:500},trueWindSpeed:{description:"True Wind Speed",path:"self.environment.wind.speedTrue",source:"default",pathType:"number",isPathConfigurable:!0,pathRequired:!1,showPathSkUnitsFilter:!1,pathSkUnitsFilter:"m/s",convertUnitTo:"knots",sampleTime:500},courseOverGround:{description:"True Course Over Ground",path:"self.navigation.courseOverGroundTrue",source:"default",pathType:"number",isPathConfigurable:!0,pathRequired:!1,showPathSkUnitsFilter:!1,pathSkUnitsFilter:"rad",showConvertUnitTo:!1,convertUnitTo:"deg",sampleTime:500},nextWaypointBearing:{description:"Next Waypoint True Bearing",path:"self.navigation.courseGreatCircle.nextPoint.bearingTrue",source:"default",pathType:"number",isPathConfigurable:!1,pathRequired:!1,showPathSkUnitsFilter:!1,pathSkUnitsFilter:"rad",convertUnitTo:"deg",showConvertUnitTo:!1,sampleTime:500},set:{description:"True Drift Set",path:"self.environment.current.setTrue",source:"default",pathType:"number",isPathConfigurable:!0,pathRequired:!1,showPathSkUnitsFilter:!1,pathSkUnitsFilter:"rad",convertUnitTo:"deg",showConvertUnitTo:!1,sampleTime:500},drift:{description:"Drift Speed Impact",path:"self.environment.current.drift",source:"default",pathType:"number",isPathConfigurable:!0,pathRequired:!1,showPathSkUnitsFilter:!1,pathSkUnitsFilter:"m/s",convertUnitTo:"knots",sampleTime:500}},windSectorEnable:!0,windSectorWindowSeconds:5,laylineEnable:!0,laylineAngle:40,waypointEnable:!0,courseOverGroundEnable:!0,driftEnable:!0,awsEnable:!0,twsEnable:!0,sailSetupEnable:!1,enableTimeout:!1,dataTimeout:5}}},x:3,y:0},{w:4,h:6,id:"24406c15-7738-4dc1-a206-7a4862c2931d",selector:"widget-gauge-ng-radial",input:{widgetProperties:{type:"widget-gauge-ng-radial",uuid:"24406c15-7738-4dc1-a206-7a4862c2931d",config:{displayName:"SOG",filterSelfPaths:!0,paths:{gaugePath:{description:"Numeric Data",path:"self.navigation.speedOverGround",source:"default",pathType:"number",isPathConfigurable:!0,showPathSkUnitsFilter:!0,pathSkUnitsFilter:null,convertUnitTo:"knots",sampleTime:500}},displayScale:{lower:0,upper:10,type:"linear"},gauge:{type:"ngRadial",subType:"measuring",enableTicks:!0,compassUseNumbers:!1,highlightsWidth:5,scaleStart:180},numInt:1,numDecimal:1,enableTimeout:!1,color:"yellow",dataTimeout:5,ignoreZones:!1}}},x:8,y:0},{w:3,h:4,id:"c6bcaa53-afa1-42c7-ad92-d5f7dba14734",selector:"widget-numeric",input:{widgetProperties:{type:"widget-numeric",uuid:"c6bcaa53-afa1-42c7-ad92-d5f7dba14734",config:{displayName:"STW",filterSelfPaths:!0,paths:{numericPath:{description:"Numeric Data",path:"self.navigation.speedThroughWater",source:"default",pathType:"number",isPathConfigurable:!0,convertUnitTo:"knots",showPathSkUnitsFilter:!0,pathSkUnitsFilter:null,sampleTime:500}},showMax:!0,showMin:!0,numDecimal:1,showMiniChart:!1,yScaleMin:0,yScaleMax:10,inverseYAxis:!1,verticalChart:!1,color:"contrast",enableTimeout:!1,dataTimeout:5,ignoreZones:!1}}},x:0,y:4},{w:4,h:6,id:"973c8804-be09-4923-bb5d-48c13b65db69",selector:"widget-data-chart",input:{widgetProperties:{type:"widget-data-chart",uuid:"973c8804-be09-4923-bb5d-48c13b65db69",config:{displayName:"Chart Label",filterSelfPaths:!0,convertUnitTo:"knots",datasetUUID:"afbe4e41-26f5-404f-a55d-9f7b9b76fbd1",inverseYAxis:!1,datasetAverageArray:"sma",showAverageData:!0,trackAgainstAverage:!1,showDatasetMinimumValueLine:!1,showDatasetMaximumValueLine:!1,showDatasetAverageValueLine:!0,showDatasetAngleAverageValueLine:!1,showLabel:!1,showTimeScale:!0,startScaleAtZero:!1,verticalChart:!1,showYScale:!0,yScaleSuggestedMin:null,yScaleSuggestedMax:null,enableMinMaxScaleLimit:!1,yScaleMin:null,yScaleMax:null,numDecimal:1,color:"orange",invertData:!1,verticalGraph:!1}}},x:8,y:6},{x:0,y:8,w:3,h:4,minW:1,minH:1,id:"5289a84d-18fd-4ee7-9724-72249af403f2",selector:"widget-position",input:{widgetProperties:{type:"widget-position",uuid:"5289a84d-18fd-4ee7-9724-72249af403f2",config:{displayName:"Position",filterSelfPaths:!0,paths:{longPath:{description:"Longitude",path:"self.navigation.position.longitude",source:"default",pathType:"number",isPathConfigurable:!0,convertUnitTo:"longitudeMin",showPathSkUnitsFilter:!0,pathSkUnitsFilter:null,sampleTime:500},latPath:{description:"Latitude",path:"self.navigation.position.latitude",source:"default",pathType:"number",isPathConfigurable:!0,convertUnitTo:"latitudeMin",showPathSkUnitsFilter:!0,pathSkUnitsFilter:null,sampleTime:500}},color:"grey",enableTimeout:!1,dataTimeout:5}}}},{w:5,h:2,id:"1a7a3f79-2eb4-4092-a0c3-9a61db8a8586",selector:"widget-simple-linear",input:{widgetProperties:{type:"widget-simple-linear",uuid:"1a7a3f79-2eb4-4092-a0c3-9a61db8a8586",config:{displayName:"House Bank",filterSelfPaths:!0,paths:{gaugePath:{description:"Numeric Data",path:"self.electrical.batteries.1.voltage",source:"default",pathType:"number",isPathConfigurable:!0,showPathSkUnitsFilter:!0,pathSkUnitsFilter:"V",convertUnitTo:"V",sampleTime:500}},displayScale:{lower:0,upper:15,type:"linear"},gauge:{type:"simpleLinear",unitLabelFormat:"full"},numInt:1,numDecimal:2,ignoreZones:!1,color:"green",enableTimeout:!1,dataTimeout:5}}},x:3,y:10}]},{id:"7c67c8c5-dc55-4e1d-9fc5-3dd95fd41bea",name:"Charting",icon:"dashboard-map",configuration:[{x:0,y:0,w:8,h:12,id:"488d620a-37d4-4b98-849d-304cd18003e9",selector:"widget-freeboardsk",input:{widgetProperties:{type:"widget-freeboardsk",uuid:"488d620a-37d4-4b98-849d-304cd18003e9"}}},{x:8,y:0,w:2,h:3,id:"26a2a150-5af8-4f1d-aaab-0cb2a406fc17",selector:"widget-gauge-ng-compass",input:{widgetProperties:{type:"widget-gauge-ng-compass",uuid:"26a2a150-5af8-4f1d-aaab-0cb2a406fc17",config:{displayName:"COG (T)",filterSelfPaths:!0,paths:{gaugePath:{description:"Numeric Data",path:"self.navigation.courseOverGroundTrue",source:"default",pathType:"number",isPathConfigurable:!0,showPathSkUnitsFilter:!1,pathSkUnitsFilter:"rad",showConvertUnitTo:!1,convertUnitTo:"deg",sampleTime:500}},gauge:{type:"ngRadial",subType:"marineCompass",enableTicks:!0,compassUseNumbers:!0,showValueBox:!1},enableTimeout:!1,color:"purple",dataTimeout:5}}}},{x:10,y:0,w:2,h:3,id:"caf9ca47-fcf6-4736-a314-2b5210edaf03",selector:"widget-datetime",input:{widgetProperties:{type:"widget-datetime",uuid:"caf9ca47-fcf6-4736-a314-2b5210edaf03",config:{displayName:"Next WP Arrival",filterSelfPaths:!0,paths:{gaugePath:{description:"String Data",path:"self.navigation.datetime",source:"default",pathType:"Date",isPathConfigurable:!0,sampleTime:500}},dateFormat:"dd/MM HH:mm",dateTimezone:"America/Toronto",color:"contrast",enableTimeout:!1,dataTimeout:5}}}},{x:8,y:3,w:4,h:9,id:"daa21350-009e-4d99-8209-364f9b99caee",selector:"widget-autopilot",input:{widgetProperties:{type:"widget-autopilot",uuid:"daa21350-009e-4d99-8209-364f9b99caee",config:{filterSelfPaths:!0,paths:{autopilotState:{description:"Autopilot State",path:"self.steering.autopilot.state",source:"default",pathType:"string",isPathConfigurable:!1,showPathSkUnitsFilter:!1,convertUnitTo:"",sampleTime:500},autopilotTargetHeading:{description:"Autopilot Target Magnetic Heading",path:"self.steering.autopilot.target.headingMagnetic",source:"default",pathType:"number",convertUnitTo:"deg",isPathConfigurable:!1,showPathSkUnitsFilter:!1,pathSkUnitsFilter:"rad",sampleTime:500},autopilotTargetWindHeading:{description:"Autopilot Target Apparent Wind Angle",path:"self.steering.autopilot.target.windAngleApparent",source:"default",pathType:"number",convertUnitTo:"deg",isPathConfigurable:!1,showPathSkUnitsFilter:!1,pathSkUnitsFilter:"rad",sampleTime:500},rudderAngle:{description:"Rudder Angle",path:"self.steering.rudderAngle",source:"default",pathType:"number",convertUnitTo:"deg",isPathConfigurable:!1,showPathSkUnitsFilter:!1,pathSkUnitsFilter:"rad",sampleTime:500},courseXte:{description:"Cross Track Error",path:"self.navigation.course.calcValues.crossTrackError",source:"default",pathType:"number",isPathConfigurable:!1,convertUnitTo:"m",showPathSkUnitsFilter:!0,pathRequired:!1,pathSkUnitsFilter:"m",sampleTime:500},headingMag:{description:"Magnetic Heading",path:"self.navigation.headingMagnetic",source:"default",pathType:"number",convertUnitTo:"deg",isPathConfigurable:!0,pathRequired:!1,showPathSkUnitsFilter:!1,pathSkUnitsFilter:"rad",showConvertUnitTo:!1,sampleTime:500},headingTrue:{description:"True Heading",path:"self.navigation.headingTrue",source:"default",pathType:"number",convertUnitTo:"deg",isPathConfigurable:!0,pathRequired:!1,showPathSkUnitsFilter:!1,pathSkUnitsFilter:"rad",showConvertUnitTo:!1,sampleTime:500},windAngleApparent:{description:"Apparent Wind Angle",path:"self.environment.wind.angleApparent",source:"default",pathType:"number",convertUnitTo:"deg",isPathConfigurable:!0,pathRequired:!1,showPathSkUnitsFilter:!1,pathSkUnitsFilter:"rad",showConvertUnitTo:!1,sampleTime:500},windAngleTrueWater:{description:"Wind Angle True Water",path:"self.environment.wind.angleTrueWater",source:"default",pathType:"number",convertUnitTo:"deg",isPathConfigurable:!0,pathRequired:!1,showPathSkUnitsFilter:!1,pathSkUnitsFilter:"rad",showConvertUnitTo:!1,sampleTime:500}},invertRudder:!0,headingDirectionTrue:!1,courseDirectionTrue:!1,enableTimeout:!1,dataTimeout:5,autopilotInstance:"_default"}}}}]}],Pe={themeName:""};var Gn={configVersion:11,kipUUID:M.create(),signalKUrl:"https://demo.signalk.org",proxyEnabled:!1,signalKSubscribeAll:!1,useDeviceToken:!1,loginName:null,loginPassword:null,useSharedConfig:!1,sharedConfigName:"default"};var ci="",ui=11,z=11,tr=(()=>{class n{storage=_(gt);unitDefaults=new h({});themeName=new h(ci);kipKNotificationConfig=new h(K);autoNightMode=new h(!1);redNightMode=new h(!1);nightModeBrightness=new h(1);isRemoteControl=new h(!1);instanceName=new h("");proxyEnabled=!1;signalKSubscribeAll=!1;useDeviceToken=!1;loginName;loginPassword;useSharedConfig;sharedConfigName;activeConfig={app:null,theme:null,dashboards:null};kipUUID;signalkUrl;widgets;_dashboards=[];dataSets=[];configUpgrade=A(!1);constructor(){if(console.log("[AppSettings Service] Service startup..."),this.storage.activeConfigFileVersion=ui,!window.localStorage)console.error(`[AppSettings Service] LocalStorage NOT SUPPORTED by browser
|
|
1
|
+
import{A as Ye,C as Qe,F as Xe,G as I,H as et,Hb as ke,Ia as Ae,Ja as c,Jc as U,O as tt,Oc as q,Pa as ae,Qa as d,Sa as f,W as it,Wa as k,Xb as v,Z as nt,Za as rt,a as y,aa as oe,ab as G,b as S,ba as m,ca as g,da as se,dc as T,ea as N,ec as P,f as C,ga as _,j as ie,l as h,oc as ot,p as Ze,qc as Me,r as Te,ra as A,t as b,tb as B,ua as R,v as ne,va as w,vc as Ee,w as re,wa as Ve}from"./chunk-ANRGX57I.js";var l=(function(n){return n.Disconnected="Disconnected",n.HTTPDiscovering="HTTPDiscovering",n.HTTPConnected="HTTPConnected",n.HTTPError="HTTPError",n.HTTPRetrying="HTTPRetrying",n.WebSocketConnecting="WebSocketConnecting",n.Connected="Connected",n.WebSocketError="WebSocketError",n.WebSocketRetrying="WebSocketRetrying",n.PermanentFailure="PermanentFailure",n})(l||{}),st=(()=>{class n{config={httpRetryCount:3,webSocketRetryCount:5,retryIntervals:[2e3,3e3,5e3],notificationDebounceMs:0};_currentState$=new h(l.Disconnected);_status$=new h(this.createStatus(l.Disconnected,"Not connected"));_httpRetryCount=0;_webSocketRetryCount=0;_retryTimeout=null;_notificationTimeout=null;_httpRetryCallback=null;_webSocketRetryCallback=null;_isInitializationMode=!0;constructor(){console.log("[ConnectionStateMachine] Service initialized")}get state$(){return this._currentState$.asObservable()}get status$(){return this._status$.asObservable()}get currentState(){return this._currentState$.getValue()}enableWebSocketMode(){this._isInitializationMode=!1,console.log("[ConnectionStateMachine] WebSocket mode enabled");let e=this._status$.getValue();console.log(`[ConnectionStateMachine] Current status when enabling WebSocket mode: ${e.state} - ${e.message}`),this._status$.next(e)}setHTTPRetryCallback(e){this._httpRetryCallback=e}setWebSocketRetryCallback(e){this._webSocketRetryCallback=e}startHTTPDiscovery(e="Connection request"){console.log(`[ConnectionStateMachine] Starting HTTP discovery: ${e}`),this._httpRetryCount=0,this.setState(l.HTTPDiscovering,"Discovering Signal K server...")}onHTTPDiscoverySuccess(){console.log("[ConnectionStateMachine] HTTP discovery successful"),this._httpRetryCount=0,this.setState(l.HTTPConnected,"Signal K server discovered"),this._isInitializationMode||this.startWebSocketConnection()}onHTTPDiscoveryError(e){console.log(`[ConnectionStateMachine] HTTP discovery failed: ${e}`),this._httpRetryCount<this.config.httpRetryCount?(this._httpRetryCount++,this.setState(l.HTTPRetrying,`HTTP connection failed. Retrying (${this._httpRetryCount}/${this.config.httpRetryCount})...`,this._httpRetryCount,this.config.httpRetryCount),this.scheduleHTTPRetry()):this.setState(l.PermanentFailure,`HTTP connection failed after ${this.config.httpRetryCount} attempts. Check server URL.`,this.config.httpRetryCount,this.config.httpRetryCount)}startWebSocketConnection(){if(!(this.currentState===l.HTTPConnected||this.currentState===l.WebSocketRetrying||this.currentState===l.WebSocketConnecting||this.currentState===l.Connected))return this.currentState===l.HTTPDiscovering,void 0;console.log("[ConnectionStateMachine] Starting WebSocket connection"),this._webSocketRetryCount=0,this.setState(l.WebSocketConnecting,"Connecting to Signal K Websocket...")}onWebSocketConnected(){console.log("[ConnectionStateMachine] WebSocket connected"),this._webSocketRetryCount=0,this.setState(l.Connected,"Connected to Signal K server")}onWebSocketError(e){if(console.log(`[ConnectionStateMachine] WebSocket error: ${e}`),this.currentState!==l.HTTPConnected&&this.currentState!==l.WebSocketConnecting&&this.currentState!==l.Connected&&this.currentState!==l.WebSocketRetrying){console.log("[ConnectionStateMachine] HTTP connection lost, restarting HTTP discovery"),this.startHTTPDiscovery("HTTP connection lost during WebSocket operation");return}this._webSocketRetryCount++,this.setState(l.WebSocketRetrying,`WebSocket connection failed. Retry attempt ${this._webSocketRetryCount}...`,this._webSocketRetryCount,this.config.webSocketRetryCount),this.scheduleWebSocketRetry()}shutdown(e="App shutdown"){console.log(`[ConnectionStateMachine] Shutting down all connections: ${e}`),this.clearRetryTimer(),this.clearNotificationTimeout(),this._httpRetryCount=0,this._webSocketRetryCount=0,this.setState(l.Disconnected,"Application restarting...")}isHTTPConnected(){return this.currentState===l.HTTPConnected||this.currentState===l.WebSocketConnecting||this.currentState===l.Connected||this.currentState===l.WebSocketRetrying}isFullyConnected(){return this.currentState===l.Connected}setState(e,i,r,o){this._currentState$.next(e);let s=this.createStatus(e,i,r,o);e===l.HTTPDiscovering||e===l.WebSocketConnecting?this._status$.next(s):e===l.Connected?(this.clearNotificationTimeout(),this._notificationTimeout=setTimeout(()=>{this._status$.next(s)},this.config.notificationDebounceMs)):(this.clearNotificationTimeout(),this._status$.next(s))}createStatus(e,i,r,o){return{state:e,operation:this.stateToOperationCode(e),message:i,retryCount:r||0,maxRetries:o||0,timestamp:new Date}}stateToOperationCode(e){switch(e){case l.Disconnected:return 0;case l.HTTPDiscovering:case l.WebSocketConnecting:return 1;case l.Connected:return 2;case l.HTTPError:case l.WebSocketError:case l.HTTPRetrying:case l.WebSocketRetrying:return 3;case l.HTTPConnected:return 2;case l.PermanentFailure:return 5;default:return 0}}scheduleHTTPRetry(){this.clearRetryTimer();let e=Math.min(this._httpRetryCount-1,this.config.retryIntervals.length-1),i=this.config.retryIntervals[e];console.log(`[ConnectionStateMachine] Scheduling HTTP retry in ${i}ms`),this._retryTimeout=setTimeout(()=>{this._httpRetryCallback?(console.log(`[ConnectionStateMachine] Executing HTTP retry ${this._httpRetryCount}/${this.config.httpRetryCount}`),this._httpRetryCallback()):(console.error("[ConnectionStateMachine] No HTTP retry callback set!"),this.setState(l.Disconnected,"HTTP retry callback not configured"))},i)}scheduleWebSocketRetry(){this.clearRetryTimer(),console.log(`[ConnectionStateMachine] Scheduling WebSocket retry in ${this.config.retryIntervals[1]}ms`),this._retryTimeout=setTimeout(()=>{this._webSocketRetryCallback?(console.log(`[ConnectionStateMachine] Executing WebSocket retry ${this._webSocketRetryCount}/${this.config.webSocketRetryCount}`),this._webSocketRetryCallback()):(console.log("[ConnectionStateMachine] No WebSocket retry callback - using state change method"),this.setState(l.WebSocketConnecting,`Retrying WebSocket connection (${this._webSocketRetryCount}/${this.config.webSocketRetryCount})...`,this._webSocketRetryCount,this.config.webSocketRetryCount))},this.config.retryIntervals[1])}clearRetryTimer(){this._retryTimeout&&(clearTimeout(this._retryTimeout),this._retryTimeout=null)}clearNotificationTimeout(){this._notificationTimeout&&(clearTimeout(this._notificationTimeout),this._notificationTimeout=null)}ngOnDestroy(){this.clearRetryTimer(),this.clearNotificationTimeout(),this._httpRetryCallback=null,this._webSocketRetryCallback=null,this._currentState$?.complete(),this._status$?.complete()}static \u0275fac=function(i){return new(i||n)};static \u0275prov=g({token:n,factory:n.\u0275fac,providedIn:"root"})}return n})();var le=(()=>{class n{TIMEOUT_DURATION=1e4;connectionStateMachine=_(st);constructor(){this.connectionStateMachine.setHTTPRetryCallback(()=>{console.log("[SignalKConnectionService] Executing HTTP retry via callback"),this.retryCurrentConnection()})}serverServiceEndpoint$=new h({operation:0,message:"Not connected",serverDescription:null,httpServiceUrl:null,WsServiceUrl:null});signalKURL;serverName;serverVersion$=new h(null);serverRoles=[];http=_(U);currentProxyEnabled;currentSubscribeAll;validateSignalKUrl(e){return C(this,null,function*(){if(!e)throw new Error("Please enter a server URL");try{let r=new URL(e);if(!["http:","https:"].includes(r.protocol))throw new Error("URL must start with http:// or https://")}catch{throw new Error("Invalid URL format - please check for typos and ensure it starts with http:// or https://")}let i=e;i.endsWith("signalk/")||(i+="/signalk/"),console.log(`[Connection Service] Validating Signal K server at: ${e}`);try{if(!(yield b(this.http.get(i,{observe:"response"}).pipe(ne(5e3),I(o=>{throw console.error("[Connection Service] HTTP Error details:",o),o.name==="TimeoutError"?(console.error("[Connection Service] Validation timed out after 5000ms"),new Error("Server is not responding - check if the URL is correct and the server is running")):o.status===0||o.status===void 0?new Error("Cannot connect to server - check the URL format and ensure the server is accessible"):o.status===404?new Error("Server found but no Signal K service detected - verify this is a Signal K server"):o.status===403?new Error("Server refused connection - check if the server allows connections from this browser"):o.status>=500?new Error(`Server error (${o.status}) - the Signal K server may be having issues`):new Error(`Connection failed (${o.status}) - ${o.statusText||"please check the server URL"}`)})))).body?.endpoints?.v1)throw new Error("Server responded but doesn't appear to be a Signal K server - missing required endpoints");console.log(`[Connection Service] Validation successful for: ${e}`)}catch(r){throw console.error(`[Connection Service] Validation failed for ${e}:`,r.message),r}})}initializeConnection(e,i,r){return C(this,null,function*(){if(!e.url){console.log("[Connection Service] Connection initialization called with null or empty URL value");return}this.currentProxyEnabled=i,this.currentSubscribeAll=r;let o={operation:1,message:"Connecting...",serverDescription:null,httpServiceUrl:null,WsServiceUrl:null};this.signalKURL=e,this.serverServiceEndpoint$.next(o),this.connectionStateMachine.startHTTPDiscovery(`Connecting to ${e.url}`);let s=this.signalKURL.url;s.endsWith("signalk/")||(s+="/signalk/");try{console.log("[Connection Service] Connecting to: "+this.signalKURL.url);let a=yield b(this.http.get(s,{observe:"response"}).pipe(ne(this.TIMEOUT_DURATION),I(u=>(u.name==="TimeoutError"&&console.error("[Connection Service] Connection request timed out after "+this.TIMEOUT_DURATION+"ms"),Te(u)))));Object.assign(o,this.processEndpointResponse(a,i,r)),this.connectionStateMachine.onHTTPDiscoverySuccess()}catch(a){o.operation=3,o.message=a.message,this.connectionStateMachine.onHTTPDiscoveryError(a.message),this.handleError(a)}finally{o.subscribeAll=!!r,this.serverServiceEndpoint$.next(o)}})}retryCurrentConnection(){if(!this.signalKURL?.url){console.error("[SignalKConnectionService] Cannot retry - no current URL stored");return}console.log(`[SignalKConnectionService] Retrying connection to ${this.signalKURL.url}`),this.performHTTPDiscovery()}performHTTPDiscovery(){return C(this,null,function*(){if(!this.signalKURL?.url){console.error("[SignalKConnectionService] No URL available for HTTP discovery");return}let e=this.signalKURL.url;e.endsWith("signalk/")||(e+="/signalk/");try{console.log("[Connection Service] Connecting to: "+this.signalKURL.url);let i=yield b(this.http.get(e,{observe:"response"}).pipe(ne(this.TIMEOUT_DURATION),I(o=>(o.name==="TimeoutError"&&console.error("[Connection Service] Connection request timed out after "+this.TIMEOUT_DURATION+"ms"),Te(o))))),r=this.processEndpointResponse(i,this.currentProxyEnabled,this.currentSubscribeAll);this.connectionStateMachine.onHTTPDiscoverySuccess(),this.serverServiceEndpoint$.next(r)}catch(i){let r={operation:3,message:i.message,serverDescription:null,httpServiceUrl:null,WsServiceUrl:null};this.connectionStateMachine.onHTTPDiscoveryError(i.message),this.serverServiceEndpoint$.next(r),this.handleError(i)}})}processEndpointResponse(e,i,r){console.debug("[Connection Service] Signal K HTTP Endpoints retrieved"),this.serverVersion$.next(e.body.server.version);let o=e.body.endpoints.v1["signalk-http"],s=e.body.endpoints.v1["signalk-ws"],a={operation:2,message:e.status?.toString()||"Connected",serverDescription:`${e.body.server.id} ${e.body.server.version}`,httpServiceUrl:null,WsServiceUrl:null};if(i)console.debug("[Connection Service] Proxy Mode Enabled"),a.httpServiceUrl=window.location.origin+new URL(o).pathname,a.WsServiceUrl=window.location.protocol.replace("http","ws")+"//"+window.location.host+new URL(s).pathname;else{a.httpServiceUrl=o;let u=window.location.protocol==="https:";a.WsServiceUrl=u?s.replace("ws://","wss://"):s}return console.debug("[Connection Service] HTTP URI: "+a.httpServiceUrl),console.debug("[Connection Service] WebSocket URI: "+a.WsServiceUrl),a.subscribeAll=!!r,a}handleError(e){let i=e.status===0?`[Connection Service] ${e.name}: ${e.message}`:`[Connection Service] Backend returned code ${e.status}, body was: ${e.error}`;throw console.error(i),e}getServiceEndpointStatusAsO(){return this.serverServiceEndpoint$.asObservable()}setServerInfo(e,i,r){this.serverName=e,this.serverRoles=r,console.log(`[Connection Service] Server Name: ${e}, Version: ${i}, Roles: ${JSON.stringify(r)}`)}get skServerName(){return this.serverName}get skServerVersion(){return this.serverVersion$.getValue()}get skServerRoles(){return this.serverRoles}static \u0275fac=function(i){return new(i||n)};static \u0275prov=g({token:n,factory:n.\u0275fac,providedIn:"root"})}return n})();var ti="/signalk/v1/",at="auth/login",ii="auth/logout",ni="auth/validate",ri=60,lt=(()=>{class n{http=_(U);conn=_(le);_IsLoggedIn$=new h(!1);isLoggedIn$=this._IsLoggedIn$.asObservable();_authToken$=new h(null);authToken$=this._authToken$.asObservable();connectionEndpointSubscription=null;authTokenSubscription=null;isRenewingToken=!1;loginUrl=null;logoutUrl=null;validateTokenUrl=null;constructor(){let e=JSON.parse(localStorage.getItem("authorization_token"));e&&(e.isDeviceAccessToken?e.expiry===null?(console.log("[Authentication Service] Device Access Token found with expiry: NEVER"),this._authToken$.next(e)):this.isTokenExpired(e.expiry)?(console.log("[Authentication Service] Device Access Token expired. Deleting token"),localStorage.removeItem("authorization_token")):(console.log("[Authentication Service] Device Access Token found in Local Storage"),this._authToken$.next(e)):(console.log("[Authentication Service] User session token found in Local Storage"),console.log("[Authentication Service] Deleting user session token"),localStorage.removeItem("authorization_token"))),this.authTokenSubscription=this._authToken$.pipe(Xe(i=>!!i&&i.expiry!==null),tt((i,r)=>i.expiry===r.expiry),re(i=>{let r=this.getTokenExpirationDate(i.expiry,ri),o=r.getTime()-Date.now();return console.log(`[Authentication Service] Token refresh timer set for ${o} ms (Token Expiry: ${r.toISOString()})`),Math.max(o,0)}),it(i=>Qe(i))).subscribe(()=>{this.handleTokenRenewal()}),this.connectionEndpointSubscription=this.conn.serverServiceEndpoint$.subscribe(i=>{if(i.operation===2){let r=i.httpServiceUrl.substring(0,i.httpServiceUrl.length-4);this.loginUrl=r+at,this.logoutUrl=r+ii,this.validateTokenUrl=r+ni}})}handleTokenRenewal(){if(this.isRenewingToken){console.warn("[Authentication Service] Token renewal already in progress.");return}this.isRenewingToken=!0;let e=JSON.parse(localStorage.getItem("authorization_token"));if(!e){console.warn("[Authentication Service] No token found in local storage. Cannot renew."),this.isRenewingToken=!1;return}if(e.isDeviceAccessToken)console.warn("[Authentication Service] Device Access Token expired. Manual renewal required."),this.isRenewingToken=!1;else if(this.isTokenExpired(e.expiry))console.log("[Authentication Service] User session Token expired. Cannot renew."),this.isRenewingToken=!1;else{console.log("[Authentication Service] User session Token expires soon. Renewing token...");let i=JSON.parse(localStorage.getItem("connectionConfig"));this.login({usr:i.loginName,pwd:i.loginPassword}).then(()=>{console.log("[Authentication Service] Token successfully renewed.")}).catch(r=>{console.error("[Authentication Service] Token renewal failed. Server returned:",r.error)}).finally(()=>{this.isRenewingToken=!1})}}login(o){return C(this,arguments,function*({usr:e,pwd:i,newUrl:r}){let s;if(r?s=r.replace(/\/+$/,"")+ti+at:s=this.loginUrl,this._IsLoggedIn$.getValue()&&(yield this.logout(!0)),!s)throw console.error("[Authentication Service] Login URL is not set. Cannot perform login."),this.deleteToken(),new Error("Login URL is not set.");yield b(this.http.post(s,{username:e,password:i},{observe:"response"})).then(a=>{console.log("[Authentication Service] User "+e+" login successful"),this.setSession(a.body.token)}).catch(a=>{this.deleteToken(),this.handleError(a)})})}handleError(e){throw e.status===0&&this.deleteToken(),e}setSession(e){if(e){let i=JSON.parse(atob(e.split(".")[1])).exp,r={token:null,expiry:null,isDeviceAccessToken:!1};i===void 0?(r.token=e,console.log("[Authentication Service] User Session Token received. Token Expiration: NEVER"),this._IsLoggedIn$.next(!0),this._authToken$.next(r),localStorage.setItem("authorization_token",JSON.stringify(r))):this.isTokenExpired(i)?console.log("[Authentication Service] Received expired Session Token from server"):(r.token=e,r.expiry=i,console.log("[Authentication Service] Session Authorization Token received. Token Expiration: "+this.getTokenExpirationDate(r.expiry)),this._IsLoggedIn$.next(!0),this._authToken$.next(r),localStorage.setItem("authorization_token",JSON.stringify(r)))}}isTokenExpired(e){return Math.floor(new Date().getTime()/1e3)>=e}getTokenExpirationDate(e,i){let r=new Date(0);if(i){let o=new Date(0);o.setUTCSeconds(e-i),r=o}else r.setUTCSeconds(e);return r}renewToken(){return this.http.post(this.validateTokenUrl,null,{observe:"response"})}logout(e){return C(this,null,function*(){localStorage.removeItem("authorization_token"),yield b(this.http.put(this.logoutUrl,null)).then(()=>{this._IsLoggedIn$.next(!1),e||this._authToken$.next(null),console.log("[Authentication Service] User logged out")}).catch(i=>{console.error(i)})})}deleteToken(){this._authToken$&&(console.log("[Authentication Service] Deleting Authorization token"),localStorage.removeItem("authorization_token"),this._IsLoggedIn$.next(!1),this._authToken$.next(null))}setDeviceAccessToken(e){if(e){let i=JSON.parse(atob(e.split(".")[1])).exp,r={token:null,expiry:null,isDeviceAccessToken:!0};i===void 0?(r.token=e,console.log("[Authentication Service] Device Access Token received. Token Expiration: NEVER"),this._IsLoggedIn$.next(!1),this._authToken$.next(r),localStorage.setItem("authorization_token",JSON.stringify(r))):this.isTokenExpired(i)?console.log("[Authentication Service] Received expired Device Access Token from server"):(r.token=e,r.expiry=i,console.log("[Authentication Service] Device Access Token received. Token Expiration: "+this.getTokenExpirationDate(r.expiry)),this._IsLoggedIn$.next(!1),this._authToken$.next(r),localStorage.setItem("authorization_token",JSON.stringify(r)))}}ngOnDestroy(){this.connectionEndpointSubscription?.unsubscribe(),this.authTokenSubscription?.unsubscribe()}static \u0275fac=function(i){return new(i||n)};static \u0275prov=g({token:n,factory:n.\u0275fac,providedIn:"root"})}return n})();var oi=/^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i,Ne=n=>{if(typeof n!="string")throw new TypeError("Invalid argument expected string");let t=n.match(oi);if(!t)throw new Error(`Invalid argument not valid semver ('${n}' received)`);return t.shift(),t},ct=n=>n==="*"||n==="x"||n==="X",ut=n=>{let t=parseInt(n,10);return isNaN(t)?n:t},si=(n,t)=>typeof n!=typeof t?[String(n),String(t)]:[n,t],ai=(n,t)=>{if(ct(n)||ct(t))return 0;let[e,i]=si(ut(n),ut(t));return e>i?1:e<i?-1:0},xe=(n,t)=>{for(let e=0;e<Math.max(n.length,t.length);e++){let i=ai(n[e]||"0",t[e]||"0");if(i!==0)return i}return 0};var dt=(n,t)=>{let e=Ne(n),i=Ne(t),r=e.pop(),o=i.pop(),s=xe(e,i);return s!==0?s:r&&o?xe(r.split("."),o.split(".")):r||o?r?-1:1:0};var Fe=(n,t,e)=>{li(e);let i=dt(n,t);return ft[e].includes(i)},ft={">":[1],">=":[0,1],"=":[0],"<=":[-1,0],"<":[-1],"!=":[-1,1]},ht=Object.keys(ft),li=n=>{if(typeof n!="string")throw new TypeError(`Invalid operator type, expected string but got ${typeof n}`);if(ht.indexOf(n)===-1)throw new Error(`Invalid operator, expected one of ${ht.join("|")}`)};var gt=(()=>{class n{server=_(le);http=_(U);_auth=_(lt);serverEndpoint=null;isAppDataSupported=!1;configFileVersion=null;sharedConfigName;InitConfig=null;storageServiceReady$=new h(!1);_isLoggedIn=!1;_networkStatus=void 0;patchQueue$=new ie;patch=function(e){return this.http.post(e.url,e.document).pipe(nt(()=>console.log("[Storage Service] Remote config patch request completed successfully")),I(i=>this.handleError(i)))};constructor(){let e=this.server;this._auth.isLoggedIn$.pipe(q()).subscribe(i=>{this._isLoggedIn=i,this.isStorageServiceReady()}),e.serverServiceEndpoint$.pipe(q()).subscribe(i=>{this._networkStatus=i,this.isStorageServiceReady()}),e.serverVersion$.pipe(q()).subscribe(i=>{i&&(this.isAppDataSupported=Fe(i,"1.27.0",">="))}),this.patchQueue$.pipe(et(i=>this.patch(i)),q()).subscribe(()=>{})}isStorageServiceReady(){this._networkStatus?.httpServiceUrl&&(this.serverEndpoint=this._networkStatus.httpServiceUrl.substring(0,this._networkStatus.httpServiceUrl.length-4)+"applicationData/"),this._networkStatus?.operation===2&&this._isLoggedIn&&this.serverEndpoint?(this.storageServiceReady$.next(!0),console.log(`[Remote Storage Service] Authenticated ${this._isLoggedIn} ,AppData API: ${this.serverEndpoint}`)):this.storageServiceReady$.next(!1)}ensureReady(){if(!this.storageServiceReady$.getValue())throw new Error("[StorageService] Not ready: storageServiceReady is false")}listConfigs(e){return C(this,null,function*(){this.ensureReady();let i=[];if(!this.serverEndpoint)return console.warn("[Storage Service] No server endpoint set. Cannot retrieve config list"),null;let r=this.serverEndpoint,o=r+"global/kip/"+this.configFileVersion+"/?keys=true",s=r+"user/kip/"+this.configFileVersion+"/?keys=true";return e&&(o=r+"global/kip/"+e+"/?keys=true",s=r+"user/kip/"+e+"/?keys=true"),yield b(this.http.get(o)).then(a=>{for(let u of a)i.push({scope:"global",name:u});console.log("[Storage Service] Retrieved Global config list")}).catch(a=>{this.handleError(a)}),yield b(this.http.get(s)).then(a=>{for(let u of a)i.push({scope:"user",name:u});console.log("[Storage Service] Retrieved User config list")}).catch(a=>{this.handleError(a)}),i})}getConfig(e,i,r,o){return C(this,null,function*(){this.ensureReady();let s=null,a=this.serverEndpoint+e+"/kip/"+this.configFileVersion+"/"+i;return r&&(a=this.serverEndpoint+e+"/kip/"+r+"/"+i),yield b(this.http.get(a)).then(u=>{s=u,console.log(`[Storage Service] Retrieved config [${i}] from [${e}] scope`),o&&(this.InitConfig=u)}).catch(u=>{this.handleError(u)}),s})}setConfig(e,i,r,o){return C(this,null,function*(){this.ensureReady();let s=this.serverEndpoint+e+"/kip/"+this.configFileVersion+"/"+i,a=null;return o&&(s=this.serverEndpoint+e+"/kip/"+o+"/"+i),yield b(this.http.post(s,r)).then(u=>{console.log(`[Storage Service] Saved config [${i}] to [${e}] scope`),a=u}).catch(u=>{this.handleError(u)}),a})}patchConfig(e,i,r){this.ensureReady();let o=this.serverEndpoint+"user/kip/"+this.configFileVersion,s;switch(r&&(o=this.serverEndpoint+"user/kip/"+r),e){case"IAppConfig":s=[{op:"replace",path:`/${this.sharedConfigName}/app`,value:i}];break;case"IThemeConfig":s=[{op:"replace",path:`/${this.sharedConfigName}/theme/themeName`,value:i.themeName}];break;case"IWidgetConfig":s=[{op:"replace",path:`/${this.sharedConfigName}/widget`,value:i}];break;case"ILayoutConfig":s=[{op:"replace",path:`/${this.sharedConfigName}/layout`,value:i}];break;case"Dashboards":s=[{op:"replace",path:`/${this.sharedConfigName}/dashboards`,value:i}];break;case"Array<IUnitDefaults>":s=[{op:"replace",path:`/${this.sharedConfigName}/app/unitDefaults`,value:i}];break;case"Array<IDatasetDef>":s=[{op:"replace",path:`/${this.sharedConfigName}/app/dataSets`,value:i}];break;case"INotificationConfig":s=[{op:"replace",path:`/${this.sharedConfigName}/app/notificationConfig`,value:i}];break;default:console.warn("[Storage Service] JSON Patch request type unknown");break}let a={url:o,document:s};this.patchQueue$.next(a)}patchGlobal(e,i,r,o,s){this.ensureReady();let a=this.serverEndpoint+i+"/kip/"+this.configFileVersion;s&&(a=this.serverEndpoint+i+"/kip/"+s);let u;switch(o){case"add":u=[{op:"add",path:`/${e}`,value:r}];break;case"replace":u=[{op:"replace",path:`/${e}`,value:r}];break;case"remove":u=[{op:"remove",path:`/${e}`,value:r}];break;default:console.warn("[Storage Service] JSON Patch operation request type unknown");break}let ei={url:a,document:u};this.patchQueue$.next(ei)}removeItem(e,i,r){this.ensureReady();let o=this.serverEndpoint+e+"/kip/"+this.configFileVersion;r&&(o=this.serverEndpoint+e+"/kip/"+r);let s=[{op:"remove",path:`/${i}`}],a={url:o,document:s};this.patchQueue$.next(a)}clear(){this.ensureReady()}set activeConfigFileVersion(e){this.configFileVersion=e}handleError(e){throw e.status===0?console.error("[Storage Service] An error occurred:",e.error):console.error("[Storage Service] Backend returned error: ",e.message),e}get initConfig(){return this.InitConfig}static \u0275fac=function(i){return new(i||n)};static \u0275prov=g({token:n,factory:n.\u0275fac,providedIn:"root"})}return n})();var M=class{static create(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){let e=Math.random()*16|0;return(t=="x"?e:e&3|8).toString(16)})}};var K={disableNotifications:!1,menuGrouping:!0,security:{disableSecurity:!0},devices:{disableDevices:!1,showNormalState:!1,showNominalState:!1},sound:{disableSound:!1,muteNormal:!0,muteNominal:!0,muteWarn:!0,muteAlert:!1,muteAlarm:!1,muteEmergency:!1}};var ce={Unitless:"unitless",Speed:"knots",Flow:"l/h",Temperature:"celsius",Length:"m",Volume:"liter",Current:"A",Potential:"V",Charge:"C",Power:"W",Energy:"J",Pressure:"mmHg","Fuel Distance":"nm/l","Energy Distance":"nm/kWh",Density:"kg/m3",Time:"Hours","Angular Velocity":"deg/min",Angle:"deg",Frequency:"Hz",Ratio:"ratio",Resistance:"ohm"};var pt={configVersion:11,autoNightMode:!0,redNightMode:!1,nightModeBrightness:.27,isRemoteControl:!1,instanceName:"",dataSets:[],unitDefaults:ce,notificationConfig:K},mt={themeName:""};var vt={configVersion:11,kipUUID:M.create(),signalKUrl:null,proxyEnabled:!1,signalKSubscribeAll:!1,useDeviceToken:!1,loginName:null,loginPassword:null,useSharedConfig:!1,sharedConfigName:"default"};var Ie={configVersion:11,autoNightMode:!1,redNightMode:!1,nightModeBrightness:.27,isRemoteControl:!1,instanceName:"",dataSets:[{uuid:"afbe4e41-26f5-404f-a55d-9f7b9b76fbd1",path:"self.environment.wind.speedApparent",pathSource:"default",period:1,baseUnit:"m/s",label:"self.environment.wind.speedApparent, Source: default, Scale: minute, Period: 1",timeScaleFormat:"minute"}],unitDefaults:{Unitless:"unitless",Speed:"knots",Flow:"l/h",Temperature:"celsius",Length:"m",Volume:"liter",Current:"A",Potential:"V",Charge:"C",Power:"W",Energy:"J",Pressure:"mmHg","Fuel Distance":"nm/l","Energy Distance":"nm/kWh",Density:"kg/m3",Time:"Hours","Angular Velocity":"deg/min",Angle:"deg",Frequency:"Hz",Ratio:"ratio",Resistance:"ohm"},notificationConfig:{disableNotifications:!1,menuGrouping:!0,security:{disableSecurity:!0},devices:{disableDevices:!1,showNormalState:!1,showNominalState:!1},sound:{disableSound:!1,muteNormal:!0,muteNominal:!0,muteWarn:!0,muteAlert:!1,muteAlarm:!1,muteEmergency:!1}}},Re=[{id:"3e0825ee-95fd-4ad4-8802-e0507845b668",name:"Sailing",icon:"dashboard-sailing",configuration:[{w:3,h:4,id:"339698a7-2cff-4ab9-9b50-d8056f971471",selector:"widget-numeric",input:{widgetProperties:{type:"widget-numeric",uuid:"339698a7-2cff-4ab9-9b50-d8056f971471",config:{displayName:"Depth",filterSelfPaths:!0,paths:{numericPath:{description:"Numeric Data",path:"self.environment.depth.belowTransducer",source:"default",pathType:"number",isPathConfigurable:!0,convertUnitTo:"m",showPathSkUnitsFilter:!0,pathSkUnitsFilter:null,sampleTime:500}},showMax:!1,showMin:!1,numDecimal:1,showMiniChart:!0,yScaleMin:0,yScaleMax:100,inverseYAxis:!1,verticalChart:!1,color:"blue",enableTimeout:!1,dataTimeout:5,ignoreZones:!1}}},x:0,y:0},{w:5,h:10,id:"a44028e0-dfee-4492-895b-2b03a60f3a69",selector:"widget-wind-steer",input:{widgetProperties:{type:"widget-wind-steer",uuid:"a44028e0-dfee-4492-895b-2b03a60f3a69",config:{filterSelfPaths:!0,paths:{headingPath:{description:"True Heading",path:"self.navigation.headingTrue",source:"default",pathType:"number",isPathConfigurable:!0,pathRequired:!0,showPathSkUnitsFilter:!1,pathSkUnitsFilter:"rad",convertUnitTo:"deg",showConvertUnitTo:!1,sampleTime:500},appWindAngle:{description:"Apparent Wind Angle",path:"self.environment.wind.angleApparent",source:"default",pathType:"number",isPathConfigurable:!0,pathRequired:!0,showPathSkUnitsFilter:!1,pathSkUnitsFilter:"rad",convertUnitTo:"deg",showConvertUnitTo:!1,sampleTime:500},appWindSpeed:{description:"Apparent Wind Speed",path:"self.environment.wind.speedApparent",source:"default",pathType:"number",isPathConfigurable:!0,pathRequired:!0,showPathSkUnitsFilter:!1,pathSkUnitsFilter:"m/s",convertUnitTo:"knots",sampleTime:500},trueWindAngle:{description:"True Wind Angle",path:"self.environment.wind.angleTrueWater",source:"default",pathType:"number",isPathConfigurable:!0,pathRequired:!1,showPathSkUnitsFilter:!1,pathSkUnitsFilter:"rad",convertUnitTo:"deg",showConvertUnitTo:!1,sampleTime:500},trueWindSpeed:{description:"True Wind Speed",path:"self.environment.wind.speedTrue",source:"default",pathType:"number",isPathConfigurable:!0,pathRequired:!1,showPathSkUnitsFilter:!1,pathSkUnitsFilter:"m/s",convertUnitTo:"knots",sampleTime:500},courseOverGround:{description:"True Course Over Ground",path:"self.navigation.courseOverGroundTrue",source:"default",pathType:"number",isPathConfigurable:!0,pathRequired:!1,showPathSkUnitsFilter:!1,pathSkUnitsFilter:"rad",showConvertUnitTo:!1,convertUnitTo:"deg",sampleTime:500},nextWaypointBearing:{description:"Next Waypoint True Bearing",path:"self.navigation.courseGreatCircle.nextPoint.bearingTrue",source:"default",pathType:"number",isPathConfigurable:!1,pathRequired:!1,showPathSkUnitsFilter:!1,pathSkUnitsFilter:"rad",convertUnitTo:"deg",showConvertUnitTo:!1,sampleTime:500},set:{description:"True Drift Set",path:"self.environment.current.setTrue",source:"default",pathType:"number",isPathConfigurable:!0,pathRequired:!1,showPathSkUnitsFilter:!1,pathSkUnitsFilter:"rad",convertUnitTo:"deg",showConvertUnitTo:!1,sampleTime:500},drift:{description:"Drift Speed Impact",path:"self.environment.current.drift",source:"default",pathType:"number",isPathConfigurable:!0,pathRequired:!1,showPathSkUnitsFilter:!1,pathSkUnitsFilter:"m/s",convertUnitTo:"knots",sampleTime:500}},windSectorEnable:!0,windSectorWindowSeconds:5,laylineEnable:!0,laylineAngle:40,waypointEnable:!0,courseOverGroundEnable:!0,driftEnable:!0,awsEnable:!0,twsEnable:!0,sailSetupEnable:!1,enableTimeout:!1,dataTimeout:5}}},x:3,y:0},{w:4,h:6,id:"24406c15-7738-4dc1-a206-7a4862c2931d",selector:"widget-gauge-ng-radial",input:{widgetProperties:{type:"widget-gauge-ng-radial",uuid:"24406c15-7738-4dc1-a206-7a4862c2931d",config:{displayName:"SOG",filterSelfPaths:!0,paths:{gaugePath:{description:"Numeric Data",path:"self.navigation.speedOverGround",source:"default",pathType:"number",isPathConfigurable:!0,showPathSkUnitsFilter:!0,pathSkUnitsFilter:null,convertUnitTo:"knots",sampleTime:500}},displayScale:{lower:0,upper:10,type:"linear"},gauge:{type:"ngRadial",subType:"measuring",enableTicks:!0,compassUseNumbers:!1,highlightsWidth:5,scaleStart:180},numInt:1,numDecimal:1,enableTimeout:!1,color:"yellow",dataTimeout:5,ignoreZones:!1}}},x:8,y:0},{w:3,h:4,id:"c6bcaa53-afa1-42c7-ad92-d5f7dba14734",selector:"widget-numeric",input:{widgetProperties:{type:"widget-numeric",uuid:"c6bcaa53-afa1-42c7-ad92-d5f7dba14734",config:{displayName:"STW",filterSelfPaths:!0,paths:{numericPath:{description:"Numeric Data",path:"self.navigation.speedThroughWater",source:"default",pathType:"number",isPathConfigurable:!0,convertUnitTo:"knots",showPathSkUnitsFilter:!0,pathSkUnitsFilter:null,sampleTime:500}},showMax:!0,showMin:!0,numDecimal:1,showMiniChart:!1,yScaleMin:0,yScaleMax:10,inverseYAxis:!1,verticalChart:!1,color:"contrast",enableTimeout:!1,dataTimeout:5,ignoreZones:!1}}},x:0,y:4},{w:4,h:6,id:"973c8804-be09-4923-bb5d-48c13b65db69",selector:"widget-data-chart",input:{widgetProperties:{type:"widget-data-chart",uuid:"973c8804-be09-4923-bb5d-48c13b65db69",config:{displayName:"Chart Label",filterSelfPaths:!0,convertUnitTo:"knots",datasetUUID:"afbe4e41-26f5-404f-a55d-9f7b9b76fbd1",inverseYAxis:!1,datasetAverageArray:"sma",showAverageData:!0,trackAgainstAverage:!1,showDatasetMinimumValueLine:!1,showDatasetMaximumValueLine:!1,showDatasetAverageValueLine:!0,showDatasetAngleAverageValueLine:!1,showLabel:!1,showTimeScale:!0,startScaleAtZero:!1,verticalChart:!1,showYScale:!0,yScaleSuggestedMin:null,yScaleSuggestedMax:null,enableMinMaxScaleLimit:!1,yScaleMin:null,yScaleMax:null,numDecimal:1,color:"orange",invertData:!1,verticalGraph:!1}}},x:8,y:6},{x:0,y:8,w:3,h:4,minW:1,minH:1,id:"5289a84d-18fd-4ee7-9724-72249af403f2",selector:"widget-position",input:{widgetProperties:{type:"widget-position",uuid:"5289a84d-18fd-4ee7-9724-72249af403f2",config:{displayName:"Position",filterSelfPaths:!0,paths:{longPath:{description:"Longitude",path:"self.navigation.position.longitude",source:"default",pathType:"number",isPathConfigurable:!0,convertUnitTo:"longitudeMin",showPathSkUnitsFilter:!0,pathSkUnitsFilter:null,sampleTime:500},latPath:{description:"Latitude",path:"self.navigation.position.latitude",source:"default",pathType:"number",isPathConfigurable:!0,convertUnitTo:"latitudeMin",showPathSkUnitsFilter:!0,pathSkUnitsFilter:null,sampleTime:500}},color:"grey",enableTimeout:!1,dataTimeout:5}}}},{w:5,h:2,id:"1a7a3f79-2eb4-4092-a0c3-9a61db8a8586",selector:"widget-simple-linear",input:{widgetProperties:{type:"widget-simple-linear",uuid:"1a7a3f79-2eb4-4092-a0c3-9a61db8a8586",config:{displayName:"House Bank",filterSelfPaths:!0,paths:{gaugePath:{description:"Numeric Data",path:"self.electrical.batteries.1.voltage",source:"default",pathType:"number",isPathConfigurable:!0,showPathSkUnitsFilter:!0,pathSkUnitsFilter:"V",convertUnitTo:"V",sampleTime:500}},displayScale:{lower:0,upper:15,type:"linear"},gauge:{type:"simpleLinear",unitLabelFormat:"full"},numInt:1,numDecimal:2,ignoreZones:!1,color:"green",enableTimeout:!1,dataTimeout:5}}},x:3,y:10}]},{id:"7c67c8c5-dc55-4e1d-9fc5-3dd95fd41bea",name:"Charting",icon:"dashboard-map",configuration:[{x:0,y:0,w:8,h:12,id:"488d620a-37d4-4b98-849d-304cd18003e9",selector:"widget-freeboardsk",input:{widgetProperties:{type:"widget-freeboardsk",uuid:"488d620a-37d4-4b98-849d-304cd18003e9"}}},{x:8,y:0,w:2,h:3,id:"26a2a150-5af8-4f1d-aaab-0cb2a406fc17",selector:"widget-gauge-ng-compass",input:{widgetProperties:{type:"widget-gauge-ng-compass",uuid:"26a2a150-5af8-4f1d-aaab-0cb2a406fc17",config:{displayName:"COG (T)",filterSelfPaths:!0,paths:{gaugePath:{description:"Numeric Data",path:"self.navigation.courseOverGroundTrue",source:"default",pathType:"number",isPathConfigurable:!0,showPathSkUnitsFilter:!1,pathSkUnitsFilter:"rad",showConvertUnitTo:!1,convertUnitTo:"deg",sampleTime:500}},gauge:{type:"ngRadial",subType:"marineCompass",enableTicks:!0,compassUseNumbers:!0,showValueBox:!1},enableTimeout:!1,color:"purple",dataTimeout:5}}}},{x:10,y:0,w:2,h:3,id:"caf9ca47-fcf6-4736-a314-2b5210edaf03",selector:"widget-datetime",input:{widgetProperties:{type:"widget-datetime",uuid:"caf9ca47-fcf6-4736-a314-2b5210edaf03",config:{displayName:"Next WP Arrival",filterSelfPaths:!0,paths:{gaugePath:{description:"String Data",path:"self.navigation.datetime",source:"default",pathType:"Date",isPathConfigurable:!0,sampleTime:500}},dateFormat:"dd/MM HH:mm",dateTimezone:"America/Toronto",color:"contrast",enableTimeout:!1,dataTimeout:5}}}},{x:8,y:3,w:4,h:9,id:"daa21350-009e-4d99-8209-364f9b99caee",selector:"widget-autopilot",input:{widgetProperties:{type:"widget-autopilot",uuid:"daa21350-009e-4d99-8209-364f9b99caee",config:{filterSelfPaths:!0,paths:{autopilotState:{description:"Autopilot State",path:"self.steering.autopilot.state",source:"default",pathType:"string",isPathConfigurable:!1,showPathSkUnitsFilter:!1,convertUnitTo:"",sampleTime:500},autopilotTargetHeading:{description:"Autopilot Target Magnetic Heading",path:"self.steering.autopilot.target.headingMagnetic",source:"default",pathType:"number",convertUnitTo:"deg",isPathConfigurable:!1,showPathSkUnitsFilter:!1,pathSkUnitsFilter:"rad",sampleTime:500},autopilotTargetWindHeading:{description:"Autopilot Target Apparent Wind Angle",path:"self.steering.autopilot.target.windAngleApparent",source:"default",pathType:"number",convertUnitTo:"deg",isPathConfigurable:!1,showPathSkUnitsFilter:!1,pathSkUnitsFilter:"rad",sampleTime:500},rudderAngle:{description:"Rudder Angle",path:"self.steering.rudderAngle",source:"default",pathType:"number",convertUnitTo:"deg",isPathConfigurable:!1,showPathSkUnitsFilter:!1,pathSkUnitsFilter:"rad",sampleTime:500},courseXte:{description:"Cross Track Error",path:"self.navigation.course.calcValues.crossTrackError",source:"default",pathType:"number",isPathConfigurable:!1,convertUnitTo:"m",showPathSkUnitsFilter:!0,pathRequired:!1,pathSkUnitsFilter:"m",sampleTime:500},headingMag:{description:"Magnetic Heading",path:"self.navigation.headingMagnetic",source:"default",pathType:"number",convertUnitTo:"deg",isPathConfigurable:!0,pathRequired:!1,showPathSkUnitsFilter:!1,pathSkUnitsFilter:"rad",showConvertUnitTo:!1,sampleTime:500},headingTrue:{description:"True Heading",path:"self.navigation.headingTrue",source:"default",pathType:"number",convertUnitTo:"deg",isPathConfigurable:!0,pathRequired:!1,showPathSkUnitsFilter:!1,pathSkUnitsFilter:"rad",showConvertUnitTo:!1,sampleTime:500},windAngleApparent:{description:"Apparent Wind Angle",path:"self.environment.wind.angleApparent",source:"default",pathType:"number",convertUnitTo:"deg",isPathConfigurable:!0,pathRequired:!1,showPathSkUnitsFilter:!1,pathSkUnitsFilter:"rad",showConvertUnitTo:!1,sampleTime:500},windAngleTrueWater:{description:"Wind Angle True Water",path:"self.environment.wind.angleTrueWater",source:"default",pathType:"number",convertUnitTo:"deg",isPathConfigurable:!0,pathRequired:!1,showPathSkUnitsFilter:!1,pathSkUnitsFilter:"rad",showConvertUnitTo:!1,sampleTime:500}},invertRudder:!0,headingDirectionTrue:!1,courseDirectionTrue:!1,enableTimeout:!1,dataTimeout:5,autopilotInstance:"_default"}}}}]}],Pe={themeName:""};var Gn={configVersion:11,kipUUID:M.create(),signalKUrl:"https://demo.signalk.org",proxyEnabled:!1,signalKSubscribeAll:!1,useDeviceToken:!1,loginName:null,loginPassword:null,useSharedConfig:!1,sharedConfigName:"default"};var ci="",ui=11,z=11,tr=(()=>{class n{storage=_(gt);unitDefaults=new h({});themeName=new h(ci);kipKNotificationConfig=new h(K);autoNightMode=new h(!1);redNightMode=new h(!1);nightModeBrightness=new h(1);isRemoteControl=new h(!1);instanceName=new h("");proxyEnabled=!1;signalKSubscribeAll=!1;useDeviceToken=!1;loginName;loginPassword;useSharedConfig;sharedConfigName;activeConfig={app:null,theme:null,dashboards:null};kipUUID;signalkUrl;widgets;_dashboards=[];dataSets=[];configUpgrade=A(!1);constructor(){if(console.log("[AppSettings Service] Service startup..."),this.storage.activeConfigFileVersion=ui,!window.localStorage)console.error(`[AppSettings Service] LocalStorage NOT SUPPORTED by browser
|
|
2
2
|
This is a requirement to run Kip. See browser documentation to enable this feature.`);else{this.loadConnectionConfig();let e;if(this.storage.initConfig===null&&this.useSharedConfig&&this.loginName!==null&&this.loginPassword!==null&&this.signalkUrl.url!==null?this.resetSettings():e=this.storage.initConfig,e)console.log("[AppSettings Service] Remote configuration storage enabled"),this.checkConfigUpgradeRequired(!1),this.activeConfig=e,this.pushSettings();else{console.log("[AppSettings Service] LocalStorage enabled");let i={app:null,theme:null,dashboards:null};i.app=this.loadConfigFromLocalStorage("appConfig"),i.app.configVersion!==z&&this.checkConfigUpgradeRequired(!0),i.dashboards=this.loadConfigFromLocalStorage("dashboardsConfig"),i.theme=this.loadConfigFromLocalStorage("themeConfig"),this.activeConfig=i,this.pushSettings()}}}loadConnectionConfig(){let e=this.loadConfigFromLocalStorage("connectionConfig");switch(e.configVersion){case 11:break;default:console.error(`[AppSettings Service] Invalid connectionConfig version ${e.configVersion}. Resetting and loading connection configuration default`),this.resetConnection();break}this.signalkUrl={url:e.signalKUrl,new:!1},this.proxyEnabled=e.proxyEnabled,this.signalKSubscribeAll=e.signalKSubscribeAll,this.useDeviceToken=e.useDeviceToken,this.loginName=e.loginName,this.loginPassword=e.loginPassword,this.useSharedConfig=e.useSharedConfig,this.sharedConfigName=e.sharedConfigName,this.kipUUID=e.kipUUID}resetConnection(){localStorage.setItem("connectionConfig",JSON.stringify(this.getDefaultConnectionConfig())),this.reloadApp()}checkConfigUpgradeRequired(e){e?this.configUpgrade.set(!0):this.storage.listConfigs(9).then(i=>C(this,null,function*(){for(let r of i)try{if((yield this.storage.getConfig(r.scope,r.name,9)).app?.configVersion===10){this.configUpgrade.set(!0),console.log("[AppSettings Service] Configuration upgrade required for version 10.");break}}catch(o){console.error(`[AppSettings Service] Error fetching configuration for ${r.name}:`,o)}})).catch(i=>{console.error("[AppSettings Service] Error fetching configuration data:",i)})}loadConfigFromLocalStorage(e){let i=JSON.parse(localStorage.getItem(e));if(i===null)switch(console.log(`[AppSettings Service] Error loading ${e} config. Force loading ${e} defaults`),e){case"appConfig":i=this.getDefaultAppConfig();break;case"connectionConfig":i=this.getDefaultConnectionConfig();break;case"dashboardsConfig":i=this.getDefaultDashboardsConfig();break;case"themeConfig":i=this.getDefaultThemeConfig();break;default:console.error(`[AppSettings Service] Invalid ${e} default config requested`);break}if(e==="connectionConfig"&&i.configVersion!==z)switch(console.log(`[AppSettings Service] Invalid ${e} version. Force loading defaults`),e){case"connectionConfig":i=this.getDefaultConnectionConfig();break}return i}pushSettings(){this.themeName.next(this.activeConfig.theme.themeName),this.dataSets=this.activeConfig.app.dataSets,this.unitDefaults.next(this.activeConfig.app.unitDefaults),this.kipKNotificationConfig.next(this.activeConfig.app.notificationConfig),this.activeConfig.app.autoNightMode===void 0?this.setAutoNightMode(!1):this.autoNightMode.next(this.activeConfig.app.autoNightMode),this.activeConfig.app.redNightMode===void 0?this.setRedNightMode(!1):this.redNightMode.next(this.activeConfig.app.redNightMode),this.activeConfig.app.nightModeBrightness===void 0?this.setNightModeBrightness(.2):this.nightModeBrightness.next(this.activeConfig.app.nightModeBrightness),this.activeConfig.dashboards===void 0?this._dashboards=[]:this._dashboards=this.activeConfig.dashboards,this.activeConfig.app.isRemoteControl===void 0?this.setIsRemoteControl(!1):this.isRemoteControl.next(this.activeConfig.app.isRemoteControl),this.activeConfig.app.instanceName===void 0?this.setInstanceName(""):this.instanceName.next(this.activeConfig.app.instanceName)}getDefaultUnitsAsO(){return this.unitDefaults.asObservable()}getDefaultUnits(){return this.unitDefaults.getValue()}setDefaultUnits(e){this.unitDefaults.next(e),this.useSharedConfig?this.storage.patchConfig("Array<IUnitDefaults>",e):this.saveAppConfigToLocalStorage()}getAppConfig(){return this.buildAppStorageObject()}getConnectionConfig(){return this.buildConnectionStorageObject()}setConnectionConfig(e){this.loginName=e.loginName,this.loginPassword=e.loginPassword,this.useSharedConfig=e.useSharedConfig,this.proxyEnabled=e.proxyEnabled,this.signalKSubscribeAll=e.signalKSubscribeAll,this.signalkUrl.url=e.signalKUrl,e.useSharedConfig?this.useDeviceToken=!1:this.useDeviceToken=!0,this.saveConnectionConfigToLocalStorage()}setUseDeviceToken(e){this.useDeviceToken=e,this.saveConnectionConfigToLocalStorage()}getDashboardConfig(){return this.buildDashboardStorageObject()}getThemeConfig(){return this.buildThemeStorageObject()}get KipUUID(){return this.kipUUID}getThemeNameAsO(){return this.themeName.asObservable()}setThemeName(e){if(this.themeName.next(e),this.useSharedConfig){let i={themeName:e};this.storage.patchConfig("IThemeConfig",i)}else this.saveThemeConfigToLocalStorage()}getThemeName(){return this.themeName.getValue()}getAutoNightModeAsO(){return this.autoNightMode.asObservable()}setAutoNightMode(e){this.autoNightMode.next(e);let i=this.buildAppStorageObject();this.useSharedConfig?this.storage.patchConfig("IAppConfig",i):this.saveAppConfigToLocalStorage()}getAutoNightMode(){return this.autoNightMode.getValue()}getRedNightModeAsO(){return this.redNightMode.asObservable()}getRedNightMode(){return this.redNightMode.getValue()}setRedNightMode(e){this.redNightMode.next(e);let i=this.buildAppStorageObject();this.useSharedConfig?this.storage.patchConfig("IAppConfig",i):this.saveAppConfigToLocalStorage()}getIsRemoteControlAsO(){return this.isRemoteControl.asObservable()}getIsRemoteControl(){return this.isRemoteControl.getValue()}setIsRemoteControl(e){this.isRemoteControl.next(e);let i=this.buildAppStorageObject();this.useSharedConfig?this.storage.patchConfig("IAppConfig",i):this.saveAppConfigToLocalStorage()}getInstanceNameAsO(){return this.instanceName.asObservable()}getInstanceName(){return this.instanceName.getValue()}setInstanceName(e){this.instanceName.next(e);let i=this.buildAppStorageObject();this.useSharedConfig?this.storage.patchConfig("IAppConfig",i):this.saveAppConfigToLocalStorage()}getNightModeBrightness(){return this.nightModeBrightness.getValue()}setNightModeBrightness(e){this.nightModeBrightness.next(e);let i=this.buildAppStorageObject();this.useSharedConfig?this.storage.patchConfig("IAppConfig",i):this.saveAppConfigToLocalStorage()}getWidgets(){return this.widgets}saveDashboards(e){this.useSharedConfig?this.storage.storageServiceReady$.getValue()&&this.storage.patchConfig("Dashboards",e):this.saveLDashboardsConfigToLocalStorage(e),this._dashboards=e}saveDataSets(e){this.dataSets=e,this.useSharedConfig?this.storage.patchConfig("Array<IDatasetDef>",e):this.saveAppConfigToLocalStorage()}getDataSets(){return this.dataSets}getNotificationServiceConfigAsO(){return this.kipKNotificationConfig.asObservable()}getNotificationConfig(){return this.kipKNotificationConfig.getValue()}setNotificationConfig(e){this.kipKNotificationConfig.next(e),this.useSharedConfig?this.storage.patchConfig("INotificationConfig",e):this.saveAppConfigToLocalStorage()}resetSettings(){let e={app:null,theme:null,dashboards:null};e.app=this.getDefaultAppConfig(),e.theme=this.getDefaultThemeConfig(),e.dashboards=this.getDefaultDashboardsConfig(),this.useSharedConfig?this.storage.storageServiceReady$.getValue()&&this.storage.setConfig("user",this.sharedConfigName,e).then(()=>{console.log("[AppSettings Service] Replaced server config name: "+this.sharedConfigName+", with default configuration values"),this.reloadApp()}).catch(i=>{console.error("[AppSettings Service] Error replacing server config name: "+this.sharedConfigName+", with default configuration values",i)}):this.reloadApp()}replaceConfig(e,i,r){let o=JSON.stringify(i);localStorage.setItem(e,o),r&&this.reloadApp()}loadDemoConfig(){if(this.useSharedConfig){let e={app:Ie,dashboards:Re,theme:Pe};console.log("[AppSettings Service] Loading Demo configuration settings as remote config: "+this.useSharedConfig+" and reloading app."),this.storage.setConfig("user",this.sharedConfigName,e),this.reloadApp()}else console.log("[AppSettings Service] Loading Demo configuration settings to LocalStorage"),this.replaceConfig("appConfig",Ie),this.replaceConfig("dashboardsConfig",Re),this.replaceConfig("themeConfig",Pe,!0)}reloadApp(){console.log("[AppSettings Service] Reload app"),!window.__KIP_TEST__&&location.replace("./")}buildAppStorageObject(){return{configVersion:z,autoNightMode:this.autoNightMode.getValue(),redNightMode:this.redNightMode.getValue(),nightModeBrightness:this.nightModeBrightness.getValue(),isRemoteControl:this.isRemoteControl.getValue(),instanceName:this.instanceName.getValue(),dataSets:this.dataSets,unitDefaults:this.unitDefaults.getValue(),notificationConfig:this.kipKNotificationConfig.getValue()}}buildConnectionStorageObject(){return{configVersion:z,kipUUID:this.kipUUID,signalKUrl:this.signalkUrl.url,proxyEnabled:this.proxyEnabled,signalKSubscribeAll:this.signalKSubscribeAll,useDeviceToken:this.useDeviceToken,loginName:this.loginName,loginPassword:this.loginPassword,useSharedConfig:this.useSharedConfig,sharedConfigName:this.sharedConfigName}}buildDashboardStorageObject(){return this._dashboards}buildThemeStorageObject(){return{themeName:this.themeName.getValue()}}saveAppConfigToLocalStorage(){console.log("[AppSettings Service] Saving Application config to LocalStorage"),localStorage.setItem("appConfig",JSON.stringify(this.buildAppStorageObject()))}saveConnectionConfigToLocalStorage(){console.log("[AppSettings Service] Saving Connection config to LocalStorage"),localStorage.setItem("connectionConfig",JSON.stringify(this.buildConnectionStorageObject()))}saveLDashboardsConfigToLocalStorage(e){console.log("[AppSettings Service] Saving Dashboard config to LocalStorage"),localStorage.setItem("dashboardsConfig",JSON.stringify(e))}saveThemeConfigToLocalStorage(){console.log("[AppSettings Service] Saving Theme config to LocalStorage"),localStorage.setItem("themeConfig",JSON.stringify(this.buildThemeStorageObject()))}getDefaultAppConfig(){let e=pt;return e.notificationConfig=K,e.unitDefaults=ce,e.configVersion=z,localStorage.setItem("appConfig",JSON.stringify(e)),e}getDefaultConnectionConfig(){let e=vt;return e.kipUUID=M.create(),e.signalKUrl=window.location.origin,localStorage.setItem("connectionConfig",JSON.stringify(e)),e}getDefaultDashboardsConfig(){let e=[];return localStorage.setItem("dashboardsConfig",JSON.stringify(e)),e}getDefaultThemeConfig(){let e=mt;return localStorage.setItem("themeConfig",JSON.stringify(e)),e}static \u0275fac=function(i){return new(i||n)};static \u0275prov=g({token:n,factory:n.\u0275fac,providedIn:"root"})}return n})();var Vt=(()=>{class n{_renderer;_elementRef;onChange=e=>{};onTouched=()=>{};constructor(e,i){this._renderer=e,this._elementRef=i}setProperty(e,i){this._renderer.setProperty(this._elementRef.nativeElement,e,i)}registerOnTouched(e){this.onTouched=e}registerOnChange(e){this.onChange=e}setDisabledState(e){this.setProperty("disabled",e)}static \u0275fac=function(i){return new(i||n)(c(Ae),c(Ve))};static \u0275dir=d({type:n})}return n})(),At=(()=>{class n extends Vt{static \u0275fac=(()=>{let e;return function(r){return(e||(e=w(n)))(r||n)}})();static \u0275dir=d({type:n,features:[f]})}return n})(),te=new N("");var di={provide:te,useExisting:m(()=>kt),multi:!0};function hi(){let n=Ee()?Ee().getUserAgent():"";return/android (\d+)/.test(n.toLowerCase())}var fi=new N(""),kt=(()=>{class n extends Vt{_compositionMode;_composing=!1;constructor(e,i,r){super(e,i),this._compositionMode=r,this._compositionMode==null&&(this._compositionMode=!hi())}writeValue(e){let i=e??"";this.setProperty("value",i)}_handleInput(e){(!this._compositionMode||this._compositionMode&&!this._composing)&&this.onChange(e)}_compositionStart(){this._composing=!0}_compositionEnd(e){this._composing=!1,this._compositionMode&&this.onChange(e)}static \u0275fac=function(i){return new(i||n)(c(Ae),c(Ve),c(fi,8))};static \u0275dir=d({type:n,selectors:[["input","formControlName","",3,"type","checkbox"],["textarea","formControlName",""],["input","formControl","",3,"type","checkbox"],["textarea","formControl",""],["input","ngModel","",3,"type","checkbox"],["textarea","ngModel",""],["","ngDefaultControl",""]],hostBindings:function(i,r){i&1&&B("input",function(s){return r._handleInput(s.target.value)})("blur",function(){return r.onTouched()})("compositionstart",function(){return r._compositionStart()})("compositionend",function(s){return r._compositionEnd(s.target.value)})},standalone:!1,features:[v([di]),f]})}return n})();function je(n){return n==null||He(n)===0}function He(n){return n==null?null:Array.isArray(n)||typeof n=="string"?n.length:n instanceof Set?n.size:null}var D=new N(""),F=new N(""),gi=/^(?=.{1,254}$)(?=.{1,64}@)[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,yt=class{static min(t){return Mt(t)}static max(t){return Et(t)}static required(t){return Nt(t)}static requiredTrue(t){return pi(t)}static email(t){return mi(t)}static minLength(t){return vi(t)}static maxLength(t){return yi(t)}static pattern(t){return xt(t)}static nullValidator(t){return de()}static compose(t){return Ot(t)}static composeAsync(t){return $t(t)}};function Mt(n){return t=>{if(t.value==null||n==null)return null;let e=parseFloat(t.value);return!isNaN(e)&&e<n?{min:{min:n,actual:t.value}}:null}}function Et(n){return t=>{if(t.value==null||n==null)return null;let e=parseFloat(t.value);return!isNaN(e)&&e>n?{max:{max:n,actual:t.value}}:null}}function Nt(n){return je(n.value)?{required:!0}:null}function pi(n){return n.value===!0?null:{required:!0}}function mi(n){return je(n.value)||gi.test(n.value)?null:{email:!0}}function vi(n){return t=>{let e=t.value?.length??He(t.value);return e===null||e===0?null:e<n?{minlength:{requiredLength:n,actualLength:e}}:null}}function yi(n){return t=>{let e=t.value?.length??He(t.value);return e!==null&&e>n?{maxlength:{requiredLength:n,actualLength:e}}:null}}function xt(n){if(!n)return de;let t,e;return typeof n=="string"?(e="",n.charAt(0)!=="^"&&(e+="^"),e+=n,n.charAt(n.length-1)!=="$"&&(e+="$"),t=new RegExp(e)):(e=n.toString(),t=n),i=>{if(je(i.value))return null;let r=i.value;return t.test(r)?null:{pattern:{requiredPattern:e,actualValue:r}}}}function de(n){return null}function Ft(n){return n!=null}function It(n){return rt(n)?Ze(n):n}function Rt(n){let t={};return n.forEach(e=>{t=e!=null?y(y({},t),e):t}),Object.keys(t).length===0?null:t}function Pt(n,t){return t.map(e=>e(n))}function Ci(n){return!n.validate}function Ut(n){return n.map(t=>Ci(t)?t:e=>t.validate(e))}function Ot(n){if(!n)return null;let t=n.filter(Ft);return t.length==0?null:function(e){return Rt(Pt(e,t))}}function Le(n){return n!=null?Ot(Ut(n)):null}function $t(n){if(!n)return null;let t=n.filter(Ft);return t.length==0?null:function(e){let i=Pt(e,t).map(It);return Ye(i).pipe(re(Rt))}}function We(n){return n!=null?$t(Ut(n)):null}function Ct(n,t){return n===null?[t]:Array.isArray(n)?[...n,t]:[n,t]}function jt(n){return n._rawValidators}function Ht(n){return n._rawAsyncValidators}function Ue(n){return n?Array.isArray(n)?n:[n]:[]}function he(n,t){return Array.isArray(n)?n.includes(t):n===t}function _t(n,t){let e=Ue(t);return Ue(n).forEach(r=>{he(e,r)||e.push(r)}),e}function bt(n,t){return Ue(t).filter(e=>!he(n,e))}var fe=class{get value(){return this.control?this.control.value:null}get valid(){return this.control?this.control.valid:null}get invalid(){return this.control?this.control.invalid:null}get pending(){return this.control?this.control.pending:null}get disabled(){return this.control?this.control.disabled:null}get enabled(){return this.control?this.control.enabled:null}get errors(){return this.control?this.control.errors:null}get pristine(){return this.control?this.control.pristine:null}get dirty(){return this.control?this.control.dirty:null}get touched(){return this.control?this.control.touched:null}get status(){return this.control?this.control.status:null}get untouched(){return this.control?this.control.untouched:null}get statusChanges(){return this.control?this.control.statusChanges:null}get valueChanges(){return this.control?this.control.valueChanges:null}get path(){return null}_composedValidatorFn;_composedAsyncValidatorFn;_rawValidators=[];_rawAsyncValidators=[];_setValidators(t){this._rawValidators=t||[],this._composedValidatorFn=Le(this._rawValidators)}_setAsyncValidators(t){this._rawAsyncValidators=t||[],this._composedAsyncValidatorFn=We(this._rawAsyncValidators)}get validator(){return this._composedValidatorFn||null}get asyncValidator(){return this._composedAsyncValidatorFn||null}_onDestroyCallbacks=[];_registerOnDestroy(t){this._onDestroyCallbacks.push(t)}_invokeOnDestroyCallbacks(){this._onDestroyCallbacks.forEach(t=>t()),this._onDestroyCallbacks=[]}reset(t=void 0){this.control&&this.control.reset(t)}hasError(t,e){return this.control?this.control.hasError(t,e):!1}getError(t,e){return this.control?this.control.getError(t,e):null}},p=class extends fe{name;get formDirective(){return null}get path(){return null}},V=class extends fe{_parent=null;name=null;valueAccessor=null},ge=class{_cd;constructor(t){this._cd=t}get isTouched(){return this._cd?.control?._touched?.(),!!this._cd?.control?.touched}get isUntouched(){return!!this._cd?.control?.untouched}get isPristine(){return this._cd?.control?._pristine?.(),!!this._cd?.control?.pristine}get isDirty(){return!!this._cd?.control?.dirty}get isValid(){return this._cd?.control?._status?.(),!!this._cd?.control?.valid}get isInvalid(){return!!this._cd?.control?.invalid}get isPending(){return!!this._cd?.control?.pending}get isSubmitted(){return this._cd?._submitted?.(),!!this._cd?.submitted}},_i={"[class.ng-untouched]":"isUntouched","[class.ng-touched]":"isTouched","[class.ng-pristine]":"isPristine","[class.ng-dirty]":"isDirty","[class.ng-valid]":"isValid","[class.ng-invalid]":"isInvalid","[class.ng-pending]":"isPending"},wr=S(y({},_i),{"[class.ng-submitted]":"isSubmitted"}),Tr=(()=>{class n extends ge{constructor(e){super(e)}static \u0275fac=function(i){return new(i||n)(c(V,2))};static \u0275dir=d({type:n,selectors:[["","formControlName",""],["","ngModel",""],["","formControl",""]],hostVars:14,hostBindings:function(i,r){i&2&&ke("ng-untouched",r.isUntouched)("ng-touched",r.isTouched)("ng-pristine",r.isPristine)("ng-dirty",r.isDirty)("ng-valid",r.isValid)("ng-invalid",r.isInvalid)("ng-pending",r.isPending)},standalone:!1,features:[f]})}return n})(),Vr=(()=>{class n extends ge{constructor(e){super(e)}static \u0275fac=function(i){return new(i||n)(c(p,10))};static \u0275dir=d({type:n,selectors:[["","formGroupName",""],["","formArrayName",""],["","ngModelGroup",""],["","formGroup",""],["form",3,"ngNoForm",""],["","ngForm",""]],hostVars:16,hostBindings:function(i,r){i&2&&ke("ng-untouched",r.isUntouched)("ng-touched",r.isTouched)("ng-pristine",r.isPristine)("ng-dirty",r.isDirty)("ng-valid",r.isValid)("ng-invalid",r.isInvalid)("ng-pending",r.isPending)("ng-submitted",r.isSubmitted)},standalone:!1,features:[f]})}return n})();var J="VALID",ue="INVALID",$="PENDING",Z="DISABLED",E=class{},pe=class extends E{value;source;constructor(t,e){super(),this.value=t,this.source=e}},Q=class extends E{pristine;source;constructor(t,e){super(),this.pristine=t,this.source=e}},X=class extends E{touched;source;constructor(t,e){super(),this.touched=t,this.source=e}},j=class extends E{status;source;constructor(t,e){super(),this.status=t,this.source=e}},me=class extends E{source;constructor(t){super(),this.source=t}},ve=class extends E{source;constructor(t){super(),this.source=t}};function Ge(n){return(be(n)?n.validators:n)||null}function bi(n){return Array.isArray(n)?Le(n):n||null}function Be(n,t){return(be(t)?t.asyncValidators:n)||null}function Si(n){return Array.isArray(n)?We(n):n||null}function be(n){return n!=null&&!Array.isArray(n)&&typeof n=="object"}function Lt(n,t,e){let i=n.controls;if(!(t?Object.keys(i):i).length)throw new oe(1e3,"");if(!i[e])throw new oe(1001,"")}function Wt(n,t,e){n._forEachChild((i,r)=>{if(e[r]===void 0)throw new oe(1002,"")})}var L=class{_pendingDirty=!1;_hasOwnPendingAsyncValidator=null;_pendingTouched=!1;_onCollectionChange=()=>{};_updateOn;_parent=null;_asyncValidationSubscription;_composedValidatorFn;_composedAsyncValidatorFn;_rawValidators;_rawAsyncValidators;value;constructor(t,e){this._assignValidators(t),this._assignAsyncValidators(e)}get validator(){return this._composedValidatorFn}set validator(t){this._rawValidators=this._composedValidatorFn=t}get asyncValidator(){return this._composedAsyncValidatorFn}set asyncValidator(t){this._rawAsyncValidators=this._composedAsyncValidatorFn=t}get parent(){return this._parent}get status(){return T(this.statusReactive)}set status(t){T(()=>this.statusReactive.set(t))}_status=P(()=>this.statusReactive());statusReactive=A(void 0);get valid(){return this.status===J}get invalid(){return this.status===ue}get pending(){return this.status==$}get disabled(){return this.status===Z}get enabled(){return this.status!==Z}errors;get pristine(){return T(this.pristineReactive)}set pristine(t){T(()=>this.pristineReactive.set(t))}_pristine=P(()=>this.pristineReactive());pristineReactive=A(!0);get dirty(){return!this.pristine}get touched(){return T(this.touchedReactive)}set touched(t){T(()=>this.touchedReactive.set(t))}_touched=P(()=>this.touchedReactive());touchedReactive=A(!1);get untouched(){return!this.touched}_events=new ie;events=this._events.asObservable();valueChanges;statusChanges;get updateOn(){return this._updateOn?this._updateOn:this.parent?this.parent.updateOn:"change"}setValidators(t){this._assignValidators(t)}setAsyncValidators(t){this._assignAsyncValidators(t)}addValidators(t){this.setValidators(_t(t,this._rawValidators))}addAsyncValidators(t){this.setAsyncValidators(_t(t,this._rawAsyncValidators))}removeValidators(t){this.setValidators(bt(t,this._rawValidators))}removeAsyncValidators(t){this.setAsyncValidators(bt(t,this._rawAsyncValidators))}hasValidator(t){return he(this._rawValidators,t)}hasAsyncValidator(t){return he(this._rawAsyncValidators,t)}clearValidators(){this.validator=null}clearAsyncValidators(){this.asyncValidator=null}markAsTouched(t={}){let e=this.touched===!1;this.touched=!0;let i=t.sourceControl??this;this._parent&&!t.onlySelf&&this._parent.markAsTouched(S(y({},t),{sourceControl:i})),e&&t.emitEvent!==!1&&this._events.next(new X(!0,i))}markAllAsDirty(t={}){this.markAsDirty({onlySelf:!0,emitEvent:t.emitEvent,sourceControl:this}),this._forEachChild(e=>e.markAllAsDirty(t))}markAllAsTouched(t={}){this.markAsTouched({onlySelf:!0,emitEvent:t.emitEvent,sourceControl:this}),this._forEachChild(e=>e.markAllAsTouched(t))}markAsUntouched(t={}){let e=this.touched===!0;this.touched=!1,this._pendingTouched=!1;let i=t.sourceControl??this;this._forEachChild(r=>{r.markAsUntouched({onlySelf:!0,emitEvent:t.emitEvent,sourceControl:i})}),this._parent&&!t.onlySelf&&this._parent._updateTouched(t,i),e&&t.emitEvent!==!1&&this._events.next(new X(!1,i))}markAsDirty(t={}){let e=this.pristine===!0;this.pristine=!1;let i=t.sourceControl??this;this._parent&&!t.onlySelf&&this._parent.markAsDirty(S(y({},t),{sourceControl:i})),e&&t.emitEvent!==!1&&this._events.next(new Q(!1,i))}markAsPristine(t={}){let e=this.pristine===!1;this.pristine=!0,this._pendingDirty=!1;let i=t.sourceControl??this;this._forEachChild(r=>{r.markAsPristine({onlySelf:!0,emitEvent:t.emitEvent})}),this._parent&&!t.onlySelf&&this._parent._updatePristine(t,i),e&&t.emitEvent!==!1&&this._events.next(new Q(!0,i))}markAsPending(t={}){this.status=$;let e=t.sourceControl??this;t.emitEvent!==!1&&(this._events.next(new j(this.status,e)),this.statusChanges.emit(this.status)),this._parent&&!t.onlySelf&&this._parent.markAsPending(S(y({},t),{sourceControl:e}))}disable(t={}){let e=this._parentMarkedDirty(t.onlySelf);this.status=Z,this.errors=null,this._forEachChild(r=>{r.disable(S(y({},t),{onlySelf:!0}))}),this._updateValue();let i=t.sourceControl??this;t.emitEvent!==!1&&(this._events.next(new pe(this.value,i)),this._events.next(new j(this.status,i)),this.valueChanges.emit(this.value),this.statusChanges.emit(this.status)),this._updateAncestors(S(y({},t),{skipPristineCheck:e}),this),this._onDisabledChange.forEach(r=>r(!0))}enable(t={}){let e=this._parentMarkedDirty(t.onlySelf);this.status=J,this._forEachChild(i=>{i.enable(S(y({},t),{onlySelf:!0}))}),this.updateValueAndValidity({onlySelf:!0,emitEvent:t.emitEvent}),this._updateAncestors(S(y({},t),{skipPristineCheck:e}),this),this._onDisabledChange.forEach(i=>i(!1))}_updateAncestors(t,e){this._parent&&!t.onlySelf&&(this._parent.updateValueAndValidity(t),t.skipPristineCheck||this._parent._updatePristine({},e),this._parent._updateTouched({},e))}setParent(t){this._parent=t}getRawValue(){return this.value}updateValueAndValidity(t={}){if(this._setInitialStatus(),this._updateValue(),this.enabled){let i=this._cancelExistingSubscription();this.errors=this._runValidator(),this.status=this._calculateStatus(),(this.status===J||this.status===$)&&this._runAsyncValidator(i,t.emitEvent)}let e=t.sourceControl??this;t.emitEvent!==!1&&(this._events.next(new pe(this.value,e)),this._events.next(new j(this.status,e)),this.valueChanges.emit(this.value),this.statusChanges.emit(this.status)),this._parent&&!t.onlySelf&&this._parent.updateValueAndValidity(S(y({},t),{sourceControl:e}))}_updateTreeValidity(t={emitEvent:!0}){this._forEachChild(e=>e._updateTreeValidity(t)),this.updateValueAndValidity({onlySelf:!0,emitEvent:t.emitEvent})}_setInitialStatus(){this.status=this._allControlsDisabled()?Z:J}_runValidator(){return this.validator?this.validator(this):null}_runAsyncValidator(t,e){if(this.asyncValidator){this.status=$,this._hasOwnPendingAsyncValidator={emitEvent:e!==!1,shouldHaveEmitted:t!==!1};let i=It(this.asyncValidator(this));this._asyncValidationSubscription=i.subscribe(r=>{this._hasOwnPendingAsyncValidator=null,this.setErrors(r,{emitEvent:e,shouldHaveEmitted:t})})}}_cancelExistingSubscription(){if(this._asyncValidationSubscription){this._asyncValidationSubscription.unsubscribe();let t=(this._hasOwnPendingAsyncValidator?.emitEvent||this._hasOwnPendingAsyncValidator?.shouldHaveEmitted)??!1;return this._hasOwnPendingAsyncValidator=null,t}return!1}setErrors(t,e={}){this.errors=t,this._updateControlsErrors(e.emitEvent!==!1,this,e.shouldHaveEmitted)}get(t){let e=t;return e==null||(Array.isArray(e)||(e=e.split(".")),e.length===0)?null:e.reduce((i,r)=>i&&i._find(r),this)}getError(t,e){let i=e?this.get(e):this;return i&&i.errors?i.errors[t]:null}hasError(t,e){return!!this.getError(t,e)}get root(){let t=this;for(;t._parent;)t=t._parent;return t}_updateControlsErrors(t,e,i){this.status=this._calculateStatus(),t&&this.statusChanges.emit(this.status),(t||i)&&this._events.next(new j(this.status,e)),this._parent&&this._parent._updateControlsErrors(t,e,i)}_initObservables(){this.valueChanges=new k,this.statusChanges=new k}_calculateStatus(){return this._allControlsDisabled()?Z:this.errors?ue:this._hasOwnPendingAsyncValidator||this._anyControlsHaveStatus($)?$:this._anyControlsHaveStatus(ue)?ue:J}_anyControlsHaveStatus(t){return this._anyControls(e=>e.status===t)}_anyControlsDirty(){return this._anyControls(t=>t.dirty)}_anyControlsTouched(){return this._anyControls(t=>t.touched)}_updatePristine(t,e){let i=!this._anyControlsDirty(),r=this.pristine!==i;this.pristine=i,this._parent&&!t.onlySelf&&this._parent._updatePristine(t,e),r&&this._events.next(new Q(this.pristine,e))}_updateTouched(t={},e){this.touched=this._anyControlsTouched(),this._events.next(new X(this.touched,e)),this._parent&&!t.onlySelf&&this._parent._updateTouched(t,e)}_onDisabledChange=[];_registerOnCollectionChange(t){this._onCollectionChange=t}_setUpdateStrategy(t){be(t)&&t.updateOn!=null&&(this._updateOn=t.updateOn)}_parentMarkedDirty(t){let e=this._parent&&this._parent.dirty;return!t&&!!e&&!this._parent._anyControlsDirty()}_find(t){return null}_assignValidators(t){this._rawValidators=Array.isArray(t)?t.slice():t,this._composedValidatorFn=bi(this._rawValidators)}_assignAsyncValidators(t){this._rawAsyncValidators=Array.isArray(t)?t.slice():t,this._composedAsyncValidatorFn=Si(this._rawAsyncValidators)}},x=class extends L{constructor(t,e,i){super(Ge(e),Be(i,e)),this.controls=t,this._initObservables(),this._setUpdateStrategy(e),this._setUpControls(),this.updateValueAndValidity({onlySelf:!0,emitEvent:!!this.asyncValidator})}controls;registerControl(t,e){return this.controls[t]?this.controls[t]:(this.controls[t]=e,e.setParent(this),e._registerOnCollectionChange(this._onCollectionChange),e)}addControl(t,e,i={}){this.registerControl(t,e),this.updateValueAndValidity({emitEvent:i.emitEvent}),this._onCollectionChange()}removeControl(t,e={}){this.controls[t]&&this.controls[t]._registerOnCollectionChange(()=>{}),delete this.controls[t],this.updateValueAndValidity({emitEvent:e.emitEvent}),this._onCollectionChange()}setControl(t,e,i={}){this.controls[t]&&this.controls[t]._registerOnCollectionChange(()=>{}),delete this.controls[t],e&&this.registerControl(t,e),this.updateValueAndValidity({emitEvent:i.emitEvent}),this._onCollectionChange()}contains(t){return this.controls.hasOwnProperty(t)&&this.controls[t].enabled}setValue(t,e={}){Wt(this,!0,t),Object.keys(t).forEach(i=>{Lt(this,!0,i),this.controls[i].setValue(t[i],{onlySelf:!0,emitEvent:e.emitEvent})}),this.updateValueAndValidity(e)}patchValue(t,e={}){t!=null&&(Object.keys(t).forEach(i=>{let r=this.controls[i];r&&r.patchValue(t[i],{onlySelf:!0,emitEvent:e.emitEvent})}),this.updateValueAndValidity(e))}reset(t={},e={}){this._forEachChild((i,r)=>{i.reset(t?t[r]:null,{onlySelf:!0,emitEvent:e.emitEvent})}),this._updatePristine(e,this),this._updateTouched(e,this),this.updateValueAndValidity(e)}getRawValue(){return this._reduceChildren({},(t,e,i)=>(t[i]=e.getRawValue(),t))}_syncPendingControls(){let t=this._reduceChildren(!1,(e,i)=>i._syncPendingControls()?!0:e);return t&&this.updateValueAndValidity({onlySelf:!0}),t}_forEachChild(t){Object.keys(this.controls).forEach(e=>{let i=this.controls[e];i&&t(i,e)})}_setUpControls(){this._forEachChild(t=>{t.setParent(this),t._registerOnCollectionChange(this._onCollectionChange)})}_updateValue(){this.value=this._reduceValue()}_anyControls(t){for(let[e,i]of Object.entries(this.controls))if(this.contains(e)&&t(i))return!0;return!1}_reduceValue(){let t={};return this._reduceChildren(t,(e,i,r)=>((i.enabled||this.disabled)&&(e[r]=i.value),e))}_reduceChildren(t,e){let i=t;return this._forEachChild((r,o)=>{i=e(i,r,o)}),i}_allControlsDisabled(){for(let t of Object.keys(this.controls))if(this.controls[t].enabled)return!1;return Object.keys(this.controls).length>0||this.disabled}_find(t){return this.controls.hasOwnProperty(t)?this.controls[t]:null}};var Ar=x;var Oe=class extends x{};var W=new N("",{providedIn:"root",factory:()=>Se}),Se="always";function De(n,t){return[...t.path,n]}function ee(n,t,e=Se){qe(n,t),t.valueAccessor.writeValue(n.value),(n.disabled||e==="always")&&t.valueAccessor.setDisabledState?.(n.disabled),wi(n,t),Vi(n,t),Ti(n,t),Di(n,t)}function ye(n,t,e=!0){let i=()=>{};t.valueAccessor&&(t.valueAccessor.registerOnChange(i),t.valueAccessor.registerOnTouched(i)),_e(n,t),n&&(t._invokeOnDestroyCallbacks(),n._registerOnCollectionChange(()=>{}))}function Ce(n,t){n.forEach(e=>{e.registerOnValidatorChange&&e.registerOnValidatorChange(t)})}function Di(n,t){if(t.valueAccessor.setDisabledState){let e=i=>{t.valueAccessor.setDisabledState(i)};n.registerOnDisabledChange(e),t._registerOnDestroy(()=>{n._unregisterOnDisabledChange(e)})}}function qe(n,t){let e=jt(n);t.validator!==null?n.setValidators(Ct(e,t.validator)):typeof e=="function"&&n.setValidators([e]);let i=Ht(n);t.asyncValidator!==null?n.setAsyncValidators(Ct(i,t.asyncValidator)):typeof i=="function"&&n.setAsyncValidators([i]);let r=()=>n.updateValueAndValidity();Ce(t._rawValidators,r),Ce(t._rawAsyncValidators,r)}function _e(n,t){let e=!1;if(n!==null){if(t.validator!==null){let r=jt(n);if(Array.isArray(r)&&r.length>0){let o=r.filter(s=>s!==t.validator);o.length!==r.length&&(e=!0,n.setValidators(o))}}if(t.asyncValidator!==null){let r=Ht(n);if(Array.isArray(r)&&r.length>0){let o=r.filter(s=>s!==t.asyncValidator);o.length!==r.length&&(e=!0,n.setAsyncValidators(o))}}}let i=()=>{};return Ce(t._rawValidators,i),Ce(t._rawAsyncValidators,i),e}function wi(n,t){t.valueAccessor.registerOnChange(e=>{n._pendingValue=e,n._pendingChange=!0,n._pendingDirty=!0,n.updateOn==="change"&&Gt(n,t)})}function Ti(n,t){t.valueAccessor.registerOnTouched(()=>{n._pendingTouched=!0,n.updateOn==="blur"&&n._pendingChange&&Gt(n,t),n.updateOn!=="submit"&&n.markAsTouched()})}function Gt(n,t){n._pendingDirty&&n.markAsDirty(),n.setValue(n._pendingValue,{emitModelToViewChange:!1}),t.viewToModelUpdate(n._pendingValue),n._pendingChange=!1}function Vi(n,t){let e=(i,r)=>{t.valueAccessor.writeValue(i),r&&t.viewToModelUpdate(i)};n.registerOnChange(e),t._registerOnDestroy(()=>{n._unregisterOnChange(e)})}function Bt(n,t){n==null,qe(n,t)}function Ai(n,t){return _e(n,t)}function Ke(n,t){if(!n.hasOwnProperty("model"))return!1;let e=n.model;return e.isFirstChange()?!0:!Object.is(t,e.currentValue)}function ki(n){return Object.getPrototypeOf(n.constructor)===At}function qt(n,t){n._syncPendingControls(),t.forEach(e=>{let i=e.control;i.updateOn==="submit"&&i._pendingChange&&(e.viewToModelUpdate(i._pendingValue),i._pendingChange=!1)})}function ze(n,t){if(!t)return null;Array.isArray(t);let e,i,r;return t.forEach(o=>{o.constructor===kt?e=o:ki(o)?i=o:r=o}),r||i||e||null}function Mi(n,t){let e=n.indexOf(t);e>-1&&n.splice(e,1)}var Ei={provide:p,useExisting:m(()=>Ni)},Y=Promise.resolve(),Ni=(()=>{class n extends p{callSetDisabledState;get submitted(){return T(this.submittedReactive)}_submitted=P(()=>this.submittedReactive());submittedReactive=A(!1);_directives=new Set;form;ngSubmit=new k;options;constructor(e,i,r){super(),this.callSetDisabledState=r,this.form=new x({},Le(e),We(i))}ngAfterViewInit(){this._setUpdateStrategy()}get formDirective(){return this}get control(){return this.form}get path(){return[]}get controls(){return this.form.controls}addControl(e){Y.then(()=>{let i=this._findContainer(e.path);e.control=i.registerControl(e.name,e.control),ee(e.control,e,this.callSetDisabledState),e.control.updateValueAndValidity({emitEvent:!1}),this._directives.add(e)})}getControl(e){return this.form.get(e.path)}removeControl(e){Y.then(()=>{let i=this._findContainer(e.path);i&&i.removeControl(e.name),this._directives.delete(e)})}addFormGroup(e){Y.then(()=>{let i=this._findContainer(e.path),r=new x({});Bt(r,e),i.registerControl(e.name,r),r.updateValueAndValidity({emitEvent:!1})})}removeFormGroup(e){Y.then(()=>{let i=this._findContainer(e.path);i&&i.removeControl(e.name)})}getFormGroup(e){return this.form.get(e.path)}updateModel(e,i){Y.then(()=>{this.form.get(e.path).setValue(i)})}setValue(e){this.control.setValue(e)}onSubmit(e){return this.submittedReactive.set(!0),qt(this.form,this._directives),this.ngSubmit.emit(e),this.form._events.next(new me(this.control)),e?.target?.method==="dialog"}onReset(){this.resetForm()}resetForm(e=void 0){this.form.reset(e),this.submittedReactive.set(!1),this.form._events.next(new ve(this.form))}_setUpdateStrategy(){this.options&&this.options.updateOn!=null&&(this.form._updateOn=this.options.updateOn)}_findContainer(e){return e.pop(),e.length?this.form.get(e):this.form}static \u0275fac=function(i){return new(i||n)(c(D,10),c(F,10),c(W,8))};static \u0275dir=d({type:n,selectors:[["form",3,"ngNoForm","",3,"formGroup",""],["ng-form"],["","ngForm",""]],hostBindings:function(i,r){i&1&&B("submit",function(s){return r.onSubmit(s)})("reset",function(){return r.onReset()})},inputs:{options:[0,"ngFormOptions","options"]},outputs:{ngSubmit:"ngSubmit"},exportAs:["ngForm"],standalone:!1,features:[v([Ei]),f]})}return n})();function St(n,t){let e=n.indexOf(t);e>-1&&n.splice(e,1)}function Dt(n){return typeof n=="object"&&n!==null&&Object.keys(n).length===2&&"value"in n&&"disabled"in n}var H=class extends L{defaultValue=null;_onChange=[];_pendingValue;_pendingChange=!1;constructor(t=null,e,i){super(Ge(e),Be(i,e)),this._applyFormState(t),this._setUpdateStrategy(e),this._initObservables(),this.updateValueAndValidity({onlySelf:!0,emitEvent:!!this.asyncValidator}),be(e)&&(e.nonNullable||e.initialValueIsDefault)&&(Dt(t)?this.defaultValue=t.value:this.defaultValue=t)}setValue(t,e={}){this.value=this._pendingValue=t,this._onChange.length&&e.emitModelToViewChange!==!1&&this._onChange.forEach(i=>i(this.value,e.emitViewToModelChange!==!1)),this.updateValueAndValidity(e)}patchValue(t,e={}){this.setValue(t,e)}reset(t=this.defaultValue,e={}){this._applyFormState(t),this.markAsPristine(e),this.markAsUntouched(e),this.setValue(this.value,e),this._pendingChange=!1}_updateValue(){}_anyControls(t){return!1}_allControlsDisabled(){return this.disabled}registerOnChange(t){this._onChange.push(t)}_unregisterOnChange(t){St(this._onChange,t)}registerOnDisabledChange(t){this._onDisabledChange.push(t)}_unregisterOnDisabledChange(t){St(this._onDisabledChange,t)}_forEachChild(t){}_syncPendingControls(){return this.updateOn==="submit"&&(this._pendingDirty&&this.markAsDirty(),this._pendingTouched&&this.markAsTouched(),this._pendingChange)?(this.setValue(this._pendingValue,{onlySelf:!0,emitModelToViewChange:!1}),!0):!1}_applyFormState(t){Dt(t)?(this.value=this._pendingValue=t.value,t.disabled?this.disable({onlySelf:!0,emitEvent:!1}):this.enable({onlySelf:!0,emitEvent:!1})):this.value=this._pendingValue=t}},Mr=H,xi=n=>n instanceof H,Fi=(()=>{class n extends p{_parent;ngOnInit(){this._checkParentType(),this.formDirective.addFormGroup(this)}ngOnDestroy(){this.formDirective&&this.formDirective.removeFormGroup(this)}get control(){return this.formDirective.getFormGroup(this)}get path(){return De(this.name==null?this.name:this.name.toString(),this._parent)}get formDirective(){return this._parent?this._parent.formDirective:null}_checkParentType(){}static \u0275fac=(()=>{let e;return function(r){return(e||(e=w(n)))(r||n)}})();static \u0275dir=d({type:n,standalone:!1,features:[f]})}return n})();var Ii={provide:V,useExisting:m(()=>Ri)},wt=Promise.resolve(),Ri=(()=>{class n extends V{_changeDetectorRef;callSetDisabledState;control=new H;static ngAcceptInputType_isDisabled;_registered=!1;viewModel;name="";isDisabled;model;options;update=new k;constructor(e,i,r,o,s,a){super(),this._changeDetectorRef=s,this.callSetDisabledState=a,this._parent=e,this._setValidators(i),this._setAsyncValidators(r),this.valueAccessor=ze(this,o)}ngOnChanges(e){if(this._checkForErrors(),!this._registered||"name"in e){if(this._registered&&(this._checkName(),this.formDirective)){let i=e.name.previousValue;this.formDirective.removeControl({name:i,path:this._getPath(i)})}this._setUpControl()}"isDisabled"in e&&this._updateDisabled(e),Ke(e,this.viewModel)&&(this._updateValue(this.model),this.viewModel=this.model)}ngOnDestroy(){this.formDirective&&this.formDirective.removeControl(this)}get path(){return this._getPath(this.name)}get formDirective(){return this._parent?this._parent.formDirective:null}viewToModelUpdate(e){this.viewModel=e,this.update.emit(e)}_setUpControl(){this._setUpdateStrategy(),this._isStandalone()?this._setUpStandalone():this.formDirective.addControl(this),this._registered=!0}_setUpdateStrategy(){this.options&&this.options.updateOn!=null&&(this.control._updateOn=this.options.updateOn)}_isStandalone(){return!this._parent||!!(this.options&&this.options.standalone)}_setUpStandalone(){ee(this.control,this,this.callSetDisabledState),this.control.updateValueAndValidity({emitEvent:!1})}_checkForErrors(){this._checkName()}_checkName(){this.options&&this.options.name&&(this.name=this.options.name),!this._isStandalone()&&this.name}_updateValue(e){wt.then(()=>{this.control.setValue(e,{emitViewToModelChange:!1}),this._changeDetectorRef?.markForCheck()})}_updateDisabled(e){let i=e.isDisabled.currentValue,r=i!==0&&Me(i);wt.then(()=>{r&&!this.control.disabled?this.control.disable():!r&&this.control.disabled&&this.control.enable(),this._changeDetectorRef?.markForCheck()})}_getPath(e){return this._parent?De(e,this._parent):[e]}static \u0275fac=function(i){return new(i||n)(c(p,9),c(D,10),c(F,10),c(te,10),c(ot,8),c(W,8))};static \u0275dir=d({type:n,selectors:[["","ngModel","",3,"formControlName","",3,"formControl",""]],inputs:{name:"name",isDisabled:[0,"disabled","isDisabled"],model:[0,"ngModel","model"],options:[0,"ngModelOptions","options"]},outputs:{update:"ngModelChange"},exportAs:["ngModel"],standalone:!1,features:[v([Ii]),f,R]})}return n})();var Er=(()=>{class n{static \u0275fac=function(i){return new(i||n)};static \u0275dir=d({type:n,selectors:[["form",3,"ngNoForm","",3,"ngNativeValidate",""]],hostAttrs:["novalidate",""],standalone:!1})}return n})(),Pi={provide:te,useExisting:m(()=>Ui),multi:!0},Ui=(()=>{class n extends At{writeValue(e){let i=e??"";this.setProperty("value",i)}registerOnChange(e){this.onChange=i=>{e(i==""?null:parseFloat(i))}}static \u0275fac=(()=>{let e;return function(r){return(e||(e=w(n)))(r||n)}})();static \u0275dir=d({type:n,selectors:[["input","type","number","formControlName",""],["input","type","number","formControl",""],["input","type","number","ngModel",""]],hostBindings:function(i,r){i&1&&B("input",function(s){return r.onChange(s.target.value)})("blur",function(){return r.onTouched()})},standalone:!1,features:[v([Pi]),f]})}return n})();var Je=new N(""),Oi={provide:V,useExisting:m(()=>$i)},$i=(()=>{class n extends V{_ngModelWarningConfig;callSetDisabledState;viewModel;form;set isDisabled(e){}model;update=new k;static _ngModelWarningSentOnce=!1;_ngModelWarningSent=!1;constructor(e,i,r,o,s){super(),this._ngModelWarningConfig=o,this.callSetDisabledState=s,this._setValidators(e),this._setAsyncValidators(i),this.valueAccessor=ze(this,r)}ngOnChanges(e){if(this._isControlChanged(e)){let i=e.form.previousValue;i&&ye(i,this,!1),ee(this.form,this,this.callSetDisabledState),this.form.updateValueAndValidity({emitEvent:!1})}Ke(e,this.viewModel)&&(this.form.setValue(this.model),this.viewModel=this.model)}ngOnDestroy(){this.form&&ye(this.form,this,!1)}get path(){return[]}get control(){return this.form}viewToModelUpdate(e){this.viewModel=e,this.update.emit(e)}_isControlChanged(e){return e.hasOwnProperty("form")}static \u0275fac=function(i){return new(i||n)(c(D,10),c(F,10),c(te,10),c(Je,8),c(W,8))};static \u0275dir=d({type:n,selectors:[["","formControl",""]],inputs:{form:[0,"formControl","form"],isDisabled:[0,"disabled","isDisabled"],model:[0,"ngModel","model"]},outputs:{update:"ngModelChange"},exportAs:["ngForm"],standalone:!1,features:[v([Oi]),f,R]})}return n})(),ji={provide:p,useExisting:m(()=>Kt)},Kt=(()=>{class n extends p{callSetDisabledState;get submitted(){return T(this._submittedReactive)}set submitted(e){this._submittedReactive.set(e)}_submitted=P(()=>this._submittedReactive());_submittedReactive=A(!1);_oldForm;_onCollectionChange=()=>this._updateDomValue();directives=[];form=null;ngSubmit=new k;constructor(e,i,r){super(),this.callSetDisabledState=r,this._setValidators(e),this._setAsyncValidators(i)}ngOnChanges(e){e.hasOwnProperty("form")&&(this._updateValidators(),this._updateDomValue(),this._updateRegistrations(),this._oldForm=this.form)}ngOnDestroy(){this.form&&(_e(this.form,this),this.form._onCollectionChange===this._onCollectionChange&&this.form._registerOnCollectionChange(()=>{}))}get formDirective(){return this}get control(){return this.form}get path(){return[]}addControl(e){let i=this.form.get(e.path);return ee(i,e,this.callSetDisabledState),i.updateValueAndValidity({emitEvent:!1}),this.directives.push(e),i}getControl(e){return this.form.get(e.path)}removeControl(e){ye(e.control||null,e,!1),Mi(this.directives,e)}addFormGroup(e){this._setUpFormContainer(e)}removeFormGroup(e){this._cleanUpFormContainer(e)}getFormGroup(e){return this.form.get(e.path)}addFormArray(e){this._setUpFormContainer(e)}removeFormArray(e){this._cleanUpFormContainer(e)}getFormArray(e){return this.form.get(e.path)}updateModel(e,i){this.form.get(e.path).setValue(i)}onSubmit(e){return this._submittedReactive.set(!0),qt(this.form,this.directives),this.ngSubmit.emit(e),this.form._events.next(new me(this.control)),e?.target?.method==="dialog"}onReset(){this.resetForm()}resetForm(e=void 0,i={}){this.form.reset(e,i),this._submittedReactive.set(!1),i?.emitEvent!==!1&&this.form._events.next(new ve(this.form))}_updateDomValue(){this.directives.forEach(e=>{let i=e.control,r=this.form.get(e.path);i!==r&&(ye(i||null,e),xi(r)&&(ee(r,e,this.callSetDisabledState),e.control=r))}),this.form._updateTreeValidity({emitEvent:!1})}_setUpFormContainer(e){let i=this.form.get(e.path);Bt(i,e),i.updateValueAndValidity({emitEvent:!1})}_cleanUpFormContainer(e){if(this.form){let i=this.form.get(e.path);i&&Ai(i,e)&&i.updateValueAndValidity({emitEvent:!1})}}_updateRegistrations(){this.form._registerOnCollectionChange(this._onCollectionChange),this._oldForm&&this._oldForm._registerOnCollectionChange(()=>{})}_updateValidators(){qe(this.form,this),this._oldForm&&_e(this._oldForm,this)}static \u0275fac=function(i){return new(i||n)(c(D,10),c(F,10),c(W,8))};static \u0275dir=d({type:n,selectors:[["","formGroup",""]],hostBindings:function(i,r){i&1&&B("submit",function(s){return r.onSubmit(s)})("reset",function(){return r.onReset()})},inputs:{form:[0,"formGroup","form"]},outputs:{ngSubmit:"ngSubmit"},exportAs:["ngForm"],standalone:!1,features:[v([ji]),f,R]})}return n})(),Hi={provide:p,useExisting:m(()=>zt)},zt=(()=>{class n extends Fi{name=null;constructor(e,i,r){super(),this._parent=e,this._setValidators(i),this._setAsyncValidators(r)}_checkParentType(){Zt(this._parent)}static \u0275fac=function(i){return new(i||n)(c(p,13),c(D,10),c(F,10))};static \u0275dir=d({type:n,selectors:[["","formGroupName",""]],inputs:{name:[0,"formGroupName","name"]},standalone:!1,features:[v([Hi]),f]})}return n})(),Li={provide:p,useExisting:m(()=>Jt)},Jt=(()=>{class n extends p{_parent;name=null;constructor(e,i,r){super(),this._parent=e,this._setValidators(i),this._setAsyncValidators(r)}ngOnInit(){Zt(this._parent),this.formDirective.addFormArray(this)}ngOnDestroy(){this.formDirective?.removeFormArray(this)}get control(){return this.formDirective.getFormArray(this)}get formDirective(){return this._parent?this._parent.formDirective:null}get path(){return De(this.name==null?this.name:this.name.toString(),this._parent)}static \u0275fac=function(i){return new(i||n)(c(p,13),c(D,10),c(F,10))};static \u0275dir=d({type:n,selectors:[["","formArrayName",""]],inputs:{name:[0,"formArrayName","name"]},standalone:!1,features:[v([Li]),f]})}return n})();function Zt(n){return!(n instanceof zt)&&!(n instanceof Kt)&&!(n instanceof Jt)}var Wi={provide:V,useExisting:m(()=>Gi)},Gi=(()=>{class n extends V{_ngModelWarningConfig;_added=!1;viewModel;control;name=null;set isDisabled(e){}model;update=new k;static _ngModelWarningSentOnce=!1;_ngModelWarningSent=!1;constructor(e,i,r,o,s){super(),this._ngModelWarningConfig=s,this._parent=e,this._setValidators(i),this._setAsyncValidators(r),this.valueAccessor=ze(this,o)}ngOnChanges(e){this._added||this._setUpControl(),Ke(e,this.viewModel)&&(this.viewModel=this.model,this.formDirective.updateModel(this,this.model))}ngOnDestroy(){this.formDirective&&this.formDirective.removeControl(this)}viewToModelUpdate(e){this.viewModel=e,this.update.emit(e)}get path(){return De(this.name==null?this.name:this.name.toString(),this._parent)}get formDirective(){return this._parent?this._parent.formDirective:null}_setUpControl(){this.control=this.formDirective.addControl(this),this._added=!0}static \u0275fac=function(i){return new(i||n)(c(p,13),c(D,10),c(F,10),c(te,10),c(Je,8))};static \u0275dir=d({type:n,selectors:[["","formControlName",""]],inputs:{name:[0,"formControlName","name"],isDisabled:[0,"disabled","isDisabled"],model:[0,"ngModel","model"]},outputs:{update:"ngModelChange"},standalone:!1,features:[v([Wi]),f,R]})}return n})();function Yt(n){return typeof n=="number"?n:parseFloat(n)}var we=(()=>{class n{_validator=de;_onChange;_enabled;ngOnChanges(e){if(this.inputName in e){let i=this.normalizeInput(e[this.inputName].currentValue);this._enabled=this.enabled(i),this._validator=this._enabled?this.createValidator(i):de,this._onChange&&this._onChange()}}validate(e){return this._validator(e)}registerOnValidatorChange(e){this._onChange=e}enabled(e){return e!=null}static \u0275fac=function(i){return new(i||n)};static \u0275dir=d({type:n,features:[R]})}return n})(),Bi={provide:D,useExisting:m(()=>qi),multi:!0},qi=(()=>{class n extends we{max;inputName="max";normalizeInput=e=>Yt(e);createValidator=e=>Et(e);static \u0275fac=(()=>{let e;return function(r){return(e||(e=w(n)))(r||n)}})();static \u0275dir=d({type:n,selectors:[["input","type","number","max","","formControlName",""],["input","type","number","max","","formControl",""],["input","type","number","max","","ngModel",""]],hostVars:1,hostBindings:function(i,r){i&2&&G("max",r._enabled?r.max:null)},inputs:{max:"max"},standalone:!1,features:[v([Bi]),f]})}return n})(),Ki={provide:D,useExisting:m(()=>zi),multi:!0},zi=(()=>{class n extends we{min;inputName="min";normalizeInput=e=>Yt(e);createValidator=e=>Mt(e);static \u0275fac=(()=>{let e;return function(r){return(e||(e=w(n)))(r||n)}})();static \u0275dir=d({type:n,selectors:[["input","type","number","min","","formControlName",""],["input","type","number","min","","formControl",""],["input","type","number","min","","ngModel",""]],hostVars:1,hostBindings:function(i,r){i&2&&G("min",r._enabled?r.min:null)},inputs:{min:"min"},standalone:!1,features:[v([Ki]),f]})}return n})(),Ji={provide:D,useExisting:m(()=>Zi),multi:!0};var Zi=(()=>{class n extends we{required;inputName="required";normalizeInput=Me;createValidator=e=>Nt;enabled(e){return e}static \u0275fac=(()=>{let e;return function(r){return(e||(e=w(n)))(r||n)}})();static \u0275dir=d({type:n,selectors:[["","required","","formControlName","",3,"type","checkbox"],["","required","","formControl","",3,"type","checkbox"],["","required","","ngModel","",3,"type","checkbox"]],hostVars:1,hostBindings:function(i,r){i&2&&G("required",r._enabled?"":null)},inputs:{required:"required"},standalone:!1,features:[v([Ji]),f]})}return n})();var Yi={provide:D,useExisting:m(()=>Qi),multi:!0},Qi=(()=>{class n extends we{pattern;inputName="pattern";normalizeInput=e=>e;createValidator=e=>xt(e);static \u0275fac=(()=>{let e;return function(r){return(e||(e=w(n)))(r||n)}})();static \u0275dir=d({type:n,selectors:[["","pattern","","formControlName",""],["","pattern","","formControl",""],["","pattern","","ngModel",""]],hostVars:1,hostBindings:function(i,r){i&2&&G("pattern",r._enabled?r.pattern:null)},inputs:{pattern:"pattern"},standalone:!1,features:[v([Yi]),f]})}return n})();var Qt=(()=>{class n{static \u0275fac=function(i){return new(i||n)};static \u0275mod=ae({type:n});static \u0275inj=se({})}return n})(),$e=class extends L{constructor(t,e,i){super(Ge(e),Be(i,e)),this.controls=t,this._initObservables(),this._setUpdateStrategy(e),this._setUpControls(),this.updateValueAndValidity({onlySelf:!0,emitEvent:!!this.asyncValidator})}controls;at(t){return this.controls[this._adjustIndex(t)]}push(t,e={}){this.controls.push(t),this._registerControl(t),this.updateValueAndValidity({emitEvent:e.emitEvent}),this._onCollectionChange()}insert(t,e,i={}){this.controls.splice(t,0,e),this._registerControl(e),this.updateValueAndValidity({emitEvent:i.emitEvent})}removeAt(t,e={}){let i=this._adjustIndex(t);i<0&&(i=0),this.controls[i]&&this.controls[i]._registerOnCollectionChange(()=>{}),this.controls.splice(i,1),this.updateValueAndValidity({emitEvent:e.emitEvent})}setControl(t,e,i={}){let r=this._adjustIndex(t);r<0&&(r=0),this.controls[r]&&this.controls[r]._registerOnCollectionChange(()=>{}),this.controls.splice(r,1),e&&(this.controls.splice(r,0,e),this._registerControl(e)),this.updateValueAndValidity({emitEvent:i.emitEvent}),this._onCollectionChange()}get length(){return this.controls.length}setValue(t,e={}){Wt(this,!1,t),t.forEach((i,r)=>{Lt(this,!1,r),this.at(r).setValue(i,{onlySelf:!0,emitEvent:e.emitEvent})}),this.updateValueAndValidity(e)}patchValue(t,e={}){t!=null&&(t.forEach((i,r)=>{this.at(r)&&this.at(r).patchValue(i,{onlySelf:!0,emitEvent:e.emitEvent})}),this.updateValueAndValidity(e))}reset(t=[],e={}){this._forEachChild((i,r)=>{i.reset(t[r],{onlySelf:!0,emitEvent:e.emitEvent})}),this._updatePristine(e,this),this._updateTouched(e,this),this.updateValueAndValidity(e)}getRawValue(){return this.controls.map(t=>t.getRawValue())}clear(t={}){this.controls.length<1||(this._forEachChild(e=>e._registerOnCollectionChange(()=>{})),this.controls.splice(0),this.updateValueAndValidity({emitEvent:t.emitEvent}))}_adjustIndex(t){return t<0?t+this.length:t}_syncPendingControls(){let t=this.controls.reduce((e,i)=>i._syncPendingControls()?!0:e,!1);return t&&this.updateValueAndValidity({onlySelf:!0}),t}_forEachChild(t){this.controls.forEach((e,i)=>{t(e,i)})}_updateValue(){this.value=this.controls.filter(t=>t.enabled||this.disabled).map(t=>t.value)}_anyControls(t){return this.controls.some(e=>e.enabled&&t(e))}_setUpControls(){this._forEachChild(t=>this._registerControl(t))}_allControlsDisabled(){for(let t of this.controls)if(t.enabled)return!1;return this.controls.length>0||this.disabled}_registerControl(t){t.setParent(this),t._registerOnCollectionChange(this._onCollectionChange)}_find(t){return this.at(t)??null}};function Tt(n){return!!n&&(n.asyncValidators!==void 0||n.validators!==void 0||n.updateOn!==void 0)}var Xi=(()=>{class n{useNonNullable=!1;get nonNullable(){let e=new n;return e.useNonNullable=!0,e}group(e,i=null){let r=this._reduceControls(e),o={};return Tt(i)?o=i:i!==null&&(o.validators=i.validator,o.asyncValidators=i.asyncValidator),new x(r,o)}record(e,i=null){let r=this._reduceControls(e);return new Oe(r,i)}control(e,i,r){let o={};return this.useNonNullable?(Tt(i)?o=i:(o.validators=i,o.asyncValidators=r),new H(e,S(y({},o),{nonNullable:!0}))):new H(e,i,r)}array(e,i,r){let o=e.map(s=>this._createControl(s));return new $e(o,i,r)}_reduceControls(e){let i={};return Object.keys(e).forEach(r=>{i[r]=this._createControl(e[r])}),i}_createControl(e){if(e instanceof H)return e;if(e instanceof L)return e;if(Array.isArray(e)){let i=e[0],r=e.length>1?e[1]:null,o=e.length>2?e[2]:null;return this.control(i,r,o)}else return this.control(e)}static \u0275fac=function(i){return new(i||n)};static \u0275prov=g({token:n,factory:n.\u0275fac,providedIn:"root"})}return n})();var Nr=(()=>{class n extends Xi{group(e,i=null){return super.group(e,i)}control(e,i,r){return super.control(e,i,r)}array(e,i,r){return super.array(e,i,r)}static \u0275fac=(()=>{let e;return function(r){return(e||(e=w(n)))(r||n)}})();static \u0275prov=g({token:n,factory:n.\u0275fac,providedIn:"root"})}return n})();var xr=(()=>{class n{static withConfig(e){return{ngModule:n,providers:[{provide:W,useValue:e.callSetDisabledState??Se}]}}static \u0275fac=function(i){return new(i||n)};static \u0275mod=ae({type:n});static \u0275inj=se({imports:[Qt]})}return n})(),Fr=(()=>{class n{static withConfig(e){return{ngModule:n,providers:[{provide:Je,useValue:e.warnOnNgModelWithFormControl??"always"},{provide:W,useValue:e.callSetDisabledState??Se}]}}static \u0275fac=function(i){return new(i||n)};static \u0275mod=ae({type:n});static \u0275inj=se({imports:[Qt]})}return n})();var Pr=(()=>{class n{isErrorState(e,i){return!!(e&&e.invalid&&(e.touched||i&&i.submitted))}static \u0275fac=function(i){return new(i||n)};static \u0275prov=g({token:n,factory:n.\u0275fac,providedIn:"root"})}return n})();var Xt=class{_defaultMatcher;ngControl;_parentFormGroup;_parentForm;_stateChanges;errorState=!1;matcher;constructor(t,e,i,r,o){this._defaultMatcher=t,this.ngControl=e,this._parentFormGroup=i,this._parentForm=r,this._stateChanges=o}updateErrorState(){let t=this.errorState,e=this._parentFormGroup||this._parentForm,i=this.matcher||this._defaultMatcher,r=this.ngControl?this.ngControl.control:null,o=i?.isErrorState(r,e)??!1;o!==t&&(this.errorState=o,this._stateChanges.next())}};export{M as a,K as b,vt as c,l as d,st as e,le as f,Fe as g,lt as h,gt as i,tr as j,te as k,kt as l,D as m,yt as n,p as o,V as p,Tr as q,Vr as r,x as s,Ar as t,Ni as u,H as v,Mr as w,Ri as x,Er as y,Ui as z,$i as A,Kt as B,zt as C,Jt as D,Gi as E,qi as F,zi as G,Zi as H,Qi as I,Nr as J,xr as K,Fr as L,Pr as M,Xt as N};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as H}from"./chunk-
|
|
1
|
+
import{a as H}from"./chunk-G4B4D3XR.js";import{B as j,D as K,k as T,l as U,o as F,p as O,q as A,r as P,u as G,v as Y}from"./chunk-XFU5YJJP.js";import{H as k,K as z,l as L,q as N,r as W,u as B,x as R,y as q}from"./chunk-GIZH6HIB.js";import{Fa as a,Fb as h,Kb as n,Lb as E,Mb as I,Oa as y,Pb as f,Qb as M,Rb as C,Yb as _,Yd as V,bb as S,cb as x,ga as c,hb as d,ib as e,ja as m,jb as t,ka as p,kb as g,rb as b,tb as v,vb as D}from"./chunk-ANRGX57I.js";var J=()=>({standalone:!1});function Q(o,X){if(o&1&&(e(0,"div",3),g(1,"i",10),n(2),t()),o&2){let u=D();a(2),I(" ",u.data.error," ")}}var de=(()=>{class o{dialogRef=c(T);data=c(U);titleDialog="Sign in to Signal K";saveCredential(){this.data.error=null,this.dialogRef.close(this.data)}static \u0275fac=function(s){return new(s||o)};static \u0275cmp=y({type:o,selectors:[["app-modal-user-credential"]],decls:26,vars:10,consts:[["login","ngForm"],["name","login",3,"ngSubmit"],["mat-dialog-title",""],[1,"errorMsgBox"],[1,"login-grid"],[1,"userLoginInput"],["type","text","autocomplete","username","id","username","matInput","","placeholder","User ID","name","username","required","",3,"ngModelChange","ngModel","ngModelOptions"],["type","password","autocomplete","current-password","autocapitalize","off","autocorrect","off","spellcheck","false","id","current-password","matInput","","placeholder","Password","name","current-password","required","",3,"ngModelChange","ngModel","ngModelOptions"],["mat-flat-button","","type","button",3,"mat-dialog-close"],["mat-flat-button","","type","submit",3,"disabled"],["aria-hidden","true",1,"fa-solid","fa-times-circle",2,"color","red","padding-right","5px"]],template:function(s,i){if(s&1){let l=b();e(0,"form",1,0),v("ngSubmit",function(){return m(l),p(i.saveCredential())}),e(2,"span",2),n(3),t(),e(4,"mat-dialog-content"),S(5,Q,3,1,"div",3),g(6,"br"),e(7,"div",4)(8,"mat-form-field",5)(9,"mat-label"),n(10,"User ID"),t(),e(11,"input",6),C("ngModelChange",function(r){return m(l),M(i.data.user,r)||(i.data.user=r),p(r)}),t(),e(12,"mat-error"),n(13," You must enter a User ID value "),t()(),e(14,"mat-form-field",5)(15,"mat-label"),n(16,"Password"),t(),e(17,"input",7),C("ngModelChange",function(r){return m(l),M(i.data.password,r)||(i.data.password=r),p(r)}),t(),e(18,"mat-error"),n(19," You must enter a password value "),t()()()(),g(20,"mat-divider"),e(21,"mat-dialog-actions")(22,"button",8),n(23,"Cancel"),t(),e(24,"button",9),n(25,"Sign in"),t()()()}if(s&2){let l=h(1);a(3),E(i.titleDialog),a(2),x(i.data.error?5:-1),a(6),f("ngModel",i.data.user),d("ngModelOptions",_(8,J)),a(6),f("ngModel",i.data.password),d("ngModelOptions",_(9,J)),a(5),d("mat-dialog-close",!1),a(2),d("disabled",!l.valid)}},dependencies:[z,q,L,N,W,k,R,B,O,A,j,G,K,Y,H,P,V,F],styles:[".errorMsgBox[_ngcontent-%COMP%]{background-color:#fff8dc;color:#2f4f4f;display:flex;padding:5px;font-family:Arial,Times,serif;font-size:14px}.login-grid[_ngcontent-%COMP%]{display:grid;gap:10px;padding-left:10px;padding-right:10px}.userLoginInput[_ngcontent-%COMP%]{margin-bottom:10px}"]})}return o})();export{de as a};
|