@kosdev-code/kos-ui-sdk 2.0.44 → 2.0.46

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/index.cjs CHANGED
@@ -1,80 +1,80 @@
1
- "use strict";var fu=Object.defineProperty;var gu=(t,e,s)=>e in t?fu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var l=(t,e,s)=>(gu(t,typeof e!="symbol"?e+"":e,s),s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const $=require("loglevel"),M=require("mobx"),b=require("robot3"),Re=require("date-fns"),T=require("@emotion/react/jsx-runtime"),co=require("@emotion/styled"),ni=require("react-dom"),je=require("@emotion/react"),f=require("react"),lo=require("mobx-react-lite"),pu=require("@use-gesture/react"),cr="method",ii="topic",gt="url",os="request-id",lr="response-id",uo="status",$e="dst-addr",ai="src-addr",Me="type",ho="ordered",fo="tracker",ci="Content-Type",li="Cache-Control",di="requestId",ui=process.env.KOS_LOGIN_URL||"http://localhost",hi=process.env.KOS_APP_PORT||"8080",mu=`${ui}:${hi}`,xs="{MODEL_ID}";var ns=(t=>(t.SEND="/ws/log/msg/send",t.RECEIVED="/ws/log/msg/receive",t))(ns||{}),fi=(t=>(t.MSG_RECEIVE="/mock/msg/receive",t))(fi||{});const go="/kos/model/ready/";$.info("Initializing event bus");globalThis.kos=globalThis.kos||{};globalThis.kos.subscriptions=globalThis.kos.subscriptions||{};const K=globalThis.kos.subscriptions,yu=()=>Symbol("eventKey");function po(t){return K[t]&&Object.getOwnPropertySymbols(K[t]).length>0}function O(t,e){const s=yu();return K[t]||($.debug(`Initializing subscription for ${t}`),K[t]={}),$.debug(`Subscribing to ${t} with id ${s.toString()}`),K[t][s]=e,{count:K[t]?Object.getOwnPropertySymbols(K[t]).length:0,unsubscribe:()=>($.debug(`Unsubscribing from ${t} with id ${s.toString()}`),K[t]&&K[t][s]&&delete K[t][s],K[t]&&Object.getOwnPropertySymbols(K[t]).length===0&&delete K[t],{count:K[t]?Object.getOwnPropertySymbols(K[t]).length:0})}}function j(t,e,s={}){if(!K[t]||Object.getOwnPropertySymbols(K[t]).length===0)return $.debug(`No subscriptions for ${t}. Not publishing.`),{eventType:t,subscribers:0};const r=Object.getOwnPropertySymbols(K[t]).length;return Object.getOwnPropertySymbols(K[t]).forEach(o=>{if(s.sync){const n=s.sync;$.debug(`Performing sync publish for ${t} with sync id ${n}`),K[t][o]({body:e,headers:s}).then(i=>{$.debug(`Response recieved for ${n}, publishing back to source.`),j(n,i)})}else $.debug(`Performing async publish for ${t}`),K[t][o]({body:e,headers:s})}),{eventType:t,subscribers:r}}function bu(){$.warn("Resetting event bus"),Object.keys(K).forEach(t=>delete K[t])}function gi(t,e){const s=O(t,r=>{s.unsubscribe(),e(r)});return s.unsubscribe}function mo(t,e){return new Promise((s,r)=>{let o=null;const n=gi(t,i=>{o&&clearTimeout(o),s(i)});e&&(o=setTimeout(()=>{n(),r(new Error(`Timeout waiting for event: ${t}`))},e))})}const wu=Object.freeze(Object.defineProperty({__proto__:null,hasEventSubscriptions:po,once:gi,publish:j,reset:bu,subscribe:O,waitFor:mo},Symbol.toStringTag,{value:"Module"}));function dr(t,e){const s=O(t,r=>{s.unsubscribe(),e(r)});return s.unsubscribe}function ur(t,e){return new Promise((s,r)=>{let o=null;const n=dr(t,i=>{o&&clearTimeout(o),s(i)});e&&(o=setTimeout(()=>{n(),r(new Error(`Timeout waiting for event: ${t}`))},e))})}function pi(t,e){const s=t.map(r=>ur(r,e));return Promise.all(s)}function mi(t,e){return new Promise((s,r)=>{const o=[];let n=null,i=!1;const a=()=>{o.forEach(c=>c()),n&&clearTimeout(n)};t.forEach(c=>{const d=dr(c,u=>{i||(i=!0,a(),s({eventType:c,data:u}))});o.push(d)}),e&&(n=setTimeout(()=>{i||(i=!0,a(),r(new Error(`Timeout waiting for any event: ${t.join(", ")}`)))},e))})}function yi(t,e,s){return O(t,o=>{o&&e(o)&&s(o)}).unsubscribe}function bi(t,e,s){return O(t,o=>{if(o){const n=e(o);s(n)}}).unsubscribe}function wi(t,e,s){let r=null;const o=O(t,n=>{r&&clearTimeout(r),r=setTimeout(()=>{s(n)},e)});return()=>{r&&clearTimeout(r),o.unsubscribe()}}function vi(t,e,s){let r=0,o=null;const n=O(t,i=>{const a=Date.now(),c=a-r;c>=e?(r=a,s(i)):o||(o=setTimeout(()=>{r=Date.now(),s(i),o=null},e-c))});return()=>{o&&clearTimeout(o),n.unsubscribe()}}function Mi(t,e,s){let r=[],o=null;const n=()=>{r.length>0&&(s([...r]),r=[])},i=O(t,a=>{a&&(r.push(a),o||(o=setTimeout(()=>{n(),o=null},e)))});return()=>{o&&(clearTimeout(o),n()),i.unsubscribe()}}function yo(t,e=1){const s=[];return O(t,r=>{r&&(s.push(r),s.length>e&&s.shift())}),{subscribe:r=>(s.forEach(o=>r(o)),O(t,r))}}function Ei(t,e){const s=t.map(r=>O(r,o=>{o&&e(r,o)}));return()=>{s.forEach(r=>r.unsubscribe())}}function Ti(t,e){let s=t;const r=[],o=new Set;return Object.values(e).forEach(n=>{Object.keys(n).forEach(i=>{o.add(i)})}),o.forEach(n=>{const{unsubscribe:i}=O(n,a=>{const c=e[s];c&&c[n]&&(s=c[n](a))});r.push(i)}),{get state(){return s},unsubscribe:()=>{r.forEach(n=>n())}}}function _i(t,e,s,r){const o=ur(e,r);return j(t,s),o}async function*Ii(t){const e=[],s=[],r=O(t,o=>{o&&(s.length>0?s.shift()(o):e.push(o))});try{for(;;)e.length>0?yield e.shift():yield await new Promise(o=>{s.push(o)})}finally{r.unsubscribe()}}const vu={once:dr,waitFor:ur,waitForAll:pi,race:mi,filter:yi,map:bi,debounce:wi,throttle:vi,buffer:Mi,replay:yo,merge:Ei,stateMachine:Ti,request:_i,eventIterator:Ii},Mu=Object.freeze(Object.defineProperty({__proto__:null,EventBusFunctional:vu,buffer:Mi,debounce:wi,eventIterator:Ii,filter:yi,map:bi,merge:Ei,once:dr,race:mi,replay:yo,request:_i,stateMachine:Ti,throttle:vi,waitFor:ur,waitForAll:pi},Symbol.toStringTag,{value:"Module"}));async function hr(t,e){const{getCurrentState:s,transformState:r,shouldUseFetchedState:o,timeout:n}=e,i=mo(t,n),a=await s(),c=r?r(a):a;return o&&o(c)?(i.catch(()=>{}),c):await Promise.race([i,new Promise(u=>{setTimeout(()=>u(c),100)})])}function Si(t,e,s){const{getCurrentState:r,transformState:o}=s;let n=!1;const i=O(t,a=>{a&&(n=!0,e(a))});return Promise.resolve(r()).then(a=>{const c=o?o(a):a;n||e(c)}).catch(a=>{console.error("Failed to fetch initial state:",a)}),i.unsubscribe}function Oi(t,e){let s;const r=new Set,o=async()=>{try{typeof e=="string"?s=await(await fetch(e)).json():s=await e(),r.forEach(a=>a(s))}catch(a){throw console.error("Failed to fetch initial state:",a),a}};O(t,a=>{a!=null&&a.body&&(s=a.body,r.forEach(c=>c(s)))});let n=!1;const i=()=>{n||(n=!0,o())};return{get state(){return s},async getState(){return i(),s===void 0&&await new Promise(a=>{const c=()=>{s!==void 0?a():setTimeout(c,10)};c()}),s},subscribe(a){return i(),r.add(a),s!==void 0&&a(s),()=>{r.delete(a)}},async refresh(){return await o(),s}}}async function bo(t,e){if(typeof t=="string")return hr(t,e);const s=t,{getCurrentState:r,shouldUseFetchedState:o,timeout:n}=e,i=await r(),a=e.transformState?e.transformState(i):i;if(o&&o(a))return a;const c=s.map(u=>mo(u,n)),d=await Promise.all(c);return d[d.length-1]}function $i(t,e,s){const{fetchMissedEvents:r,checkInterval:o=3e4,deduplicateById:n}=s,i=new Set,a=O(t,async d=>{if(d){if(n){const u=n(d);if(i.has(u))return;i.add(u),i.size>1e3&&Array.from(i).slice(0,500).forEach(g=>i.delete(g))}await e(d)}}),c=setInterval(async()=>{try{const d=await r(),u=Array.isArray(d)?d:[d];for(const h of u)if(n){const g=n(h);i.has(g)||(i.add(g),await e(h))}else await e(h)}catch(d){console.error("Failed to fetch missed events:",d)}},o);return()=>{a.unsubscribe(),clearInterval(c)}}function Di(t){const{connectEvent:e,disconnectEvent:s,errorEvent:r,dataEvent:o,fetchInitialState:n,reconnectDelay:i=5e3}=t,a={state:"disconnected",data:void 0,async waitForConnection(u){if(a.state==="connected"&&a.data)return a.data;const h=await hr(e,{getCurrentState:n,shouldUseFetchedState:g=>!!g,timeout:u});return a.state="connected",a.data=h,d(),h},subscribe(u){return c.add(u),u(a),()=>{c.delete(u)}},async reconnect(){a.state="connecting",d();try{const u=await n();a.state="connected",a.data=u,d()}catch{a.state="error",d(),setTimeout(()=>{a.state==="error"&&a.reconnect()},i)}}},c=new Set,d=()=>{c.forEach(u=>u(a))};return O(e,u=>{a.state="connected",u!=null&&u.body&&(a.data=u.body),d()}),O(s,()=>{a.state="disconnected",d(),setTimeout(()=>{a.state==="disconnected"&&a.reconnect()},i)}),r&&O(r,()=>{a.state="error",d()}),o&&O(o,u=>{u!=null&&u.body&&a.state==="connected"&&(a.data=u.body,d())}),a.reconnect(),a}const Eu={waitForOrGetState:hr,subscribeWithInitialState:Si,createStatefulEventStream:Oi,waitForAllWithState:bo,createResilientEventHandler:$i,createConnectionStateManager:Di},Tu=Object.freeze(Object.defineProperty({__proto__:null,EventBusState:Eu,createConnectionStateManager:Di,createResilientEventHandler:$i,createStatefulEventStream:Oi,subscribeWithInitialState:Si,waitForAllWithState:bo,waitForOrGetState:hr},Symbol.toStringTag,{value:"Module"})),_u=(t,e=0)=>{if(!+t)return{value:0,scale:"bytes",toString:()=>"0 bytes"};const s=1024,r=e<0?0:e,o=["bytes","KB","MB","GB","TB"],n=Math.floor(Math.log(t)/Math.log(s)),i=parseFloat((t/Math.pow(s,n)).toFixed(r)),a=o[n];return{value:i,scale:a,toString:()=>`${i} ${a}`}};function wo(t){let e="pending",s;const r=t.then(n=>{e="success",s=n},n=>{e="error",s=n});return{read:()=>{switch(e){case"pending":throw r;case"error":throw s;default:return s}}}}function pt(){return"xxxxxxxx-xxxx-4xxx-2xxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=Math.random()*16|0;return(t=="x"?e:e&3|8).toString(16)})}function Iu(t,e){e.forEach(s=>{Object.getOwnPropertyNames(s.prototype).forEach(r=>{const o=Object.getOwnPropertyDescriptor(s.prototype,r);Object.defineProperty(t.prototype,r,o)})})}function Su(t,e){const s=t??[],r=e??[];return s.length!==r.length?!1:s.every((o,n)=>o===r[n])}const vo=(t,e)=>{const s=t.map(n=>n.id);return e.map(n=>n.id).filter(n=>!s.includes(n))},Ou=({container:t,onAddItem:e,onRemoveItem:s,idMapper:r=o=>o})=>o=>{const n=o.map(r),a=vo(n,t.data).map(s).filter(Boolean);t.removeAll(a);const c=n.map(e).filter(Boolean);t.addAll(c)},$u=({container:t,onAddItem:e,onRemoveItem:s,idMapper:r=o=>o})=>o=>{const n=o.map(r);vo(n,t.models).forEach(s),n.forEach(e)},Du=({items:t,onAddItem:e,onRemoveItem:s,idMapper:r=o=>o})=>o=>{const n=o.map(r);vo(n,t).forEach(s),n.forEach(e)},Cu=(t,e="parent-")=>{let s=t;return s.startsWith(e)&&(s=s.replace(e,"")),s},En=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"}),Tn=[{amount:60,name:"seconds"},{amount:60,name:"minutes"},{amount:24,name:"hours"},{amount:7,name:"days"},{amount:4.34524,name:"weeks"},{amount:12,name:"months"},{amount:Number.POSITIVE_INFINITY,name:"years"}];function Ci(t){let e=(t.getTime()-Date.now())/1e3;for(let s=0;s<=Tn.length;s++){const r=Tn[s];if(Math.abs(e)<r.amount)return En.format(Math.round(e),r.name);e/=r.amount}return En.format(Math.round(e),"years")}const Mo=t=>t%4===0&&t%100!==0||t%400===0,Eo=(t,e)=>[31,Mo(t)?29:28,31,30,31,30,31,31,30,31,30,31][e],Ri=(t,e)=>{const s=new Date(t),r=t.getDate();return s.setDate(1),s.setMonth(s.getMonth()+e),s.setDate(Math.min(r,Eo(s.getFullYear(),s.getMonth()))),s},Ai=(t,e)=>{const s=new Date(t);return s.setDate(s.getDate()+e),s},rt="en-US",xi={short:{year:"numeric",month:"2-digit",day:"2-digit"},medium:{year:"numeric",month:"short",day:"2-digit"},long:{year:"numeric",month:"long",day:"numeric"},full:{year:"numeric",month:"long",day:"numeric",weekday:"long"}},Pi={short:{hour:"2-digit",minute:"2-digit",hour12:!0},medium:{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!0},long:{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!0,timeZoneName:"short"},full:{hour:"2-digit",minute:"2-digit",hour12:!0,timeZoneName:"long"}},Li=(t,{dateStyle:e="short",locales:s=rt}={dateStyle:"short",locales:rt})=>{const r=e==="short"?xi.short:{dateStyle:e};return new Intl.DateTimeFormat(s,r).format(t)},ki=(t,{locales:e=rt,timeStyle:s="short"}={locales:rt,timeStyle:"short"})=>{const r=Pi[s];return new Intl.DateTimeFormat(e,r).format(t)},Fi=(t,{dateStyle:e="short",locales:s=rt,timeStyle:r="short"}={dateStyle:"short",locales:rt,timeStyle:"short"})=>{const o={...e&&xi[e],...r&&Pi[r]};return new Intl.DateTimeFormat(s,o).format(t)},Ru=Object.freeze(Object.defineProperty({__proto__:null,addDaysToDate:Ai,addMonthsToDate:Ri,formatDate:Li,formatDateSince:Ci,formatDateTime:Fi,formatTime:ki,getDaysInMonth:Eo,isLeapYear:Mo},Symbol.toStringTag,{value:"Module"}));function Ni(t,e,s=300){let r;return(...o)=>{clearTimeout(r),r=setTimeout(()=>{e.apply(t,o)},s)}}const Q="canvas-renderer",Or=new Map,_n=new Map,$r=new Map,Dr=new Map,is=(t,e)=>{Ui[t]=e},Ui={indexExtension:{registerIndexExtension:(t,e)=>{const s=Dr.get(t)||{};Object.assign(s,e),Dr.set(t,e)},loadIndexExtensions:t=>Dr.get(t)||{}},loader:{registerLoader:(t,e)=>{_n.set(t,e)},executeLoader:async(t,e)=>{const s=_n.get(t);if(s)return await s(e)}},propertyMapper:{registerPropertyMapper:(t,e)=>{$r.set(t,e)},hasMapper:t=>$r.has(t),executeMapper:(t,e,s)=>{const r=$r.get(t);return r?r(e,s):""}},dataMapper:{registerDataMapper:(t,e)=>{const s=Or.get(t)||[];s.push(e),Or.set(t,s)},executeMapper:async(t,e,s)=>{const r=Or.get(t);if(!r)return{};const o={};for(const n of r){const i=await n(e,s);Object.assign(o,i)}return o}},canvas:{registerRenderer:(t,e)=>{if(!S[Q]){console.warn(`Canvas renderer extension point is not registered. Cannot register renderer "${t}".`);return}S[Q].register(t,e)}}},S=Ui,Au=async({context:t,extension:e})=>{const s=await S.loader.executeLoader(e,{});return t==null||t.set(e,s),s},xu=async({extension:t,contextData:e,data:s})=>await S.dataMapper.executeMapper(t,s,e),Pu=async({extension:t,contextData:e,data:s})=>await S.propertyMapper.executeMapper(t,s,e),Lu=Object.freeze(Object.defineProperty({__proto__:null,executeDataMapperExtension:xu,executeLoaderExtension:Au,executePropertyMapperExtension:Pu},Symbol.toStringTag,{value:"Module"})),ku="Extensions";class Fu{constructor(){l(this,"extensions");this.extensions={}}register(e,s,r){this.extensions[e]={},this.extensions[e][s]={component:r}}get(e,s){if(!this.extensions[e])throw new Error(`Extension point ${e} not found`);return this.extensions[e][s]}get allExtensions(){return this.extensions}}const ue=(t=null)=>(t||window.location.search.replace("?","")).split("&").map(e=>{const[s,r]=e.split("=");return[s,decodeURIComponent(r||"")]}).reduce((e,[s,r])=>(e[s]=r,e),{}),ji="studio.tools.preview",Nu="studio.relax.store.validation",Bi="studio.log.debug",Ki="studio.log.info",Uu={profiles:[ji]};var oi;const ju=((oi=globalThis.getKosConfig)==null?void 0:oi.call(globalThis))||JSON.stringify(Uu),Hi=JSON.parse(ju);globalThis.kosConfig=Hi;const To=Hi,zi=()=>To.profiles||[],Hr=t=>zi().includes(t),Bu=()=>To.logging||!1,Ku=()=>{const t=Hr(Bi),e=Hr(Ki);return t?"DEBUG":e?"INFO":void 0},Gi=()=>{const t=ue(),e=Ku(),r=t.kosLogLevel??e??window.kosLogLevel??process.env.KOS_LOG_LEVEL;return r||"WARN"},Vi=()=>window.kosMessageLogging||process.env.KOS_MESSAGE_LOGGING==="true",Yi=()=>window.kosMessageStudioLogging||process.env.KOS_MESSAGE_STUDIO_LOGGING==="true",qi="ws-log",Hu=$.methodFactory,Wi=Vi(),zu=Yi();$.methodFactory=function(t,e,s){const r=Hu(t,e,s);return function(o,n){var c;const i=s?String(s):"",a=i?`[${String(i).substring(i.lastIndexOf(":")+1)}] | `:"[root] | ";r(`${a}${o}`,n||""),(c=globalThis==null?void 0:globalThis.kosConfig)!=null&&c.logging&&globalThis.kosLog&&(s!==qi||Wi&&zu)&&globalThis.kosLog(`UI: ${a}${o}`)}};let Qi=Gi();$.setLevel(Qi);window.setKosLogLevel=t=>{Qi=t,$.setLevel(t)};const Ps=$.getLogger(qi);window.enableKosMessageLog=()=>{Ps.setLevel($.levels.INFO)};window.disableKosMessageLog=()=>{Ps.setLevel($.levels.ERROR)};Wi?window.enableKosMessageLog():window.disableKosMessageLog();const Gu=["color: black","display: block","background-color: lightgreen","padding: 4px","margin: 0","text-shadow: 0 1px 0 rgba(0, 0, 0, 0.3)","box-shadow: 0 1px 0 rgba(255, 255, 255, 0.4) inset, 0 5px 3px -5px rgba(0, 0, 0, 0.5), 0 -13px 5px -10px rgba(255, 255, 255, 0.4) inset","font-weight: bold"].join(";"),Vu=["color: black","display: block","padding: 4px","background-color: yellow","margin: 0","text-shadow: 0 1px 0 rgba(0, 0, 0, 0.3)","box-shadow: 0 1px 0 rgba(255, 255, 255, 0.4) inset, 0 5px 3px -5px rgba(0, 0, 0, 0.5), 0 -13px 5px -10px rgba(255, 255, 255, 0.4) inset","font-weight: bold"].join(";"),ps=t=>e=>{$.getLevel()<=t&&e()},p={...$,ifDebug:ps($.levels.DEBUG),ifInfo:ps($.levels.INFO),ifWarn:ps($.levels.WARN),ifError:ps($.levels.ERROR),getLogger:t=>$.getLogger(`kos::${t}`),getLoggers:()=>$.getLoggers(),createLogger:({name:t,group:e})=>{var n,i,a,c;const s=`${e?`${e}:`:"kos"}::${t}`,r=$.getLogger(s);let o=(i=(n=globalThis.kos.logOverrides)==null?void 0:n.find(d=>d.name===s))==null?void 0:i.level;return o?r.setLevel(o):(o=(c=(a=globalThis.kos.logOverrides)==null?void 0:a.find(d=>s.startsWith(d.name)))==null?void 0:c.level,o&&r.setLevel(o)),r},wsSend:(...t)=>{const e=String(t).replace(/\n/g,"\\n");Ps.info(`%c⬆ ${e}`,Gu)},wsReceive:(...t)=>{const e=String(t).replace(/\n/g,"\\n");Ps.info(`%c⬇ ${e}`,Vu)}},Zi="featureFlagResolver",ms=new Map;is(Zi,{register:(t,e)=>{var s;ms.has(t)||ms.set(t,[]),(s=ms.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=ms.get(t);if(!s)return[];const r=s.map(a=>a(e)),n=(await Promise.allSettled(r)).map(a=>a.status==="fulfilled"?a.value:(p.info(`Feature flag resolver ${t} failed: ${a.reason}`),[])).flat(),i=Array.from(new Set(n)).reduce((a,c)=>(a[c]=!0,a),{});return Ji.updateFlags(i),Object.keys(i)}});const Yu="kos.loader.featureFlag";class Xi{constructor(e={}){l(this,"flags",{});this.flags=e}isFeatureEnabled(e){return!!this.flags[e]}enableFeature(e){this.flags[e]=!0}disableFeature(e){this.flags[e]=!1}toggleFeature(e){this.flags[e]=!this.flags[e]}updateFlags(e){this.flags={...this.flags,...e}}}window.KosFeatureFlags=window.KosFeatureFlags??new Xi;const Ji=window.KosFeatureFlags,ea=(t,e,s)=>{s/=100;const r=e*Math.min(s,1-s)/100,o=n=>{const i=(n+t/30)%12,a=s-r*Math.max(Math.min(i-3,9-i,1),-1);return Math.round(255*a).toString(16).padStart(2,"0")};return`#${o(0)}${o(8)}${o(4)}`},ta=t=>{const s=new RegExp("hsl\\((\\d+),\\s+(\\d+)\\%,\\s+(\\d+)\\%\\)").exec(t);if(!s)throw Error("Invalid HSL string");return ea(parseInt(s[1]),parseInt(s[2]),parseInt(s[3]))},sa=(t,e)=>getComputedStyle(t).getPropertyValue(e),qu=(t,e)=>ta(sa(t,e)),Wu=(t,e)=>{const s={...t};return s.id&&delete s.id,s},zr=(t,e,s=Wu)=>{const r=s(t,e);M.runInAction(()=>{Object.assign(e,r)})},Cr=new Map,ra={addToDeletionQueue:(t,e)=>{const s=Cr.get(t)||[];s.push(e),Cr.set(t,s)},cancelDeletion:t=>{const e=Cr.get(t);e&&e.forEach(s=>{clearTimeout(s)})}},Qu=p.createLogger({name:"kos-dependency-manager"});class Zu{constructor(){l(this,"_usedByCache",new Map);l(this,"_usesCache",new Map)}add(e,s){ra.cancelDeletion(s);const r=this._usedByCache.get(s)||[];r.includes(e)||r.push(e),this._usedByCache.set(s,r);const o=this._usesCache.get(e)||[];o.includes(s)||o.push(s),this._usesCache.set(e,o)}remove(e,s){const r=this._usedByCache.get(s)||[];this._usedByCache.set(s,r.filter(n=>n!==e));const o=this._usesCache.get(e)||[];this._usesCache.set(e,o.filter(n=>n!==s))}canDestroy(e){const s=this._usedByCache.get(e);return s!=null&&s.length?(Qu.info(`Model ${e} is still used by: ${s.join(", ")}`),!1):!0}clear(){this._usedByCache.clear(),this._usesCache.clear()}}var w=(t=>(t.CREATING="creating",t.CREATED="created",t.INITIALIZING="initializing",t.INITIALIZED="initialized",t.LOADING="loading",t.LOADED="loaded",t.ONLINE="online",t.READYING="readying",t.READY="ready",t.READY_FAILED="ready_failed",t.RESETTING="resetting",t.RESET="reset",t.OFFLINE="offline",t.UNLOADING="unloading",t.UNLOADED="unloaded",t.FAILED="failed",t.INACTIVE="inactive",t.ACTIVE="active",t.ACTIVATING="activating",t.DEACTIVATING="deactivating",t))(w||{}),A=(t=>(t.CREATE="create",t.INITIALIZE="init",t.LOAD="load",t.READY="ready",t.GO_ONLINE="go_online",t.GO_OFFLINE="go_offline",t.RESET="go_offline",t.UNLOAD="unload",t.FAILED="failed",t.GO_ACTIVE="go_active",t.GO_INACTIVE="go_inactive",t.TIMEOUT="timeout",t))(A||{});const In=p.createLogger({name:"kos-model-cache"});class Xu{constructor(e=[]){l(this,"_modelsById",M.observable.map(new Map));l(this,"_toDelete",new Map);l(this,"_preloaded",[]);l(this,"_isPreloaded",!1);this.preloadKeys=e}get models(){return Array.from(this._modelsById.values()).map(e=>e).filter(e=>!this._toDelete.has(e.modelId))}getModelById(e){if(e&&!this._toDelete.has(e))return this._modelsById.get(e)}addModel(e){const s=this.getModelById(e.modelId)||e;return this._modelsById.set(s.modelId,s),s}removeModel(e){this._modelsById.delete(e),this._toDelete.delete(e)}hasModel(e){return!!e&&this._modelsById.has(e)&&!this._toDelete.has(e)}restoreFromDeleteCache(e){if(e&&this._toDelete.has(e)){const s=this._toDelete.get(e);this._toDelete.delete(e),this._modelsById.set(e,s)}}markForDeletion(e){this._modelsById.delete(e.modelId),this._toDelete.set(e.modelId,e)}preload(e){return this._isPreloaded?(In.debug("Returning cached preloaded models"),this._preloaded):(this._preloaded=this.preloadKeys.map(s=>(In.debug(`Preloading model: ${typeof s=="string"?s:s.modelType}`),e(s))).filter(s=>!!s),this._isPreloaded=!0,this._preloaded)}}const J=Symbol("SubscriptionHandlers"),F=Symbol("DependencyModels"),Ft=Symbol("FutureService"),Nt=Symbol("ChildModels"),Ut=Symbol("ParentModel"),jt=Symbol("LogConfig"),Os=Symbol("ReferenceConfig"),oa=Symbol("KosModelSymbol"),Ke=Symbol("ModelEffects"),Ls=Symbol("CompanionParentModel"),be=(t,e)=>{t[Nt]=t[Nt]||{},t[Nt][e]=!0},Ge=t=>`{PROP_${String(t)}}`,Ju=t=>`{PROP_${String(t)}}`,eh=Ge("kosParentId"),fr=t=>e=>{e[Ut]=e[Ut]||{};const s=(t==null?void 0:t.parentId)||eh;e[Ut]={parentId:s}},ot=({value:t,modelId:e,modelData:s})=>{let r=t;if(Array.isArray(r))return[...t];if(typeof r!="string"&&typeof r!="object")return r;if(typeof r=="object")r=Object.keys(r).reduce((o,n)=>(o[n]=ot({value:r[n],modelId:e,modelData:s}),o),{});else if(typeof r=="string"){const o=new RegExp(".*({PROP_(.+)})");let n=r!=null&&r.includes(xs)?r.replace(xs,e):r;const i=n.match(o);if(i&&s&&(Object.getOwnPropertyNames(s).includes(i[2])||Object.getOwnPropertyNames(Object.getPrototypeOf(s)).includes(i[2]))){const a=s[i[2]];n=a?n.replace(i[1],a):void 0}return n}else return r;return r},th=p.createLogger({group:"decorators",name:"kos-model"});function sh(t,e,s){var n;const r=(n=t[Ut])==null?void 0:n.parentId;if(!r)return;const o=ot({value:r,modelData:s,modelId:e});o&&typeof o=="string"&&z.setParentContext(e,o)}function rh(t){const e=t[Ft];e&&Object.entries(e).forEach(([s,{handler:r}])=>{t[s]=r})}function oh(t,e){const s=t[F]||{};Object.entries(s).forEach(([r,o])=>{const n=ot({value:o.id||o.modelType,modelData:t,modelId:e}),i=Object.entries((o==null?void 0:o.options)||{}).reduce((a,[c,d])=>(a[c]=ot({value:d,modelData:t,modelId:e}),a),{});if(typeof n=="string"){if(!o.lazy){const a=I.getInstance().modelManager.createModelInstance(o.modelType,n,i);t[r]=a.data}I.getInstance().modelManager.addDependency(e,n)}})}function nh(t){try{return M.makeAutoObservable(t)}catch(e){return th.error("Failed to make observable:",e),t}}const ih={construct(t,e){var a;const[s,r={}]=e,o=z.createContext(s);sh(t,s,r);const n=p.createLogger({name:t.prototype.modelTypeId,group:((a=t[jt])==null?void 0:a.group)??"kos-model"}),i=new t(s,r,{logger:n,kosContext:o});return rh(i),oh(i,s),nh(i)}};function R(t){return e=>{var r,o;const s=e;return s.prototype.modelTypeId=t,s.prototype[oa]=!0,(r=s.prototype)[J]??(r[J]={}),(o=s.prototype)[F]??(o[F]={}),p.ifDebug(()=>{p.debug(`Registering model with id ${t}`)}),new Proxy(s,ih)}}const ah=({modelType:t})=>e=>{fr()(e),R(t)(e)};function ch(t,e,s){const r=s.value;s.value=function(...o){const n=z.getContext(this.id);return o.push(n),r.apply(this,o)}}var H=(t=>(t.INIT="init",t.LOAD="load",t.READY="ready",t.ACTIVATE="activate",t.ONLINE="online",t))(H||{});const lh=Object.freeze(Object.defineProperty({__proto__:null,DependencyLifecycle:H},Symbol.toStringTag,{value:"Module"})),Ie=Symbol("HttpRouteHandlers"),Sn="__httpBrowserRouter";function gr(t){return function(s){return function(r,o,n){r[Ie]=r[Ie]||[];const i={method:t,path:s,handler:o};return r[Ie].push(i),r[F]=r[F]||{},r[F][Sn]||(r[F][Sn]={modelType:"browser-router-model",lifecycle:H.INIT}),n}}}const na=gr("GET"),as=gr("POST"),dh=gr("PUT"),ia=gr("DELETE"),uh=ia;function ks(t){return!!(t!=null&&t[Ie])&&t[Ie].length>0}function aa(t){return(t==null?void 0:t[Ie])||[]}const hh=({group:t}={group:""})=>e=>{e[jt]=e[jt]||{},e[jt]={group:t}};function ca(t){return(e,s,r)=>{e[Ke]=e[Ke]||{},e[Ke][s]={dependencies:t==null?void 0:t.dependencies,value:r.value},r.value=function(){throw new Error(`Method ${s} cannot be called directly.`)}}}const fh=t=>(e,s)=>{e[Os]=e[Os]||{},e[Os][s]=t},mt=({modelType:t,id:e,options:s,lifecycle:r})=>(o,n)=>{o[F]=o[F]||{},o[F][n]={modelType:t,id:e,options:s,lifecycle:r||H.INIT}},gh=({topic:t,handler:e,websocket:s=!1,condition:r=()=>!0})=>o=>{o[J]=o[J]||{},Array.isArray(t)?t.forEach(n=>{o[J][n]={websocket:s,handler:e,condition:r}}):o[J][t]={websocket:s,handler:Ni(o,M.action(e),200),condition:r}};function la(t,e,s){const r={};if(!t.endsWith("/*"))return r;const o=t.slice(0,-2);if(e.startsWith(o)){const n=e.slice(o.length+1),i=s||"path";r[i]=n}return r}function da(t){return t.endsWith("/*")}function U({topic:t,condition:e=(_,N)=>!0,transform:s=_=>_,websocket:r=!1,fos:o=!1,bridge:n=!1,skipParse:i=!1,lifecycle:a,destinationAddress:c,debounce:d,throttle:u,buffer:h,filter:g,once:m,replay:y,wildcardName:v,flow:E}){return(_,N,x)=>{_[J]=_[J]||{};let P=x.value;const W=typeof d=="number"?d:d==null?void 0:d.delay,re=typeof u=="number"?u:u==null?void 0:u.interval;W&&W>0?P=ph(P,d):re&&re>0?P=mh(P,u):h?P=yh(P,h):m&&(P=bh(P));let L=e;if(g){const V=e;L=(ce,gs,Et)=>g(Et)?V(ce,gs,Et):!1}const Ce={websocket:r,fos:o,bridge:n,handler:P,condition:L,transform:s,lifecycle:a,skipParse:i,destinationAddress:c,wildcardName:v,flow:E};Array.isArray(t)?t.forEach(V=>{_[J][V]=Ce}):_[J][t]=Ce,y&&wh(t,y.bufferSize)}}function ph(t,e){const s=typeof e=="number"?e:e.delay,r=typeof e=="object"?e.discardIntermediate:!1;let o=null,n=[];return function(i){r?(o&&clearTimeout(o),o=setTimeout(()=>{t.call(this,i),o=null},s)):(n.push(i),o&&clearTimeout(o),o=setTimeout(()=>{const a=[...n];n=[],t.call(this,a),o=null},s))}}function mh(t,e){const s=typeof e=="number"?e:e.interval,r=typeof e=="object"?e.discardIntermediate:!1;let o=0,n=null,i=[],a=!1;const c=function(){if(i.length>0){const d=[...i];i=[],t.call(this,d)}};return function(d){const u=Date.now(),h=u-o;r?h>=s?(o=u,t.call(this,d)):n||(n=setTimeout(()=>{o=Date.now(),t.call(this,d),n=null},s-h)):(i.push(d),h>=s?(o=u,c.call(this)):a||(a=!0,n=setTimeout(()=>{o=Date.now(),c.call(this),n=null,a=!1},s-h)))}}function yh(t,e){const s=[];let r=null;const o=e.maxSize||1e3,n=i=>{s.length>0&&(t.call(i,[...s]),s.length=0)};return function(i){if(s.push(i),s.length>=o){r&&(clearTimeout(r),r=null),n(this);return}r||(r=setTimeout(()=>{n(this),r=null},e.time))}}function bh(t){let e=!1;return function(s){e||(e=!0,t.call(this,s))}}function wh(t,e){(Array.isArray(t)?t:[t]).forEach(r=>{yo(r,e)})}function ua(t,e){return`${go}${t}${e?`/${e}`:`/${t}`}`}function ha(t){return`${go}${t}`}function Rr(t){const e=[];return new Promise((s,r)=>{for(const{condition:o,onMatch:n}of t){const i=M.when(o,()=>{e.forEach(a=>a());try{n==null||n(),s()}catch(a){r(a)}});e.push(i)}})}const fa=5e3;class vh extends Error{constructor(s,r){super(s);l(this,"model");this.model=r}}const ga=(t,e,s)=>{let r;return{promise:new Promise((i,a)=>{r=setTimeout(()=>{p.error(`Model ${e.modelId} - ${e.modelTypeName} - ${s} timed out after ${t}ms`),a(new vh(`${e.modelId} - ${e.modelTypeName} - ${s}`,e))},t)}),cancel:()=>{r&&clearTimeout(r)}}},pa=t=>t.fsm.transitionTo(A.GO_ACTIVE,w.ACTIVE),ma=t=>t.whenReady(),ya=t=>t.fsm.transitionTo(A.LOAD,w.LOADED),Mh=t=>t.fsm.transitionTo(A.UNLOAD,w.UNLOADED),ba=t=>t.fsm.transitionTo(A.INITIALIZE,w.INITIALIZED);var _o=(t=>(t.ACTIVE="active",t.READY="ready",t.LOAD="load",t.UNLOAD="unload",t.INIT="init",t))(_o||{});const $s={active:pa,ready:ma,load:ya,init:ba},wa=(t,e)=>{const s=e.id||e.modelType,r=ot({value:s,modelData:t.modelData,modelId:t.modelId});p.debug(`activating dependent model ${e.modelType} with id ${r}`);const o=Object.keys((e==null?void 0:e.options)||{}).reduce((i,a)=>{const c=e.options[a];return i[a]=ot({value:c,modelData:t.modelData,modelId:t.modelId}),i},{});return{dependentModel:I.getInstance().modelManager.createModelInstance(e.modelType,r,o),dataModelId:r}},va=(t,e=H.READY)=>{var o;const s=((o=t.modelData)==null?void 0:o[F])||{};return Object.keys(s).length===0?(p.debug(`${t.modelId} has no dependencies. Returning`),[]):Object.keys(s).filter(n=>s[n].lifecycle===e).map(n=>{const i=s[n],{dependentModel:a,dataModelId:c}=wa(t,i);t.modelData[n]=a.data,p.debug(`waiting for dependent model ${i.modelType} with id ${c} - waiting for WHENREADY`);const d=async(g,m,y)=>{var v;await((v=g.whenReady)==null?void 0:v.call(g)),p.debug(`dependent model ${m} with id ${y} - READY`)},{promise:u,cancel:h}=ga(fa,t,t.status);return Promise.race([d(a.model,i.modelType,c).then(()=>{h()}).catch(g=>{console.error(`Error waiting for dependent model ${i.modelType} with id ${c}:`,g),h()}),u])}).filter(n=>!!n)},Ma=async(t,e,s,r)=>{if(p.debug(`Execute lifecycle with ${e.length} models`),e.length===0){p.debug(`${t.modelId} has no children. Returning`);return}if(!s){p.error(`${t.modelId} is not transitioning with a valid target ${s}`);return}const o=e.map(a=>{let c;return $s[s]&&a?c=$s[s](a):(a||p.error("model is undefined. This shouldn't happen"),$s[s]||p.error(`There is no promise in the Transition Map for ${s}`)),{promise:c,modelId:a==null?void 0:a.modelId,model:a,type:a==null?void 0:a.modelTypeName,status:a==null?void 0:a.status}}).filter(a=>a.promise?a.model?!0:(p.error(`No model found ${a.modelId}`),!1):(p.error(`No promise found ${a.modelId}`),!1)),i=(await Promise.allSettled(o.map(a=>{var u;const{promise:c,cancel:d}=ga(fa,a.model,a.status);return Promise.race([(u=a.promise)==null?void 0:u.then(()=>{d()}).catch(h=>{p.error(`Model ${a.modelId} - ${a.type} failed to transition to ${s}: ${h.message}`),d()}),c])}))).filter(a=>a.status==="rejected");i.length>0&&p.error(`Model ${t.modelId} had ${i.length} failed child models on ${r}`)},Ea=async(t,e,s)=>{await Ma(t,t.getChildren().filter(r=>!!r),e,s)},It=async(t,e)=>{const r=(await Promise.allSettled(va(t,e))).filter(o=>o.status==="rejected");r.length&&(p.error(`There were ${r.length} failed dependent models on ${e}`),p.error(r))},Eh=t=>typeof t.toJSON=="function",Bt=t=>t[F]!==void 0,Io=t=>t.revision!==void 0&&t.index!==void 0,Ta=t=>{if(t){if(Bt(t))return t;if(Io(t))return t.data;if(t instanceof Map||t instanceof M.ObservableMap||t instanceof Set)return Array.from(t.values()).filter(Bt);if(Array.isArray(t))return t.filter(Bt)}};function Th(t){const e=`KosModel(${t.modelTypeName}:${t.modelId})`;try{Object.defineProperty(t,Symbol.toStringTag,{value:e,configurable:!0})}catch{t.toString=()=>e}try{Object.defineProperty(t.constructor,"name",{value:`KosModel_${t.modelTypeName}`,configurable:!0})}catch{t.constructor.name=`KosModel_${t.modelTypeName}`}const s=["fsm","effectManager","subscriptionManager","onlineLifecycleManager","companionManager","childResolver","_offlineQueue"];for(const r of s)r in t&&Object.defineProperty(t,r,{enumerable:!1});Object.defineProperty(t,"debugState",{enumerable:!1,configurable:!0,get(){var r,o,n;return{id:t.modelId,type:t.modelTypeName,initialized:t.initialized,loaded:t.loaded,status:t.status,onlineStatus:t.onlineStatus,activeStatus:t.activeStatus,companions:(o=(r=t.companionManager)==null?void 0:r.all())==null?void 0:o.map(i=>i.modelTypeName),children:(n=t.getChildren)==null?void 0:n.call(t).map(i=>i.modelId),effects:!!t.effectManager,subs:!!t.subscriptionManager}}}),_h(t.modelData,t.modelTypeName,t.modelId,t)}function _h(t,e,s,r){Object.defineProperty(t,Symbol.toStringTag,{value:`KosModelData(${e}:${s})`,configurable:!0});try{Object.defineProperty(t.constructor,"name",{value:`${e}ModelData`,configurable:!0})}catch{t.constructor.name=`${e}ModelData`}Object.defineProperty(t,"debugState",{enumerable:!1,configurable:!0,get(){var a,c,d;const o=((a=r.getChildren)==null?void 0:a.call(r))||[],n=((c=r.companionManager)==null?void 0:c.all())||[],i=r.modelData[F]||{};return{id:s,type:e,companions:{count:n.length,data:n.map(u=>({type:u.modelTypeName,id:u.modelId}))},dependencies:{count:Object.keys(i).length,data:Object.values(i).map(u=>({id:u.id||u.modelType,type:u.modelType,options:u.options,lifecycle:u.lifecycle}))},children:{count:o.length,data:o.map(u=>({id:u.modelId,type:u.modelTypeName}))},data:((d=t.toJSON)==null?void 0:d.call(t))||{},subs:!!r.subscriptionManager}}}),Object.defineProperty(t,"toJSON",{configurable:!0,enumerable:!1,writable:!0,value:()=>{const o={};for(const n of Object.keys(t))if(!(n.startsWith("_")||typeof t[n]=="function"))try{const i=t[n];Bt(i)?o[`[KOS Model] ${n}`]=typeof i.toJSON=="function"?i.toJSON():{id:i.id,type:i.constructor.name}:Io(i)?o[`[KOS Container] ${n}`]=typeof i.toJSON=="function"?i.toJSON():["Container"]:Array.isArray(i)?o[n]=`[Array(${i.length})]`:typeof i=="object"&&i!==null?o[n]=JSON.parse(JSON.stringify(i)):o[n]=i}catch{o[n]="[unreadable]"}return o}})}class Ih{constructor(e){this.model=e}resolve(){const e=new Set([...this.getResolvedDecoratedChildren(),...this.getAdditionalChildren(),...this.model.companionModels.all()]),s=Array.from(e).map(r=>this.model.modelManager.getModelById(r.id||"")).filter(r=>r&&r.status!==w.FAILED).filter(r=>!!r);return s.forEach(r=>{try{z.setParentContext(r.modelId,this.model.modelId)}catch(o){console.error(`Failed to set parent context for ${r.modelId} under ${this.model.modelId}`,o)}}),s}getResolvedDecoratedChildren(){var s;const e=((s=this.model.modelData)==null?void 0:s[Nt])||{};return Object.keys(e).map(r=>Ta(this.model.modelData[r])).filter(r=>!!r).flat()}getAdditionalChildren(){var e,s;return((s=(e=this.model.modelData)==null?void 0:e.getChildren)==null?void 0:s.call(e))||[]}}class Sh{constructor(e){l(this,"companions",new M.ObservableMap);this.hostModel=e}add(e){this.companions.set(e.modelTypeName,e)}clear(){this.companions.clear()}get(e){return this.companions.get(e)}all(){return[...this.companions.values()]}get data(){return this.companions}}class Oh{constructor(e,s,r,o){l(this,"disposers",[]);this.modelTypeName=e,this.modelId=s,this.modelData=r,this.log=o}setup(){var s;const e=((s=this.modelData)==null?void 0:s[Ke])||{};for(const r of Object.keys(e)){const{value:o,dependencies:n,options:i}=e[r],a=o.bind(this.modelData),c=()=>{this.log.info(`Running effect ${r} for ${this.modelTypeName} (${this.modelId})`),M.runInAction(()=>a())},d=n?M.reaction(()=>n(this.modelData),c,{fireImmediately:!!(i!=null&&i.fireImmediately)}):M.autorun(c);this.disposers.push(d)}}disposeAll(){for(const e of this.disposers)try{e()}catch(s){this.log.info(`Failed to dispose effect for ${this.modelId}`,s)}this.disposers=[]}}const $h=p.createLogger({name:"model-active-machine"}),Dh=t=>{const e=b.createMachine(w.INACTIVE,{[w.FAILED]:b.state(b.transition(A.GO_ACTIVE,w.ACTIVATING)),[w.INACTIVE]:b.state(b.transition(A.GO_ACTIVE,w.ACTIVATING)),[w.ACTIVATING]:b.invoke(()=>(t.activeStatus=w.ACTIVATING,t.activate()),b.transition("done",w.ACTIVE,b.action(()=>{t.activeStatus=w.ACTIVE})),b.transition("error",w.FAILED,b.action(()=>{t.activeStatus=w.FAILED}))),[w.ACTIVE]:b.state(b.transition(A.GO_INACTIVE,w.DEACTIVATING)),[w.DEACTIVATING]:b.invoke(()=>(t.activeStatus=w.DEACTIVATING,t.deactivate()),b.transition("done",w.INACTIVE,b.action(()=>{t.activeStatus=w.INACTIVE})),b.transition("error",w.FAILED,b.action(()=>{t.activeStatus=w.FAILED})))});return{service:b.interpret(e,r=>$h.debug(r.machine.current)),machine:e}},On=p.createLogger({name:"model-online-machine"}),Ch=t=>{const e=b.createMachine(w.OFFLINE,{[w.ONLINE]:b.state(b.transition(A.GO_OFFLINE,w.OFFLINE,b.action(async()=>{await t.offline(),t.onlineStatus=w.OFFLINE}))),[w.OFFLINE]:b.state(b.transition(A.GO_ONLINE,w.ONLINE,b.action(async()=>{On.debug(`Going online with model ${t.modelId}`),await t.online(),t.onlineStatus=w.ONLINE,await t.fsm.transitionTo(A.INITIALIZE,w.INITIALIZED)})))}),s=b.interpret(e,r=>On.debug(r.machine.current));return{machine:e,service:s}},Rh=t=>{var r;const e=Dh(t).service,s=Ch(t).service;return b.createMachine(w.CREATING,{[w.CREATING]:b.state(b.transition(A.CREATE,w.CREATED)),[w.CREATED]:b.state(b.immediate(w.INITIALIZING)),[w.INITIALIZING]:b.invoke(()=>(X(()=>{t.status=w.INITIALIZING}),t.init()),b.transition("done",w.INITIALIZED,b.action(()=>{t.status=w.INITIALIZED})),b.transition("error",w.FAILED,b.action(()=>{p.error(`Model ${t.modelId} - ${t.modelTypeName} failed to initialize. Transitioning to FAILED state.`),t.status=w.FAILED}))),[w.INITIALIZED]:b.state(b.immediate(w.LOADING)),[w.LOADING]:b.invoke(()=>(X(()=>{t.status=w.LOADING}),t.load()),b.transition("done",w.LOADED,b.action(()=>{t.status=w.LOADED})),b.transition("error",w.FAILED,b.action(()=>{t.status=w.FAILED}))),[w.LOADED]:b.state(b.immediate(w.READYING),b.transition(A.UNLOAD,w.UNLOADING)),[w.RESETTING]:b.invoke(()=>{var o;return X(()=>{t.status=w.RESETTING}),(o=t.unload)==null||o.call(t),t.load()},b.transition("done",w.LOADED,b.action(()=>{t.status=w.LOADED}))),[w.READYING]:b.invoke(()=>(X(()=>{t.status=w.READYING}),t.ready()),b.transition("done",w.READY,b.action(()=>{X(()=>{t.status=w.READY}),s.send(A.GO_ONLINE)})),b.transition("error",w.FAILED,b.action(()=>{t.status=w.FAILED}))),[w.READY]:b.state(b.transition(A.UNLOAD,w.UNLOADED,b.action((r=t.unload)==null?void 0:r.bind(t))),b.transition(A.RESET,w.RESETTING),b.transition(A.GO_ONLINE,w.READY,b.action(()=>{s.send(A.GO_ONLINE)})),b.transition(A.GO_OFFLINE,w.READY,b.action(()=>{s.send(A.GO_OFFLINE)})),b.transition(A.GO_ACTIVE,w.READY,b.action(()=>{e.send(A.GO_ACTIVE)})),b.transition(A.GO_INACTIVE,w.READY,b.action(()=>{e.send(A.GO_INACTIVE)}))),[w.UNLOADED]:b.state(),[w.FAILED]:b.state()})},Ah=p.createLogger({name:"kos-model-lifecycle"}),xh=t=>({service:b.interpret(Rh(t),s=>Ah.debug(`state machine for model ${t.modelId}: ${s.machine.current});`))});class Ph{constructor(e,s){l(this,"disposer");l(this,"service");this.model=e,this.log=s;const r=xh(e);this.service=r.service,this.service.send(A.CREATE)}get current(){return this.service.machine.current}async transitionTo(e,s,r=w.FAILED){return this.getTransitionStatusFor(s)===s?(this.log.debug(`Model ${this.model.modelId} already in state ${s}, skipping transition`),Promise.resolve()):(this.log.debug(`Transitioning model ${this.model.modelId} with event ${e} toward target ${s}`),new Promise((n,i)=>{var a;(a=this.disposer)==null||a.call(this),this.disposer=M.when(()=>{const c=this.getTransitionStatusFor(s);return c===s||c===r},()=>{this.getTransitionStatusFor(s)===r?(this.log.error(`Model ${this.model.modelId} entered error state ${r} during transition`),i(new Error(`FSM transition failed for model ${this.model.modelId} with event ${e}`))):(this.log.debug(`Model ${this.model.modelId} reached target state ${s}`),n())}),this.service.send(e)}).finally(()=>{var n;(n=this.disposer)==null||n.call(this),this.disposer=void 0}))}getTransitionStatusFor(e){return[w.ACTIVE,w.INACTIVE].includes(e)?this.model.activeStatus:[w.ONLINE,w.OFFLINE].includes(e)?this.model.onlineStatus:this.model.status}}const _a="browser-router-model";class So{constructor(e,s){l(this,"logger");l(this,"model");l(this,"router",null);l(this,"registered",!1);l(this,"registeredRoutes",[]);this.model=e,this.logger=s}registerAll(){var s;if(!ks(this.model))return;let e=this.model.__httpBrowserRouter;if(!e)for(const r of Object.keys(this.model)){const o=this.model[r];if(o&&typeof o=="object"&&"use"in o&&typeof o.use=="function"){e=o;break}}if(e||(e=(s=ve(_a))==null?void 0:s.model),!e)throw this.logger.error("Cannot register HTTP routes: BrowserRouter not found. The HTTP decorators should have auto-injected it, but something went wrong."),new Error("BrowserRouter is required for HTTP route decorators but was not found. This should not happen as HTTP decorators auto-inject the dependency.");this.setRouter(e)}setRouter(e){this.router=e,this.registered||this.registerRoutes()}hasRoutes(){return ks(this.model)}registerRoutes(){if(!this.router){this.logger.warn("Cannot register routes: router not set");return}if(this.registered){this.logger.debug("Routes already registered");return}const e=aa(this.model);e.length!==0&&(this.logger.debug(`Registering ${e.length} HTTP routes`),e.forEach(s=>{this.registerRoute(s)}),this.registered=!0)}resolvePropKey(e){const s=/\{PROP_([^}]+)\}/g;let r=e;if(r.includes("{MODEL_ID}")){const n=this.model.id||this.model._id||"unknown";r=r.replace(/\{MODEL_ID\}/g,n)}let o;for(;(o=s.exec(e))!==null;){const n=o[1];if(n in this.model){const i=this.model[n];r=r.replace(o[0],String(i))}else this.logger.warn(`Property '${n}' not found on model for PropKey resolution in path: ${e}`)}return r}registerRoute(e){if(!this.router)return;const s=this.model[e.handler];if(!s||typeof s!="function"){this.logger.error(`Handler method '${e.handler}' not found on model`);return}const r=this.resolvePropKey(e.path);this.logger.debug(`Registering ${e.method} ${r} -> ${e.handler}`+(r!==e.path?` (resolved from ${e.path})`:""));const o=async(n,i)=>{var a;try{await s.call(this.model,n,i)}catch(c){this.logger.error(`Error in route handler ${e.method} ${r}:`,c),(a=i.status)==null||a.call(i,500).send({error:"Internal server error",message:c instanceof Error?c.message:String(c)})}};this.checkForDuplicateRoute(e.method,r),this.router.use(e.method,r,o),this.registeredRoutes.push({method:e.method,path:r})}checkForDuplicateRoute(e,s){if(!this.router)return;this.router.getRoutes().find(n=>n.method===e&&n.path===s)&&this.logger.warn(`Duplicate route detected: ${e} ${s}. This route is already registered by another model. The new handler from model '${this.model.id||"unknown"}' will override the existing one. Only the last registered handler will receive requests. Consider using different paths or namespacing to avoid conflicts.`)}dispose(){if(this.router&&this.registeredRoutes.length>0){this.logger.debug(`Removing ${this.registeredRoutes.length} HTTP routes for model ${this.model.id||"unknown"}`);let e=0;for(const s of this.registeredRoutes){const r=this.router.remove(s.method,s.path);e+=r,r>0?this.logger.debug(`Removed route: ${s.method} ${s.path}`):this.logger.warn(`Failed to remove route: ${s.method} ${s.path} (not found)`)}this.logger.debug(`Successfully removed ${e} routes from browser router`)}this.registered=!1,this.registeredRoutes=[],this.router=null}getRegisteredRoutes(){return[...this.registeredRoutes]}}function Lh(t,e){if(!ks(t))return;const s=ve(_a);if(!(s!=null&&s.model))throw e.error("Cannot register HTTP routes: BrowserRouter not found. Make sure to include BrowserRouter in your model dependencies or create an instance."),new Error("BrowserRouter is required for HTTP route decorators but was not found. Add it as a dependency using @kosDependency or ensure an instance exists.");new So(t,e).setRouter(s.model)}class kh{static create({modelId:e,modelTypeName:s,component:r}){const o=[r??"kos",s,e].filter(Boolean).join(".");return p.createLogger({name:o})}}class Fh{constructor(e){l(this,"queue",[]);this.log=e}enqueue(e){this.queue.push(e)}flush(){if(this.queue.length!==0){this.log.warn(`Processing ${this.queue.length} offline message(s)`);for(const e of this.queue)try{e()}catch(s){this.log.error("Error while processing offline message:",s)}this.queue=[],this.log.info("Offline queue flushed")}}clear(){this.queue=[]}get length(){return this.queue.length}get isEmpty(){return this.queue.length===0}}class Nh{constructor(e,s){l(this,"unsubscribers",[]);this.model=e,this.log=s}register(){this.dispose();const e=this.model.modelId,s=O("/kosCore/online",async()=>{this.log.debug(`Online event received for ${e}, waiting for readiness...`),await this.model.whenReady(),this.log.debug(`${e} is ready — sending GO_ONLINE`),await this.model.fsm.transitionTo(A.GO_ONLINE,w.ONLINE)}),r=O("/kosCore/offline",async()=>{this.log.debug(`Offline event received for ${e} — sending GO_OFFLINE`),await this.model.fsm.transitionTo(A.GO_OFFLINE,w.OFFLINE)});this.unsubscribers.push(s.unsubscribe),this.unsubscribers.push(r.unsubscribe)}dispose(){this.unsubscribers.forEach(e=>e()),this.unsubscribers=[]}}class Uh{constructor(e){l(this,"subscription");l(this,"unsubscribe");l(this,"eventType");this.eventType=e,this.subscription={queue:[],resolvers:[],closed:!1};const s=O(e,r=>{if(!this.subscription.closed&&r!==void 0){const o=this.subscription.resolvers.shift();o?o(r):this.subscription.queue.push(r)}});this.unsubscribe=s.unsubscribe}async next(){return this.subscription.closed&&this.subscription.queue.length===0?{done:!0,value:void 0}:this.subscription.queue.length>0?{done:!1,value:this.subscription.queue.shift()}:new Promise(e=>{this.subscription.closed?e({done:!0,value:void 0}):this.subscription.resolvers.push(s=>{e({done:!1,value:s})})})}async return(){return this.subscription.closed=!0,this.unsubscribe(),this.subscription.resolvers.forEach(e=>{e(void 0)}),this.subscription.resolvers=[],{done:!0,value:void 0}}async throw(e){throw this.subscription.closed=!0,this.unsubscribe(),e}[Symbol.asyncIterator](){return this}}function $n(t){return new Uh(t)}var Ia=(t=>(t.GET="GET",t.PUT="PUT",t.POST="POST",t.DELETE="DELETE",t))(Ia||{});const Sa=({path:t,requestId:e,method:s,destinationAddress:r})=>{let o=`${cr}:${s}
1
+ "use strict";var fu=Object.defineProperty;var gu=(t,e,s)=>e in t?fu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var l=(t,e,s)=>(gu(t,typeof e!="symbol"?e+"":e,s),s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const $=require("loglevel"),M=require("mobx"),b=require("robot3"),Re=require("date-fns"),T=require("@emotion/react/jsx-runtime"),go=require("@emotion/styled"),ii=require("react-dom"),je=require("@emotion/react"),f=require("react"),po=require("mobx-react-lite"),pu=require("@use-gesture/react"),cr="method",ai="topic",pt="url",os="request-id",lr="response-id",mo="status",$e="dst-addr",ci="src-addr",Me="type",yo="ordered",bo="tracker",li="Content-Type",di="Cache-Control",ui="requestId",hi=process.env.KOS_LOGIN_URL||"http://localhost",fi=process.env.KOS_APP_PORT||"8080",mu=`${hi}:${fi}`,xs="{MODEL_ID}";var ns=(t=>(t.SEND="/ws/log/msg/send",t.RECEIVED="/ws/log/msg/receive",t))(ns||{}),gi=(t=>(t.MSG_RECEIVE="/mock/msg/receive",t))(gi||{});const wo="/kos/model/ready/";$.info("Initializing event bus");globalThis.kos=globalThis.kos||{};globalThis.kos.subscriptions=globalThis.kos.subscriptions||{};const K=globalThis.kos.subscriptions,yu=()=>Symbol("eventKey");function vo(t){return K[t]&&Object.getOwnPropertySymbols(K[t]).length>0}function O(t,e){const s=yu();return K[t]||($.debug(`Initializing subscription for ${t}`),K[t]={}),$.debug(`Subscribing to ${t} with id ${s.toString()}`),K[t][s]=e,{count:K[t]?Object.getOwnPropertySymbols(K[t]).length:0,unsubscribe:()=>($.debug(`Unsubscribing from ${t} with id ${s.toString()}`),K[t]&&K[t][s]&&delete K[t][s],K[t]&&Object.getOwnPropertySymbols(K[t]).length===0&&delete K[t],{count:K[t]?Object.getOwnPropertySymbols(K[t]).length:0})}}function j(t,e,s={}){if(!K[t]||Object.getOwnPropertySymbols(K[t]).length===0)return $.debug(`No subscriptions for ${t}. Not publishing.`),{eventType:t,subscribers:0};const r=Object.getOwnPropertySymbols(K[t]).length;return Object.getOwnPropertySymbols(K[t]).forEach(o=>{if(s.sync){const n=s.sync;$.debug(`Performing sync publish for ${t} with sync id ${n}`),K[t][o]({body:e,headers:s}).then(i=>{$.debug(`Response recieved for ${n}, publishing back to source.`),j(n,i)})}else $.debug(`Performing async publish for ${t}`),K[t][o]({body:e,headers:s})}),{eventType:t,subscribers:r}}function bu(){$.warn("Resetting event bus"),Object.keys(K).forEach(t=>delete K[t])}function pi(t,e){const s=O(t,r=>{s.unsubscribe(),e(r)});return s.unsubscribe}function Mo(t,e){return new Promise((s,r)=>{let o=null;const n=pi(t,i=>{o&&clearTimeout(o),s(i)});e&&(o=setTimeout(()=>{n(),r(new Error(`Timeout waiting for event: ${t}`))},e))})}const wu=Object.freeze(Object.defineProperty({__proto__:null,hasEventSubscriptions:vo,once:pi,publish:j,reset:bu,subscribe:O,waitFor:Mo},Symbol.toStringTag,{value:"Module"}));function dr(t,e){const s=O(t,r=>{s.unsubscribe(),e(r)});return s.unsubscribe}function ur(t,e){return new Promise((s,r)=>{let o=null;const n=dr(t,i=>{o&&clearTimeout(o),s(i)});e&&(o=setTimeout(()=>{n(),r(new Error(`Timeout waiting for event: ${t}`))},e))})}function mi(t,e){const s=t.map(r=>ur(r,e));return Promise.all(s)}function yi(t,e){return new Promise((s,r)=>{const o=[];let n=null,i=!1;const a=()=>{o.forEach(c=>c()),n&&clearTimeout(n)};t.forEach(c=>{const d=dr(c,u=>{i||(i=!0,a(),s({eventType:c,data:u}))});o.push(d)}),e&&(n=setTimeout(()=>{i||(i=!0,a(),r(new Error(`Timeout waiting for any event: ${t.join(", ")}`)))},e))})}function bi(t,e,s){return O(t,o=>{o&&e(o)&&s(o)}).unsubscribe}function wi(t,e,s){return O(t,o=>{if(o){const n=e(o);s(n)}}).unsubscribe}function vi(t,e,s){let r=null;const o=O(t,n=>{r&&clearTimeout(r),r=setTimeout(()=>{s(n)},e)});return()=>{r&&clearTimeout(r),o.unsubscribe()}}function Mi(t,e,s){let r=0,o=null;const n=O(t,i=>{const a=Date.now(),c=a-r;c>=e?(r=a,s(i)):o||(o=setTimeout(()=>{r=Date.now(),s(i),o=null},e-c))});return()=>{o&&clearTimeout(o),n.unsubscribe()}}function Ei(t,e,s){let r=[],o=null;const n=()=>{r.length>0&&(s([...r]),r=[])},i=O(t,a=>{a&&(r.push(a),o||(o=setTimeout(()=>{n(),o=null},e)))});return()=>{o&&(clearTimeout(o),n()),i.unsubscribe()}}function Eo(t,e=1){const s=[];return O(t,r=>{r&&(s.push(r),s.length>e&&s.shift())}),{subscribe:r=>(s.forEach(o=>r(o)),O(t,r))}}function Ti(t,e){const s=t.map(r=>O(r,o=>{o&&e(r,o)}));return()=>{s.forEach(r=>r.unsubscribe())}}function _i(t,e){let s=t;const r=[],o=new Set;return Object.values(e).forEach(n=>{Object.keys(n).forEach(i=>{o.add(i)})}),o.forEach(n=>{const{unsubscribe:i}=O(n,a=>{const c=e[s];c&&c[n]&&(s=c[n](a))});r.push(i)}),{get state(){return s},unsubscribe:()=>{r.forEach(n=>n())}}}function Ii(t,e,s,r){const o=ur(e,r);return j(t,s),o}async function*Si(t){const e=[],s=[],r=O(t,o=>{o&&(s.length>0?s.shift()(o):e.push(o))});try{for(;;)e.length>0?yield e.shift():yield await new Promise(o=>{s.push(o)})}finally{r.unsubscribe()}}const vu={once:dr,waitFor:ur,waitForAll:mi,race:yi,filter:bi,map:wi,debounce:vi,throttle:Mi,buffer:Ei,replay:Eo,merge:Ti,stateMachine:_i,request:Ii,eventIterator:Si},Mu=Object.freeze(Object.defineProperty({__proto__:null,EventBusFunctional:vu,buffer:Ei,debounce:vi,eventIterator:Si,filter:bi,map:wi,merge:Ti,once:dr,race:yi,replay:Eo,request:Ii,stateMachine:_i,throttle:Mi,waitFor:ur,waitForAll:mi},Symbol.toStringTag,{value:"Module"}));async function hr(t,e){const{getCurrentState:s,transformState:r,shouldUseFetchedState:o,timeout:n}=e,i=Mo(t,n),a=await s(),c=r?r(a):a;return o&&o(c)?(i.catch(()=>{}),c):await Promise.race([i,new Promise(u=>{setTimeout(()=>u(c),100)})])}function Oi(t,e,s){const{getCurrentState:r,transformState:o}=s;let n=!1;const i=O(t,a=>{a&&(n=!0,e(a))});return Promise.resolve(r()).then(a=>{const c=o?o(a):a;n||e(c)}).catch(a=>{console.error("Failed to fetch initial state:",a)}),i.unsubscribe}function $i(t,e){let s;const r=new Set,o=async()=>{try{typeof e=="string"?s=await(await fetch(e)).json():s=await e(),r.forEach(a=>a(s))}catch(a){throw console.error("Failed to fetch initial state:",a),a}};O(t,a=>{a!=null&&a.body&&(s=a.body,r.forEach(c=>c(s)))});let n=!1;const i=()=>{n||(n=!0,o())};return{get state(){return s},async getState(){return i(),s===void 0&&await new Promise(a=>{const c=()=>{s!==void 0?a():setTimeout(c,10)};c()}),s},subscribe(a){return i(),r.add(a),s!==void 0&&a(s),()=>{r.delete(a)}},async refresh(){return await o(),s}}}async function To(t,e){if(typeof t=="string")return hr(t,e);const s=t,{getCurrentState:r,shouldUseFetchedState:o,timeout:n}=e,i=await r(),a=e.transformState?e.transformState(i):i;if(o&&o(a))return a;const c=s.map(u=>Mo(u,n)),d=await Promise.all(c);return d[d.length-1]}function Di(t,e,s){const{fetchMissedEvents:r,checkInterval:o=3e4,deduplicateById:n}=s,i=new Set,a=O(t,async d=>{if(d){if(n){const u=n(d);if(i.has(u))return;i.add(u),i.size>1e3&&Array.from(i).slice(0,500).forEach(g=>i.delete(g))}await e(d)}}),c=setInterval(async()=>{try{const d=await r(),u=Array.isArray(d)?d:[d];for(const h of u)if(n){const g=n(h);i.has(g)||(i.add(g),await e(h))}else await e(h)}catch(d){console.error("Failed to fetch missed events:",d)}},o);return()=>{a.unsubscribe(),clearInterval(c)}}function Ci(t){const{connectEvent:e,disconnectEvent:s,errorEvent:r,dataEvent:o,fetchInitialState:n,reconnectDelay:i=5e3}=t,a={state:"disconnected",data:void 0,async waitForConnection(u){if(a.state==="connected"&&a.data)return a.data;const h=await hr(e,{getCurrentState:n,shouldUseFetchedState:g=>!!g,timeout:u});return a.state="connected",a.data=h,d(),h},subscribe(u){return c.add(u),u(a),()=>{c.delete(u)}},async reconnect(){a.state="connecting",d();try{const u=await n();a.state="connected",a.data=u,d()}catch{a.state="error",d(),setTimeout(()=>{a.state==="error"&&a.reconnect()},i)}}},c=new Set,d=()=>{c.forEach(u=>u(a))};return O(e,u=>{a.state="connected",u!=null&&u.body&&(a.data=u.body),d()}),O(s,()=>{a.state="disconnected",d(),setTimeout(()=>{a.state==="disconnected"&&a.reconnect()},i)}),r&&O(r,()=>{a.state="error",d()}),o&&O(o,u=>{u!=null&&u.body&&a.state==="connected"&&(a.data=u.body,d())}),a.reconnect(),a}const Eu={waitForOrGetState:hr,subscribeWithInitialState:Oi,createStatefulEventStream:$i,waitForAllWithState:To,createResilientEventHandler:Di,createConnectionStateManager:Ci},Tu=Object.freeze(Object.defineProperty({__proto__:null,EventBusState:Eu,createConnectionStateManager:Ci,createResilientEventHandler:Di,createStatefulEventStream:$i,subscribeWithInitialState:Oi,waitForAllWithState:To,waitForOrGetState:hr},Symbol.toStringTag,{value:"Module"})),_u=(t,e=0)=>{if(!+t)return{value:0,scale:"bytes",toString:()=>"0 bytes"};const s=1024,r=e<0?0:e,o=["bytes","KB","MB","GB","TB"],n=Math.floor(Math.log(t)/Math.log(s)),i=parseFloat((t/Math.pow(s,n)).toFixed(r)),a=o[n];return{value:i,scale:a,toString:()=>`${i} ${a}`}};function _o(t){let e="pending",s;const r=t.then(n=>{e="success",s=n},n=>{e="error",s=n});return{read:()=>{switch(e){case"pending":throw r;case"error":throw s;default:return s}}}}function mt(){return"xxxxxxxx-xxxx-4xxx-2xxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=Math.random()*16|0;return(t=="x"?e:e&3|8).toString(16)})}function Iu(t,e){e.forEach(s=>{Object.getOwnPropertyNames(s.prototype).forEach(r=>{const o=Object.getOwnPropertyDescriptor(s.prototype,r);Object.defineProperty(t.prototype,r,o)})})}function Su(t,e){const s=t??[],r=e??[];return s.length!==r.length?!1:s.every((o,n)=>o===r[n])}const Io=(t,e)=>{const s=t.map(n=>n.id);return e.map(n=>n.id).filter(n=>!s.includes(n))},Ou=({container:t,onAddItem:e,onRemoveItem:s,idMapper:r=o=>o})=>o=>{const n=o.map(r),a=Io(n,t.data).map(s).filter(Boolean);t.removeAll(a);const c=n.map(e).filter(Boolean);t.addAll(c)},$u=({container:t,onAddItem:e,onRemoveItem:s,idMapper:r=o=>o})=>o=>{const n=o.map(r);Io(n,t.models).forEach(s),n.forEach(e)},Du=({items:t,onAddItem:e,onRemoveItem:s,idMapper:r=o=>o})=>o=>{const n=o.map(r);Io(n,t).forEach(s),n.forEach(e)},Cu=(t,e="parent-")=>{let s=t;return s.startsWith(e)&&(s=s.replace(e,"")),s},On=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"}),$n=[{amount:60,name:"seconds"},{amount:60,name:"minutes"},{amount:24,name:"hours"},{amount:7,name:"days"},{amount:4.34524,name:"weeks"},{amount:12,name:"months"},{amount:Number.POSITIVE_INFINITY,name:"years"}];function Ri(t){let e=(t.getTime()-Date.now())/1e3;for(let s=0;s<=$n.length;s++){const r=$n[s];if(Math.abs(e)<r.amount)return On.format(Math.round(e),r.name);e/=r.amount}return On.format(Math.round(e),"years")}const So=t=>t%4===0&&t%100!==0||t%400===0,Oo=(t,e)=>[31,So(t)?29:28,31,30,31,30,31,31,30,31,30,31][e],Ai=(t,e)=>{const s=new Date(t),r=t.getDate();return s.setDate(1),s.setMonth(s.getMonth()+e),s.setDate(Math.min(r,Oo(s.getFullYear(),s.getMonth()))),s},xi=(t,e)=>{const s=new Date(t);return s.setDate(s.getDate()+e),s},rt="en-US",Pi={short:{year:"numeric",month:"2-digit",day:"2-digit"},medium:{year:"numeric",month:"short",day:"2-digit"},long:{year:"numeric",month:"long",day:"numeric"},full:{year:"numeric",month:"long",day:"numeric",weekday:"long"}},Li={short:{hour:"2-digit",minute:"2-digit",hour12:!0},medium:{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!0},long:{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!0,timeZoneName:"short"},full:{hour:"2-digit",minute:"2-digit",hour12:!0,timeZoneName:"long"}},ki=(t,{dateStyle:e="short",locales:s=rt}={dateStyle:"short",locales:rt})=>{const r=e==="short"?Pi.short:{dateStyle:e};return new Intl.DateTimeFormat(s,r).format(t)},Fi=(t,{locales:e=rt,timeStyle:s="short"}={locales:rt,timeStyle:"short"})=>{const r=Li[s];return new Intl.DateTimeFormat(e,r).format(t)},Ni=(t,{dateStyle:e="short",locales:s=rt,timeStyle:r="short"}={dateStyle:"short",locales:rt,timeStyle:"short"})=>{const o={...e&&Pi[e],...r&&Li[r]};return new Intl.DateTimeFormat(s,o).format(t)},Ru=Object.freeze(Object.defineProperty({__proto__:null,addDaysToDate:xi,addMonthsToDate:Ai,formatDate:ki,formatDateSince:Ri,formatDateTime:Ni,formatTime:Fi,getDaysInMonth:Oo,isLeapYear:So},Symbol.toStringTag,{value:"Module"}));function Ui(t,e,s=300){let r;return(...o)=>{clearTimeout(r),r=setTimeout(()=>{e.apply(t,o)},s)}}const Q="canvas-renderer",Or=new Map,Dn=new Map,$r=new Map,Dr=new Map,is=(t,e)=>{ji[t]=e},ji={indexExtension:{registerIndexExtension:(t,e)=>{const s=Dr.get(t)||{};Object.assign(s,e),Dr.set(t,e)},loadIndexExtensions:t=>Dr.get(t)||{}},loader:{registerLoader:(t,e)=>{Dn.set(t,e)},executeLoader:async(t,e)=>{const s=Dn.get(t);if(s)return await s(e)}},propertyMapper:{registerPropertyMapper:(t,e)=>{$r.set(t,e)},hasMapper:t=>$r.has(t),executeMapper:(t,e,s)=>{const r=$r.get(t);return r?r(e,s):""}},dataMapper:{registerDataMapper:(t,e)=>{const s=Or.get(t)||[];s.push(e),Or.set(t,s)},executeMapper:async(t,e,s)=>{const r=Or.get(t);if(!r)return{};const o={};for(const n of r){const i=await n(e,s);Object.assign(o,i)}return o}},canvas:{registerRenderer:(t,e)=>{if(!S[Q]){console.warn(`Canvas renderer extension point is not registered. Cannot register renderer "${t}".`);return}S[Q].register(t,e)}}},S=ji,Au=async({context:t,extension:e})=>{const s=await S.loader.executeLoader(e,{});return t==null||t.set(e,s),s},xu=async({extension:t,contextData:e,data:s})=>await S.dataMapper.executeMapper(t,s,e),Pu=async({extension:t,contextData:e,data:s})=>await S.propertyMapper.executeMapper(t,s,e),Lu=Object.freeze(Object.defineProperty({__proto__:null,executeDataMapperExtension:xu,executeLoaderExtension:Au,executePropertyMapperExtension:Pu},Symbol.toStringTag,{value:"Module"})),ku="Extensions";class Fu{constructor(){l(this,"extensions");this.extensions={}}register(e,s,r){this.extensions[e]={},this.extensions[e][s]={component:r}}get(e,s){if(!this.extensions[e])throw new Error(`Extension point ${e} not found`);return this.extensions[e][s]}get allExtensions(){return this.extensions}}const ue=(t=null)=>(t||window.location.search.replace("?","")).split("&").map(e=>{const[s,r]=e.split("=");return[s,decodeURIComponent(r||"")]}).reduce((e,[s,r])=>(e[s]=r,e),{}),Bi="studio.tools.preview",Nu="studio.relax.store.validation",Ki="studio.log.debug",Hi="studio.log.info",Uu={profiles:[Bi]};var ni;const ju=((ni=globalThis.getKosConfig)==null?void 0:ni.call(globalThis))||JSON.stringify(Uu),zi=JSON.parse(ju);globalThis.kosConfig=zi;const $o=zi,Gi=()=>$o.profiles||[],zr=t=>Gi().includes(t),Bu=()=>$o.logging||!1,Ku=()=>{const t=zr(Ki),e=zr(Hi);return t?"DEBUG":e?"INFO":void 0},Vi=()=>{const t=ue(),e=Ku(),r=t.kosLogLevel??e??window.kosLogLevel??process.env.KOS_LOG_LEVEL;return r||"WARN"},Yi=()=>window.kosMessageLogging||process.env.KOS_MESSAGE_LOGGING==="true",qi=()=>window.kosMessageStudioLogging||process.env.KOS_MESSAGE_STUDIO_LOGGING==="true",Wi="ws-log",Hu=$.methodFactory,Qi=Yi(),zu=qi();$.methodFactory=function(t,e,s){const r=Hu(t,e,s);return function(o,n){var c;const i=s?String(s):"",a=i?`[${String(i).substring(i.lastIndexOf(":")+1)}] | `:"[root] | ";r(`${a}${o}`,n||""),(c=globalThis==null?void 0:globalThis.kosConfig)!=null&&c.logging&&globalThis.kosLog&&(s!==Wi||Qi&&zu)&&globalThis.kosLog(`UI: ${a}${o}`)}};let Zi=Vi();$.setLevel(Zi);window.setKosLogLevel=t=>{Zi=t,$.setLevel(t)};const Ps=$.getLogger(Wi);window.enableKosMessageLog=()=>{Ps.setLevel($.levels.INFO)};window.disableKosMessageLog=()=>{Ps.setLevel($.levels.ERROR)};Qi?window.enableKosMessageLog():window.disableKosMessageLog();const Gu=["color: black","display: block","background-color: lightgreen","padding: 4px","margin: 0","text-shadow: 0 1px 0 rgba(0, 0, 0, 0.3)","box-shadow: 0 1px 0 rgba(255, 255, 255, 0.4) inset, 0 5px 3px -5px rgba(0, 0, 0, 0.5), 0 -13px 5px -10px rgba(255, 255, 255, 0.4) inset","font-weight: bold"].join(";"),Vu=["color: black","display: block","padding: 4px","background-color: yellow","margin: 0","text-shadow: 0 1px 0 rgba(0, 0, 0, 0.3)","box-shadow: 0 1px 0 rgba(255, 255, 255, 0.4) inset, 0 5px 3px -5px rgba(0, 0, 0, 0.5), 0 -13px 5px -10px rgba(255, 255, 255, 0.4) inset","font-weight: bold"].join(";"),ps=t=>e=>{$.getLevel()<=t&&e()},p={...$,ifDebug:ps($.levels.DEBUG),ifInfo:ps($.levels.INFO),ifWarn:ps($.levels.WARN),ifError:ps($.levels.ERROR),getLogger:t=>$.getLogger(`kos::${t}`),getLoggers:()=>$.getLoggers(),createLogger:({name:t,group:e})=>{var n,i,a,c;const s=`${e?`${e}:`:"kos"}::${t}`,r=$.getLogger(s);let o=(i=(n=globalThis.kos.logOverrides)==null?void 0:n.find(d=>d.name===s))==null?void 0:i.level;return o?r.setLevel(o):(o=(c=(a=globalThis.kos.logOverrides)==null?void 0:a.find(d=>s.startsWith(d.name)))==null?void 0:c.level,o&&r.setLevel(o)),r},wsSend:(...t)=>{const e=String(t).replace(/\n/g,"\\n");Ps.info(`%c⬆ ${e}`,Gu)},wsReceive:(...t)=>{const e=String(t).replace(/\n/g,"\\n");Ps.info(`%c⬇ ${e}`,Vu)}},Xi="featureFlagResolver",ms=new Map;is(Xi,{register:(t,e)=>{var s;ms.has(t)||ms.set(t,[]),(s=ms.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=ms.get(t);if(!s)return[];const r=s.map(a=>a(e)),n=(await Promise.allSettled(r)).map(a=>a.status==="fulfilled"?a.value:(p.info(`Feature flag resolver ${t} failed: ${a.reason}`),[])).flat(),i=Array.from(new Set(n)).reduce((a,c)=>(a[c]=!0,a),{});return ea.updateFlags(i),Object.keys(i)}});const Yu="kos.loader.featureFlag";class Ji{constructor(e={}){l(this,"flags",{});this.flags=e}isFeatureEnabled(e){return!!this.flags[e]}enableFeature(e){this.flags[e]=!0}disableFeature(e){this.flags[e]=!1}toggleFeature(e){this.flags[e]=!this.flags[e]}updateFlags(e){this.flags={...this.flags,...e}}}window.KosFeatureFlags=window.KosFeatureFlags??new Ji;const ea=window.KosFeatureFlags,ta=(t,e,s)=>{s/=100;const r=e*Math.min(s,1-s)/100,o=n=>{const i=(n+t/30)%12,a=s-r*Math.max(Math.min(i-3,9-i,1),-1);return Math.round(255*a).toString(16).padStart(2,"0")};return`#${o(0)}${o(8)}${o(4)}`},sa=t=>{const s=new RegExp("hsl\\((\\d+),\\s+(\\d+)\\%,\\s+(\\d+)\\%\\)").exec(t);if(!s)throw Error("Invalid HSL string");return ta(parseInt(s[1]),parseInt(s[2]),parseInt(s[3]))},ra=(t,e)=>getComputedStyle(t).getPropertyValue(e),qu=(t,e)=>sa(ra(t,e)),Wu=(t,e)=>{const s={...t};return s.id&&delete s.id,s},Gr=(t,e,s=Wu)=>{const r=s(t,e);M.runInAction(()=>{Object.assign(e,r)})},Cr=new Map,oa={addToDeletionQueue:(t,e)=>{const s=Cr.get(t)||[];s.push(e),Cr.set(t,s)},cancelDeletion:t=>{const e=Cr.get(t);e&&e.forEach(s=>{clearTimeout(s)})}},Qu=p.createLogger({name:"kos-dependency-manager"});class Zu{constructor(){l(this,"_usedByCache",new Map);l(this,"_usesCache",new Map)}add(e,s){oa.cancelDeletion(s);const r=this._usedByCache.get(s)||[];r.includes(e)||r.push(e),this._usedByCache.set(s,r);const o=this._usesCache.get(e)||[];o.includes(s)||o.push(s),this._usesCache.set(e,o)}remove(e,s){const r=this._usedByCache.get(s)||[];this._usedByCache.set(s,r.filter(n=>n!==e));const o=this._usesCache.get(e)||[];this._usesCache.set(e,o.filter(n=>n!==s))}canDestroy(e){const s=this._usedByCache.get(e);return s!=null&&s.length?(Qu.info(`Model ${e} is still used by: ${s.join(", ")}`),!1):!0}clear(){this._usedByCache.clear(),this._usesCache.clear()}}var w=(t=>(t.CREATING="creating",t.CREATED="created",t.INITIALIZING="initializing",t.INITIALIZED="initialized",t.LOADING="loading",t.LOADED="loaded",t.ONLINE="online",t.READYING="readying",t.READY="ready",t.READY_FAILED="ready_failed",t.RESETTING="resetting",t.RESET="reset",t.OFFLINE="offline",t.UNLOADING="unloading",t.UNLOADED="unloaded",t.FAILED="failed",t.INACTIVE="inactive",t.ACTIVE="active",t.ACTIVATING="activating",t.DEACTIVATING="deactivating",t))(w||{}),A=(t=>(t.CREATE="create",t.INITIALIZE="init",t.LOAD="load",t.READY="ready",t.GO_ONLINE="go_online",t.GO_OFFLINE="go_offline",t.RESET="go_offline",t.UNLOAD="unload",t.FAILED="failed",t.GO_ACTIVE="go_active",t.GO_INACTIVE="go_inactive",t.TIMEOUT="timeout",t))(A||{});const Cn=p.createLogger({name:"kos-model-cache"});class Xu{constructor(e=[]){l(this,"_modelsById",M.observable.map(new Map));l(this,"_toDelete",new Map);l(this,"_preloaded",[]);l(this,"_isPreloaded",!1);this.preloadKeys=e}get models(){return Array.from(this._modelsById.values()).map(e=>e).filter(e=>!this._toDelete.has(e.modelId))}getModelById(e){if(e&&!this._toDelete.has(e))return this._modelsById.get(e)}addModel(e){const s=this.getModelById(e.modelId)||e;return this._modelsById.set(s.modelId,s),s}removeModel(e){this._modelsById.delete(e),this._toDelete.delete(e)}hasModel(e){return!!e&&this._modelsById.has(e)&&!this._toDelete.has(e)}restoreFromDeleteCache(e){if(e&&this._toDelete.has(e)){const s=this._toDelete.get(e);this._toDelete.delete(e),this._modelsById.set(e,s)}}markForDeletion(e){this._modelsById.delete(e.modelId),this._toDelete.set(e.modelId,e)}preload(e){return this._isPreloaded?(Cn.debug("Returning cached preloaded models"),this._preloaded):(this._preloaded=this.preloadKeys.map(s=>(Cn.debug(`Preloading model: ${typeof s=="string"?s:s.modelType}`),e(s))).filter(s=>!!s),this._isPreloaded=!0,this._preloaded)}}const J=Symbol("SubscriptionHandlers"),F=Symbol("DependencyModels"),Nt=Symbol("FutureService"),Ut=Symbol("ChildModels"),jt=Symbol("ParentModel"),Bt=Symbol("LogConfig"),Os=Symbol("ReferenceConfig"),na=Symbol("KosModelSymbol"),Ke=Symbol("ModelEffects"),Ls=Symbol("CompanionParentModel"),be=(t,e)=>{t[Ut]=t[Ut]||{},t[Ut][e]=!0},Ge=t=>`{PROP_${String(t)}}`,Ju=t=>`{PROP_${String(t)}}`,eh=Ge("kosParentId"),fr=t=>e=>{e[jt]=e[jt]||{};const s=(t==null?void 0:t.parentId)||eh;e[jt]={parentId:s}},ot=({value:t,modelId:e,modelData:s})=>{let r=t;if(Array.isArray(r))return[...t];if(typeof r!="string"&&typeof r!="object")return r;if(typeof r=="object")r=Object.keys(r).reduce((o,n)=>(o[n]=ot({value:r[n],modelId:e,modelData:s}),o),{});else if(typeof r=="string"){const o=new RegExp(".*({PROP_(.+)})");let n=r!=null&&r.includes(xs)?r.replace(xs,e):r;const i=n.match(o);if(i&&s&&(Object.getOwnPropertyNames(s).includes(i[2])||Object.getOwnPropertyNames(Object.getPrototypeOf(s)).includes(i[2]))){const a=s[i[2]];n=a?n.replace(i[1],a):void 0}return n}else return r;return r},th=p.createLogger({group:"decorators",name:"kos-model"});function sh(t,e,s){var n;const r=(n=t[jt])==null?void 0:n.parentId;if(!r)return;const o=ot({value:r,modelData:s,modelId:e});o&&typeof o=="string"&&z.setParentContext(e,o)}function rh(t){const e=t[Nt];e&&Object.entries(e).forEach(([s,{handler:r}])=>{t[s]=r})}function oh(t,e){const s=t[F]||{};Object.entries(s).forEach(([r,o])=>{const n=ot({value:o.id||o.modelType,modelData:t,modelId:e}),i=Object.entries((o==null?void 0:o.options)||{}).reduce((a,[c,d])=>(a[c]=ot({value:d,modelData:t,modelId:e}),a),{});if(typeof n=="string"){if(!o.lazy){const a=I.getInstance().modelManager.createModelInstance(o.modelType,n,i);t[r]=a.data}I.getInstance().modelManager.addDependency(e,n)}})}function nh(t){try{return M.makeAutoObservable(t)}catch(e){return th.error("Failed to make observable:",e),t}}const ih={construct(t,e){var a;const[s,r={}]=e,o=z.createContext(s);sh(t,s,r);const n=p.createLogger({name:t.prototype.modelTypeId,group:((a=t[Bt])==null?void 0:a.group)??"kos-model"}),i=new t(s,r,{logger:n,kosContext:o});return rh(i),oh(i,s),nh(i)}};function R(t){return e=>{var r,o;const s=e;return s.prototype.modelTypeId=t,s.prototype[na]=!0,(r=s.prototype)[J]??(r[J]={}),(o=s.prototype)[F]??(o[F]={}),p.ifDebug(()=>{p.debug(`Registering model with id ${t}`)}),new Proxy(s,ih)}}const ah=({modelType:t})=>e=>{fr()(e),R(t)(e)};function ch(t,e,s){const r=s.value;s.value=function(...o){const n=z.getContext(this.id);return o.push(n),r.apply(this,o)}}var H=(t=>(t.INIT="init",t.LOAD="load",t.READY="ready",t.ACTIVATE="activate",t.ONLINE="online",t))(H||{});const lh=Object.freeze(Object.defineProperty({__proto__:null,DependencyLifecycle:H},Symbol.toStringTag,{value:"Module"})),Ie=Symbol("HttpRouteHandlers"),Rn="__httpBrowserRouter";function gr(t){return function(s){return function(r,o,n){r[Ie]=r[Ie]||[];const i={method:t,path:s,handler:o};return r[Ie].push(i),r[F]=r[F]||{},r[F][Rn]||(r[F][Rn]={modelType:"browser-router-model",lifecycle:H.INIT}),n}}}const ia=gr("GET"),as=gr("POST"),dh=gr("PUT"),aa=gr("DELETE"),uh=aa;function ks(t){return!!(t!=null&&t[Ie])&&t[Ie].length>0}function ca(t){return(t==null?void 0:t[Ie])||[]}const hh=({group:t}={group:""})=>e=>{e[Bt]=e[Bt]||{},e[Bt]={group:t}};function la(t){return(e,s,r)=>{e[Ke]=e[Ke]||{},e[Ke][s]={dependencies:t==null?void 0:t.dependencies,value:r.value},r.value=function(){throw new Error(`Method ${s} cannot be called directly.`)}}}const fh=t=>(e,s)=>{e[Os]=e[Os]||{},e[Os][s]=t},yt=({modelType:t,id:e,options:s,lifecycle:r})=>(o,n)=>{o[F]=o[F]||{},o[F][n]={modelType:t,id:e,options:s,lifecycle:r||H.INIT}},gh=({topic:t,handler:e,websocket:s=!1,condition:r=()=>!0})=>o=>{o[J]=o[J]||{},Array.isArray(t)?t.forEach(n=>{o[J][n]={websocket:s,handler:e,condition:r}}):o[J][t]={websocket:s,handler:Ui(o,M.action(e),200),condition:r}};function da(t,e,s){const r={};if(!t.endsWith("/*"))return r;const o=t.slice(0,-2);if(e.startsWith(o)){const n=e.slice(o.length+1),i=s||"path";r[i]=n}return r}function ua(t){return t.endsWith("/*")}function U({topic:t,condition:e=(_,N)=>!0,transform:s=_=>_,websocket:r=!1,fos:o=!1,bridge:n=!1,skipParse:i=!1,lifecycle:a,destinationAddress:c,debounce:d,throttle:u,buffer:h,filter:g,once:m,replay:y,wildcardName:v,flow:E}){return(_,N,x)=>{_[J]=_[J]||{};let P=x.value;const W=typeof d=="number"?d:d==null?void 0:d.delay,re=typeof u=="number"?u:u==null?void 0:u.interval;W&&W>0?P=ph(P,d):re&&re>0?P=mh(P,u):h?P=yh(P,h):m&&(P=bh(P));let L=e;if(g){const V=e;L=(ce,gs,Tt)=>g(Tt)?V(ce,gs,Tt):!1}const Ce={websocket:r,fos:o,bridge:n,handler:P,condition:L,transform:s,lifecycle:a,skipParse:i,destinationAddress:c,wildcardName:v,flow:E};Array.isArray(t)?t.forEach(V=>{_[J][V]=Ce}):_[J][t]=Ce,y&&wh(t,y.bufferSize)}}function ph(t,e){const s=typeof e=="number"?e:e.delay,r=typeof e=="object"?e.discardIntermediate:!1;let o=null,n=[];return function(i){r?(o&&clearTimeout(o),o=setTimeout(()=>{t.call(this,i),o=null},s)):(n.push(i),o&&clearTimeout(o),o=setTimeout(()=>{const a=[...n];n=[],t.call(this,a),o=null},s))}}function mh(t,e){const s=typeof e=="number"?e:e.interval,r=typeof e=="object"?e.discardIntermediate:!1;let o=0,n=null,i=[],a=!1;const c=function(){if(i.length>0){const d=[...i];i=[],t.call(this,d)}};return function(d){const u=Date.now(),h=u-o;r?h>=s?(o=u,t.call(this,d)):n||(n=setTimeout(()=>{o=Date.now(),t.call(this,d),n=null},s-h)):(i.push(d),h>=s?(o=u,c.call(this)):a||(a=!0,n=setTimeout(()=>{o=Date.now(),c.call(this),n=null,a=!1},s-h)))}}function yh(t,e){const s=[];let r=null;const o=e.maxSize||1e3,n=i=>{s.length>0&&(t.call(i,[...s]),s.length=0)};return function(i){if(s.push(i),s.length>=o){r&&(clearTimeout(r),r=null),n(this);return}r||(r=setTimeout(()=>{n(this),r=null},e.time))}}function bh(t){let e=!1;return function(s){e||(e=!0,t.call(this,s))}}function wh(t,e){(Array.isArray(t)?t:[t]).forEach(r=>{Eo(r,e)})}function ha(t,e){return`${wo}${t}${e?`/${e}`:`/${t}`}`}function fa(t){return`${wo}${t}`}function Rr(t){const e=[];return new Promise((s,r)=>{for(const{condition:o,onMatch:n}of t){const i=M.when(o,()=>{e.forEach(a=>a());try{n==null||n(),s()}catch(a){r(a)}});e.push(i)}})}const ga=5e3;class vh extends Error{constructor(s,r){super(s);l(this,"model");this.model=r}}const pa=(t,e,s)=>{let r;return{promise:new Promise((i,a)=>{r=setTimeout(()=>{p.error(`Model ${e.modelId} - ${e.modelTypeName} - ${s} timed out after ${t}ms`),a(new vh(`${e.modelId} - ${e.modelTypeName} - ${s}`,e))},t)}),cancel:()=>{r&&clearTimeout(r)}}},ma=t=>t.fsm.transitionTo(A.GO_ACTIVE,w.ACTIVE),ya=t=>t.whenReady(),ba=t=>t.fsm.transitionTo(A.LOAD,w.LOADED),Mh=t=>t.fsm.transitionTo(A.UNLOAD,w.UNLOADED),wa=t=>t.fsm.transitionTo(A.INITIALIZE,w.INITIALIZED);var Do=(t=>(t.ACTIVE="active",t.READY="ready",t.LOAD="load",t.UNLOAD="unload",t.INIT="init",t))(Do||{});const $s={active:ma,ready:ya,load:ba,init:wa},va=(t,e)=>{const s=e.id||e.modelType,r=ot({value:s,modelData:t.modelData,modelId:t.modelId});p.debug(`activating dependent model ${e.modelType} with id ${r}`);const o=Object.keys((e==null?void 0:e.options)||{}).reduce((i,a)=>{const c=e.options[a];return i[a]=ot({value:c,modelData:t.modelData,modelId:t.modelId}),i},{});return{dependentModel:I.getInstance().modelManager.createModelInstance(e.modelType,r,o),dataModelId:r}},Ma=(t,e=H.READY)=>{var o;const s=((o=t.modelData)==null?void 0:o[F])||{};return Object.keys(s).length===0?(p.debug(`${t.modelId} has no dependencies. Returning`),[]):Object.keys(s).filter(n=>s[n].lifecycle===e).map(n=>{const i=s[n],{dependentModel:a,dataModelId:c}=va(t,i);t.modelData[n]=a.data,p.debug(`waiting for dependent model ${i.modelType} with id ${c} - waiting for WHENREADY`);const d=async(g,m,y)=>{var v;await((v=g.whenReady)==null?void 0:v.call(g)),p.debug(`dependent model ${m} with id ${y} - READY`)},{promise:u,cancel:h}=pa(ga,t,t.status);return Promise.race([d(a.model,i.modelType,c).then(()=>{h()}).catch(g=>{console.error(`Error waiting for dependent model ${i.modelType} with id ${c}:`,g),h()}),u])}).filter(n=>!!n)},Ea=async(t,e,s,r)=>{if(p.debug(`Execute lifecycle with ${e.length} models`),e.length===0){p.debug(`${t.modelId} has no children. Returning`);return}if(!s){p.error(`${t.modelId} is not transitioning with a valid target ${s}`);return}const o=e.map(a=>{let c;return $s[s]&&a?c=$s[s](a):(a||p.error("model is undefined. This shouldn't happen"),$s[s]||p.error(`There is no promise in the Transition Map for ${s}`)),{promise:c,modelId:a==null?void 0:a.modelId,model:a,type:a==null?void 0:a.modelTypeName,status:a==null?void 0:a.status}}).filter(a=>a.promise?a.model?!0:(p.error(`No model found ${a.modelId}`),!1):(p.error(`No promise found ${a.modelId}`),!1)),i=(await Promise.allSettled(o.map(a=>{var u;const{promise:c,cancel:d}=pa(ga,a.model,a.status);return Promise.race([(u=a.promise)==null?void 0:u.then(()=>{d()}).catch(h=>{p.error(`Model ${a.modelId} - ${a.type} failed to transition to ${s}: ${h.message}`),d()}),c])}))).filter(a=>a.status==="rejected");i.length>0&&p.error(`Model ${t.modelId} had ${i.length} failed child models on ${r}`)},Ta=async(t,e,s)=>{await Ea(t,t.getChildren().filter(r=>!!r),e,s)},St=async(t,e)=>{const r=(await Promise.allSettled(Ma(t,e))).filter(o=>o.status==="rejected");r.length&&(p.error(`There were ${r.length} failed dependent models on ${e}`),p.error(r))},Eh=t=>typeof t.toJSON=="function",Kt=t=>t[F]!==void 0,Co=t=>t.revision!==void 0&&t.index!==void 0,_a=t=>{if(t){if(Kt(t))return t;if(Co(t))return t.data;if(t instanceof Map||t instanceof M.ObservableMap||t instanceof Set)return Array.from(t.values()).filter(Kt);if(Array.isArray(t))return t.filter(Kt)}};function Th(t){const e=`KosModel(${t.modelTypeName}:${t.modelId})`;try{Object.defineProperty(t,Symbol.toStringTag,{value:e,configurable:!0})}catch{t.toString=()=>e}try{Object.defineProperty(t.constructor,"name",{value:`KosModel_${t.modelTypeName}`,configurable:!0})}catch{t.constructor.name=`KosModel_${t.modelTypeName}`}const s=["fsm","effectManager","subscriptionManager","onlineLifecycleManager","companionManager","childResolver","_offlineQueue"];for(const r of s)r in t&&Object.defineProperty(t,r,{enumerable:!1});Object.defineProperty(t,"debugState",{enumerable:!1,configurable:!0,get(){var r,o,n;return{id:t.modelId,type:t.modelTypeName,initialized:t.initialized,loaded:t.loaded,status:t.status,onlineStatus:t.onlineStatus,activeStatus:t.activeStatus,companions:(o=(r=t.companionManager)==null?void 0:r.all())==null?void 0:o.map(i=>i.modelTypeName),children:(n=t.getChildren)==null?void 0:n.call(t).map(i=>i.modelId),effects:!!t.effectManager,subs:!!t.subscriptionManager}}}),_h(t.modelData,t.modelTypeName,t.modelId,t)}function _h(t,e,s,r){Object.defineProperty(t,Symbol.toStringTag,{value:`KosModelData(${e}:${s})`,configurable:!0});try{Object.defineProperty(t.constructor,"name",{value:`${e}ModelData`,configurable:!0})}catch{t.constructor.name=`${e}ModelData`}Object.defineProperty(t,"debugState",{enumerable:!1,configurable:!0,get(){var a,c,d;const o=((a=r.getChildren)==null?void 0:a.call(r))||[],n=((c=r.companionManager)==null?void 0:c.all())||[],i=r.modelData[F]||{};return{id:s,type:e,companions:{count:n.length,data:n.map(u=>({type:u.modelTypeName,id:u.modelId}))},dependencies:{count:Object.keys(i).length,data:Object.values(i).map(u=>({id:u.id||u.modelType,type:u.modelType,options:u.options,lifecycle:u.lifecycle}))},children:{count:o.length,data:o.map(u=>({id:u.modelId,type:u.modelTypeName}))},data:((d=t.toJSON)==null?void 0:d.call(t))||{},subs:!!r.subscriptionManager}}}),Object.defineProperty(t,"toJSON",{configurable:!0,enumerable:!1,writable:!0,value:()=>{const o={};for(const n of Object.keys(t))if(!(n.startsWith("_")||typeof t[n]=="function"))try{const i=t[n];Kt(i)?o[`[KOS Model] ${n}`]=typeof i.toJSON=="function"?i.toJSON():{id:i.id,type:i.constructor.name}:Co(i)?o[`[KOS Container] ${n}`]=typeof i.toJSON=="function"?i.toJSON():["Container"]:Array.isArray(i)?o[n]=`[Array(${i.length})]`:typeof i=="object"&&i!==null?o[n]=JSON.parse(JSON.stringify(i)):o[n]=i}catch{o[n]="[unreadable]"}return o}})}class Ih{constructor(e){this.model=e}resolve(){const e=new Set([...this.getResolvedDecoratedChildren(),...this.getAdditionalChildren(),...this.model.companionModels.all()]),s=Array.from(e).map(r=>this.model.modelManager.getModelById(r.id||"")).filter(r=>r&&r.status!==w.FAILED).filter(r=>!!r);return s.forEach(r=>{try{z.setParentContext(r.modelId,this.model.modelId)}catch(o){console.error(`Failed to set parent context for ${r.modelId} under ${this.model.modelId}`,o)}}),s}getResolvedDecoratedChildren(){var s;const e=((s=this.model.modelData)==null?void 0:s[Ut])||{};return Object.keys(e).map(r=>_a(this.model.modelData[r])).filter(r=>!!r).flat()}getAdditionalChildren(){var e,s;return((s=(e=this.model.modelData)==null?void 0:e.getChildren)==null?void 0:s.call(e))||[]}}class Sh{constructor(e){l(this,"companions",new M.ObservableMap);this.hostModel=e}add(e){this.companions.set(e.modelTypeName,e)}clear(){this.companions.clear()}get(e){return this.companions.get(e)}all(){return[...this.companions.values()]}get data(){return this.companions}}class Oh{constructor(e,s,r,o){l(this,"disposers",[]);this.modelTypeName=e,this.modelId=s,this.modelData=r,this.log=o}setup(){var s;const e=((s=this.modelData)==null?void 0:s[Ke])||{};for(const r of Object.keys(e)){const{value:o,dependencies:n,options:i}=e[r],a=o.bind(this.modelData),c=()=>{this.log.info(`Running effect ${r} for ${this.modelTypeName} (${this.modelId})`),M.runInAction(()=>a())},d=n?M.reaction(()=>n(this.modelData),c,{fireImmediately:!!(i!=null&&i.fireImmediately)}):M.autorun(c);this.disposers.push(d)}}disposeAll(){for(const e of this.disposers)try{e()}catch(s){this.log.info(`Failed to dispose effect for ${this.modelId}`,s)}this.disposers=[]}}const $h=p.createLogger({name:"model-active-machine"}),Dh=t=>{const e=b.createMachine(w.INACTIVE,{[w.FAILED]:b.state(b.transition(A.GO_ACTIVE,w.ACTIVATING)),[w.INACTIVE]:b.state(b.transition(A.GO_ACTIVE,w.ACTIVATING)),[w.ACTIVATING]:b.invoke(()=>(t.activeStatus=w.ACTIVATING,t.activate()),b.transition("done",w.ACTIVE,b.action(()=>{t.activeStatus=w.ACTIVE})),b.transition("error",w.FAILED,b.action(()=>{t.activeStatus=w.FAILED}))),[w.ACTIVE]:b.state(b.transition(A.GO_INACTIVE,w.DEACTIVATING)),[w.DEACTIVATING]:b.invoke(()=>(t.activeStatus=w.DEACTIVATING,t.deactivate()),b.transition("done",w.INACTIVE,b.action(()=>{t.activeStatus=w.INACTIVE})),b.transition("error",w.FAILED,b.action(()=>{t.activeStatus=w.FAILED})))});return{service:b.interpret(e,r=>$h.debug(r.machine.current)),machine:e}},An=p.createLogger({name:"model-online-machine"}),Ch=t=>{const e=b.createMachine(w.OFFLINE,{[w.ONLINE]:b.state(b.transition(A.GO_OFFLINE,w.OFFLINE,b.action(async()=>{await t.offline(),t.onlineStatus=w.OFFLINE}))),[w.OFFLINE]:b.state(b.transition(A.GO_ONLINE,w.ONLINE,b.action(async()=>{An.debug(`Going online with model ${t.modelId}`),await t.online(),t.onlineStatus=w.ONLINE,await t.fsm.transitionTo(A.INITIALIZE,w.INITIALIZED)})))}),s=b.interpret(e,r=>An.debug(r.machine.current));return{machine:e,service:s}},Rh=t=>{var r;const e=Dh(t).service,s=Ch(t).service;return b.createMachine(w.CREATING,{[w.CREATING]:b.state(b.transition(A.CREATE,w.CREATED)),[w.CREATED]:b.state(b.immediate(w.INITIALIZING)),[w.INITIALIZING]:b.invoke(()=>(X(()=>{t.status=w.INITIALIZING}),t.init()),b.transition("done",w.INITIALIZED,b.action(()=>{t.status=w.INITIALIZED})),b.transition("error",w.FAILED,b.action(()=>{p.error(`Model ${t.modelId} - ${t.modelTypeName} failed to initialize. Transitioning to FAILED state.`),t.status=w.FAILED}))),[w.INITIALIZED]:b.state(b.immediate(w.LOADING)),[w.LOADING]:b.invoke(()=>(X(()=>{t.status=w.LOADING}),t.load()),b.transition("done",w.LOADED,b.action(()=>{t.status=w.LOADED})),b.transition("error",w.FAILED,b.action(()=>{t.status=w.FAILED}))),[w.LOADED]:b.state(b.immediate(w.READYING),b.transition(A.UNLOAD,w.UNLOADING)),[w.RESETTING]:b.invoke(()=>{var o;return X(()=>{t.status=w.RESETTING}),(o=t.unload)==null||o.call(t),t.load()},b.transition("done",w.LOADED,b.action(()=>{t.status=w.LOADED}))),[w.READYING]:b.invoke(()=>(X(()=>{t.status=w.READYING}),t.ready()),b.transition("done",w.READY,b.action(()=>{X(()=>{t.status=w.READY}),s.send(A.GO_ONLINE)})),b.transition("error",w.FAILED,b.action(()=>{t.status=w.FAILED}))),[w.READY]:b.state(b.transition(A.UNLOAD,w.UNLOADED,b.action((r=t.unload)==null?void 0:r.bind(t))),b.transition(A.RESET,w.RESETTING),b.transition(A.GO_ONLINE,w.READY,b.action(()=>{s.send(A.GO_ONLINE)})),b.transition(A.GO_OFFLINE,w.READY,b.action(()=>{s.send(A.GO_OFFLINE)})),b.transition(A.GO_ACTIVE,w.READY,b.action(()=>{e.send(A.GO_ACTIVE)})),b.transition(A.GO_INACTIVE,w.READY,b.action(()=>{e.send(A.GO_INACTIVE)}))),[w.UNLOADED]:b.state(),[w.FAILED]:b.state()})},Ah=p.createLogger({name:"kos-model-lifecycle"}),xh=t=>({service:b.interpret(Rh(t),s=>Ah.debug(`state machine for model ${t.modelId}: ${s.machine.current});`))});class Ph{constructor(e,s){l(this,"disposer");l(this,"service");this.model=e,this.log=s;const r=xh(e);this.service=r.service,this.service.send(A.CREATE)}get current(){return this.service.machine.current}async transitionTo(e,s,r=w.FAILED){return this.getTransitionStatusFor(s)===s?(this.log.debug(`Model ${this.model.modelId} already in state ${s}, skipping transition`),Promise.resolve()):(this.log.debug(`Transitioning model ${this.model.modelId} with event ${e} toward target ${s}`),new Promise((n,i)=>{var a;(a=this.disposer)==null||a.call(this),this.disposer=M.when(()=>{const c=this.getTransitionStatusFor(s);return c===s||c===r},()=>{this.getTransitionStatusFor(s)===r?(this.log.error(`Model ${this.model.modelId} entered error state ${r} during transition`),i(new Error(`FSM transition failed for model ${this.model.modelId} with event ${e}`))):(this.log.debug(`Model ${this.model.modelId} reached target state ${s}`),n())}),this.service.send(e)}).finally(()=>{var n;(n=this.disposer)==null||n.call(this),this.disposer=void 0}))}getTransitionStatusFor(e){return[w.ACTIVE,w.INACTIVE].includes(e)?this.model.activeStatus:[w.ONLINE,w.OFFLINE].includes(e)?this.model.onlineStatus:this.model.status}}const Ia="browser-router-model";class Ro{constructor(e,s){l(this,"logger");l(this,"model");l(this,"router",null);l(this,"registered",!1);l(this,"registeredRoutes",[]);this.model=e,this.logger=s}registerAll(){var s;if(!ks(this.model))return;let e=this.model.__httpBrowserRouter;if(!e)for(const r of Object.keys(this.model)){const o=this.model[r];if(o&&typeof o=="object"&&"use"in o&&typeof o.use=="function"){e=o;break}}if(e||(e=(s=ve(Ia))==null?void 0:s.model),!e)throw this.logger.error("Cannot register HTTP routes: BrowserRouter not found. The HTTP decorators should have auto-injected it, but something went wrong."),new Error("BrowserRouter is required for HTTP route decorators but was not found. This should not happen as HTTP decorators auto-inject the dependency.");this.setRouter(e)}setRouter(e){this.router=e,this.registered||this.registerRoutes()}hasRoutes(){return ks(this.model)}registerRoutes(){if(!this.router){this.logger.warn("Cannot register routes: router not set");return}if(this.registered){this.logger.debug("Routes already registered");return}const e=ca(this.model);e.length!==0&&(this.logger.debug(`Registering ${e.length} HTTP routes`),e.forEach(s=>{this.registerRoute(s)}),this.registered=!0)}resolvePropKey(e){const s=/\{PROP_([^}]+)\}/g;let r=e;if(r.includes("{MODEL_ID}")){const n=this.model.id||this.model._id||"unknown";r=r.replace(/\{MODEL_ID\}/g,n)}let o;for(;(o=s.exec(e))!==null;){const n=o[1];if(n in this.model){const i=this.model[n];r=r.replace(o[0],String(i))}else this.logger.warn(`Property '${n}' not found on model for PropKey resolution in path: ${e}`)}return r}registerRoute(e){if(!this.router)return;const s=this.model[e.handler];if(!s||typeof s!="function"){this.logger.error(`Handler method '${e.handler}' not found on model`);return}const r=this.resolvePropKey(e.path);this.logger.debug(`Registering ${e.method} ${r} -> ${e.handler}`+(r!==e.path?` (resolved from ${e.path})`:""));const o=async(n,i)=>{var a;try{await s.call(this.model,n,i)}catch(c){this.logger.error(`Error in route handler ${e.method} ${r}:`,c),(a=i.status)==null||a.call(i,500).send({error:"Internal server error",message:c instanceof Error?c.message:String(c)})}};this.checkForDuplicateRoute(e.method,r),this.router.use(e.method,r,o),this.registeredRoutes.push({method:e.method,path:r})}checkForDuplicateRoute(e,s){if(!this.router)return;this.router.getRoutes().find(n=>n.method===e&&n.path===s)&&this.logger.warn(`Duplicate route detected: ${e} ${s}. This route is already registered by another model. The new handler from model '${this.model.id||"unknown"}' will override the existing one. Only the last registered handler will receive requests. Consider using different paths or namespacing to avoid conflicts.`)}dispose(){if(this.router&&this.registeredRoutes.length>0){this.logger.debug(`Removing ${this.registeredRoutes.length} HTTP routes for model ${this.model.id||"unknown"}`);let e=0;for(const s of this.registeredRoutes){const r=this.router.remove(s.method,s.path);e+=r,r>0?this.logger.debug(`Removed route: ${s.method} ${s.path}`):this.logger.warn(`Failed to remove route: ${s.method} ${s.path} (not found)`)}this.logger.debug(`Successfully removed ${e} routes from browser router`)}this.registered=!1,this.registeredRoutes=[],this.router=null}getRegisteredRoutes(){return[...this.registeredRoutes]}}function Lh(t,e){if(!ks(t))return;const s=ve(Ia);if(!(s!=null&&s.model))throw e.error("Cannot register HTTP routes: BrowserRouter not found. Make sure to include BrowserRouter in your model dependencies or create an instance."),new Error("BrowserRouter is required for HTTP route decorators but was not found. Add it as a dependency using @kosDependency or ensure an instance exists.");new Ro(t,e).setRouter(s.model)}class kh{static create({modelId:e,modelTypeName:s,component:r}){const o=[r??"kos",s,e].filter(Boolean).join(".");return p.createLogger({name:o})}}class Fh{constructor(e){l(this,"queue",[]);this.log=e}enqueue(e){this.queue.push(e)}flush(){if(this.queue.length!==0){this.log.warn(`Processing ${this.queue.length} offline message(s)`);for(const e of this.queue)try{e()}catch(s){this.log.error("Error while processing offline message:",s)}this.queue=[],this.log.info("Offline queue flushed")}}clear(){this.queue=[]}get length(){return this.queue.length}get isEmpty(){return this.queue.length===0}}class Nh{constructor(e,s){l(this,"unsubscribers",[]);this.model=e,this.log=s}register(){this.dispose();const e=this.model.modelId,s=O("/kosCore/online",async()=>{this.log.debug(`Online event received for ${e}, waiting for readiness...`),await this.model.whenReady(),this.log.debug(`${e} is ready — sending GO_ONLINE`),await this.model.fsm.transitionTo(A.GO_ONLINE,w.ONLINE)}),r=O("/kosCore/offline",async()=>{this.log.debug(`Offline event received for ${e} — sending GO_OFFLINE`),await this.model.fsm.transitionTo(A.GO_OFFLINE,w.OFFLINE)});this.unsubscribers.push(s.unsubscribe),this.unsubscribers.push(r.unsubscribe)}dispose(){this.unsubscribers.forEach(e=>e()),this.unsubscribers=[]}}class Uh{constructor(e){l(this,"subscription");l(this,"unsubscribe");l(this,"eventType");this.eventType=e,this.subscription={queue:[],resolvers:[],closed:!1};const s=O(e,r=>{if(!this.subscription.closed&&r!==void 0){const o=this.subscription.resolvers.shift();o?o(r):this.subscription.queue.push(r)}});this.unsubscribe=s.unsubscribe}async next(){return this.subscription.closed&&this.subscription.queue.length===0?{done:!0,value:void 0}:this.subscription.queue.length>0?{done:!1,value:this.subscription.queue.shift()}:new Promise(e=>{this.subscription.closed?e({done:!0,value:void 0}):this.subscription.resolvers.push(s=>{e({done:!1,value:s})})})}async return(){return this.subscription.closed=!0,this.unsubscribe(),this.subscription.resolvers.forEach(e=>{e(void 0)}),this.subscription.resolvers=[],{done:!0,value:void 0}}async throw(e){throw this.subscription.closed=!0,this.unsubscribe(),e}[Symbol.asyncIterator](){return this}}function xn(t){return new Uh(t)}var Sa=(t=>(t.GET="GET",t.PUT="PUT",t.POST="POST",t.DELETE="DELETE",t))(Sa||{});const Oa=({path:t,requestId:e,method:s,destinationAddress:r})=>{let o=`${cr}:${s}
2
2
  `;return o+=`topic:${t}
3
- `,o+=`${gt}:${t}
3
+ `,o+=`${pt}:${t}
4
4
  `,o+=`${os}:${e}
5
5
  `,r&&(o+=`${$e}:${r}
6
6
  `),o+=`${Me}:kos.studio.request
7
7
  `,o+=`
8
- `,o},Oa=({path:t,requestId:e,method:s,destinationAddress:r,ordered:o,tracker:n})=>{let i=`${ii}:/http${t}
8
+ `,o},$a=({path:t,requestId:e,method:s,destinationAddress:r,ordered:o,tracker:n})=>{let i=`${ai}:/http${t}
9
9
  `;return i+=`${cr}:${s}
10
- `,i+=`${gt}:${t}
11
- `,i+=`${di}:${e}
10
+ `,i+=`${pt}:${t}
11
+ `,i+=`${ui}:${e}
12
12
  `,r&&(i+=`${$e}:${r}
13
- `),o&&(i+=`${ho}:true
14
- `),n&&(i+=`${fo}:${n}
13
+ `),o&&(i+=`${yo}:true
14
+ `),n&&(i+=`${bo}:${n}
15
15
  `),i+=`${Me}:fos.http.request
16
16
  `,i+=`
17
- `,i},$a=({path:t,requestId:e,method:s,destinationAddress:r,ordered:o,tracker:n,bridge:i,headers:a})=>{let c=`${cr}:${s}
18
- `;return c+=`${gt}:${t}
17
+ `,i},Da=({path:t,requestId:e,method:s,destinationAddress:r,ordered:o,tracker:n,bridge:i,headers:a})=>{let c=`${cr}:${s}
18
+ `;return c+=`${pt}:${t}
19
19
  `,c+=`${os}:${e}
20
20
  `,r&&(c+=`${$e}:${r}
21
- `),o&&(c+=`${ho}:true
22
- `),n&&(c+=`${fo}:${n}
21
+ `),o&&(c+=`${yo}:true
22
+ `),n&&(c+=`${bo}:${n}
23
23
  `),a&&Object.keys(a).forEach(d=>{c+=`${d}:${a[d]}
24
24
  `}),c+=`${Me}:${i?"fos":"kos"}.http.request
25
25
  `,c+=`
26
- `,c},ke=(t,e)=>{let s=t;return e&&(s+=e),s};function Da(t){const e={...t};return{append(s,r){e[s]=r},delete(s){delete e[s]},get(s){return e[s]},forEach(s){Object.keys(e).forEach(r=>s(e[r],r,this))},has(s){return Object.hasOwn(e,s)},set(s,r){e[s]=r},keys(){return Object.keys(e)},values(){return Object.values(e)},entries(){return Object.entries(e)}}}function Ca(t){let e=!1;return window.ReadableStream?new ReadableStream({start(r){function o(){return Promise.resolve({done:e,value:t}).then(({done:n,value:i})=>{if(n){r.close();return}r.enqueue(i),e=!0,o()})}o()}}):t}const Ra=({path:t,requestId:e,destinationAddress:s})=>{let r=`topic:${t}
27
- `;return r+=`${gt}:${t}
26
+ `,c},ke=(t,e)=>{let s=t;return e&&(s+=e),s};function Ca(t){const e={...t};return{append(s,r){e[s]=r},delete(s){delete e[s]},get(s){return e[s]},forEach(s){Object.keys(e).forEach(r=>s(e[r],r,this))},has(s){return Object.hasOwn(e,s)},set(s,r){e[s]=r},keys(){return Object.keys(e)},values(){return Object.values(e)},entries(){return Object.entries(e)}}}function Ra(t){let e=!1;return window.ReadableStream?new ReadableStream({start(r){function o(){return Promise.resolve({done:e,value:t}).then(({done:n,value:i})=>{if(n){r.close();return}r.enqueue(i),e=!0,o()})}o()}}):t}const Aa=({path:t,requestId:e,destinationAddress:s})=>{let r=`topic:${t}
27
+ `;return r+=`${pt}:${t}
28
28
  `,r+=`${os}:${e}
29
29
  `,r+=`${$e}:${s}
30
30
  `,r+=`${Me}:kos.studio.request
31
31
  `,r+=`
32
- `,r},Aa=({requestId:t,destinationAddress:e,requestType:s,headers:r})=>{let o=`${os}:${t}
32
+ `,r},xa=({requestId:t,destinationAddress:e,requestType:s,headers:r})=>{let o=`${os}:${t}
33
33
  `;return o+=`${$e}:${e}
34
34
  `,o+=`${Me}:${s}
35
35
  `,r&&Object.keys(r).forEach(n=>{o+=`${n}:${r[n]}
36
36
  `}),o+=`
37
- `,o},jh=(t,e)=>{const s=t,r=ke(Aa(e),typeof s=="string"?s:JSON.stringify(s)),o=I.getInstance().transport.socket;o?(p.debug("Sending message",r),o.socket.send(r)):p.error("socket transport is not initialized")},xa=({path:t,responseId:e,status:s,destinationAddress:r})=>{let o=`topic:${t}
38
- `;return o+=`${gt}:${t}
37
+ `,o},jh=(t,e)=>{const s=t,r=ke(xa(e),typeof s=="string"?s:JSON.stringify(s)),o=I.getInstance().transport.socket;o?(p.debug("Sending message",r),o.socket.send(r)):p.error("socket transport is not initialized")},Pa=({path:t,responseId:e,status:s,destinationAddress:r})=>{let o=`topic:${t}
38
+ `;return o+=`${pt}:${t}
39
39
  `,e&&(o+=`${lr}:${e}
40
- `),o+=`${uo}:${s}
40
+ `),o+=`${mo}:${s}
41
41
  `,o+=`${$e}:${r}
42
42
  `,o+=`${Me}:kos.studio.response
43
43
  `,o+=`
44
- `,o},Bh=(t,e)=>{const s=t,r=ke(Ra(e),JSON.stringify(s)),o=I.getInstance().transport.socket;o?o.socket.send(r):p.error("socket transport is not initialized")},Kh=(t,e)=>{const s=e.responseId?{status:e.status,data:t}:t,r=ke(xa(e),JSON.stringify(s)),o=I.getInstance().transport.socket;o?o.socket.send(r):p.error("socket transport is not initialized")},Pa=({topic:t})=>{let e=`topic:${t}
44
+ `,o},Bh=(t,e)=>{const s=t,r=ke(Aa(e),JSON.stringify(s)),o=I.getInstance().transport.socket;o?o.socket.send(r):p.error("socket transport is not initialized")},Kh=(t,e)=>{const s=e.responseId?{status:e.status,data:t}:t,r=ke(Pa(e),JSON.stringify(s)),o=I.getInstance().transport.socket;o?o.socket.send(r):p.error("socket transport is not initialized")},La=({topic:t})=>{let e=`topic:${t}
45
45
  `;return e+=`${Me}:kos.broker.send
46
46
  `,e+=`
47
- `,e},La=({responseId:t,destinationAddress:e,type:s,sourceAddress:r,status:o})=>{let n=`${lr}:${t}
47
+ `,e},ka=({responseId:t,destinationAddress:e,type:s,sourceAddress:r,status:o})=>{let n=`${lr}:${t}
48
48
  `;return n+=`${$e}:${e}
49
- `,n+=`${ai}:${r}
49
+ `,n+=`${ci}:${r}
50
50
  `,n+=`${Me}:${s??"kos.message.request"}
51
- `,n+=`${uo}:${o}
52
- `,n+=`${ci}:application/json
53
- `,n+=`${li}:no-cache
51
+ `,n+=`${mo}:${o}
52
+ `,n+=`${li}:application/json
53
+ `,n+=`${di}:no-cache
54
54
  `,n+=`
55
- `,n},ka=({topic:t,responseId:e,destinationAddress:s,type:r})=>{let o=`topic:${t}
55
+ `,n},Fa=({topic:t,responseId:e,destinationAddress:s,type:r})=>{let o=`topic:${t}
56
56
  `;return e&&(o+=`${lr}:${e}
57
57
  `),o+=`${$e}:${s}
58
58
  `,o+=`${Me}:${r??"kos.message.request"}
59
59
  `,o+=`
60
- `,o},Hh=({msg:t,options:e})=>{const s=t,r=ke(Pa(e),JSON.stringify(s)),o=I.getInstance().transport.socket;o?o.socket.send(r):p.error("socket transport is not initialized")},Fa=({msg:t,options:e})=>{const s=t,r=ke(ka(e),JSON.stringify(s)),o=I.getInstance().transport.socket;o?o.socket.send(r):p.error("socket transport is not initialized")},Na=({msg:t,options:e})=>{const s=t,r=ke(La(e),JSON.stringify(s)),o=I.getInstance().transport.socket;o?o.socket.send(r):p.error("socket transport is not initialized")},Gr=(t,e)=>{try{return e?t.body??t:JSON.parse(t.body)}catch{return t.body||t}};class zh extends WebSocket{constructor(e){super(e)}}var pe=(t=>(t.CONNECTED="websocket.connected",t.DISCONNECTED="websocket.disconnected",t.ERROR="websocket.error",t.MAX_RETRIES_EXCEEDED="websocket.max_retries_exceeded",t.RELOAD="websocket.reload",t))(pe||{});function Dn(t){const e=`
60
+ `,o},Hh=({msg:t,options:e})=>{const s=t,r=ke(La(e),JSON.stringify(s)),o=I.getInstance().transport.socket;o?o.socket.send(r):p.error("socket transport is not initialized")},Na=({msg:t,options:e})=>{const s=t,r=ke(Fa(e),JSON.stringify(s)),o=I.getInstance().transport.socket;o?o.socket.send(r):p.error("socket transport is not initialized")},Ua=({msg:t,options:e})=>{const s=t,r=ke(ka(e),JSON.stringify(s)),o=I.getInstance().transport.socket;o?o.socket.send(r):p.error("socket transport is not initialized")},Vr=(t,e)=>{try{return e?t.body??t:JSON.parse(t.body)}catch{return t.body||t}};class zh extends WebSocket{constructor(e){super(e)}}var pe=(t=>(t.CONNECTED="websocket.connected",t.DISCONNECTED="websocket.disconnected",t.ERROR="websocket.error",t.MAX_RETRIES_EXCEEDED="websocket.max_retries_exceeded",t.RELOAD="websocket.reload",t))(pe||{});function Pn(t){const e=`
61
61
 
62
62
  `,s=`
63
63
  `,r=/:(.*)/s,[o,n]=t.split(e).map(a=>a.trim());return{headers:o.split(s).reduce((a,c)=>{const[d,u]=c.split(r).map(h=>h.trim());return d&&u&&(a[d]=u),a},{}),body:n}}function Gh(t){const e=`
64
64
 
65
65
  `,s=`
66
- `,r=/:(.*)/s,[,o,n]=t.split(e).map(a=>a.trim());return{headers:o.split(s).reduce((a,c)=>{const[d,u]=c.split(r).map(h=>h.trim());return d&&u&&(a[d]=u),a},{}),body:n}}const fe=class fe{constructor({host:e,port:s,protocol:r,alias:o,onConnectionEstablished:n,onConnectionLost:i,Transport:a=zh}){l(this,"host");l(this,"port");l(this,"protocol");l(this,"socket");l(this,"connectionEstablished");l(this,"alias");l(this,"onConnectionEstablished");l(this,"onConnectionLost");l(this,"offlineMessages",[]);l(this,"oldSend");l(this,"reconnectAttempts",0);this.host=e,this.port=s,this.protocol=r,this.onConnectionEstablished=n,this.onConnectionLost=i,this.alias=o,this.socket=new a(`${this.protocol}${this.host}:${this.port}/events`),this.socket.onmessage=this.onMessage.bind(this),this.socket.onopen=this.onOpen.bind(this),this.socket.onclose=this.onClose.bind(this),this.socket.onerror=this.onError.bind(this),this.oldSend=this.socket.send,this.connectionEstablished=!1,O("/mock/msg/receive",c=>{var d,u;if(c!=null&&c.body){p.wsReceive(c==null?void 0:c.body);const h={data:c.body};(u=(d=this.socket)==null?void 0:d.onmessage)==null||u.call(d,h)}}),M.makeObservable(this,{connectionEstablished:M.observable})}addOfflineMessage(e){this.offlineMessages.push({msg:e})}processMessageEvent(e){const{data:s}=e;return Dn(s)}onMessage(e){try{p.debug("webSocketTransport: onMessage received");const{headers:s,body:r}=this.processMessageEvent(e);p.wsReceive(e.data);const o=s.subscription||s[this.RESPONSE_ID_HEADER]||s.topic||s.type;if(o){let n=r,i=s;if(o==="kos.sniffer.msg"){const{headers:a,body:c}=Gh(e.data);n=c,i={...s,...a}}j(o,n,i)}}catch(s){p.error("onMessage exception",s.message,s.stack)}}onOpen(e){p.info("websocket connection opened"),this.reconnectAttempts=0,this.socket=e.currentTarget,M.runInAction(()=>{var s;this.connectionEstablished=!0,this.alias&&this.socket.send(`type:kos.addr.alias
66
+ `,r=/:(.*)/s,[,o,n]=t.split(e).map(a=>a.trim());return{headers:o.split(s).reduce((a,c)=>{const[d,u]=c.split(r).map(h=>h.trim());return d&&u&&(a[d]=u),a},{}),body:n}}const fe=class fe{constructor({host:e,port:s,protocol:r,alias:o,onConnectionEstablished:n,onConnectionLost:i,Transport:a=zh}){l(this,"host");l(this,"port");l(this,"protocol");l(this,"socket");l(this,"connectionEstablished");l(this,"alias");l(this,"onConnectionEstablished");l(this,"onConnectionLost");l(this,"offlineMessages",[]);l(this,"oldSend");l(this,"reconnectAttempts",0);this.host=e,this.port=s,this.protocol=r,this.onConnectionEstablished=n,this.onConnectionLost=i,this.alias=o,this.socket=new a(`${this.protocol}${this.host}:${this.port}/events`),this.socket.onmessage=this.onMessage.bind(this),this.socket.onopen=this.onOpen.bind(this),this.socket.onclose=this.onClose.bind(this),this.socket.onerror=this.onError.bind(this),this.oldSend=this.socket.send,this.connectionEstablished=!1,O("/mock/msg/receive",c=>{var d,u;if(c!=null&&c.body){p.wsReceive(c==null?void 0:c.body);const h={data:c.body};(u=(d=this.socket)==null?void 0:d.onmessage)==null||u.call(d,h)}}),M.makeObservable(this,{connectionEstablished:M.observable})}addOfflineMessage(e){this.offlineMessages.push({msg:e})}processMessageEvent(e){const{data:s}=e;return Pn(s)}onMessage(e){try{p.debug("webSocketTransport: onMessage received");const{headers:s,body:r}=this.processMessageEvent(e);p.wsReceive(e.data);const o=s.subscription||s[this.RESPONSE_ID_HEADER]||s.topic||s.type;if(o){let n=r,i=s;if(o==="kos.sniffer.msg"){const{headers:a,body:c}=Gh(e.data);n=c,i={...s,...a}}j(o,n,i)}}catch(s){p.error("onMessage exception",s.message,s.stack)}}onOpen(e){p.info("websocket connection opened"),this.reconnectAttempts=0,this.socket=e.currentTarget,M.runInAction(()=>{var s;this.connectionEstablished=!0,this.alias&&this.socket.send(`type:kos.addr.alias
67
67
  alias:${this.alias}
68
68
 
69
- `),p.debug(`sending ${this.offlineMessages.length} offline FOS messages`),this.offlineMessages.forEach(r=>{var o;p.debug(`sending offline message ${r.msg}`),(o=this.socket)==null||o.send(r.msg)}),this.offlineMessages=[],(s=this.onConnectionEstablished)==null||s.call(this)})}onClose(e){const{code:s,reason:r,wasClean:o}=e;p.warn(`WebSocket closed: code=${s}, reason=${r||"none"}, wasClean=${o}`),M.runInAction(()=>{this.connectionEstablished=!1}),j("websocket.disconnected",{code:s,reason:r,wasClean:o});const n=this.shouldAttemptReconnection(s);if(this.onConnectionLost)if(n&&this.reconnectAttempts<fe.MAX_RECONNECT_ATTEMPTS){const i=this.calculateBackoffDelay();p.debug(`Reconnecting in ${i}ms (attempt ${this.reconnectAttempts+1}/${fe.MAX_RECONNECT_ATTEMPTS})`),setTimeout(()=>{var a;this.reconnectAttempts++,(a=this.onConnectionLost)==null||a.call(this)},i)}else this.reconnectAttempts>=fe.MAX_RECONNECT_ATTEMPTS?(p.error(`Max reconnection attempts (${fe.MAX_RECONNECT_ATTEMPTS}) reached. Giving up.`),j("websocket.max_retries_exceeded",{attempts:this.reconnectAttempts})):p.info(`Not reconnecting due to close code ${s} (intentional close or configuration error)`)}onError(e){p.error("websocket error: ",e),j("websocket.error",{event:e})}shouldAttemptReconnection(e){switch(e){case 1e3:return!0;case 1001:return!0;case 1002:return!1;case 1003:return!1;case 1005:return!0;case 1006:return!0;case 1007:return!1;case 1008:return!1;case 1009:return!1;case 1010:return!1;case 1011:return!0;case 1012:return!0;case 1013:return!0;case 1014:return!0;case 1015:return!1;default:return!0}}calculateBackoffDelay(){const e=Math.min(fe.BASE_DELAY_MS*Math.pow(2,this.reconnectAttempts),fe.MAX_DELAY_MS),s=e*.25*(Math.random()*2-1);return Math.floor(e+s)}send(e){var s,r;if(p.wsSend(e),window.kosLogEvents){const{headers:o,body:n}=Dn(String(e));j(ns.SEND,{headers:o,body:n})}if(window.kosTopicIntercept&&window.kosEnableMocks){const{handler:o,requestId:n}=window.kosTopicIntercept(e);if(o){e=`mocked:true
69
+ `),p.debug(`sending ${this.offlineMessages.length} offline FOS messages`),this.offlineMessages.forEach(r=>{var o;p.debug(`sending offline message ${r.msg}`),(o=this.socket)==null||o.send(r.msg)}),this.offlineMessages=[],(s=this.onConnectionEstablished)==null||s.call(this)})}onClose(e){const{code:s,reason:r,wasClean:o}=e;p.warn(`WebSocket closed: code=${s}, reason=${r||"none"}, wasClean=${o}`),M.runInAction(()=>{this.connectionEstablished=!1}),j("websocket.disconnected",{code:s,reason:r,wasClean:o});const n=this.shouldAttemptReconnection(s);if(this.onConnectionLost)if(n&&this.reconnectAttempts<fe.MAX_RECONNECT_ATTEMPTS){const i=this.calculateBackoffDelay();p.debug(`Reconnecting in ${i}ms (attempt ${this.reconnectAttempts+1}/${fe.MAX_RECONNECT_ATTEMPTS})`),setTimeout(()=>{var a;this.reconnectAttempts++,(a=this.onConnectionLost)==null||a.call(this)},i)}else this.reconnectAttempts>=fe.MAX_RECONNECT_ATTEMPTS?(p.error(`Max reconnection attempts (${fe.MAX_RECONNECT_ATTEMPTS}) reached. Giving up.`),j("websocket.max_retries_exceeded",{attempts:this.reconnectAttempts})):p.info(`Not reconnecting due to close code ${s} (intentional close or configuration error)`)}onError(e){p.error("websocket error: ",e),j("websocket.error",{event:e})}shouldAttemptReconnection(e){switch(e){case 1e3:return!0;case 1001:return!0;case 1002:return!1;case 1003:return!1;case 1005:return!0;case 1006:return!0;case 1007:return!1;case 1008:return!1;case 1009:return!1;case 1010:return!1;case 1011:return!0;case 1012:return!0;case 1013:return!0;case 1014:return!0;case 1015:return!1;default:return!0}}calculateBackoffDelay(){const e=Math.min(fe.BASE_DELAY_MS*Math.pow(2,this.reconnectAttempts),fe.MAX_DELAY_MS),s=e*.25*(Math.random()*2-1);return Math.floor(e+s)}send(e){var s,r;if(p.wsSend(e),window.kosLogEvents){const{headers:o,body:n}=Pn(String(e));j(ns.SEND,{headers:o,body:n})}if(window.kosTopicIntercept&&window.kosEnableMocks){const{handler:o,requestId:n}=window.kosTopicIntercept(e);if(o){e=`mocked:true
70
70
  ${e}`;const a={data:`mocked:true
71
- ${o(n)}`};(r=(s=this.socket)==null?void 0:s.onmessage)==null||r.call(s,a)}else this.oldSend.call(this.socket,e)}else this.oldSend.call(this.socket,e)}};l(fe,"MAX_RECONNECT_ATTEMPTS",10),l(fe,"BASE_DELAY_MS",1e3),l(fe,"MAX_DELAY_MS",3e4);let Vt=fe;class Vh{constructor(e){l(this,"addEventListener");l(this,"dispatchEvent");l(this,"removeEventListener");l(this,"_onclose");l(this,"_onerror");l(this,"_onmessage");l(this,"_onopen");l(this,"messageQueue",[]);l(this,"isSending",!1);$.debug(`called Bridge Transport with addr ${e}`);const s=this;globalThis.kosWindowWebsocketRecv=r=>{if(s.onmessage){const o={data:r};s.onmessage(o)}},$.debug("Opening bridge transport"),globalThis.kosWindowWebsocketOpen(),$.debug("Opened bridge transport"),this._onclose=null,this._onerror=null,this._onmessage=null,this._onopen=null,this.addEventListener=()=>$.debug("not implemented"),this.dispatchEvent=()=>$.debug("not implemented"),this.removeEventListener=()=>$.debug("not implemented")}close(){$.debug("closing")}sendNextMessage(){if(this.messageQueue.length>0){const e=this.messageQueue.shift();globalThis.kosWindowWebsocketSend(e),setTimeout(()=>this.sendNextMessage(),1)}else this.isSending=!1}enqueueMessage(e){this.messageQueue.push(e),this.isSending||(this.isSending=!0,this.sendNextMessage())}send(e){globalThis.kosWindowWebsocketSend(e)}get onmessage(){return this._onmessage}set onmessage(e){this._onmessage=e}get onopen(){return this._onopen}set onopen(e){this._onopen=e}get onclose(){return this._onclose}set onclose(e){this._onclose=e}get onerror(){return this._onerror}set onerror(e){this._onerror=e}}class Yh extends Vt{constructor({host:s,port:r,alias:o}){super({host:s,port:r,Transport:Vh,alias:o,protocol:"kos://"});l(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="response-id"}}class qh extends Vt{constructor({host:s,port:r}){super({host:s,port:r,protocol:"ws://"});l(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="requestId"}}class Wh extends Vt{constructor({host:s,port:r,protocol:o,onConnectionEstablished:n,onConnectionLost:i,alias:a}){super({host:s,port:r,onConnectionEstablished:n,onConnectionLost:i,alias:a,protocol:o});l(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="response-id"}}window.kosEnableMocks=process.env.KOS_MOCK_WS==="true";window.kosLogEvents=process.env.KOS_LOG_WS==="true";class Vr{static build({host:e,port:s,protocol:r,fos:o,alias:n,onConnectionEstablished:i,onConnectionLost:a}){return p.debug("initializing websocket connection"),p.warn(`kosWindowWebsocketOpen: ${globalThis.kosWindowWebsocketOpen?"true":"false"}`),p.warn(`fos: ${o?"true":"false"}`),window.kosMockWs||globalThis.kosWindowWebsocketOpen&&!o?(p.warn("Using bridged message transport"),new Yh({host:e,port:s,protocol:r,onConnectionEstablished:i,onConnectionLost:a,alias:n})):o?new qh({host:e,port:s,protocol:r,alias:n,onConnectionEstablished:i,onConnectionLost:a}):new Wh({host:e,port:s,protocol:r,alias:n,onConnectionEstablished:i,onConnectionLost:a})}}const Qh=ue();Qh.fos&&(window.kosUseFos=!0);const Cn=process.env.KOS_FOS_PORT;window.kosUseFos=!!(window.kosUseFos||process.env.KOS_USE_FOS==="true");window.kosFosPort=Cn?parseInt(Cn):0;const Ne=$.getLogger("web-socket-transport");var Ua=(t=>(t.NOT_INITIALIZED="not_initialized",t.INITIALIZED="initialized",t.OFFLINE="OFFLINE",t.ONLINE="ONLINE",t))(Ua||{});class nt{constructor({host:e="localhost",port:s=8080,protocol:r="ws://",token:o,initialize:n,alias:i,fos:a}){l(this,"host");l(this,"port");l(this,"protocol");l(this,"_token");l(this,"webSocketSupported",!!globalThis.WebSocket);l(this,"authorized");l(this,"alias");l(this,"socket");l(this,"fosSocket");l(this,"fosPort");l(this,"useFosTransport");this.host=e,this.port=s,this.protocol=r,this._token=o,this.alias=i,this.authorized=process.env.KOS_ALLOW_ANONYMOUS==="true",this.useFosTransport=!!a,this.fosPort=a==null?void 0:a.port,this.socket=void 0,this.fosSocket=void 0;let c=!1;M.makeObservable(this,{authorized:M.observable,socket:M.observable,fosSocket:M.observable,init:M.action,connectionEstablished:M.computed}),M.reaction(()=>this.connectionEstablished,d=>{d&&(Ne.warn("Connection Established"),j(pe.CONNECTED,pe.CONNECTED),c&&j(pe.RELOAD,pe.RELOAD),c=!0)}),n&&this.init()}get connectionEstablished(){return!this.webSocketSupported||!this.socket||this.useFosTransport&&!this.fosSocket?!1:this.useFosTransport&&this.fosSocket?this.socket.connectionEstablished&&this.fosSocket.connectionEstablished:!this.useFosTransport&&this.socket?this.socket.connectionEstablished:!1}init(){var e,s;if(p.warn(`Initializing WebSocketTransport on ${this.host}:${this.port}`),this.useFosTransport&&(this.fosSocket=Vr.build({host:this.host,port:this.fosPort||9854,protocol:this.protocol,fos:!0})),this.socket=Vr.build({host:this.host,port:this.port,protocol:this.protocol,alias:this.alias,onConnectionLost:()=>{Ne.error("Connection Lost"),j(pe.DISCONNECTED,pe.DISCONNECTED),this.init()}}),globalThis.kosWindowWebsocketOpen){const r={currentTarget:this.socket.socket};(s=(e=this.socket.socket)==null?void 0:e.onopen)==null||s.call(e,r)}return this}_sendSubscriptionMessage(e,s,r=!1,o=!1,n){var g,m,y,v;Ne.debug(`${s} to topic ${e}`);const i=ue(),a=i==null?void 0:i.connId,c=n??a??((g=window==null?void 0:window.kosBridge)==null?void 0:g.call(window,"connId"));Ne.debug(`subscribing with connId ${c}`);const d=c?`dst-addr:${c}
71
+ ${o(n)}`};(r=(s=this.socket)==null?void 0:s.onmessage)==null||r.call(s,a)}else this.oldSend.call(this.socket,e)}else this.oldSend.call(this.socket,e)}};l(fe,"MAX_RECONNECT_ATTEMPTS",10),l(fe,"BASE_DELAY_MS",1e3),l(fe,"MAX_DELAY_MS",3e4);let Yt=fe;class Vh{constructor(e){l(this,"addEventListener");l(this,"dispatchEvent");l(this,"removeEventListener");l(this,"_onclose");l(this,"_onerror");l(this,"_onmessage");l(this,"_onopen");l(this,"messageQueue",[]);l(this,"isSending",!1);$.debug(`called Bridge Transport with addr ${e}`);const s=this;globalThis.kosWindowWebsocketRecv=r=>{if(s.onmessage){const o={data:r};s.onmessage(o)}},$.debug("Opening bridge transport"),globalThis.kosWindowWebsocketOpen(),$.debug("Opened bridge transport"),this._onclose=null,this._onerror=null,this._onmessage=null,this._onopen=null,this.addEventListener=()=>$.debug("not implemented"),this.dispatchEvent=()=>$.debug("not implemented"),this.removeEventListener=()=>$.debug("not implemented")}close(){$.debug("closing")}sendNextMessage(){if(this.messageQueue.length>0){const e=this.messageQueue.shift();globalThis.kosWindowWebsocketSend(e),setTimeout(()=>this.sendNextMessage(),1)}else this.isSending=!1}enqueueMessage(e){this.messageQueue.push(e),this.isSending||(this.isSending=!0,this.sendNextMessage())}send(e){globalThis.kosWindowWebsocketSend(e)}get onmessage(){return this._onmessage}set onmessage(e){this._onmessage=e}get onopen(){return this._onopen}set onopen(e){this._onopen=e}get onclose(){return this._onclose}set onclose(e){this._onclose=e}get onerror(){return this._onerror}set onerror(e){this._onerror=e}}class Yh extends Yt{constructor({host:s,port:r,alias:o}){super({host:s,port:r,Transport:Vh,alias:o,protocol:"kos://"});l(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="response-id"}}class qh extends Yt{constructor({host:s,port:r}){super({host:s,port:r,protocol:"ws://"});l(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="requestId"}}class Wh extends Yt{constructor({host:s,port:r,protocol:o,onConnectionEstablished:n,onConnectionLost:i,alias:a}){super({host:s,port:r,onConnectionEstablished:n,onConnectionLost:i,alias:a,protocol:o});l(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="response-id"}}window.kosEnableMocks=process.env.KOS_MOCK_WS==="true";window.kosLogEvents=process.env.KOS_LOG_WS==="true";class Yr{static build({host:e,port:s,protocol:r,fos:o,alias:n,onConnectionEstablished:i,onConnectionLost:a}){return p.debug("initializing websocket connection"),p.warn(`kosWindowWebsocketOpen: ${globalThis.kosWindowWebsocketOpen?"true":"false"}`),p.warn(`fos: ${o?"true":"false"}`),window.kosMockWs||globalThis.kosWindowWebsocketOpen&&!o?(p.warn("Using bridged message transport"),new Yh({host:e,port:s,protocol:r,onConnectionEstablished:i,onConnectionLost:a,alias:n})):o?new qh({host:e,port:s,protocol:r,alias:n,onConnectionEstablished:i,onConnectionLost:a}):new Wh({host:e,port:s,protocol:r,alias:n,onConnectionEstablished:i,onConnectionLost:a})}}const Qh=ue();Qh.fos&&(window.kosUseFos=!0);const Ln=process.env.KOS_FOS_PORT;window.kosUseFos=!!(window.kosUseFos||process.env.KOS_USE_FOS==="true");window.kosFosPort=Ln?parseInt(Ln):0;const Ne=$.getLogger("web-socket-transport");var ja=(t=>(t.NOT_INITIALIZED="not_initialized",t.INITIALIZED="initialized",t.OFFLINE="OFFLINE",t.ONLINE="ONLINE",t))(ja||{});class nt{constructor({host:e="localhost",port:s=8080,protocol:r="ws://",token:o,initialize:n,alias:i,fos:a}){l(this,"host");l(this,"port");l(this,"protocol");l(this,"_token");l(this,"webSocketSupported",!!globalThis.WebSocket);l(this,"authorized");l(this,"alias");l(this,"socket");l(this,"fosSocket");l(this,"fosPort");l(this,"useFosTransport");this.host=e,this.port=s,this.protocol=r,this._token=o,this.alias=i,this.authorized=process.env.KOS_ALLOW_ANONYMOUS==="true",this.useFosTransport=!!a,this.fosPort=a==null?void 0:a.port,this.socket=void 0,this.fosSocket=void 0;let c=!1;M.makeObservable(this,{authorized:M.observable,socket:M.observable,fosSocket:M.observable,init:M.action,connectionEstablished:M.computed}),M.reaction(()=>this.connectionEstablished,d=>{d&&(Ne.warn("Connection Established"),j(pe.CONNECTED,pe.CONNECTED),c&&j(pe.RELOAD,pe.RELOAD),c=!0)}),n&&this.init()}get connectionEstablished(){return!this.webSocketSupported||!this.socket||this.useFosTransport&&!this.fosSocket?!1:this.useFosTransport&&this.fosSocket?this.socket.connectionEstablished&&this.fosSocket.connectionEstablished:!this.useFosTransport&&this.socket?this.socket.connectionEstablished:!1}init(){var e,s;if(p.warn(`Initializing WebSocketTransport on ${this.host}:${this.port}`),this.useFosTransport&&(this.fosSocket=Yr.build({host:this.host,port:this.fosPort||9854,protocol:this.protocol,fos:!0})),this.socket=Yr.build({host:this.host,port:this.port,protocol:this.protocol,alias:this.alias,onConnectionLost:()=>{Ne.error("Connection Lost"),j(pe.DISCONNECTED,pe.DISCONNECTED),this.init()}}),globalThis.kosWindowWebsocketOpen){const r={currentTarget:this.socket.socket};(s=(e=this.socket.socket)==null?void 0:e.onopen)==null||s.call(e,r)}return this}_sendSubscriptionMessage(e,s,r=!1,o=!1,n){var g,m,y,v;Ne.debug(`${s} to topic ${e}`);const i=ue(),a=i==null?void 0:i.connId,c=n??a??((g=window==null?void 0:window.kosBridge)==null?void 0:g.call(window,"connId"));Ne.debug(`subscribing with connId ${c}`);const d=c?`dst-addr:${c}
72
72
  `:"",u=r?`subscribe:${e}`:o?`type:fos.broker
73
73
  cmd:${s}
74
74
  ${d}topics:${e}
75
75
  `:`${d}type:kos.broker.${s}
76
76
 
77
- ["${e}"]`;if(r?(m=this.fosSocket)==null?void 0:m.connectionEstablished:(y=this.socket)==null?void 0:y.connectionEstablished){const E=r?this.fosSocket:this.socket;(v=E==null?void 0:E.socket)==null||v.send(u)}else{Ne.debug("no connection adding to offline messages");const E=r?this.fosSocket:this.socket;E==null||E.addOfflineMessage(u)}}subscribeTopic({topic:e,callback:s,fos:r,bridge:o,destinationAddress:n}){const{unsubscribe:i,count:a}=O(e,s);return Ne.debug(`Topic ${e} currently has ${a} subscribers`),this._sendSubscriptionMessage(e,"subscribe",r,o,n),()=>{const{count:c}=i();Ne.debug(`Topic ${e} currently has ${c} subscribers`),c===0&&this._sendSubscriptionMessage(e,"unsubscribe",r,o,n)}}async whenReady(){const e=this;return this.webSocketSupported?(await M.when(()=>{var s,r;return!!((s=e.socket)!=null&&s.connectionEstablished)&&(!e.useFosTransport||!!((r=e.fosSocket)!=null&&r.connectionEstablished))&&e.authorized}),{status:"success"}):{status:"not supported"}}get token(){return this._token}set token(e){this._token=e,this.init()}static host(e="localhost"){return this.getInstance().host=e,this}static port(e=8080){return this.getInstance().port=e,this}static alias(e){this.getInstance().alias=e}static getInstance(e=8080,s){if(!this._instance){const r=window.kosUseFos?{port:window.kosFosPort||8081}:void 0;this._instance=new this({port:e,token:s,fos:r})}return this._instance}}l(nt,"_instance");class Zh{constructor(e){l(this,"config");l(this,"stats");l(this,"filterHistory",[]);l(this,"activePromises",new Set);l(this,"eventQueue",[]);l(this,"rateLimitWindow",new Map);this.config=e,this.stats={eventsReceived:0,batchesProcessed:0,eventsDropped:0,currentQueueSize:0,averageBatchSize:0,processingRate:0,lastProcessedAt:Date.now()}}async*processEvents(e){const s=this.config.batch||{size:1,window:0};if(s.size===1&&!s.window)for await(const r of e)yield*this.processSingleEvent(r);else yield*this.processBatchedEvents(e,s)}async*processSingleEvent(e){if(this.stats.eventsReceived++,!(this.config.filter&&!this.shouldProcessEvent(e))){if(this.config.rateLimit&&!this.checkRateLimit())if(this.config.rateLimit.onExceeded==="drop"){this.stats.eventsDropped++;return}else this.config.rateLimit.onExceeded==="delay"&&await this.waitForRateLimit();if(this.config.backpressure){this.enqueueEvent(e),await this.waitForCapacity();const s=this.dequeueEvent();s&&(yield this.config.transform?this.config.transform([s]):[s],this.updateProcessingStats([s]))}else yield this.config.transform?this.config.transform([e]):[e],this.updateProcessingStats([e])}}async*processBatchedEvents(e,s){const r=s.size||100,o=s.window||1e3;let n=[],i=Date.now();const a=async()=>{if(n.length===0)return;const c=[...n];n=[],i=Date.now();const d=this.config.filter?c.filter(h=>this.shouldProcessEvent(h)):c;if(d.length===0)return;this.config.backpressure&&await this.waitForCapacity();const u=this.config.transform?this.config.transform(d):d;return this.stats.batchesProcessed++,this.updateProcessingStats(d),u};try{for await(const d of e)if(this.stats.eventsReceived++,this.config.backpressure)for(this.enqueueEvent(d);this.eventQueue.length>0;){const u=this.dequeueEvent();u&&n.push(u);const g=Date.now()-i;if(n.length>=r||g>=o){const m=await a();m!==void 0&&(yield m);break}}else{n.push(d);const h=Date.now()-i;if(n.length>=r||h>=o){const g=await a();g!==void 0&&(yield g)}}const c=await a();c!==void 0&&(yield c)}finally{}}shouldProcessEvent(e){if(!this.config.filter)return!0;const s={history:[...this.filterHistory],currentBatch:[],startTime:Date.now()},r=this.config.filter.predicate(e,s);return this.config.filter.historySize&&(this.filterHistory.push(e),this.filterHistory.length>this.config.filter.historySize&&this.filterHistory.shift()),r}checkRateLimit(){if(!this.config.rateLimit)return!0;const e=Date.now(),s=Math.floor(e/this.config.rateLimit.windowMs),r=this.rateLimitWindow.get(s)||0;if(r>=this.config.rateLimit.maxEvents)return!1;this.rateLimitWindow.set(s,r+1);for(const[o]of this.rateLimitWindow)o<s-1&&this.rateLimitWindow.delete(o);return!0}async waitForRateLimit(){if(!this.config.rateLimit)return;const e=Date.now(),o=(Math.floor(e/this.config.rateLimit.windowMs)+1)*this.config.rateLimit.windowMs-e;o>0&&await new Promise(n=>setTimeout(n,o))}async waitForCapacity(){if(!this.config.backpressure)return;const e=this.config.backpressure.maxConcurrent||5,s=this.config.backpressure.maxQueue||1e3;for(;this.activePromises.size>=e;)await Promise.race(this.activePromises);this.eventQueue.length>=s&&this.handleQueueOverflow()}handleQueueOverflow(){if(!this.config.backpressure)return;const e=this.config.backpressure.maxQueue||1e3,s=this.config.backpressure.dropPolicy||"oldest",r=this.config.backpressure.onQueueFull;if(s==="none")return;const o=this.eventQueue.length-e;if(o<=0)return;let n=[];if(s==="oldest"?n=this.eventQueue.splice(0,o):s==="newest"&&(n=this.eventQueue.splice(-o)),this.stats.eventsDropped+=n.length,this.stats.currentQueueSize=this.eventQueue.length,r&&n.length>0)try{r(n)}catch(i){console.warn("Error in onQueueFull callback:",i)}}enqueueEvent(e){if(this.eventQueue.push(e),this.stats.currentQueueSize=this.eventQueue.length,this.config.backpressure){const s=this.config.backpressure.maxQueue||1e3;this.eventQueue.length>s&&this.handleQueueOverflow()}}dequeueEvent(){const e=this.eventQueue.shift();return this.stats.currentQueueSize=this.eventQueue.length,e}updateProcessingStats(e){const s=Date.now(),r=s-this.stats.lastProcessedAt;this.stats.averageBatchSize=(this.stats.averageBatchSize*this.stats.batchesProcessed+e.length)/(this.stats.batchesProcessed+1),this.stats.processingRate=r>0?e.length/(r/1e3):this.stats.processingRate,this.stats.lastProcessedAt=s,this.stats.currentQueueSize=this.eventQueue.length}trackPromise(e){return this.activePromises.add(e),e.finally(()=>this.activePromises.delete(e)),e}getStats(){return{...this.stats}}}class Xh{constructor(e,s,r,o,n){l(this,"disposers",[]);l(this,"activatableDisposers",[]);l(this,"flowControllers",new Map);this.model=e,this.modelData=s,this.modelId=r,this.offlineQueue=o,this.log=n}registerAll(e){var o;const s=((o=this.modelData)==null?void 0:o[J])||{},r=Object.keys(s);this.log.debug(`Found ${r.length} subscriptions in ${this.modelId} (lifecycle: ${e??"any"})`),r.forEach(n=>{const i=s[n],a=i.lifecycle;if(e&&e!==a)return;const c=this.resolvePropKey(n);if(this.log.debug(`Resolved topic: ${n} → ${c}`),i.flow)this.subscribeWithFlowControl(i,c,a);else{const d=this.createHandler(c,i);this.subscribe(i,c,d,a===H.ACTIVATE)}})}deactivate(){this.log.debug(`Deactivating subscriptions for ${this.modelId}`);for(const e of this.activatableDisposers)try{e()}catch(s){this.log.error("Error during subscription disposal",s)}this.activatableDisposers=[]}disposeAll(){const e=[...this.disposers,...this.activatableDisposers];this.log.debug(`Disposing ${e.length} subscriptions for ${this.modelId}`);for(const[s,r]of this.flowControllers)this.log.debug(`Disposing flow controller for ${s}`);this.flowControllers.clear();for(const s of e)try{s()}catch(r){this.log.error("Error during subscription disposal",r)}this.disposers=[],this.activatableDisposers=[]}subscribe(e,s,r,o){const n=e.destinationAddress?this.resolvePropKey(e.destinationAddress):null;if(e.websocket){this.log.debug(`Subscribing to WebSocket topic: ${s}`);const i=nt.getInstance().subscribeTopic({topic:s,callback:r,fos:e.fos,bridge:e.bridge,destinationAddress:n});this.disposers.push(i)}else{this.log.debug(`Subscribing to EventBus topic: ${s}`);const{unsubscribe:i}=O(s,r);o?this.activatableDisposers.push(i):this.disposers.push(i)}}createHandler(e,s){return async r=>{var o;try{const n=(o=r==null?void 0:r.headers)==null?void 0:o["src-addr"],i=s.destinationAddress&&this.resolvePropKey(s.destinationAddress),a=i?n===i:!0,c=this.extractWildcardCapture(e,r,s);if(this.model.isReady()){const d=Gr(r,s.skipParse),u=s.transform(d);if(a&&s.condition(u,this.modelData,r))return this.callHandlerWithWildcard(s,u,c,r)}else{this.log.warn(`Model ${this.modelId} not ready. Queuing message for ${e}`);const d=()=>{const u=Gr(r,s.skipParse),h=s.transform(u);if(a&&s.condition(h,this.modelData,r))return this.callHandlerWithWildcard(s,h,c,r)};this.offlineQueue.enqueue(d)}}catch(n){this.log.error(`Error handling subscription for ${e}`,n)}}}extractWildcardCapture(e,s,r){var n;if(!r.wildcardName||!da(e))return null;const o=((n=s==null?void 0:s.headers)==null?void 0:n.topic)||"";return la(e,o,r.wildcardName)}callHandlerWithWildcard(e,s,r,o){if(r&&Object.keys(r).length>0){const n={...o,wildcardCapture:r};return e.handler.call(this.modelData,s,n,this.modelData)}else return e.handler.call(this.modelData,s,o,this.modelData)}resolvePropKey(e){const s=/.*({PROP_(.+)})/;let r=e.includes("{MODEL_ID}")?e.replace("{MODEL_ID}",this.modelId):e;const o=r.match(s);return o&&o[2]in this.modelData&&(r=r.replace(o[1],this.modelData[o[2]])),r}async subscribeWithFlowControl(e,s,r){this.log.debug(`Setting up flow control for topic: ${s}`);const o=new Zh(e.flow);this.flowControllers.set(s,o);const n=this.createFlowControlHandler(s,e),i=this.startFlowProcessing(e,s,n,o),a=()=>{this.flowControllers.delete(s),i.then(c=>c==null?void 0:c.abort())};r===H.ACTIVATE?this.activatableDisposers.push(a):this.disposers.push(a)}async startFlowProcessing(e,s,r,o){const n=new AbortController;try{let i;if(e.websocket){const a=e.destinationAddress?this.resolvePropKey(e.destinationAddress):null;nt.getInstance().subscribeTopic({topic:s,callback:()=>{},fos:e.fos,bridge:e.bridge,destinationAddress:a}),i=$n(s)}else i=$n(s);return(async()=>{try{for await(const a of o.processEvents(i)){if(n.signal.aborted)break;const c=r(a);c instanceof Promise&&await o.trackPromise(c)}}catch(a){this.log.error(`Flow control error for ${s}:`,a)}})(),n}catch(i){return this.log.error(`Failed to start flow processing for ${s}:`,i),null}}createFlowControlHandler(e,s){return async r=>{var o,n,i,a;try{if(s.condition&&!s.condition(r,this.modelData,r))return;if(this.model.isReady())return s.handler.call(this.modelData,r,r,this.modelData);{this.log.warn(`Model ${this.modelId} not ready. Queuing flow-controlled message for ${e}`);const c=()=>s.handler.call(this.modelData,r,r,this.modelData);this.offlineQueue.enqueue(c)}}catch(c){if(this.log.error(`Error in flow control handler for ${e}:`,c),(n=(o=s.flow)==null?void 0:o.errorHandling)!=null&&n.retry)await this.retryHandler(s,r,c);else if(!((a=(i=s.flow)==null?void 0:i.errorHandling)!=null&&a.continueOnError))throw c}}}async retryHandler(e,s,r){const o=e.flow.errorHandling.retry;let n=r;for(let i=1;i<=o.attempts;i++)try{return this.log.debug(`Retry attempt ${i}/${o.attempts} for handler`),await new Promise(a=>setTimeout(a,o.backoffMs*i)),e.handler.call(this.modelData,s,s,this.modelData)}catch(a){n=a,this.log.warn(`Retry attempt ${i} failed:`,a)}throw this.log.error("All retry attempts failed, throwing last error:",n),n}getFlowControlStats(){const e={};for(const[s,r]of this.flowControllers)e[s]=r.getStats();return e}}function We(t,e){const s=`[Model:${e}]`;return{debug:(...r)=>t.debug(s,...r),info:(...r)=>t.info(s,...r),warn:(...r)=>t.warn(s,...r),error:(...r)=>t.error(s,...r)}}function Jh(t){return!!(t!=null&&t[Ke])&&Object.keys(t[Ke]).length>0}function ef(t){return!!(t!=null&&t[J])&&Object.keys(t[J]).length>0}function tf(t){return!!(t!=null&&t[Ie])&&t[Ie].length>0}class sf{static createAll(e){const{modelId:s,modelTypeName:r,modelData:o}=e,n=kh.create({modelId:s,modelTypeName:r}),i=new Ph(e,We(n,"fsm")),a=new Fh(We(n,"offline-queue")),c=new Sh(e),d=new Ih(e),u={fsm:i,offlineQueue:a,companionManager:c,childResolver:d};if(Jh(o)&&(u.effectManager=new Oh(r,s,o,We(n,"effect"))),ef(o)){const h=We(n,"subscription");u.subscriptionManager=new Xh(e,o,s,a,h),u.onlineLifecycleManager=new Nh(e,We(n,"online"))}return tf(o)&&(u.httpRouteManager=new So(o,We(n,"http-routes"))),u}}const k=$.getLogger("kos-model"),rf="kos.extension.model.loader";class ja{constructor({modelTypeName:e,id:s,modelData:r}){l(this,"_id");l(this,"_status");l(this,"_activeStatus");l(this,"_onlineStatus");l(this,"modelData");l(this,"modelTypeName");l(this,"initialized");l(this,"loaded");l(this,"offlineQueue");l(this,"subscriptionManager");l(this,"effectManager");l(this,"httpRouteManager");l(this,"onlineLifecycleManager");l(this,"companionManager");l(this,"childResolver");l(this,"fsm");this._id=typeof s<"u"?`${s}`:e,this.modelTypeName=e,this.initialized=!1,this.loaded=!1,this.modelData=r,this._status=w.CREATED,this._activeStatus=w.INACTIVE,this._onlineStatus=w.OFFLINE;const o=sf.createAll(this);this.fsm=o.fsm,this.offlineQueue=o.offlineQueue,this.companionManager=o.companionManager,this.childResolver=o.childResolver,o.effectManager&&(this.effectManager=o.effectManager),o.subscriptionManager&&(this.subscriptionManager=o.subscriptionManager),o.httpRouteManager&&(this.httpRouteManager=o.httpRouteManager),o.onlineLifecycleManager&&(this.onlineLifecycleManager=o.onlineLifecycleManager),M.makeAutoObservable(this,{fsm:!1,effectManager:!1,subscriptionManager:!1,onlineLifecycleManager:!1,companionManager:!1,childResolver:!1,offlineQueue:!1}),Th(this)}get companionModels(){return this.companionManager}set status(e){this._status=e}get status(){return this._status}get modelId(){return this._id}get id(){return this._id}get activeStatus(){return this._activeStatus}set activeStatus(e){this._activeStatus=e}get onlineStatus(){return this._onlineStatus}set onlineStatus(e){this._onlineStatus=e}get modelManager(){return globalThis.kos.modelManager}isActive(){return this._status===w.ACTIVE}isOnline(){return this._onlineStatus===w.ONLINE}isReady(){return this._status===w.READY}async deactivate(){var e,s,r;k.debug(`deactivating model ${this.modelTypeName} with id ${this.modelId}`);try{const o=z.getContext(this.modelId);await((s=(e=this.modelData)==null?void 0:e.deactivate)==null?void 0:s.call(e,o)),k.debug(`Model ${this.modelTypeName} with id ${this.modelId} deactivated`),(r=this.subscriptionManager)==null||r.deactivate()}catch(o){throw k.debug(`Model ${this.modelId} failed to deactivated`),o}}async activate(){var e,s,r;k.debug(`activating model ${this.modelTypeName} with id ${this.modelId}`),await It(this,H.ACTIVATE);try{const o=z.getContext(this.modelId);await((s=(e=this.modelData)==null?void 0:e.activate)==null?void 0:s.call(e,o)),k.debug(`Model ${this.modelTypeName} with id ${this.modelId} subscribing to all topics`),(r=this.subscriptionManager)==null||r.registerAll(H.ACTIVATE),k.debug(`Model ${this.modelTypeName} with id ${this.modelId} activated`)}catch(o){throw k.debug(`Model ${this.modelId} failed to activate`),o}}async whenLoaded(){await Rr([{condition:()=>this.status===w.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.loaded,onMatch:()=>{k.debug(`Model ${this.modelId} is loaded`)}}])}async whenInitialized(){await Rr([{condition:()=>this.status===w.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.initialized,onMatch:()=>{k.debug(`Model ${this.modelId} is initialized`)}}])}async whenReady(){await Rr([{condition:()=>this.status===w.FAILED,onMatch:()=>{throw new Error(`Failed to ready model ${this.modelId}`)}},{condition:()=>this.status===w.READY,onMatch:()=>{k.debug(`Model ${this.modelId} is ready`)}}])}async ready(){var e,s,r;if(this.fsm.current===w.READY){k.debug(`already readying model ${this.modelTypeName} with id ${this.modelId} returning`);return}try{k.debug(`readying model ${this.modelTypeName} with id ${this.modelId}`),await It(this,H.READY),await Ea(this,_o.READY,H.READY);const o=z.getContext(this.modelId);await((s=(e=this.modelData)==null?void 0:e.ready)==null?void 0:s.call(e,o)),this.offlineQueue.flush(),(r=this.subscriptionManager)==null||r.registerAll(H.READY),k.debug(`Model ${this.modelId} is ready`);const n={modelId:this.modelId,modelType:this.modelTypeName};j(ua(this.modelTypeName,this.modelId),n),j(ha(this.modelTypeName),n)}catch(o){throw k.error(o),Error(o)}}async load(){var o,n,i,a,c;const e=this[Ls];e&&await e.whenLoaded();const{modelTypeName:s,modelId:r}=this;if(this.fsm.current===w.LOADED||this.fsm.current===w.LOADING){k.debug(`Model ${s} with id ${r} already loaded or loading`);return}k.debug(`Loading model ${s} with id ${r}`),await It(this,H.LOAD);try{const d=z.getContext(r),u=`${rf}.${s}`,h=await S.loader.executeLoader(u,{});h&&(k.info(`Setting loaded context for ${r}, type: ${s}`),d==null||d.set(u,h)),await((n=(o=this.modelData)==null?void 0:o.load)==null?void 0:n.call(o,d)),X(()=>{this.loaded=!0}),k.debug(`Model ${s} with id ${r} successfully loaded`),(i=this.subscriptionManager)==null||i.registerAll(H.LOAD),(a=this.httpRouteManager)==null||a.registerAll(),(c=this.effectManager)==null||c.setup()}catch(d){throw k.error(`Model ${r} failed to load`,d),d}}async unload(){var e,s,r,o,n,i;k.debug(`unloading model ${this.modelTypeName} with id ${this.modelId}`);try{const a=this.getChildren().map(d=>{var u;return(u=d.unload)==null?void 0:u.call(d)}).filter(d=>!!d);await Promise.allSettled(a);const c=z.getContext(this.modelId);await((s=(e=this.modelData)==null?void 0:e.unload)==null?void 0:s.call(e,c)),this.loaded=!1,(r=this.onlineLifecycleManager)==null||r.dispose(),k.debug(`Model ${this.modelTypeName} with id ${this.modelId} unloaded`),(o=this.effectManager)==null||o.disposeAll(),(n=this.subscriptionManager)==null||n.disposeAll(),(i=this.httpRouteManager)==null||i.dispose()}catch(a){throw k.debug(`Model ${this.modelId} failed to unload`),a}}async init(){var n,i,a;const e=this[Ls];e&&await e.whenInitialized();const{modelId:s,modelTypeName:r}=this,o=z.getContext(s);k.debug(`Initializing model ${r} with id ${s}`),await It(this,H.INIT);try{await((i=(n=this.modelData)==null?void 0:n.init)==null?void 0:i.call(n,o)),this.initialized=!0,k.debug(`Model ${r} with id ${s} initialized`),(a=this.onlineLifecycleManager)==null||a.register(),this.registerSubscribers(H.INIT)}catch(c){throw k.error(`Model ${s} failed to initialize`,c),c}}async registerSubscribers(e){var s;k.debug(`registering subscribers in ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.registerAll(e)}async online(){var s,r;k.debug(`online model ${this.modelTypeName} with id ${this.modelId}`),this.registerSubscribers();const e=z.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.online)==null?void 0:r.call(s,e))}async offline(){var s,r,o;k.debug(`offline model ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.disposeAll();const e=z.getContext(this.modelId);await((o=(r=this.modelData)==null?void 0:r.offline)==null?void 0:o.call(r,e))}accept(e){e.visit(this)}getChildren(){return this.childResolver.resolve()}addCompanionModel(e){this.companionManager.add(e)}clearCompanionModels(){this.companionManager.clear()}}const Ba=t=>typeof t=="function",Rn=p.createLogger({name:"kos-model-instantiator"});class of{constructor(e,s){this.registry=e,this.cache=s}createModelInstance(e,s,r={}){const o=this.registry.models[e];if(!o)throw new Error(`No model registered for type ${e}`);const n=o.singleton?e:s;if(this.cache.restoreFromDeleteCache(n),!this.cache.hasModel(n)){Rn.debug(`Creating model instance: ${e} [${n}]`);const a=o.create?o.create({modelTypeId:e,id:n,options:r}):new o.class(n,r),c=new ja({modelTypeName:e,id:n,modelData:a});this.cache.addModel(c),this._createCompanionModels(c,r)}const i=this.cache.getModelById(n);if(!i)throw Rn.error(`Model ${e} [${n}] not found in cache`),new Error(`Model ${e} [${n}] not found in cache`);return{model:i,data:i.modelData}}_createCompanionModels(e,s){var n;const r=e.modelTypeName,o=((n=this.registry.companionModels)==null?void 0:n[r])||[];for(const{type:i}of o){const a=Ba(i)?i(e.modelData,s):i;if(!a)continue;const c=`${a}-${e.modelId}`,d=this.createModelInstance(a,c,{data:s,companionParent:e.modelData,kosParentId:e.modelId});d!=null&&d.model&&(d.model[Ls]=e,e.addCompanionModel(d.model))}}}let nf=class{constructor(e){this._registry=e}get registry(){return this._registry}getModelTypeRegistry(e){const s=this.registry.models[e];if(!s)throw new Error(`No registration for model type ${e}`);return s}registerModel(e){const s=e.type;this.registry.models[s]||(this.registry.models={...this.registry.models,...e.registration})}registerCompanionModel(e,s){var r,o;(r=this.registry).companionModels??(r.companionModels={}),(o=this.registry.companionModels)[e]??(o[e]=[]),this.registry.companionModels[e].some(n=>n.type===s)||this.registry.companionModels[e].push({type:s})}getModelSubscriptions(e){var s;return((s=this.getModelTypeRegistry(e))==null?void 0:s.subscriptions)||{}}getDataModelBuilder(e){var r;const s=(r=this.getModelTypeRegistry(e))==null?void 0:r.builder;if(!s)throw new Error(`No builder found for model type ${e}`);return s}getModelFactory(e){return yt(e)}};const Ka=10,An=p.createLogger({name:"kos-model-manager"});class Ha{constructor(){l(this,"cache");l(this,"instantiator");l(this,"dependencies");l(this,"_registry");globalThis.kos=globalThis.kos||{},this.dependencies=new Zu,globalThis.kos.modelManager=this,globalThis.kos.resolveKosModel=e=>{const s=this.getModelById(e);if(s)return s.modelData||{}},globalThis.kos.kosModelJson=e=>{var r,o;const s=this.getModelById(e);if(s)return((o=(r=s.modelData).toJSON)==null?void 0:o.call(r))||{}},globalThis.kos.kosModelDebug=e=>{var r;const s=this.getModelById(e);if(s)return((r=s.modelData)==null?void 0:r.debugState)||{}},globalThis.kos.kmd=globalThis.kos.kosModelDebug,globalThis.kos.kmj=globalThis.kos.kosModelJson}static create(e,s){const r=this.getInstance(s);return r._registry=new nf(e),r.cache=new Xu(e.preloadModels),r.instantiator=new of(e,r.cache),r}static getInstance(e){var s,r;return(!((s=globalThis.kos)!=null&&s.modelManager)||e)&&(An.debug("Creating new instance of KosModelManager"),new this),(r=globalThis.kos)==null?void 0:r.modelManager}get registry(){return this._registry.registry}get preloadedModels(){return this.cache.preload(e=>(An.debug(`preloading ${e}`),typeof e=="string"?this.createModelInstance(e).model:this.createModelInstance(e.modelType,e.modelId,e.options).model))}get models(){return this.cache.models}getModelById(e){return this.cache.getModelById(e)}addModel(e){return this.cache.addModel(e)}removeModel(e){this.cache.removeModel(e.modelId)}hasModel(e){return this.cache.hasModel(e)}getModelsByType(e,s){return Array.from(this.models).filter(r=>r.modelTypeName===e).filter(r=>s?s(r.modelData):!0).map(r=>r.modelData)}getModelSubscriptions(e){return this._registry.getModelSubscriptions(e)}getDataModelBuilder(e){return this._registry.getDataModelBuilder(e)}getModelFactory(e){return yt(e)}addDependency(e,s){this.cache.restoreFromDeleteCache(s),this.dependencies.add(e,s)}removeDependency(e,s){this.dependencies.remove(e,s)}async reloadModel(e){if(e.id){const s=this.getModelById(e.id);s&&await s.fsm.transitionTo(A.RESET,w.RESETTING)}}async initiateDestroyModel(e){if(!e.id)throw new Error("Model ID is required");if(!this.dependencies.canDestroy(e.id))return;const s=this.getModelById(e.id);s&&(this.cache.markForDeletion(s),ra.addToDeletionQueue(e.id,setTimeout(()=>this.destroyModel(s),Ka)))}async destroyModel(e){var s;e!=null&&e.modelId&&this.dependencies.canDestroy(e.modelId)&&(await((s=e.unload)==null?void 0:s.call(e)),this.removeModel(e))}createModelInstance(e,s,r={}){return this.instantiator.createModelInstance(e,s,r)}registerCompanionModel(e,s){this._registry.registerCompanionModel(e,s)}registerModel(e){this._registry.registerModel(e)}}var Ds=(t=>(t.CREATING="creating",t.CREATED="created",t.INITIALIZING="initializing",t.INITIALIZED="initialized",t.LOADING="loading",t.LOADED="loaded",t.ONLINE="online",t.READYING="readying",t.READY="ready",t.OFFLINE="offline",t.UNLOADING="unloading",t.UNLOADED="unloaded",t.RELOADING="reloading",t))(Ds||{}),et=(t=>(t.CREATE="create",t.INITIALIZE="init",t.READY="ready",t.GO_ONLINE="go_online",t.GO_OFFLINE="go_offline",t.UNLOAD="unload",t.RELOAD="reload",t))(et||{});const af=t=>{const e=b.createMachine("offline",{online:b.state(b.transition("go_offline","offline",b.action(()=>{t.offline(),M.runInAction(()=>{t.isOnline=!1})}))),offline:b.state(b.transition("go_online","online",b.action(()=>{t.online(),M.runInAction(()=>{t.isOnline=!0})})))}),s=b.interpret(e,n=>$.debug(n.machine.current)),r=b.createMachine({creating:b.state(b.transition("create","created")),created:b.state(b.immediate("initializing")),initializing:b.invoke(()=>t.init(),b.transition("done","initialized")),initialized:b.state(b.immediate("loading")),loading:b.invoke(()=>t.load(),b.transition("done","loaded")),loaded:b.state(b.immediate("readying"),b.transition("unload","unloading")),readying:b.invoke(()=>t.ready(),b.transition("done","ready",b.action(()=>{M.runInAction(()=>{t.status="ready"})}))),reloading:b.invoke(()=>t.reload(),b.transition("done","loading")),ready:b.state(b.transition("reload","reloading"),b.transition("unload","unloaded",b.action(t.unload.bind(t))),b.transition("go_online","ready",b.action(()=>{s.send("go_online")})),b.transition("go_offline","ready",b.action(()=>{s.send("go_offline")}))),unloaded:b.state()});return{service:b.interpret(r,n=>$.debug(n.machine.current)),online:s}},ae=async t=>{if(t.id){const e=I.getInstance().modelManager.getModelById(t.id);if(!e)throw new Error(`Model with ID ${t.id} not found`);await(e==null?void 0:e.whenReady())}else throw new Error("Data model must have a valid ID");return t},He=async t=>{await I.getInstance().whenReady(),await I.getInstance().modelManager.initiateDestroyModel(t)},cf=async t=>{if(await I.getInstance().whenReady(),!t.id)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t.id);e&&await e.fsm.transitionTo(A.UNLOAD,w.UNLOADED)},lf=async t=>{await I.getInstance().whenReady(),await I.getInstance().modelManager.reloadModel(t),p.debug(`reload model initiated for model ${t.id}, model ready: ${Fs(t)} - ${Date.now()} `),await ae(t),p.debug(`reload model complete for model ${t.id}, model ready: ${Fs(t)} - ${Date.now()} `)},df=async t=>{if(await I.getInstance().whenReady(),!t)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t);return e==null?void 0:e.modelTypeName},za=async t=>{if(await I.getInstance().whenReady(),!t)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t);return{model:e==null?void 0:e.modelData,type:e==null?void 0:e.modelTypeName}},ve=t=>{if(!t)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t);return{model:e==null?void 0:e.modelData,type:e==null?void 0:e.modelTypeName}},Ga=(t,e)=>{if(!t)throw new Error("Model type is required");return I.getInstance().modelManager.getModelsByType(t).filter(o=>Object.keys(e).every(n=>o[n]===e[n]))},uf=(t,e)=>Ga(t,e)[0],hf=(t,e)=>{if(!t.id)throw new Error("Model ID is required");const s=I.getInstance().modelManager.getModelById(t.id);if(!s)throw new Error("Model not found");const r=s.companionModels.get(e);return r==null?void 0:r.modelData},Va=t=>{if(!t.id)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t.id);if(!e)throw new Error("Model not found");return Array.from(e.companionModels.all()).map(r=>r.modelData)},ff=t=>{if(!t)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t);if(!e)throw new Error("Model not found");return e.companionModels.data},Yr=(t,e)=>{const s=I.getInstance().modelManager.getModelById(t);if(!s){p.info(`Model not found for id ${t}`);return}return Array.from(s.companionModels.all()).find(o=>e(o.modelData))},he=t=>e=>Object.getPrototypeOf(e).modelTypeId===t,Fs=t=>{const e=I.getInstance().modelManager.getModelById(t.id);if(!e)throw new Error("Model not found");return e.isReady()},gf=p.createLogger({name:"kos-model-factory"}),Kt={byModelType:t=>I.getInstance().modelManager.getModelFactory(t),getModelInstance:(t,e,s)=>{const r=Kt.byModelType(e);if(!r)throw gf.error(`No registered factory found for model type ${e}. Please register a factory for this model type. `),Error(`No factory found for model type ${e}`);return r.build(t,s)}},te={Factory:{create:t=>e=>(s,r)=>(r&&z.setParentContext(e,r),Kt.getModelInstance(e,t,s))},Singleton:{create:t=>(e,s)=>(s&&z.setParentContext(t,s),Kt.getModelInstance(t,t,e))},Model:{instance:t=>e=>Kt.getModelInstance(e,t)}};window.KosRegistry=window.KosRegistry||{coreModels:new Map,preloadModels:[],companionModels:new Map,models:new Map};const xn=window.KosRegistry.coreModels,Ar=window.KosRegistry.preloadModels,xr=window.KosRegistry.companionModels,ys=window.KosRegistry.models,C={model:{registerLegacyModel:t=>(e,s)=>(xn.set(e,s),{preload:C.model.preloadModel(t),model:C.model.register(t),companion:C.companion.register(t),legacy:C.model.registerLegacyModel(t),root:t}),preloadModel:t=>e=>(Ar.includes(e)||Ar.push(e),{preload:C.model.preloadModel(t),model:C.model.register(t),companion:C.companion.register(t),legacy:C.model.registerLegacyModel(t),root:t}),register:t=>(e,s)=>{const r=Pr(e)?e.registration():e;return ys.set(r.type,r),Pr(e)&&e.relatedModels.forEach(o=>ys.set(o.type,o.registration())),I.getInstance().isReady&&(I.getInstance().modelManager.registry.models[r.type]||(console.info(`Model with type ${r.type} doesn't exist. Adding new registration`),I.getInstance().modelManager.registry.models[r.type]=r.registration[r.type],Pr(e)&&e.relatedModels.forEach(o=>I.getInstance().modelManager.registry.models[o.type]=o.registration().registration))),s&&C.model.preloadModel(t)(r.type),{preload:C.model.preloadModel(t),model:C.model.register(t),companion:C.companion.register(t),legacy:C.model.registerLegacyModel(t),root:t}},get:t=>ys.get(t),getAll:()=>Array.from(ys.entries()),getPreloadModels:()=>Ar,getLegacyModels:()=>Array.from(xn.entries()).reduce((t,[e,s])=>(t[e]=s,t),{})},companion:{register:t=>(e,s)=>{const r=xr.get(e)||[];return r.push(s),xr.set(e,r),{preload:C.model.preloadModel(t),model:C.model.register(t),companion:C.companion.register(t),legacy:C.model.registerLegacyModel(t),root:t}},getAll:()=>Array.from(xr.entries())}},Ya=C.model.registerLegacyModel,qa=C.model.register,pf=C.companion.register,mf=C.model.preloadModel,Wa=t=>typeof t.updateModel=="function",Pr=t=>t.registration!==void 0&&typeof t.registration=="function";class Qa{constructor(e){l(this,"singleton");l(this,"type");l(this,"loader");l(this,"class");l(this,"guard");l(this,"factory");l(this,"relatedModels",[]);this.singleton=e.singleton,this.guard=he(e.type),this.type=e.type,this.loader=`kos.extension.model.loader.${e.type}`,this.factory=e.factory,this.class=e.class}addRelatedModel(e){this.relatedModels.push(e)}registerRelatedModels(){this.relatedModels.forEach(e=>e.register())}register(){C.model.register({})(this.registration()),this.registerRelatedModels()}}class we extends Qa{constructor(e){super({...e,singleton:!1,factory:te.Factory.create(e.type)})}instance(e){const s=this.factory(e);return{get:()=>{const r=ve(e);if(!r)throw new Error("Model not found with id "+e);if(this.guard(r))return r;throw new Error("Model is not of type "+this.type)},forceUpdate:{options:r=>({build:()=>{const o=s(r);if(this.guard(o)){if(Wa(o))o.updateModel(r);else throw new Error(`Model ${this.type} is not updateable. Please implement UpdateAware interface`);return o}else throw new Error("Model is not of type "+this.type)}})},options:r=>({build:()=>{const o=s(r);if(this.guard(o))return o;throw new Error("Model is not of type "+this.type)}})}}registration(){return{type:this.type,predicate:this.guard,registration:{[this.type]:{class:this.class,singleton:!1}},factory:this.factory}}}class Ee extends Qa{constructor(e){super({...e,singleton:!0,factory:te.Singleton.create(e.type)})}instance(){const e=this.factory;return{get:()=>{const r=ve(this.type);if(!r)throw new Error("Model not found with id "+this.type);if(this.guard(r))return r;throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(r).modelTypeId}`)},forceUpdate:{options:r=>({build:()=>{const o=e(r);if(this.guard(o)){if(Wa(o))o.updateModel(r);else throw new Error(`Model ${this.type} is not updateable. Please implement UpdateAware interface`);return o}else throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(o).modelTypeId}`)}})},options:r=>({build:()=>{const o=e(r);if(this.guard(o))return o;throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(o).modelTypeId}`)}})}}registration(){return{type:this.type,predicate:this.guard,registration:{[this.type]:{class:this.class,singleton:!0}},factory:this.factory}}}const Y=p.createLogger({name:"kos-core"}),yf=()=>{const t=ue(),e=t==null?void 0:t.alias,s=process.env.KOS_CONNECTION_ALIAS;return e||s||void 0},bf=()=>{const t=window.location.protocol,e=ue(),s=e==null?void 0:e.host;let r;try{r=new URL(s).protocol==="https:"?"wss://":"ws://"}catch{}return r||(t==="https:"?"wss://":"ws://")},wf=()=>{const t=window.location.hostname,e=process.env.KOS_HOST,s=ue(),r=s==null?void 0:s.host;let o;try{o=new URL(r).hostname}catch{}return o??e??t},vf=()=>{const t=window.location.port,e=process.env.KOS_PORT,s=ue(),r=s==null?void 0:s.host;let o;try{o=new URL(r).port}catch{}return o??e??t},Mf=(t,e)=>{let s;return{promise:new Promise((n,i)=>{s=setTimeout(()=>{e?p.error(`Model ${e.modelId} - ${e.modelTypeName} preloading - timed out after ${t}ms`):p.error(`KOS Core preloading timed out after ${t}ms`),i(new Error(`Model ${e==null?void 0:e.modelId} - ${e==null?void 0:e.modelTypeName} - timed out after ${t}ms`))},t)}),cancel:()=>{s&&clearTimeout(s)}}},Pn=t=>typeof t.reload=="function",Ef=t=>typeof t.unload=="function";var Za=(t=>(t.LOGGED_IN="logged_in",t.LOGGED_OUT="logged_out",t))(Za||{});class I{constructor(e){l(this,"fsmService");l(this,"status");l(this,"initialized");l(this,"loaded");l(this,"_transport");l(this,"modelManager");l(this,"authState");l(this,"isOnline");l(this,"_reloading");l(this,"_unloading");l(this,"connectionAlias");this.initialized=!1,this.connectionAlias=e,this.loaded=!1,this.isOnline=!1,this.status=Ds.CREATED,this.authState="logged_out",this._reloading=!1,this._unloading=!1,M.makeAutoObservable(this),O("token",a=>{a&&(this.transport.token=a.body)}),O(pe.DISCONNECTED,async()=>{await Promise.allSettled(this.modelManager.models.map(async a=>{var c,d;try{await((c=a.offline)==null?void 0:c.call(a))}catch(u){Y.error(`model ${a.modelId} offline() threw:`,u)}(d=a.onlineLifecycleManager)==null||d.dispose()})),this.fsmService.service.send(et.GO_OFFLINE)}),O(pe.CONNECTED,async()=>{await this.whenReady(),await Promise.allSettled(this.modelManager.models.map(async a=>{var c,d;(c=a.onlineLifecycleManager)==null||c.register();try{await((d=a.online)==null?void 0:d.call(a))}catch(u){Y.error(`model ${a.modelId} online() threw:`,u)}})),this.fsmService.service.send(et.GO_ONLINE)}),O("/studioServer/auth/LOGGED_IN",()=>{this.authState="logged_in",this.transport.authorized=!0}),O("/studioServer/auth/LOGIN_REQUIRED",()=>{this.authState="logged_out",this.transport.authorized=!1}),O(pe.RELOAD,()=>{this.fsmService.service.send(et.RELOAD)}),O("/studio/project/reload",()=>{this.fsmService.service.send(et.RELOAD)});const s=nt.getInstance(),r=wf(),o=vf(),n=bf();s.host=r,s.port=Number.parseInt(o),s.protocol=n,process.env.KOS_ALLOW_ANONYMOUS==="true"&&(s.authorized=!0);const i=yf()??e;i&&(s.alias=i.replace("{{TIMESTAMP}}",Date.now().toString())),this._transport=s.init(),this.fsmService=af(this),this.fsmService.service.send(et.CREATE)}get onlineStatus(){return this.isOnline&&!this._reloading&&!this._unloading}get reloading(){return this._reloading}get unloading(){return this._unloading}async reload(){var o,n,i,a;const e=Date.now();if(this._reloading){Y.info("reload already in progress");return}this._reloading=!0,Y.warn("reloading KOS Core"),Y.warn("reloading preloaded models");const s=this.modelManager;for(const c of s.preloadedModels)Pn(c.modelData)&&(Y.info(`reloading model ${c.modelId}`),(o=c.unload)==null||o.call(c),await c.modelData.reload(),(n=c.registerSubscribers)==null||n.call(c),Y.info(`reloading model ${c.modelId} complete`));for(const c of s.models)!s.preloadedModels.includes(c)&&Pn(c.modelData)&&((i=c.unload)==null||i.call(c),await c.modelData.reload(),(a=c.registerSubscribers)==null||a.call(c));const r=Date.now()-e;setTimeout(()=>{M.runInAction(()=>{Y.warn("reloading KOS Core complete"),this._reloading=!1})},1e3-r)}async online(){Y.debug("KOS Core going online"),await this._transport.whenReady(),Y.debug("KOS Transport Ready. Calling online() for models"),j("/kosCore/online","/kosCore/online"),console.timeEnd("kosCore:startup")}async offline(){Y.debug("KOS Core going offline"),j("/kosCore/offline","/kosCore/offline")}async unload(){var o;Y.debug("Unloading KOS Core");const e=Date.now();this._unloading=!0,Y.debug("unloading KOS Core");const s=this.modelManager;for(const n of s.models)Ef(n.modelData)&&((o=n.unload)==null||o.call(n));const r=Date.now()-e;setTimeout(()=>{M.runInAction(()=>{this._unloading=!1})},1e3-r)}async whenReady(){await M.when(()=>this.status===Ds.READY)}async ready(){Y.debug("Readying KOS Core"),await this._transport.whenReady();const e=this.modelManager.preloadedModels.map(o=>({modelId:o.modelId,model:o,promise:o.whenReady()})),r=(await Promise.allSettled(e.map(o=>{const{promise:n,cancel:i}=Mf(5e3,o.model);Promise.race([o.promise.then(()=>{i()}),n])}))).filter(o=>o.status==="rejected");if(r.length)throw Y.error(`There were ${r.length} failed models on model preloading`),Error(`There were ${r.length} failed models on model preloading`);Y.debug("leaving kos-core ready() ")}get isReady(){return this.status===Ds.READY}set transport(e){this._transport=e}get transport(){return this._transport}get coreInitialized(){return this.initialized}get modelsLoaded(){return this.loaded}async init(){Y.debug("entering kos-core init()"),console.time("kosCore:startup"),console.time("kosCore:init"),await this._transport.whenReady(),this.initialized=!0,Y.debug("initialized - leaving kos-core init()"),console.timeEnd("kosCore:init")}async load(){Y.debug("entering kos-core load()"),console.time("kosCore:load"),this.loaded=!0,Y.debug("loaded - leaving kos-core load()"),console.timeEnd("kosCore:load")}static create(e,s,r){var i,a,c;const o=this.getInstance({reset:s,connectionAlias:r});(i=e.extensions)!=null&&i.dataMapper&&Object.keys(e.extensions.dataMapper).forEach(d=>{var h,g;const u=(g=(h=e.extensions)==null?void 0:h.dataMapper)==null?void 0:g[d];u&&(Array.isArray(u)?u.forEach(m=>{S.dataMapper.registerDataMapper(d,m)}):S.dataMapper.registerDataMapper(d,u))}),(a=e.extensions)!=null&&a.propertyMapper&&Object.keys(e.extensions.propertyMapper).forEach(d=>{var h,g;const u=(g=(h=e.extensions)==null?void 0:h.propertyMapper)==null?void 0:g[d];u&&S.propertyMapper.registerPropertyMapper(d,u)}),(c=e.extensions)!=null&&c.contextLoader&&Object.keys(e.extensions.contextLoader).forEach(d=>{var h,g;const u=(g=(h=e.extensions)==null?void 0:h.contextLoader)==null?void 0:g[d];u&&S.loader.registerLoader(d,u)}),C.model.getAll().forEach(([,d])=>{e.models={...e.models,...d.registration}}),e.models={...e.models,...C.model.getLegacyModels()},C.companion.getAll().forEach(([d,u])=>{e.companionModels={...e.companionModels},e.companionModels[d]=e.companionModels[d]||[];for(const h of u)e.companionModels[d].push({type:h})}),C.model.getPreloadModels().forEach(d=>{e.preloadModels.includes(d)||e.preloadModels.push(d)});const n=Ha.create(e,s);return o.modelManager=n,o}static getInstance(e){return this._instance=window.KosCore,(!this._instance||e!=null&&e.reset)&&(window.KosCore=new this(e==null?void 0:e.connectionAlias),this._instance=window.KosCore),this._instance}}l(I,"_instance");function qr(t){const e=new Uint8Array(t);let s="";for(let r=0;r<e.byteLength;r++)s+=String.fromCharCode(e[r]);return btoa(s)}function Tf(t){const e=atob(t),s=new Uint8Array(e.length);for(let r=0;r<e.length;r++)s[r]=e.charCodeAt(r);return s.buffer}async function _f(t){return await t.arrayBuffer()}function If(t,e){return new Blob([t],{type:e})}async function Sf(t){const e={},s=[],r=[];t.forEach((o,n)=>{r.push([n,o])});for(const[o,n]of r)if(n instanceof File){const i=await n.arrayBuffer();s.push({name:o,filename:n.name,type:n.type,data:qr(i)})}else e[o]=n.toString();return{fields:e,files:s}}function Of(t){return new ReadableStream({async start(){},async pull(e){await t(e)},cancel(){}})}async function $f(t){if(!t)return{data:"",contentType:"text/plain"};if(typeof t=="string")return{data:t,contentType:"text/plain"};if(t instanceof ArrayBuffer||t instanceof Uint8Array){let e;return t instanceof Uint8Array?(e=new ArrayBuffer(t.byteLength),new Uint8Array(e).set(t)):e=t,{data:qr(e),contentType:"application/octet-stream",encoding:"base64"}}if(t instanceof Blob){const e=await _f(t);return{data:qr(e),contentType:t.type||"application/octet-stream",encoding:"base64"}}if(t instanceof FormData){const e=await Sf(t);return{data:JSON.stringify(e),contentType:"multipart/form-data",encoding:"json"}}throw new Error("Unsupported body type")}const Ue=p.createLogger({name:"kos-fetch"}),Df=process.env.KOS_WS_TIMEOUT?parseInt(process.env.KOS_WS_TIMEOUT):3e4,Cf=()=>new Promise(t=>{setTimeout(()=>{t(!0)},0)}),Rf=t=>{if("timeout"in AbortSignal)return AbortSignal.timeout(t);const e=new AbortController;return setTimeout(()=>{e.abort(new DOMException(`Request timed out after ${t}ms`,"TimeoutError"))},t),e.signal},Af=t=>{if("any"in AbortSignal)return AbortSignal.any(t);const e=new AbortController;for(const s of t){if(s.aborted)return e.abort(s.reason),e.signal;s.addEventListener("abort",()=>e.abort(s.reason),{once:!0})}return e.signal},xf=t=>t!=null&&t.studio?Sa:t!=null&&t.fos?Oa:$a,Pf=async(t,e)=>{const s=I.getInstance().transport;await s.whenReady();const r=pt(),o=new URL(t),n=`${o.pathname}${o.search}`;Ue.debug(`path: ${n}`);const i=(e==null?void 0:e.timeout)||Df,a=xf(e),c=Rf(i),d=e!=null&&e.signal?Af([e.signal,c]):c,u=await $f(e==null?void 0:e.body),h={};u.contentType&&(h["content-type"]=u.contentType),u.encoding&&(h["content-encoding"]=u.encoding);const g=ke(a({path:n,requestId:r,method:(e==null?void 0:e.method)||"GET",destinationAddress:(e==null?void 0:e.destinationAddress)||"",ordered:e==null?void 0:e.ordered,tracker:e==null?void 0:e.tracker,bridge:e==null?void 0:e.bridge,headers:{...e==null?void 0:e.headers,...h}}),u.data);return new Promise((m,y)=>{let v=null;if(d.aborted){const x=d.reason;(x==null?void 0:x.name)==="TimeoutError"?Ue.error(`Timeout occurred - url: ${t}`):Ue.debug(`Request aborted - url: ${t}`),y(x||new DOMException("Aborted","AbortError"));return}const E=()=>{v&&v();const x=d.reason;(x==null?void 0:x.name)==="TimeoutError"?Ue.error(`Timeout occurred - url: ${t}`):Ue.debug(`Request aborted - url: ${t}`),y(x||new DOMException("Aborted","AbortError"))};d.addEventListener("abort",E,{once:!0});const _=O(r,x=>{d.removeEventListener("abort",E);const D=(x==null?void 0:x.headers)||{},P=D["content-type"]||"text/plain",W=D["content-encoding"],re=(x==null?void 0:x.body)||"";let L=re;if(W==="base64"&&re)try{L=Tf(re)}catch(V){Ue.error("Failed to decode base64 response",V)}const Ce={headers:Da(D),status:D.status&&parseInt(D.status)||200,ok:D.status==="200",json:async()=>{try{if(typeof L=="string")return L.length?JSON.parse(L):null;{const ce=new TextDecoder().decode(L);return ce.length?JSON.parse(ce):null}}catch{throw Error("Not a JSON response")}},text:async()=>typeof L=="string"?L:new TextDecoder().decode(L),arrayBuffer:async()=>L instanceof ArrayBuffer?L:new TextEncoder().encode(L).buffer,blob:async()=>L instanceof ArrayBuffer?If(L,P):new Blob([L],{type:P}),formData:async()=>{const V=new FormData;if(P==="multipart/form-data"&&typeof L=="string")try{const ce=JSON.parse(L);ce.fields&&Object.entries(ce.fields).forEach(([gs,Et])=>{V.append(gs,Et)}),ce.files&&Ue.warn("File reconstruction in FormData not fully implemented")}catch{throw new Error("Failed to parse FormData")}return V},body:e!=null&&e.stream?Of(async V=>{if(L instanceof ArrayBuffer)V.enqueue(new Uint8Array(L));else{const ce=new TextEncoder;V.enqueue(ce.encode(L))}V.close()}):Ca(typeof L=="string"?L:""),redirected:!1,statusText:"",type:"basic",url:"",clone:function(){return{...this}},bodyUsed:!1};_.unsubscribe(),Cf().then(()=>m(Ce))});v=_.unsubscribe;const N=e!=null&&e.fos?s.fosSocket:s.socket;if(!N)throw Error(`No web socket transport available: ${e}`);N==null||N.send(g)})};exports.BASE_URL="kos:";exports.kosFetch=Pf;if(process.env.KOS_MOCK_FETCH==="true"){const t=process.env.KOS_PORT||"9999";exports.kosFetch=fetch,exports.BASE_URL=`http://localhost:${t}`}const Lf=p.createLogger({name:"kos-model-visitor",group:"kos-ui-core"});class kf{constructor(){l(this,"visitedModels",new Set);this.visitedModels=new Set}start(e){var r;if(e.id===void 0)throw new Error("rootModel must have an id");const s=I.getInstance().modelManager.getModelById(e.id);if(!s)throw new Error(`Could not find rootModel with id: ${e.id}`);this.visitedModels.clear(),(r=s.accept)==null||r.call(s,this)}visit(e){var r;if(this.visitedModels.has(e.modelId)){Lf.info(`model ${e.modelId} already visited`);return}const s=!!this.visitModel(e.modelData,this);this.visitedModels.add(e.modelId),!s&&((r=e.getChildren)==null||r.call(e).forEach(o=>{var n;(n=o.accept)==null||n.call(o,this)}))}}const Xa=()=>({isMock:!1,URL:exports.BASE_URL}),bs=p.createLogger({name:"kos-service-request"}),Ln="errUnknown";async function ws(t,e,s,r,o){const n=r!=null&&r.path?Object.keys(r.path).reduce((d,u)=>String(d).replace(`{${u}}`,r==null?void 0:r.path[u]),String(t)):String(t),i=r!=null&&r.query?Object.keys(r.query).map(d=>`${d}=${r.query[d]}`).join("&"):"",a=`${Xa().URL}${n}${i?`?${encodeURIComponent(i)}`:""}`;bs.debug(`fullUrl: ${a}`);const c={method:String(e).toUpperCase(),body:null,...s};o&&(c.body=JSON.stringify(o));try{const d=await exports.kosFetch(a,c);return d.status<200||d.status>=400?[`${d.statusText||Ln}`,null]:[null,(await d.json()).data]}catch(d){if(d instanceof DOMException){if(d.name==="TimeoutError")return bs.error(`Request timed out: ${a}`),["Request timed out",null];if(d.name==="AbortError")return bs.debug(`Request aborted: ${a}`),["Request aborted",null]}return bs.error(`Unexpected error during fetch: ${d}`),[d instanceof Error?d.message:Ln,null]}}function Oo(){return{get:(t,e,s)=>ws(t,"get",s,e),post:(t,e,s,r)=>ws(t,"post",r,e,s),put:(t,e,s,r)=>ws(t,"put",r,e,s),delete:(t,e,s,r)=>ws(t,"delete",r,e,s)}}class Ja{constructor(){l(this,"middlewares",[])}use(e){this.middlewares.push(e)}async execute(e){let s=0;const r=async()=>{s++,s<this.middlewares.length&&await this.middlewares[s](e,r)};await this.middlewares[s](e,r)}}const Ff=async(t,e)=>{const s=new Ja;e.forEach(o=>s.use(o));const r={data:t,result:{}};return await s.execute(r),r.result},yt=t=>({type:t,build:(e,s)=>I.getInstance().modelManager.createModelInstance(t,e,s).data,buildAsync:async(e,s)=>{const r=I.getInstance().modelManager.createModelInstance(t,e,s);return await r.model.whenInitialized(),r.data}}),Nf=t=>{I.getInstance().modelManager.registerModel(t)},Uf=(t,e)=>{I.getInstance().modelManager.registerCompanionModel(t,e)},ec=Symbol("KosObservableData");class tc{constructor(){l(this,"map");l(this,"atomMap",new Map);l(this,"proxyHandler",{get:(e,s)=>{var r;return e[s]!==void 0?e[s]:this.atomMap.has(s)&&(r=this.atomMap.get(s))!=null&&r.reportObserved()?this.getValue(s):this.getValue(s)},set:(e,s,r)=>{var o;return this.setValue(s,r),this.atomMap.has(s)||this.atomMap.set(s,M.createAtom(s.toString())),(o=this.atomMap.get(s))==null||o.reportChanged(),!0},ownKeys:()=>Array.from(this.map.keys())});this.map=M.observable.map(new Map)}setValue(e,s){this.map.set(e,s)}getValue(e){return this.map.get(e)}has(e){return this.map.has(e)}get entries(){return Array.from(this.map.entries())}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}setValues(e){e&&Object.keys(e).forEach(s=>{this.setValue(s,e[s])})}get proxy(){return new Proxy(this,this.proxyHandler)}}tc.prototype[ec]=!0;function jf(t,e){return new Proxy(t,{construct:(s,r)=>{const o=new t(...r);return o.setValues(e),o.proxy}})}const Ae=t=>{const e=jf(tc,t);return new e(t)},kn="/kos/ui/internal/heartbeat/",Bf=({relationshipId:t,destinationAddress:e,onAbort:s,waitTime:r,beatTime:o})=>{const n=I.getInstance().transport,i=new AbortController;let a=performance.now();const c=n.subscribeTopic({topic:`${kn}${t}`,callback:()=>{a=performance.now()}}),d=r??3e3,u=window.setInterval(()=>{let v=performance.now()-a;v=v/1e3,v>d/1e3&&i.abort()},d),h=o??2e3,g=window.setInterval(()=>{Fa({msg:{},options:{topic:`${kn}${t}`,destinationAddress:e}})},h),m=()=>{window.clearInterval(g),window.clearInterval(u),c()},y=()=>{m(),s&&s(),i.signal.removeEventListener("abort",y)};return i.signal.addEventListener("abort",y),{cleanUpHeartbeat:m}},sc=(...t)=>e=>t.reduce((s,r)=>r(s),e),Kf={maxAttempts:5,baseDelayMs:100,backoffFactor:1.5};async function Hf(t,e){let s=1;const r={...Kf,...e},{maxAttempts:o,baseDelayMs:n,backoffFactor:i}=r;let a=n;for(;s<=o;)try{return await t()}catch(c){if(p.error(`Attempt ${s} failed: ${c}`),s<o)a=n*Math.pow(i,s),await new Promise(d=>setTimeout(d,a)),s++;else throw c}throw new Error("All attempts failed")}const zf=p.createLogger({name:"kos-service-request"}),oe=t=>({isMock:!1,URL:exports.BASE_URL}),Gf=(t,e,s)=>async({id:r,tracker:o,urlOverride:n,ordered:i,studio:a,fos:c,bridge:d,timeout:u,signal:h,destinationAddress:g})=>{const m={method:"DELETE"};t&&(m.destinationAddress=t),o&&(m.tracker=o),bt(m,{ordered:i,studio:a,fos:c,bridge:d,timeout:u,signal:h,destinationAddress:g});try{const y=await s(n||`${e}/${r}`,m);if(!y.ok)throw Error(`There was a problem deleting the model; returned status ${y.status}`);return await y.json()??void 0}catch(y){if(y instanceof DOMException){if(y.name==="TimeoutError")throw new B("Request timed out while deleting model");if(y.name==="AbortError")throw new B("Request was cancelled while deleting model")}throw y}},bt=(t,{ordered:e,studio:s,fos:r,destinationAddress:o,bridge:n,timeout:i,signal:a})=>(i&&(t.timeout=i),a&&(t.signal=a),e&&(t.ordered=e),s&&(t.studio=s),r&&(t.fos=r),n&&(t.bridge=n),(o||o==="")&&(t.destinationAddress=o),t),Vf=(t,e,s)=>async({urlOverride:r,ordered:o,studio:n,fos:i,bridge:a,timeout:c,signal:d,destinationAddress:u})=>{const h={method:"GET"};t&&(h.destinationAddress=t),bt(h,{timeout:c,ordered:o,studio:n,fos:i,bridge:a,signal:d,destinationAddress:u});const g=r||e;try{const m=await s(g,h);if(!m.ok){let v;try{v=await m.json()}catch{}throw new B(`There was a problem retrieving the model; returned status ${m.status}`,v??void 0)}return await m.json()??void 0}catch(m){if(m instanceof DOMException){if(m.name==="TimeoutError")throw new B("Request timed out while retrieving models");if(m.name==="AbortError")throw new B("Request was cancelled while retrieving models")}throw m}},Yf=(t,e,s)=>async({urlOverride:r,ordered:o,studio:n,fos:i,bridge:a,tracker:c,timeout:d,signal:u,destinationAddress:h})=>{const g={method:"GET"};t&&(g.destinationAddress=t),c&&(g.tracker=c),bt(g,{timeout:d,ordered:o,studio:n,fos:i,bridge:a,signal:u,destinationAddress:h});const m=r||e;zf.debug(`resolvedUrl: ${m}`);try{const y=await s(m,g);if(!y.ok){let E;try{E=await y.json()}catch{}throw new B(`There was a problem retrieving the model; returned status ${y.status}`,E??void 0)}return await y.json()??void 0}catch(y){if(y instanceof DOMException){if(y.name==="TimeoutError")throw new B("Request timed out while retrieving model");if(y.name==="AbortError")throw new B("Request was cancelled while retrieving model")}throw y}},qf=(t,e,s)=>async({urlOverride:r,id:o,ordered:n,studio:i,fos:a,bridge:c,timeout:d,signal:u,destinationAddress:h})=>{const g={method:"GET"};t&&(g.destinationAddress=t),bt(g,{timeout:d,ordered:n,studio:i,fos:a,bridge:c,signal:u,destinationAddress:h});const m=r||`${e}/${o}`;try{const y=await s(m,g);if(!y.ok){let E;try{E=await y.json()}catch{}throw new B(`There was a problem retrieving the model; returned status ${y.status}`,E??void 0)}return await y.json()??void 0}catch(y){if(y instanceof DOMException){if(y.name==="TimeoutError")throw new B("Request timed out while retrieving model by ID");if(y.name==="AbortError")throw new B("Request was cancelled while retrieving model by ID")}throw y}};class B extends Error{constructor(s,r){super(s);l(this,"payload");this.name="FetchException",this.payload=r}}const Fn=(t,e,s)=>async({model:r,urlOverride:o,ordered:n,tracker:i,studio:a,fos:c,bridge:d,timeout:u,signal:h,destinationAddress:g})=>{const m={method:"POST",body:typeof r=="string"?r:JSON.stringify(r)};t&&(m.destinationAddress=t),i&&(m.tracker=i),bt(m,{timeout:u,ordered:n,studio:a,fos:c,bridge:d,signal:h,destinationAddress:g});try{const y=await s(o||e,m);if(!y.ok){let E;try{E=await y.json()}catch{}throw new B(`There was a problem sending the POST data; returned status ${y.status}`,E??void 0)}return await y.json()??void 0}catch(y){if(y instanceof DOMException){if(y.name==="TimeoutError")throw new B("Request timed out while adding model");if(y.name==="AbortError")throw new B("Request was cancelled while adding model")}throw y}},Nn=(t="POST",e,s,r)=>async({model:o,id:n,urlOverride:i,ordered:a,studio:c,fos:d,bridge:u,timeout:h,signal:g,destinationAddress:m})=>{const y={method:t};o&&(y.body=JSON.stringify(o)),e&&(y.destinationAddress=e),bt(y,{timeout:h,ordered:a,studio:c,fos:d,bridge:u,signal:g,destinationAddress:m});try{const v=await r(i||`${s}/${n}`,y);if(!v.ok){let _;try{_=await v.json()}catch{}throw new B(`There was a problem modifying the model; returned status ${v.status}`,_??void 0)}return await v.json()??void 0}catch(v){if(v instanceof DOMException){if(v.name==="TimeoutError")throw new B("Request timed out while modifying model");if(v.name==="AbortError")throw new B("Request was cancelled while modifying model")}throw v}},se={build:({destinationAddress:t="",basePath:e,getAllPath:s,getOnePath:r,deleteModelPath:o,addModelPath:n,modifyModelPath:i,mock:a=!1})=>{const c=a?fetch:exports.kosFetch;return{getAll:Vf(t,s||e,c),getModelById:qf(t,r||e,c),getOne:Yf(t,r||e,c),addModel:Fn(t,n||e,c),deleteModel:Gf(t,o||e,c),modifyModel:Nn("POST",t,i||e,c),putModel:Nn("PUT",t,i||e,c),postModel:Fn(t,n||e,c)}}},Wf=pt(),rc=()=>`kos-${Wf}`,Qf=t=>!!t&&!t.includes("VM_SERVICE")&&t.startsWith(rc()),$o=async(t,e=6e4)=>new Promise((s,r)=>{const{unsubscribe:o}=O(t,i=>{$.debug(`recieved response for refId ${t}: ${i}`),o(),clearTimeout(n);try{const a=i!=null&&i.body?JSON.parse(i.body):{};s(a)}catch{const a=(i==null?void 0:i.body)||{};s(a)}}),n=setTimeout(()=>{o(),r(Error(`Request with ID ${t} timed out. Cancelling.`))},e)}),Zf=async(t,e,s)=>{const r=$o(s),o=await Promise.allSettled([t(e),r]);if(o[0].status==="fulfilled"){if(o[1].status==="rejected")throw Error(o[1].reason);if(o[0].value){if(o[1].value.error)throw Error(o[1].value.error);return o[0].value.data=o[1].value,o[0].value}}else throw Error(o[0].reason)},Xf=async({topic:t,msg:e,requestId:s})=>{const r=s??pt(),o=$o(r);j(t,e,{sync:r});const n=await o;if(n.error)throw Error(n.error);return n},le=new Map;class oc{constructor(e){l(this,"_context");l(this,"_parent");l(this,"_id");this._id=e,this._context=new M.ObservableMap({}),this._parent="",M.makeAutoObservable(this)}setParent(e){X(()=>{this._parent=e})}get id(){return this._id}get context(){return this._context}get parentModel(){var e;if(this._parent)return(e=ve(this._parent))==null?void 0:e.model}get companionModels(){const e=ve(this._id);return e!=null&&e.model?Va(e.model):[]}get(e){var s,r;if(this._context.has(e))return this._context.get(e);if(this.companionModels.length>0){const o=this.companionModels.find(n=>{var i;return!n.id||!le.has(n.id)?!1:(i=le.get(n.id))==null?void 0:i.context.has(e)});if(o)return(s=le.get(o.id))==null?void 0:s.get(e)}if(this._parent)return(r=le.get(this._parent))==null?void 0:r.get(e)}set(e,s){this._context.set(e,s)}remove(e){this._context.delete(e)}clear(){this._context.clear()}}const z={createContext:(t,e)=>{const s=le.get(t)??new oc(t);if(e){if(!le.has(e))throw new Error(`Parent context ${e} does not exist`);s.setParent(e)}else t!=="root"&&s.setParent("root");return le.set(t,s),s},getContext:t=>le.get(t),deleteContext:t=>{le.delete(t)},setParentContext:(t,e)=>{var s;if(!le.has(e))throw new Error(`Parent context ${e} does not exist`);(s=le.get(t))==null||s.setParent(e)},rootContext:()=>le.get("root")};z.createContext("root");const Jf=t=>z.getContext(t.id);function eg(t,e){return t.length!==e.length?!1:t.every(s=>e.includes(s))}class Do{constructor({container:e,key:s}){l(this,"_container");l(this,"_map");l(this,"_key");l(this,"data");this._container=e,this._map=M.observable.map(new Map),this._key=s,this.data=Ae(),this.generateIndex(),M.autorun(()=>{this._container.revision&&this.generateIndex()}),M.makeAutoObservable(this)}refresh(){this.generateIndex()}addItemToIndex(e,s,r=this._map,o=this.data){const n=r.get(e)||new Set;n.add(s),r.set(e,n),o[e]=Array.from(n)}resolveIndex(e,s){this.data.keys.filter(o=>!Object.keys(s).includes(o)).forEach(o=>{delete this.data[o],this._map.delete(o)}),Object.keys(s).forEach(o=>{const n=s[o],i=this.data[o]||[];if(eg(n,i))p.debug(`KosContainerIndex - Index ${o} is the same`);else{this.data[o]=n;const a=e.get(o)||new Set;this._map.set(o,a)}})}generateIndex(){M.runInAction(async()=>{const e=new Map,s={};for(const r of this._container.data){const o=typeof this._key=="function"?await this._key(r):r[this._key];Array.isArray(o)?o.forEach(n=>{this.addItemToIndex(n,r,e,s)}):typeof o=="string"||typeof o=="number"?this.addItemToIndex(String(o),r,e,s):typeof o=="boolean"&&this.addItemToIndex(String(o),r,e,s)}this.resolveIndex(e,s)})}get keys(){return Array.from(this._map.keys())}get index(){return this._map}getByKey(e){const s=this._map.get(e);return s?Array.from(s):[]}}function tg(t,e,s=[]){const r=Object.getOwnPropertyDescriptors(t);return Object.keys(r).filter(i=>M.isComputedProp(t,i)).filter(i=>s.includes(i)).map(i=>M.reaction(()=>t[i],(a,c)=>{e({name:i,newValue:a,oldValue:c})}))}const Tt=p.createLogger({name:"kos-container-model"});class Te{constructor(e){l(this,"_data");l(this,"_sortKey");l(this,"_revision");l(this,"_index");l(this,"_optionsMap");l(this,"_disposerMap",new Map);l(this,"_parentId");l(this,"idx");this._data=M.observable.map(new Map),this._sortKey=e==null?void 0:e.sortKey,this._revision=1;const s=e!=null&&e.extensionId?S.indexExtension.loadIndexExtensions(e.extensionId):{},r=(e==null?void 0:e.indexMap)||{};this._optionsMap={...r,...s};const o=e!=null&&e.indexMap?Object.keys(e.indexMap).reduce((n,i)=>(n[i]=void 0,n),{}):{};this._index=M.observable.map(o),this.idx=Ae(),this._parentId=e==null?void 0:e.parentId,M.makeAutoObservable(this),this.init()}init(){Object.keys(this._optionsMap).forEach(e=>{const s=this._optionsMap[e],r=new Do({container:this,key:s});this._index.set(e,r),this.idx[e]=r.data})}[Symbol.iterator](){return this.data[Symbol.iterator]()}get index(){return this._index}get revision(){return this._revision}get indexKeys(){return Array.from(this.index.keys()).reduce((e,s)=>{var r;return e[s]=(r=this.index.get(s))==null?void 0:r.keys,e},{})}sortFn(e,s){const r=this._sortKey;return r?String(e[r]).localeCompare(String(s[r]),void 0,{numeric:!0}):0}get data(){const e=Array.from(this._data.values());return this._sortKey&&e.sort(this.sortFn.bind(this)),e}increment(){M.runInAction(()=>{this._revision=this._revision+1})}addAll(e){M.runInAction(()=>{e.forEach(s=>this.addModel(s,!0))}),this.increment()}removeAll(e){M.runInAction(()=>{e.forEach(s=>this.removeModel(s,!0)),this.increment()})}addModel(e,s){this._data.set(e.id||"",e),e.id&&this._parentId&&z.setParentContext(e.id,this._parentId),s||this.increment();const r=this._disposerMap.get(e.id);r&&(r(),this._disposerMap.delete(e.id));const o=Object.entries(this._optionsMap||{}),n=Object.values(this._optionsMap||{}),i=new Map(o.map(([u,h])=>[h,u])),a=u=>{var g,m;n.includes(u.name)&&((g=this.index.get(i.get(u.name)))==null||g.refresh());const h=o.filter(([,y])=>typeof y=="function");for(const[y]of h)(m=this.index.get(y))==null||m.refresh()},c=tg(e,a,n.filter(u=>typeof u=="string")),d=M.observe(e,a);this._disposerMap.set(e.id||"",()=>[d,...c].forEach(u=>u()))}removeModel(e,s){this._data.delete(e),s||this.increment();const r=this._disposerMap.get(e);r&&(r(),this._disposerMap.delete(e))}updateModel(e){this._data.set(e.id||"",e),this.increment()}getModel(e){return this._data.get(e)}getIndexKeys(e){return this.index.has(e)?this.index.get(e).keys??[]:(Tt.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[])}getIndexByKey(e,s){if(this.index.has(e)){const r=this.index.get(e);return r.index.has(s)?r.getByKey(s):(Tt.info(`key ${s} not found in ${e} index: ${Array.from(r.index.keys())}`),[])}else return Tt.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[]}async clear(){this._data.forEach(e=>{const s=e.id;He(e).then(()=>{Tt.debug(`${s} destroyed, removing from map`),this.removeModel(s,!0)}).catch(r=>Tt.error(r))}),this.increment()}filter(e,s){return this.data.filter(e,s)}sort(e){return this.data.sort(e)}map(e,s){return this.data.map(e,s)}forEach(e,s){this.data.forEach(e,s)}toJSON(){return{indexes:this.indexKeys,data:this.data.map(s=>({id:s.id,type:s.constructor.name}))}}}const Lr=p.createLogger({name:"kos-data-container"});class Co{constructor(e){l(this,"_data");l(this,"_sortKey");l(this,"_revision");l(this,"_index");l(this,"_optionsMap");l(this,"_disposerMap",new Map);l(this,"idx");this._data=M.observable.map(new Map),this._sortKey=e==null?void 0:e.sortKey,this._revision=1,this._optionsMap=(e==null?void 0:e.indexMap)||{};const s=e!=null&&e.indexMap?Object.keys(e.indexMap).reduce((r,o)=>(r[o]=void 0,r),{}):{};this._index=M.observable.map(s),this.idx=Ae(),M.makeAutoObservable(this,{}),this.init()}init(){Object.keys(this._optionsMap).forEach(e=>{const s=this._optionsMap[e],r=new Do({container:this,key:s});this._index.set(e,r),this.idx[e]=r.data})}[Symbol.iterator](){return this.data[Symbol.iterator]()}get index(){return this._index}get indexKeys(){return Array.from(this.index.keys()).reduce((e,s)=>{var r;return e[s]=(r=this.index.get(s))==null?void 0:r.keys,e},{})}get revision(){return this._revision}addAll(e){M.runInAction(()=>{e.forEach(s=>this.addModel(s))})}removeAll(e){M.runInAction(()=>{e.forEach(s=>this.removeModel(s))})}sortFn(e,s){const r=this._sortKey;return r?String(e[r]).localeCompare(String(s[r]),void 0,{numeric:!0}):0}get data(){const e=Array.from(this._data.values());return this._sortKey&&e.sort(this.sortFn.bind(this)),e}increment(){M.runInAction(()=>{this._revision=this._revision+1})}addModel(e,s){const r=M.isObservable(e)?e:M.observable.object(e),o=this._disposerMap.get(e.id);o&&(o(),this._disposerMap.delete(e.id)),this._data.set(r.id||"",r),s||this.increment();const n=M.observe(r,i=>{Object.values(this._optionsMap||{}).includes(i.name)&&this.increment()});this._disposerMap.set(r.id||"",n)}removeModel(e){this._data.delete(e),this.increment();const s=this._disposerMap.get(e);s&&(s(),this._disposerMap.delete(e))}updateModel(e){const s=M.observable.object(e);this._data.set(s.id||"",s),this.increment()}getModel(e){return this._data.get(e)}getIndexKeys(e){return this.index.has(e)?this.index.get(e).keys??[]:(Lr.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[])}getIndexByKey(e,s){if(this.index.has(e)){const r=this.index.get(e);return r.index.has(s)?r.getByKey(s):(Lr.info(`key ${s} not found in ${e} index: ${Array.from(r.index.keys())}`),[])}else return Lr.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[]}async clear(){this._data.clear(),this.increment()}filter(e,s){return this.data.filter(e,s)}sort(e){return this.data.sort(e)}map(e,s){return this.data.map(e,s)}forEach(e,s){this.data.forEach(e,s)}toJSON(){return{indexes:this.indexKeys,data:this.data.map(s=>({id:s.id}))}}}class sg{constructor({type:e,model:s,childRegistration:r}){l(this,"type");l(this,"childRegistration");l(this,"model");this.type=e,this.model=s,this.childRegistration=r}get factory(){return te.Factory.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!1,factory:this.factory},...this.childRegistration}}get predicate(){return he(this.type)}}class rg{constructor({type:e,model:s,childRegistration:r}){l(this,"type");l(this,"model");l(this,"childRegistration");this.type=e,this.model=s,this.childRegistration=r}get factory(){return te.Singleton.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!0,factory:this.factory},...this.childRegistration}}get predicate(){return he(this.type)}}class nc{constructor(){l(this,"_token");M.makeAutoObservable(this),O("token",e=>{this.token=e==null?void 0:e.body})}get token(){return this._token}set token(e){this._token=e}}class ic{constructor(){l(this,"routes",[]);l(this,"openApiRoutes",[])}use(e,s,...r){this.routes.push({method:e,path:s,middlewares:r});const o=this.extractOpenApiParams(s);this.openApiRoutes.push({method:e,path:s,parameters:o})}remove(e,s){const r=this.routes.length;return this.routes=this.routes.filter(o=>!(o.method===e&&o.path===s)),this.openApiRoutes=this.openApiRoutes.filter(o=>!(o.method===e&&o.path===s)),r-this.routes.length}removeAllForPath(e){const s=this.routes.length;return this.routes=this.routes.filter(r=>r.path!==e),this.openApiRoutes=this.openApiRoutes.filter(r=>r.path!==e),s-this.routes.length}getRoutes(){return this.routes.map(e=>({method:e.method,path:e.path}))}async handle(e,s){var a;const{path:r,query:o,params:n}=this.extractPathParams(e.path),i={...e,params:n,query:o};for(const c of this.routes){const d=this.matchRoute(c.path,r);if(c.method===e.method&&d){i.params=d;let u=0;const h=async()=>{if(u<c.middlewares.length){const g=c.middlewares[u++];await g(i,s,h)}};await h();return}}(a=s.status)==null||a.call(s,404).send({error:"Route not found"})}extractOpenApiParams(e){return e.split("/").filter(s=>s.startsWith(":")).map(s=>({name:s.slice(1),in:"path",required:!0,schema:{type:"string"}}))}generateOpenApiSpec(){const e={};for(const s of this.openApiRoutes)e[s.path]||(e[s.path]={}),e[s.path][s.method.toLowerCase()]={summary:s.description||`Handles ${s.method} ${s.path}`,parameters:s.parameters||[],responses:{200:{description:"Successful response"}}};return{openapi:"3.0.0",info:{title:"Kos Router API",version:"1.0.0",description:"Dynamically generated OpenAPI documentation"},paths:e}}extractPathParams(e){const[s,r]=e.split("?"),o=this.parseQueryParams(r);for(const n of this.routes){const i=this.matchRoute(n.path,s);if(i)return{path:s,query:o,params:i}}return{path:s,query:o,params:{}}}matchRoute(e,s){const r=e.split("/").filter(Boolean),o=s.split("/").filter(Boolean);if(r.length!==o.length)return null;const n={};for(let i=0;i<r.length;i++)if(r[i].startsWith(":"))n[r[i].slice(1)]=decodeURIComponent(o[i]);else if(r[i]!==o[i])return null;return n}parseQueryParams(e){return e?e.split("&").reduce((s,r)=>{const[o,n]=r.split("=").map(decodeURIComponent);return s[o]=n??"",s},{}):{}}}const ac=p.createLogger({name:"intent-service"}),og=t=>{po(`/kos/intent/${t.type}`)?j(`/kos/intent/${t.type}`,t.options,{"kos.intent.type":t.type}):ac.info(`No subscribers for intent ${t.type}. Intent not sent.`)},ng=async t=>new Promise(e=>{const{type:s,options:r}=t;if(po(`/kos/intent/${t.type}`)){const o=pt(),{unsubscribe:n}=O(o,a=>{clearTimeout(i),n(),a&&(a.headers=a.headers||{},a.headers["kos.intent.type"]=s,a.headers.responseId=o),e([null,{body:a==null?void 0:a.body,payload:a}])}),i=setTimeout(()=>{n(),e([`Intent ${s} timed out after 1 second`,null]),console.warn(`Intent ${s} timed out after 1 second`)},1e3);j(`/kos/intent/${s}`,r,{"kos.intent.type":s,sync:o})}else ac.info(`No subscribers for intent ${t.type}. Intent not sent.`),e([null,{body:void 0,payload:void 0}])}),_e=p.createLogger({name:"app-startup-service"});async function cc(t,e={}){const{timeout:s=3e4,throwOnTimeout:r=!0,requirePostStarted:o=!1}=e;if(t.length===0)return _e.warn("No app IDs provided to waitForAppsToStart"),!0;_e.debug(`Waiting for apps to start: ${t.join(", ")}`);try{const n=t.map(c=>`/kos/app/started/${c}`),i=await bo(n,{getCurrentState:async()=>{try{const{default:c}=await Promise.resolve().then(()=>cp),[d,u]=await c.get("/api/kos/apps/started");return d?(_e.error("Error fetching started apps:",d),[]):u}catch(c){_e.error("Failed to fetch app startup status:",c)}return[]},shouldUseFetchedState:c=>t.every(d=>{const u=c.find(h=>h.appId===d);return!(!u||!u.started||o&&!u.postStarted)}),timeout:s}),a=t.filter(c=>{const d=i.find(u=>u.appId===c);return!!(!d||!d.started||o&&!d.postStarted)});if(a.length>0){const c=`Apps not started: ${a.join(", ")}`;if(_e.error(c),r)throw new Error(`App startup timeout: ${c}`);return!1}return _e.info(`All apps started successfully: ${t.join(", ")}`),!0}catch(n){const i=`Failed to wait for apps to start: ${t.join(", ")}`;if(_e.error(i,n),r)throw new Error(`${i} - ${n instanceof Error?n.message:String(n)}`);return!1}}async function ig(t,e={}){return cc([t],e)}async function ag(t,e=!1){const s={};try{const r=await exports.kosFetch("kos:///api/kos/apps/started");if(!r.ok)return t.forEach(i=>s[i]=!1),s;const o=await r.json(),n=(o==null?void 0:o.data)??[];t.forEach(i=>{const a=n.find(c=>c.appId===i);s[i]=(a==null?void 0:a.started)===!0&&(!e||(a==null?void 0:a.postStarted)===!0)})}catch(r){_e.error("Failed to check app startup status:",r),t.forEach(o=>s[o]=!1)}return s}async function cg(){try{const t=await exports.kosFetch("kos:///api/kos/apps/started");if(!t.ok)return[];const e=await t.json();return(e==null?void 0:e.data)??[]}catch(t){return _e.error("Failed to fetch started apps:",t),[]}}const Wr=M.when,Ro=M.computed,X=M.runInAction,G=M.autorun,lc=M.reaction,Ao=M.observable,xo="Not Assigned",lg="kos.trouble.added",dg="kos.trouble.removed";var me=(t=>(t.TroubleRank="kos.trouble.rank.mapper",t.TroubleColor="kos.trouble.color.mapper",t.TroubleRole="kos.trouble.role.mapper",t))(me||{}),Ht=(t=>(t.TIME_CHANGE="/kos/internal/time/time",t.DAY_CHANGE="/kos/internal/time/day",t.TIMEZONE_CHANGE="/kos/internal/time/timezone",t))(Ht||{});const dc=p.createLogger({name:"config-bean-service",group:"Services"}),Po=exports.BASE_URL,uc=t=>(t==null?void 0:t.decimals)!==void 0,{postModel:ug,getOne:hg}=se.build({destinationAddress:"",basePath:`${Po}/kos/config/`}),hc=async(t,e,s="/api/kos/config")=>(dc.debug(`sending modify request for ConfigBean: ${t}`),ug({model:e,urlOverride:`${Po}${s}/${t}`})),fc=async(t,e="/api/kos/config")=>(dc.debug(`sending get request for ConfigBean: ${t}`),await hg({urlOverride:`${Po}${e}/details/${t}/15`})),Lo=t=>t.toLowerCase()==="true"||t.toLowerCase()==="false",pr=t=>{try{const e=Number(t);return!isNaN(e)}catch{return!1}};function gc(t=[]){return t.reverse().reduce((e,s)=>{const{overrides:r}=s;return r&&(e={...e,...r}),e},{})}function pc(t,e="",s={}){for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const o=e?`${e}.${r}`:r;typeof t[r]=="object"&&t[r]!==null&&!Array.isArray(t[r])?pc(t[r],o,s):s[o]=t[r]}return s}const mc=(t,e)=>{const s=t.details[0].bean||gc(t.details[0].scopes),r=pc(s);M.runInAction(()=>{const o={...r};e.props.setValues(o)})},yc=(t,e)=>{M.runInAction(()=>{t.changes.forEach(s=>{const r=s.attr;let o=s.currentValue,n=s.previousValue;typeof o=="string"&&Lo(o)&&(o=o.toLowerCase()=="true",n=(n==null?void 0:n.toLowerCase())=="true"),typeof o=="string"&&pr(o)&&(o=Number(o),n=Number(n)),e.props[r]=o,e.prevProps[r]=n})})},bc=t=>Object.fromEntries(t.props.entries),fg=t=>e=>s=>t.build(e,s);var gg=Object.defineProperty,pg=Object.getOwnPropertyDescriptor,wc=(t,e,s,r)=>{for(var o=r>1?void 0:r?pg(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&gg(e,s,o),o};function mg(t,e){for(const s of t)if(new RegExp(`^${s}$`).test(e))return s}const ko="config-bean-model",vs=p.getLogger(ko),yg=Ge("path");let Ns=class{constructor(t,e){l(this,"_modifyConfigBean");l(this,"_getConfigBean");l(this,"_schema");l(this,"id");l(this,"path");l(this,"props");l(this,"prevProps");l(this,"serviceBasePath");Object.assign(this,e),this.id=t,this.path=e.path,this.serviceBasePath=e.serviceBasePath;const{modifyConfigBean:s=hc,getConfigBean:r=fc}=e;this._modifyConfigBean=s,this._getConfigBean=r,this.props=Ae(),this.prevProps=Ae()}get values(){return this.props.values}async ready(){vs.debug(`readying config bean ${this.path}`),vs.debug(`complete readying config bean ${this.path}`)}async load(){vs.debug(`loading config bean ${this.path}`);const t=await this._getConfigBean(this.path,this.serviceBasePath);if(t!=null&&t.data){const e=t.data;mc(e,this),vs.debug(this.values);const s=t==null?void 0:t.data.details[0].schema;X(()=>{s&&(this._schema=s)})}}get schemaKeys(){var t;return Object.keys(((t=this._schema)==null?void 0:t.schema)||{})}getSchemaForProperty(t){var s,r;if(this.schemaKeys.includes(t))return(s=this._schema)==null?void 0:s.schema[t];const e=mg(this.schemaKeys,t);if(e)return(r=this._schema)==null?void 0:r.schema[e]}async updateProperty(t,e){this.props[t]=e,await this.updateConfigBean()}async updateConfigBean(){const t=bc(this);await this._modifyConfigBean(this.path,t,this.serviceBasePath)}handleConfigBeanUpdated(t){yc(t,this)}};wc([U({topic:`/kos/config/${yg}`,websocket:!0})],Ns.prototype,"handleConfigBeanUpdated",1);Ns=wc([R(ko)],Ns);const Yt=new we({class:Ns,type:ko}),mr=({path:t,lazy:e,serviceBasePath:s})=>(r,o)=>{r[F]=r[F]||{},r[F][o]={modelType:Yt.type,id:`${Yt.type}-${t}`,options:{path:t,serviceBasePath:s},lifecycle:H.INIT,lazy:e}},{URL:vc}=oe(),{getOne:bg,getAll:wg}=se.build({basePath:`${vc}/api/kos/regions/info`}),Mc=async()=>await bg({}),Ec=async()=>await wg({urlOverride:`${vc}/api/kos/regions`}),vg=Object.freeze(Object.defineProperty({__proto__:null,getRegionInfo:Mc,getRegions:Ec},Symbol.toStringTag,{value:"Module"}));var ie=(t=>(t[t.family=0]="family",t[t.scale=1]="scale",t[t.offset=2]="offset",t[t.decimals=3]="decimals",t[t.alias=4]="alias",t[t.system=5]="system",t))(ie||{});const Tc={s:["time",1,0,0],second:["time",1,0,0],m:["time",1/60,0,0],minute:["time",1/60,0,0],h:["time",1/3600,0,0],hour:["time",1/3600,0,0],day:["time",1/86400,0,0],week:["time",1/604800,0,0],month:["time",1/2628e3,0,0],year:["time",1/31536e3,0,0],default:["time",1/.001,0,0],ms:["time",1/.001,0,0],millisecond:["time",1/.001,0,0],microsecond:["time",1/1e-6,0,0],nanosecond:["time",1/1e-9,0,0],picosecond:["time",1/1e-12,0,0]};function Mg(t,e){const s=e.id,r=e.units.reduce((o,n)=>{const i=[n.measure,n.scale,n.offset,n.decimals,n.alias,s];return o[n.name]=i,n.alias&&(o[n.alias]=i),o},{...Tc});return{...t,...r}}function Eg(t,e){const s=e.id,r=e.units.reduce((o,n)=>{const i=o[n.measure]||{},a=i[s]||{};i[s]=a;const c=[n.measure,n.scale,n.offset,n.decimals,n.alias,s];return a[n.name]=c,Object.hasOwn(n,"default")&&Object.defineProperty(a,"default",{value:c,writable:!0,enumerable:!0,configurable:!0}),o[n.measure]=i,n.alias&&(o[n.alias]=i),o},{time:{[s]:{...Tc}}});return Object.keys(r).forEach(o=>{t[o]={...t[o],...r[o]}}),t}function Tg(t,e){const s=e.id,r=e.units.reduce((o,n)=>{const i=o[n.measure]||{};return Object.hasOwn(n,"default")&&(i[s]=n.name),o[n.measure]=i,o},{time:{[s]:"millisecond"}});return Object.keys(r).forEach(o=>{t[o]={...t[o],...r[o]}}),t}var _g=Object.defineProperty,Ig=Object.getOwnPropertyDescriptor,Fo=(t,e,s,r)=>{for(var o=r>1?void 0:r?Ig(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&_g(e,s,o),o};const Cs="region-info-model",_t=p.createLogger({name:"region-info-model"});let qt=class{constructor(t){l(this,"id");l(this,"unitSystemMap");l(this,"measureMap");l(this,"defaultMeasureMap");l(this,"regionMap");l(this,"timeFormats");l(this,"dateFormats");l(this,"unitSystems");l(this,"regionSource");l(this,"region");l(this,"regions",[]);l(this,"timeZoneMap",{});this.id=t,this.unitSystems={},this.unitSystemMap={},this.measureMap={},this.defaultMeasureMap={},this.timeFormats={},this.regions=[],this.dateFormats={},this.timeZoneMap={},this.regionMap={}}get availableRegions(){return this.regions}get defaultUnitSystem(){return String(this.regionSource.props.unitSystemId).toLowerCase()||""}get unitSystemId(){return this.defaultUnitSystem}get timeFormatId(){const t=this.regionSource.props.timeFormatId;if(!t)return"";const e=String(t),s=this.timeFormats[e];return s?String(s.id):""}get selectedTimeFormat(){const t=this.timeFormatId;return t?String(this.timeFormats[t].format):"HH:mm:ss"}get is12HourTimeFormat(){const t=this.timeFormatId;return t?this.timeFormats[t].ampm:!0}get dateFormatId(){const t=this.regionSource.props.dateFormatId;if(!t)return"";const e=String(t);return e?this.dateFormats[e].id:""}get selectedDateFormat(){const t=this.dateFormatId;return t?this.dateFormats[t].format:""}get selectedDateOrder(){const t=this.dateFormatId;return t?this.dateFormats[t].order.toLowerCase():"dmy"}get selectedCountry(){return this.regionSource.props.country||"en"}get selectedTimeZone(){return this.regionSource.props.timeZone||""}get timeZones(){return this.regionId?this.timeZoneMap[this.regionId]||[]:[]}get allTimeZones(){return Intl.supportedValuesOf("timeZone")}get regionId(){return this.region.props.regionId||""}get selectedRegion(){return this.regionMap[this.regionId]}get selectedUnitSystem(){return String(this.regionSource.props.unitSystemId)||""}get timeFormatOptions(){return Object.keys(this.timeFormats).map(t=>({id:t,format:this.timeFormats[t].format,ampm:this.timeFormats[t].ampm}))}get dateFormatOptions(){return Object.keys(this.dateFormats).map(t=>({id:t,format:this.dateFormats[t].format,order:this.dateFormats[t].order}))}get unitSystemOptions(){return Object.keys(this.unitSystems).map(t=>({id:t,name:t}))}setSelectedTimeFormat(t){if(!this.timeFormatOptions.find(e=>e.id===t))throw Error(`Invalid time format id. Must be one of ${this.timeFormatOptions.map(e=>e.id).join(", ")}`);this.regionSource.updateProperty("timeFormatId",t)}setSelectedDateFormat(t){if(!this.dateFormatOptions.find(e=>e.id===t))throw Error(`Invalid date format id. Must be one of ${this.dateFormatOptions.map(e=>e.id).join(", ")}`);this.regionSource.updateProperty("dateFormatId",t)}setSelectedUnitSystem(t){if(!this.unitSystemOptions.find(e=>e.id===t))throw Error(`Invalid date format id. Must be one of ${this.unitSystemOptions.map(e=>e.id).join(", ")}`);this.regionSource.updateProperty("unitSystemId",t)}getUnitSystem(t){if(!t)return this.defaultUnitSystem;const e=t==="drt"?"second":t,s=this.unitSystemMap[e];if(!s)throw Error(`No unit found with name: ${e}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return s[ie.system]}getUnitMeasure(t){const e=t==="drt"?"second":t,s=this.unitSystemMap[e];if(!s)throw Error(`No unit found with name: ${e}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return s[ie.family]}getDefaultUnitDecimalPlaces(t,e,s){if(!t||!e)throw Error("Measure and unit system are required");const r=s==="drt"?"second":s,o=this.measureMap[t];if(!o)throw Error(`No unit systems found for measure: ${t}. Measure should come from list of measures: ${Object.keys(this.measureMap).join(", ")}`);const n=o[e.toLowerCase()];if(!n)throw Error(`No unit system found for measure: ${t} and unit system: ${e}. Unit system should come form list of unit systems: ${Object.keys(o).join(", ")}`);const i=n[r||"default"];if(!i)throw Error(`No unit "${r||"default"}" found for measure: ${t} and unit system: ${e}. Unit should come from list of units: ${Object.keys(n).join(", ")}`);return i[ie.decimals]}getDefaultUnitForMeasure(t,e){if(!t||!e)throw Error("Measure and unit system are required");const s=this.defaultMeasureMap[t];if(!s)throw Error(`No unit systems found for measure: ${t}. Measure should come from list of measures: ${Object.keys(this.measureMap).join(", ")}`);const r=s[e.toLowerCase()];if(!r)throw Error(`No unit system found for measure: ${t} and unit system: ${e}. Unit system should come form list of unit systems: ${Object.keys(s).join(", ")}`);return r}convertByUnit(t,e,s){if(e[ie.family]!==s[ie.family])throw new Error(`Cannot convert between units of different families: ${e[ie.family]} and ${s[ie.family]}`);const r=e[ie.offset],o=e[ie.scale],n=s[ie.scale],i=s[ie.offset],a=s[ie.decimals];return((t-r)/(o/n)+i).toFixed(a)}convertByUnitName(t,e,s){const r=this.unitSystemMap[e],o=this.unitSystemMap[s];if(!r||!o)throw new Error(`No unit found with name: ${e} or ${s}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return this.convertByUnit(t,r,o)}convert(t,e,s){var a,c;if(e.unit&&s.unit)return this.convertByUnitName(t,e.unit,s.unit);const r=e.unit||"",o=s.unit||"";let n=this.unitSystemMap[r],i=this.unitSystemMap[o];if(!i&&s.measure&&s.system){const d=this.measureMap[s.measure];if(!d)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);i=(a=d[s.system])==null?void 0:a.default,i||_t.info("Could not find default unit for measure",s.measure)}if(!n&&e.measure&&e.system){const d=this.measureMap[e.measure];if(!d)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);n=(c=d[e.system])==null?void 0:c.default,n||_t.info("Could not find default unit for measure",e.measure)}return!n||!i?(_t.warn("Could not find unit to convert to or from. Return value as is"),String(t)):this.convertByUnit(t,n,i)}async init(){_t.debug("initializing region info")}async load(){_t.debug("loading region info");const t=await Ec();t&&(this.regions=t.data.map(s=>s.id),this.timeZoneMap=t.data.reduce((s,r)=>({...s,[r.id]:r.timeZones}),this.timeZoneMap),this.regionMap=t.data.reduce((s,r)=>({...s,[r.id]:r}),{}));const e=await Mc();e&&(this.unitSystems=e.data.unitSystems.reduce((s,r)=>{const o={id:r.id,name:r.id};return s[r.id]=o,s},this.unitSystems),this.unitSystemMap=e.data.unitSystems.reduce(Mg,{}),this.measureMap=e.data.unitSystems.reduce(Eg,{}),this.defaultMeasureMap=e.data.unitSystems.reduce(Tg,{}),this.timeFormats=e.data.timeFormats.reduce((s,r)=>({...s,[r.id]:r}),{}),this.dateFormats=e.data.dateFormats.reduce((s,r)=>({...s,[r.id]:r}),{}))}async ready(){var t,e;await((e=(t=this.regionSource).ready)==null?void 0:e.call(t))}};Fo([mr({path:"kos:service:region:settings"})],qt.prototype,"regionSource",2);Fo([mr({path:"kos:service:region"})],qt.prototype,"region",2);qt=Fo([R(Cs)],qt);const ee={registration:{[Cs]:{class:qt,singleton:!0}},type:Cs,factory:te.Singleton.create(Cs)},Us=({source:t,defaultSystem:e="si",defaultMeasure:s})=>{let r={system:e,measure:s};return typeof t=="string"?r={...r,unit:t}:r={...r,...t},r},No=(t,e,s)=>{const{model:r}=ve(ee.type);if(!r)throw new Error("RegionInfo model not found");if(!Fs(r))throw new Error("RegionInfo model not ready");const o={system:r.defaultUnitSystem},n=Us({source:e}),i=Us({source:s||o,defaultMeasure:r.getUnitMeasure(n.unit||"")});return r.convert(t,n,i)};function Un(t,e,s){const r=e.toLowerCase().replace(/_/g,"-").replace(/s$/,""),o=new Intl.NumberFormat().resolvedOptions().locale??"en-US";try{const n=(s==null?void 0:s.mode)||"long",i=(s==null?void 0:s.maxDecimals)??2,a=(s==null?void 0:s.minDecimals)??0;return new Intl.NumberFormat(o,{style:"unit",unit:r,unitDisplay:n,minimumFractionDigits:a,maximumFractionDigits:i}).format(t)}catch{return e}}const Sg=(t,e,s,r)=>{const o=No(t,e,s),n=Us({source:e}),{model:i}=ve(ee.type);if(!i)throw new Error("RegionInfo model not found");const a=i.getUnitMeasure(n.unit||""),c={system:i.defaultUnitSystem},d=Us({source:s||c,defaultMeasure:i.getUnitMeasure(n.unit||"")}),u=i.getDefaultUnitForMeasure(a,d.system),h=i.getDefaultUnitDecimalPlaces(a,d.system),g={...r,minDecimals:(r==null?void 0:r.minDecimals)??h,maxDecimals:(r==null?void 0:r.maxDecimals)??h};return{value:o,unit:u||n.unit||"",display:Un(o,u||n.unit||"",{...g,mode:"long"}),shortDisplay:Un(o,u||n.unit||"",{...g,mode:"short"})}};function jn({start:t,end:e,count:s,decimals:r=0}){if(typeof t!="number"||typeof e!="number"||typeof s!="number")throw new Error("All input values should be numbers.");if(s<2)throw new Error("Count should be at least 2 for distribution.");if(t>=e)throw new Error("Start should be less than end.");const o=(e-t)/(s-1),n=[];for(let i=0;i<s;i++){const a=Math.round(t+i*o);n.push(a.toFixed(r))}return n}function Bn({start:t,end:e,interval:s,decimals:r=0}){if(typeof t!="number"||typeof e!="number"||typeof s!="number")throw new Error("All input values should be numbers.");if(s<=0)throw new Error("Interval should be a positive number.");if(t>=e)throw new Error("Start should be less than end.");const o=[];let n=t;for(;n<=e;)o.push(n.toFixed(r)),n+=s;return o[o.length-1]!==e.toString()&&o.push(e.toString()),o}const Qe=(t,e)=>s=>!t||!e?s:pr(s)?No(Number(s),t,e):s,Og=(t,e,s,r)=>{if((t==null?void 0:t.type)==="enum"||!(t!=null&&t.options))return[];if(t.options.type==="rangeCount")return jn(t.options).map(Qe(s,r));if(t.options.type==="rangeInterval")return Bn(t.options).map(Qe(s,r));if(t.options.type==="list"){const{list:o}=t.options;return o.map(Qe(s,r))}else{if(t.options.type==="unitSystemRangeCount"&&e)return jn(t.options.unitSystems[e]).map(Qe(s,r));if(t.options.type==="unitSystemRangeInterval"&&e)return Bn(t.options.unitSystems[e]).map(Qe(s,r));if(t.options.type==="unitSystemList"&&e){const{list:o}=t.options.unitSystems[e];return o.map(Qe(s,r))}}return[]},$g=(t,e)=>{if(!((t==null?void 0:t.type)==="enum"||!(t!=null&&t.options)))return t.options.type==="unitSystemRangeCount"&&e?{type:"rangeCount",...t.options.unitSystems[e]}:t.options.type==="unitSystemRangeInterval"&&e?{type:"rangeInterval",...t.options.unitSystems[e]}:t.options.type==="unitSystemList"&&e?{type:"list",...t.options.unitSystems[e]}:t.options.type==="unitSystemKeypad"&&e?{type:"keypad",...t.options.unitSystems[e]}:t.options};var Dg=Object.defineProperty,Cg=Object.getOwnPropertyDescriptor,Uo=(t,e,s,r)=>{for(var o=r>1?void 0:r?Cg(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Dg(e,s,o),o};function Rg(t){return(t==null?void 0:t.type)==="enum"}function Ag(t){switch(t){case"s":return"second";case"ms":return"millisecond";case"min":return"minute";case"h":return"hour";case"d":return"day";case"w":return"week";case"m":return"month";case"y":return"year";case"ml":return"milliliter";default:return t}}function xg(t,e){const s=new Date;s.setHours(0,0,0,0);const r=new Date(s.getTime()+t*1e3);return Re.format(r,e)}const Rs="config-bean-prop-model",Ze=p.createLogger({name:"config-bean-prop-model"}),Pg=Ge("path"),Lg=Ge("serviceBasePath");let Wt=class{constructor(t,e){l(this,"id");l(this,"path");l(this,"attribute");l(this,"converter");l(this,"formatter");l(this,"optionsExpander");l(this,"serviceBasePath");l(this,"regionInfo");l(this,"bean");this.id=t,this.path=e.path,this.attribute=e.attribute,this.converter=e.converter,this.formatter=e.formatter,this.serviceBasePath=e.serviceBasePath,this.optionsExpander=e.optionsExpander}getDefaultUnitDecimalPlaces(t,e,s){if(!t)throw new Error("measure is required");if(!e)throw new Error("unitSystem is required");return uc(this.displayOptions)?this.displayOptions.decimals:this.regionInfo.getDefaultUnitDecimalPlaces(t,e,s)}getDefaultUnitForMeasure(t,e){if(!t)throw new Error("measure is required");if(!e)throw new Error("unitSystem is required");return this.regionInfo.getDefaultUnitForMeasure(t,e)}get schemaType(){const t=this.bean.getSchemaForProperty(this.attribute);return t!=null&&t.type?t.type:"String"}get schemaFormat(){const t=this.bean.getSchemaForProperty(this.attribute);return t!=null&&t.format?Ag(t.format):""}get options(){var i;const t=this.regionInfo.defaultUnitSystem,e=this.getConverter(),s=((i=e==null?void 0:e.to)==null?void 0:i.system)??t,r=this.bean.getSchemaForProperty(this.attribute),o=Rg(r)?r.values:Og(r,s,e==null?void 0:e.from,e==null?void 0:e.to),n=o.length>0?o.map(a=>({label:a,value:a})):[];return this.optionsExpander?typeof this.optionsExpander=="function"?this.optionsExpander(s,o):this.optionsExpander:n}convertUnit(t,e,s){const r=(t==null?void 0:t.measure)||s,o=(t==null?void 0:t.system)||e,n=t==null?void 0:t.unit;return{measure:r,system:o,unit:n}}getConverterUnits(){const t=this.regionInfo.defaultUnitSystem,e=this.getConverter();if(!e)throw Error("No converter defined");const s=e.measure,r=this.convertUnit(e.from,"si",s),o=this.convertUnit(e.to,t,s);return{backend:r,display:o}}set value(t){this.updateProperty(t)}get value(){return this.getValue(!0)}get rawValue(){return this.bean.props[this.attribute]}get significantValue(){var o,n;const t=this.value,e=this.regionInfo.defaultUnitSystem,s=this.getConverter(),r=(s==null?void 0:s.measure)||((o=s==null?void 0:s.to)==null?void 0:o.measure);if(!isNaN(t)&&s&&r){const i=this.getDefaultUnitDecimalPlaces(r,e,(n=s==null?void 0:s.to)==null?void 0:n.unit);try{const c=this.getFormatterOptions(s);if(c){let d=String(t);return d=c.formatToParts(Number(t))[0].value,Number(d)}}catch(c){Ze.info(`error formatting value ${t}`,c)}return Number(t).toFixed(i)}return t}get previousValue(){return this.getValue(!1)}getValue(t){const e=this.bean[t?"props":"prevProps"][this.attribute];if(typeof e=="boolean")return e;if(this.getConverter()&&!isNaN(e)){const{backend:r,display:o}=this.getConverterUnits();return this.regionInfo.convert(Number(e),r,o)}return e||""}async activate(){Ze.debug(`activating config bean ${this.id}`)}get displayValue(){const t=this.value;if(typeof t=="boolean")return String(t);if(this.schemaFormat==="drt"){const s=this.regionInfo.is12HourTimeFormat?"h:mm:ss a":"HH:mm:ss";return xg(t,s)}if(!isNaN(t))try{const e=this.getConverter(),s=this.getFormatterOptions(e);if(s){let r=String(t);return r=s.format(Number(t)),r}}catch(e){Ze.error(`error formatting value ${t}`,e)}return String(t)}get unit(){const t=this.getConverter();if(!isNaN(this.value)){const e=this.getFormatterOptions(t);if(e){const r=e.formatToParts(Number(this.value)).find(o=>o.type==="unit");return(r==null?void 0:r.value)??this.getDefaultUnit(t)}}return this.getDefaultUnit(t)}get displayOptions(){var o;const t=this.bean.getSchemaForProperty(this.attribute),e=this.regionInfo.defaultUnitSystem,s=this.getConverter(),r=((o=s==null?void 0:s.to)==null?void 0:o.system)??e;return $g(t,r)}getMeasureFromFormat(){const t=this.schemaFormat;return t?this.regionInfo.getUnitMeasure(t):""}getConverterFromFormat(){const t=this.getMeasureFromFormat();if(t){const e=this.regionInfo.selectedUnitSystem;return{unit:this.schemaFormat||this.regionInfo.getDefaultUnitForMeasure(t,e),measure:t}}return{}}getDefaultUnit(t){var r,o;const e=this.regionInfo.defaultUnitSystem,s=t==null?void 0:t.measure;return s?((r=t==null?void 0:t.to)==null?void 0:r.unit)||this.getDefaultUnitForMeasure(s,((o=t==null?void 0:t.to)==null?void 0:o.system)||e):this.getConverterFromFormat().unit}getFormatterOptions(t){var n,i,a;const e=this.regionInfo.defaultUnitSystem,s=t==null?void 0:t.measure,r=new Intl.NumberFormat().resolvedOptions().locale;let o=null;if(s||this.formatter){const c=s?{style:"unit",unit:this.getDefaultUnit(t)}:null,d=this.formatter||c;if(d){let u=typeof d=="function"?d(((n=t==null?void 0:t.to)==null?void 0:n.system)||e):d;s&&(u={unit:this.getDefaultUnit(t),...u},u.style==="unit"&&(u.maximumFractionDigits=u.maximumFractionDigits??this.getDefaultUnitDecimalPlaces(s,((i=t==null?void 0:t.to)==null?void 0:i.system)||e,(a=t==null?void 0:t.to)==null?void 0:a.unit)));try{o=new Intl.NumberFormat(r,{...u})}catch(h){Ze.error(`error creating formatter ${u}. Returning the raw value`,h)}}else Ze.debug(`no formatter found for config bean prop ${this.id}. Returning the raw value`)}return o}getConverter(){var r,o,n,i,a,c,d,u,h,g,m;const{unit:t,measure:e}=this.getConverterFromFormat();if(this.schemaFormat==="drt")return;const s=t==="drt"?"second":t;if(this.converter){const y=(r=this.converter)==null?void 0:r.measure,v=(n=(o=this.converter)==null?void 0:o.to)==null?void 0:n.measure,E=(a=(i=this.converter)==null?void 0:i.from)==null?void 0:a.measure,_=y||v||E||e,N=((d=(c=this.converter)==null?void 0:c.to)==null?void 0:d.unit)||this.regionInfo.getDefaultUnitForMeasure(_,((h=(u=this.converter)==null?void 0:u.to)==null?void 0:h.system)??this.regionInfo.defaultUnitSystem),x=((m=(g=this.converter)==null?void 0:g.to)==null?void 0:m.system)??this.regionInfo.getUnitSystem(N),D=this.schemaFormat==="drt"?"second":this.schemaFormat||s;return{...this.converter,from:{unit:D,...this.converter.from},to:{...this.converter.to,unit:N,system:x},measure:_}}if(s&&e){const y=this.regionInfo.getDefaultUnitForMeasure(e,this.regionInfo.defaultUnitSystem),v=this.regionInfo.getUnitSystem(s),E=this.regionInfo.getUnitSystem(y);return{measure:e,to:{unit:v===E?s:y}}}}async updateProperty(t){Ze.debug(`updating property ${this.attribute} with value ${t}`);let e=t;if(this.getConverter()&&!isNaN(e)){const{backend:o,display:n}=this.getConverterUnits();e=this.regionInfo.convert(Number(e),n,o)}const r=Array.isArray(e)?JSON.stringify(e):String(e);await this.bean.updateProperty(this.attribute,r)}};Uo([mt({modelType:ee.type})],Wt.prototype,"regionInfo",2);Uo([mr({path:Pg,serviceBasePath:Lg})],Wt.prototype,"bean",2);Wt=Uo([R(Rs)],Wt);const Ve={registration:{[Rs]:{class:Wt,singleton:!1}},type:Rs,factory:te.Factory.create(Rs)};function kg(t){const{path:e,attribute:s,converter:r,formatter:o,lazy:n,optionsExpander:i,serviceBasePath:a}=t,c=r;return c&&(typeof c!="function"&&typeof c.from=="string"&&(c.from={unit:c.from}),typeof c!="function"&&typeof c.to=="string"&&(c.to={unit:c.to})),(d,u)=>{d[F]=d[F]||{},d[F][u]={modelType:Ve.type,id:`${e}-${s}`,options:{path:e,attribute:s,serviceBasePath:a,converter:c,formatter:o,optionsExpander:i},lifecycle:H.INIT,lazy:n}}}class Fg{constructor(e,s){l(this,"futures");l(this,"defaultContext");l(this,"context");l(this,"disposers",new Map);l(this,"container");this.futures=Ao.map(new Map),this.context="",this.defaultContext=s||"",this.container=e,M.makeAutoObservable(this)}get allFutures(){return Array.from(this.futures.values())}get future(){return this.futures.get(this.defaultContext)}addFuture(e,s){this.futures.set(s||e.id,e),this.context=s||e.id;const r=G(()=>{var o,n;(e.endState||e.progress)&&((n=(o=this.container)==null?void 0:o.onFutureUpdate)==null||n.call(o,e))});this.disposers.set(s||e.id,r)}removeFuture(e){var s;this.futures.delete(e||this.context),(s=this.disposers.get(e||this.context))==null||s(),this.disposers.delete(e||this.context)}getFuture(e){return this.futures.get(e||this.context)}get futureMap(){return this.futures}}class yr{constructor(e){l(this,"disposer");l(this,"_future");l(this,"container");l(this,"onFutureUpdate");this._future=void 0,this.container=e,M.makeAutoObservable(this)}removeFuture(){var e;this._future=void 0,(e=this.disposer)==null||e.call(this),this.disposer=void 0}get future(){return this._future}getFuture(){return this._future}addFuture(e){this._future=e;const s=G(()=>{var r,o;(e.endState||e.progress)&&((o=(r=this.container)==null?void 0:r.onFutureUpdate)==null||o.call(r,e))});this.disposer=s}get allFutures(){return this._future?[this._future]:[]}get timeRemaining(){var e;return((e=this._future)==null?void 0:e.timeRemaining)||""}get status(){var e;return((e=this._future)==null?void 0:e.status)||"NOT_RESOLVED"}get progress(){var e;return((e=this._future)==null?void 0:e.progress)||-1}async cancel(){if(this._future)try{await this._future.cancelFuture()}catch(e){throw p.error(e),e}}}const _c="future-model",wt=yt(_c),br=p.createLogger({name:"future-service",group:"Services"}),{isMock:Ng,URL:cs}=oe();var xe=(t=>(t.Success="SUCCESS",t.Fail="FAIL",t.Aborted="ABORT",t.Canceled="CANCEL",t))(xe||{});const{getAll:Ug,modifyModel:jg,addModel:Bg,deleteModel:Kg,postModel:Hg}=se.build({destinationAddress:"",basePath:`${cs}/api/future`,mock:Ng}),zg=async()=>await Ug({}),Ic=async(t,e="/api/kos/future")=>(br.info(`sending delete request for Future: ${t}`),await Kg({id:t,urlOverride:`${cs}${e}/${t}`})),Sc=async(t,e="/api/kos/future")=>(br.info("sending add request for Future"),await Bg({model:t,urlOverride:`${cs}${e}`})),Gg=async(t,e,s="/api/kos/future")=>(br.info(`sending modify request for Future: ${t}`),jg({model:e,id:t,urlOverride:`${cs}${s}/${t}`})),Oc=async(t,e="/api/kos/future")=>(br.info(`sending cancel request for Future: ${t}`),Hg({urlOverride:`${cs}${e}/${t}/cancel`,ordered:!0,model:{}})),jo=t=>({id:String(t.id),progress:t.progress,remainingTimeMs:t.remainingTimeMs,endState:t.endState,reason:t.reason,clientData:t.clientData,reasonData:t.reasonData,note:t.note,tracker:t.tracker}),Bo=(t,e)=>{p.debug(`future dto ${t.id} end state ${t.endState}`),p.debug(`future model ${e.id} end state ${e.endState}`),e.endState?p.debug(`future model ${e.id} is already complete`):(p.debug(`updating future model ${e.id}`),M.runInAction(()=>{const s=jo(t);X(()=>{Object.keys(s).forEach(r=>{r==="id"?(e.futureId=s.id,s.tracker||(e.id=s.id)):r==="tracker"?e.id=s.tracker:e[r]=s[r]})})}))},$c=t=>e=>s=>t.build(String(e),s),Ko=t=>e=>sc(jo,$c(t)(e.tracker||e.id))(e);var Vg=Object.defineProperty,Yg=Object.getOwnPropertyDescriptor,Dc=(t,e,s,r)=>{for(var o=r>1?void 0:r?Yg(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Vg(e,s,o),o};const kr=p.getLogger(wt.type);let js=class{constructor(t,e,s){l(this,"logger");l(this,"_cancelFuture");l(this,"futureId");Object.assign(this,e),this.logger=s.logger,this.id=t,this.futureId=e.id,this.namespace=e.namespace||"kos",this._cancelFuture=Oc,Wr(()=>this.status===xe.Success||this.status===xe.Fail,()=>{kr.info(`Future ${this.id} has completed with status ${this.status}`),He(this)})}async load(){kr.debug(`loading Future ${this.id}`)}unload(){kr.info(`unloading Future ${this.id}`)}async cancelFuture(){const t=this.namespace==="studio"?"/api/future":`/api/${this.namespace}/future`;await Wr(()=>this.futureId!==xo),await this._cancelFuture(this.futureId,t)}get status(){return this.endState?this.endState:this.progress>-1?"IN_PROGRESS":"NOT_ACTIVE"}get timeRemaining(){var a,c;const t=this.remainingTimeMs||-1;if(t<0)return"";const e={year:1e3*60*60*24*365,month:1e3*60*60*24*30,day:1e3*60*60*24,hour:1e3*60*60,minute:1e3*60,second:1e3};let s="second",r=0;for(const[d,u]of Object.entries(e))if(Math.abs(t)>=u){s=d,r=Math.round(t/u);break}const n=new Intl.RelativeTimeFormat("en",{numeric:"auto"}).formatToParts(r,s);return n.length===3?`${((a=n[1])==null?void 0:a.value)??0} ${((c=n[2])==null?void 0:c.value)??""}`:"0 seconds"}handleFutureUpdated(t){this.logger.debug(`Future ${this.id} updated. future: ${t.id} endState: ${t.endState} progress: ${t.progress} remainingTimeMs: ${t.remainingTimeMs}`),Bo(t,this)}};Dc([U({topic:`kos.future/${xs}`})],js.prototype,"handleFutureUpdated",1);js=Dc([R(wt.type)],js);const Cc=js,Rc=Oo();var qg=Object.defineProperty,Wg=Object.getOwnPropertyDescriptor,Ac=(t,e,s,r)=>{for(var o=r>1?void 0:r?Wg(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&qg(e,s,o),o};const xc="browser-router-model",Qg="kos.http.request",Zg="kos.http.response";let Bs=class{constructor(t,e,s){l(this,"_id");l(this,"logger");l(this,"router");this._id=t,this.logger=s.logger,this.router=new ic}get id(){return this._id}async handleRequest(t,e){const s=e.headers["src-addr"],r=e.headers["dst-addr"],o=e.headers.url,n=e.headers.method,i=e.headers["request-id"],a={id:i,method:n,path:o,body:t};let c=200;const d={send:u=>{this.logger.debug(`sending response to ${r}`),this.logger.debug(u),Na({msg:u,options:{responseId:i,destinationAddress:s,type:Zg,sourceAddress:r,status:c}})},status:function(u){return c=u,this}};if(a.path==="/openapi.json"){d.send(this.router.generateOpenApiSpec());return}await this.router.handle(a,d)}use(t,e,...s){this.router.use(t,e,...s)}remove(t,e){return this.router.remove(t,e)}removeAllForPath(t){return this.router.removeAllForPath(t)}getRoutes(){return this.router.getRoutes()}async init(){this.logger.debug(`initializing browser-router ${this.id}`)}async load(){this.logger.debug(`loading browser-router ${this.id}`)}};Ac([U({topic:Qg})],Bs.prototype,"handleRequest",1);Bs=Ac([R(xc)],Bs);const Ho=new Ee({class:Bs,type:xc}),Pc="future-container-model",Pe=yt(Pc),Lc=t=>Ko(wt)(t),Xg=t=>{const e=Lc(t);return Pe.build(Pe.type,{}).addFutureModel(e),e},Jg=t=>Pe.build(Pe.type,{}).getFuture(String(t)),ze={buildFutureModel:Lc,initiateFuture:Xg,getFuture:Jg};var ep=Object.defineProperty,tp=Object.getOwnPropertyDescriptor,zo=(t,e,s,r)=>{for(var o=r>1?void 0:r?tp(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&ep(e,s,o),o};const Ms=p.getLogger(Pe.type);let Qt=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_deleteFuture");l(this,"_addFuture");l(this,"_futures");l(this,"createModel");l(this,"deleteModel");const{deleteFuture:r=Ic,addFuture:o=Sc}=e;this.logger=s.logger,this._deleteFuture=r,this._addFuture=o,this.id=t,this._futures=new Te,this.createModel=this.createFuture,this.deleteModel=this.removeFuture}get futures(){return this._futures.data}get models(){return this.futures}getFuture(t){return this._futures.getModel(t)}addFutureModel(t){this._futures.addModel(t)}removeFutureModel(t){this._futures.removeModel(t)}async removeFuture(t){try{await this._deleteFuture(t)}catch(e){Ms.error("error deleting a Future"),Ms.error(e)}}async createFuture(t){try{const e=await this._addFuture(t),s=e==null?void 0:e.data;if(s){const r=Ko(wt)(s);return this.addFutureModel(r),r}}catch(e){throw Ms.error("error creating a Future"),Ms.error(e),e}}handleFutureUpdated(t,e){const s=ze.buildFutureModel(t);this.addFutureModel(s);const r=`kos.future/${t.tracker||t.id}`;this.logger.debug(`publishing future update to ${r}`),j(r,e.body,e.headers)}};zo([be],Qt.prototype,"_futures",2);zo([U({topic:"kos.future"})],Qt.prototype,"handleFutureUpdated",1);Qt=zo([R(Pe.type)],Qt);const kc=Qt,{URL:ls}=oe(),{getOne:sp,postModel:rp,deleteModel:Fc}=se.build({basePath:`${ls}/api/keyVal`}),Qr=p.createLogger({name:"key-value-service",group:"Services"}),Nc=async(t,e)=>{await Fc({urlOverride:`${ls}/api/keyVal/${t}/${e}`,id:e})},Uc=async(t,e,s)=>{const r=await rp({urlOverride:`${ls}/api/keyVal/${t}/${e}`,model:s.toString()});if((r==null?void 0:r.status)!==200)throw Qr.error("Failed to update studio-state data",r),new Error(`Failed to update studio-state data for namespace ${t}`);return r.data},jc=async(t="studio")=>{Qr.debug("sending GET for studio-state");const e=await sp({urlOverride:`${ls}/api/keyVal/${t}`});if((e==null?void 0:e.status)!==200)throw Qr.error("Failed to retrieve studio-state data",e),new Error(`Failed to retrieve studio-state data for namespace ${t}`);return e.data},op=async t=>{await Fc({urlOverride:`${ls}/api/keyVal/${t}}`,id:""})},np=Object.freeze(Object.defineProperty({__proto__:null,deleteKeyValue:Nc,deleteKeyValueNamespace:op,getKeyValue:jc,updateKeyValue:Uc},Symbol.toStringTag,{value:"Module"}));var ip=Object.defineProperty,ap=Object.getOwnPropertyDescriptor,Go=(t,e,s,r)=>{for(var o=r>1?void 0:r?ap(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&ip(e,s,o),o};const Bc="key-value-model";let Zt=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"namespace");l(this,"data");this.id=t,this.logger=s.logger,this.data=Ae(),this.namespace=e.namespace||"studio"}async init(){this.logger.debug(`initializing studio-state ${this.id}`)}async updateState(t,e){this.logger.debug(`updating studio-state ${t} with value ${e}`),e!==void 0?(await Uc(this.namespace,t,e),this.data[t]=e):(await Nc(this.namespace,t),this.data[t]=void 0)}async load(){this.logger.debug(`loading studio-state ${this.id}`);const t=await jc(this.namespace);this.data.setValues(t)}handleStateUpdate(t){t.namespace===this.namespace&&(this.data[t.key]=t.value)}handleStateDelete(t){t.namespace===this.namespace&&(this.data[t.key]=void 0)}};Go([U({topic:"/keyVal/set"})],Zt.prototype,"handleStateUpdate",1);Go([U({topic:"/keyVal/remove"})],Zt.prototype,"handleStateDelete",1);Zt=Go([R(Bc)],Zt);const Vo=new we({class:Zt,type:Bc}),De=Oo(),cp=Object.freeze(Object.defineProperty({__proto__:null,default:De},Symbol.toStringTag,{value:"Module"})),lp=p.createLogger({name:"kos-log-manager-service",group:"Services"}),dp="/api/kos/logs/overrides",Kc=async()=>(lp.debug("sending GET for kos-log-manager"),await De.get(dp)),up=Object.freeze(Object.defineProperty({__proto__:null,getLogOverrides:Kc},Symbol.toStringTag,{value:"Module"}));var hp=Object.defineProperty,fp=Object.getOwnPropertyDescriptor,wr=(t,e,s,r)=>{for(var o=r>1?void 0:r?fp(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&hp(e,s,o),o};const Hc="kos-log-manager-model",gp="/kos/logs/override/add/*",pp="/kos/logs/override/remove/*",mp=t=>{if(typeof t=="string")return t;if(typeof t=="number")switch(t){case 0:return"trace";case 1:return"debug";case 2:return"info";case 3:return"warn";case 4:return"error";default:return"info"}return"info"};let it=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_overrides");this.id=t,this.logger=s.logger,this._overrides=new Co}updateModel(t){}resolveLoggers(){const t=p.getLoggers(),s=Object.entries(t).map(([r,o])=>({name:r,level:mp(o.getLevel())})).reduce((r,{name:o,level:n})=>(r[o]={name:o,level:n},r),{});return this.logger.debug("Resolved loggers",s),s}async getAllLoggers(t,e){const s=Object.values(this.resolveLoggers());return e==null||e.send(s),s}setLogLevels(t){Object.values(this.resolveLoggers()).filter(r=>r.name.startsWith(t.name)).forEach(r=>{const o=p.getLoggers()[r.name];if(!o){this.logger.debug(`Logger ${r.name} not found`);return}o.setLevel(t.level)});const s=p.getLoggers()[t.name];if(!s){this.logger.debug(`Logger ${t.name} not found`);return}s.setLevel(t.level),globalThis.kos.logOverrides=this._overrides.data}resetLogLevels(t){Object.values(this.resolveLoggers()).filter(r=>r.name.startsWith(t.name)).forEach(r=>{const o=p.getLoggers()[r.name];o||this.logger.debug(`Logger ${r.name} not found`),o==null||o.resetLevel()});const s=p.getLoggers()[t.name];s||this.logger.debug(`Logger ${t.name} not found`),s==null||s.resetLevel(),globalThis.kos.logOverrides=this._overrides.data}handleOverrideAdded(t,e){var s;this.logger.debug(`Override received for node type ${((s=e.wildcardCapture)==null?void 0:s.nodeType)??"unknown"}`),this._overrides.addModel({...t,id:t.name}),this.setLogLevels(t)}handleOverrideRemoved(t){this._overrides.removeModel(t.name),this.resetLogLevels(t)}async init(){this.logger.debug(`initializing kos-log-manager ${this.id}`)}async load(){this.logger.debug(`loading kos-log-manager ${this.id}`),this.resolveLoggers();const[t,e]=await Kc();if(t){this.logger.error("Failed to load log overrides",t);return}const s=(e==null?void 0:e.filter(r=>{var o;return((o=r.type)==null?void 0:o.toUpperCase())==="UI"}).map(r=>({name:r.name??"",type:r.type??"",level:r.level??"info",id:r.name||""})))??[];this._overrides.addAll(s),s.forEach(r=>{this.setLogLevels(r)})}};wr([na("/api/kos/ui/loggers")],it.prototype,"getAllLoggers",1);wr([U({topic:gp,websocket:!0,wildcardName:"nodeType"})],it.prototype,"handleOverrideAdded",1);wr([U({topic:pp,websocket:!0,wildcardName:"nodeType"})],it.prototype,"handleOverrideRemoved",1);it=wr([R(Hc)],it);const zc=new Ee({class:it,type:Hc}),{URL:ds}=oe(),{postModel:Yo,getOne:yp}=se.build({basePath:`${ds}/api/kos-time`});p.createLogger({name:"kos-time-service",group:"Services"});const Gc=async t=>{const e=await Yo({model:t,urlOverride:`${ds}/api/kos/time/time`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set time");return e.data},Vc=async t=>{const e=await Yo({model:t,urlOverride:`${ds}/api/kos/time/date`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set time");return e.data},Yc=async t=>{const e=await Yo({model:{},urlOverride:`${ds}/api/kos/time/timezone?tz=${t}`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set timezone");return e.data},qc=async()=>{const t=await yp({urlOverride:`${ds}/api/kos/time/timezone`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set timezone");return t.data.timeZone},bp=Object.freeze(Object.defineProperty({__proto__:null,getTimezone:qc,setDate:Vc,setTime:Gc,setTimezone:Yc},Symbol.toStringTag,{value:"Module"}));var wp=Object.defineProperty,vp=Object.getOwnPropertyDescriptor,vr=(t,e,s,r)=>{for(var o=r>1?void 0:r?vp(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&wp(e,s,o),o};const St="kos-time-model",Mp="/kos/time/time",Ep="/kos/time/day",Tp="/kos/time/timezone";let at=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"timezone");this.id=t,this.logger=s.logger,this.timezone=""}async updateSystemTime(t){await Gc(t)}async updateSystemDate(t){await Vc(t)}async updateSystemTimezone(t){await Yc(t)}handleTimeChange(){j(Ht.TIME_CHANGE,{})}handleDayChange(){j(Ht.DAY_CHANGE,{})}async handleTimeZoneChange(){await this.retrieveTimezone(),j(Ht.TIMEZONE_CHANGE,{})}async init(){this.logger.debug(`initializing kos-time ${this.id}`)}async retrieveTimezone(){const t=await qc();this.setTimezone(t)}setTimezone(t){this.timezone=t}async load(){this.logger.debug(`loading kos-time ${this.id}`),this.retrieveTimezone()}};vr([U({topic:Mp,websocket:!0})],at.prototype,"handleTimeChange",1);vr([U({topic:Ep,websocket:!0})],at.prototype,"handleDayChange",1);vr([U({topic:Tp,websocket:!0})],at.prototype,"handleTimeZoneChange",1);at=vr([R(St)],at);const Ks={registration:{[St]:{class:at,singleton:!0}},type:St,predicate:he(St),factory:te.Singleton.create(St)};var _p=Object.defineProperty,Ip=Object.getOwnPropertyDescriptor,Wc=(t,e,s,r)=>{for(var o=r>1?void 0:r?Ip(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&_p(e,s,o),o};const Qc="log-block-container-model";let Hs=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new Te({parentId:t,sortKey:"blockNum"})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug(`initializing log-block-container container ${this.id}`)}async load(){this.logger.debug(`loading log-block-container container ${this.id}`)}};Wc([be],Hs.prototype,"_models",2);Hs=Wc([R(Qc)],Hs);const Sp=p.createLogger({name:"log-stream-container-service",group:"Services"}),Zc=()=>{var r;const t=ue(),s=(t==null?void 0:t.connId)||((r=window==null?void 0:window.kosBridge)==null?void 0:r.call(window,"connId"));return p.error(`getKosConnectionId: ${s}`),s},vt=Zc(),Op="/api/kos/logs/node/{nodeId}/streams",Xc=async()=>(Sp.debug("sending GET for log-stream-container"),await De.get(Op,{path:{nodeId:"primary"}},{destinationAddress:vt})),Jc=async(t,e="primary")=>{await De.post("/api/kos/logs/node/{nodeId}/{stream}/subscribe",{path:{nodeId:e,stream:t}},void 0,{destinationAddress:vt})},el=async t=>{await De.post("/api/kos/logs/node/{nodeId}/{stream}/unsubscribe",{path:{nodeId:"primary",stream:t}},void 0,{destinationAddress:vt})},$p=async()=>{await De.post("/api/kos/logs/overrides",{},{level:"WARN",name:"com.example",nodeType:"java",type:"package"},{destinationAddress:vt})},tl=async t=>await De.get("/api/kos/logs/node/{nodeId}/{stream}/blocks",{path:{nodeId:"primary",stream:t}},{destinationAddress:vt}),sl=async(t,e)=>await De.get("/api/kos/logs/node/{nodeId}/{stream}/blocks/{blockId}",{path:{nodeId:"primary",stream:t,blockId:e}},{destinationAddress:vt}),Dp=Object.freeze(Object.defineProperty({__proto__:null,createOverride:$p,getKosConnectionId:Zc,getLogStreamBlock:sl,getLogStreamBlocks:tl,getLogStreams:Xc,subscribeToLogStream:Jc,unsubscribeFromLogStream:el},Symbol.toStringTag,{value:"Module"}));var Cp=Object.getOwnPropertyDescriptor,Rp=(t,e,s,r)=>{for(var o=r>1?void 0:r?Cp(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const rl="log-block-model";let Zr=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"nodeId");l(this,"stream");l(this,"blockNum");l(this,"startLineNum");l(this,"endLineNum");l(this,"startTime");l(this,"endTime");l(this,"lineCount");l(this,"lines");l(this,"inc");this.id=t,this.logger=s.logger,this.nodeId=e.nodeId,this.stream=e.stream,this.blockNum=e.blockNum,this.startLineNum=e.startLineNum,this.endLineNum=e.endLineNum,this.startTime=e.startTime,this.endTime=e.endTime,this.lineCount=e.lineCount,this.lines=[],this.inc=0}async syncLines(){const[t,e]=await sl(this.stream,this.blockNum);if(t){this.logger.error(`Failed to get log block ${this.blockNum}`);return}e&&this.addLines(e.lines,!0)}updateModel(t){this.startLineNum=t.startLineNum,this.endLineNum=t.endLineNum,this.startTime=t.startTime,this.endTime=t.endTime,this.lineCount=t.lineCount}addLines(t,e){const s=e?[]:this.lines;this.lines=[...s,...t],this.inc+=1}async init(){this.logger.debug(`initializing log-block ${this.id}`)}async load(){this.logger.debug(`loading log-block ${this.id}`)}};Zr=Rp([R(rl)],Zr);const Xt=new we({class:Zr,type:rl}),Mr=new we({class:Hs,type:Qc});Mr.addRelatedModel(Xt);var Ap=Object.defineProperty,xp=Object.getOwnPropertyDescriptor,ol=(t,e,s,r)=>{for(var o=r>1?void 0:r?xp(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Ap(e,s,o),o};const nl="log-stream-model";let zs=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"nodeId");l(this,"_blocks");l(this,"name");l(this,"currentBlockId");l(this,"isResetting");l(this,"generatorInstance");l(this,"shouldStop",!1);this.id=t,this.logger=s.logger,this.currentBlockId="",this.name=e.name,this.nodeId=e.nodeId,this.isResetting=!0,this._blocks=Mr.instance(`${t}-blocks`).options({}).build()}get firstLineNum(){const t=this.populated[0];return t?t.startLineNum:0}get currentBlock(){const t=this.currentBlockId;return this._blocks.getModel(t)}get populated(){return this._blocks.data.filter(t=>t.lines.length>0)}get blocks(){return this._blocks.data}get totalLineCount(){return this.populated.reduce((t,e)=>t+e.lineCount,0)}accept(t){t.visit(this)}updateBlock(t){var r;let e=this._blocks.models.getModel(`${t.stream}-block-${t.blockNum}`);const s={nodeId:t.nodeId,blockNum:t.blockNum,endLineNum:t.endLineNum,lineCount:t.lineCount,startLineNum:t.startLineNum,stream:this.name,endTime:new Date(t.endTime),startTime:new Date(t.startTime)};e||(e=Xt.instance(`${t.stream}-block-${t.blockNum}`).options(s).build(),this._blocks.addModel(e)),e&&e.updateModel(s),(!this.currentBlock||t.blockNum>=((r=this.currentBlock)==null?void 0:r.blockNum))&&(this.currentBlockId=`${t.stream}-block-${t.blockNum}`)}addBlock(t){var s;const e=Xt.instance(`${t.stream}-block-${t.blockNum}`).options({nodeId:t.nodeId,blockNum:t.blockNum,endLineNum:t.endLineNum,lineCount:t.lineCount,startLineNum:t.startLineNum,stream:this.name,endTime:new Date(t.endTime),startTime:new Date(t.startTime)}).build();this._blocks.addModel(e),(!this.currentBlock||t.blockNum>=((s=this.currentBlock)==null?void 0:s.blockNum))&&(this.currentBlockId=`${t.stream}-block-${t.blockNum}`)}removeBlock(t){this._blocks.models.removeModel(`${this.name}-block-${t}`)}async subscribe(){await Jc(this.name)}async unsubscribe(){await el(this.name)}async reset(){if(this.isResetting=!0,this.populated.length>0)return;this.logger.debug(`resetting log-stream ${this.id}`);for(const e of this._blocks.models.data)e.lines=[];const t=this._blocks.data[this._blocks.data.length-1];t&&await t.syncLines(),this.isResetting=!1}async init(){this.logger.debug(`initializing log-stream ${this.id}`)}async load(){this.logger.debug(`loading log-stream ${this.id}`);const[t,e]=await tl(this.name);if(t){this.logger.error(`Error loading log stream: ${t}`);return}if(e)for(const r of e)this.addBlock(r);const s=this._blocks.data[this._blocks.data.length-1];if(s&&await s.syncLines(),this._blocks.data.length>1){const r=this._blocks.data[this._blocks.data.length-2];r&&await r.syncLines()}}start(){return this.shouldStop=!1,this.generatorInstance=this.streamLogs(),this.generatorInstance}stop(){var t;this.shouldStop=!0,(t=this.generatorInstance)==null||t.next(),console.log("Requested generator stop.")}async*streamLogs(){const t=[];let e=null,s=0,r=this.currentBlockId;const o=lc(()=>{const n=this.currentBlock;return n?{blockId:this.currentBlockId,lineCount:n.lines.length}:null},n=>{const i=this.currentBlock;if(i)if(r!==(n==null?void 0:n.blockId))r=n==null?void 0:n.blockId,s=0,t.push(...i.lines);else{const a=i.lines.slice(s);t.push(...a),s+=a.length}e&&(e(),e=null)},{fireImmediately:!0});try{for(const n of this.populated.filter(i=>i!==this.currentBlock))for(const i of n.lines)yield i;for(;;)for(t.length===0&&await new Promise(n=>e=n);t.length>0;)yield t.shift()}finally{o()}}};ol([be],zs.prototype,"_blocks",2);zs=ol([R(nl)],zs);const zt=new we({class:zs,type:nl});var Pp=Object.defineProperty,Lp=Object.getOwnPropertyDescriptor,Ye=(t,e,s,r)=>{for(var o=r>1?void 0:r?Lp(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Pp(e,s,o),o};const il="log-stream-container-model",kp="/kos/logs/subscription/addBlock/*",Fp="/kos/logs/subscription/updateBlock/*",Np="/kos/logs/subscription/removeBlock/*",Up="/kos/logs/subscription/lines/*",al="/kos/logs/streams/add/*";let Se=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"selectedStream");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new Te({parentId:t}),this.selectedStream=void 0}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}updateModel(t){}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}updateSelectedStream(t){this.selectedStream=t}handleStreamAdded(t){this.logger.debug(`Received topic: ${al}`);const e=t.stream,s=zt.instance(e).options({name:e,nodeId:"primary"}).build();this.addModel(s)}handleAddBlock(t,e){this.logger.debug(`Received topic: ${e.headers.topic}`);const s=t.stream,r=this.models.getModel(s);r&&r.addBlock(t)}handleRemoveBlock(t,e){this.logger.debug(`Received topic: ${e.headers.topic}`);const s=t.stream,r=this.models.getModel(s);r&&r.removeBlock(t.blockNum)}handleUpdateBlock(t,e){this.logger.debug(`Received topic: ${e.headers.topic}`);const s=t.stream,r=this.models.getModel(s);r&&r.updateBlock(t)}handleLogLine(t,e){var o;this.logger.debug(`Received topic: ${e.headers.topic}`);const s=t.stream,r=this.models.getModel(s);r&&((o=r.currentBlock)==null||o.addLines(t.lines))}async init(){this.logger.debug(`initializing log-stream-container container ${this.id}`)}async subscribeToLogStream(t){const e=zt.instance(t).options({name:t,nodeId:"primary"}).build();this.addModel(e),await e.subscribe()}async load(){this.logger.debug(`loading log-stream-container container ${this.id}`);const[t,e]=await Xc();if(t){this.logger.error(`Error loading log-streams: ${t}`);return}e&&e.forEach(s=>{const r=zt.instance(s).options({name:s,nodeId:"primary"}).build();this.addModel(r)})}};Ye([be],Se.prototype,"_models",2);Ye([U({topic:[al],websocket:!0})],Se.prototype,"handleStreamAdded",1);Ye([U({topic:[kp],websocket:!0})],Se.prototype,"handleAddBlock",1);Ye([U({topic:[Np],websocket:!0})],Se.prototype,"handleRemoveBlock",1);Ye([U({topic:[Fp],websocket:!0})],Se.prototype,"handleUpdateBlock",1);Ye([U({topic:[Up],websocket:!0})],Se.prototype,"handleLogLine",1);Se=Ye([R(il)],Se);const us=new Ee({class:Se,type:il});us.addRelatedModel(zt);us.addRelatedModel(Mr);us.addRelatedModel(Xt);const jp=t=>t.rank!==void 0,Bp=t=>t.visibleRole!==void 0,Kp=t=>t.color!==void 0,Hp=t=>{const e=t.info;return jp(e)?e.rank:0},zp=t=>{const e=t.info;return Kp(e)?e.color:"orange"},Gp=t=>{const e=t.info;return Bp(e)?e.visibleRole:"TECHNICIAN"},{URL:qo}=oe(),{getAll:Vp,postModel:cl}=se.build({basePath:`${qo}/api/kos/troubles`}),ll=async()=>await Vp({}),dl=async(t,e)=>{try{const s=await cl({model:{},urlOverride:`${qo}/api/kos/troubles/resolve/${t}`,tracker:e});return s!=null&&s.data&&ze.initiateFuture(s.data),s.data}catch{const r={id:e||"",endState:xe.Fail,tracker:e,reason:"Failed to resolve trouble"};return ze.initiateFuture(r),r}},Yp=async(t,e)=>{try{const s=await cl({model:t,urlOverride:`${qo}/api/kos/troubles/resolve/`,tracker:e});return s!=null&&s.data&&ze.initiateFuture(s.data),s.data}catch{const r={id:e||"",endState:xe.Fail,tracker:e,reason:"Failed to resolve troubles"};return ze.initiateFuture(r),r}},qp=Object.freeze(Object.defineProperty({__proto__:null,bulkResolveTroubles:Yp,getTroubles:ll,resolveTrouble:dl},Symbol.toStringTag,{value:"Module"})),Gs="troubleDataMapper",Es=new Map;is(Gs,{register:(t,e)=>{var s;Es.has(t)||Es.set(t,[]),(s=Es.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=Es.get(t);if(!s)return{...e.data};const r=s.map(i=>i(e));return(await Promise.allSettled(r)).reduce((i,a)=>(a.status==="fulfilled"?i={...i,...a.value}:p.info(`Trouble mapper ${t} failed: ${a.reason}`),i),{...e.data})}});const hs="troubleMapper",Ts=new Map;is(hs,{register:(t,e)=>{var s;Ts.has(t)||Ts.set(t,[]),(s=Ts.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=Ts.get(t);if(!s)return[];const r=s.map(i=>i(e)),n=(await Promise.allSettled(r)).map(i=>i.status==="fulfilled"?i.value:(p.info(`Trouble mapper ${t} failed: ${i.reason}`),[])).flat();return Array.from(new Set(n))}});S[hs].register("nozzle",async t=>[t.data.nozzlePath]);S[hs].register("path",async t=>[t.data.path]);const Wp=async t=>{const e=new Set,s=t.ifaces,r=s==null?void 0:s.map(n=>S[hs].execute(n,t));return(await Promise.allSettled(r)).forEach(n=>{n.status==="fulfilled"&&n.value.forEach(i=>e.add(i))}),Array.from(e)},ul=async t=>{const e=t.ifaces,s=e==null?void 0:e.map(i=>S[Gs].execute(i,t)),r=S[Gs].execute(t.type,t);s.push(r);const n=(await Promise.allSettled(s)).reduce((i,a)=>(a.status==="fulfilled"&&(i={...i,...a.value}),i),{});return{...t.data,...n}};class Qp{constructor(){l(this,"type","ResolvableTrouble");l(this,"title","Resolvable Trouble");l(this,"subtitle","Trouble")}}class Zp{constructor(){l(this,"type","BlockPumpTrouble");l(this,"title","Block Pump Trouble");l(this,"subtitle","Trouble")}}class Xe{static getHandler(e){switch(e){case"ResolvableTrouble":return new Qp;case"BlockPumpTrouble":return new Zp;default:return}}}var Xp=Object.defineProperty,Jp=Object.getOwnPropertyDescriptor,hl=(t,e,s,r)=>{for(var o=r>1?void 0:r?Jp(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Xp(e,s,o),o};const Ot="trouble-model";function _s(t){return typeof t.shouldDefer=="boolean"}let Vs=class{constructor(t,{resolvable:e,tags:s,info:r,id:o,clientData:n,rank:i,ifaces:a,type:c,group:d,createTime:u,role:h,color:g,...m},y){l(this,"id");l(this,"logger");l(this,"_troubleId");l(this,"_resolvable");l(this,"type");l(this,"futureHandler");l(this,"ifaces");l(this,"clientData");l(this,"info");l(this,"role");l(this,"color");l(this,"tags");l(this,"data");l(this,"rank");l(this,"group");l(this,"createTime");l(this,"_mapped",{});this.id=t,this.logger=y.logger,this.type=c,this._troubleId=o,this._resolvable=!!e,this.ifaces=a,this.rank=i,this.role=h,this.color=g,this.tags=s,this.info=r,this.group=d,this.createTime=u,this.clientData=n,this.data={},Object.assign(this.data,m),this.futureHandler=new yr(this)}getTitleWithContext(t){var s,r;const e=t?(r=(s=Xe.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[t]:Xe.getHandler(this.type);return(e==null?void 0:e.title)||"Trouble"}getSubtitleWithContext(t){var s,r;const e=t?(r=(s=Xe.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[t]:Xe.getHandler(this.type);return(e==null?void 0:e.subtitle)||"Trouble"}get rawId(){return this._troubleId}get title(){var t;return((t=Xe.getHandler(this.type))==null?void 0:t.title)||"Trouble"}get subtitle(){var t;return((t=Xe.getHandler(this.type))==null?void 0:t.subtitle)||"Trouble"}get troubleId(){return this._troubleId}get resolvable(){return this._resolvable}get future(){return this.futureHandler.future}async resolveMappedData(){return await ul(this)}get deferredCompanion(){const t=Yr(this.id,e=>_s(e));if(t&&_s(t.modelData))return t.modelData}get deferred(){return this.deferredCompanion?this.deferredCompanion.deferred:!1}get shouldDefer(){const t=Yr(this.id,e=>_s(e));return t&&_s(t.modelData)?t.modelData.shouldDefer:!1}clearDefer(){var t;(t=this.deferredCompanion)==null||t.clearDefer()}defer(){var t;(t=this.deferredCompanion)==null||t.defer()}getChildren(){return[...this.futureHandler.allFutures]}async resolve(t){var e;if(!this._resolvable)throw this.logger.error(`attempting to resolve an unresolvable trouble with id ${this._troubleId}`),new Error("Trouble is not resolvable");if(this.shouldDefer){(e=this.deferredCompanion)==null||e.defer();return}return await dl(this._troubleId,t)}};hl([hn()],Vs.prototype,"resolve",1);Vs=hl([R(Ot)],Vs);const Jt={registration:{[Ot]:{class:Vs,singleton:!1}},type:Ot,predicate:he(Ot),factory:te.Factory.create(Ot)};var em=Object.defineProperty,tm=Object.getOwnPropertyDescriptor,Er=(t,e,s,r)=>{for(var o=r>1?void 0:r?tm(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&em(e,s,o),o};const Kn=p.createLogger({name:"trouble-container-model"});function Hn(t){return S.propertyMapper.hasMapper(me.TroubleRank)?S.propertyMapper.executeMapper(me.TroubleRank,t):Hp(t)}function zn(t){return(S.propertyMapper.hasMapper(me.TroubleColor)?S.propertyMapper.executeMapper(me.TroubleColor,t):zp(t)).toLowerCase()}function Gn(t){return(S.propertyMapper.hasMapper(me.TroubleRole)?S.propertyMapper.executeMapper(me.TroubleRole,t):Gp(t)).toLowerCase()}const sm="trouble-container-model";class de{}l(de,"INDEX_TROUBLES_BY_IFACE","byIface"),l(de,"INDEX_TROUBLES_BY_TYPE","byType"),l(de,"INDEX_TROUBLES_BY_GROUP","byGroup"),l(de,"INDEX_TROUBLES_BY_DEFERRED","byDeferred"),l(de,"SORT_KEY_RANK","rank"),l(de,"TROUBLES_DEFERRED","true");let ct=class{constructor(t){l(this,"id");l(this,"troubles");this.id=t,this.troubles=new Te({indexMap:{[de.INDEX_TROUBLES_BY_IFACE]:Wp,[de.INDEX_TROUBLES_BY_TYPE]:"type",[de.INDEX_TROUBLES_BY_GROUP]:"group",[de.INDEX_TROUBLES_BY_DEFERRED]:"deferred"},sortKey:de.SORT_KEY_RANK,parentId:t})}async load(){Kn.debug("loading trouble container");const t=await ll();try{t==null||t.data.forEach(e=>{const s={...e,rank:Hn(e),color:zn(e),role:Gn(e),id:String(e.id)},r=Jt.factory(`trouble-${e.id}`)(s);this.troubles.addModel(r)})}catch(e){throw Kn.error(e),e}}handleTroubleRemoved(t){const e=`trouble-${t}`,s=this.troubles.getModel(e);this.troubles.removeModel(e),s&&He(s)}handleTroubleAdded(t){const e={...t,rank:Hn(t),color:zn(t),role:Gn(t),id:String(t.id)};if(e.role==="NONE")return;const s=Jt.factory(`trouble-${t.id}`)(e);this.troubles.addModel(s)}};Er([be],ct.prototype,"troubles",2);Er([U({topic:"/kos/trouble/remove",websocket:!0,lifecycle:H.INIT})],ct.prototype,"handleTroubleRemoved",1);Er([U({topic:"/kos/trouble/add",websocket:!0})],ct.prototype,"handleTroubleAdded",1);ct=Er([R(sm)],ct);const Is="trouble-container-model",lt={registration:{[Is]:{class:ct,singleton:!0}},type:Is,predicate:he(Is),factory:te.Singleton.create(Is)},{URL:fl}=oe(),{getAll:rm}=se.build({basePath:`${fl}/api/kos/ota`}),Vn=p.createLogger({name:"ota-service",group:"Services"}),om=async()=>{Vn.debug("sending GET request to /api/kos/ota/artifacts");const t=await rm({urlOverride:`${fl}/api/kos/ota/artifacts`});return Vn.debug("getArtifacts - response:",t),t==null?void 0:t.data};var nm=Object.defineProperty,im=Object.getOwnPropertyDescriptor,Tr=(t,e,s,r)=>{for(var o=r>1?void 0:r?im(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&nm(e,s,o),o};const gl="ota-model",am=t=>{let e=null;for(const s in t){const r=t[s],o=r.lastUpdateTime;(!e||e.lastUpdateTime<o)&&(e=r)}return e},Fr=t=>{const e=t.artifactInfo,s=am(t.requests),r=(e==null?void 0:e.identifier)||(s==null?void 0:s.kabId);if(!r)return;let o;switch(t.status){case"INSTALLED":o="ready";break;case"INVALID":o="error";break;case"MISSING":o=((s==null?void 0:s.currentSize)||0)>0?"downloading":"idle";break;case"STAGED":o="pending"}const n=e===void 0;return{id:r,manifest:n,label:e==null?void 0:e.version,name:e==null?void 0:e.name,status:o,error:o==="error"?s==null?void 0:s.lastErrorReason:void 0,errorCount:o==="error"?s==null?void 0:s.errorCount:0,progress:o==="downloading"&&s&&!n?s.currentSize/(e==null?void 0:e.size)*100:void 0,size:e==null?void 0:e.size}};let dt=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"data",new Co);l(this,"troubleContainer");this.id=t,this.logger=s.logger}get downloadInProgressTrouble(){var e;return(e=this.troubleContainer.troubles.getIndexByKey("byType","OTADownloadInProgressTrouble"))==null?void 0:e[0]}get updatePendingTrouble(){var e;return(e=this.troubleContainer.troubles.getIndexByKey("byType","OTAUpdatePendingTrouble"))==null?void 0:e[0]}get pausedDueToErrorsTrouble(){var e;return(e=this.troubleContainer.troubles.getIndexByKey("byType","OTAPausedDueToErrorsTrouble"))==null?void 0:e[0]}get updates(){return this.data}get status(){return this.pausedDueToErrorsTrouble?"error":this.downloadInProgressTrouble?"downloading":this.updatePendingTrouble?"pending":"idle"}installAndReboot(){var t;this.updatePendingTrouble||this.logger.error("installAndReboot - OTAUpdatePendingTrouble not present"),this.logger.debug("installAndReboot - resolve OTAUpdatePendingTrouble"),(t=this.updatePendingTrouble)==null||t.resolve()}async init(){this.logger.debug(`initializing ota ${this.id}`)}async load(){this.logger.debug(`loading ota ${this.id}`);try{const t=await om();t&&t.forEach(e=>{const s=Fr(e);s&&this.data.addModel(s)})}catch(t){this.logger.error(`loading ota ${this.id} - error:`,t)}}async handleAllArtifacts(t){this.logger.debug("handleAllArtifacts:",t),await this.data.clear();try{t.forEach(e=>{const s=Fr(e);s&&this.data.addModel(s)})}catch(e){this.logger.error(`handleAllArtifacts ${this.id} - error:`,e)}}handleChangedArtifacts(t){this.logger.debug("handleChangedArtifacts:",t);try{t.forEach(e=>{const s=Fr(e);s&&this.data.updateModel(s)})}catch(e){this.logger.error(`handleChangedArtifacts ${this.id} - error:`,e)}}};Tr([mt({modelType:lt.type})],dt.prototype,"troubleContainer",2);Tr([U({topic:"/kos/ota/artifacts/all",websocket:!0})],dt.prototype,"handleAllArtifacts",1);Tr([U({topic:"/kos/ota/artifacts/changed",websocket:!0})],dt.prototype,"handleChangedArtifacts",1);dt=Tr([R(gl)],dt);const Ys=new Ee({class:dt,type:gl});function cm(t){let e;const s=async(...r)=>{e&&e.abort(),e=new AbortController;const o=e;try{return await t(...r,o.signal)}finally{e===o&&(e=void 0)}};return s.cancel=()=>{e&&(e.abort(),e=void 0)},s.getController=()=>e,s.isActive=()=>!!e,s}const Nr=p.createLogger({name:"software-info-service",group:"Services"}),Wo=async t=>{Nr.debug("sending GET for software-info");const[e,s]=await Rc.get("/api/kos/manifest/info",void 0,{signal:t});if(!s)throw t!=null&&t.aborted?(Nr.debug("Request was aborted"),new B("Request was aborted")):(Nr.error("Failed to fetch software-info",e),new B("Failed to fetch software-info"));return s},lm=cm(Wo),dm=Object.freeze(Object.defineProperty({__proto__:null,getSoftwareInfos:Wo,getSoftwareInfosWithCancel:lm},Symbol.toStringTag,{value:"Module"}));var um=Object.getOwnPropertyDescriptor,hm=(t,e,s,r)=>{for(var o=r>1?void 0:r?um(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const $t="software-info-model";let Xr=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"nodes");this.id=t,this.logger=s.logger,this.nodes=[]}async init(){this.logger.debug(`initializing software-info ${this.id}`)}groupBy(t,e){return t.reduce((s,r)=>(s[r[e]]=[...s[r[e]]||[],r],s),{})}async load(){this.logger.debug(`loading software-info ${this.id}`);try{const t=await Wo(),e=(t==null?void 0:t.nodes)||{};X(()=>{const r=Object.keys(e).map(o=>e[o][0]).map(o=>({nodeName:o.nodeType,kosVersion:o.kosVersion,group:this.groupBy(o.artifacts,"group")}));this.nodes=r})}catch(t){t instanceof B&&this.logger.error("Failed to fetch software-info",t)}}};Xr=hm([R($t)],Xr);const qs={registration:{[$t]:{class:Xr,singleton:!1}},type:$t,predicate:he($t),factory:te.Factory.create($t)},{URL:pl}=oe(),{getOne:fm}=se.build({basePath:`${pl}/api/kos/state`}),gm=p.createLogger({name:"state-bean-service",group:"Services"}),ml=async({path:t})=>(gm.debug("sending GET for state-bean"),await fm({urlOverride:`${pl}/api/kos/state/${t}`})),pm=Object.freeze(Object.defineProperty({__proto__:null,getStateBeanData:ml},Symbol.toStringTag,{value:"Module"}));var mm=Object.defineProperty,ym=Object.getOwnPropertyDescriptor,yl=(t,e,s,r)=>{for(var o=r>1?void 0:r?ym(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&mm(e,s,o),o};const Dt="state-bean-model",bm=Ge("path");let Ws=class{constructor(t,e,s){l(this,"id");l(this,"path");l(this,"props");l(this,"logger");this.id=t,this.logger=s.logger,this.props=Ao.map(new Map),zr(e,this)}updateModel(t){zr(t,this)}handleConfigBeanUpdated(t){Object.entries(t).forEach(([e,s])=>{let r=s;typeof r=="string"&&Lo(r)&&(r=r.toLowerCase()=="true"),typeof r=="string"&&pr(r)&&(r=Number(r)),this.props.set(e,r)})}async init(){this.logger.debug(`initializing state-bean ${this.id}`)}updateProps(t){Object.entries(t).forEach(([e,s])=>{this.props.set(e,s)})}async load(){this.logger.debug(`loading state-bean ${this.id}`);const t=await ml({path:this.path});t!=null&&t.data&&this.updateProps(t.data)}};yl([U({topic:`/kos/state/${bm}`,websocket:!0})],Ws.prototype,"handleConfigBeanUpdated",1);Ws=yl([R(Dt)],Ws);const es={registration:{[Dt]:{class:Ws,singleton:!1}},type:Dt,predicate:he(Dt),factory:te.Factory.create(Dt)};var wm=Object.defineProperty,vm=Object.getOwnPropertyDescriptor,bl=(t,e,s,r)=>{for(var o=r>1?void 0:r?vm(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&wm(e,s,o),o};const Ct="state-prop-model",Yn=Ge("path");let Qs=class{constructor(t,e,s){l(this,"id");l(this,"path");l(this,"attribute");l(this,"logger");l(this,"stateBean");this.id=t,this.logger=s.logger,this.path=e.path,this.attribute=e.attribute}get value(){return this.stateBean.props.get(this.attribute)}async init(){this.logger.debug(`initializing state-prop ${this.id}`)}async load(){this.logger.debug(`loading state-prop ${this.id}`)}toString(){var t;return((t=this.value)==null?void 0:t.toString())??""}};bl([mt({modelType:es.type,id:`state-bean-${Yn}`,options:{path:Yn}})],Qs.prototype,"stateBean",2);Qs=bl([R(Ct)],Qs);const Qo={registration:{[Ct]:{class:Qs,singleton:!1}},type:Ct,predicate:he(Ct),factory:te.Factory.create(Ct)},{URL:Mm}=oe(),{getAll:Em}=se.build({basePath:`${Mm}/api/state-prop`}),Tm=p.createLogger({name:"state-prop-service",group:"Services"}),_m=async()=>(Tm.debug("sending GET for state-prop"),await Em({})),Im=Object.freeze(Object.defineProperty({__proto__:null,getStateProps:_m},Symbol.toStringTag,{value:"Module"})),{URL:Zo}=oe(),{getOne:wl}=se.build({basePath:`${Zo}/api/translation`}),Gt=p.createLogger({name:"translation-service",group:"Services"}),Sm=()=>{const t=window.location.origin,e=ue();return(e==null?void 0:e.host)||t},vl=async(t,e)=>{Gt.debug("sending GET for translation");const s=e??Sm();try{const r=await fetch(`${s}${t}`);return r.status!==200?(Gt.warn(`Failed to fetch translations at ${t}: ${r.status}`),{}):await r.json()}catch(r){throw Gt.error("Error fetching translations",r),r}},Om=async()=>{Gt.debug("getting localization descriptor");const t=await wl({urlOverride:`${Zo}/api/system/kos/localization`});if((t==null?void 0:t.status)!==200)throw new Error(`Failed to get tool localization descriptor ${t==null?void 0:t.status}`);return t.data},Ml=t=>async()=>{Gt.debug("getting kos localization descriptor");const e=await wl({urlOverride:`${Zo}/api/kos/localization/contexts`});if((e==null?void 0:e.status)!==200)throw new Error(`Failed to get tool localization descriptor ${e==null?void 0:e.status}`);return e.data[t]},El="langResolver";var $m=Object.getOwnPropertyDescriptor,Dm=(t,e,s,r)=>{for(var o=r>1?void 0:r?$m(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const Rt="translation-model";function Cm(t){const e=typeof t=="string",s=e?!1:!!(t!=null&&t.data)&&typeof(t==null?void 0:t.data)!="string",r=e?t:t==null?void 0:t.defaultValue,o=e||t==null?void 0:t.context,n=e?void 0:s?t==null?void 0:t.data:t;return{isBasicOptions:e,defaultValue:r,context:o,data:n}}function Tl(t,e=""){return Object.keys(t).reduce((s,r)=>{const o=e?`${e}.${r}`:r;if(typeof t[r]=="object"&&t[r]!==null){const n=Tl(t[r],o);return{...s,...n}}else return{...s,[o]:t[r]}},{})}function _l(t,e){const s={...t};for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(typeof e[r]=="object"&&e[r]!==null&&typeof t[r]=="object"&&t[r]!==null?s[r]=_l(t[r],e[r]):s[r]=e[r]);return s}const Jr=(t,e)=>{const s=/__(.*?)__/g,r=t.replace(s,(o,n)=>Object.prototype.hasOwnProperty.call(e||{},n.trim())?e==null?void 0:e[n.trim()]:o);return r===t?r:s.test(r)?Jr(r,e):r},Ss=(t,e,s)=>{const r=/{{(.*?)}}/g,n=Jr(t,e).replace(r,(a,c)=>Object.prototype.hasOwnProperty.call(s||{},c.trim())?s==null?void 0:s[c.trim()]:a);return Jr(n,e)},qn=(t,e)=>{if(e.includes(":")){const[s,r]=e.split(":");return{namespace:s,key:r}}else return{namespace:t,key:e}};let eo=class{constructor(t,e,s){l(this,"id");l(this,"namespace");l(this,"descriptor");l(this,"defaultLocale");l(this,"currentLocale");l(this,"bundleResolver");l(this,"data");l(this,"logger");l(this,"resolver");l(this,"disposer");l(this,"context");l(this,"rootUrl");this.id=t,this.defaultLocale=e.defaultLocale||"en",this.currentLocale=e.currentLocale||"en",this.namespace=e.namespace,this.descriptor=e.descriptor,this.rootUrl=e.rootUrl,this.data={},this.resolver=e.resolver||s.kosContext.get(El),this.bundleResolver=e.bundleResolver,this.logger=s.logger,this.context=s.kosContext.parentModel}getTranslationLocales(t){const e=this.descriptor[t];if(!t||!e)return[this.defaultLocale];if(!this.defaultLocale&&!e.fallbacks)return[t];let s=e.fallbacks||[this.defaultLocale];return s.includes(t)||(s=[t,...s]),s}async loadTranslations(){const t=this.getTranslationLocales(this.currentLocale).reverse(),e=t.map(r=>{if(this.bundleResolver){const o=z.getContext(this.id);return this.bundleResolver(this.namespace,r,o)}try{const o=this.resolver(this.namespace,r);return vl(o,this.rootUrl)}catch{return Promise.resolve({})}}),s=await Promise.allSettled(e);X(()=>{const r=s.reduce((o,n,i)=>(n.status==="fulfilled"?(this.logger.debug(`resolved ${t[i]}`,n.value),n.value&&(o=_l(o,n.value))):this.logger.error(`failed to load translation ${this.id} for ${t[i]}`),o),{});this.data=Tl(r)})}async init(){this.logger.debug(`initializing translation ${this.id}`)}exists(t){const{namespace:e,key:s}=qn(this.namespace,t);if(e!==this.namespace){const r=this.context.getModel(e);return r?r.exists(s):!1}return!!this.data[s]}resolveKey(t,e){if(!t)return this.logger.debug("key is empty"),"";const{defaultValue:s,context:r,data:o}=Cm(e),{namespace:n,key:i}=qn(this.namespace,t),a=`${i}_${r}`;if(n!==this.namespace){const c=this.context.getModel(n);return c?c.resolveKey(i,e):i}if(r&&this.data[a]){const c=this.data[a];return Array.isArray(c)?c.map(d=>Ss(d,this.data,o)):Ss(this.data[a],this.data,o)}if(this.data[i]){const c=this.data[a];return Array.isArray(c)?c.map(d=>Ss(d,this.data,o)):Ss(this.data[i],this.data,o)}return s??i}unload(){this.logger.debug(`unloading translation ${this.id}`),this.disposer&&this.disposer()}async load(){this.logger.debug(`loading translation ${this.id}`),await this.loadTranslations()}async ready(){this.logger.debug(`ready translation ${this.id}`),this.disposer=M.reaction(()=>this.currentLocale,(t,e)=>{this.logger.info(`translation langs for namespace ${this.id} changed from ${e} to ${t}`),this.loadTranslations()})}};eo=Dm([fr(),R(Rt)],eo);const Zs={registration:{[Rt]:{class:eo,singleton:!1}},type:Rt,predicate:he(Rt),factory:te.Factory.create(Rt)};var Rm=Object.defineProperty,Am=Object.getOwnPropertyDescriptor,Il=(t,e,s,r)=>{for(var o=r>1?void 0:r?Am(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Rm(e,s,o),o};const At="translation-container-model",xm=(t,e="/")=>t.join(e).replace(new RegExp(e+"{1,}","g"),e);function Pm(t,e){const s=this.descriptor.namespaces[t];if(!s)throw new Error(`namespace ${t} not found in descriptor`);const r=s.basePath,o=s.locales[e].file;return xm([r,o])}let Xs=class{constructor(t,e,s){l(this,"id");l(this,"lang");l(this,"rootUrl");l(this,"descriptor");l(this,"_defaultNamespace");l(this,"resolver");l(this,"logger");l(this,"descriptorUrl");l(this,"namespaces",[]);l(this,"_models");this.id=t,this.lang=e.lang||"en",this.descriptor=e.descriptor,this._defaultNamespace=e.defaultNamespace,this.descriptorUrl=e.descriptorUrl,this.rootUrl=e.rootUrl,this.resolver=e.resolver||Pm.bind(this),s.kosContext.set(El,this.resolver),this.logger=s.logger,this._models=new Te({parentId:t})}set currentLocale(t){this.lang=t,this.models.data.forEach(e=>{e.currentLocale=t})}get defaultNamespace(){return this._defaultNamespace?this.getModel(`translation-${this._defaultNamespace}`):void 0}getModel(t){return this.logger.debug(`getting model ${t}`),this._models.getModel(`translation-${t}`)}get models(){return this._models}get data(){return this._models.data}async reload(){for(const t of this.namespaces){const e=this.resolveNamespace(t);await ae(e)}}resolveNamespace(t){var s;if((s=this.descriptor.namespaces)==null?void 0:s[t]){const r=Object.keys(this.descriptor.namespaces[t].locales)[0],o=this.descriptor.namespaces[t].locales[r].defaultLocale,n=Zs.factory(`translation-${t}`)({kosParentId:this.id,namespace:t,rootUrl:this.rootUrl,currentLocale:this.lang,defaultLocale:o,descriptor:this.descriptor.namespaces[t].locales,resolver:this.resolver});return this.addModel(n),this.namespaces.includes(t)||X(()=>{this.namespaces.push(t)}),n}else{this.logger.warn(`namespace ${t} not found in descriptor`);const r=Zs.factory(`translation-${t}`)({kosParentId:this.id,namespace:t,rootUrl:this.rootUrl,currentLocale:this.lang,defaultLocale:this.lang,descriptor:{},resolver:this.resolver});return this.addModel(r),r}}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug(`initializing translation-container container ${this.id}`)}async load(){this.logger.debug(`loading translation-container container ${this.id}`)}};Il([be],Xs.prototype,"_models",2);Xs=Il([R(At)],Xs);const Oe={registration:{[At]:{class:Xs,singleton:!0}},type:At,predicate:he(At),factory:te.Singleton.create(At)},Lm={set(t,e){const s=z.getContext(Oe.type);s&&s.set(t,e)},get(t){const e=z.getContext(Oe.type);return e==null?void 0:e.get(t)}},Sl={async init(t){const e=Oe.factory(t);return await ae(e),{translations:e}}};function km(t){return t.troubles!==void 0&&t.troubles instanceof Array&&t.troublesByType!==void 0&&typeof t.troublesByType=="object"}const Fm=(t,e)=>{const s=e.type;return t[s]||(t[s]=[]),t[s].push(e),t},Ol="kos-ws-event",Xo=yt(Ol);var Nm=Object.defineProperty,Um=Object.getOwnPropertyDescriptor,Jo=(t,e,s,r)=>{for(var o=r>1?void 0:r?Um(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Nm(e,s,o),o};const jm=({headers:t,body:e})=>Object.entries(t).map(([r,o])=>`${r}:${o}`).join("\\n")+"\\n\\n"+e;exports.WsEventModel=class{constructor(e){l(this,"id");l(this,"events");l(this,"_topicMap");this.id=e,this.events=M.observable.map(new Map),this._topicMap=new Map}get websocketEvents(){return Array.from(this.events.values())}handleSendEvent(e,s){this.processEvent(s,!0)}handleReceiveEvent(e,s){this.processEvent(s)}processEvent(e,s=!1){p.debug("kos event received");const{body:r,headers:o}=e.body,n=o["request-id"]||o["response-id"],i=o["request-id"]||o["response-id"]||o.topic||o.type;if(i){let a=i;if(n)a=`${a}-${s?"send":"receive"}`;else{const d=this._topicMap.get(i)||0;a=`${a}-${d+1}`,this._topicMap.set(i,d+1)}const c={msgId:a,content:r,headers:o,timestamp:Date.now(),raw:jm({headers:o,body:r}),direction:s?"send":"receive",mocked:!!o.mocked};this.events.set(a,c),p.debug(`logged ${this.events.size} events`)}}};Jo([U({topic:[ns.SEND]})],exports.WsEventModel.prototype,"handleSendEvent",1);Jo([U({topic:[ns.RECEIVED]})],exports.WsEventModel.prototype,"handleReceiveEvent",1);exports.WsEventModel=Jo([R(Xo.type)],exports.WsEventModel);const Wn=ue(),Bm=Wn.debug==="true"||Wn.debug===!0,Km="/api/system/canvas",$l=async(t,e)=>{const s=e||Km,r=`${exports.BASE_URL}${s}`;await exports.kosFetch(r,{method:"POST",headers:{hide:Bm?"false":"true"},body:t})},Hm=Object.freeze(Object.defineProperty({__proto__:null,sendCanvasData:$l},Symbol.toStringTag,{value:"Module"}));function Qn(t,e,s){{const r=t.filter((o,n)=>n%4!==3);return btoa(String.fromCharCode(...r))}}var zm=Object.defineProperty,Gm=Object.getOwnPropertyDescriptor,Dl=(t,e,s,r)=>{for(var o=r>1?void 0:r?Gm(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&zm(e,s,o),o};const Cl="canvas-renderer-model";function Ur(t){return typeof t.onDone=="function"}let Js=class{constructor(t,e,s){l(this,"id");l(this,"router");l(this,"logger");l(this,"_renderer",null);l(this,"_clearOnComplete");l(this,"isStreaming",!1);l(this,"renderLoopId",null);l(this,"sendIntervalId",null);l(this,"timeoutId",null);l(this,"apiPath");l(this,"endpointName");l(this,"width",50);l(this,"height",30);l(this,"fps",10);l(this,"durationMs",null);l(this,"_onFrame",null);this.id=t,this.logger=s.logger,this.width=e.width??50,this.height=e.height??30,this.fps=e.fps??10,this.durationMs=e.durationMs??null,this.apiPath=e.apiPath??"/api/system/canvas",this.endpointName=e.endpoint}set onFrame(t){this._onFrame=t}set renderer(t){var e,s;this._renderer&&(this.stopStreaming(),(s=(e=this._renderer).dispose)==null||s.call(e)),this._renderer=t,this.isStreaming&&this.startStreaming()}setClearOnComplete(t){this._clearOnComplete=t}sendDataFrame(t,e){$l(t,e)}checkStreaming(){if(this.isOneShotDone()||!this.isStreaming){requestAnimationFrame(()=>{const t=this.isOneShotDone();this.stopStreaming(!t)});return}}handleFrame(t){var s;const e=Qn(t);this.sendDataFrame(e,this.apiPath),(s=this._onFrame)==null||s.call(this,e)}stopStreaming(t=!0){var e,s;this.logger.debug(`stopStreaming called with clearCanvas=${t}`),this.isStreaming=!1,this.renderLoopId&&cancelAnimationFrame(this.renderLoopId),this.sendIntervalId&&clearInterval(this.sendIntervalId),this.timeoutId&&clearTimeout(this.timeoutId),(s=(e=this._renderer)==null?void 0:e.pause)==null||s.call(e),t&&(this.logger.debug("Clearing canvas..."),this.clearCanvas())}clearCanvas(){var s;const t=this.width>0?this.width:50,e=this.height>0?this.height:30;if(t>0&&e>0){const r=t*e*4,o=new Uint8ClampedArray(r);for(let i=3;i<r;i+=4)o[i]=255;const n=Qn(o);this.logger.debug(`Sending clear frame: ${t}x${e}, apiPath: ${this.apiPath}`),this.sendDataFrame(n,this.apiPath),(s=this._onFrame)==null||s.call(this,n)}}isOneShotDone(){var t,e;return Ur(this._renderer)&&((e=(t=this._renderer).isOneShot)==null?void 0:e.call(t))===!0&&this._renderer.isOneShotDone}startStreaming(){var t,e,s,r;{if(!this._renderer)return;if(!this.apiPath){this.logger.error(`No endpoint configured for canvas renderer ${this.id}`);return}this.isStreaming=!0,this._renderer.reset(),(e=(t=this._renderer).play)==null||e.call(t);const o=Ur(this._renderer);Ur(this._renderer)&&this._renderer.onDone(()=>{var c,d,u;this.logger.debug(`Renderer completed for ${this.id}`),j("/canvas/renderer/completed",{endpoint:this.endpointName,rendererId:this.id,rendererType:(c=this._renderer)==null?void 0:c.constructor.name,timestamp:Date.now()});let a=!0;this._clearOnComplete!==void 0?a=this._clearOnComplete:a=!(((u=(d=this._renderer)==null?void 0:d.isOneShot)==null?void 0:u.call(d))??!1),this.stopStreaming(a)}),this._renderer.renderFrame(this.width,this.height);const n=(r=(s=this._renderer).readPixels)==null?void 0:r.call(s,this.width,this.height);if(n&&this._onFrame&&this.handleFrame(n),this.isOneShotDone()){requestAnimationFrame(()=>{this.stopStreaming(!1)});return}const i=()=>{var a;(a=this._renderer)==null||a.renderFrame(this.width,this.height),this.renderLoopId=requestAnimationFrame(i)};this.renderLoopId=requestAnimationFrame(i),this.sendIntervalId=setInterval(()=>{var c,d;const a=(d=(c=this._renderer)==null?void 0:c.readPixels)==null?void 0:d.call(c,this.width,this.height);a&&this._onFrame&&(this.handleFrame(a),this.checkStreaming())},1e3/this.fps),!o&&this.durationMs!=null&&(this.timeoutId=setTimeout(()=>{this.stopStreaming()},this.durationMs))}}async init(){this.logger.debug(`initializing canvas-renderer ${this.id}`)}async load(){this.logger.debug(`loading canvas-renderer ${this.id}`),this.router.use("POST",`/api/ui/canvas/${this.endpointName}/stop`,async(t,e)=>{this.logger.debug(`HTTP stop endpoint called for ${this.endpointName}`),this.stopStreaming(),e.send({status:"OK"})}),this.router.use("POST",`/api/ui/canvas/${this.endpointName}/start`,async(t,e)=>{this.startStreaming(),e.send({status:"OK"})})}};Dl([mt({modelType:Ho.type})],Js.prototype,"router",2);Js=Dl([R(Cl)],Js);const en=new we({class:Js,type:Cl});class Rl{constructor({src:e}){l(this,"video");l(this,"canvas");l(this,"ctx");l(this,"lastUpdate",0);l(this,"doneCallback",null);this.video=document.createElement("video"),this.video.src=e,this.video.crossOrigin="anonymous",this.video.muted=!0,this.video.loop=!1,this.canvas=document.createElement("canvas");const s=this.canvas.getContext("2d");if(!s)throw new Error("2D canvas not supported");this.ctx=s,this.handleEnded=this.handleEnded.bind(this),this.video.addEventListener("ended",this.handleEnded)}handleEnded(){this.doneCallback&&this.doneCallback()}reset(){this.video.pause(),this.video.currentTime=0,this.lastUpdate=performance.now()}play(){this.video.play().catch(console.warn)}pause(){this.video.pause()}renderFrame(e,s){this.canvas.width=e,this.canvas.height=s,this.video.readyState>=2&&this.ctx.drawImage(this.video,0,0,e,s)}readPixels(e,s){return this.ctx.getImageData(0,0,e,s).data}onDone(e){this.doneCallback=e}dispose(){this.video.pause(),this.video.removeAttribute("src"),this.video.load(),this.video.remove(),this.video.removeEventListener("ended",this.handleEnded),this.doneCallback=null}shouldStep(e){const s=performance.now();return s-this.lastUpdate>=e?(this.lastUpdate=s,!0):!1}}class Vm{constructor(){l(this,"canvas");l(this,"gl");l(this,"lastWidth",0);l(this,"lastHeight",0);l(this,"lastUpdate",0);this.canvas=document.createElement("canvas");const e=this.canvas.getContext("webgl");if(!e)throw new Error("WebGL not supported");this.gl=e}shouldStep(e){const s=performance.now();return s-this.lastUpdate>=e?(this.lastUpdate=s,!0):!1}readPixels(e=this.lastWidth,s=this.lastHeight){const r=new Uint8Array(e*s*4);this.gl.readPixels(0,0,e,s,this.gl.RGBA,this.gl.UNSIGNED_BYTE,r);const o=new Uint8ClampedArray(r.length);for(let n=0;n<s;n++){const i=n*e*4,a=(s-1-n)*e*4;o.set(r.subarray(i,i+e*4),a)}return o}}class Ym extends Vm{constructor({speedPx:s=1}={}){super();l(this,"program");l(this,"posBuffer");l(this,"aPosition");l(this,"uMinHue");l(this,"uMaxHue");l(this,"uHueOffset");l(this,"uGridHeight");l(this,"minHue",0);l(this,"maxHue",80);l(this,"hueOffset",0);l(this,"speedPx",1);this.speedPx=s;const r=this.gl,o=`
77
+ ["${e}"]`;if(r?(m=this.fosSocket)==null?void 0:m.connectionEstablished:(y=this.socket)==null?void 0:y.connectionEstablished){const E=r?this.fosSocket:this.socket;(v=E==null?void 0:E.socket)==null||v.send(u)}else{Ne.debug("no connection adding to offline messages");const E=r?this.fosSocket:this.socket;E==null||E.addOfflineMessage(u)}}subscribeTopic({topic:e,callback:s,fos:r,bridge:o,destinationAddress:n}){const{unsubscribe:i,count:a}=O(e,s);return Ne.debug(`Topic ${e} currently has ${a} subscribers`),this._sendSubscriptionMessage(e,"subscribe",r,o,n),()=>{const{count:c}=i();Ne.debug(`Topic ${e} currently has ${c} subscribers`),c===0&&this._sendSubscriptionMessage(e,"unsubscribe",r,o,n)}}async whenReady(){const e=this;return this.webSocketSupported?(await M.when(()=>{var s,r;return!!((s=e.socket)!=null&&s.connectionEstablished)&&(!e.useFosTransport||!!((r=e.fosSocket)!=null&&r.connectionEstablished))&&e.authorized}),{status:"success"}):{status:"not supported"}}get token(){return this._token}set token(e){this._token=e,this.init()}static host(e="localhost"){return this.getInstance().host=e,this}static port(e=8080){return this.getInstance().port=e,this}static alias(e){this.getInstance().alias=e}static getInstance(e=8080,s){if(!this._instance){const r=window.kosUseFos?{port:window.kosFosPort||8081}:void 0;this._instance=new this({port:e,token:s,fos:r})}return this._instance}}l(nt,"_instance");class Zh{constructor(e){l(this,"config");l(this,"stats");l(this,"filterHistory",[]);l(this,"activePromises",new Set);l(this,"eventQueue",[]);l(this,"rateLimitWindow",new Map);this.config=e,this.stats={eventsReceived:0,batchesProcessed:0,eventsDropped:0,currentQueueSize:0,averageBatchSize:0,processingRate:0,lastProcessedAt:Date.now()}}async*processEvents(e){const s=this.config.batch||{size:1,window:0};if(s.size===1&&!s.window)for await(const r of e)yield*this.processSingleEvent(r);else yield*this.processBatchedEvents(e,s)}async*processSingleEvent(e){if(this.stats.eventsReceived++,!(this.config.filter&&!this.shouldProcessEvent(e))){if(this.config.rateLimit&&!this.checkRateLimit())if(this.config.rateLimit.onExceeded==="drop"){this.stats.eventsDropped++;return}else this.config.rateLimit.onExceeded==="delay"&&await this.waitForRateLimit();if(this.config.backpressure){this.enqueueEvent(e),await this.waitForCapacity();const s=this.dequeueEvent();s&&(yield this.config.transform?this.config.transform([s]):[s],this.updateProcessingStats([s]))}else yield this.config.transform?this.config.transform([e]):[e],this.updateProcessingStats([e])}}async*processBatchedEvents(e,s){const r=s.size||100,o=s.window||1e3;let n=[],i=Date.now();const a=async()=>{if(n.length===0)return;const c=[...n];n=[],i=Date.now();const d=this.config.filter?c.filter(h=>this.shouldProcessEvent(h)):c;if(d.length===0)return;this.config.backpressure&&await this.waitForCapacity();const u=this.config.transform?this.config.transform(d):d;return this.stats.batchesProcessed++,this.updateProcessingStats(d),u};try{for await(const d of e)if(this.stats.eventsReceived++,this.config.backpressure)for(this.enqueueEvent(d);this.eventQueue.length>0;){const u=this.dequeueEvent();u&&n.push(u);const g=Date.now()-i;if(n.length>=r||g>=o){const m=await a();m!==void 0&&(yield m);break}}else{n.push(d);const h=Date.now()-i;if(n.length>=r||h>=o){const g=await a();g!==void 0&&(yield g)}}const c=await a();c!==void 0&&(yield c)}finally{}}shouldProcessEvent(e){if(!this.config.filter)return!0;const s={history:[...this.filterHistory],currentBatch:[],startTime:Date.now()},r=this.config.filter.predicate(e,s);return this.config.filter.historySize&&(this.filterHistory.push(e),this.filterHistory.length>this.config.filter.historySize&&this.filterHistory.shift()),r}checkRateLimit(){if(!this.config.rateLimit)return!0;const e=Date.now(),s=Math.floor(e/this.config.rateLimit.windowMs),r=this.rateLimitWindow.get(s)||0;if(r>=this.config.rateLimit.maxEvents)return!1;this.rateLimitWindow.set(s,r+1);for(const[o]of this.rateLimitWindow)o<s-1&&this.rateLimitWindow.delete(o);return!0}async waitForRateLimit(){if(!this.config.rateLimit)return;const e=Date.now(),o=(Math.floor(e/this.config.rateLimit.windowMs)+1)*this.config.rateLimit.windowMs-e;o>0&&await new Promise(n=>setTimeout(n,o))}async waitForCapacity(){if(!this.config.backpressure)return;const e=this.config.backpressure.maxConcurrent||5,s=this.config.backpressure.maxQueue||1e3;for(;this.activePromises.size>=e;)await Promise.race(this.activePromises);this.eventQueue.length>=s&&this.handleQueueOverflow()}handleQueueOverflow(){if(!this.config.backpressure)return;const e=this.config.backpressure.maxQueue||1e3,s=this.config.backpressure.dropPolicy||"oldest",r=this.config.backpressure.onQueueFull;if(s==="none")return;const o=this.eventQueue.length-e;if(o<=0)return;let n=[];if(s==="oldest"?n=this.eventQueue.splice(0,o):s==="newest"&&(n=this.eventQueue.splice(-o)),this.stats.eventsDropped+=n.length,this.stats.currentQueueSize=this.eventQueue.length,r&&n.length>0)try{r(n)}catch(i){console.warn("Error in onQueueFull callback:",i)}}enqueueEvent(e){if(this.eventQueue.push(e),this.stats.currentQueueSize=this.eventQueue.length,this.config.backpressure){const s=this.config.backpressure.maxQueue||1e3;this.eventQueue.length>s&&this.handleQueueOverflow()}}dequeueEvent(){const e=this.eventQueue.shift();return this.stats.currentQueueSize=this.eventQueue.length,e}updateProcessingStats(e){const s=Date.now(),r=s-this.stats.lastProcessedAt;this.stats.averageBatchSize=(this.stats.averageBatchSize*this.stats.batchesProcessed+e.length)/(this.stats.batchesProcessed+1),this.stats.processingRate=r>0?e.length/(r/1e3):this.stats.processingRate,this.stats.lastProcessedAt=s,this.stats.currentQueueSize=this.eventQueue.length}trackPromise(e){return this.activePromises.add(e),e.finally(()=>this.activePromises.delete(e)),e}getStats(){return{...this.stats}}}class Xh{constructor(e,s,r,o,n){l(this,"disposers",[]);l(this,"activatableDisposers",[]);l(this,"flowControllers",new Map);this.model=e,this.modelData=s,this.modelId=r,this.offlineQueue=o,this.log=n}registerAll(e){var o;const s=((o=this.modelData)==null?void 0:o[J])||{},r=Object.keys(s);this.log.debug(`Found ${r.length} subscriptions in ${this.modelId} (lifecycle: ${e??"any"})`),r.forEach(n=>{const i=s[n],a=i.lifecycle;if(e&&e!==a)return;const c=this.resolvePropKey(n);if(this.log.debug(`Resolved topic: ${n} → ${c}`),i.flow)this.subscribeWithFlowControl(i,c,a);else{const d=this.createHandler(c,i);this.subscribe(i,c,d,a===H.ACTIVATE)}})}deactivate(){this.log.debug(`Deactivating subscriptions for ${this.modelId}`);for(const e of this.activatableDisposers)try{e()}catch(s){this.log.error("Error during subscription disposal",s)}this.activatableDisposers=[]}disposeAll(){const e=[...this.disposers,...this.activatableDisposers];this.log.debug(`Disposing ${e.length} subscriptions for ${this.modelId}`);for(const[s,r]of this.flowControllers)this.log.debug(`Disposing flow controller for ${s}`);this.flowControllers.clear();for(const s of e)try{s()}catch(r){this.log.error("Error during subscription disposal",r)}this.disposers=[],this.activatableDisposers=[]}subscribe(e,s,r,o){const n=e.destinationAddress?this.resolvePropKey(e.destinationAddress):null;if(e.websocket){this.log.debug(`Subscribing to WebSocket topic: ${s}`);const i=nt.getInstance().subscribeTopic({topic:s,callback:r,fos:e.fos,bridge:e.bridge,destinationAddress:n});this.disposers.push(i)}else{this.log.debug(`Subscribing to EventBus topic: ${s}`);const{unsubscribe:i}=O(s,r);o?this.activatableDisposers.push(i):this.disposers.push(i)}}createHandler(e,s){return async r=>{var o;try{const n=(o=r==null?void 0:r.headers)==null?void 0:o["src-addr"],i=s.destinationAddress&&this.resolvePropKey(s.destinationAddress),a=i?n===i:!0,c=this.extractWildcardCapture(e,r,s);if(this.model.isReady()){const d=Vr(r,s.skipParse),u=s.transform(d);if(a&&s.condition(u,this.modelData,r))return this.callHandlerWithWildcard(s,u,c,r)}else{this.log.warn(`Model ${this.modelId} not ready. Queuing message for ${e}`);const d=()=>{const u=Vr(r,s.skipParse),h=s.transform(u);if(a&&s.condition(h,this.modelData,r))return this.callHandlerWithWildcard(s,h,c,r)};this.offlineQueue.enqueue(d)}}catch(n){this.log.error(`Error handling subscription for ${e}`,n)}}}extractWildcardCapture(e,s,r){var n;if(!r.wildcardName||!ua(e))return null;const o=((n=s==null?void 0:s.headers)==null?void 0:n.topic)||"";return da(e,o,r.wildcardName)}callHandlerWithWildcard(e,s,r,o){if(r&&Object.keys(r).length>0){const n={...o,wildcardCapture:r};return e.handler.call(this.modelData,s,n,this.modelData)}else return e.handler.call(this.modelData,s,o,this.modelData)}resolvePropKey(e){const s=/.*({PROP_(.+)})/;let r=e.includes("{MODEL_ID}")?e.replace("{MODEL_ID}",this.modelId):e;const o=r.match(s);return o&&o[2]in this.modelData&&(r=r.replace(o[1],this.modelData[o[2]])),r}async subscribeWithFlowControl(e,s,r){this.log.debug(`Setting up flow control for topic: ${s}`);const o=new Zh(e.flow);this.flowControllers.set(s,o);const n=this.createFlowControlHandler(s,e),i=this.startFlowProcessing(e,s,n,o),a=()=>{this.flowControllers.delete(s),i.then(c=>c==null?void 0:c.abort())};r===H.ACTIVATE?this.activatableDisposers.push(a):this.disposers.push(a)}async startFlowProcessing(e,s,r,o){const n=new AbortController;try{let i;if(e.websocket){const a=e.destinationAddress?this.resolvePropKey(e.destinationAddress):null;nt.getInstance().subscribeTopic({topic:s,callback:()=>{},fos:e.fos,bridge:e.bridge,destinationAddress:a}),i=xn(s)}else i=xn(s);return(async()=>{try{for await(const a of o.processEvents(i)){if(n.signal.aborted)break;const c=r(a);c instanceof Promise&&await o.trackPromise(c)}}catch(a){this.log.error(`Flow control error for ${s}:`,a)}})(),n}catch(i){return this.log.error(`Failed to start flow processing for ${s}:`,i),null}}createFlowControlHandler(e,s){return async r=>{var o,n,i,a;try{if(s.condition&&!s.condition(r,this.modelData,r))return;if(this.model.isReady())return s.handler.call(this.modelData,r,r,this.modelData);{this.log.warn(`Model ${this.modelId} not ready. Queuing flow-controlled message for ${e}`);const c=()=>s.handler.call(this.modelData,r,r,this.modelData);this.offlineQueue.enqueue(c)}}catch(c){if(this.log.error(`Error in flow control handler for ${e}:`,c),(n=(o=s.flow)==null?void 0:o.errorHandling)!=null&&n.retry)await this.retryHandler(s,r,c);else if(!((a=(i=s.flow)==null?void 0:i.errorHandling)!=null&&a.continueOnError))throw c}}}async retryHandler(e,s,r){const o=e.flow.errorHandling.retry;let n=r;for(let i=1;i<=o.attempts;i++)try{return this.log.debug(`Retry attempt ${i}/${o.attempts} for handler`),await new Promise(a=>setTimeout(a,o.backoffMs*i)),e.handler.call(this.modelData,s,s,this.modelData)}catch(a){n=a,this.log.warn(`Retry attempt ${i} failed:`,a)}throw this.log.error("All retry attempts failed, throwing last error:",n),n}getFlowControlStats(){const e={};for(const[s,r]of this.flowControllers)e[s]=r.getStats();return e}}function We(t,e){const s=`[Model:${e}]`;return{debug:(...r)=>t.debug(s,...r),info:(...r)=>t.info(s,...r),warn:(...r)=>t.warn(s,...r),error:(...r)=>t.error(s,...r)}}function Jh(t){return!!(t!=null&&t[Ke])&&Object.keys(t[Ke]).length>0}function ef(t){return!!(t!=null&&t[J])&&Object.keys(t[J]).length>0}function tf(t){return!!(t!=null&&t[Ie])&&t[Ie].length>0}class sf{static createAll(e){const{modelId:s,modelTypeName:r,modelData:o}=e,n=kh.create({modelId:s,modelTypeName:r}),i=new Ph(e,We(n,"fsm")),a=new Fh(We(n,"offline-queue")),c=new Sh(e),d=new Ih(e),u={fsm:i,offlineQueue:a,companionManager:c,childResolver:d};if(Jh(o)&&(u.effectManager=new Oh(r,s,o,We(n,"effect"))),ef(o)){const h=We(n,"subscription");u.subscriptionManager=new Xh(e,o,s,a,h),u.onlineLifecycleManager=new Nh(e,We(n,"online"))}return tf(o)&&(u.httpRouteManager=new Ro(o,We(n,"http-routes"))),u}}const k=$.getLogger("kos-model"),rf="kos.extension.model.loader";class Ba{constructor({modelTypeName:e,id:s,modelData:r}){l(this,"_id");l(this,"_status");l(this,"_activeStatus");l(this,"_onlineStatus");l(this,"modelData");l(this,"modelTypeName");l(this,"initialized");l(this,"loaded");l(this,"offlineQueue");l(this,"subscriptionManager");l(this,"effectManager");l(this,"httpRouteManager");l(this,"onlineLifecycleManager");l(this,"companionManager");l(this,"childResolver");l(this,"fsm");this._id=typeof s<"u"?`${s}`:e,this.modelTypeName=e,this.initialized=!1,this.loaded=!1,this.modelData=r,this._status=w.CREATED,this._activeStatus=w.INACTIVE,this._onlineStatus=w.OFFLINE;const o=sf.createAll(this);this.fsm=o.fsm,this.offlineQueue=o.offlineQueue,this.companionManager=o.companionManager,this.childResolver=o.childResolver,o.effectManager&&(this.effectManager=o.effectManager),o.subscriptionManager&&(this.subscriptionManager=o.subscriptionManager),o.httpRouteManager&&(this.httpRouteManager=o.httpRouteManager),o.onlineLifecycleManager&&(this.onlineLifecycleManager=o.onlineLifecycleManager),M.makeAutoObservable(this,{fsm:!1,effectManager:!1,subscriptionManager:!1,onlineLifecycleManager:!1,companionManager:!1,childResolver:!1,offlineQueue:!1}),Th(this)}get companionModels(){return this.companionManager}set status(e){this._status=e}get status(){return this._status}get modelId(){return this._id}get id(){return this._id}get activeStatus(){return this._activeStatus}set activeStatus(e){this._activeStatus=e}get onlineStatus(){return this._onlineStatus}set onlineStatus(e){this._onlineStatus=e}get modelManager(){return globalThis.kos.modelManager}isActive(){return this._status===w.ACTIVE}isOnline(){return this._onlineStatus===w.ONLINE}isReady(){return this._status===w.READY}async deactivate(){var e,s,r;k.debug(`deactivating model ${this.modelTypeName} with id ${this.modelId}`);try{const o=z.getContext(this.modelId);await((s=(e=this.modelData)==null?void 0:e.deactivate)==null?void 0:s.call(e,o)),k.debug(`Model ${this.modelTypeName} with id ${this.modelId} deactivated`),(r=this.subscriptionManager)==null||r.deactivate()}catch(o){throw k.debug(`Model ${this.modelId} failed to deactivated`),o}}async activate(){var e,s,r;k.debug(`activating model ${this.modelTypeName} with id ${this.modelId}`),await St(this,H.ACTIVATE);try{const o=z.getContext(this.modelId);await((s=(e=this.modelData)==null?void 0:e.activate)==null?void 0:s.call(e,o)),k.debug(`Model ${this.modelTypeName} with id ${this.modelId} subscribing to all topics`),(r=this.subscriptionManager)==null||r.registerAll(H.ACTIVATE),k.debug(`Model ${this.modelTypeName} with id ${this.modelId} activated`)}catch(o){throw k.debug(`Model ${this.modelId} failed to activate`),o}}async whenLoaded(){await Rr([{condition:()=>this.status===w.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.loaded,onMatch:()=>{k.debug(`Model ${this.modelId} is loaded`)}}])}async whenInitialized(){await Rr([{condition:()=>this.status===w.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.initialized,onMatch:()=>{k.debug(`Model ${this.modelId} is initialized`)}}])}async whenReady(){await Rr([{condition:()=>this.status===w.FAILED,onMatch:()=>{throw new Error(`Failed to ready model ${this.modelId}`)}},{condition:()=>this.status===w.READY,onMatch:()=>{k.debug(`Model ${this.modelId} is ready`)}}])}async ready(){var e,s,r;if(this.fsm.current===w.READY){k.debug(`already readying model ${this.modelTypeName} with id ${this.modelId} returning`);return}try{k.debug(`readying model ${this.modelTypeName} with id ${this.modelId}`),await St(this,H.READY),await Ta(this,Do.READY,H.READY);const o=z.getContext(this.modelId);await((s=(e=this.modelData)==null?void 0:e.ready)==null?void 0:s.call(e,o)),this.offlineQueue.flush(),(r=this.subscriptionManager)==null||r.registerAll(H.READY),k.debug(`Model ${this.modelId} is ready`);const n={modelId:this.modelId,modelType:this.modelTypeName};j(ha(this.modelTypeName,this.modelId),n),j(fa(this.modelTypeName),n)}catch(o){throw k.error(o),Error(o)}}async load(){var o,n,i,a,c;const e=this[Ls];e&&await e.whenLoaded();const{modelTypeName:s,modelId:r}=this;if(this.fsm.current===w.LOADED||this.fsm.current===w.LOADING){k.debug(`Model ${s} with id ${r} already loaded or loading`);return}k.debug(`Loading model ${s} with id ${r}`),await St(this,H.LOAD);try{const d=z.getContext(r),u=`${rf}.${s}`,h=await S.loader.executeLoader(u,{});h&&(k.info(`Setting loaded context for ${r}, type: ${s}`),d==null||d.set(u,h)),await((n=(o=this.modelData)==null?void 0:o.load)==null?void 0:n.call(o,d)),X(()=>{this.loaded=!0}),k.debug(`Model ${s} with id ${r} successfully loaded`),(i=this.subscriptionManager)==null||i.registerAll(H.LOAD),(a=this.httpRouteManager)==null||a.registerAll(),(c=this.effectManager)==null||c.setup()}catch(d){throw k.error(`Model ${r} failed to load`,d),d}}async unload(){var e,s,r,o,n,i;k.debug(`unloading model ${this.modelTypeName} with id ${this.modelId}`);try{const a=this.getChildren().map(d=>{var u;return(u=d.unload)==null?void 0:u.call(d)}).filter(d=>!!d);await Promise.allSettled(a);const c=z.getContext(this.modelId);await((s=(e=this.modelData)==null?void 0:e.unload)==null?void 0:s.call(e,c)),this.loaded=!1,(r=this.onlineLifecycleManager)==null||r.dispose(),k.debug(`Model ${this.modelTypeName} with id ${this.modelId} unloaded`),(o=this.effectManager)==null||o.disposeAll(),(n=this.subscriptionManager)==null||n.disposeAll(),(i=this.httpRouteManager)==null||i.dispose()}catch(a){throw k.debug(`Model ${this.modelId} failed to unload`),a}}async init(){var n,i,a;const e=this[Ls];e&&await e.whenInitialized();const{modelId:s,modelTypeName:r}=this,o=z.getContext(s);k.debug(`Initializing model ${r} with id ${s}`),await St(this,H.INIT);try{await((i=(n=this.modelData)==null?void 0:n.init)==null?void 0:i.call(n,o)),this.initialized=!0,k.debug(`Model ${r} with id ${s} initialized`),(a=this.onlineLifecycleManager)==null||a.register(),this.registerSubscribers(H.INIT)}catch(c){throw k.error(`Model ${s} failed to initialize`,c),c}}async registerSubscribers(e){var s;k.debug(`registering subscribers in ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.registerAll(e)}async online(){var s,r;k.debug(`online model ${this.modelTypeName} with id ${this.modelId}`),this.registerSubscribers();const e=z.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.online)==null?void 0:r.call(s,e))}async offline(){var s,r,o;k.debug(`offline model ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.disposeAll();const e=z.getContext(this.modelId);await((o=(r=this.modelData)==null?void 0:r.offline)==null?void 0:o.call(r,e))}accept(e){e.visit(this)}getChildren(){return this.childResolver.resolve()}addCompanionModel(e){this.companionManager.add(e)}clearCompanionModels(){this.companionManager.clear()}}const Ka=t=>typeof t=="function",kn=p.createLogger({name:"kos-model-instantiator"});class of{constructor(e,s){this.registry=e,this.cache=s}createModelInstance(e,s,r={}){const o=this.registry.models[e];if(!o)throw new Error(`No model registered for type ${e}`);const n=o.singleton?e:s;if(this.cache.restoreFromDeleteCache(n),!this.cache.hasModel(n)){kn.debug(`Creating model instance: ${e} [${n}]`);const a=o.create?o.create({modelTypeId:e,id:n,options:r}):new o.class(n,r),c=new Ba({modelTypeName:e,id:n,modelData:a});this.cache.addModel(c),this._createCompanionModels(c,r)}const i=this.cache.getModelById(n);if(!i)throw kn.error(`Model ${e} [${n}] not found in cache`),new Error(`Model ${e} [${n}] not found in cache`);return{model:i,data:i.modelData}}_createCompanionModels(e,s){var n;const r=e.modelTypeName,o=((n=this.registry.companionModels)==null?void 0:n[r])||[];for(const{type:i}of o){const a=Ka(i)?i(e.modelData,s):i;if(!a)continue;const c=`${a}-${e.modelId}`,d=this.createModelInstance(a,c,{data:s,companionParent:e.modelData,kosParentId:e.modelId});d!=null&&d.model&&(d.model[Ls]=e,e.addCompanionModel(d.model))}}}let nf=class{constructor(e){this._registry=e}get registry(){return this._registry}getModelTypeRegistry(e){const s=this.registry.models[e];if(!s)throw new Error(`No registration for model type ${e}`);return s}registerModel(e){const s=e.type;this.registry.models[s]||(this.registry.models={...this.registry.models,...e.registration})}registerCompanionModel(e,s){var r,o;(r=this.registry).companionModels??(r.companionModels={}),(o=this.registry.companionModels)[e]??(o[e]=[]),this.registry.companionModels[e].some(n=>n.type===s)||this.registry.companionModels[e].push({type:s})}getModelSubscriptions(e){var s;return((s=this.getModelTypeRegistry(e))==null?void 0:s.subscriptions)||{}}getDataModelBuilder(e){var r;const s=(r=this.getModelTypeRegistry(e))==null?void 0:r.builder;if(!s)throw new Error(`No builder found for model type ${e}`);return s}getModelFactory(e){return bt(e)}};const Ha=10,Fn=p.createLogger({name:"kos-model-manager"});class za{constructor(){l(this,"cache");l(this,"instantiator");l(this,"dependencies");l(this,"_registry");globalThis.kos=globalThis.kos||{},this.dependencies=new Zu,globalThis.kos.modelManager=this,globalThis.kos.resolveKosModel=e=>{const s=this.getModelById(e);if(s)return s.modelData||{}},globalThis.kos.kosModelJson=e=>{var r,o;const s=this.getModelById(e);if(s)return((o=(r=s.modelData).toJSON)==null?void 0:o.call(r))||{}},globalThis.kos.kosModelDebug=e=>{var r;const s=this.getModelById(e);if(s)return((r=s.modelData)==null?void 0:r.debugState)||{}},globalThis.kos.kmd=globalThis.kos.kosModelDebug,globalThis.kos.kmj=globalThis.kos.kosModelJson}static create(e,s){const r=this.getInstance(s);return r._registry=new nf(e),r.cache=new Xu(e.preloadModels),r.instantiator=new of(e,r.cache),r}static getInstance(e){var s,r;return(!((s=globalThis.kos)!=null&&s.modelManager)||e)&&(Fn.debug("Creating new instance of KosModelManager"),new this),(r=globalThis.kos)==null?void 0:r.modelManager}get registry(){return this._registry.registry}get preloadedModels(){return this.cache.preload(e=>(Fn.debug(`preloading ${e}`),typeof e=="string"?this.createModelInstance(e).model:this.createModelInstance(e.modelType,e.modelId,e.options).model))}get models(){return this.cache.models}getModelById(e){return this.cache.getModelById(e)}addModel(e){return this.cache.addModel(e)}removeModel(e){this.cache.removeModel(e.modelId)}hasModel(e){return this.cache.hasModel(e)}getModelsByType(e,s){return Array.from(this.models).filter(r=>r.modelTypeName===e).filter(r=>s?s(r.modelData):!0).map(r=>r.modelData)}getModelSubscriptions(e){return this._registry.getModelSubscriptions(e)}getDataModelBuilder(e){return this._registry.getDataModelBuilder(e)}getModelFactory(e){return bt(e)}addDependency(e,s){this.cache.restoreFromDeleteCache(s),this.dependencies.add(e,s)}removeDependency(e,s){this.dependencies.remove(e,s)}async reloadModel(e){if(e.id){const s=this.getModelById(e.id);s&&await s.fsm.transitionTo(A.RESET,w.RESETTING)}}async initiateDestroyModel(e){if(!e.id)throw new Error("Model ID is required");if(!this.dependencies.canDestroy(e.id))return;const s=this.getModelById(e.id);s&&(this.cache.markForDeletion(s),oa.addToDeletionQueue(e.id,setTimeout(()=>this.destroyModel(s),Ha)))}async destroyModel(e){var s;e!=null&&e.modelId&&this.dependencies.canDestroy(e.modelId)&&(await((s=e.unload)==null?void 0:s.call(e)),this.removeModel(e))}createModelInstance(e,s,r={}){return this.instantiator.createModelInstance(e,s,r)}registerCompanionModel(e,s){this._registry.registerCompanionModel(e,s)}registerModel(e){this._registry.registerModel(e)}}var Ds=(t=>(t.CREATING="creating",t.CREATED="created",t.INITIALIZING="initializing",t.INITIALIZED="initialized",t.LOADING="loading",t.LOADED="loaded",t.ONLINE="online",t.READYING="readying",t.READY="ready",t.OFFLINE="offline",t.UNLOADING="unloading",t.UNLOADED="unloaded",t.RELOADING="reloading",t))(Ds||{}),et=(t=>(t.CREATE="create",t.INITIALIZE="init",t.READY="ready",t.GO_ONLINE="go_online",t.GO_OFFLINE="go_offline",t.UNLOAD="unload",t.RELOAD="reload",t))(et||{});const af=t=>{const e=b.createMachine("offline",{online:b.state(b.transition("go_offline","offline",b.action(()=>{t.offline(),M.runInAction(()=>{t.isOnline=!1})}))),offline:b.state(b.transition("go_online","online",b.action(()=>{t.online(),M.runInAction(()=>{t.isOnline=!0})})))}),s=b.interpret(e,n=>$.debug(n.machine.current)),r=b.createMachine({creating:b.state(b.transition("create","created")),created:b.state(b.immediate("initializing")),initializing:b.invoke(()=>t.init(),b.transition("done","initialized")),initialized:b.state(b.immediate("loading")),loading:b.invoke(()=>t.load(),b.transition("done","loaded")),loaded:b.state(b.immediate("readying"),b.transition("unload","unloading")),readying:b.invoke(()=>t.ready(),b.transition("done","ready",b.action(()=>{M.runInAction(()=>{t.status="ready"})}))),reloading:b.invoke(()=>t.reload(),b.transition("done","loading")),ready:b.state(b.transition("reload","reloading"),b.transition("unload","unloaded",b.action(t.unload.bind(t))),b.transition("go_online","ready",b.action(()=>{s.send("go_online")})),b.transition("go_offline","ready",b.action(()=>{s.send("go_offline")}))),unloaded:b.state()});return{service:b.interpret(r,n=>$.debug(n.machine.current)),online:s}},ae=async t=>{if(t.id){const e=I.getInstance().modelManager.getModelById(t.id);if(!e)throw new Error(`Model with ID ${t.id} not found`);await(e==null?void 0:e.whenReady())}else throw new Error("Data model must have a valid ID");return t},He=async t=>{await I.getInstance().whenReady(),await I.getInstance().modelManager.initiateDestroyModel(t)},cf=async t=>{if(await I.getInstance().whenReady(),!t.id)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t.id);e&&await e.fsm.transitionTo(A.UNLOAD,w.UNLOADED)},lf=async t=>{await I.getInstance().whenReady(),await I.getInstance().modelManager.reloadModel(t),p.debug(`reload model initiated for model ${t.id}, model ready: ${Fs(t)} - ${Date.now()} `),await ae(t),p.debug(`reload model complete for model ${t.id}, model ready: ${Fs(t)} - ${Date.now()} `)},df=async t=>{if(await I.getInstance().whenReady(),!t)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t);return e==null?void 0:e.modelTypeName},Ga=async t=>{if(await I.getInstance().whenReady(),!t)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t);return{model:e==null?void 0:e.modelData,type:e==null?void 0:e.modelTypeName}},ve=t=>{if(!t)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t);return{model:e==null?void 0:e.modelData,type:e==null?void 0:e.modelTypeName}},Va=(t,e)=>{if(!t)throw new Error("Model type is required");return I.getInstance().modelManager.getModelsByType(t).filter(o=>Object.keys(e).every(n=>o[n]===e[n]))},uf=(t,e)=>Va(t,e)[0],hf=(t,e)=>{if(!t.id)throw new Error("Model ID is required");const s=I.getInstance().modelManager.getModelById(t.id);if(!s)throw new Error("Model not found");const r=s.companionModels.get(e);return r==null?void 0:r.modelData},Ya=t=>{if(!t.id)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t.id);if(!e)throw new Error("Model not found");return Array.from(e.companionModels.all()).map(r=>r.modelData)},ff=t=>{if(!t)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t);if(!e)throw new Error("Model not found");return e.companionModels.data},qr=(t,e)=>{const s=I.getInstance().modelManager.getModelById(t);if(!s){p.info(`Model not found for id ${t}`);return}return Array.from(s.companionModels.all()).find(o=>e(o.modelData))},he=t=>e=>Object.getPrototypeOf(e).modelTypeId===t,Fs=t=>{const e=I.getInstance().modelManager.getModelById(t.id);if(!e)throw new Error("Model not found");return e.isReady()},gf=p.createLogger({name:"kos-model-factory"}),Ht={byModelType:t=>I.getInstance().modelManager.getModelFactory(t),getModelInstance:(t,e,s)=>{const r=Ht.byModelType(e);if(!r)throw gf.error(`No registered factory found for model type ${e}. Please register a factory for this model type. `),Error(`No factory found for model type ${e}`);return r.build(t,s)}},te={Factory:{create:t=>e=>(s,r)=>(r&&z.setParentContext(e,r),Ht.getModelInstance(e,t,s))},Singleton:{create:t=>(e,s)=>(s&&z.setParentContext(t,s),Ht.getModelInstance(t,t,e))},Model:{instance:t=>e=>Ht.getModelInstance(e,t)}};window.KosRegistry=window.KosRegistry||{coreModels:new Map,preloadModels:[],companionModels:new Map,models:new Map};const Nn=window.KosRegistry.coreModels,Ar=window.KosRegistry.preloadModels,xr=window.KosRegistry.companionModels,ys=window.KosRegistry.models,C={model:{registerLegacyModel:t=>(e,s)=>(Nn.set(e,s),{preload:C.model.preloadModel(t),model:C.model.register(t),companion:C.companion.register(t),legacy:C.model.registerLegacyModel(t),root:t}),preloadModel:t=>e=>(Ar.includes(e)||Ar.push(e),{preload:C.model.preloadModel(t),model:C.model.register(t),companion:C.companion.register(t),legacy:C.model.registerLegacyModel(t),root:t}),register:t=>(e,s)=>{const r=Pr(e)?e.registration():e;return ys.set(r.type,r),Pr(e)&&e.relatedModels.forEach(o=>ys.set(o.type,o.registration())),I.getInstance().isReady&&(I.getInstance().modelManager.registry.models[r.type]||(console.info(`Model with type ${r.type} doesn't exist. Adding new registration`),I.getInstance().modelManager.registry.models[r.type]=r.registration[r.type],Pr(e)&&e.relatedModels.forEach(o=>I.getInstance().modelManager.registry.models[o.type]=o.registration().registration))),s&&C.model.preloadModel(t)(r.type),{preload:C.model.preloadModel(t),model:C.model.register(t),companion:C.companion.register(t),legacy:C.model.registerLegacyModel(t),root:t}},get:t=>ys.get(t),getAll:()=>Array.from(ys.entries()),getPreloadModels:()=>Ar,getLegacyModels:()=>Array.from(Nn.entries()).reduce((t,[e,s])=>(t[e]=s,t),{})},companion:{register:t=>(e,s)=>{const r=xr.get(e)||[];return r.push(s),xr.set(e,r),{preload:C.model.preloadModel(t),model:C.model.register(t),companion:C.companion.register(t),legacy:C.model.registerLegacyModel(t),root:t}},getAll:()=>Array.from(xr.entries())}},qa=C.model.registerLegacyModel,Wa=C.model.register,pf=C.companion.register,mf=C.model.preloadModel,Qa=t=>typeof t.updateModel=="function",Pr=t=>t.registration!==void 0&&typeof t.registration=="function";class Za{constructor(e){l(this,"singleton");l(this,"type");l(this,"loader");l(this,"class");l(this,"guard");l(this,"factory");l(this,"relatedModels",[]);this.singleton=e.singleton,this.guard=he(e.type),this.type=e.type,this.loader=`kos.extension.model.loader.${e.type}`,this.factory=e.factory,this.class=e.class}addRelatedModel(e){this.relatedModels.push(e)}registerRelatedModels(){this.relatedModels.forEach(e=>e.register())}register(){C.model.register({})(this.registration()),this.registerRelatedModels()}}class we extends Za{constructor(e){super({...e,singleton:!1,factory:te.Factory.create(e.type)})}instance(e){const s=this.factory(e);return{get:()=>{const r=ve(e);if(!r)throw new Error("Model not found with id "+e);if(this.guard(r))return r;throw new Error("Model is not of type "+this.type)},forceUpdate:{options:r=>({build:()=>{const o=s(r);if(this.guard(o)){if(Qa(o))o.updateModel(r);else throw new Error(`Model ${this.type} is not updateable. Please implement UpdateAware interface`);return o}else throw new Error("Model is not of type "+this.type)}})},options:r=>({build:()=>{const o=s(r);if(this.guard(o))return o;throw new Error("Model is not of type "+this.type)}})}}registration(){return{type:this.type,predicate:this.guard,registration:{[this.type]:{class:this.class,singleton:!1}},factory:this.factory}}}class Ee extends Za{constructor(e){super({...e,singleton:!0,factory:te.Singleton.create(e.type)})}instance(){const e=this.factory;return{get:()=>{const r=ve(this.type);if(!r)throw new Error("Model not found with id "+this.type);if(this.guard(r))return r;throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(r).modelTypeId}`)},forceUpdate:{options:r=>({build:()=>{const o=e(r);if(this.guard(o)){if(Qa(o))o.updateModel(r);else throw new Error(`Model ${this.type} is not updateable. Please implement UpdateAware interface`);return o}else throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(o).modelTypeId}`)}})},options:r=>({build:()=>{const o=e(r);if(this.guard(o))return o;throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(o).modelTypeId}`)}})}}registration(){return{type:this.type,predicate:this.guard,registration:{[this.type]:{class:this.class,singleton:!0}},factory:this.factory}}}const Y=p.createLogger({name:"kos-core"}),yf=()=>{const t=ue(),e=t==null?void 0:t.alias,s=process.env.KOS_CONNECTION_ALIAS;return e||s||void 0},bf=()=>{const t=window.location.protocol,e=ue(),s=e==null?void 0:e.host;let r;try{r=new URL(s).protocol==="https:"?"wss://":"ws://"}catch{}return r||(t==="https:"?"wss://":"ws://")},wf=()=>{const t=window.location.hostname,e=process.env.KOS_HOST,s=ue(),r=s==null?void 0:s.host;let o;try{o=new URL(r).hostname}catch{}return o??e??t},vf=()=>{const t=window.location.port,e=process.env.KOS_PORT,s=ue(),r=s==null?void 0:s.host;let o;try{o=new URL(r).port}catch{}return o??e??t},Mf=(t,e)=>{let s;return{promise:new Promise((n,i)=>{s=setTimeout(()=>{e?p.error(`Model ${e.modelId} - ${e.modelTypeName} preloading - timed out after ${t}ms`):p.error(`KOS Core preloading timed out after ${t}ms`),i(new Error(`Model ${e==null?void 0:e.modelId} - ${e==null?void 0:e.modelTypeName} - timed out after ${t}ms`))},t)}),cancel:()=>{s&&clearTimeout(s)}}},Un=t=>typeof t.reload=="function",Ef=t=>typeof t.unload=="function";var Xa=(t=>(t.LOGGED_IN="logged_in",t.LOGGED_OUT="logged_out",t))(Xa||{});class I{constructor(e){l(this,"fsmService");l(this,"status");l(this,"initialized");l(this,"loaded");l(this,"_transport");l(this,"modelManager");l(this,"authState");l(this,"isOnline");l(this,"_reloading");l(this,"_unloading");l(this,"connectionAlias");this.initialized=!1,this.connectionAlias=e,this.loaded=!1,this.isOnline=!1,this.status=Ds.CREATED,this.authState="logged_out",this._reloading=!1,this._unloading=!1,M.makeAutoObservable(this),O("token",a=>{a&&(this.transport.token=a.body)}),O(pe.DISCONNECTED,async()=>{await Promise.allSettled(this.modelManager.models.map(async a=>{var c,d;try{await((c=a.offline)==null?void 0:c.call(a))}catch(u){Y.error(`model ${a.modelId} offline() threw:`,u)}(d=a.onlineLifecycleManager)==null||d.dispose()})),this.fsmService.service.send(et.GO_OFFLINE)}),O(pe.CONNECTED,async()=>{await this.whenReady(),await Promise.allSettled(this.modelManager.models.map(async a=>{var c,d;(c=a.onlineLifecycleManager)==null||c.register();try{await((d=a.online)==null?void 0:d.call(a))}catch(u){Y.error(`model ${a.modelId} online() threw:`,u)}})),this.fsmService.service.send(et.GO_ONLINE)}),O("/studioServer/auth/LOGGED_IN",()=>{this.authState="logged_in",this.transport.authorized=!0}),O("/studioServer/auth/LOGIN_REQUIRED",()=>{this.authState="logged_out",this.transport.authorized=!1}),O(pe.RELOAD,()=>{this.fsmService.service.send(et.RELOAD)}),O("/studio/project/reload",()=>{this.fsmService.service.send(et.RELOAD)});const s=nt.getInstance(),r=wf(),o=vf(),n=bf();s.host=r,s.port=Number.parseInt(o),s.protocol=n,process.env.KOS_ALLOW_ANONYMOUS==="true"&&(s.authorized=!0);const i=yf()??e;i&&(s.alias=i.replace("{{TIMESTAMP}}",Date.now().toString())),this._transport=s.init(),this.fsmService=af(this),this.fsmService.service.send(et.CREATE)}get onlineStatus(){return this.isOnline&&!this._reloading&&!this._unloading}get reloading(){return this._reloading}get unloading(){return this._unloading}async reload(){var o,n,i,a;const e=Date.now();if(this._reloading){Y.info("reload already in progress");return}this._reloading=!0,Y.warn("reloading KOS Core"),Y.warn("reloading preloaded models");const s=this.modelManager;for(const c of s.preloadedModels)Un(c.modelData)&&(Y.info(`reloading model ${c.modelId}`),(o=c.unload)==null||o.call(c),await c.modelData.reload(),(n=c.registerSubscribers)==null||n.call(c),Y.info(`reloading model ${c.modelId} complete`));for(const c of s.models)!s.preloadedModels.includes(c)&&Un(c.modelData)&&((i=c.unload)==null||i.call(c),await c.modelData.reload(),(a=c.registerSubscribers)==null||a.call(c));const r=Date.now()-e;setTimeout(()=>{M.runInAction(()=>{Y.warn("reloading KOS Core complete"),this._reloading=!1})},1e3-r)}async online(){Y.debug("KOS Core going online"),await this._transport.whenReady(),Y.debug("KOS Transport Ready. Calling online() for models"),j("/kosCore/online","/kosCore/online"),console.timeEnd("kosCore:startup")}async offline(){Y.debug("KOS Core going offline"),j("/kosCore/offline","/kosCore/offline")}async unload(){var o;Y.debug("Unloading KOS Core");const e=Date.now();this._unloading=!0,Y.debug("unloading KOS Core");const s=this.modelManager;for(const n of s.models)Ef(n.modelData)&&((o=n.unload)==null||o.call(n));const r=Date.now()-e;setTimeout(()=>{M.runInAction(()=>{this._unloading=!1})},1e3-r)}async whenReady(){await M.when(()=>this.status===Ds.READY)}async ready(){Y.debug("Readying KOS Core"),await this._transport.whenReady();const e=this.modelManager.preloadedModels.map(o=>({modelId:o.modelId,model:o,promise:o.whenReady()})),r=(await Promise.allSettled(e.map(o=>{const{promise:n,cancel:i}=Mf(5e3,o.model);Promise.race([o.promise.then(()=>{i()}),n])}))).filter(o=>o.status==="rejected");if(r.length)throw Y.error(`There were ${r.length} failed models on model preloading`),Error(`There were ${r.length} failed models on model preloading`);Y.debug("leaving kos-core ready() ")}get isReady(){return this.status===Ds.READY}set transport(e){this._transport=e}get transport(){return this._transport}get coreInitialized(){return this.initialized}get modelsLoaded(){return this.loaded}async init(){Y.debug("entering kos-core init()"),console.time("kosCore:startup"),console.time("kosCore:init"),await this._transport.whenReady(),this.initialized=!0,Y.debug("initialized - leaving kos-core init()"),console.timeEnd("kosCore:init")}async load(){Y.debug("entering kos-core load()"),console.time("kosCore:load"),this.loaded=!0,Y.debug("loaded - leaving kos-core load()"),console.timeEnd("kosCore:load")}static create(e,s,r){var i,a,c;const o=this.getInstance({reset:s,connectionAlias:r});(i=e.extensions)!=null&&i.dataMapper&&Object.keys(e.extensions.dataMapper).forEach(d=>{var h,g;const u=(g=(h=e.extensions)==null?void 0:h.dataMapper)==null?void 0:g[d];u&&(Array.isArray(u)?u.forEach(m=>{S.dataMapper.registerDataMapper(d,m)}):S.dataMapper.registerDataMapper(d,u))}),(a=e.extensions)!=null&&a.propertyMapper&&Object.keys(e.extensions.propertyMapper).forEach(d=>{var h,g;const u=(g=(h=e.extensions)==null?void 0:h.propertyMapper)==null?void 0:g[d];u&&S.propertyMapper.registerPropertyMapper(d,u)}),(c=e.extensions)!=null&&c.contextLoader&&Object.keys(e.extensions.contextLoader).forEach(d=>{var h,g;const u=(g=(h=e.extensions)==null?void 0:h.contextLoader)==null?void 0:g[d];u&&S.loader.registerLoader(d,u)}),C.model.getAll().forEach(([,d])=>{e.models={...e.models,...d.registration}}),e.models={...e.models,...C.model.getLegacyModels()},C.companion.getAll().forEach(([d,u])=>{e.companionModels={...e.companionModels},e.companionModels[d]=e.companionModels[d]||[];for(const h of u)e.companionModels[d].push({type:h})}),C.model.getPreloadModels().forEach(d=>{e.preloadModels.includes(d)||e.preloadModels.push(d)});const n=za.create(e,s);return o.modelManager=n,o}static getInstance(e){return this._instance=window.KosCore,(!this._instance||e!=null&&e.reset)&&(window.KosCore=new this(e==null?void 0:e.connectionAlias),this._instance=window.KosCore),this._instance}}l(I,"_instance");function Wr(t){const e=new Uint8Array(t);let s="";for(let r=0;r<e.byteLength;r++)s+=String.fromCharCode(e[r]);return btoa(s)}function Tf(t){const e=atob(t),s=new Uint8Array(e.length);for(let r=0;r<e.length;r++)s[r]=e.charCodeAt(r);return s.buffer}async function _f(t){return await t.arrayBuffer()}function If(t,e){return new Blob([t],{type:e})}async function Sf(t){const e={},s=[],r=[];t.forEach((o,n)=>{r.push([n,o])});for(const[o,n]of r)if(n instanceof File){const i=await n.arrayBuffer();s.push({name:o,filename:n.name,type:n.type,data:Wr(i)})}else e[o]=n.toString();return{fields:e,files:s}}function Of(t){return new ReadableStream({async start(){},async pull(e){await t(e)},cancel(){}})}async function $f(t){if(!t)return{data:"",contentType:"text/plain"};if(typeof t=="string")return{data:t,contentType:"text/plain"};if(t instanceof ArrayBuffer||t instanceof Uint8Array){let e;return t instanceof Uint8Array?(e=new ArrayBuffer(t.byteLength),new Uint8Array(e).set(t)):e=t,{data:Wr(e),contentType:"application/octet-stream",encoding:"base64"}}if(t instanceof Blob){const e=await _f(t);return{data:Wr(e),contentType:t.type||"application/octet-stream",encoding:"base64"}}if(t instanceof FormData){const e=await Sf(t);return{data:JSON.stringify(e),contentType:"multipart/form-data",encoding:"json"}}throw new Error("Unsupported body type")}const Ue=p.createLogger({name:"kos-fetch"}),Df=process.env.KOS_WS_TIMEOUT?parseInt(process.env.KOS_WS_TIMEOUT):3e4,Cf=()=>new Promise(t=>{setTimeout(()=>{t(!0)},0)}),Rf=t=>{if("timeout"in AbortSignal)return AbortSignal.timeout(t);const e=new AbortController;return setTimeout(()=>{e.abort(new DOMException(`Request timed out after ${t}ms`,"TimeoutError"))},t),e.signal},Af=t=>{if("any"in AbortSignal)return AbortSignal.any(t);const e=new AbortController;for(const s of t){if(s.aborted)return e.abort(s.reason),e.signal;s.addEventListener("abort",()=>e.abort(s.reason),{once:!0})}return e.signal},xf=t=>t!=null&&t.studio?Oa:t!=null&&t.fos?$a:Da,Pf=async(t,e)=>{const s=I.getInstance().transport;await s.whenReady();const r=mt(),o=new URL(t),n=`${o.pathname}${o.search}`;Ue.debug(`path: ${n}`);const i=(e==null?void 0:e.timeout)||Df,a=xf(e),c=Rf(i),d=e!=null&&e.signal?Af([e.signal,c]):c,u=await $f(e==null?void 0:e.body),h={};u.contentType&&(h["content-type"]=u.contentType),u.encoding&&(h["content-encoding"]=u.encoding);const g=ke(a({path:n,requestId:r,method:(e==null?void 0:e.method)||"GET",destinationAddress:(e==null?void 0:e.destinationAddress)||"",ordered:e==null?void 0:e.ordered,tracker:e==null?void 0:e.tracker,bridge:e==null?void 0:e.bridge,headers:{...e==null?void 0:e.headers,...h}}),u.data);return new Promise((m,y)=>{let v=null;if(d.aborted){const x=d.reason;(x==null?void 0:x.name)==="TimeoutError"?Ue.error(`Timeout occurred - url: ${t}`):Ue.debug(`Request aborted - url: ${t}`),y(x||new DOMException("Aborted","AbortError"));return}const E=()=>{v&&v();const x=d.reason;(x==null?void 0:x.name)==="TimeoutError"?Ue.error(`Timeout occurred - url: ${t}`):Ue.debug(`Request aborted - url: ${t}`),y(x||new DOMException("Aborted","AbortError"))};d.addEventListener("abort",E,{once:!0});const _=O(r,x=>{d.removeEventListener("abort",E);const D=(x==null?void 0:x.headers)||{},P=D["content-type"]||"text/plain",W=D["content-encoding"],re=(x==null?void 0:x.body)||"";let L=re;if(W==="base64"&&re)try{L=Tf(re)}catch(V){Ue.error("Failed to decode base64 response",V)}const Ce={headers:Ca(D),status:D.status&&parseInt(D.status)||200,ok:D.status==="200",json:async()=>{try{if(typeof L=="string")return L.length?JSON.parse(L):null;{const ce=new TextDecoder().decode(L);return ce.length?JSON.parse(ce):null}}catch{throw Error("Not a JSON response")}},text:async()=>typeof L=="string"?L:new TextDecoder().decode(L),arrayBuffer:async()=>L instanceof ArrayBuffer?L:new TextEncoder().encode(L).buffer,blob:async()=>L instanceof ArrayBuffer?If(L,P):new Blob([L],{type:P}),formData:async()=>{const V=new FormData;if(P==="multipart/form-data"&&typeof L=="string")try{const ce=JSON.parse(L);ce.fields&&Object.entries(ce.fields).forEach(([gs,Tt])=>{V.append(gs,Tt)}),ce.files&&Ue.warn("File reconstruction in FormData not fully implemented")}catch{throw new Error("Failed to parse FormData")}return V},body:e!=null&&e.stream?Of(async V=>{if(L instanceof ArrayBuffer)V.enqueue(new Uint8Array(L));else{const ce=new TextEncoder;V.enqueue(ce.encode(L))}V.close()}):Ra(typeof L=="string"?L:""),redirected:!1,statusText:"",type:"basic",url:"",clone:function(){return{...this}},bodyUsed:!1};_.unsubscribe(),Cf().then(()=>m(Ce))});v=_.unsubscribe;const N=e!=null&&e.fos?s.fosSocket:s.socket;if(!N)throw Error(`No web socket transport available: ${e}`);N==null||N.send(g)})};exports.BASE_URL="kos:";exports.kosFetch=Pf;if(process.env.KOS_MOCK_FETCH==="true"){const t=process.env.KOS_PORT||"9999";exports.kosFetch=fetch,exports.BASE_URL=`http://localhost:${t}`}const Lf=p.createLogger({name:"kos-model-visitor",group:"kos-ui-core"});class kf{constructor(){l(this,"visitedModels",new Set);this.visitedModels=new Set}start(e){var r;if(e.id===void 0)throw new Error("rootModel must have an id");const s=I.getInstance().modelManager.getModelById(e.id);if(!s)throw new Error(`Could not find rootModel with id: ${e.id}`);this.visitedModels.clear(),(r=s.accept)==null||r.call(s,this)}visit(e){var r;if(this.visitedModels.has(e.modelId)){Lf.info(`model ${e.modelId} already visited`);return}const s=!!this.visitModel(e.modelData,this);this.visitedModels.add(e.modelId),!s&&((r=e.getChildren)==null||r.call(e).forEach(o=>{var n;(n=o.accept)==null||n.call(o,this)}))}}const Ja=()=>({isMock:!1,URL:exports.BASE_URL}),bs=p.createLogger({name:"kos-service-request"}),jn="errUnknown";async function ws(t,e,s,r,o){const n=r!=null&&r.path?Object.keys(r.path).reduce((d,u)=>String(d).replace(`{${u}}`,r==null?void 0:r.path[u]),String(t)):String(t),i=r!=null&&r.query?Object.keys(r.query).map(d=>`${d}=${r.query[d]}`).join("&"):"",a=`${Ja().URL}${n}${i?`?${encodeURIComponent(i)}`:""}`;bs.debug(`fullUrl: ${a}`);const c={method:String(e).toUpperCase(),body:null,...s};o&&(c.body=JSON.stringify(o));try{const d=await exports.kosFetch(a,c);return d.status<200||d.status>=400?[`${d.statusText||jn}`,null]:[null,(await d.json()).data]}catch(d){if(d instanceof DOMException){if(d.name==="TimeoutError")return bs.error(`Request timed out: ${a}`),["Request timed out",null];if(d.name==="AbortError")return bs.debug(`Request aborted: ${a}`),["Request aborted",null]}return bs.error(`Unexpected error during fetch: ${d}`),[d instanceof Error?d.message:jn,null]}}function Ao(){return{get:(t,e,s)=>ws(t,"get",s,e),post:(t,e,s,r)=>ws(t,"post",r,e,s),put:(t,e,s,r)=>ws(t,"put",r,e,s),delete:(t,e,s,r)=>ws(t,"delete",r,e,s)}}class ec{constructor(){l(this,"middlewares",[])}use(e){this.middlewares.push(e)}async execute(e){let s=0;const r=async()=>{s++,s<this.middlewares.length&&await this.middlewares[s](e,r)};await this.middlewares[s](e,r)}}const Ff=async(t,e)=>{const s=new ec;e.forEach(o=>s.use(o));const r={data:t,result:{}};return await s.execute(r),r.result},bt=t=>({type:t,build:(e,s)=>I.getInstance().modelManager.createModelInstance(t,e,s).data,buildAsync:async(e,s)=>{const r=I.getInstance().modelManager.createModelInstance(t,e,s);return await r.model.whenInitialized(),r.data}}),Nf=t=>{I.getInstance().modelManager.registerModel(t)},Uf=(t,e)=>{I.getInstance().modelManager.registerCompanionModel(t,e)},tc=Symbol("KosObservableData");class sc{constructor(){l(this,"map");l(this,"atomMap",new Map);l(this,"proxyHandler",{get:(e,s)=>{var r;return e[s]!==void 0?e[s]:this.atomMap.has(s)&&(r=this.atomMap.get(s))!=null&&r.reportObserved()?this.getValue(s):this.getValue(s)},set:(e,s,r)=>{var o;return this.setValue(s,r),this.atomMap.has(s)||this.atomMap.set(s,M.createAtom(s.toString())),(o=this.atomMap.get(s))==null||o.reportChanged(),!0},ownKeys:()=>Array.from(this.map.keys())});this.map=M.observable.map(new Map)}setValue(e,s){this.map.set(e,s)}getValue(e){return this.map.get(e)}has(e){return this.map.has(e)}get entries(){return Array.from(this.map.entries())}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}setValues(e){e&&Object.keys(e).forEach(s=>{this.setValue(s,e[s])})}get proxy(){return new Proxy(this,this.proxyHandler)}}sc.prototype[tc]=!0;function jf(t,e){return new Proxy(t,{construct:(s,r)=>{const o=new t(...r);return o.setValues(e),o.proxy}})}const Ae=t=>{const e=jf(sc,t);return new e(t)},Bn="/kos/ui/internal/heartbeat/",Bf=({relationshipId:t,destinationAddress:e,onAbort:s,waitTime:r,beatTime:o})=>{const n=I.getInstance().transport,i=new AbortController;let a=performance.now();const c=n.subscribeTopic({topic:`${Bn}${t}`,callback:()=>{a=performance.now()}}),d=r??3e3,u=window.setInterval(()=>{let v=performance.now()-a;v=v/1e3,v>d/1e3&&i.abort()},d),h=o??2e3,g=window.setInterval(()=>{Na({msg:{},options:{topic:`${Bn}${t}`,destinationAddress:e}})},h),m=()=>{window.clearInterval(g),window.clearInterval(u),c()},y=()=>{m(),s&&s(),i.signal.removeEventListener("abort",y)};return i.signal.addEventListener("abort",y),{cleanUpHeartbeat:m}},rc=(...t)=>e=>t.reduce((s,r)=>r(s),e),Kf={maxAttempts:5,baseDelayMs:100,backoffFactor:1.5};async function Hf(t,e){let s=1;const r={...Kf,...e},{maxAttempts:o,baseDelayMs:n,backoffFactor:i}=r;let a=n;for(;s<=o;)try{return await t()}catch(c){if(p.error(`Attempt ${s} failed: ${c}`),s<o)a=n*Math.pow(i,s),await new Promise(d=>setTimeout(d,a)),s++;else throw c}throw new Error("All attempts failed")}const zf=p.createLogger({name:"kos-service-request"}),oe=t=>({isMock:!1,URL:exports.BASE_URL}),Gf=(t,e,s)=>async({id:r,tracker:o,urlOverride:n,ordered:i,studio:a,fos:c,bridge:d,timeout:u,signal:h,destinationAddress:g})=>{const m={method:"DELETE"};t&&(m.destinationAddress=t),o&&(m.tracker=o),wt(m,{ordered:i,studio:a,fos:c,bridge:d,timeout:u,signal:h,destinationAddress:g});try{const y=await s(n||`${e}/${r}`,m);if(!y.ok)throw Error(`There was a problem deleting the model; returned status ${y.status}`);return await y.json()??void 0}catch(y){if(y instanceof DOMException){if(y.name==="TimeoutError")throw new B("Request timed out while deleting model");if(y.name==="AbortError")throw new B("Request was cancelled while deleting model")}throw y}},wt=(t,{ordered:e,studio:s,fos:r,destinationAddress:o,bridge:n,timeout:i,signal:a})=>(i&&(t.timeout=i),a&&(t.signal=a),e&&(t.ordered=e),s&&(t.studio=s),r&&(t.fos=r),n&&(t.bridge=n),(o||o==="")&&(t.destinationAddress=o),t),Vf=(t,e,s)=>async({urlOverride:r,ordered:o,studio:n,fos:i,bridge:a,timeout:c,signal:d,destinationAddress:u})=>{const h={method:"GET"};t&&(h.destinationAddress=t),wt(h,{timeout:c,ordered:o,studio:n,fos:i,bridge:a,signal:d,destinationAddress:u});const g=r||e;try{const m=await s(g,h);if(!m.ok){let v;try{v=await m.json()}catch{}throw new B(`There was a problem retrieving the model; returned status ${m.status}`,v??void 0)}return await m.json()??void 0}catch(m){if(m instanceof DOMException){if(m.name==="TimeoutError")throw new B("Request timed out while retrieving models");if(m.name==="AbortError")throw new B("Request was cancelled while retrieving models")}throw m}},Yf=(t,e,s)=>async({urlOverride:r,ordered:o,studio:n,fos:i,bridge:a,tracker:c,timeout:d,signal:u,destinationAddress:h})=>{const g={method:"GET"};t&&(g.destinationAddress=t),c&&(g.tracker=c),wt(g,{timeout:d,ordered:o,studio:n,fos:i,bridge:a,signal:u,destinationAddress:h});const m=r||e;zf.debug(`resolvedUrl: ${m}`);try{const y=await s(m,g);if(!y.ok){let E;try{E=await y.json()}catch{}throw new B(`There was a problem retrieving the model; returned status ${y.status}`,E??void 0)}return await y.json()??void 0}catch(y){if(y instanceof DOMException){if(y.name==="TimeoutError")throw new B("Request timed out while retrieving model");if(y.name==="AbortError")throw new B("Request was cancelled while retrieving model")}throw y}},qf=(t,e,s)=>async({urlOverride:r,id:o,ordered:n,studio:i,fos:a,bridge:c,timeout:d,signal:u,destinationAddress:h})=>{const g={method:"GET"};t&&(g.destinationAddress=t),wt(g,{timeout:d,ordered:n,studio:i,fos:a,bridge:c,signal:u,destinationAddress:h});const m=r||`${e}/${o}`;try{const y=await s(m,g);if(!y.ok){let E;try{E=await y.json()}catch{}throw new B(`There was a problem retrieving the model; returned status ${y.status}`,E??void 0)}return await y.json()??void 0}catch(y){if(y instanceof DOMException){if(y.name==="TimeoutError")throw new B("Request timed out while retrieving model by ID");if(y.name==="AbortError")throw new B("Request was cancelled while retrieving model by ID")}throw y}};class B extends Error{constructor(s,r){super(s);l(this,"payload");this.name="FetchException",this.payload=r}}const Kn=(t,e,s)=>async({model:r,urlOverride:o,ordered:n,tracker:i,studio:a,fos:c,bridge:d,timeout:u,signal:h,destinationAddress:g})=>{const m={method:"POST",body:typeof r=="string"?r:JSON.stringify(r)};t&&(m.destinationAddress=t),i&&(m.tracker=i),wt(m,{timeout:u,ordered:n,studio:a,fos:c,bridge:d,signal:h,destinationAddress:g});try{const y=await s(o||e,m);if(!y.ok){let E;try{E=await y.json()}catch{}throw new B(`There was a problem sending the POST data; returned status ${y.status}`,E??void 0)}return await y.json()??void 0}catch(y){if(y instanceof DOMException){if(y.name==="TimeoutError")throw new B("Request timed out while adding model");if(y.name==="AbortError")throw new B("Request was cancelled while adding model")}throw y}},Hn=(t="POST",e,s,r)=>async({model:o,id:n,urlOverride:i,ordered:a,studio:c,fos:d,bridge:u,timeout:h,signal:g,destinationAddress:m})=>{const y={method:t};o&&(y.body=JSON.stringify(o)),e&&(y.destinationAddress=e),wt(y,{timeout:h,ordered:a,studio:c,fos:d,bridge:u,signal:g,destinationAddress:m});try{const v=await r(i||`${s}/${n}`,y);if(!v.ok){let _;try{_=await v.json()}catch{}throw new B(`There was a problem modifying the model; returned status ${v.status}`,_??void 0)}return await v.json()??void 0}catch(v){if(v instanceof DOMException){if(v.name==="TimeoutError")throw new B("Request timed out while modifying model");if(v.name==="AbortError")throw new B("Request was cancelled while modifying model")}throw v}},se={build:({destinationAddress:t="",basePath:e,getAllPath:s,getOnePath:r,deleteModelPath:o,addModelPath:n,modifyModelPath:i,mock:a=!1})=>{const c=a?fetch:exports.kosFetch;return{getAll:Vf(t,s||e,c),getModelById:qf(t,r||e,c),getOne:Yf(t,r||e,c),addModel:Kn(t,n||e,c),deleteModel:Gf(t,o||e,c),modifyModel:Hn("POST",t,i||e,c),putModel:Hn("PUT",t,i||e,c),postModel:Kn(t,n||e,c)}}},Wf=mt(),oc=()=>`kos-${Wf}`,Qf=t=>!!t&&!t.includes("VM_SERVICE")&&t.startsWith(oc()),xo=async(t,e=6e4)=>new Promise((s,r)=>{const{unsubscribe:o}=O(t,i=>{$.debug(`recieved response for refId ${t}: ${i}`),o(),clearTimeout(n);try{const a=i!=null&&i.body?JSON.parse(i.body):{};s(a)}catch{const a=(i==null?void 0:i.body)||{};s(a)}}),n=setTimeout(()=>{o(),r(Error(`Request with ID ${t} timed out. Cancelling.`))},e)}),Zf=async(t,e,s)=>{const r=xo(s),o=await Promise.allSettled([t(e),r]);if(o[0].status==="fulfilled"){if(o[1].status==="rejected")throw Error(o[1].reason);if(o[0].value){if(o[1].value.error)throw Error(o[1].value.error);return o[0].value.data=o[1].value,o[0].value}}else throw Error(o[0].reason)},Xf=async({topic:t,msg:e,requestId:s})=>{const r=s??mt(),o=xo(r);j(t,e,{sync:r});const n=await o;if(n.error)throw Error(n.error);return n},le=new Map;class nc{constructor(e){l(this,"_context");l(this,"_parent");l(this,"_id");this._id=e,this._context=new M.ObservableMap({}),this._parent="",M.makeAutoObservable(this)}setParent(e){X(()=>{this._parent=e})}get id(){return this._id}get context(){return this._context}get parentModel(){var e;if(this._parent)return(e=ve(this._parent))==null?void 0:e.model}get companionModels(){const e=ve(this._id);return e!=null&&e.model?Ya(e.model):[]}get(e){var s,r;if(this._context.has(e))return this._context.get(e);if(this.companionModels.length>0){const o=this.companionModels.find(n=>{var i;return!n.id||!le.has(n.id)?!1:(i=le.get(n.id))==null?void 0:i.context.has(e)});if(o)return(s=le.get(o.id))==null?void 0:s.get(e)}if(this._parent)return(r=le.get(this._parent))==null?void 0:r.get(e)}set(e,s){this._context.set(e,s)}remove(e){this._context.delete(e)}clear(){this._context.clear()}}const z={createContext:(t,e)=>{const s=le.get(t)??new nc(t);if(e){if(!le.has(e))throw new Error(`Parent context ${e} does not exist`);s.setParent(e)}else t!=="root"&&s.setParent("root");return le.set(t,s),s},getContext:t=>le.get(t),deleteContext:t=>{le.delete(t)},setParentContext:(t,e)=>{var s;if(!le.has(e))throw new Error(`Parent context ${e} does not exist`);(s=le.get(t))==null||s.setParent(e)},rootContext:()=>le.get("root")};z.createContext("root");const Jf=t=>z.getContext(t.id);function eg(t,e){return t.length!==e.length?!1:t.every(s=>e.includes(s))}class Po{constructor({container:e,key:s}){l(this,"_container");l(this,"_map");l(this,"_key");l(this,"data");this._container=e,this._map=M.observable.map(new Map),this._key=s,this.data=Ae(),this.generateIndex(),M.autorun(()=>{this._container.revision&&this.generateIndex()}),M.makeAutoObservable(this)}refresh(){this.generateIndex()}addItemToIndex(e,s,r=this._map,o=this.data){const n=r.get(e)||new Set;n.add(s),r.set(e,n),o[e]=Array.from(n)}resolveIndex(e,s){this.data.keys.filter(o=>!Object.keys(s).includes(o)).forEach(o=>{delete this.data[o],this._map.delete(o)}),Object.keys(s).forEach(o=>{const n=s[o],i=this.data[o]||[];if(eg(n,i))p.debug(`KosContainerIndex - Index ${o} is the same`);else{this.data[o]=n;const a=e.get(o)||new Set;this._map.set(o,a)}})}generateIndex(){M.runInAction(async()=>{const e=new Map,s={};for(const r of this._container.data){const o=typeof this._key=="function"?await this._key(r):r[this._key];Array.isArray(o)?o.forEach(n=>{this.addItemToIndex(n,r,e,s)}):typeof o=="string"||typeof o=="number"?this.addItemToIndex(String(o),r,e,s):typeof o=="boolean"&&this.addItemToIndex(String(o),r,e,s)}this.resolveIndex(e,s)})}get keys(){return Array.from(this._map.keys())}get index(){return this._map}getByKey(e){const s=this._map.get(e);return s?Array.from(s):[]}}function tg(t,e,s=[]){const r=Object.getOwnPropertyDescriptors(t);return Object.keys(r).filter(i=>M.isComputedProp(t,i)).filter(i=>s.includes(i)).map(i=>M.reaction(()=>t[i],(a,c)=>{e({name:i,newValue:a,oldValue:c})}))}const _t=p.createLogger({name:"kos-container-model"});class Te{constructor(e){l(this,"_data");l(this,"_sortKey");l(this,"_revision");l(this,"_index");l(this,"_optionsMap");l(this,"_disposerMap",new Map);l(this,"_parentId");l(this,"idx");this._data=M.observable.map(new Map),this._sortKey=e==null?void 0:e.sortKey,this._revision=1;const s=e!=null&&e.extensionId?S.indexExtension.loadIndexExtensions(e.extensionId):{},r=(e==null?void 0:e.indexMap)||{};this._optionsMap={...r,...s};const o=e!=null&&e.indexMap?Object.keys(e.indexMap).reduce((n,i)=>(n[i]=void 0,n),{}):{};this._index=M.observable.map(o),this.idx=Ae(),this._parentId=e==null?void 0:e.parentId,M.makeAutoObservable(this),this.init()}init(){Object.keys(this._optionsMap).forEach(e=>{const s=this._optionsMap[e],r=new Po({container:this,key:s});this._index.set(e,r),this.idx[e]=r.data})}[Symbol.iterator](){return this.data[Symbol.iterator]()}get index(){return this._index}get revision(){return this._revision}get indexKeys(){return Array.from(this.index.keys()).reduce((e,s)=>{var r;return e[s]=(r=this.index.get(s))==null?void 0:r.keys,e},{})}sortFn(e,s){const r=this._sortKey;return r?String(e[r]).localeCompare(String(s[r]),void 0,{numeric:!0}):0}get data(){const e=Array.from(this._data.values());return this._sortKey&&e.sort(this.sortFn.bind(this)),e}increment(){M.runInAction(()=>{this._revision=this._revision+1})}addAll(e){M.runInAction(()=>{e.forEach(s=>this.addModel(s,!0))}),this.increment()}removeAll(e){M.runInAction(()=>{e.forEach(s=>this.removeModel(s,!0)),this.increment()})}addModel(e,s){this._data.set(e.id||"",e),e.id&&this._parentId&&z.setParentContext(e.id,this._parentId),s||this.increment();const r=this._disposerMap.get(e.id);r&&(r(),this._disposerMap.delete(e.id));const o=Object.entries(this._optionsMap||{}),n=Object.values(this._optionsMap||{}),i=new Map(o.map(([u,h])=>[h,u])),a=u=>{var g,m;n.includes(u.name)&&((g=this.index.get(i.get(u.name)))==null||g.refresh());const h=o.filter(([,y])=>typeof y=="function");for(const[y]of h)(m=this.index.get(y))==null||m.refresh()},c=tg(e,a,n.filter(u=>typeof u=="string")),d=M.observe(e,a);this._disposerMap.set(e.id||"",()=>[d,...c].forEach(u=>u()))}removeModel(e,s){this._data.delete(e),s||this.increment();const r=this._disposerMap.get(e);r&&(r(),this._disposerMap.delete(e))}updateModel(e){this._data.set(e.id||"",e),this.increment()}getModel(e){return this._data.get(e)}getIndexKeys(e){return this.index.has(e)?this.index.get(e).keys??[]:(_t.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[])}getIndexByKey(e,s){if(this.index.has(e)){const r=this.index.get(e);return r.index.has(s)?r.getByKey(s):(_t.info(`key ${s} not found in ${e} index: ${Array.from(r.index.keys())}`),[])}else return _t.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[]}async clear(){this._data.forEach(e=>{const s=e.id;He(e).then(()=>{_t.debug(`${s} destroyed, removing from map`),this.removeModel(s,!0)}).catch(r=>_t.error(r))}),this.increment()}filter(e,s){return this.data.filter(e,s)}sort(e){return this.data.sort(e)}map(e,s){return this.data.map(e,s)}forEach(e,s){this.data.forEach(e,s)}toJSON(){return{indexes:this.indexKeys,data:this.data.map(s=>({id:s.id,type:s.constructor.name}))}}}const Lr=p.createLogger({name:"kos-data-container"});class Lo{constructor(e){l(this,"_data");l(this,"_sortKey");l(this,"_revision");l(this,"_index");l(this,"_optionsMap");l(this,"_disposerMap",new Map);l(this,"idx");this._data=M.observable.map(new Map),this._sortKey=e==null?void 0:e.sortKey,this._revision=1,this._optionsMap=(e==null?void 0:e.indexMap)||{};const s=e!=null&&e.indexMap?Object.keys(e.indexMap).reduce((r,o)=>(r[o]=void 0,r),{}):{};this._index=M.observable.map(s),this.idx=Ae(),M.makeAutoObservable(this,{}),this.init()}init(){Object.keys(this._optionsMap).forEach(e=>{const s=this._optionsMap[e],r=new Po({container:this,key:s});this._index.set(e,r),this.idx[e]=r.data})}[Symbol.iterator](){return this.data[Symbol.iterator]()}get index(){return this._index}get indexKeys(){return Array.from(this.index.keys()).reduce((e,s)=>{var r;return e[s]=(r=this.index.get(s))==null?void 0:r.keys,e},{})}get revision(){return this._revision}addAll(e){M.runInAction(()=>{e.forEach(s=>this.addModel(s))})}removeAll(e){M.runInAction(()=>{e.forEach(s=>this.removeModel(s))})}sortFn(e,s){const r=this._sortKey;return r?String(e[r]).localeCompare(String(s[r]),void 0,{numeric:!0}):0}get data(){const e=Array.from(this._data.values());return this._sortKey&&e.sort(this.sortFn.bind(this)),e}increment(){M.runInAction(()=>{this._revision=this._revision+1})}addModel(e,s){const r=M.isObservable(e)?e:M.observable.object(e),o=this._disposerMap.get(e.id);o&&(o(),this._disposerMap.delete(e.id)),this._data.set(r.id||"",r),s||this.increment();const n=M.observe(r,i=>{Object.values(this._optionsMap||{}).includes(i.name)&&this.increment()});this._disposerMap.set(r.id||"",n)}removeModel(e){this._data.delete(e),this.increment();const s=this._disposerMap.get(e);s&&(s(),this._disposerMap.delete(e))}updateModel(e){const s=M.observable.object(e);this._data.set(s.id||"",s),this.increment()}getModel(e){return this._data.get(e)}getIndexKeys(e){return this.index.has(e)?this.index.get(e).keys??[]:(Lr.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[])}getIndexByKey(e,s){if(this.index.has(e)){const r=this.index.get(e);return r.index.has(s)?r.getByKey(s):(Lr.info(`key ${s} not found in ${e} index: ${Array.from(r.index.keys())}`),[])}else return Lr.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[]}async clear(){this._data.clear(),this.increment()}filter(e,s){return this.data.filter(e,s)}sort(e){return this.data.sort(e)}map(e,s){return this.data.map(e,s)}forEach(e,s){this.data.forEach(e,s)}toJSON(){return{indexes:this.indexKeys,data:this.data.map(s=>({id:s.id}))}}}class sg{constructor({type:e,model:s,childRegistration:r}){l(this,"type");l(this,"childRegistration");l(this,"model");this.type=e,this.model=s,this.childRegistration=r}get factory(){return te.Factory.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!1,factory:this.factory},...this.childRegistration}}get predicate(){return he(this.type)}}class rg{constructor({type:e,model:s,childRegistration:r}){l(this,"type");l(this,"model");l(this,"childRegistration");this.type=e,this.model=s,this.childRegistration=r}get factory(){return te.Singleton.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!0,factory:this.factory},...this.childRegistration}}get predicate(){return he(this.type)}}class ic{constructor(){l(this,"_token");M.makeAutoObservable(this),O("token",e=>{this.token=e==null?void 0:e.body})}get token(){return this._token}set token(e){this._token=e}}class ac{constructor(){l(this,"routes",[]);l(this,"openApiRoutes",[])}use(e,s,...r){this.routes.push({method:e,path:s,middlewares:r});const o=this.extractOpenApiParams(s);this.openApiRoutes.push({method:e,path:s,parameters:o})}remove(e,s){const r=this.routes.length;return this.routes=this.routes.filter(o=>!(o.method===e&&o.path===s)),this.openApiRoutes=this.openApiRoutes.filter(o=>!(o.method===e&&o.path===s)),r-this.routes.length}removeAllForPath(e){const s=this.routes.length;return this.routes=this.routes.filter(r=>r.path!==e),this.openApiRoutes=this.openApiRoutes.filter(r=>r.path!==e),s-this.routes.length}getRoutes(){return this.routes.map(e=>({method:e.method,path:e.path}))}async handle(e,s){var a;const{path:r,query:o,params:n}=this.extractPathParams(e.path),i={...e,params:n,query:o};for(const c of this.routes){const d=this.matchRoute(c.path,r);if(c.method===e.method&&d){i.params=d;let u=0;const h=async()=>{if(u<c.middlewares.length){const g=c.middlewares[u++];await g(i,s,h)}};await h();return}}(a=s.status)==null||a.call(s,404).send({error:"Route not found"})}extractOpenApiParams(e){return e.split("/").filter(s=>s.startsWith(":")).map(s=>({name:s.slice(1),in:"path",required:!0,schema:{type:"string"}}))}generateOpenApiSpec(){const e={};for(const s of this.openApiRoutes)e[s.path]||(e[s.path]={}),e[s.path][s.method.toLowerCase()]={summary:s.description||`Handles ${s.method} ${s.path}`,parameters:s.parameters||[],responses:{200:{description:"Successful response"}}};return{openapi:"3.0.0",info:{title:"Kos Router API",version:"1.0.0",description:"Dynamically generated OpenAPI documentation"},paths:e}}extractPathParams(e){const[s,r]=e.split("?"),o=this.parseQueryParams(r);for(const n of this.routes){const i=this.matchRoute(n.path,s);if(i)return{path:s,query:o,params:i}}return{path:s,query:o,params:{}}}matchRoute(e,s){const r=e.split("/").filter(Boolean),o=s.split("/").filter(Boolean);if(r.length!==o.length)return null;const n={};for(let i=0;i<r.length;i++)if(r[i].startsWith(":"))n[r[i].slice(1)]=decodeURIComponent(o[i]);else if(r[i]!==o[i])return null;return n}parseQueryParams(e){return e?e.split("&").reduce((s,r)=>{const[o,n]=r.split("=").map(decodeURIComponent);return s[o]=n??"",s},{}):{}}}const cc=p.createLogger({name:"intent-service"}),og=t=>{vo(`/kos/intent/${t.type}`)?j(`/kos/intent/${t.type}`,t.options,{"kos.intent.type":t.type}):cc.info(`No subscribers for intent ${t.type}. Intent not sent.`)},ng=async t=>new Promise(e=>{const{type:s,options:r}=t;if(vo(`/kos/intent/${t.type}`)){const o=mt(),{unsubscribe:n}=O(o,a=>{clearTimeout(i),n(),a&&(a.headers=a.headers||{},a.headers["kos.intent.type"]=s,a.headers.responseId=o),e([null,{body:a==null?void 0:a.body,payload:a}])}),i=setTimeout(()=>{n(),e([`Intent ${s} timed out after 1 second`,null]),console.warn(`Intent ${s} timed out after 1 second`)},1e3);j(`/kos/intent/${s}`,r,{"kos.intent.type":s,sync:o})}else cc.info(`No subscribers for intent ${t.type}. Intent not sent.`),e([null,{body:void 0,payload:void 0}])}),_e=p.createLogger({name:"app-startup-service"});async function lc(t,e={}){const{timeout:s=3e4,throwOnTimeout:r=!0,requirePostStarted:o=!1}=e;if(t.length===0)return _e.warn("No app IDs provided to waitForAppsToStart"),!0;_e.debug(`Waiting for apps to start: ${t.join(", ")}`);try{const n=t.map(c=>`/kos/app/started/${c}`),i=await To(n,{getCurrentState:async()=>{try{const{default:c}=await Promise.resolve().then(()=>cp),[d,u]=await c.get("/api/kos/apps/started");return d?(_e.error("Error fetching started apps:",d),[]):u}catch(c){_e.error("Failed to fetch app startup status:",c)}return[]},shouldUseFetchedState:c=>t.every(d=>{const u=c.find(h=>h.appId===d);return!(!u||!u.started||o&&!u.postStarted)}),timeout:s}),a=t.filter(c=>{const d=i.find(u=>u.appId===c);return!!(!d||!d.started||o&&!d.postStarted)});if(a.length>0){const c=`Apps not started: ${a.join(", ")}`;if(_e.error(c),r)throw new Error(`App startup timeout: ${c}`);return!1}return _e.info(`All apps started successfully: ${t.join(", ")}`),!0}catch(n){const i=`Failed to wait for apps to start: ${t.join(", ")}`;if(_e.error(i,n),r)throw new Error(`${i} - ${n instanceof Error?n.message:String(n)}`);return!1}}async function ig(t,e={}){return lc([t],e)}async function ag(t,e=!1){const s={};try{const r=await exports.kosFetch("kos:///api/kos/apps/started");if(!r.ok)return t.forEach(i=>s[i]=!1),s;const o=await r.json(),n=(o==null?void 0:o.data)??[];t.forEach(i=>{const a=n.find(c=>c.appId===i);s[i]=(a==null?void 0:a.started)===!0&&(!e||(a==null?void 0:a.postStarted)===!0)})}catch(r){_e.error("Failed to check app startup status:",r),t.forEach(o=>s[o]=!1)}return s}async function cg(){try{const t=await exports.kosFetch("kos:///api/kos/apps/started");if(!t.ok)return[];const e=await t.json();return(e==null?void 0:e.data)??[]}catch(t){return _e.error("Failed to fetch started apps:",t),[]}}const Qr=M.when,ko=M.computed,X=M.runInAction,G=M.autorun,dc=M.reaction,Fo=M.observable,No="Not Assigned",lg="kos.trouble.added",dg="kos.trouble.removed";var me=(t=>(t.TroubleRank="kos.trouble.rank.mapper",t.TroubleColor="kos.trouble.color.mapper",t.TroubleRole="kos.trouble.role.mapper",t))(me||{}),zt=(t=>(t.TIME_CHANGE="/kos/internal/time/time",t.DAY_CHANGE="/kos/internal/time/day",t.TIMEZONE_CHANGE="/kos/internal/time/timezone",t))(zt||{});const uc=p.createLogger({name:"config-bean-service",group:"Services"}),Uo=exports.BASE_URL,hc=t=>(t==null?void 0:t.decimals)!==void 0,{postModel:ug,getOne:hg}=se.build({destinationAddress:"",basePath:`${Uo}/kos/config/`}),fc=async(t,e,s="/api/kos/config")=>(uc.debug(`sending modify request for ConfigBean: ${t}`),ug({model:e,urlOverride:`${Uo}${s}/${t}`})),gc=async(t,e="/api/kos/config")=>(uc.debug(`sending get request for ConfigBean: ${t}`),await hg({urlOverride:`${Uo}${e}/details/${t}/15`})),jo=t=>t.toLowerCase()==="true"||t.toLowerCase()==="false",pr=t=>{try{const e=Number(t);return!isNaN(e)}catch{return!1}};function pc(t=[]){return t.reverse().reduce((e,s)=>{const{overrides:r}=s;return r&&(e={...e,...r}),e},{})}function mc(t,e="",s={}){for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const o=e?`${e}.${r}`:r;typeof t[r]=="object"&&t[r]!==null&&!Array.isArray(t[r])?mc(t[r],o,s):s[o]=t[r]}return s}const yc=(t,e)=>{const s=t.details[0].bean||pc(t.details[0].scopes),r=mc(s);M.runInAction(()=>{const o={...r};e.props.setValues(o)})},bc=(t,e)=>{M.runInAction(()=>{t.changes.forEach(s=>{const r=s.attr;let o=s.currentValue,n=s.previousValue;typeof o=="string"&&jo(o)&&(o=o.toLowerCase()=="true",n=(n==null?void 0:n.toLowerCase())=="true"),typeof o=="string"&&pr(o)&&(o=Number(o),n=Number(n)),e.props[r]=o,e.prevProps[r]=n})})},wc=t=>Object.fromEntries(t.props.entries),fg=t=>e=>s=>t.build(e,s);var gg=Object.defineProperty,pg=Object.getOwnPropertyDescriptor,vc=(t,e,s,r)=>{for(var o=r>1?void 0:r?pg(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&gg(e,s,o),o};function mg(t,e){for(const s of t)if(new RegExp(`^${s}$`).test(e))return s}const Bo="config-bean-model",vs=p.getLogger(Bo),yg=Ge("path");let Ns=class{constructor(t,e){l(this,"_modifyConfigBean");l(this,"_getConfigBean");l(this,"_schema");l(this,"id");l(this,"path");l(this,"props");l(this,"prevProps");l(this,"serviceBasePath");Object.assign(this,e),this.id=t,this.path=e.path,this.serviceBasePath=e.serviceBasePath;const{modifyConfigBean:s=fc,getConfigBean:r=gc}=e;this._modifyConfigBean=s,this._getConfigBean=r,this.props=Ae(),this.prevProps=Ae()}get values(){return this.props.values}async ready(){vs.debug(`readying config bean ${this.path}`),vs.debug(`complete readying config bean ${this.path}`)}async load(){vs.debug(`loading config bean ${this.path}`);const t=await this._getConfigBean(this.path,this.serviceBasePath);if(t!=null&&t.data){const e=t.data;yc(e,this),vs.debug(this.values);const s=t==null?void 0:t.data.details[0].schema;X(()=>{s&&(this._schema=s)})}}get schemaKeys(){var t;return Object.keys(((t=this._schema)==null?void 0:t.schema)||{})}getSchemaForProperty(t){var s,r;if(this.schemaKeys.includes(t))return(s=this._schema)==null?void 0:s.schema[t];const e=mg(this.schemaKeys,t);if(e)return(r=this._schema)==null?void 0:r.schema[e]}async updateProperty(t,e){this.props[t]=e,await this.updateConfigBean()}async updateConfigBean(){const t=wc(this);await this._modifyConfigBean(this.path,t,this.serviceBasePath)}handleConfigBeanUpdated(t){bc(t,this)}};vc([U({topic:`/kos/config/${yg}`,websocket:!0})],Ns.prototype,"handleConfigBeanUpdated",1);Ns=vc([R(Bo)],Ns);const qt=new we({class:Ns,type:Bo}),mr=({path:t,lazy:e,serviceBasePath:s})=>(r,o)=>{r[F]=r[F]||{},r[F][o]={modelType:qt.type,id:`${qt.type}-${t}`,options:{path:t,serviceBasePath:s},lifecycle:H.INIT,lazy:e}},{URL:Mc}=oe(),{getOne:bg,getAll:wg}=se.build({basePath:`${Mc}/api/kos/regions/info`}),Ec=async()=>await bg({}),Tc=async()=>await wg({urlOverride:`${Mc}/api/kos/regions`}),vg=Object.freeze(Object.defineProperty({__proto__:null,getRegionInfo:Ec,getRegions:Tc},Symbol.toStringTag,{value:"Module"}));var ie=(t=>(t[t.family=0]="family",t[t.scale=1]="scale",t[t.offset=2]="offset",t[t.decimals=3]="decimals",t[t.alias=4]="alias",t[t.system=5]="system",t))(ie||{});const _c={s:["time",1,0,0],second:["time",1,0,0],m:["time",1/60,0,0],minute:["time",1/60,0,0],h:["time",1/3600,0,0],hour:["time",1/3600,0,0],day:["time",1/86400,0,0],week:["time",1/604800,0,0],month:["time",1/2628e3,0,0],year:["time",1/31536e3,0,0],default:["time",1/.001,0,0],ms:["time",1/.001,0,0],millisecond:["time",1/.001,0,0],microsecond:["time",1/1e-6,0,0],nanosecond:["time",1/1e-9,0,0],picosecond:["time",1/1e-12,0,0]};function Mg(t,e){const s=e.id,r=e.units.reduce((o,n)=>{const i=[n.measure,n.scale,n.offset,n.decimals,n.alias,s];return o[n.name]=i,n.alias&&(o[n.alias]=i),o},{..._c});return{...t,...r}}function Eg(t,e){const s=e.id,r=e.units.reduce((o,n)=>{const i=o[n.measure]||{},a=i[s]||{};i[s]=a;const c=[n.measure,n.scale,n.offset,n.decimals,n.alias,s];return a[n.name]=c,Object.hasOwn(n,"default")&&Object.defineProperty(a,"default",{value:c,writable:!0,enumerable:!0,configurable:!0}),o[n.measure]=i,n.alias&&(o[n.alias]=i),o},{time:{[s]:{..._c}}});return Object.keys(r).forEach(o=>{t[o]={...t[o],...r[o]}}),t}function Tg(t,e){const s=e.id,r=e.units.reduce((o,n)=>{const i=o[n.measure]||{};return Object.hasOwn(n,"default")&&(i[s]=n.name),o[n.measure]=i,o},{time:{[s]:"millisecond"}});return Object.keys(r).forEach(o=>{t[o]={...t[o],...r[o]}}),t}var _g=Object.defineProperty,Ig=Object.getOwnPropertyDescriptor,Ko=(t,e,s,r)=>{for(var o=r>1?void 0:r?Ig(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&_g(e,s,o),o};const Cs="region-info-model",It=p.createLogger({name:"region-info-model"});let Wt=class{constructor(t){l(this,"id");l(this,"unitSystemMap");l(this,"measureMap");l(this,"defaultMeasureMap");l(this,"regionMap");l(this,"timeFormats");l(this,"dateFormats");l(this,"unitSystems");l(this,"regionSource");l(this,"region");l(this,"regions",[]);l(this,"timeZoneMap",{});this.id=t,this.unitSystems={},this.unitSystemMap={},this.measureMap={},this.defaultMeasureMap={},this.timeFormats={},this.regions=[],this.dateFormats={},this.timeZoneMap={},this.regionMap={}}get availableRegions(){return this.regions}get defaultUnitSystem(){return String(this.regionSource.props.unitSystemId).toLowerCase()||""}get unitSystemId(){return this.defaultUnitSystem}get timeFormatId(){const t=this.regionSource.props.timeFormatId;if(!t)return"";const e=String(t),s=this.timeFormats[e];return s?String(s.id):""}get selectedTimeFormat(){const t=this.timeFormatId;return t?String(this.timeFormats[t].format):"HH:mm:ss"}get is12HourTimeFormat(){const t=this.timeFormatId;return t?this.timeFormats[t].ampm:!0}get dateFormatId(){const t=this.regionSource.props.dateFormatId;if(!t)return"";const e=String(t);return e?this.dateFormats[e].id:""}get selectedDateFormat(){const t=this.dateFormatId;return t?this.dateFormats[t].format:""}get selectedDateOrder(){const t=this.dateFormatId;return t?this.dateFormats[t].order.toLowerCase():"dmy"}get selectedCountry(){return this.regionSource.props.country||"en"}get selectedTimeZone(){return this.regionSource.props.timeZone||""}get timeZones(){return this.regionId?this.timeZoneMap[this.regionId]||[]:[]}get allTimeZones(){return Intl.supportedValuesOf("timeZone")}get regionId(){return this.region.props.regionId||""}get selectedRegion(){return this.regionMap[this.regionId]}get selectedUnitSystem(){return String(this.regionSource.props.unitSystemId)||""}get timeFormatOptions(){return Object.keys(this.timeFormats).map(t=>({id:t,format:this.timeFormats[t].format,ampm:this.timeFormats[t].ampm}))}get dateFormatOptions(){return Object.keys(this.dateFormats).map(t=>({id:t,format:this.dateFormats[t].format,order:this.dateFormats[t].order}))}get unitSystemOptions(){return Object.keys(this.unitSystems).map(t=>({id:t,name:t}))}setSelectedTimeFormat(t){if(!this.timeFormatOptions.find(e=>e.id===t))throw Error(`Invalid time format id. Must be one of ${this.timeFormatOptions.map(e=>e.id).join(", ")}`);this.regionSource.updateProperty("timeFormatId",t)}setSelectedDateFormat(t){if(!this.dateFormatOptions.find(e=>e.id===t))throw Error(`Invalid date format id. Must be one of ${this.dateFormatOptions.map(e=>e.id).join(", ")}`);this.regionSource.updateProperty("dateFormatId",t)}setSelectedUnitSystem(t){if(!this.unitSystemOptions.find(e=>e.id===t))throw Error(`Invalid date format id. Must be one of ${this.unitSystemOptions.map(e=>e.id).join(", ")}`);this.regionSource.updateProperty("unitSystemId",t)}getUnitSystem(t){if(!t)return this.defaultUnitSystem;const e=t==="drt"?"second":t,s=this.unitSystemMap[e];if(!s)throw Error(`No unit found with name: ${e}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return s[ie.system]}getUnitMeasure(t){const e=t==="drt"?"second":t,s=this.unitSystemMap[e];if(!s)throw Error(`No unit found with name: ${e}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return s[ie.family]}getDefaultUnitDecimalPlaces(t,e,s){if(!t||!e)throw Error("Measure and unit system are required");const r=s==="drt"?"second":s,o=this.measureMap[t];if(!o)throw Error(`No unit systems found for measure: ${t}. Measure should come from list of measures: ${Object.keys(this.measureMap).join(", ")}`);const n=o[e.toLowerCase()];if(!n)throw Error(`No unit system found for measure: ${t} and unit system: ${e}. Unit system should come form list of unit systems: ${Object.keys(o).join(", ")}`);const i=n[r||"default"];if(!i)throw Error(`No unit "${r||"default"}" found for measure: ${t} and unit system: ${e}. Unit should come from list of units: ${Object.keys(n).join(", ")}`);return i[ie.decimals]}getDefaultUnitForMeasure(t,e){if(!t||!e)throw Error("Measure and unit system are required");const s=this.defaultMeasureMap[t];if(!s)throw Error(`No unit systems found for measure: ${t}. Measure should come from list of measures: ${Object.keys(this.measureMap).join(", ")}`);const r=s[e.toLowerCase()];if(!r)throw Error(`No unit system found for measure: ${t} and unit system: ${e}. Unit system should come form list of unit systems: ${Object.keys(s).join(", ")}`);return r}convertByUnit(t,e,s){if(e[ie.family]!==s[ie.family])throw new Error(`Cannot convert between units of different families: ${e[ie.family]} and ${s[ie.family]}`);const r=e[ie.offset],o=e[ie.scale],n=s[ie.scale],i=s[ie.offset],a=s[ie.decimals];return((t-r)/(o/n)+i).toFixed(a)}convertByUnitName(t,e,s){const r=this.unitSystemMap[e],o=this.unitSystemMap[s];if(!r||!o)throw new Error(`No unit found with name: ${e} or ${s}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return this.convertByUnit(t,r,o)}convert(t,e,s){var a,c;if(e.unit&&s.unit)return this.convertByUnitName(t,e.unit,s.unit);const r=e.unit||"",o=s.unit||"";let n=this.unitSystemMap[r],i=this.unitSystemMap[o];if(!i&&s.measure&&s.system){const d=this.measureMap[s.measure];if(!d)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);i=(a=d[s.system])==null?void 0:a.default,i||It.info("Could not find default unit for measure",s.measure)}if(!n&&e.measure&&e.system){const d=this.measureMap[e.measure];if(!d)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);n=(c=d[e.system])==null?void 0:c.default,n||It.info("Could not find default unit for measure",e.measure)}return!n||!i?(It.warn("Could not find unit to convert to or from. Return value as is"),String(t)):this.convertByUnit(t,n,i)}async init(){It.debug("initializing region info")}async load(){It.debug("loading region info");const t=await Tc();t&&(this.regions=t.data.map(s=>s.id),this.timeZoneMap=t.data.reduce((s,r)=>({...s,[r.id]:r.timeZones}),this.timeZoneMap),this.regionMap=t.data.reduce((s,r)=>({...s,[r.id]:r}),{}));const e=await Ec();e&&(this.unitSystems=e.data.unitSystems.reduce((s,r)=>{const o={id:r.id,name:r.id};return s[r.id]=o,s},this.unitSystems),this.unitSystemMap=e.data.unitSystems.reduce(Mg,{}),this.measureMap=e.data.unitSystems.reduce(Eg,{}),this.defaultMeasureMap=e.data.unitSystems.reduce(Tg,{}),this.timeFormats=e.data.timeFormats.reduce((s,r)=>({...s,[r.id]:r}),{}),this.dateFormats=e.data.dateFormats.reduce((s,r)=>({...s,[r.id]:r}),{}))}async ready(){var t,e;await((e=(t=this.regionSource).ready)==null?void 0:e.call(t))}};Ko([mr({path:"kos:service:region:settings"})],Wt.prototype,"regionSource",2);Ko([mr({path:"kos:service:region"})],Wt.prototype,"region",2);Wt=Ko([R(Cs)],Wt);const ee={registration:{[Cs]:{class:Wt,singleton:!0}},type:Cs,factory:te.Singleton.create(Cs)},Us=({source:t,defaultSystem:e="si",defaultMeasure:s})=>{let r={system:e,measure:s};return typeof t=="string"?r={...r,unit:t}:r={...r,...t},r},Ho=(t,e,s)=>{const{model:r}=ve(ee.type);if(!r)throw new Error("RegionInfo model not found");if(!Fs(r))throw new Error("RegionInfo model not ready");const o={system:r.defaultUnitSystem},n=Us({source:e}),i=Us({source:s||o,defaultMeasure:r.getUnitMeasure(n.unit||"")});return r.convert(t,n,i)};function zn(t,e,s){const r=e.toLowerCase().replace(/_/g,"-").replace(/s$/,""),o=new Intl.NumberFormat().resolvedOptions().locale??"en-US";try{const n=(s==null?void 0:s.mode)||"long",i=(s==null?void 0:s.maxDecimals)??2,a=(s==null?void 0:s.minDecimals)??0;return new Intl.NumberFormat(o,{style:"unit",unit:r,unitDisplay:n,minimumFractionDigits:a,maximumFractionDigits:i}).format(t)}catch{return e}}const Sg=(t,e,s,r)=>{const o=Ho(t,e,s),n=Us({source:e}),{model:i}=ve(ee.type);if(!i)throw new Error("RegionInfo model not found");const a=i.getUnitMeasure(n.unit||""),c={system:i.defaultUnitSystem},d=Us({source:s||c,defaultMeasure:i.getUnitMeasure(n.unit||"")}),u=i.getDefaultUnitForMeasure(a,d.system),h=i.getDefaultUnitDecimalPlaces(a,d.system),g={...r,minDecimals:(r==null?void 0:r.minDecimals)??h,maxDecimals:(r==null?void 0:r.maxDecimals)??h};return{value:o,unit:u||n.unit||"",display:zn(o,u||n.unit||"",{...g,mode:"long"}),shortDisplay:zn(o,u||n.unit||"",{...g,mode:"short"})}};function Gn({start:t,end:e,count:s,decimals:r=0}){if(typeof t!="number"||typeof e!="number"||typeof s!="number")throw new Error("All input values should be numbers.");if(s<2)throw new Error("Count should be at least 2 for distribution.");if(t>=e)throw new Error("Start should be less than end.");const o=(e-t)/(s-1),n=[];for(let i=0;i<s;i++){const a=Math.round(t+i*o);n.push(a.toFixed(r))}return n}function Vn({start:t,end:e,interval:s,decimals:r=0}){if(typeof t!="number"||typeof e!="number"||typeof s!="number")throw new Error("All input values should be numbers.");if(s<=0)throw new Error("Interval should be a positive number.");if(t>=e)throw new Error("Start should be less than end.");const o=[];let n=t;for(;n<=e;)o.push(n.toFixed(r)),n+=s;return o[o.length-1]!==e.toString()&&o.push(e.toString()),o}const Qe=(t,e)=>s=>!t||!e?s:pr(s)?Ho(Number(s),t,e):s,Og=(t,e,s,r)=>{if((t==null?void 0:t.type)==="enum"||!(t!=null&&t.options))return[];if(t.options.type==="rangeCount")return Gn(t.options).map(Qe(s,r));if(t.options.type==="rangeInterval")return Vn(t.options).map(Qe(s,r));if(t.options.type==="list"){const{list:o}=t.options;return o.map(Qe(s,r))}else{if(t.options.type==="unitSystemRangeCount"&&e)return Gn(t.options.unitSystems[e]).map(Qe(s,r));if(t.options.type==="unitSystemRangeInterval"&&e)return Vn(t.options.unitSystems[e]).map(Qe(s,r));if(t.options.type==="unitSystemList"&&e){const{list:o}=t.options.unitSystems[e];return o.map(Qe(s,r))}}return[]},$g=(t,e)=>{if(!((t==null?void 0:t.type)==="enum"||!(t!=null&&t.options)))return t.options.type==="unitSystemRangeCount"&&e?{type:"rangeCount",...t.options.unitSystems[e]}:t.options.type==="unitSystemRangeInterval"&&e?{type:"rangeInterval",...t.options.unitSystems[e]}:t.options.type==="unitSystemList"&&e?{type:"list",...t.options.unitSystems[e]}:t.options.type==="unitSystemKeypad"&&e?{type:"keypad",...t.options.unitSystems[e]}:t.options};var Dg=Object.defineProperty,Cg=Object.getOwnPropertyDescriptor,zo=(t,e,s,r)=>{for(var o=r>1?void 0:r?Cg(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Dg(e,s,o),o};function Rg(t){return(t==null?void 0:t.type)==="enum"}function Ag(t){switch(t){case"s":return"second";case"ms":return"millisecond";case"min":return"minute";case"h":return"hour";case"d":return"day";case"w":return"week";case"m":return"month";case"y":return"year";case"ml":return"milliliter";default:return t}}function xg(t,e){const s=new Date;s.setHours(0,0,0,0);const r=new Date(s.getTime()+t*1e3);return Re.format(r,e)}const Rs="config-bean-prop-model",Ze=p.createLogger({name:"config-bean-prop-model"}),Pg=Ge("path"),Lg=Ge("serviceBasePath");let Qt=class{constructor(t,e){l(this,"id");l(this,"path");l(this,"attribute");l(this,"converter");l(this,"formatter");l(this,"optionsExpander");l(this,"serviceBasePath");l(this,"regionInfo");l(this,"bean");this.id=t,this.path=e.path,this.attribute=e.attribute,this.converter=e.converter,this.formatter=e.formatter,this.serviceBasePath=e.serviceBasePath,this.optionsExpander=e.optionsExpander}getDefaultUnitDecimalPlaces(t,e,s){if(!t)throw new Error("measure is required");if(!e)throw new Error("unitSystem is required");return hc(this.displayOptions)?this.displayOptions.decimals:this.regionInfo.getDefaultUnitDecimalPlaces(t,e,s)}getDefaultUnitForMeasure(t,e){if(!t)throw new Error("measure is required");if(!e)throw new Error("unitSystem is required");return this.regionInfo.getDefaultUnitForMeasure(t,e)}get schemaType(){const t=this.bean.getSchemaForProperty(this.attribute);return t!=null&&t.type?t.type:"String"}get schemaFormat(){const t=this.bean.getSchemaForProperty(this.attribute);return t!=null&&t.format?Ag(t.format):""}get options(){var i;const t=this.regionInfo.defaultUnitSystem,e=this.getConverter(),s=((i=e==null?void 0:e.to)==null?void 0:i.system)??t,r=this.bean.getSchemaForProperty(this.attribute),o=Rg(r)?r.values:Og(r,s,e==null?void 0:e.from,e==null?void 0:e.to),n=o.length>0?o.map(a=>({label:a,value:a})):[];return this.optionsExpander?typeof this.optionsExpander=="function"?this.optionsExpander(s,o):this.optionsExpander:n}convertUnit(t,e,s){const r=(t==null?void 0:t.measure)||s,o=(t==null?void 0:t.system)||e,n=t==null?void 0:t.unit;return{measure:r,system:o,unit:n}}getConverterUnits(){const t=this.regionInfo.defaultUnitSystem,e=this.getConverter();if(!e)throw Error("No converter defined");const s=e.measure,r=this.convertUnit(e.from,"si",s),o=this.convertUnit(e.to,t,s);return{backend:r,display:o}}set value(t){this.updateProperty(t)}get value(){return this.getValue(!0)}get rawValue(){return this.bean.props[this.attribute]}get significantValue(){var o,n;const t=this.value,e=this.regionInfo.defaultUnitSystem,s=this.getConverter(),r=(s==null?void 0:s.measure)||((o=s==null?void 0:s.to)==null?void 0:o.measure);if(!isNaN(t)&&s&&r){const i=this.getDefaultUnitDecimalPlaces(r,e,(n=s==null?void 0:s.to)==null?void 0:n.unit);try{const c=this.getFormatterOptions(s);if(c){let d=String(t);return d=c.formatToParts(Number(t))[0].value,Number(d)}}catch(c){Ze.info(`error formatting value ${t}`,c)}return Number(t).toFixed(i)}return t}get previousValue(){return this.getValue(!1)}getValue(t){const e=this.bean[t?"props":"prevProps"][this.attribute];if(typeof e=="boolean")return e;if(this.getConverter()&&!isNaN(e)){const{backend:r,display:o}=this.getConverterUnits();return this.regionInfo.convert(Number(e),r,o)}return e||""}async activate(){Ze.debug(`activating config bean ${this.id}`)}get displayValue(){const t=this.value;if(typeof t=="boolean")return String(t);if(this.schemaFormat==="drt"){const s=this.regionInfo.is12HourTimeFormat?"h:mm:ss a":"HH:mm:ss";return xg(t,s)}if(!isNaN(t))try{const e=this.getConverter(),s=this.getFormatterOptions(e);if(s){let r=String(t);return r=s.format(Number(t)),r}}catch(e){Ze.error(`error formatting value ${t}`,e)}return String(t)}get unit(){const t=this.getConverter();if(!isNaN(this.value)){const e=this.getFormatterOptions(t);if(e){const r=e.formatToParts(Number(this.value)).find(o=>o.type==="unit");return(r==null?void 0:r.value)??this.getDefaultUnit(t)}}return this.getDefaultUnit(t)}get displayOptions(){var o;const t=this.bean.getSchemaForProperty(this.attribute),e=this.regionInfo.defaultUnitSystem,s=this.getConverter(),r=((o=s==null?void 0:s.to)==null?void 0:o.system)??e;return $g(t,r)}getMeasureFromFormat(){const t=this.schemaFormat;return t?this.regionInfo.getUnitMeasure(t):""}getConverterFromFormat(){const t=this.getMeasureFromFormat();if(t){const e=this.regionInfo.selectedUnitSystem;return{unit:this.schemaFormat||this.regionInfo.getDefaultUnitForMeasure(t,e),measure:t}}return{}}getDefaultUnit(t){var r,o;const e=this.regionInfo.defaultUnitSystem,s=t==null?void 0:t.measure;return s?((r=t==null?void 0:t.to)==null?void 0:r.unit)||this.getDefaultUnitForMeasure(s,((o=t==null?void 0:t.to)==null?void 0:o.system)||e):this.getConverterFromFormat().unit}getFormatterOptions(t){var n,i,a;const e=this.regionInfo.defaultUnitSystem,s=t==null?void 0:t.measure,r=new Intl.NumberFormat().resolvedOptions().locale;let o=null;if(s||this.formatter){const c=s?{style:"unit",unit:this.getDefaultUnit(t)}:null,d=this.formatter||c;if(d){let u=typeof d=="function"?d(((n=t==null?void 0:t.to)==null?void 0:n.system)||e):d;s&&(u={unit:this.getDefaultUnit(t),...u},u.style==="unit"&&(u.maximumFractionDigits=u.maximumFractionDigits??this.getDefaultUnitDecimalPlaces(s,((i=t==null?void 0:t.to)==null?void 0:i.system)||e,(a=t==null?void 0:t.to)==null?void 0:a.unit)));try{o=new Intl.NumberFormat(r,{...u})}catch(h){Ze.error(`error creating formatter ${u}. Returning the raw value`,h)}}else Ze.debug(`no formatter found for config bean prop ${this.id}. Returning the raw value`)}return o}getConverter(){var r,o,n,i,a,c,d,u,h,g,m;const{unit:t,measure:e}=this.getConverterFromFormat();if(this.schemaFormat==="drt")return;const s=t==="drt"?"second":t;if(this.converter){const y=(r=this.converter)==null?void 0:r.measure,v=(n=(o=this.converter)==null?void 0:o.to)==null?void 0:n.measure,E=(a=(i=this.converter)==null?void 0:i.from)==null?void 0:a.measure,_=y||v||E||e,N=((d=(c=this.converter)==null?void 0:c.to)==null?void 0:d.unit)||this.regionInfo.getDefaultUnitForMeasure(_,((h=(u=this.converter)==null?void 0:u.to)==null?void 0:h.system)??this.regionInfo.defaultUnitSystem),x=((m=(g=this.converter)==null?void 0:g.to)==null?void 0:m.system)??this.regionInfo.getUnitSystem(N),D=this.schemaFormat==="drt"?"second":this.schemaFormat||s;return{...this.converter,from:{unit:D,...this.converter.from},to:{...this.converter.to,unit:N,system:x},measure:_}}if(s&&e){const y=this.regionInfo.getDefaultUnitForMeasure(e,this.regionInfo.defaultUnitSystem),v=this.regionInfo.getUnitSystem(s),E=this.regionInfo.getUnitSystem(y);return{measure:e,to:{unit:v===E?s:y}}}}async updateProperty(t){Ze.debug(`updating property ${this.attribute} with value ${t}`);let e=t;if(this.getConverter()&&!isNaN(e)){const{backend:o,display:n}=this.getConverterUnits();e=this.regionInfo.convert(Number(e),n,o)}const r=Array.isArray(e)?JSON.stringify(e):String(e);await this.bean.updateProperty(this.attribute,r)}};zo([yt({modelType:ee.type})],Qt.prototype,"regionInfo",2);zo([mr({path:Pg,serviceBasePath:Lg})],Qt.prototype,"bean",2);Qt=zo([R(Rs)],Qt);const Ve={registration:{[Rs]:{class:Qt,singleton:!1}},type:Rs,factory:te.Factory.create(Rs)};function kg(t){const{path:e,attribute:s,converter:r,formatter:o,lazy:n,optionsExpander:i,serviceBasePath:a}=t,c=r;return c&&(typeof c!="function"&&typeof c.from=="string"&&(c.from={unit:c.from}),typeof c!="function"&&typeof c.to=="string"&&(c.to={unit:c.to})),(d,u)=>{d[F]=d[F]||{},d[F][u]={modelType:Ve.type,id:`${e}-${s}`,options:{path:e,attribute:s,serviceBasePath:a,converter:c,formatter:o,optionsExpander:i},lifecycle:H.INIT,lazy:n}}}class Fg{constructor(e,s){l(this,"futures");l(this,"defaultContext");l(this,"context");l(this,"disposers",new Map);l(this,"container");this.futures=Fo.map(new Map),this.context="",this.defaultContext=s||"",this.container=e,M.makeAutoObservable(this)}get allFutures(){return Array.from(this.futures.values())}get future(){return this.futures.get(this.defaultContext)}addFuture(e,s){this.futures.set(s||e.id,e),this.context=s||e.id;const r=G(()=>{var o,n;(e.endState||e.progress)&&((n=(o=this.container)==null?void 0:o.onFutureUpdate)==null||n.call(o,e))});this.disposers.set(s||e.id,r)}removeFuture(e){var s;this.futures.delete(e||this.context),(s=this.disposers.get(e||this.context))==null||s(),this.disposers.delete(e||this.context)}getFuture(e){return this.futures.get(e||this.context)}get futureMap(){return this.futures}}class yr{constructor(e){l(this,"disposer");l(this,"_future");l(this,"container");l(this,"onFutureUpdate");this._future=void 0,this.container=e,M.makeAutoObservable(this)}removeFuture(){var e;this._future=void 0,(e=this.disposer)==null||e.call(this),this.disposer=void 0}get future(){return this._future}getFuture(){return this._future}addFuture(e){this._future=e;const s=G(()=>{var r,o;(e.endState||e.progress)&&((o=(r=this.container)==null?void 0:r.onFutureUpdate)==null||o.call(r,e))});this.disposer=s}get allFutures(){return this._future?[this._future]:[]}get timeRemaining(){var e;return((e=this._future)==null?void 0:e.timeRemaining)||""}get status(){var e;return((e=this._future)==null?void 0:e.status)||"NOT_RESOLVED"}get progress(){var e;return((e=this._future)==null?void 0:e.progress)||-1}async cancel(){if(this._future)try{await this._future.cancelFuture()}catch(e){throw p.error(e),e}}}const Ic="future-model",vt=bt(Ic),br=p.createLogger({name:"future-service",group:"Services"}),{isMock:Ng,URL:cs}=oe();var xe=(t=>(t.Success="SUCCESS",t.Fail="FAIL",t.Aborted="ABORT",t.Canceled="CANCEL",t))(xe||{});const{getAll:Ug,modifyModel:jg,addModel:Bg,deleteModel:Kg,postModel:Hg}=se.build({destinationAddress:"",basePath:`${cs}/api/future`,mock:Ng}),zg=async()=>await Ug({}),Sc=async(t,e="/api/kos/future")=>(br.info(`sending delete request for Future: ${t}`),await Kg({id:t,urlOverride:`${cs}${e}/${t}`})),Oc=async(t,e="/api/kos/future")=>(br.info("sending add request for Future"),await Bg({model:t,urlOverride:`${cs}${e}`})),Gg=async(t,e,s="/api/kos/future")=>(br.info(`sending modify request for Future: ${t}`),jg({model:e,id:t,urlOverride:`${cs}${s}/${t}`})),$c=async(t,e="/api/kos/future")=>(br.info(`sending cancel request for Future: ${t}`),Hg({urlOverride:`${cs}${e}/${t}/cancel`,ordered:!0,model:{}})),Go=t=>({id:String(t.id),progress:t.progress,remainingTimeMs:t.remainingTimeMs,endState:t.endState,reason:t.reason,clientData:t.clientData,reasonData:t.reasonData,note:t.note,tracker:t.tracker}),Vo=(t,e)=>{p.debug(`future dto ${t.id} end state ${t.endState}`),p.debug(`future model ${e.id} end state ${e.endState}`),e.endState?p.debug(`future model ${e.id} is already complete`):(p.debug(`updating future model ${e.id}`),M.runInAction(()=>{const s=Go(t);X(()=>{Object.keys(s).forEach(r=>{r==="id"?(e.futureId=s.id,s.tracker||(e.id=s.id)):r==="tracker"?e.id=s.tracker:e[r]=s[r]})})}))},Dc=t=>e=>s=>t.build(String(e),s),Yo=t=>e=>rc(Go,Dc(t)(e.tracker||e.id))(e);var Vg=Object.defineProperty,Yg=Object.getOwnPropertyDescriptor,Cc=(t,e,s,r)=>{for(var o=r>1?void 0:r?Yg(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Vg(e,s,o),o};const kr=p.getLogger(vt.type);let js=class{constructor(t,e,s){l(this,"logger");l(this,"_cancelFuture");l(this,"futureId");Object.assign(this,e),this.logger=s.logger,this.id=t,this.futureId=e.id,this.namespace=e.namespace||"kos",this._cancelFuture=$c,Qr(()=>this.status===xe.Success||this.status===xe.Fail,()=>{kr.info(`Future ${this.id} has completed with status ${this.status}`),He(this)})}async load(){kr.debug(`loading Future ${this.id}`)}unload(){kr.info(`unloading Future ${this.id}`)}async cancelFuture(){const t=this.namespace==="studio"?"/api/future":`/api/${this.namespace}/future`;await Qr(()=>this.futureId!==No),await this._cancelFuture(this.futureId,t)}get status(){return this.endState?this.endState:this.progress>-1?"IN_PROGRESS":"NOT_ACTIVE"}get timeRemaining(){var a,c;const t=this.remainingTimeMs||-1;if(t<0)return"";const e={year:1e3*60*60*24*365,month:1e3*60*60*24*30,day:1e3*60*60*24,hour:1e3*60*60,minute:1e3*60,second:1e3};let s="second",r=0;for(const[d,u]of Object.entries(e))if(Math.abs(t)>=u){s=d,r=Math.round(t/u);break}const n=new Intl.RelativeTimeFormat("en",{numeric:"auto"}).formatToParts(r,s);return n.length===3?`${((a=n[1])==null?void 0:a.value)??0} ${((c=n[2])==null?void 0:c.value)??""}`:"0 seconds"}handleFutureUpdated(t){this.logger.debug(`Future ${this.id} updated. future: ${t.id} endState: ${t.endState} progress: ${t.progress} remainingTimeMs: ${t.remainingTimeMs}`),Vo(t,this)}};Cc([U({topic:`kos.future/${xs}`})],js.prototype,"handleFutureUpdated",1);js=Cc([R(vt.type)],js);const Rc=js,Ac=Ao();var qg=Object.defineProperty,Wg=Object.getOwnPropertyDescriptor,xc=(t,e,s,r)=>{for(var o=r>1?void 0:r?Wg(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&qg(e,s,o),o};const Pc="browser-router-model",Qg="kos.http.request",Zg="kos.http.response";let Bs=class{constructor(t,e,s){l(this,"_id");l(this,"logger");l(this,"router");this._id=t,this.logger=s.logger,this.router=new ac}get id(){return this._id}async handleRequest(t,e){const s=e.headers["src-addr"],r=e.headers["dst-addr"],o=e.headers.url,n=e.headers.method,i=e.headers["request-id"],a={id:i,method:n,path:o,body:t};let c=200;const d={send:u=>{this.logger.debug(`sending response to ${r}`),this.logger.debug(u),Ua({msg:u,options:{responseId:i,destinationAddress:s,type:Zg,sourceAddress:r,status:c}})},status:function(u){return c=u,this}};if(a.path==="/openapi.json"){d.send(this.router.generateOpenApiSpec());return}await this.router.handle(a,d)}use(t,e,...s){this.router.use(t,e,...s)}remove(t,e){return this.router.remove(t,e)}removeAllForPath(t){return this.router.removeAllForPath(t)}getRoutes(){return this.router.getRoutes()}async init(){this.logger.debug(`initializing browser-router ${this.id}`)}async load(){this.logger.debug(`loading browser-router ${this.id}`)}};xc([U({topic:Qg})],Bs.prototype,"handleRequest",1);Bs=xc([R(Pc)],Bs);const qo=new Ee({class:Bs,type:Pc}),Lc="future-container-model",Pe=bt(Lc),kc=t=>Yo(vt)(t),Xg=t=>{const e=kc(t);return Pe.build(Pe.type,{}).addFutureModel(e),e},Jg=t=>Pe.build(Pe.type,{}).getFuture(String(t)),ze={buildFutureModel:kc,initiateFuture:Xg,getFuture:Jg};var ep=Object.defineProperty,tp=Object.getOwnPropertyDescriptor,Wo=(t,e,s,r)=>{for(var o=r>1?void 0:r?tp(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&ep(e,s,o),o};const Ms=p.getLogger(Pe.type);let Zt=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_deleteFuture");l(this,"_addFuture");l(this,"_futures");l(this,"createModel");l(this,"deleteModel");const{deleteFuture:r=Sc,addFuture:o=Oc}=e;this.logger=s.logger,this._deleteFuture=r,this._addFuture=o,this.id=t,this._futures=new Te,this.createModel=this.createFuture,this.deleteModel=this.removeFuture}get futures(){return this._futures.data}get models(){return this.futures}getFuture(t){return this._futures.getModel(t)}addFutureModel(t){this._futures.addModel(t)}removeFutureModel(t){this._futures.removeModel(t)}async removeFuture(t){try{await this._deleteFuture(t)}catch(e){Ms.error("error deleting a Future"),Ms.error(e)}}async createFuture(t){try{const e=await this._addFuture(t),s=e==null?void 0:e.data;if(s){const r=Yo(vt)(s);return this.addFutureModel(r),r}}catch(e){throw Ms.error("error creating a Future"),Ms.error(e),e}}handleFutureUpdated(t,e){const s=ze.buildFutureModel(t);this.addFutureModel(s);const r=`kos.future/${t.tracker||t.id}`;this.logger.debug(`publishing future update to ${r}`),j(r,e.body,e.headers)}};Wo([be],Zt.prototype,"_futures",2);Wo([U({topic:"kos.future"})],Zt.prototype,"handleFutureUpdated",1);Zt=Wo([R(Pe.type)],Zt);const Fc=Zt,{URL:ls}=oe(),{getOne:sp,postModel:rp,deleteModel:Nc}=se.build({basePath:`${ls}/api/keyVal`}),Zr=p.createLogger({name:"key-value-service",group:"Services"}),Uc=async(t,e)=>{await Nc({urlOverride:`${ls}/api/keyVal/${t}/${e}`,id:e})},jc=async(t,e,s)=>{const r=await rp({urlOverride:`${ls}/api/keyVal/${t}/${e}`,model:s.toString()});if((r==null?void 0:r.status)!==200)throw Zr.error("Failed to update studio-state data",r),new Error(`Failed to update studio-state data for namespace ${t}`);return r.data},Bc=async(t="studio")=>{Zr.debug("sending GET for studio-state");const e=await sp({urlOverride:`${ls}/api/keyVal/${t}`});if((e==null?void 0:e.status)!==200)throw Zr.error("Failed to retrieve studio-state data",e),new Error(`Failed to retrieve studio-state data for namespace ${t}`);return e.data},op=async t=>{await Nc({urlOverride:`${ls}/api/keyVal/${t}}`,id:""})},np=Object.freeze(Object.defineProperty({__proto__:null,deleteKeyValue:Uc,deleteKeyValueNamespace:op,getKeyValue:Bc,updateKeyValue:jc},Symbol.toStringTag,{value:"Module"}));var ip=Object.defineProperty,ap=Object.getOwnPropertyDescriptor,Qo=(t,e,s,r)=>{for(var o=r>1?void 0:r?ap(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&ip(e,s,o),o};const Kc="key-value-model";let Xt=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"namespace");l(this,"data");this.id=t,this.logger=s.logger,this.data=Ae(),this.namespace=e.namespace||"studio"}async init(){this.logger.debug(`initializing studio-state ${this.id}`)}async updateState(t,e){this.logger.debug(`updating studio-state ${t} with value ${e}`),e!==void 0?(await jc(this.namespace,t,e),this.data[t]=e):(await Uc(this.namespace,t),this.data[t]=void 0)}async load(){this.logger.debug(`loading studio-state ${this.id}`);const t=await Bc(this.namespace);this.data.setValues(t)}handleStateUpdate(t){t.namespace===this.namespace&&(this.data[t.key]=t.value)}handleStateDelete(t){t.namespace===this.namespace&&(this.data[t.key]=void 0)}};Qo([U({topic:"/keyVal/set"})],Xt.prototype,"handleStateUpdate",1);Qo([U({topic:"/keyVal/remove"})],Xt.prototype,"handleStateDelete",1);Xt=Qo([R(Kc)],Xt);const Zo=new we({class:Xt,type:Kc}),De=Ao(),cp=Object.freeze(Object.defineProperty({__proto__:null,default:De},Symbol.toStringTag,{value:"Module"})),lp=p.createLogger({name:"kos-log-manager-service",group:"Services"}),dp="/api/kos/logs/overrides",Hc=async()=>(lp.debug("sending GET for kos-log-manager"),await De.get(dp)),up=Object.freeze(Object.defineProperty({__proto__:null,getLogOverrides:Hc},Symbol.toStringTag,{value:"Module"}));var hp=Object.defineProperty,fp=Object.getOwnPropertyDescriptor,wr=(t,e,s,r)=>{for(var o=r>1?void 0:r?fp(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&hp(e,s,o),o};const zc="kos-log-manager-model",gp="/kos/logs/override/add/*",pp="/kos/logs/override/remove/*",mp=t=>{if(typeof t=="string")return t;if(typeof t=="number")switch(t){case 0:return"trace";case 1:return"debug";case 2:return"info";case 3:return"warn";case 4:return"error";default:return"info"}return"info"};let it=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_overrides");this.id=t,this.logger=s.logger,this._overrides=new Lo}updateModel(t){}resolveLoggers(){const t=p.getLoggers(),s=Object.entries(t).map(([r,o])=>({name:r,level:mp(o.getLevel())})).reduce((r,{name:o,level:n})=>(r[o]={name:o,level:n},r),{});return this.logger.debug("Resolved loggers",s),s}async getAllLoggers(t,e){const s=Object.values(this.resolveLoggers());return e==null||e.send(s),s}setLogLevels(t){Object.values(this.resolveLoggers()).filter(r=>r.name.startsWith(t.name)).forEach(r=>{const o=p.getLoggers()[r.name];if(!o){this.logger.debug(`Logger ${r.name} not found`);return}o.setLevel(t.level)});const s=p.getLoggers()[t.name];if(!s){this.logger.debug(`Logger ${t.name} not found`);return}s.setLevel(t.level),globalThis.kos.logOverrides=this._overrides.data}resetLogLevels(t){Object.values(this.resolveLoggers()).filter(r=>r.name.startsWith(t.name)).forEach(r=>{const o=p.getLoggers()[r.name];o||this.logger.debug(`Logger ${r.name} not found`),o==null||o.resetLevel()});const s=p.getLoggers()[t.name];s||this.logger.debug(`Logger ${t.name} not found`),s==null||s.resetLevel(),globalThis.kos.logOverrides=this._overrides.data}handleOverrideAdded(t,e){var s;this.logger.debug(`Override received for node type ${((s=e.wildcardCapture)==null?void 0:s.nodeType)??"unknown"}`),this._overrides.addModel({...t,id:t.name}),this.setLogLevels(t)}handleOverrideRemoved(t){this._overrides.removeModel(t.name),this.resetLogLevels(t)}async init(){this.logger.debug(`initializing kos-log-manager ${this.id}`)}async load(){this.logger.debug(`loading kos-log-manager ${this.id}`),this.resolveLoggers();const[t,e]=await Hc();if(t){this.logger.error("Failed to load log overrides",t);return}const s=(e==null?void 0:e.filter(r=>{var o;return((o=r.type)==null?void 0:o.toUpperCase())==="UI"}).map(r=>({name:r.name??"",type:r.type??"",level:r.level??"info",id:r.name||""})))??[];this._overrides.addAll(s),s.forEach(r=>{this.setLogLevels(r)})}};wr([ia("/api/kos/ui/loggers")],it.prototype,"getAllLoggers",1);wr([U({topic:gp,websocket:!0,wildcardName:"nodeType"})],it.prototype,"handleOverrideAdded",1);wr([U({topic:pp,websocket:!0,wildcardName:"nodeType"})],it.prototype,"handleOverrideRemoved",1);it=wr([R(zc)],it);const Gc=new Ee({class:it,type:zc}),{URL:ds}=oe(),{postModel:Xo,getOne:yp}=se.build({basePath:`${ds}/api/kos-time`});p.createLogger({name:"kos-time-service",group:"Services"});const Vc=async t=>{const e=await Xo({model:t,urlOverride:`${ds}/api/kos/time/time`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set time");return e.data},Yc=async t=>{const e=await Xo({model:t,urlOverride:`${ds}/api/kos/time/date`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set time");return e.data},qc=async t=>{const e=await Xo({model:{},urlOverride:`${ds}/api/kos/time/timezone?tz=${t}`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set timezone");return e.data},Wc=async()=>{const t=await yp({urlOverride:`${ds}/api/kos/time/timezone`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set timezone");return t.data.timeZone},bp=Object.freeze(Object.defineProperty({__proto__:null,getTimezone:Wc,setDate:Yc,setTime:Vc,setTimezone:qc},Symbol.toStringTag,{value:"Module"}));var wp=Object.defineProperty,vp=Object.getOwnPropertyDescriptor,vr=(t,e,s,r)=>{for(var o=r>1?void 0:r?vp(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&wp(e,s,o),o};const Ot="kos-time-model",Mp="/kos/time/time",Ep="/kos/time/day",Tp="/kos/time/timezone";let at=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"timezone");this.id=t,this.logger=s.logger,this.timezone=""}async updateSystemTime(t){await Vc(t)}async updateSystemDate(t){await Yc(t)}async updateSystemTimezone(t){await qc(t)}handleTimeChange(){j(zt.TIME_CHANGE,{})}handleDayChange(){j(zt.DAY_CHANGE,{})}async handleTimeZoneChange(){await this.retrieveTimezone(),j(zt.TIMEZONE_CHANGE,{})}async init(){this.logger.debug(`initializing kos-time ${this.id}`)}async retrieveTimezone(){const t=await Wc();this.setTimezone(t)}setTimezone(t){this.timezone=t}async load(){this.logger.debug(`loading kos-time ${this.id}`),this.retrieveTimezone()}};vr([U({topic:Mp,websocket:!0})],at.prototype,"handleTimeChange",1);vr([U({topic:Ep,websocket:!0})],at.prototype,"handleDayChange",1);vr([U({topic:Tp,websocket:!0})],at.prototype,"handleTimeZoneChange",1);at=vr([R(Ot)],at);const Ks={registration:{[Ot]:{class:at,singleton:!0}},type:Ot,predicate:he(Ot),factory:te.Singleton.create(Ot)};var _p=Object.defineProperty,Ip=Object.getOwnPropertyDescriptor,Qc=(t,e,s,r)=>{for(var o=r>1?void 0:r?Ip(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&_p(e,s,o),o};const Zc="log-block-container-model";let Hs=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new Te({parentId:t,sortKey:"blockNum"})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug(`initializing log-block-container container ${this.id}`)}async load(){this.logger.debug(`loading log-block-container container ${this.id}`)}};Qc([be],Hs.prototype,"_models",2);Hs=Qc([R(Zc)],Hs);const Sp=p.createLogger({name:"log-stream-container-service",group:"Services"}),Xc=()=>{var r;const t=ue(),s=(t==null?void 0:t.connId)||((r=window==null?void 0:window.kosBridge)==null?void 0:r.call(window,"connId"));return p.error(`getKosConnectionId: ${s}`),s},Mt=Xc(),Op="/api/kos/logs/node/{nodeId}/streams",Jc=async()=>(Sp.debug("sending GET for log-stream-container"),await De.get(Op,{path:{nodeId:"primary"}},{destinationAddress:Mt})),el=async(t,e="primary")=>{await De.post("/api/kos/logs/node/{nodeId}/{stream}/subscribe",{path:{nodeId:e,stream:t}},void 0,{destinationAddress:Mt})},tl=async t=>{await De.post("/api/kos/logs/node/{nodeId}/{stream}/unsubscribe",{path:{nodeId:"primary",stream:t}},void 0,{destinationAddress:Mt})},$p=async()=>{await De.post("/api/kos/logs/overrides",{},{level:"WARN",name:"com.example",nodeType:"java",type:"package"},{destinationAddress:Mt})},sl=async t=>await De.get("/api/kos/logs/node/{nodeId}/{stream}/blocks",{path:{nodeId:"primary",stream:t}},{destinationAddress:Mt}),rl=async(t,e)=>await De.get("/api/kos/logs/node/{nodeId}/{stream}/blocks/{blockId}",{path:{nodeId:"primary",stream:t,blockId:e}},{destinationAddress:Mt}),Dp=Object.freeze(Object.defineProperty({__proto__:null,createOverride:$p,getKosConnectionId:Xc,getLogStreamBlock:rl,getLogStreamBlocks:sl,getLogStreams:Jc,subscribeToLogStream:el,unsubscribeFromLogStream:tl},Symbol.toStringTag,{value:"Module"}));var Cp=Object.getOwnPropertyDescriptor,Rp=(t,e,s,r)=>{for(var o=r>1?void 0:r?Cp(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const ol="log-block-model";let Xr=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"nodeId");l(this,"stream");l(this,"blockNum");l(this,"startLineNum");l(this,"endLineNum");l(this,"startTime");l(this,"endTime");l(this,"lineCount");l(this,"lines");l(this,"inc");this.id=t,this.logger=s.logger,this.nodeId=e.nodeId,this.stream=e.stream,this.blockNum=e.blockNum,this.startLineNum=e.startLineNum,this.endLineNum=e.endLineNum,this.startTime=e.startTime,this.endTime=e.endTime,this.lineCount=e.lineCount,this.lines=[],this.inc=0}async syncLines(){const[t,e]=await rl(this.stream,this.blockNum);if(t){this.logger.error(`Failed to get log block ${this.blockNum}`);return}e&&this.addLines(e.lines,!0)}updateModel(t){this.startLineNum=t.startLineNum,this.endLineNum=t.endLineNum,this.startTime=t.startTime,this.endTime=t.endTime,this.lineCount=t.lineCount}addLines(t,e){const s=e?[]:this.lines;this.lines=[...s,...t],this.inc+=1}async init(){this.logger.debug(`initializing log-block ${this.id}`)}async load(){this.logger.debug(`loading log-block ${this.id}`)}};Xr=Rp([R(ol)],Xr);const Jt=new we({class:Xr,type:ol}),Mr=new we({class:Hs,type:Zc});Mr.addRelatedModel(Jt);var Ap=Object.defineProperty,xp=Object.getOwnPropertyDescriptor,nl=(t,e,s,r)=>{for(var o=r>1?void 0:r?xp(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Ap(e,s,o),o};const il="log-stream-model";let zs=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"nodeId");l(this,"_blocks");l(this,"name");l(this,"currentBlockId");l(this,"isResetting");l(this,"generatorInstance");l(this,"shouldStop",!1);this.id=t,this.logger=s.logger,this.currentBlockId="",this.name=e.name,this.nodeId=e.nodeId,this.isResetting=!0,this._blocks=Mr.instance(`${t}-blocks`).options({}).build()}get firstLineNum(){const t=this.populated[0];return t?t.startLineNum:0}get currentBlock(){const t=this.currentBlockId;return this._blocks.getModel(t)}get populated(){return this._blocks.data.filter(t=>t.lines.length>0)}get blocks(){return this._blocks.data}get totalLineCount(){return this.populated.reduce((t,e)=>t+e.lineCount,0)}accept(t){t.visit(this)}updateBlock(t){var r;let e=this._blocks.models.getModel(`${t.stream}-block-${t.blockNum}`);const s={nodeId:t.nodeId,blockNum:t.blockNum,endLineNum:t.endLineNum,lineCount:t.lineCount,startLineNum:t.startLineNum,stream:this.name,endTime:new Date(t.endTime),startTime:new Date(t.startTime)};e||(e=Jt.instance(`${t.stream}-block-${t.blockNum}`).options(s).build(),this._blocks.addModel(e)),e&&e.updateModel(s),(!this.currentBlock||t.blockNum>=((r=this.currentBlock)==null?void 0:r.blockNum))&&(this.currentBlockId=`${t.stream}-block-${t.blockNum}`)}addBlock(t){var s;const e=Jt.instance(`${t.stream}-block-${t.blockNum}`).options({nodeId:t.nodeId,blockNum:t.blockNum,endLineNum:t.endLineNum,lineCount:t.lineCount,startLineNum:t.startLineNum,stream:this.name,endTime:new Date(t.endTime),startTime:new Date(t.startTime)}).build();this._blocks.addModel(e),(!this.currentBlock||t.blockNum>=((s=this.currentBlock)==null?void 0:s.blockNum))&&(this.currentBlockId=`${t.stream}-block-${t.blockNum}`)}removeBlock(t){this._blocks.models.removeModel(`${this.name}-block-${t}`)}async subscribe(){await el(this.name)}async unsubscribe(){await tl(this.name)}async reset(){if(this.isResetting=!0,this.populated.length>0)return;this.logger.debug(`resetting log-stream ${this.id}`);for(const e of this._blocks.models.data)e.lines=[];const t=this._blocks.data[this._blocks.data.length-1];t&&await t.syncLines(),this.isResetting=!1}async init(){this.logger.debug(`initializing log-stream ${this.id}`)}async load(){this.logger.debug(`loading log-stream ${this.id}`);const[t,e]=await sl(this.name);if(t){this.logger.error(`Error loading log stream: ${t}`);return}if(e)for(const r of e)this.addBlock(r);const s=this._blocks.data[this._blocks.data.length-1];if(s&&await s.syncLines(),this._blocks.data.length>1){const r=this._blocks.data[this._blocks.data.length-2];r&&await r.syncLines()}}start(){return this.shouldStop=!1,this.generatorInstance=this.streamLogs(),this.generatorInstance}stop(){var t;this.shouldStop=!0,(t=this.generatorInstance)==null||t.next(),console.log("Requested generator stop.")}async*streamLogs(){const t=[];let e=null,s=0,r=this.currentBlockId;const o=dc(()=>{const n=this.currentBlock;return n?{blockId:this.currentBlockId,lineCount:n.lines.length}:null},n=>{const i=this.currentBlock;if(i)if(r!==(n==null?void 0:n.blockId))r=n==null?void 0:n.blockId,s=0,t.push(...i.lines);else{const a=i.lines.slice(s);t.push(...a),s+=a.length}e&&(e(),e=null)},{fireImmediately:!0});try{for(const n of this.populated.filter(i=>i!==this.currentBlock))for(const i of n.lines)yield i;for(;;)for(t.length===0&&await new Promise(n=>e=n);t.length>0;)yield t.shift()}finally{o()}}};nl([be],zs.prototype,"_blocks",2);zs=nl([R(il)],zs);const Gt=new we({class:zs,type:il});var Pp=Object.defineProperty,Lp=Object.getOwnPropertyDescriptor,Ye=(t,e,s,r)=>{for(var o=r>1?void 0:r?Lp(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Pp(e,s,o),o};const al="log-stream-container-model",kp="/kos/logs/subscription/addBlock/*",Fp="/kos/logs/subscription/updateBlock/*",Np="/kos/logs/subscription/removeBlock/*",Up="/kos/logs/subscription/lines/*",cl="/kos/logs/streams/add/*";let Se=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"selectedStream");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new Te({parentId:t}),this.selectedStream=void 0}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}updateModel(t){}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}updateSelectedStream(t){this.selectedStream=t}handleStreamAdded(t){this.logger.debug(`Received topic: ${cl}`);const e=t.stream,s=Gt.instance(e).options({name:e,nodeId:"primary"}).build();this.addModel(s)}handleAddBlock(t,e){this.logger.debug(`Received topic: ${e.headers.topic}`);const s=t.stream,r=this.models.getModel(s);r&&r.addBlock(t)}handleRemoveBlock(t,e){this.logger.debug(`Received topic: ${e.headers.topic}`);const s=t.stream,r=this.models.getModel(s);r&&r.removeBlock(t.blockNum)}handleUpdateBlock(t,e){this.logger.debug(`Received topic: ${e.headers.topic}`);const s=t.stream,r=this.models.getModel(s);r&&r.updateBlock(t)}handleLogLine(t,e){var o;this.logger.debug(`Received topic: ${e.headers.topic}`);const s=t.stream,r=this.models.getModel(s);r&&((o=r.currentBlock)==null||o.addLines(t.lines))}async init(){this.logger.debug(`initializing log-stream-container container ${this.id}`)}async subscribeToLogStream(t){const e=Gt.instance(t).options({name:t,nodeId:"primary"}).build();this.addModel(e),await e.subscribe()}async load(){this.logger.debug(`loading log-stream-container container ${this.id}`);const[t,e]=await Jc();if(t){this.logger.error(`Error loading log-streams: ${t}`);return}e&&e.forEach(s=>{const r=Gt.instance(s).options({name:s,nodeId:"primary"}).build();this.addModel(r)})}};Ye([be],Se.prototype,"_models",2);Ye([U({topic:[cl],websocket:!0})],Se.prototype,"handleStreamAdded",1);Ye([U({topic:[kp],websocket:!0})],Se.prototype,"handleAddBlock",1);Ye([U({topic:[Np],websocket:!0})],Se.prototype,"handleRemoveBlock",1);Ye([U({topic:[Fp],websocket:!0})],Se.prototype,"handleUpdateBlock",1);Ye([U({topic:[Up],websocket:!0})],Se.prototype,"handleLogLine",1);Se=Ye([R(al)],Se);const us=new Ee({class:Se,type:al});us.addRelatedModel(Gt);us.addRelatedModel(Mr);us.addRelatedModel(Jt);const jp=t=>t.rank!==void 0,Bp=t=>t.visibleRole!==void 0,Kp=t=>t.color!==void 0,Hp=t=>{const e=t.info;return jp(e)?e.rank:0},zp=t=>{const e=t.info;return Kp(e)?e.color:"orange"},Gp=t=>{const e=t.info;return Bp(e)?e.visibleRole:"TECHNICIAN"},{URL:Jo}=oe(),{getAll:Vp,postModel:ll}=se.build({basePath:`${Jo}/api/kos/troubles`}),Jr=async()=>await Vp({}),dl=async(t,e)=>{try{const s=await ll({model:{},urlOverride:`${Jo}/api/kos/troubles/resolve/${t}`,tracker:e});return s!=null&&s.data&&ze.initiateFuture(s.data),s.data}catch{const r={id:e||"",endState:xe.Fail,tracker:e,reason:"Failed to resolve trouble"};return ze.initiateFuture(r),r}},Yp=async(t,e)=>{try{const s=await ll({model:t,urlOverride:`${Jo}/api/kos/troubles/resolve/`,tracker:e});return s!=null&&s.data&&ze.initiateFuture(s.data),s.data}catch{const r={id:e||"",endState:xe.Fail,tracker:e,reason:"Failed to resolve troubles"};return ze.initiateFuture(r),r}},qp=Object.freeze(Object.defineProperty({__proto__:null,bulkResolveTroubles:Yp,getTroubles:Jr,resolveTrouble:dl},Symbol.toStringTag,{value:"Module"})),Gs="troubleDataMapper",Es=new Map;is(Gs,{register:(t,e)=>{var s;Es.has(t)||Es.set(t,[]),(s=Es.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=Es.get(t);if(!s)return{...e.data};const r=s.map(i=>i(e));return(await Promise.allSettled(r)).reduce((i,a)=>(a.status==="fulfilled"?i={...i,...a.value}:p.info(`Trouble mapper ${t} failed: ${a.reason}`),i),{...e.data})}});const hs="troubleMapper",Ts=new Map;is(hs,{register:(t,e)=>{var s;Ts.has(t)||Ts.set(t,[]),(s=Ts.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=Ts.get(t);if(!s)return[];const r=s.map(i=>i(e)),n=(await Promise.allSettled(r)).map(i=>i.status==="fulfilled"?i.value:(p.info(`Trouble mapper ${t} failed: ${i.reason}`),[])).flat();return Array.from(new Set(n))}});S[hs].register("nozzle",async t=>[t.data.nozzlePath]);S[hs].register("path",async t=>[t.data.path]);const Wp=async t=>{const e=new Set,s=t.ifaces,r=s==null?void 0:s.map(n=>S[hs].execute(n,t));return(await Promise.allSettled(r)).forEach(n=>{n.status==="fulfilled"&&n.value.forEach(i=>e.add(i))}),Array.from(e)},ul=async t=>{const e=t.ifaces,s=e==null?void 0:e.map(i=>S[Gs].execute(i,t)),r=S[Gs].execute(t.type,t);s.push(r);const n=(await Promise.allSettled(s)).reduce((i,a)=>(a.status==="fulfilled"&&(i={...i,...a.value}),i),{});return{...t.data,...n}};class Qp{constructor(){l(this,"type","ResolvableTrouble");l(this,"title","Resolvable Trouble");l(this,"subtitle","Trouble")}}class Zp{constructor(){l(this,"type","BlockPumpTrouble");l(this,"title","Block Pump Trouble");l(this,"subtitle","Trouble")}}class Xe{static getHandler(e){switch(e){case"ResolvableTrouble":return new Qp;case"BlockPumpTrouble":return new Zp;default:return}}}var Xp=Object.defineProperty,Jp=Object.getOwnPropertyDescriptor,hl=(t,e,s,r)=>{for(var o=r>1?void 0:r?Jp(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Xp(e,s,o),o};const $t="trouble-model";function _s(t){return typeof t.shouldDefer=="boolean"}let Vs=class{constructor(t,{resolvable:e,tags:s,info:r,id:o,clientData:n,rank:i,ifaces:a,type:c,group:d,createTime:u,role:h,color:g,...m},y){l(this,"id");l(this,"logger");l(this,"_troubleId");l(this,"_resolvable");l(this,"type");l(this,"futureHandler");l(this,"ifaces");l(this,"clientData");l(this,"info");l(this,"role");l(this,"color");l(this,"tags");l(this,"data");l(this,"rank");l(this,"group");l(this,"createTime");l(this,"_mapped",{});this.id=t,this.logger=y.logger,this.type=c,this._troubleId=o,this._resolvable=!!e,this.ifaces=a,this.rank=i,this.role=h,this.color=g,this.tags=s,this.info=r,this.group=d,this.createTime=u,this.clientData=n,this.data={},Object.assign(this.data,m),this.futureHandler=new yr(this)}getTitleWithContext(t){var s,r;const e=t?(r=(s=Xe.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[t]:Xe.getHandler(this.type);return(e==null?void 0:e.title)||"Trouble"}getSubtitleWithContext(t){var s,r;const e=t?(r=(s=Xe.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[t]:Xe.getHandler(this.type);return(e==null?void 0:e.subtitle)||"Trouble"}get rawId(){return this._troubleId}get title(){var t;return((t=Xe.getHandler(this.type))==null?void 0:t.title)||"Trouble"}get subtitle(){var t;return((t=Xe.getHandler(this.type))==null?void 0:t.subtitle)||"Trouble"}get troubleId(){return this._troubleId}get resolvable(){return this._resolvable}get future(){return this.futureHandler.future}async resolveMappedData(){return await ul(this)}get deferredCompanion(){const t=qr(this.id,e=>_s(e));if(t&&_s(t.modelData))return t.modelData}get deferred(){return this.deferredCompanion?this.deferredCompanion.deferred:!1}get shouldDefer(){const t=qr(this.id,e=>_s(e));return t&&_s(t.modelData)?t.modelData.shouldDefer:!1}clearDefer(){var t;(t=this.deferredCompanion)==null||t.clearDefer()}defer(){var t;(t=this.deferredCompanion)==null||t.defer()}getChildren(){return[...this.futureHandler.allFutures]}async resolve(t){var e;if(!this._resolvable)throw this.logger.error(`attempting to resolve an unresolvable trouble with id ${this._troubleId}`),new Error("Trouble is not resolvable");if(this.shouldDefer){(e=this.deferredCompanion)==null||e.defer();return}return await dl(this._troubleId,t)}};hl([yn()],Vs.prototype,"resolve",1);Vs=hl([R($t)],Vs);const ct={registration:{[$t]:{class:Vs,singleton:!1}},type:$t,predicate:he($t),factory:te.Factory.create($t)};var em=Object.defineProperty,tm=Object.getOwnPropertyDescriptor,Er=(t,e,s,r)=>{for(var o=r>1?void 0:r?tm(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&em(e,s,o),o};const Fr=p.createLogger({name:"trouble-container-model"}),sm=t=>{const e={...t,rank:eo(t),color:to(t),role:so(t),id:String(t.id)};return ct.factory(`trouble-${t.id}`)(e)};function eo(t){return S.propertyMapper.hasMapper(me.TroubleRank)?S.propertyMapper.executeMapper(me.TroubleRank,t):Hp(t)}function to(t){return(S.propertyMapper.hasMapper(me.TroubleColor)?S.propertyMapper.executeMapper(me.TroubleColor,t):zp(t)).toLowerCase()}function so(t){return(S.propertyMapper.hasMapper(me.TroubleRole)?S.propertyMapper.executeMapper(me.TroubleRole,t):Gp(t)).toLowerCase()}const rm="trouble-container-model";class de{}l(de,"INDEX_TROUBLES_BY_IFACE","byIface"),l(de,"INDEX_TROUBLES_BY_TYPE","byType"),l(de,"INDEX_TROUBLES_BY_GROUP","byGroup"),l(de,"INDEX_TROUBLES_BY_DEFERRED","byDeferred"),l(de,"SORT_KEY_RANK","rank"),l(de,"TROUBLES_DEFERRED","true");let lt=class{constructor(t){l(this,"id");l(this,"troubles");this.id=t,this.troubles=new Te({indexMap:{[de.INDEX_TROUBLES_BY_IFACE]:Wp,[de.INDEX_TROUBLES_BY_TYPE]:"type",[de.INDEX_TROUBLES_BY_GROUP]:"group",[de.INDEX_TROUBLES_BY_DEFERRED]:"deferred"},sortKey:de.SORT_KEY_RANK,parentId:t})}async reload(){Fr.info("reloading trouble container");const t=await Jr(),e=(t==null?void 0:t.data)??[],s=new Set(e.map(n=>`trouble-${n.id}`)),r=this.troubles.data.map(n=>n.id).filter(n=>!s.has(n)),o=e.filter(n=>!this.troubles.getModel(`trouble-${n.id}`)).map(sm);this.troubles.removeAll(r),this.troubles.addAll(o)}async load(){Fr.debug("loading trouble container");const t=await Jr();try{t==null||t.data.forEach(e=>{const s={...e,rank:eo(e),color:to(e),role:so(e),id:String(e.id)},r=ct.factory(`trouble-${e.id}`)(s);this.troubles.addModel(r)})}catch(e){throw Fr.error(e),e}}handleTroubleRemoved(t){const e=`trouble-${t}`,s=this.troubles.getModel(e);this.troubles.removeModel(e),s&&He(s)}handleTroubleAdded(t){const e={...t,rank:eo(t),color:to(t),role:so(t),id:String(t.id)};if(e.role==="NONE")return;const s=ct.factory(`trouble-${t.id}`)(e);this.troubles.addModel(s)}};Er([be],lt.prototype,"troubles",2);Er([U({topic:"/kos/trouble/remove",websocket:!0,lifecycle:H.INIT})],lt.prototype,"handleTroubleRemoved",1);Er([U({topic:"/kos/trouble/add",websocket:!0})],lt.prototype,"handleTroubleAdded",1);lt=Er([R(rm)],lt);const Is="trouble-container-model",dt={registration:{[Is]:{class:lt,singleton:!0}},type:Is,predicate:he(Is),factory:te.Singleton.create(Is)},{URL:fl}=oe(),{getAll:om}=se.build({basePath:`${fl}/api/kos/ota`}),Yn=p.createLogger({name:"ota-service",group:"Services"}),nm=async()=>{Yn.debug("sending GET request to /api/kos/ota/artifacts");const t=await om({urlOverride:`${fl}/api/kos/ota/artifacts`});return Yn.debug("getArtifacts - response:",t),t==null?void 0:t.data};var im=Object.defineProperty,am=Object.getOwnPropertyDescriptor,Tr=(t,e,s,r)=>{for(var o=r>1?void 0:r?am(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&im(e,s,o),o};const gl="ota-model",cm=t=>{let e=null;for(const s in t){const r=t[s],o=r.lastUpdateTime;(!e||e.lastUpdateTime<o)&&(e=r)}return e},Nr=t=>{const e=t.artifactInfo,s=cm(t.requests),r=(e==null?void 0:e.identifier)||(s==null?void 0:s.kabId);if(!r)return;let o;switch(t.status){case"INSTALLED":o="ready";break;case"INVALID":o="error";break;case"MISSING":o=((s==null?void 0:s.currentSize)||0)>0?"downloading":"idle";break;case"STAGED":o="pending"}const n=e===void 0;return{id:r,manifest:n,label:e==null?void 0:e.version,name:e==null?void 0:e.name,status:o,error:o==="error"?s==null?void 0:s.lastErrorReason:void 0,errorCount:o==="error"?s==null?void 0:s.errorCount:0,progress:o==="downloading"&&s&&!n?s.currentSize/(e==null?void 0:e.size)*100:void 0,size:e==null?void 0:e.size}};let ut=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"data",new Lo);l(this,"troubleContainer");this.id=t,this.logger=s.logger}get downloadInProgressTrouble(){var e;return(e=this.troubleContainer.troubles.getIndexByKey("byType","OTADownloadInProgressTrouble"))==null?void 0:e[0]}get updatePendingTrouble(){var e;return(e=this.troubleContainer.troubles.getIndexByKey("byType","OTAUpdatePendingTrouble"))==null?void 0:e[0]}get pausedDueToErrorsTrouble(){var e;return(e=this.troubleContainer.troubles.getIndexByKey("byType","OTAPausedDueToErrorsTrouble"))==null?void 0:e[0]}get updates(){return this.data}get status(){return this.pausedDueToErrorsTrouble?"error":this.downloadInProgressTrouble?"downloading":this.updatePendingTrouble?"pending":"idle"}installAndReboot(){var t;this.updatePendingTrouble||this.logger.error("installAndReboot - OTAUpdatePendingTrouble not present"),this.logger.debug("installAndReboot - resolve OTAUpdatePendingTrouble"),(t=this.updatePendingTrouble)==null||t.resolve()}async init(){this.logger.debug(`initializing ota ${this.id}`)}async load(){this.logger.debug(`loading ota ${this.id}`);try{const t=await nm();t&&t.forEach(e=>{const s=Nr(e);s&&this.data.addModel(s)})}catch(t){this.logger.error(`loading ota ${this.id} - error:`,t)}}async handleAllArtifacts(t){this.logger.debug("handleAllArtifacts:",t),await this.data.clear();try{t.forEach(e=>{const s=Nr(e);s&&this.data.addModel(s)})}catch(e){this.logger.error(`handleAllArtifacts ${this.id} - error:`,e)}}handleChangedArtifacts(t){this.logger.debug("handleChangedArtifacts:",t);try{t.forEach(e=>{const s=Nr(e);s&&this.data.updateModel(s)})}catch(e){this.logger.error(`handleChangedArtifacts ${this.id} - error:`,e)}}};Tr([yt({modelType:dt.type})],ut.prototype,"troubleContainer",2);Tr([U({topic:"/kos/ota/artifacts/all",websocket:!0})],ut.prototype,"handleAllArtifacts",1);Tr([U({topic:"/kos/ota/artifacts/changed",websocket:!0})],ut.prototype,"handleChangedArtifacts",1);ut=Tr([R(gl)],ut);const Ys=new Ee({class:ut,type:gl});function lm(t){let e;const s=async(...r)=>{e&&e.abort(),e=new AbortController;const o=e;try{return await t(...r,o.signal)}finally{e===o&&(e=void 0)}};return s.cancel=()=>{e&&(e.abort(),e=void 0)},s.getController=()=>e,s.isActive=()=>!!e,s}const Ur=p.createLogger({name:"software-info-service",group:"Services"}),en=async t=>{Ur.debug("sending GET for software-info");const[e,s]=await Ac.get("/api/kos/manifest/info",void 0,{signal:t});if(!s)throw t!=null&&t.aborted?(Ur.debug("Request was aborted"),new B("Request was aborted")):(Ur.error("Failed to fetch software-info",e),new B("Failed to fetch software-info"));return s},dm=lm(en),um=Object.freeze(Object.defineProperty({__proto__:null,getSoftwareInfos:en,getSoftwareInfosWithCancel:dm},Symbol.toStringTag,{value:"Module"}));var hm=Object.getOwnPropertyDescriptor,fm=(t,e,s,r)=>{for(var o=r>1?void 0:r?hm(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const Dt="software-info-model";let ro=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"nodes");this.id=t,this.logger=s.logger,this.nodes=[]}async init(){this.logger.debug(`initializing software-info ${this.id}`)}groupBy(t,e){return t.reduce((s,r)=>(s[r[e]]=[...s[r[e]]||[],r],s),{})}async load(){this.logger.debug(`loading software-info ${this.id}`);try{const t=await en(),e=(t==null?void 0:t.nodes)||{};X(()=>{const r=Object.keys(e).map(o=>e[o][0]).map(o=>({nodeName:o.nodeType,kosVersion:o.kosVersion,group:this.groupBy(o.artifacts,"group")}));this.nodes=r})}catch(t){t instanceof B&&this.logger.error("Failed to fetch software-info",t)}}};ro=fm([R(Dt)],ro);const qs={registration:{[Dt]:{class:ro,singleton:!1}},type:Dt,predicate:he(Dt),factory:te.Factory.create(Dt)},{URL:pl}=oe(),{getOne:gm}=se.build({basePath:`${pl}/api/kos/state`}),pm=p.createLogger({name:"state-bean-service",group:"Services"}),ml=async({path:t})=>(pm.debug("sending GET for state-bean"),await gm({urlOverride:`${pl}/api/kos/state/${t}`})),mm=Object.freeze(Object.defineProperty({__proto__:null,getStateBeanData:ml},Symbol.toStringTag,{value:"Module"}));var ym=Object.defineProperty,bm=Object.getOwnPropertyDescriptor,yl=(t,e,s,r)=>{for(var o=r>1?void 0:r?bm(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&ym(e,s,o),o};const Ct="state-bean-model",wm=Ge("path");let Ws=class{constructor(t,e,s){l(this,"id");l(this,"path");l(this,"props");l(this,"logger");this.id=t,this.logger=s.logger,this.props=Fo.map(new Map),Gr(e,this)}updateModel(t){Gr(t,this)}handleConfigBeanUpdated(t){Object.entries(t).forEach(([e,s])=>{let r=s;typeof r=="string"&&jo(r)&&(r=r.toLowerCase()=="true"),typeof r=="string"&&pr(r)&&(r=Number(r)),this.props.set(e,r)})}async init(){this.logger.debug(`initializing state-bean ${this.id}`)}updateProps(t){Object.entries(t).forEach(([e,s])=>{this.props.set(e,s)})}async load(){this.logger.debug(`loading state-bean ${this.id}`);const t=await ml({path:this.path});t!=null&&t.data&&this.updateProps(t.data)}};yl([U({topic:`/kos/state/${wm}`,websocket:!0})],Ws.prototype,"handleConfigBeanUpdated",1);Ws=yl([R(Ct)],Ws);const es={registration:{[Ct]:{class:Ws,singleton:!1}},type:Ct,predicate:he(Ct),factory:te.Factory.create(Ct)};var vm=Object.defineProperty,Mm=Object.getOwnPropertyDescriptor,bl=(t,e,s,r)=>{for(var o=r>1?void 0:r?Mm(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&vm(e,s,o),o};const Rt="state-prop-model",qn=Ge("path");let Qs=class{constructor(t,e,s){l(this,"id");l(this,"path");l(this,"attribute");l(this,"logger");l(this,"stateBean");this.id=t,this.logger=s.logger,this.path=e.path,this.attribute=e.attribute}get value(){return this.stateBean.props.get(this.attribute)}async init(){this.logger.debug(`initializing state-prop ${this.id}`)}async load(){this.logger.debug(`loading state-prop ${this.id}`)}toString(){var t;return((t=this.value)==null?void 0:t.toString())??""}};bl([yt({modelType:es.type,id:`state-bean-${qn}`,options:{path:qn}})],Qs.prototype,"stateBean",2);Qs=bl([R(Rt)],Qs);const tn={registration:{[Rt]:{class:Qs,singleton:!1}},type:Rt,predicate:he(Rt),factory:te.Factory.create(Rt)},{URL:Em}=oe(),{getAll:Tm}=se.build({basePath:`${Em}/api/state-prop`}),_m=p.createLogger({name:"state-prop-service",group:"Services"}),Im=async()=>(_m.debug("sending GET for state-prop"),await Tm({})),Sm=Object.freeze(Object.defineProperty({__proto__:null,getStateProps:Im},Symbol.toStringTag,{value:"Module"})),{URL:sn}=oe(),{getOne:wl}=se.build({basePath:`${sn}/api/translation`}),Vt=p.createLogger({name:"translation-service",group:"Services"}),Om=()=>{const t=window.location.origin,e=ue();return(e==null?void 0:e.host)||t},vl=async(t,e)=>{Vt.debug("sending GET for translation");const s=e??Om();try{const r=await fetch(`${s}${t}`);return r.status!==200?(Vt.warn(`Failed to fetch translations at ${t}: ${r.status}`),{}):await r.json()}catch(r){throw Vt.error("Error fetching translations",r),r}},$m=async()=>{Vt.debug("getting localization descriptor");const t=await wl({urlOverride:`${sn}/api/system/kos/localization`});if((t==null?void 0:t.status)!==200)throw new Error(`Failed to get tool localization descriptor ${t==null?void 0:t.status}`);return t.data},Ml=t=>async()=>{Vt.debug("getting kos localization descriptor");const e=await wl({urlOverride:`${sn}/api/kos/localization/contexts`});if((e==null?void 0:e.status)!==200)throw new Error(`Failed to get tool localization descriptor ${e==null?void 0:e.status}`);return e.data[t]},El="langResolver";var Dm=Object.getOwnPropertyDescriptor,Cm=(t,e,s,r)=>{for(var o=r>1?void 0:r?Dm(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const At="translation-model";function Rm(t){const e=typeof t=="string",s=e?!1:!!(t!=null&&t.data)&&typeof(t==null?void 0:t.data)!="string",r=e?t:t==null?void 0:t.defaultValue,o=e||t==null?void 0:t.context,n=e?void 0:s?t==null?void 0:t.data:t;return{isBasicOptions:e,defaultValue:r,context:o,data:n}}function Tl(t,e=""){return Object.keys(t).reduce((s,r)=>{const o=e?`${e}.${r}`:r;if(typeof t[r]=="object"&&t[r]!==null){const n=Tl(t[r],o);return{...s,...n}}else return{...s,[o]:t[r]}},{})}function _l(t,e){const s={...t};for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(typeof e[r]=="object"&&e[r]!==null&&typeof t[r]=="object"&&t[r]!==null?s[r]=_l(t[r],e[r]):s[r]=e[r]);return s}const oo=(t,e)=>{const s=/__(.*?)__/g,r=t.replace(s,(o,n)=>Object.prototype.hasOwnProperty.call(e||{},n.trim())?e==null?void 0:e[n.trim()]:o);return r===t?r:s.test(r)?oo(r,e):r},Ss=(t,e,s)=>{const r=/{{(.*?)}}/g,n=oo(t,e).replace(r,(a,c)=>Object.prototype.hasOwnProperty.call(s||{},c.trim())?s==null?void 0:s[c.trim()]:a);return oo(n,e)},Wn=(t,e)=>{if(e.includes(":")){const[s,r]=e.split(":");return{namespace:s,key:r}}else return{namespace:t,key:e}};let no=class{constructor(t,e,s){l(this,"id");l(this,"namespace");l(this,"descriptor");l(this,"defaultLocale");l(this,"currentLocale");l(this,"bundleResolver");l(this,"data");l(this,"logger");l(this,"resolver");l(this,"disposer");l(this,"context");l(this,"rootUrl");this.id=t,this.defaultLocale=e.defaultLocale||"en",this.currentLocale=e.currentLocale||"en",this.namespace=e.namespace,this.descriptor=e.descriptor,this.rootUrl=e.rootUrl,this.data={},this.resolver=e.resolver||s.kosContext.get(El),this.bundleResolver=e.bundleResolver,this.logger=s.logger,this.context=s.kosContext.parentModel}getTranslationLocales(t){const e=this.descriptor[t];if(!t||!e)return[this.defaultLocale];if(!this.defaultLocale&&!e.fallbacks)return[t];let s=e.fallbacks||[this.defaultLocale];return s.includes(t)||(s=[t,...s]),s}async loadTranslations(){const t=this.getTranslationLocales(this.currentLocale).reverse(),e=t.map(r=>{if(this.bundleResolver){const o=z.getContext(this.id);return this.bundleResolver(this.namespace,r,o)}try{const o=this.resolver(this.namespace,r);return vl(o,this.rootUrl)}catch{return Promise.resolve({})}}),s=await Promise.allSettled(e);X(()=>{const r=s.reduce((o,n,i)=>(n.status==="fulfilled"?(this.logger.debug(`resolved ${t[i]}`,n.value),n.value&&(o=_l(o,n.value))):this.logger.error(`failed to load translation ${this.id} for ${t[i]}`),o),{});this.data=Tl(r)})}async init(){this.logger.debug(`initializing translation ${this.id}`)}exists(t){const{namespace:e,key:s}=Wn(this.namespace,t);if(e!==this.namespace){const r=this.context.getModel(e);return r?r.exists(s):!1}return!!this.data[s]}resolveKey(t,e){if(!t)return this.logger.debug("key is empty"),"";const{defaultValue:s,context:r,data:o}=Rm(e),{namespace:n,key:i}=Wn(this.namespace,t),a=`${i}_${r}`;if(n!==this.namespace){const c=this.context.getModel(n);return c?c.resolveKey(i,e):i}if(r&&this.data[a]){const c=this.data[a];return Array.isArray(c)?c.map(d=>Ss(d,this.data,o)):Ss(this.data[a],this.data,o)}if(this.data[i]){const c=this.data[a];return Array.isArray(c)?c.map(d=>Ss(d,this.data,o)):Ss(this.data[i],this.data,o)}return s??i}unload(){this.logger.debug(`unloading translation ${this.id}`),this.disposer&&this.disposer()}async load(){this.logger.debug(`loading translation ${this.id}`),await this.loadTranslations()}async ready(){this.logger.debug(`ready translation ${this.id}`),this.disposer=M.reaction(()=>this.currentLocale,(t,e)=>{this.logger.info(`translation langs for namespace ${this.id} changed from ${e} to ${t}`),this.loadTranslations()})}};no=Cm([fr(),R(At)],no);const Zs={registration:{[At]:{class:no,singleton:!1}},type:At,predicate:he(At),factory:te.Factory.create(At)};var Am=Object.defineProperty,xm=Object.getOwnPropertyDescriptor,Il=(t,e,s,r)=>{for(var o=r>1?void 0:r?xm(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Am(e,s,o),o};const xt="translation-container-model",Pm=(t,e="/")=>t.join(e).replace(new RegExp(e+"{1,}","g"),e);function Lm(t,e){const s=this.descriptor.namespaces[t];if(!s)throw new Error(`namespace ${t} not found in descriptor`);const r=s.basePath,o=s.locales[e].file;return Pm([r,o])}let Xs=class{constructor(t,e,s){l(this,"id");l(this,"lang");l(this,"rootUrl");l(this,"descriptor");l(this,"_defaultNamespace");l(this,"resolver");l(this,"logger");l(this,"descriptorUrl");l(this,"namespaces",[]);l(this,"_models");this.id=t,this.lang=e.lang||"en",this.descriptor=e.descriptor,this._defaultNamespace=e.defaultNamespace,this.descriptorUrl=e.descriptorUrl,this.rootUrl=e.rootUrl,this.resolver=e.resolver||Lm.bind(this),s.kosContext.set(El,this.resolver),this.logger=s.logger,this._models=new Te({parentId:t})}set currentLocale(t){this.lang=t,this.models.data.forEach(e=>{e.currentLocale=t})}get defaultNamespace(){return this._defaultNamespace?this.getModel(`translation-${this._defaultNamespace}`):void 0}getModel(t){return this.logger.debug(`getting model ${t}`),this._models.getModel(`translation-${t}`)}get models(){return this._models}get data(){return this._models.data}async reload(){for(const t of this.namespaces){const e=this.resolveNamespace(t);await ae(e)}}resolveNamespace(t){var s;if((s=this.descriptor.namespaces)==null?void 0:s[t]){const r=Object.keys(this.descriptor.namespaces[t].locales)[0],o=this.descriptor.namespaces[t].locales[r].defaultLocale,n=Zs.factory(`translation-${t}`)({kosParentId:this.id,namespace:t,rootUrl:this.rootUrl,currentLocale:this.lang,defaultLocale:o,descriptor:this.descriptor.namespaces[t].locales,resolver:this.resolver});return this.addModel(n),this.namespaces.includes(t)||X(()=>{this.namespaces.push(t)}),n}else{this.logger.warn(`namespace ${t} not found in descriptor`);const r=Zs.factory(`translation-${t}`)({kosParentId:this.id,namespace:t,rootUrl:this.rootUrl,currentLocale:this.lang,defaultLocale:this.lang,descriptor:{},resolver:this.resolver});return this.addModel(r),r}}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug(`initializing translation-container container ${this.id}`)}async load(){this.logger.debug(`loading translation-container container ${this.id}`)}};Il([be],Xs.prototype,"_models",2);Xs=Il([R(xt)],Xs);const Oe={registration:{[xt]:{class:Xs,singleton:!0}},type:xt,predicate:he(xt),factory:te.Singleton.create(xt)},km={set(t,e){const s=z.getContext(Oe.type);s&&s.set(t,e)},get(t){const e=z.getContext(Oe.type);return e==null?void 0:e.get(t)}},Sl={async init(t){const e=Oe.factory(t);return await ae(e),{translations:e}}};function Fm(t){return t.troubles!==void 0&&t.troubles instanceof Array&&t.troublesByType!==void 0&&typeof t.troublesByType=="object"}const Nm=(t,e)=>{const s=e.type;return t[s]||(t[s]=[]),t[s].push(e),t},Ol="kos-ws-event",rn=bt(Ol);var Um=Object.defineProperty,jm=Object.getOwnPropertyDescriptor,on=(t,e,s,r)=>{for(var o=r>1?void 0:r?jm(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Um(e,s,o),o};const Bm=({headers:t,body:e})=>Object.entries(t).map(([r,o])=>`${r}:${o}`).join("\\n")+"\\n\\n"+e;exports.WsEventModel=class{constructor(e){l(this,"id");l(this,"events");l(this,"_topicMap");this.id=e,this.events=M.observable.map(new Map),this._topicMap=new Map}get websocketEvents(){return Array.from(this.events.values())}handleSendEvent(e,s){this.processEvent(s,!0)}handleReceiveEvent(e,s){this.processEvent(s)}processEvent(e,s=!1){p.debug("kos event received");const{body:r,headers:o}=e.body,n=o["request-id"]||o["response-id"],i=o["request-id"]||o["response-id"]||o.topic||o.type;if(i){let a=i;if(n)a=`${a}-${s?"send":"receive"}`;else{const d=this._topicMap.get(i)||0;a=`${a}-${d+1}`,this._topicMap.set(i,d+1)}const c={msgId:a,content:r,headers:o,timestamp:Date.now(),raw:Bm({headers:o,body:r}),direction:s?"send":"receive",mocked:!!o.mocked};this.events.set(a,c),p.debug(`logged ${this.events.size} events`)}}};on([U({topic:[ns.SEND]})],exports.WsEventModel.prototype,"handleSendEvent",1);on([U({topic:[ns.RECEIVED]})],exports.WsEventModel.prototype,"handleReceiveEvent",1);exports.WsEventModel=on([R(rn.type)],exports.WsEventModel);const Qn=ue(),Km=Qn.debug==="true"||Qn.debug===!0,Hm="/api/system/canvas",$l=async(t,e)=>{const s=e||Hm,r=`${exports.BASE_URL}${s}`;await exports.kosFetch(r,{method:"POST",headers:{hide:Km?"false":"true"},body:t})},zm=Object.freeze(Object.defineProperty({__proto__:null,sendCanvasData:$l},Symbol.toStringTag,{value:"Module"}));function Zn(t,e,s){{const r=t.filter((o,n)=>n%4!==3);return btoa(String.fromCharCode(...r))}}var Gm=Object.defineProperty,Vm=Object.getOwnPropertyDescriptor,Dl=(t,e,s,r)=>{for(var o=r>1?void 0:r?Vm(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Gm(e,s,o),o};const Cl="canvas-renderer-model";function jr(t){return typeof t.onDone=="function"}let Js=class{constructor(t,e,s){l(this,"id");l(this,"router");l(this,"logger");l(this,"_renderer",null);l(this,"_clearOnComplete");l(this,"isStreaming",!1);l(this,"renderLoopId",null);l(this,"sendIntervalId",null);l(this,"timeoutId",null);l(this,"apiPath");l(this,"endpointName");l(this,"width",50);l(this,"height",30);l(this,"fps",10);l(this,"durationMs",null);l(this,"_onFrame",null);this.id=t,this.logger=s.logger,this.width=e.width??50,this.height=e.height??30,this.fps=e.fps??10,this.durationMs=e.durationMs??null,this.apiPath=e.apiPath??"/api/system/canvas",this.endpointName=e.endpoint}set onFrame(t){this._onFrame=t}set renderer(t){var e,s;this._renderer&&(this.stopStreaming(),(s=(e=this._renderer).dispose)==null||s.call(e)),this._renderer=t,this.isStreaming&&this.startStreaming()}setClearOnComplete(t){this._clearOnComplete=t}sendDataFrame(t,e){$l(t,e)}checkStreaming(){if(this.isOneShotDone()||!this.isStreaming){requestAnimationFrame(()=>{const t=this.isOneShotDone();this.stopStreaming(!t)});return}}handleFrame(t){var s;const e=Zn(t);this.sendDataFrame(e,this.apiPath),(s=this._onFrame)==null||s.call(this,e)}stopStreaming(t=!0){var e,s;this.logger.debug(`stopStreaming called with clearCanvas=${t}`),this.isStreaming=!1,this.renderLoopId&&cancelAnimationFrame(this.renderLoopId),this.sendIntervalId&&clearInterval(this.sendIntervalId),this.timeoutId&&clearTimeout(this.timeoutId),(s=(e=this._renderer)==null?void 0:e.pause)==null||s.call(e),t&&(this.logger.debug("Clearing canvas..."),this.clearCanvas())}clearCanvas(){var s;const t=this.width>0?this.width:50,e=this.height>0?this.height:30;if(t>0&&e>0){const r=t*e*4,o=new Uint8ClampedArray(r);for(let i=3;i<r;i+=4)o[i]=255;const n=Zn(o);this.logger.debug(`Sending clear frame: ${t}x${e}, apiPath: ${this.apiPath}`),this.sendDataFrame(n,this.apiPath),(s=this._onFrame)==null||s.call(this,n)}}isOneShotDone(){var t,e;return jr(this._renderer)&&((e=(t=this._renderer).isOneShot)==null?void 0:e.call(t))===!0&&this._renderer.isOneShotDone}startStreaming(){var t,e,s,r;{if(!this._renderer)return;if(!this.apiPath){this.logger.error(`No endpoint configured for canvas renderer ${this.id}`);return}this.isStreaming=!0,this._renderer.reset(),(e=(t=this._renderer).play)==null||e.call(t);const o=jr(this._renderer);jr(this._renderer)&&this._renderer.onDone(()=>{var c,d,u;this.logger.debug(`Renderer completed for ${this.id}`),j("/canvas/renderer/completed",{endpoint:this.endpointName,rendererId:this.id,rendererType:(c=this._renderer)==null?void 0:c.constructor.name,timestamp:Date.now()});let a=!0;this._clearOnComplete!==void 0?a=this._clearOnComplete:a=!(((u=(d=this._renderer)==null?void 0:d.isOneShot)==null?void 0:u.call(d))??!1),this.stopStreaming(a)}),this._renderer.renderFrame(this.width,this.height);const n=(r=(s=this._renderer).readPixels)==null?void 0:r.call(s,this.width,this.height);if(n&&this._onFrame&&this.handleFrame(n),this.isOneShotDone()){requestAnimationFrame(()=>{this.stopStreaming(!1)});return}const i=()=>{var a;(a=this._renderer)==null||a.renderFrame(this.width,this.height),this.renderLoopId=requestAnimationFrame(i)};this.renderLoopId=requestAnimationFrame(i),this.sendIntervalId=setInterval(()=>{var c,d;const a=(d=(c=this._renderer)==null?void 0:c.readPixels)==null?void 0:d.call(c,this.width,this.height);a&&this._onFrame&&(this.handleFrame(a),this.checkStreaming())},1e3/this.fps),!o&&this.durationMs!=null&&(this.timeoutId=setTimeout(()=>{this.stopStreaming()},this.durationMs))}}async init(){this.logger.debug(`initializing canvas-renderer ${this.id}`)}async load(){this.logger.debug(`loading canvas-renderer ${this.id}`),this.router.use("POST",`/api/ui/canvas/${this.endpointName}/stop`,async(t,e)=>{this.logger.debug(`HTTP stop endpoint called for ${this.endpointName}`),this.stopStreaming(),e.send({status:"OK"})}),this.router.use("POST",`/api/ui/canvas/${this.endpointName}/start`,async(t,e)=>{this.startStreaming(),e.send({status:"OK"})})}};Dl([yt({modelType:qo.type})],Js.prototype,"router",2);Js=Dl([R(Cl)],Js);const nn=new we({class:Js,type:Cl});class Rl{constructor({src:e}){l(this,"video");l(this,"canvas");l(this,"ctx");l(this,"lastUpdate",0);l(this,"doneCallback",null);this.video=document.createElement("video"),this.video.src=e,this.video.crossOrigin="anonymous",this.video.muted=!0,this.video.loop=!1,this.canvas=document.createElement("canvas");const s=this.canvas.getContext("2d");if(!s)throw new Error("2D canvas not supported");this.ctx=s,this.handleEnded=this.handleEnded.bind(this),this.video.addEventListener("ended",this.handleEnded)}handleEnded(){this.doneCallback&&this.doneCallback()}reset(){this.video.pause(),this.video.currentTime=0,this.lastUpdate=performance.now()}play(){this.video.play().catch(console.warn)}pause(){this.video.pause()}renderFrame(e,s){this.canvas.width=e,this.canvas.height=s,this.video.readyState>=2&&this.ctx.drawImage(this.video,0,0,e,s)}readPixels(e,s){return this.ctx.getImageData(0,0,e,s).data}onDone(e){this.doneCallback=e}dispose(){this.video.pause(),this.video.removeAttribute("src"),this.video.load(),this.video.remove(),this.video.removeEventListener("ended",this.handleEnded),this.doneCallback=null}shouldStep(e){const s=performance.now();return s-this.lastUpdate>=e?(this.lastUpdate=s,!0):!1}}class Ym{constructor(){l(this,"canvas");l(this,"gl");l(this,"lastWidth",0);l(this,"lastHeight",0);l(this,"lastUpdate",0);this.canvas=document.createElement("canvas");const e=this.canvas.getContext("webgl");if(!e)throw new Error("WebGL not supported");this.gl=e}shouldStep(e){const s=performance.now();return s-this.lastUpdate>=e?(this.lastUpdate=s,!0):!1}readPixels(e=this.lastWidth,s=this.lastHeight){const r=new Uint8Array(e*s*4);this.gl.readPixels(0,0,e,s,this.gl.RGBA,this.gl.UNSIGNED_BYTE,r);const o=new Uint8ClampedArray(r.length);for(let n=0;n<s;n++){const i=n*e*4,a=(s-1-n)*e*4;o.set(r.subarray(i,i+e*4),a)}return o}}class qm extends Ym{constructor({speedPx:s=1}={}){super();l(this,"program");l(this,"posBuffer");l(this,"aPosition");l(this,"uMinHue");l(this,"uMaxHue");l(this,"uHueOffset");l(this,"uGridHeight");l(this,"minHue",0);l(this,"maxHue",80);l(this,"hueOffset",0);l(this,"speedPx",1);this.speedPx=s;const r=this.gl,o=`
78
78
  attribute vec2 a_position;
79
79
  void main() {
80
80
  gl_Position = vec4(a_position, 0, 1);
@@ -108,8 +108,8 @@ ${d}topics:${e}
108
108
  vec3 rgb = hslToRgb(hue, 1.0, 0.5);
109
109
  gl_FragColor = vec4(rgb, 1.0);
110
110
  }
111
- `,i=this.compileShader(r.VERTEX_SHADER,o),a=this.compileShader(r.FRAGMENT_SHADER,n);this.program=this.createProgram(i,a),this.posBuffer=r.createBuffer(),r.bindBuffer(r.ARRAY_BUFFER,this.posBuffer),r.bufferData(r.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),r.STATIC_DRAW),this.aPosition=r.getAttribLocation(this.program,"a_position"),this.uMinHue=r.getUniformLocation(this.program,"minHue"),this.uMaxHue=r.getUniformLocation(this.program,"maxHue"),this.uHueOffset=r.getUniformLocation(this.program,"hueOffset"),this.uGridHeight=r.getUniformLocation(this.program,"gridHeight")}reset(){this.hueOffset=0,this.lastUpdate=performance.now()}renderFrame(s,r){const o=this.gl;if(this.canvas.width=s,this.canvas.height=r,this.shouldStep(50)){const n=this.speedPx/r;this.hueOffset=(this.hueOffset+n)%1}o.viewport(0,0,s,r),o.clear(o.COLOR_BUFFER_BIT),o.useProgram(this.program),o.enableVertexAttribArray(this.aPosition),o.bindBuffer(o.ARRAY_BUFFER,this.posBuffer),o.vertexAttribPointer(this.aPosition,2,o.FLOAT,!1,0,0),o.uniform1f(this.uMinHue,this.minHue/360),o.uniform1f(this.uMaxHue,this.maxHue/360),o.uniform1f(this.uHueOffset,this.hueOffset),o.uniform1f(this.uGridHeight,r),o.drawArrays(o.TRIANGLES,0,6)}compileShader(s,r){const o=this.gl.createShader(s);if(this.gl.shaderSource(o,r),this.gl.compileShader(o),!this.gl.getShaderParameter(o,this.gl.COMPILE_STATUS))throw new Error(this.gl.getShaderInfoLog(o)||"Shader compile failed");return o}createProgram(s,r){const o=this.gl.createProgram();if(this.gl.attachShader(o,s),this.gl.attachShader(o,r),this.gl.linkProgram(o),!this.gl.getProgramParameter(o,this.gl.LINK_STATUS))throw new Error("Program linking failed");return o}}class qe{constructor(){l(this,"canvas");l(this,"ctx");l(this,"lastUpdate",0);this.canvas=document.createElement("canvas");const e=this.canvas.getContext("2d");if(!e)throw new Error("2D canvas not supported");this.ctx=e}dispose(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.remove()}shouldStep(e){const s=performance.now();return s-this.lastUpdate>=e?(this.lastUpdate=s,!0):!1}readPixels(e,s){return this.ctx.getImageData(0,0,e,s).data}}function tn(t){class e extends t{constructor(){super(...arguments);l(this,"doneCallback",null);l(this,"oneShotDone",!1)}isOneShot(){return!0}onDone(o){this.doneCallback=o}signalDoneIfNeeded(){var o;this.oneShotDone||((o=this.doneCallback)==null||o.call(this),this.oneShotDone=!0)}resetOneShot(){this.doneCallback=null,this.oneShotDone=!1}get isOneShotDone(){return this.oneShotDone}}return e}const qm=tn(qe);class Wm extends qm{constructor({colors:s=["red","yellow","green"],direction:r="horizontal",speed:o=2,loop:n=!0}={}){super();l(this,"offset",0);l(this,"speed");l(this,"colors");l(this,"direction");l(this,"loop");this.colors=s,this.direction=r,this.speed=o,this.loop=n}reset(){this.offset=0,this.lastUpdate=performance.now(),this.loop||this.resetOneShot()}renderFrame(s,r){if(!this.loop&&this.isOneShotDone)return;this.loop&&this.shouldStep(50)&&(this.offset+=this.speed);const o=this.loop?-this.offset:0,n=this.loop?s*2-this.offset:s,i=this.ctx.createLinearGradient(o,0,n,0),a=1/(this.colors.length-1);this.colors.forEach((c,d)=>{i.addColorStop(d*a,c)}),this.ctx.fillStyle=i,this.ctx.fillRect(0,0,s,r),!this.loop&&!this.isOneShotDone&&this.signalDoneIfNeeded()}}const Qm=tn(qe);class Al extends Qm{constructor({src:s}){super();l(this,"img");l(this,"loaded",!1);this.img=new Image,this.img.src=s,this.img.crossOrigin="anonymous",this.img.onload=()=>{this.loaded=!0}}reset(){this.resetOneShot()}renderFrame(s,r){!this.loaded||this.isOneShotDone||(this.canvas.width=s,this.canvas.height=r,this.ctx.drawImage(this.img,0,0,s,r),this.signalDoneIfNeeded())}}class Zm extends Rl{constructor(s){super(s);l(this,"loopConfig");l(this,"currentLoopCount",0);l(this,"startTime");l(this,"endTime");l(this,"completionCallback",null);this.loopConfig=s.loop??!1,this.startTime=s.startTime??0,this.endTime=s.endTime??null,this.video.removeEventListener("ended",this.handleEnded),this.video.addEventListener("ended",this.handleVideoEnd.bind(this)),this.startTime>0&&(this.video.currentTime=this.startTime),this.endTime!==null&&this.video.addEventListener("timeupdate",this.handleTimeUpdate.bind(this))}handleTimeUpdate(){this.endTime!==null&&this.video.currentTime>=this.endTime&&this.handleVideoEnd()}handleVideoEnd(){this.loopConfig===!0?(this.video.currentTime=this.startTime,this.video.play().catch(console.warn)):typeof this.loopConfig=="number"&&this.currentLoopCount<this.loopConfig-1?(this.currentLoopCount++,this.video.currentTime=this.startTime,this.video.play().catch(console.warn)):(this.video.pause(),this.completionCallback&&this.completionCallback())}reset(){super.reset(),this.currentLoopCount=0,this.video.currentTime=this.startTime}onDone(s){this.completionCallback=s}isOneShot(){return this.loopConfig===!1||this.loopConfig===1}dispose(){this.video.removeEventListener("ended",this.handleVideoEnd),this.video.removeEventListener("timeupdate",this.handleTimeUpdate),this.completionCallback=null,super.dispose()}}function Xm(t){const e=t.replace("#","");if(!/^[0-9A-Fa-f]{3}$|^[0-9A-Fa-f]{6}$/.test(e))throw new Error(`Invalid hex color: ${t}`);let s,r,o;return e.length===3?(s=parseInt(e[0]+e[0],16),r=parseInt(e[1]+e[1],16),o=parseInt(e[2]+e[2],16)):(s=parseInt(e.substring(0,2),16),r=parseInt(e.substring(2,4),16),o=parseInt(e.substring(4,6),16)),{r:s,g:r,b:o}}function xl(t){return typeof t=="string"?Xm(t):t}function er(t){const e=xl(t);return`rgb(${e.r},${e.g},${e.b})`}class Jm extends qe{constructor(s={}){super();l(this,"columns",[]);l(this,"fallChance");l(this,"speed");l(this,"baseColor");l(this,"trailColors");this.speed=s.speed??1,this.fallChance=s.fallChance??.7,s.baseColor?this.baseColor=xl(s.baseColor):this.baseColor={r:0,g:255,b:255},this.trailColors=this.calculateTrailColors()}calculateTrailColors(){const r=[];for(let o=0;o<=5;o++){const n=1-o/5*.6;r.push({r:Math.floor(this.baseColor.r*n),g:Math.floor(this.baseColor.g*n),b:Math.floor(this.baseColor.b*n)})}return r}reset(){this.columns=[],this.lastUpdate=performance.now()}renderFrame(s,r){this.columns.length!==s&&(this.columns=Array(s).fill(0).map(()=>Math.floor(Math.random()*r))),this.shouldStep(50)&&(this.columns=this.columns.map(i=>i>r+5?0:i+(Math.random()<this.fallChance?this.speed:0)));const o=this.ctx.createImageData(s,r),n=o.data;n.fill(0);for(let i=0;i<r;i++)for(let a=0;a<s;a++){const c=this.columns[a];let d=0,u=0,h=0;if(i===c)d=this.baseColor.r,u=this.baseColor.g,h=this.baseColor.b;else if(i<c&&i>c-this.trailColors.length){const m=c-i;if(m<this.trailColors.length){const y=this.trailColors[m];d=y.r,u=y.g,h=y.b}}const g=(i*s+a)*4;n[g]=d,n[g+1]=u,n[g+2]=h,n[g+3]=255}this.ctx.putImageData(o,0,0)}}class ey{constructor(e,s){l(this,"baseRenderer");l(this,"overlayIcons",new Map);l(this,"overlayConfigs");l(this,"loadedIcons",new Set);l(this,"canvas");l(this,"ctx");l(this,"persistOverlaysOnComplete");l(this,"baseRendererCompleted",!1);l(this,"completionCallback",null);l(this,"hasSignaledCompletion",!1);this.baseRenderer=s(e.baseRenderer.type,e.baseRenderer.data),this.overlayConfigs=e.overlays,this.persistOverlaysOnComplete=e.persistOverlaysOnComplete!==!1,this.canvas=document.createElement("canvas");const r=this.canvas.getContext("2d");if(!r)throw new Error("2D canvas not supported");this.ctx=r,this.loadOverlayImages(),"onDone"in this.baseRenderer&&typeof this.baseRenderer.onDone=="function"&&this.baseRenderer.onDone(()=>{this.baseRendererCompleted=!0,!this.persistOverlaysOnComplete&&this.completionCallback&&this.completionCallback()})}async loadOverlayImages(){for(const e of this.overlayConfigs){const s=new Image;s.crossOrigin="anonymous",s.onload=()=>{this.loadedIcons.add(e.src)},s.onerror=r=>{console.error(`Failed to load overlay image: ${e.src}`,r)},s.src=e.src,this.overlayIcons.set(e.src,s)}}calculateOverlayPosition(e,s,r){let o,n;if(typeof e.position=="string")switch(e.position){case"top-left":o=0,n=0;break;case"top-center":o=(s-e.size)/2,n=0;break;case"top-right":o=s-e.size,n=0;break;case"center-left":o=0,n=(r-e.size)/2;break;case"center":o=(s-e.size)/2,n=(r-e.size)/2;break;case"center-right":o=s-e.size,n=(r-e.size)/2;break;case"bottom-left":o=0,n=r-e.size;break;case"bottom-center":o=(s-e.size)/2,n=r-e.size;break;case"bottom-right":o=s-e.size,n=r-e.size;break;default:o=0,n=0}else o=e.position.x,n=e.position.y;return e.offset&&(o+=e.offset.x||0,n+=e.offset.y||0),{x:o,y:n}}reset(){this.baseRenderer.reset(),this.baseRendererCompleted=!1,this.hasSignaledCompletion=!1}renderFrame(e,s){if(this.canvas.width=e,this.canvas.height=s,this.ctx.clearRect(0,0,e,s),this.baseRendererCompleted&&this.persistOverlaysOnComplete)this.renderOverlays(e,s);else{this.baseRenderer.renderFrame(e,s);const r=this.baseRenderer.readPixels(e,s);if(r&&r.length>0){const o=new ImageData(r,e,s);this.ctx.putImageData(o,0,0)}this.renderOverlays(e,s)}}renderOverlays(e,s){for(const r of this.overlayConfigs){if(!r.persistent&&r.persistent!==void 0)continue;const o=this.overlayIcons.get(r.src);if(!o||!this.loadedIcons.has(r.src))continue;const n=this.calculateOverlayPosition(r,e,s);this.ctx.save(),r.opacity!==void 0&&(this.ctx.globalAlpha=Math.max(0,Math.min(1,r.opacity))),this.ctx.drawImage(o,n.x,n.y,r.size,r.size),this.ctx.restore()}}readPixels(e,s){return this.ctx.getImageData(0,0,e,s).data}play(){this.baseRenderer.play&&this.baseRenderer.play()}pause(){this.baseRenderer.pause&&this.baseRenderer.pause()}dispose(){this.overlayIcons.clear(),this.loadedIcons.clear(),this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.remove(),this.baseRenderer.dispose&&this.baseRenderer.dispose()}onDone(e){this.completionCallback=e,this.hasSignaledCompletion&&e()}isOneShot(){return this.persistOverlaysOnComplete?!1:"isOneShot"in this.baseRenderer&&typeof this.baseRenderer.isOneShot=="function"?this.baseRenderer.isOneShot():!1}}class Pl extends qe{constructor(s){super();l(this,"img");l(this,"loaded",!1);l(this,"scrollConfig");l(this,"loopConfig");l(this,"duration");l(this,"pauseDuration");l(this,"colorOverride");l(this,"originalSvgData",null);l(this,"position",0);l(this,"startTime",0);l(this,"lastFrameTime",0);l(this,"currentLoopCount",0);l(this,"completionCallback",null);l(this,"isPlaying",!1);l(this,"completed",!1);l(this,"isPaused",!1);l(this,"pauseStartTime",0);this.img=new Image,this.img.crossOrigin="anonymous",this.scrollConfig=s.scroll,this.loopConfig=s.loop??!1,this.duration=s.duration,this.pauseDuration=s.pauseBetweenLoops??0,this.colorOverride=s.colorOverride,this.colorOverride&&s.src.toLowerCase().includes(".svg")?this.loadAndProcessSvg(s.src):this.img.src=s.src,this.img.onload=()=>{this.loaded=!0},this.img.onerror=r=>{console.error("Failed to load image:",r)}}reset(){this.position=0,this.startTime=performance.now(),this.lastFrameTime=this.startTime,this.currentLoopCount=0,this.completed=!1,this.isPlaying=!1,this.isPaused=!1,this.pauseStartTime=0}play(){this.isPlaying||(this.isPlaying=!0,this.startTime=performance.now(),this.lastFrameTime=this.startTime)}pause(){this.isPlaying=!1}renderFrame(s,r){var a;if(!this.loaded||this.completed)return;if(this.isPaused){this.canvas.width=s,this.canvas.height=r,this.ctx.clearRect(0,0,s,r),this.pauseDuration>0&&performance.now()-this.pauseStartTime>=this.pauseDuration&&(this.isPaused=!1,this.position=0,this.startTime=performance.now(),this.lastFrameTime=this.startTime);return}if(this.canvas.width=s,this.canvas.height=r,this.ctx.clearRect(0,0,s,r),!((a=this.scrollConfig)!=null&&a.enabled)){this.ctx.drawImage(this.img,0,0,s,r),this.duration&&this.isPlaying&&performance.now()-this.startTime>=this.duration&&this.handleCompletion();return}const o=this.scrollConfig.direction||"left",n=this.scrollConfig.speed||50,i=this.scrollConfig.gap||0;if(this.isPlaying){const c=performance.now(),d=(c-this.lastFrameTime)/1e3;this.lastFrameTime=c;const u=n*d;switch(o){case"left":this.position+=u;break;case"right":this.position+=u;break;case"up":this.position+=u;break;case"down":this.position+=u;break}}this.drawScrollingImage(s,r,o,i),this.checkScrollCompletion(s,r,o,i)}drawScrollingImage(s,r,o,n){var h,g,m,y,v,E,_,N,x;const i=this.img.width/this.img.height;let a,c;((h=this.scrollConfig)==null?void 0:h.maintainAspectRatio)!==!1?(g=this.scrollConfig)!=null&&g.height?(c=this.scrollConfig.height,a=c*i):(m=this.scrollConfig)!=null&&m.width?(a=this.scrollConfig.width,c=a/i):o==="left"||o==="right"?(c=r,a=c*i):(a=s,c=a/i):(a=((y=this.scrollConfig)==null?void 0:y.width)||s,c=((v=this.scrollConfig)==null?void 0:v.height)||r);let d,u;switch(o==="left"||o==="right"?(d=0,((E=this.scrollConfig)==null?void 0:E.offsetY)==="center"||((_=this.scrollConfig)==null?void 0:_.offsetY)===void 0?u=(r-c)/2:u=this.scrollConfig.offsetY):(((N=this.scrollConfig)==null?void 0:N.offsetX)==="center"||((x=this.scrollConfig)==null?void 0:x.offsetX)===void 0?d=(s-a)/2:d=this.scrollConfig.offsetX,u=0),o){case"left":{const D=s-this.position;if(D<s&&D>-a&&this.ctx.drawImage(this.img,D,u,a,c),this.loopConfig&&this.pauseDuration===0&&this.position>n){const P=D+a+n;P<s&&this.ctx.drawImage(this.img,P,u,a,c)}break}case"right":{const D=-a+this.position;if(D>-a&&D<s&&this.ctx.drawImage(this.img,D,u,a,c),this.loopConfig&&this.pauseDuration===0&&D-n-a>-a){const P=D-a-n;P<s&&this.ctx.drawImage(this.img,P,u,a,c)}break}case"up":{const D=r-this.position;if(D>-c&&D<r&&this.ctx.drawImage(this.img,d,D,a,c),this.loopConfig&&this.pauseDuration===0&&D+c+n<r){const P=D+c+n;P>-c&&this.ctx.drawImage(this.img,d,P,a,c)}break}case"down":{const D=-c+this.position;if(D>-c&&D<r&&this.ctx.drawImage(this.img,d,D,a,c),this.loopConfig&&this.pauseDuration===0&&D-n-c>-c){const P=D-c-n;P<r&&this.ctx.drawImage(this.img,d,P,a,c)}break}}}checkScrollCompletion(s,r,o,n){var h,g,m,y,v;if(!this.isPlaying)return;const i=this.img.width/this.img.height;let a,c;switch(((h=this.scrollConfig)==null?void 0:h.maintainAspectRatio)!==!1?(g=this.scrollConfig)!=null&&g.height?(c=this.scrollConfig.height,a=c*i):(m=this.scrollConfig)!=null&&m.width?(a=this.scrollConfig.width,c=a/i):o==="left"||o==="right"?(c=r,a=c*i):(a=s,c=a/i):(a=((y=this.scrollConfig)==null?void 0:y.width)||s,c=((v=this.scrollConfig)==null?void 0:v.height)||r),o){case"left":case"right":this.loopConfig;break;case"up":case"down":this.loopConfig;break}let d=!1;const u=1;switch(o){case"left":d=s-this.position<-a-u;break;case"right":d=-a+this.position>s+u;break;case"up":d=r-this.position<-c-u;break;case"down":d=-c+this.position>r+u;break}d&&(this.loopConfig===!1||typeof this.loopConfig=="number"&&this.loopConfig===1?this.handleCompletion():typeof this.loopConfig=="number"&&this.loopConfig>1?(this.currentLoopCount++,this.currentLoopCount>=this.loopConfig?this.handleCompletion():this.startPauseOrNextLoop()):this.loopConfig===!0&&this.startPauseOrNextLoop())}startPauseOrNextLoop(){this.pauseDuration>0?(this.isPaused=!0,this.pauseStartTime=performance.now()):this.position=0}handleCompletion(){this.completed=!0,this.isPlaying=!1,this.completionCallback&&this.completionCallback()}onDone(s){this.completionCallback=s}isOneShot(){var s;return!((s=this.scrollConfig)!=null&&s.enabled)&&!this.loopConfig}async loadAndProcessSvg(s){try{const o=await(await fetch(s)).text();this.originalSvgData=o;const n=this.applySvgColorOverride(o),i=`data:image/svg+xml;base64,${btoa(n)}`;this.img.src=i}catch(r){console.error("Failed to load and process SVG:",r),this.img.src=s}}applySvgColorOverride(s){if(!this.colorOverride)return s;const r=er(this.colorOverride);return s.replace(/fill\s*=\s*["'][^"']*["']/gi,`fill="${r}"`).replace(/fill\s*:\s*[^;"]*/gi,`fill:${r}`).replace(/stroke\s*=\s*["'][^"']*["']/gi,`stroke="${r}"`).replace(/stroke\s*:\s*[^;"]*/gi,`stroke:${r}`)}dispose(){this.img.removeAttribute("src"),this.completionCallback=null,this.originalSvgData=null}}class ty extends qe{constructor(s){super();l(this,"text");l(this,"lines");l(this,"fontSize");l(this,"fontFamily");l(this,"lineHeight");l(this,"textColor");l(this,"scrollConfig");l(this,"loopConfig");l(this,"duration");l(this,"pauseDuration");l(this,"position",0);l(this,"startTime",0);l(this,"lastFrameTime",0);l(this,"currentLoopCount",0);l(this,"completionCallback",null);l(this,"isPlaying",!1);l(this,"completed",!1);l(this,"isPaused",!1);l(this,"pauseStartTime",0);l(this,"textWidth",0);l(this,"textHeight",0);l(this,"lineWidths",[]);l(this,"textMeasured",!1);this.text=s.text,this.lines=s.text.split(`
112
- `),this.fontSize=s.fontSize??8,this.lineHeight=s.lineHeight??this.fontSize+2,this.fontFamily=s.fontFamily??"monospace, 'Lucida Console', 'Courier New', Courier",this.scrollConfig=s.scroll,this.loopConfig=s.loop??!1,this.duration=s.duration,this.pauseDuration=s.pauseBetweenLoops??0,s.color?this.textColor=er(s.color):this.textColor="rgb(255,255,255)"}measureText(){if(this.textMeasured)return;this.ctx.font=`${this.fontSize}px ${this.fontFamily}`,this.lineWidths=[];let s=0;for(const r of this.lines){const n=this.ctx.measureText(r).width;this.lineWidths.push(n),s=Math.max(s,n)}this.textWidth=s,this.textHeight=this.lines.length*this.lineHeight,this.textMeasured=!0}reset(){this.position=0,this.startTime=performance.now(),this.lastFrameTime=this.startTime,this.currentLoopCount=0,this.completed=!1,this.isPlaying=!1,this.isPaused=!1,this.pauseStartTime=0,this.textMeasured=!1,this.lineWidths=[]}play(){this.isPlaying||(this.isPlaying=!0,this.startTime=performance.now(),this.lastFrameTime=this.startTime)}pause(){this.isPlaying=!1}renderFrame(s,r){var a;if(this.canvas.width=s,this.canvas.height=r,this.measureText(),this.completed)return;if(this.isPaused){this.ctx.clearRect(0,0,s,r),this.pauseDuration>0&&performance.now()-this.pauseStartTime>=this.pauseDuration&&(this.isPaused=!1,this.position=0,this.startTime=performance.now(),this.lastFrameTime=this.startTime);return}if(this.ctx.clearRect(0,0,s,r),!((a=this.scrollConfig)!=null&&a.enabled)){this.drawStaticText(s,r),this.duration&&this.isPlaying&&performance.now()-this.startTime>=this.duration&&this.handleCompletion();return}const o=this.scrollConfig.direction||"left",n=this.scrollConfig.speed||50,i=this.scrollConfig.gap||0;if(this.isPlaying){const c=performance.now(),d=(c-this.lastFrameTime)/1e3;this.lastFrameTime=c;const u=n*d;switch(o){case"left":case"right":case"up":case"down":this.position+=u;break}}this.drawScrollingText(s,r,o,i),this.checkScrollCompletion(s,r,o)}drawStaticText(s,r){this.ctx.font=`${this.fontSize}px ${this.fontFamily}`,this.ctx.fillStyle=this.textColor,this.ctx.textBaseline="top";const o=this.textHeight;let n=(r-o)/2;for(let i=0;i<this.lines.length;i++){const a=this.lines[i],c=this.lineWidths[i],d=(s-c)/2,u=n+i*this.lineHeight;this.ctx.fillText(a,d,u)}}drawScrollingText(s,r,o,n){var c,d,u,h;this.ctx.font=`${this.fontSize}px ${this.fontFamily}`,this.ctx.fillStyle=this.textColor,this.ctx.textBaseline="top";let i,a;o==="left"||o==="right"?(i=0,((c=this.scrollConfig)==null?void 0:c.offsetY)==="center"||((d=this.scrollConfig)==null?void 0:d.offsetY)===void 0?a=(r-this.textHeight)/2:a=this.scrollConfig.offsetY):(((u=this.scrollConfig)==null?void 0:u.offsetX)==="center"||((h=this.scrollConfig)==null?void 0:h.offsetX)===void 0?(i=s/2,this.ctx.textAlign="center"):(i=this.scrollConfig.offsetX,this.ctx.textAlign="left"),a=0),this.drawMultiLineScrollText(o,s,r,n,i,a)}drawMultiLineScrollText(s,r,o,n,i,a){switch(s){case"left":{const c=r-this.position;if(c<r&&c>-this.textWidth&&this.drawTextBlock(c,a,"left"),this.loopConfig&&this.pauseDuration===0&&this.position>n){const d=c+this.textWidth+n;d<r&&this.drawTextBlock(d,a,"left")}break}case"right":{const c=-this.textWidth+this.position;if(c>-this.textWidth&&c<r&&this.drawTextBlock(c,a,"left"),this.loopConfig&&this.pauseDuration===0&&c-n-this.textWidth>-this.textWidth){const d=c-this.textWidth-n;d<r&&this.drawTextBlock(d,a,"left")}break}case"up":{const c=o-this.position;if(c>-this.textHeight&&c<o&&this.drawTextBlock(i,c,"center"),this.loopConfig&&this.pauseDuration===0&&c+this.textHeight+n<o){const d=c+this.textHeight+n;d>-this.textHeight&&this.drawTextBlock(i,d,"center")}break}case"down":{const c=-this.textHeight+this.position;if(c>-this.textHeight&&c<o&&this.drawTextBlock(i,c,"center"),this.loopConfig&&this.pauseDuration===0&&c-n-this.textHeight>-this.textHeight){const d=c-this.textHeight-n;d<o&&this.drawTextBlock(i,d,"center")}break}}}drawTextBlock(s,r,o){for(let n=0;n<this.lines.length;n++){const i=this.lines[n],a=this.lineWidths[n];let c;o==="center"?c=s-a/2:c=s;const d=r+n*this.lineHeight;this.ctx.fillText(i,c,d)}}checkScrollCompletion(s,r,o){if(!this.isPlaying)return;let n=!1;const i=1;switch(o){case"left":n=s-this.position<-this.textWidth-i;break;case"right":n=-this.textWidth+this.position>s+i;break;case"up":n=r-this.position<-this.textHeight-i;break;case"down":n=-this.textHeight+this.position>r+i;break}n&&(this.loopConfig===!1||typeof this.loopConfig=="number"&&this.loopConfig===1?this.handleCompletion():typeof this.loopConfig=="number"&&this.loopConfig>1?(this.currentLoopCount++,this.currentLoopCount>=this.loopConfig?this.handleCompletion():this.startPauseOrNextLoop()):this.loopConfig===!0&&this.startPauseOrNextLoop())}startPauseOrNextLoop(){this.pauseDuration>0?(this.isPaused=!0,this.pauseStartTime=performance.now()):this.position=0}handleCompletion(){this.completed=!0,this.isPlaying=!1,this.completionCallback&&this.completionCallback()}onDone(s){this.completionCallback=s}isOneShot(){var s;return!((s=this.scrollConfig)!=null&&s.enabled)&&!this.loopConfig}dispose(){this.completionCallback=null}}class sy{constructor(e){l(this,"patterns");l(this,"currentPatternIndex",0);l(this,"currentRenderer",null);l(this,"loopConfig");l(this,"currentLoopCount",0);l(this,"transitionDuration");l(this,"patternOverrides");l(this,"completionCallback",null);l(this,"patternStore");l(this,"canvas");l(this,"ctx");l(this,"width",0);l(this,"height",0);this.patterns=e.patterns,this.loopConfig=e.loop??!1,this.transitionDuration=e.transitionDuration??0,this.patternOverrides=e.patternOverrides??{},this.patternStore=e.patternStore??new Map,this.canvas=document.createElement("canvas");const s=this.canvas.getContext("2d");if(!s)throw new Error("2D canvas not supported");if(this.ctx=s,this.patterns.length===0)throw new Error("SequenceRenderer requires at least one pattern");this.loadCurrentPattern()}loadCurrentPattern(){var n,i,a,c;const e=this.patterns[this.currentPatternIndex],s=this.patternStore.get(e);if(!s){console.warn(`Pattern "${e}" not found in store, skipping`),this.moveToNextPattern();return}this.currentRenderer&&((i=(n=this.currentRenderer).dispose)==null||i.call(n));const r=this.patternOverrides[e]??{},o={...s.data,...r};try{this.currentRenderer=tr({mode:s.type,data:o}),this.currentRenderer&&this.isDoneAware(this.currentRenderer)&&this.currentRenderer.onDone(()=>{this.handlePatternComplete()}),this.currentRenderer&&(this.currentRenderer.reset(),(c=(a=this.currentRenderer).play)==null||c.call(a),this.width>0&&this.height>0&&this.currentRenderer.renderFrame(this.width,this.height))}catch(d){console.error(`Failed to create renderer for pattern "${e}":`,d),this.moveToNextPattern()}}isDoneAware(e){return typeof(e==null?void 0:e.onDone)=="function"}handlePatternComplete(){this.transitionDuration>0?setTimeout(()=>{this.moveToNextPattern()},this.transitionDuration):this.moveToNextPattern()}moveToNextPattern(){this.currentPatternIndex++,this.currentPatternIndex>=this.patterns.length?this.loopConfig===!0?(this.currentPatternIndex=0,this.loadCurrentPattern()):typeof this.loopConfig=="number"&&this.currentLoopCount<this.loopConfig-1?(this.currentLoopCount++,this.currentPatternIndex=0,this.loadCurrentPattern()):this.completionCallback&&this.completionCallback():this.loadCurrentPattern()}reset(){this.currentPatternIndex=0,this.currentLoopCount=0,this.loadCurrentPattern()}play(){var e,s;(s=(e=this.currentRenderer)==null?void 0:e.play)==null||s.call(e)}pause(){var e,s;(s=(e=this.currentRenderer)==null?void 0:e.pause)==null||s.call(e)}renderFrame(e,s){this.width=e,this.height=s,this.canvas.width=e,this.canvas.height=s,this.currentRenderer&&this.currentRenderer.renderFrame(e,s)}readPixels(e,s){return this.currentRenderer?this.currentRenderer.readPixels(e,s):this.ctx.getImageData(0,0,e,s).data}onDone(e){this.completionCallback=e}isOneShot(){var e,s;return this.loopConfig===!1||this.loopConfig===1?this.patterns.length===1&&this.currentRenderer?((s=(e=this.currentRenderer).isOneShot)==null?void 0:s.call(e))??!1:!0:!1}dispose(){var e,s;this.currentRenderer&&((s=(e=this.currentRenderer).dispose)==null||s.call(e)),this.completionCallback=null}setPatternStore(e){this.patternStore=e,this.patterns.length>0&&this.loadCurrentPattern()}}const ry=tn(qe);class oy extends ry{constructor(s={r:0,g:0,b:0}){super();l(this,"color");let r;s.color!==void 0?r=s.color:s.r!==void 0&&s.g!==void 0&&s.b!==void 0?r={r:s.r,g:s.g,b:s.b}:r={r:0,g:0,b:0},this.color=er(r)}setColor(s){this.color=er(s),this.resetOneShot()}reset(){this.resetOneShot()}renderFrame(s,r){this.isOneShotDone||(this.canvas.width=s,this.canvas.height=r,this.ctx.fillStyle=this.color,this.ctx.fillRect(0,0,s,r),this.signalDoneIfNeeded())}}class ny extends qe{constructor({minHue:s=0,maxHue:r=360,speed:o=1}={}){super();l(this,"offset",0);l(this,"minHue");l(this,"maxHue");l(this,"speed");this.minHue=s,this.maxHue=r,this.speed=o}reset(){this.offset=0,this.lastUpdate=performance.now()}hslToRgb(s,r,o){let n,i,a;if(r===0)n=i=a=o;else{const c=(h,g,m)=>(m<0&&(m+=1),m>1&&(m-=1),m<.16666666666666666?h+(g-h)*6*m:m<.5?g:m<.6666666666666666?h+(g-h)*(.6666666666666666-m)*6:h),d=o<.5?o*(1+r):o+r-o*r,u=2*o-d;n=c(u,d,s+1/3),i=c(u,d,s),a=c(u,d,s-1/3)}return[Math.round(n*255),Math.round(i*255),Math.round(a*255)]}renderFrame(s,r){this.shouldStep(50)&&(this.offset=(this.offset+this.speed)%s);const o=this.ctx.createImageData(s,r),n=o.data;let i=0;for(let a=0;a<r;a++)for(let c=0;c<s;c++){const d=(c+this.offset)%s/s,u=this.minHue/360+d*((this.maxHue-this.minHue)/360),[h,g,m]=this.hslToRgb(u,1,.5);n[i++]=h,n[i++]=g,n[i++]=m,n[i++]=255}this.ctx.putImageData(o,0,0)}}const Zn=new Map;is(Q,{register(t,e){Zn.set(t,e)},execute(t,e){const s=Zn.get(t);return s?new s(e):null}});S.canvas.registerRenderer("video",Zm);S.canvas.registerRenderer("video-basic",Rl);S[Q].register("image-static",Al);S[Q].register("image-scrolling",Pl);const iy=class{constructor(t){var e;return(e=t.scroll)!=null&&e.enabled?new Pl(t):new Al(t)}};S[Q].register("image",iy);S[Q].register("color",oy);S[Q].register("matrix",Jm);S[Q].register("sweep",ny);S[Q].register("gradient",Wm);S[Q].register("drop",Ym);S[Q].register("sequence",sy);S[Q].register("text",ty);const ay=class{constructor(t){const e=(s,r)=>{const o=tr({mode:s,data:r});if(!o)throw new Error(`Failed to create renderer of type: ${s}`);return o};return new ey(t,e)}};S[Q].register("overlay",ay);const tr=({mode:t,data:e})=>{const s=S[Q].execute(t,e);if(s)return s;throw new Error(`Unknown mode: ${t}`)};var cy=Object.defineProperty,ly=Object.getOwnPropertyDescriptor,Mt=(t,e,s,r)=>{for(var o=r>1?void 0:r?ly(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&cy(e,s,o),o};const Ll="canvas-dispatcher-model";function dy(t){if(t=t.replace(/^#/,""),t.length===3&&(t=t.split("").map(s=>s+s).join("")),t.length!==6)return null;const e=parseInt(t,16);return{r:e>>16&255,g:e>>8&255,b:e&255}}let Le=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_content",new Map);l(this,"_patterns",new Map);l(this,"_endpointRenderers");l(this,"pattern");l(this,"data");this.id=t,this.logger=s.logger,this._endpointRenderers=new Te}addNamedEndpoint(t,e){this._endpointRenderers.getModel(t)&&this.logger.warn(`Endpoint "${t}" already exists. Overwriting.`);const s=en.instance(t).options({apiPath:e.apiPath,width:e.width,height:e.height,fps:e.fps,durationMs:e.durationMs??null,endpoint:t}).build();return this._endpointRenderers.addModel(s),s}addContent(t,e){this._content.has(t)&&this.logger.warn(`Content "${t}" already exists. Overwriting.`),this._content.set(t,e)}addPattern(t,e){this._patterns.has(t)&&this.logger.warn(`Pattern "${t}" already exists. Overwriting.`),this._patterns.set(t,e)}async handlePatternsPost(t,e){var o,n;const s=t.body,r=Array.isArray(s)?s:[s];if(r.some(i=>!i.id||!i.type||!i.data)){(o=e.status)==null||o.call(e,400).send({error:"Invalid pattern data"});return}for(const i of r)this._patterns.has(i.id)&&this.logger.warn(`Pattern "${i.id}" already exists. Overwriting.`),this.addPattern(i.id,i);(n=e.status)==null||n.call(e,200).send({status:"OK"})}async handlePatternApplication(t,e){var d,u,h;const s=t.params.pattern,r=t.params.endpoint,o=this._endpointRenderers.getModel(r);if(!o){(d=e.status)==null||d.call(e,404).send({error:`Endpoint "${r}" not found`});return}if(!this._patterns.has(s)){(u=e.status)==null||u.call(e,404).send({error:`Pattern "${s}" not found`});return}const n=this._patterns.get(s),i=n.type,a=t.body||{};this.data={...n.data,...a};const c=i==="sequence"?{...this.data,patternStore:this._patterns}:this.data;o.renderer=tr({mode:i,data:c}),o.setClearOnComplete(n.clearOnComplete),o.startStreaming(),(h=e.status)==null||h.call(e,200).send({status:"OK"})}async handleColorApplication(t,e){var d,u,h;const s=t.params.color,r=dy(s);if(!r){(d=e.status)==null||d.call(e,400).send({error:"Invalid color format"});return}const o=t.params.endpoint,n=this._endpointRenderers.getModel(o);if(!n){(u=e.status)==null||u.call(e,404).send({error:`Endpoint "${o}" not found`});return}const{r:i,b:a,g:c}=r;n.renderer=tr({mode:"color",data:{r:i,g:c,b:a}}),n.startStreaming(),(h=e.status)==null||h.call(e,200).send({status:"OK"})}async handleEndpointCreation(t,e){var r,o;const s=t.body;if(!s.apiPath||!s.id){(r=e.status)==null||r.call(e,400).send({error:"Name and path are required"});return}this.addNamedEndpoint(s.id,s),(o=e.status)==null||o.call(e,200).send({status:"OK"})}async load(t){var s;const e=t==null?void 0:t.get(ut.loader);e&&((s=e.patterns)==null||s.forEach(r=>{if(!r.id||!r.type||!r.data){this.logger.warn(`Invalid pattern data: ${JSON.stringify(r)}`);return}this.addPattern(r.id,r)}))}};Mt([be],Le.prototype,"_endpointRenderers",2);Mt([as("/api/ui/canvas/patterns")],Le.prototype,"handlePatternsPost",1);Mt([as("/api/ui/canvas/pattern/:endpoint/:pattern")],Le.prototype,"handlePatternApplication",1);Mt([as("/api/ui/canvas/color/:endpoint/:color")],Le.prototype,"handleColorApplication",1);Mt([as("/api/ui/canvas/endpoint")],Le.prototype,"handleEndpointCreation",1);Le=Mt([R(Ll)],Le);const ut=new Ee({class:Le,type:Ll}),{URL:sn}=oe(),{getOne:kl}=se.build({basePath:`${sn}/api/device`}),sr=p.createLogger({name:"device-service",group:"Services"}),Fl=async()=>{sr.debug("sending GET for device serial number");try{const t=await kl({urlOverride:`${sn}/api/kos/device/serialNumber`});return[void 0,t==null?void 0:t.data.serialNumber]}catch(t){if(t instanceof B)return sr.error(`Error fetching device serial number: ${t.payload.error}`),[t.payload.error,void 0]}return["unknownError",void 0]},Nl=async()=>{sr.debug("sending GET for device details");try{const t=await kl({urlOverride:`${sn}/api/kos/device`});return t?[void 0,t.data]:["unknownError",void 0]}catch(t){if(t instanceof B)return sr.error(`Error fetching device serial number: ${t.payload.error}`),[t.payload.error,void 0]}return["unknownError",void 0]},uy=Object.freeze(Object.defineProperty({__proto__:null,getDeviceDetails:Nl,getSerialNumber:Fl},Symbol.toStringTag,{value:"Module"}));var hy=Object.defineProperty,fy=Object.getOwnPropertyDescriptor,Ul=(t,e,s,r)=>{for(var o=r>1?void 0:r?fy(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&hy(e,s,o),o};const jl="device-model",gy="/kos/criticalData/changed",py="/kos/criticalData/available";let rr=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_serialNumber");l(this,"_name");l(this,"_nodeId");this.id=t,this.logger=s.logger,this._serialNumber="unassigned",this._name="unassigned",this._nodeId="unassigned"}get serialNumber(){return this._serialNumber}get name(){return this._name}get nodeId(){return this._nodeId}get nodeType(){const[t]=this.nodeId.split("-");return t}get nodeName(){const[,t]=this.nodeId.split("-");return t}updateModel(t){this._serialNumber=t.serialNumber??"unassigned",this._name=t.name??"unassigned",this._nodeId=t.nodeId??"unassigned"}async loadDeviceData(){const[t,e]=await Nl();if(t){this.logger.error(`Error fetching device serial number: ${t}`);return}if(e){const{name:s,nodeId:r}=e;this.updateModel({name:s,nodeId:r,serialNumber:this.serialNumber})}}async loadSerialNumber(){const[t,e]=await Fl();if(t){this.logger.error(`Error fetching device serial number: ${t}`);return}this.updateModel({serialNumber:e,name:this.name,nodeId:this.nodeId})}async handleCriticalDataChanged(){this.logger.debug(`Critical data changed for device ${this.id}`),await this.loadSerialNumber()}async init(){this.logger.debug(`initializing device ${this.id}`)}async load(){this.logger.debug(`loading device ${this.id}`),await this.loadDeviceData(),await this.loadSerialNumber()}};Ul([U({topic:[gy,py],websocket:!0})],rr.prototype,"handleCriticalDataChanged",1);rr=Ul([R(jl)],rr);const or=new Ee({class:rr,type:jl});var my=Object.getOwnPropertyDescriptor,yy=(t,e,s,r)=>{for(var o=r>1?void 0:r?my(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const Bl="network-interface-model";let to=class{constructor(t,e,s){l(this,"id");l(this,"name");l(this,"type");l(this,"nmdevicestate");l(this,"hwaddress");l(this,"mtu");l(this,"configured");l(this,"wifi");l(this,"ethernet");l(this,"ip4settings");l(this,"category");l(this,"logger");this.id=t,this.logger=s.logger,this.name=e.name,this.type=e.type,this.nmdevicestate=e.nmdevicestate,this.hwaddress=e.hwaddress,this.mtu=e.mtu,this.configured=e.configured,this.wifi=e.wifi,this.ethernet=e.ethernet,this.ip4settings=e.ip4settings,this.category=e.category}updateModel(t){this.name=t.name,this.type=t.type,this.nmdevicestate=t.nmdevicestate,this.hwaddress=t.hwaddress,this.mtu=t.mtu,this.configured=t.configured,this.wifi=t.wifi,this.ethernet=t.ethernet,this.ip4settings=t.ip4settings,this.category=t.category}async init(){this.logger.debug(`initializing network-interface ${this.id}`)}async load(){this.logger.debug(`loading network-interface ${this.id}`)}};to=yy([R(Bl)],to);const rn=new we({class:to,type:Bl}),{URL:by}=oe(),{getAll:wy}=se.build({basePath:`${by}/api/kos/network/interfaces`}),Xn=p.createLogger({name:"network-interface-service",group:"Services"}),Kl=async()=>{Xn.debug("sending GET for copy-logs");try{const t=await wy({});return[void 0,t==null?void 0:t.data]}catch(t){if(t instanceof B)return Xn.error(`Error fetching log file size: ${t.payload.error}`),[t.payload.error,void 0]}return["unknownError",void 0]},vy=Object.freeze(Object.defineProperty({__proto__:null,getNetworkInterfaces:Kl},Symbol.toStringTag,{value:"Module"}));var My=Object.defineProperty,Ey=Object.getOwnPropertyDescriptor,Hl=(t,e,s,r)=>{for(var o=r>1?void 0:r?Ey(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&My(e,s,o),o};const zl="network-interface-container-model";let nr=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new Te({parentId:t,indexMap:{byCategory:"category"}})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug(`initializing network-interface-container container ${this.id}`)}async refreshInterfaces(){this.logger.debug("refreshing interfaces");const[t,e]=await Kl();if(t){this.logger.error(`Error loading network interfaces: ${t}`);return}e&&e.forEach(s=>{const r=rn.instance(s.name).forceUpdate.options(s).build();this.addModel(r)})}async load(){this.logger.debug(`loading network-interface-container container ${this.id}`),this.refreshInterfaces()}};Hl([be],nr.prototype,"_models",2);nr=Hl([R(zl)],nr);const ts=new Ee({class:nr,type:zl});ts.addRelatedModel(rn);const{URL:Ty}=oe(),{getAll:_y}=se.build({basePath:`${Ty}/api/kos/storage/devices`}),Jn=p.createLogger({name:"storage-device-service",group:"Services"}),Gl=async()=>{Jn.debug("sending GET for storage-device");const t=await _y({});return!(t!=null&&t.data)||t.status!==200?(Jn.error("Failed to retrieve storage-device data",t),[]):t.data},Iy=Object.freeze(Object.defineProperty({__proto__:null,getStorageDevices:Gl},Symbol.toStringTag,{value:"Module"}));var Sy=Object.getOwnPropertyDescriptor,Oy=(t,e,s,r)=>{for(var o=r>1?void 0:r?Sy(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const Vl="storage-device-model";let so=class{constructor(t,e,s){l(this,"id");l(this,"mountDir");l(this,"removed");l(this,"vendor");l(this,"runTimeMs");l(this,"model");l(this,"nodeId");l(this,"local");l(this,"label");l(this,"syspath");l(this,"logger");this.id=t,this.logger=s.logger,this.mountDir=e.mountDir,this.removed=e.removed,this.vendor=e.vendor,this.runTimeMs=e.runTimeMs,this.model=e.model,this.nodeId=e.nodeId,this.local=e.local,this.label=e.label,this.syspath=e.syspath}updateModel(t){this.mountDir=t.mountDir,this.removed=t.removed,this.vendor=t.vendor,this.runTimeMs=t.runTimeMs,this.model=t.model,this.nodeId=t.nodeId,this.local=t.local,this.label=t.label,this.syspath=t.syspath}async init(){this.logger.debug(`initializing storage-device ${this.id}`)}async load(){this.logger.debug(`loading storage-device ${this.id}`)}};so=Oy([fr(),R(Vl)],so);const ir=new we({class:so,type:Vl});var $y=Object.defineProperty,Dy=Object.getOwnPropertyDescriptor,on=(t,e,s,r)=>{for(var o=r>1?void 0:r?Dy(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&$y(e,s,o),o};const Yl="storage-device-container-model",Cy="/kos/storage";let ss=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new Te({parentId:t})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug(`initializing storage-device-container container ${this.id}`)}get isStorageInserted(){return this.data.length>0}get volumes(){return this.data}handleStorageAvailability(t){this._models.data.filter(s=>!t.find(r=>r.id===s.id)).forEach(s=>{this.removeModel(s.id)}),t.forEach(s=>{const r=this.getModel(s.id);if(r){const o={...s,kosParentId:this.id};r.updateModel(o)}else{const o={...s,kosParentId:this.id},n=ir.instance(s.id).options(o).build();this.addModel(n)}})}async load(){this.logger.debug(`loading storage-device-container container ${this.id}`),(await Gl()).forEach(e=>{const s={...e,kosParentId:this.id},r=ir.instance(e.id).options(s).build();this.addModel(r)})}};on([be],ss.prototype,"_models",2);on([U({topic:Cy,websocket:!0})],ss.prototype,"handleStorageAvailability",1);ss=on([R(Yl)],ss);const ht=new Ee({class:ss,type:Yl});ht.addRelatedModel(ir);const{URL:nn}=oe(),{getAll:Ry,postModel:Ay}=se.build({basePath:`${nn}/api/kos/update/available`}),ei=p.createLogger({name:"usb-update-service",group:"Services"}),ql=async()=>{ei.debug("sending GET for usb-update");const t=await Ry({urlOverride:`${nn}/api/kos/update/available`});return!(t!=null&&t.data)||(t==null?void 0:t.status)!==200?(ei.error("Failed to retrieve usb-update data",t),[]):t.data},Wl=async(t,e,s)=>{const r=await Ay({model:{manifestId:t,deviceId:e},tracker:s,urlOverride:`${nn}/api/kos/update/install`});if(!(r!=null&&r.data))throw new Error("No response from server");return r.data},xy=Object.freeze(Object.defineProperty({__proto__:null,getAvailableUpdates:ql,installUpdate:Wl},Symbol.toStringTag,{value:"Module"}));var Py=Object.defineProperty,Ly=Object.getOwnPropertyDescriptor,Ql=(t,e,s,r)=>{for(var o=r>1?void 0:r?Ly(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Py(e,s,o),o};const Zl="usb-update-model";let ar=class{constructor(t,e,s){l(this,"id");l(this,"active");l(this,"blocked");l(this,"createTime");l(this,"deviceId");l(this,"manifestId");l(this,"notes");l(this,"futureHandler");l(this,"logger");this.id=t,this.logger=s.logger,this.active=e.active,this.blocked=e.blocked,this.createTime=e.createTime,this.deviceId=e.deviceId,this.manifestId=e.manifestId,this.notes=e.notes,this.futureHandler=new yr(this)}updateModel(t){this.active=t.active,this.blocked=t.blocked,this.createTime=t.createTime,this.deviceId=t.deviceId,this.manifestId=t.manifestId,this.notes=t.notes}reset(){this.futureHandler.removeFuture()}get future(){return this.futureHandler.future}async install(t){if(!t)throw new Error("No tracker provided");return this.logger.info(`Installing update for manifest ${this.manifestId} from device ${this.deviceId}`),Wl(this.manifestId,this.deviceId,t)}async init(){this.logger.debug(`initializing usb-update ${this.id}`)}async load(){this.logger.debug(`loading usb-update ${this.id}`)}};Ql([hn()],ar.prototype,"install",1);ar=Ql([R(Zl)],ar);const an=new we({class:ar,type:Zl});var ky=Object.defineProperty,Fy=Object.getOwnPropertyDescriptor,_r=(t,e,s,r)=>{for(var o=r>1?void 0:r?Fy(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&ky(e,s,o),o};const Xl="usb-update-container-model";let ft=class{constructor(t,e,s){l(this,"id");l(this,"disposer");l(this,"storageService");l(this,"_activeUpdate");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new Te({parentId:t})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}get activeUpdate(){return this._activeUpdate}reset(){this.clearActiveUpdate()}clearActiveUpdate(){this._activeUpdate=void 0}updateActiveUpdate(t){this._activeUpdate=t}get isUsbInserted(){return this.storageService.isStorageInserted}get hasAvailableUpdates(){return this._models.data.length>0}async syncAvailableUpdates(){const t=await ql();X(()=>{const e=t.map(s=>`${s.deviceId}-${s.manifestId}`);this._models.data.filter(s=>!e.includes(s.id)).forEach(s=>this.removeModel(s.id)),t.forEach(s=>{const r=`${s.deviceId}-${s.manifestId}`,o=an.instance(r).forceUpdate.options({...s,createTime:new Date(s.createTime)}).build();this.addModel(o)}),this.data.length===1?this.updateActiveUpdate(this.data[0]):this.clearActiveUpdate()})}usbInsertedEffect(){this.isUsbInserted?this.syncAvailableUpdates():(this._models.clear(),this.clearActiveUpdate())}async init(){this.logger.debug(`initializing usb-update-container container ${this.id}`)}unload(){var t;(t=this.disposer)==null||t.call(this)}async activate(){this.logger.debug(`activating usb-update-container container ${this.id}`),await this.syncAvailableUpdates()}async load(){this.logger.debug(`loading usb-update-container container ${this.id}`)}};_r([mt({modelType:ht.type})],ft.prototype,"storageService",2);_r([be],ft.prototype,"_models",2);_r([ca({dependencies:t=>[t.isUsbInserted]})],ft.prototype,"usbInsertedEffect",1);ft=_r([R(Xl)],ft);const rs=new Ee({class:ft,type:Xl});rs.addRelatedModel(an);const Ny=()=>({...{[wt.type]:{class:Cc},[Pe.type]:{class:kc,singleton:!0},...ee.registration,...Ve.registration,...lt.registration,...Zs.registration,...Oe.registration,[Xo.type]:{class:exports.WsEventModel,singleton:!0},...es.registration,...Qo.registration,...Ks.registration}}),cn=Ny(),Uy={models:cn,preloadModels:[]},ti=!0,Jl=t=>()=>{const e=cn;return qa(ro)(Jt).model(lt).model(ht).model(rs).model(or).model(Ys).model(Yt).model(qs).model(Vo).model(ts).model(ut).model(en).model(Ho,ti).model(us).model(zc,ti),Object.keys(e).forEach(s=>{const r=e[s];Ya(ro)(s,r)}),{preload:C.model.preloadModel(t),model:C.model.register(t),companion:C.companion.register(t),legacy:C.model.registerLegacyModel(t)}},ye={};ye.core={models:Jl(ye)};ye.preload=C.model.preloadModel(ye);ye.model=C.model.register(ye);ye.companion=C.companion.register(ye);ye.legacy=C.model.registerLegacyModel(ye);const ro=ye;class jy{registerTroubleRankMapper(e){return S.propertyMapper.registerPropertyMapper(me.TroubleRank,e),this}registerTroubleRoleMapper(e){return S.propertyMapper.registerPropertyMapper(me.TroubleRole,e),this}registerTroubleColorMapper(e){return S.propertyMapper.registerPropertyMapper(me.TroubleColor,e),this}registerModelLoader(e,s){S.loader.registerLoader(e,s)}registerCanvasPatternLoader(e){S.loader.registerLoader(ut.loader,e)}}class fs{constructor(e){l(this,"futureHandler");this.futureHandler=new yr(e)}get future(){return this.futureHandler.future}get progress(){var e;return((e=this.future)==null?void 0:e.progress)||0}get status(){var e;return((e=this.future)==null?void 0:e.status)||"IDLE"}get isRunning(){return this.future?!this.future.endState:!1}get isCancelled(){var e;return((e=this.future)==null?void 0:e.status)==="CANCELLED"||!1}async cancelFuture(){this.future&&await this.future.cancelFuture()}}function By(t){const e=new fs(t);t.futureHandler=e.futureHandler}function ed(t){const e=new fs(t),s=t;s.futureHandler=e.futureHandler,Object.defineProperty(t,"future",{get(){return e.future},enumerable:!0,configurable:!0}),Object.defineProperty(t,"progress",{get(){return e.progress},enumerable:!0,configurable:!0}),Object.defineProperty(t,"status",{get(){return e.status},enumerable:!0,configurable:!0}),Object.defineProperty(t,"isRunning",{get(){return e.isRunning},enumerable:!0,configurable:!0}),Object.defineProperty(t,"isCancelled",{get(){return e.isCancelled},enumerable:!0,configurable:!0}),s.cancelFuture=async()=>e.cancelFuture()}function Ky(){return function(t){const e=t;function s(...r){const o=e.apply(this,r)||this;return ed(o),o}return s.prototype=e.prototype,Object.setPrototypeOf(s,e),Object.getOwnPropertyNames(e).forEach(r=>{if(r!=="prototype"&&r!=="length"&&r!=="name"){const o=Object.getOwnPropertyDescriptor(e,r);o&&Object.defineProperty(s,r,o)}}),s}}function Hy(t){return new fs(t)}function zy(t){let e;const s=()=>(e||(e=new fs(t())),e);return{get futureHandler(){return s().futureHandler},get future(){return s().future},get progress(){return s().progress},get status(){return s().status},get isRunning(){return s().isRunning},get isCancelled(){return s().isCancelled},async cancelFuture(){return s().cancelFuture()}}}function Gy(t){return t&&typeof t=="object"&&"futureHandler"in t&&"future"in t&&typeof t.cancelFuture=="function"}function Vy(t){const e=["future","progress","status","isRunning","isCancelled","futureHandler"],s={};for(const r of e){const o=Object.getOwnPropertyDescriptor(t,r);s[r]={exists:r in t,descriptor:o?{enumerable:o.enumerable,configurable:o.configurable,hasGetter:typeof o.get=="function",hasSetter:typeof o.set=="function"}:null,isObservable:t&&typeof t=="object"&&Object.getOwnPropertySymbols(t).some(n=>n.toString().includes("mobx")&&n.toString().includes(r))}}return s}class td{constructor(e,s){l(this,"parent");l(this,"companion");this.companion=e,this.parent=s}getParent(){return this.parent}setupProxy(e={}){const{excludeProperties:s=[],includeLifecycle:r=!1}=e,o=r?[]:["init","load","unload","ready","dispose","destroy","onInit","onLoad","onUnload","onReady","onDispose","onDestroy"],n=["getDependencies","getChildren","update","toJSON","forceUpdate","makeAutoObservable","runInAction","transaction","observe","unobserve","intercept","spy","trace"],i=c=>c==="constructor"||c.startsWith("_")||c.startsWith("__")||o.includes(c)||n.includes(c)||s.includes(c)||c in this.companion,a=this.getAllParentProperties(i);for(const c of a)this.createProxyProperty(c)}getAllParentProperties(e){const s=new Set;Object.getOwnPropertyNames(this.parent).filter(o=>!e(o)).forEach(o=>s.add(o));let r=Object.getPrototypeOf(this.parent);for(;r&&r!==Object.prototype;)Object.getOwnPropertyNames(r).filter(o=>!e(o)).forEach(o=>s.add(o)),r=Object.getPrototypeOf(r);return Array.from(s)}createProxyProperty(e){try{const s=this.parent[e];typeof s=="function"?this.companion[e]=(...r)=>s.apply(this.parent,r):Object.defineProperty(this.companion,e,{get:()=>this.parent[e],set:r=>{this.parent[e]=r},enumerable:!0,configurable:!0})}catch(s){console.debug(`Skipping companion proxy for property ${e}:`,s)}}}function Yy(t,e,s={}){const r=new td(t,e);return t.getParent=()=>r.getParent(),Object.defineProperty(t,"_companionMixin",{value:r,enumerable:!1,configurable:!1,writable:!1}),r.setupProxy(s),r}function sd(t){return t&&typeof t=="object"&&"_companionMixin"in t&&typeof t.getParent=="function"}function rd(t){return sd(t)?t._companionMixin:null}function qy(t){const e=rd(t);if(!e)return{error:"No companion mixin found"};const s=e.getParent(),r=Object.getOwnPropertyNames(t),o=Object.getOwnPropertyNames(s),n=r.filter(i=>o.includes(i)&&i!=="constructor"&&!i.startsWith("_"));return{parentType:s.constructor.name,companionType:t.constructor.name,proxiedProps:n,proxiedCount:n.length}}const Wy=async(t,e)=>{const s=Vo.instance(t).options({}).build(),r=e?`${e}-`:"";return await ae(s),{getState:o=>s.data[`${r}${o}`],updateState:async(o,n)=>{await s.updateState(`${r}${o}`,n)},clean:async()=>{for(const o of s.data.keys)await s.updateState(`${r}${o}`,void 0)},unsubscribe:()=>{He(s)}}},od="kos:service:region",nd="regionId",Qy=`${od}-${nd}`,id=async t=>{const e=Ve.factory(Qy)({path:od,attribute:nd});await ae(e),e.updateProperty(t)},ln="/kos-timer-event",dn="/kos-timer-event/tick",un="defaultTimerEnd",xt=p.createLogger({name:"timer-manager"}),Zy=t=>t.updateProperty!==void 0;class ad{constructor(e,s,r){l(this,"name");l(this,"timeout");l(this,"timer");l(this,"state","inactive");l(this,"decrementValue",1);l(this,"remainingTime");l(this,"timeoutActions",new Map);this.name=e;const o=typeof s=="number"?s:s.value||60;this.timeout=o,this.state="inactive",this.remainingTime=o,Zy(s)&&G(()=>{p.info(`Updating config value timer ${e} with new timeout value ${s.value}`);const n=s.value||60;this.updateTimeout(n)}),this.addTimeoutAction({name:un}),r&&r.forEach(n=>{this.addTimeoutAction(n)})}get id(){return this.name}start(){if(this.state==="active"){xt.debug(`Timer ${this.name} already started`);return}(this.state==="inactive"||this.state==="paused")&&(this.state="active",this.timer=setInterval(()=>this.updateTimer(),1e3))}pause(){this.timer&&(xt.debug(`Pausing timer ${this.name}`),this.state="paused",clearInterval(this.timer))}restart(){this.pause(),this.remainingTime=this.timeout,this.start()}reset(){this.pause(),this.remainingTime=this.timeout,this.state="inactive"}updateTimeout(e){this.timeout=e,this.restart()}addTimeoutAction(e){const s=e.remainingTime??0;this.timeoutActions.has(s)||this.timeoutActions.set(s,[]);const r=e.name,o=this.timeoutActions.get(s).find(n=>n.name===r);o?o.action=e.action:this.timeoutActions.get(s).push(e)}removeTimeoutAction(e){for(const[s,r]of this.timeoutActions.entries()){const o=r.filter(n=>n.name!==e);o.length===0?this.timeoutActions.delete(s):this.timeoutActions.set(s,o)}}updateTimer(){if(this.remainingTime=Math.round((this.remainingTime-this.decrementValue)*100)/100,this.remainingTime<=0){this.state==="active"&&this.executeActions(0),this.pause();return}this.state==="active"&&this.executeActions(this.remainingTime)}executeActions(e){this.timeoutActions.has(e)&&this.timeoutActions.get(e).forEach(s=>{var r;xt.debug(`Executing timer action ${s.name} at ${e}`),(r=s.action)==null||r.call(s,s.name,e),this.notifyTimeoutAction(s),s.singleUse&&(xt.info(`${this.name} Removing single-use action ${s.name}`),this.removeTimeoutAction(s.name))}),this.notifyTick()}notifyTick(){j(`${dn}/${this.name}`,{name:this.name,remainingTime:this.remainingTime})}notifyTimeoutAction(e){j(ln,{name:this.name,action:e.name,remainingTime:this.remainingTime})}}const Pt=new Map,Je=(t,e)=>{const s=Pt.get(t);if(!s){xt.error(`Timer ${t} not found`);return}e(s)},cd={createRelativeTimer(t,e,s){const r=new Date,o=Math.round((e.getTime()-r.getTime())/1e3);return this.createTimer(t,o,s)},createTimer(t,e=60,s){if(Pt.has(t))return Pt.get(t);const r=new ad(t,e,s);return Pt.set(t,r),r},getTimer(t){return Pt.get(t)},clearTimer(t){Je(t,e=>e.pause())},restartTimer(t){Je(t,e=>e.restart())},resetTimer(t){Je(t,e=>e.reset())},addTimeoutAction(t,e){Je(t,s=>s.addTimeoutAction(e))},removeTimeoutAction(t,e){Je(t,s=>s.removeTimeoutAction(e))},startTimer(t){Je(t,e=>e.start())}},ld="kos:service:region:settings",dd="timeZone",Xy=`${ld}-${dd}`,oo=async t=>{const e=Ve.factory(Xy)({path:ld,attribute:dd});await ae(e),e.updateProperty(t)},Jy=t=>!t||!t.data;function hn(t={}){const{alias:e,namespace:s,abortController:r=!1}=t;return(o,n,i)=>{o[Ft]=o[Ft]||{};const a=i.value,c=async function(...d){const u=pt();p.debug(`Calling future service ${n} with tracker ${u}`);let h,g;r&&(h=new AbortController);const m=ze.initiateFuture({tracker:u,id:xo});s&&(m.namespace=s),p.debug(`waiting for future ${m.id} to be ready`),await ae(m),p.debug(`future ${m.id} is ready`),X(()=>{p.debug(`Adding future ${m.id} to futureHandler`),this.futureHandler.addFuture(m,e)}),r&&h&&(g=G(()=>{(m.status==="CANCELLED"||m.endState===xe.Canceled)&&(p.debug(`Future ${m.id} cancelled, aborting request`),h==null||h.abort())}),h.signal.addEventListener("abort",async()=>{if(m.status!=="CANCELLED"&&m.endState!==xe.Canceled&&!m.endState){p.debug(`AbortController aborted, cancelling future ${m.id}`);try{await m.cancelFuture()}catch(v){p.error(`Failed to cancel future ${m.id}:`,v)}}},{once:!0}));const y=()=>{g&&(g(),g=void 0)};try{const v=[...d];if(r&&h){const N=v[v.length-1];N&&typeof N=="object"&&"aborted"in N?v[v.length-1]=h.signal:v.push(h.signal)}v.push(u);const E=await a.apply(this,v);p.debug(`received future response for ${u}`,E);const _=Jy(E)?E:E==null?void 0:E.data;return _?(_.progress=1,p.debug("mapping future response to future model"),m.endState?p.debug(`future ${m.id} has already completed. Not updating the model`):Bo(_,m)):this.futureHandler.removeFuture(e),y(),_}catch(v){if(y(),r&&(h!=null&&h.signal.aborted)){const E=new Error("Operation cancelled");throw p.debug(`Operation ${n} was cancelled`),E}throw p.error(v),v}};o[Ft][n]={handler:c}}}const eb=({path:t})=>(e,s)=>{e[F]=e[F]||{},e[F][s]={modelType:es.type,id:`${es.type}-${t}`,options:{path:t},lifecycle:H.INIT}};function tb(t){const{path:e,attribute:s}=t;return(r,o)=>{r[F]=r[F]||{},r[F][o]={modelType:Qo.type,id:`${e}-${s}`,options:{path:e,attribute:s},lifecycle:H.INIT}}}const st=p.createLogger({name:"services",group:"Services"}),sb=async(t,e)=>ud(t,e,`${exports.BASE_URL}/api/server/login`),ud=async(t,e,s=`${exports.BASE_URL}/api/login`)=>{const r=await exports.kosFetch(`${s}`,{method:"POST",destinationAddress:"",body:JSON.stringify({email:t,password:e})});if(!r.ok){const n=await r.json();throw Error(`${n==null?void 0:n.error}`)}return await r.json()},rb=async t=>hd(t,`${exports.BASE_URL}/api/server/startPasswordReset`,""),hd=async(t,e=`${exports.BASE_URL}/api/startPasswordReset`,s="server")=>{const r=await exports.kosFetch(`${e}?email=${t}`,{method:"POST",destinationAddress:s});if(!r.ok)throw Error(`There was a problem reseting config; returned status ${r.status}`);return await r.json()},ob=async(t,e)=>fd(t,e,`${exports.BASE_URL}/api/server/resetPassword`),fd=async(t,e,s=`${exports.BASE_URL}/api/resetPassword`)=>{st.debug(`resetting password with token ${t} and password ${e.replace(/./g,"*")}`);const r=await exports.kosFetch(`${s}`,{method:"POST",destinationAddress:"",body:JSON.stringify({token:t,password:e})});if(st.debug(`password reset returned status ${r.status}`),!r.ok){st.error(`password reset failed with message ${r.statusText}`);const n=await r.json();throw Error(`${n==null?void 0:n.error}:There was a problem resetting the password.`)}return await r.json()},nb=async(t,e,s)=>gd(t,e,s,`${exports.BASE_URL}/api/server/acceptInvite`),gd=async(t,e,s,r=`${exports.BASE_URL}/api/server/acceptInvite`)=>{st.debug(`accepting invite with token ${t} and password ${e.replace(/./g,"*")}`);const o=await exports.kosFetch(`${r}`,{method:"POST",destinationAddress:"",body:JSON.stringify({token:t,password:e,name:s})});if(st.debug(`invitation accept returned status ${o.status}`),!o.ok){st.error(`invite failed with message ${o.statusText}`);const i=await o.json();throw Error(`${i==null?void 0:i.error}:There was a problem accepting the invite.`)}return await o.json()};function ib(t,e,s,r){const o=t instanceof Promise?{promise:t,abortController:e,cancelFuture:s,future:r}:t,{promise:n,abortController:i,cancelFuture:a,future:c}=o,d=n;let u=0,h="PENDING",g=!0;const m=new Set;let y;return c&&typeof c=="object"&&(y=M.autorun(()=>{const v=c.progress||0,E=c.status||"PENDING",_=!c.endState;(v!==u||E!==h||_!==g)&&(u=v,h=E,g=_,m.forEach(N=>{try{N(u,h)}catch(x){console.warn("Progress callback error:",x)}}))})),n.finally(()=>{g=!1,i!=null&&i.signal.aborted||(h="COMPLETED",m.forEach(v=>{try{v(u,h)}catch(E){console.warn("Progress callback error:",E)}})),y&&y(),m.clear()}),d.cancel=async()=>{i&&!i.signal.aborted&&i.abort(),a&&await a(),g=!1,h="CANCELLED",m.forEach(v=>{try{v(u,h)}catch(E){console.warn("Progress callback error:",E)}}),y&&y()},d.getController=()=>i,d.isCancelled=()=>(i==null?void 0:i.signal.aborted)??!1,Object.defineProperty(d,"progress",{get:()=>u,enumerable:!0}),Object.defineProperty(d,"status",{get:()=>h,enumerable:!0}),Object.defineProperty(d,"isRunning",{get:()=>g,enumerable:!0}),d.onProgressUpdate=v=>(m.add(v),v(u,h),()=>m.delete(v)),d}const ab=je.keyframes`
111
+ `,i=this.compileShader(r.VERTEX_SHADER,o),a=this.compileShader(r.FRAGMENT_SHADER,n);this.program=this.createProgram(i,a),this.posBuffer=r.createBuffer(),r.bindBuffer(r.ARRAY_BUFFER,this.posBuffer),r.bufferData(r.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),r.STATIC_DRAW),this.aPosition=r.getAttribLocation(this.program,"a_position"),this.uMinHue=r.getUniformLocation(this.program,"minHue"),this.uMaxHue=r.getUniformLocation(this.program,"maxHue"),this.uHueOffset=r.getUniformLocation(this.program,"hueOffset"),this.uGridHeight=r.getUniformLocation(this.program,"gridHeight")}reset(){this.hueOffset=0,this.lastUpdate=performance.now()}renderFrame(s,r){const o=this.gl;if(this.canvas.width=s,this.canvas.height=r,this.shouldStep(50)){const n=this.speedPx/r;this.hueOffset=(this.hueOffset+n)%1}o.viewport(0,0,s,r),o.clear(o.COLOR_BUFFER_BIT),o.useProgram(this.program),o.enableVertexAttribArray(this.aPosition),o.bindBuffer(o.ARRAY_BUFFER,this.posBuffer),o.vertexAttribPointer(this.aPosition,2,o.FLOAT,!1,0,0),o.uniform1f(this.uMinHue,this.minHue/360),o.uniform1f(this.uMaxHue,this.maxHue/360),o.uniform1f(this.uHueOffset,this.hueOffset),o.uniform1f(this.uGridHeight,r),o.drawArrays(o.TRIANGLES,0,6)}compileShader(s,r){const o=this.gl.createShader(s);if(this.gl.shaderSource(o,r),this.gl.compileShader(o),!this.gl.getShaderParameter(o,this.gl.COMPILE_STATUS))throw new Error(this.gl.getShaderInfoLog(o)||"Shader compile failed");return o}createProgram(s,r){const o=this.gl.createProgram();if(this.gl.attachShader(o,s),this.gl.attachShader(o,r),this.gl.linkProgram(o),!this.gl.getProgramParameter(o,this.gl.LINK_STATUS))throw new Error("Program linking failed");return o}}class qe{constructor(){l(this,"canvas");l(this,"ctx");l(this,"lastUpdate",0);this.canvas=document.createElement("canvas");const e=this.canvas.getContext("2d");if(!e)throw new Error("2D canvas not supported");this.ctx=e}dispose(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.remove()}shouldStep(e){const s=performance.now();return s-this.lastUpdate>=e?(this.lastUpdate=s,!0):!1}readPixels(e,s){return this.ctx.getImageData(0,0,e,s).data}}function an(t){class e extends t{constructor(){super(...arguments);l(this,"doneCallback",null);l(this,"oneShotDone",!1)}isOneShot(){return!0}onDone(o){this.doneCallback=o}signalDoneIfNeeded(){var o;this.oneShotDone||((o=this.doneCallback)==null||o.call(this),this.oneShotDone=!0)}resetOneShot(){this.doneCallback=null,this.oneShotDone=!1}get isOneShotDone(){return this.oneShotDone}}return e}const Wm=an(qe);class Qm extends Wm{constructor({colors:s=["red","yellow","green"],direction:r="horizontal",speed:o=2,loop:n=!0}={}){super();l(this,"offset",0);l(this,"speed");l(this,"colors");l(this,"direction");l(this,"loop");this.colors=s,this.direction=r,this.speed=o,this.loop=n}reset(){this.offset=0,this.lastUpdate=performance.now(),this.loop||this.resetOneShot()}renderFrame(s,r){if(!this.loop&&this.isOneShotDone)return;this.loop&&this.shouldStep(50)&&(this.offset+=this.speed);const o=this.loop?-this.offset:0,n=this.loop?s*2-this.offset:s,i=this.ctx.createLinearGradient(o,0,n,0),a=1/(this.colors.length-1);this.colors.forEach((c,d)=>{i.addColorStop(d*a,c)}),this.ctx.fillStyle=i,this.ctx.fillRect(0,0,s,r),!this.loop&&!this.isOneShotDone&&this.signalDoneIfNeeded()}}const Zm=an(qe);class Al extends Zm{constructor({src:s}){super();l(this,"img");l(this,"loaded",!1);this.img=new Image,this.img.src=s,this.img.crossOrigin="anonymous",this.img.onload=()=>{this.loaded=!0}}reset(){this.resetOneShot()}renderFrame(s,r){!this.loaded||this.isOneShotDone||(this.canvas.width=s,this.canvas.height=r,this.ctx.drawImage(this.img,0,0,s,r),this.signalDoneIfNeeded())}}class Xm extends Rl{constructor(s){super(s);l(this,"loopConfig");l(this,"currentLoopCount",0);l(this,"startTime");l(this,"endTime");l(this,"completionCallback",null);this.loopConfig=s.loop??!1,this.startTime=s.startTime??0,this.endTime=s.endTime??null,this.video.removeEventListener("ended",this.handleEnded),this.video.addEventListener("ended",this.handleVideoEnd.bind(this)),this.startTime>0&&(this.video.currentTime=this.startTime),this.endTime!==null&&this.video.addEventListener("timeupdate",this.handleTimeUpdate.bind(this))}handleTimeUpdate(){this.endTime!==null&&this.video.currentTime>=this.endTime&&this.handleVideoEnd()}handleVideoEnd(){this.loopConfig===!0?(this.video.currentTime=this.startTime,this.video.play().catch(console.warn)):typeof this.loopConfig=="number"&&this.currentLoopCount<this.loopConfig-1?(this.currentLoopCount++,this.video.currentTime=this.startTime,this.video.play().catch(console.warn)):(this.video.pause(),this.completionCallback&&this.completionCallback())}reset(){super.reset(),this.currentLoopCount=0,this.video.currentTime=this.startTime}onDone(s){this.completionCallback=s}isOneShot(){return this.loopConfig===!1||this.loopConfig===1}dispose(){this.video.removeEventListener("ended",this.handleVideoEnd),this.video.removeEventListener("timeupdate",this.handleTimeUpdate),this.completionCallback=null,super.dispose()}}function Jm(t){const e=t.replace("#","");if(!/^[0-9A-Fa-f]{3}$|^[0-9A-Fa-f]{6}$/.test(e))throw new Error(`Invalid hex color: ${t}`);let s,r,o;return e.length===3?(s=parseInt(e[0]+e[0],16),r=parseInt(e[1]+e[1],16),o=parseInt(e[2]+e[2],16)):(s=parseInt(e.substring(0,2),16),r=parseInt(e.substring(2,4),16),o=parseInt(e.substring(4,6),16)),{r:s,g:r,b:o}}function xl(t){return typeof t=="string"?Jm(t):t}function er(t){const e=xl(t);return`rgb(${e.r},${e.g},${e.b})`}class ey extends qe{constructor(s={}){super();l(this,"columns",[]);l(this,"fallChance");l(this,"speed");l(this,"baseColor");l(this,"trailColors");this.speed=s.speed??1,this.fallChance=s.fallChance??.7,s.baseColor?this.baseColor=xl(s.baseColor):this.baseColor={r:0,g:255,b:255},this.trailColors=this.calculateTrailColors()}calculateTrailColors(){const r=[];for(let o=0;o<=5;o++){const n=1-o/5*.6;r.push({r:Math.floor(this.baseColor.r*n),g:Math.floor(this.baseColor.g*n),b:Math.floor(this.baseColor.b*n)})}return r}reset(){this.columns=[],this.lastUpdate=performance.now()}renderFrame(s,r){this.columns.length!==s&&(this.columns=Array(s).fill(0).map(()=>Math.floor(Math.random()*r))),this.shouldStep(50)&&(this.columns=this.columns.map(i=>i>r+5?0:i+(Math.random()<this.fallChance?this.speed:0)));const o=this.ctx.createImageData(s,r),n=o.data;n.fill(0);for(let i=0;i<r;i++)for(let a=0;a<s;a++){const c=this.columns[a];let d=0,u=0,h=0;if(i===c)d=this.baseColor.r,u=this.baseColor.g,h=this.baseColor.b;else if(i<c&&i>c-this.trailColors.length){const m=c-i;if(m<this.trailColors.length){const y=this.trailColors[m];d=y.r,u=y.g,h=y.b}}const g=(i*s+a)*4;n[g]=d,n[g+1]=u,n[g+2]=h,n[g+3]=255}this.ctx.putImageData(o,0,0)}}class ty{constructor(e,s){l(this,"baseRenderer");l(this,"overlayIcons",new Map);l(this,"overlayConfigs");l(this,"loadedIcons",new Set);l(this,"canvas");l(this,"ctx");l(this,"persistOverlaysOnComplete");l(this,"baseRendererCompleted",!1);l(this,"completionCallback",null);l(this,"hasSignaledCompletion",!1);this.baseRenderer=s(e.baseRenderer.type,e.baseRenderer.data),this.overlayConfigs=e.overlays,this.persistOverlaysOnComplete=e.persistOverlaysOnComplete!==!1,this.canvas=document.createElement("canvas");const r=this.canvas.getContext("2d");if(!r)throw new Error("2D canvas not supported");this.ctx=r,this.loadOverlayImages(),"onDone"in this.baseRenderer&&typeof this.baseRenderer.onDone=="function"&&this.baseRenderer.onDone(()=>{this.baseRendererCompleted=!0,!this.persistOverlaysOnComplete&&this.completionCallback&&this.completionCallback()})}async loadOverlayImages(){for(const e of this.overlayConfigs){const s=new Image;s.crossOrigin="anonymous",s.onload=()=>{this.loadedIcons.add(e.src)},s.onerror=r=>{console.error(`Failed to load overlay image: ${e.src}`,r)},s.src=e.src,this.overlayIcons.set(e.src,s)}}calculateOverlayPosition(e,s,r){let o,n;if(typeof e.position=="string")switch(e.position){case"top-left":o=0,n=0;break;case"top-center":o=(s-e.size)/2,n=0;break;case"top-right":o=s-e.size,n=0;break;case"center-left":o=0,n=(r-e.size)/2;break;case"center":o=(s-e.size)/2,n=(r-e.size)/2;break;case"center-right":o=s-e.size,n=(r-e.size)/2;break;case"bottom-left":o=0,n=r-e.size;break;case"bottom-center":o=(s-e.size)/2,n=r-e.size;break;case"bottom-right":o=s-e.size,n=r-e.size;break;default:o=0,n=0}else o=e.position.x,n=e.position.y;return e.offset&&(o+=e.offset.x||0,n+=e.offset.y||0),{x:o,y:n}}reset(){this.baseRenderer.reset(),this.baseRendererCompleted=!1,this.hasSignaledCompletion=!1}renderFrame(e,s){if(this.canvas.width=e,this.canvas.height=s,this.ctx.clearRect(0,0,e,s),this.baseRendererCompleted&&this.persistOverlaysOnComplete)this.renderOverlays(e,s);else{this.baseRenderer.renderFrame(e,s);const r=this.baseRenderer.readPixels(e,s);if(r&&r.length>0){const o=new ImageData(r,e,s);this.ctx.putImageData(o,0,0)}this.renderOverlays(e,s)}}renderOverlays(e,s){for(const r of this.overlayConfigs){if(!r.persistent&&r.persistent!==void 0)continue;const o=this.overlayIcons.get(r.src);if(!o||!this.loadedIcons.has(r.src))continue;const n=this.calculateOverlayPosition(r,e,s);this.ctx.save(),r.opacity!==void 0&&(this.ctx.globalAlpha=Math.max(0,Math.min(1,r.opacity))),this.ctx.drawImage(o,n.x,n.y,r.size,r.size),this.ctx.restore()}}readPixels(e,s){return this.ctx.getImageData(0,0,e,s).data}play(){this.baseRenderer.play&&this.baseRenderer.play()}pause(){this.baseRenderer.pause&&this.baseRenderer.pause()}dispose(){this.overlayIcons.clear(),this.loadedIcons.clear(),this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.remove(),this.baseRenderer.dispose&&this.baseRenderer.dispose()}onDone(e){this.completionCallback=e,this.hasSignaledCompletion&&e()}isOneShot(){return this.persistOverlaysOnComplete?!1:"isOneShot"in this.baseRenderer&&typeof this.baseRenderer.isOneShot=="function"?this.baseRenderer.isOneShot():!1}}class Pl extends qe{constructor(s){super();l(this,"img");l(this,"loaded",!1);l(this,"scrollConfig");l(this,"loopConfig");l(this,"duration");l(this,"pauseDuration");l(this,"colorOverride");l(this,"originalSvgData",null);l(this,"position",0);l(this,"startTime",0);l(this,"lastFrameTime",0);l(this,"currentLoopCount",0);l(this,"completionCallback",null);l(this,"isPlaying",!1);l(this,"completed",!1);l(this,"isPaused",!1);l(this,"pauseStartTime",0);this.img=new Image,this.img.crossOrigin="anonymous",this.scrollConfig=s.scroll,this.loopConfig=s.loop??!1,this.duration=s.duration,this.pauseDuration=s.pauseBetweenLoops??0,this.colorOverride=s.colorOverride,this.colorOverride&&s.src.toLowerCase().includes(".svg")?this.loadAndProcessSvg(s.src):this.img.src=s.src,this.img.onload=()=>{this.loaded=!0},this.img.onerror=r=>{console.error("Failed to load image:",r)}}reset(){this.position=0,this.startTime=performance.now(),this.lastFrameTime=this.startTime,this.currentLoopCount=0,this.completed=!1,this.isPlaying=!1,this.isPaused=!1,this.pauseStartTime=0}play(){this.isPlaying||(this.isPlaying=!0,this.startTime=performance.now(),this.lastFrameTime=this.startTime)}pause(){this.isPlaying=!1}renderFrame(s,r){var a;if(!this.loaded||this.completed)return;if(this.isPaused){this.canvas.width=s,this.canvas.height=r,this.ctx.clearRect(0,0,s,r),this.pauseDuration>0&&performance.now()-this.pauseStartTime>=this.pauseDuration&&(this.isPaused=!1,this.position=0,this.startTime=performance.now(),this.lastFrameTime=this.startTime);return}if(this.canvas.width=s,this.canvas.height=r,this.ctx.clearRect(0,0,s,r),!((a=this.scrollConfig)!=null&&a.enabled)){this.ctx.drawImage(this.img,0,0,s,r),this.duration&&this.isPlaying&&performance.now()-this.startTime>=this.duration&&this.handleCompletion();return}const o=this.scrollConfig.direction||"left",n=this.scrollConfig.speed||50,i=this.scrollConfig.gap||0;if(this.isPlaying){const c=performance.now(),d=(c-this.lastFrameTime)/1e3;this.lastFrameTime=c;const u=n*d;switch(o){case"left":this.position+=u;break;case"right":this.position+=u;break;case"up":this.position+=u;break;case"down":this.position+=u;break}}this.drawScrollingImage(s,r,o,i),this.checkScrollCompletion(s,r,o,i)}drawScrollingImage(s,r,o,n){var h,g,m,y,v,E,_,N,x;const i=this.img.width/this.img.height;let a,c;((h=this.scrollConfig)==null?void 0:h.maintainAspectRatio)!==!1?(g=this.scrollConfig)!=null&&g.height?(c=this.scrollConfig.height,a=c*i):(m=this.scrollConfig)!=null&&m.width?(a=this.scrollConfig.width,c=a/i):o==="left"||o==="right"?(c=r,a=c*i):(a=s,c=a/i):(a=((y=this.scrollConfig)==null?void 0:y.width)||s,c=((v=this.scrollConfig)==null?void 0:v.height)||r);let d,u;switch(o==="left"||o==="right"?(d=0,((E=this.scrollConfig)==null?void 0:E.offsetY)==="center"||((_=this.scrollConfig)==null?void 0:_.offsetY)===void 0?u=(r-c)/2:u=this.scrollConfig.offsetY):(((N=this.scrollConfig)==null?void 0:N.offsetX)==="center"||((x=this.scrollConfig)==null?void 0:x.offsetX)===void 0?d=(s-a)/2:d=this.scrollConfig.offsetX,u=0),o){case"left":{const D=s-this.position;if(D<s&&D>-a&&this.ctx.drawImage(this.img,D,u,a,c),this.loopConfig&&this.pauseDuration===0&&this.position>n){const P=D+a+n;P<s&&this.ctx.drawImage(this.img,P,u,a,c)}break}case"right":{const D=-a+this.position;if(D>-a&&D<s&&this.ctx.drawImage(this.img,D,u,a,c),this.loopConfig&&this.pauseDuration===0&&D-n-a>-a){const P=D-a-n;P<s&&this.ctx.drawImage(this.img,P,u,a,c)}break}case"up":{const D=r-this.position;if(D>-c&&D<r&&this.ctx.drawImage(this.img,d,D,a,c),this.loopConfig&&this.pauseDuration===0&&D+c+n<r){const P=D+c+n;P>-c&&this.ctx.drawImage(this.img,d,P,a,c)}break}case"down":{const D=-c+this.position;if(D>-c&&D<r&&this.ctx.drawImage(this.img,d,D,a,c),this.loopConfig&&this.pauseDuration===0&&D-n-c>-c){const P=D-c-n;P<r&&this.ctx.drawImage(this.img,d,P,a,c)}break}}}checkScrollCompletion(s,r,o,n){var h,g,m,y,v;if(!this.isPlaying)return;const i=this.img.width/this.img.height;let a,c;switch(((h=this.scrollConfig)==null?void 0:h.maintainAspectRatio)!==!1?(g=this.scrollConfig)!=null&&g.height?(c=this.scrollConfig.height,a=c*i):(m=this.scrollConfig)!=null&&m.width?(a=this.scrollConfig.width,c=a/i):o==="left"||o==="right"?(c=r,a=c*i):(a=s,c=a/i):(a=((y=this.scrollConfig)==null?void 0:y.width)||s,c=((v=this.scrollConfig)==null?void 0:v.height)||r),o){case"left":case"right":this.loopConfig;break;case"up":case"down":this.loopConfig;break}let d=!1;const u=1;switch(o){case"left":d=s-this.position<-a-u;break;case"right":d=-a+this.position>s+u;break;case"up":d=r-this.position<-c-u;break;case"down":d=-c+this.position>r+u;break}d&&(this.loopConfig===!1||typeof this.loopConfig=="number"&&this.loopConfig===1?this.handleCompletion():typeof this.loopConfig=="number"&&this.loopConfig>1?(this.currentLoopCount++,this.currentLoopCount>=this.loopConfig?this.handleCompletion():this.startPauseOrNextLoop()):this.loopConfig===!0&&this.startPauseOrNextLoop())}startPauseOrNextLoop(){this.pauseDuration>0?(this.isPaused=!0,this.pauseStartTime=performance.now()):this.position=0}handleCompletion(){this.completed=!0,this.isPlaying=!1,this.completionCallback&&this.completionCallback()}onDone(s){this.completionCallback=s}isOneShot(){var s;return!((s=this.scrollConfig)!=null&&s.enabled)&&!this.loopConfig}async loadAndProcessSvg(s){try{const o=await(await fetch(s)).text();this.originalSvgData=o;const n=this.applySvgColorOverride(o),i=`data:image/svg+xml;base64,${btoa(n)}`;this.img.src=i}catch(r){console.error("Failed to load and process SVG:",r),this.img.src=s}}applySvgColorOverride(s){if(!this.colorOverride)return s;const r=er(this.colorOverride);return s.replace(/fill\s*=\s*["'][^"']*["']/gi,`fill="${r}"`).replace(/fill\s*:\s*[^;"]*/gi,`fill:${r}`).replace(/stroke\s*=\s*["'][^"']*["']/gi,`stroke="${r}"`).replace(/stroke\s*:\s*[^;"]*/gi,`stroke:${r}`)}dispose(){this.img.removeAttribute("src"),this.completionCallback=null,this.originalSvgData=null}}class sy extends qe{constructor(s){super();l(this,"text");l(this,"lines");l(this,"fontSize");l(this,"fontFamily");l(this,"lineHeight");l(this,"textColor");l(this,"scrollConfig");l(this,"loopConfig");l(this,"duration");l(this,"pauseDuration");l(this,"position",0);l(this,"startTime",0);l(this,"lastFrameTime",0);l(this,"currentLoopCount",0);l(this,"completionCallback",null);l(this,"isPlaying",!1);l(this,"completed",!1);l(this,"isPaused",!1);l(this,"pauseStartTime",0);l(this,"textWidth",0);l(this,"textHeight",0);l(this,"lineWidths",[]);l(this,"textMeasured",!1);this.text=s.text,this.lines=s.text.split(`
112
+ `),this.fontSize=s.fontSize??8,this.lineHeight=s.lineHeight??this.fontSize+2,this.fontFamily=s.fontFamily??"monospace, 'Lucida Console', 'Courier New', Courier",this.scrollConfig=s.scroll,this.loopConfig=s.loop??!1,this.duration=s.duration,this.pauseDuration=s.pauseBetweenLoops??0,s.color?this.textColor=er(s.color):this.textColor="rgb(255,255,255)"}measureText(){if(this.textMeasured)return;this.ctx.font=`${this.fontSize}px ${this.fontFamily}`,this.lineWidths=[];let s=0;for(const r of this.lines){const n=this.ctx.measureText(r).width;this.lineWidths.push(n),s=Math.max(s,n)}this.textWidth=s,this.textHeight=this.lines.length*this.lineHeight,this.textMeasured=!0}reset(){this.position=0,this.startTime=performance.now(),this.lastFrameTime=this.startTime,this.currentLoopCount=0,this.completed=!1,this.isPlaying=!1,this.isPaused=!1,this.pauseStartTime=0,this.textMeasured=!1,this.lineWidths=[]}play(){this.isPlaying||(this.isPlaying=!0,this.startTime=performance.now(),this.lastFrameTime=this.startTime)}pause(){this.isPlaying=!1}renderFrame(s,r){var a;if(this.canvas.width=s,this.canvas.height=r,this.measureText(),this.completed)return;if(this.isPaused){this.ctx.clearRect(0,0,s,r),this.pauseDuration>0&&performance.now()-this.pauseStartTime>=this.pauseDuration&&(this.isPaused=!1,this.position=0,this.startTime=performance.now(),this.lastFrameTime=this.startTime);return}if(this.ctx.clearRect(0,0,s,r),!((a=this.scrollConfig)!=null&&a.enabled)){this.drawStaticText(s,r),this.duration&&this.isPlaying&&performance.now()-this.startTime>=this.duration&&this.handleCompletion();return}const o=this.scrollConfig.direction||"left",n=this.scrollConfig.speed||50,i=this.scrollConfig.gap||0;if(this.isPlaying){const c=performance.now(),d=(c-this.lastFrameTime)/1e3;this.lastFrameTime=c;const u=n*d;switch(o){case"left":case"right":case"up":case"down":this.position+=u;break}}this.drawScrollingText(s,r,o,i),this.checkScrollCompletion(s,r,o)}drawStaticText(s,r){this.ctx.font=`${this.fontSize}px ${this.fontFamily}`,this.ctx.fillStyle=this.textColor,this.ctx.textBaseline="top";const o=this.textHeight;let n=(r-o)/2;for(let i=0;i<this.lines.length;i++){const a=this.lines[i],c=this.lineWidths[i],d=(s-c)/2,u=n+i*this.lineHeight;this.ctx.fillText(a,d,u)}}drawScrollingText(s,r,o,n){var c,d,u,h;this.ctx.font=`${this.fontSize}px ${this.fontFamily}`,this.ctx.fillStyle=this.textColor,this.ctx.textBaseline="top";let i,a;o==="left"||o==="right"?(i=0,((c=this.scrollConfig)==null?void 0:c.offsetY)==="center"||((d=this.scrollConfig)==null?void 0:d.offsetY)===void 0?a=(r-this.textHeight)/2:a=this.scrollConfig.offsetY):(((u=this.scrollConfig)==null?void 0:u.offsetX)==="center"||((h=this.scrollConfig)==null?void 0:h.offsetX)===void 0?(i=s/2,this.ctx.textAlign="center"):(i=this.scrollConfig.offsetX,this.ctx.textAlign="left"),a=0),this.drawMultiLineScrollText(o,s,r,n,i,a)}drawMultiLineScrollText(s,r,o,n,i,a){switch(s){case"left":{const c=r-this.position;if(c<r&&c>-this.textWidth&&this.drawTextBlock(c,a,"left"),this.loopConfig&&this.pauseDuration===0&&this.position>n){const d=c+this.textWidth+n;d<r&&this.drawTextBlock(d,a,"left")}break}case"right":{const c=-this.textWidth+this.position;if(c>-this.textWidth&&c<r&&this.drawTextBlock(c,a,"left"),this.loopConfig&&this.pauseDuration===0&&c-n-this.textWidth>-this.textWidth){const d=c-this.textWidth-n;d<r&&this.drawTextBlock(d,a,"left")}break}case"up":{const c=o-this.position;if(c>-this.textHeight&&c<o&&this.drawTextBlock(i,c,"center"),this.loopConfig&&this.pauseDuration===0&&c+this.textHeight+n<o){const d=c+this.textHeight+n;d>-this.textHeight&&this.drawTextBlock(i,d,"center")}break}case"down":{const c=-this.textHeight+this.position;if(c>-this.textHeight&&c<o&&this.drawTextBlock(i,c,"center"),this.loopConfig&&this.pauseDuration===0&&c-n-this.textHeight>-this.textHeight){const d=c-this.textHeight-n;d<o&&this.drawTextBlock(i,d,"center")}break}}}drawTextBlock(s,r,o){for(let n=0;n<this.lines.length;n++){const i=this.lines[n],a=this.lineWidths[n];let c;o==="center"?c=s-a/2:c=s;const d=r+n*this.lineHeight;this.ctx.fillText(i,c,d)}}checkScrollCompletion(s,r,o){if(!this.isPlaying)return;let n=!1;const i=1;switch(o){case"left":n=s-this.position<-this.textWidth-i;break;case"right":n=-this.textWidth+this.position>s+i;break;case"up":n=r-this.position<-this.textHeight-i;break;case"down":n=-this.textHeight+this.position>r+i;break}n&&(this.loopConfig===!1||typeof this.loopConfig=="number"&&this.loopConfig===1?this.handleCompletion():typeof this.loopConfig=="number"&&this.loopConfig>1?(this.currentLoopCount++,this.currentLoopCount>=this.loopConfig?this.handleCompletion():this.startPauseOrNextLoop()):this.loopConfig===!0&&this.startPauseOrNextLoop())}startPauseOrNextLoop(){this.pauseDuration>0?(this.isPaused=!0,this.pauseStartTime=performance.now()):this.position=0}handleCompletion(){this.completed=!0,this.isPlaying=!1,this.completionCallback&&this.completionCallback()}onDone(s){this.completionCallback=s}isOneShot(){var s;return!((s=this.scrollConfig)!=null&&s.enabled)&&!this.loopConfig}dispose(){this.completionCallback=null}}class ry{constructor(e){l(this,"patterns");l(this,"currentPatternIndex",0);l(this,"currentRenderer",null);l(this,"loopConfig");l(this,"currentLoopCount",0);l(this,"transitionDuration");l(this,"patternOverrides");l(this,"completionCallback",null);l(this,"patternStore");l(this,"canvas");l(this,"ctx");l(this,"width",0);l(this,"height",0);this.patterns=e.patterns,this.loopConfig=e.loop??!1,this.transitionDuration=e.transitionDuration??0,this.patternOverrides=e.patternOverrides??{},this.patternStore=e.patternStore??new Map,this.canvas=document.createElement("canvas");const s=this.canvas.getContext("2d");if(!s)throw new Error("2D canvas not supported");if(this.ctx=s,this.patterns.length===0)throw new Error("SequenceRenderer requires at least one pattern");this.loadCurrentPattern()}loadCurrentPattern(){var n,i,a,c;const e=this.patterns[this.currentPatternIndex],s=this.patternStore.get(e);if(!s){console.warn(`Pattern "${e}" not found in store, skipping`),this.moveToNextPattern();return}this.currentRenderer&&((i=(n=this.currentRenderer).dispose)==null||i.call(n));const r=this.patternOverrides[e]??{},o={...s.data,...r};try{this.currentRenderer=tr({mode:s.type,data:o}),this.currentRenderer&&this.isDoneAware(this.currentRenderer)&&this.currentRenderer.onDone(()=>{this.handlePatternComplete()}),this.currentRenderer&&(this.currentRenderer.reset(),(c=(a=this.currentRenderer).play)==null||c.call(a),this.width>0&&this.height>0&&this.currentRenderer.renderFrame(this.width,this.height))}catch(d){console.error(`Failed to create renderer for pattern "${e}":`,d),this.moveToNextPattern()}}isDoneAware(e){return typeof(e==null?void 0:e.onDone)=="function"}handlePatternComplete(){this.transitionDuration>0?setTimeout(()=>{this.moveToNextPattern()},this.transitionDuration):this.moveToNextPattern()}moveToNextPattern(){this.currentPatternIndex++,this.currentPatternIndex>=this.patterns.length?this.loopConfig===!0?(this.currentPatternIndex=0,this.loadCurrentPattern()):typeof this.loopConfig=="number"&&this.currentLoopCount<this.loopConfig-1?(this.currentLoopCount++,this.currentPatternIndex=0,this.loadCurrentPattern()):this.completionCallback&&this.completionCallback():this.loadCurrentPattern()}reset(){this.currentPatternIndex=0,this.currentLoopCount=0,this.loadCurrentPattern()}play(){var e,s;(s=(e=this.currentRenderer)==null?void 0:e.play)==null||s.call(e)}pause(){var e,s;(s=(e=this.currentRenderer)==null?void 0:e.pause)==null||s.call(e)}renderFrame(e,s){this.width=e,this.height=s,this.canvas.width=e,this.canvas.height=s,this.currentRenderer&&this.currentRenderer.renderFrame(e,s)}readPixels(e,s){return this.currentRenderer?this.currentRenderer.readPixels(e,s):this.ctx.getImageData(0,0,e,s).data}onDone(e){this.completionCallback=e}isOneShot(){var e,s;return this.loopConfig===!1||this.loopConfig===1?this.patterns.length===1&&this.currentRenderer?((s=(e=this.currentRenderer).isOneShot)==null?void 0:s.call(e))??!1:!0:!1}dispose(){var e,s;this.currentRenderer&&((s=(e=this.currentRenderer).dispose)==null||s.call(e)),this.completionCallback=null}setPatternStore(e){this.patternStore=e,this.patterns.length>0&&this.loadCurrentPattern()}}const oy=an(qe);class ny extends oy{constructor(s={r:0,g:0,b:0}){super();l(this,"color");let r;s.color!==void 0?r=s.color:s.r!==void 0&&s.g!==void 0&&s.b!==void 0?r={r:s.r,g:s.g,b:s.b}:r={r:0,g:0,b:0},this.color=er(r)}setColor(s){this.color=er(s),this.resetOneShot()}reset(){this.resetOneShot()}renderFrame(s,r){this.isOneShotDone||(this.canvas.width=s,this.canvas.height=r,this.ctx.fillStyle=this.color,this.ctx.fillRect(0,0,s,r),this.signalDoneIfNeeded())}}class iy extends qe{constructor({minHue:s=0,maxHue:r=360,speed:o=1}={}){super();l(this,"offset",0);l(this,"minHue");l(this,"maxHue");l(this,"speed");this.minHue=s,this.maxHue=r,this.speed=o}reset(){this.offset=0,this.lastUpdate=performance.now()}hslToRgb(s,r,o){let n,i,a;if(r===0)n=i=a=o;else{const c=(h,g,m)=>(m<0&&(m+=1),m>1&&(m-=1),m<.16666666666666666?h+(g-h)*6*m:m<.5?g:m<.6666666666666666?h+(g-h)*(.6666666666666666-m)*6:h),d=o<.5?o*(1+r):o+r-o*r,u=2*o-d;n=c(u,d,s+1/3),i=c(u,d,s),a=c(u,d,s-1/3)}return[Math.round(n*255),Math.round(i*255),Math.round(a*255)]}renderFrame(s,r){this.shouldStep(50)&&(this.offset=(this.offset+this.speed)%s);const o=this.ctx.createImageData(s,r),n=o.data;let i=0;for(let a=0;a<r;a++)for(let c=0;c<s;c++){const d=(c+this.offset)%s/s,u=this.minHue/360+d*((this.maxHue-this.minHue)/360),[h,g,m]=this.hslToRgb(u,1,.5);n[i++]=h,n[i++]=g,n[i++]=m,n[i++]=255}this.ctx.putImageData(o,0,0)}}const Xn=new Map;is(Q,{register(t,e){Xn.set(t,e)},execute(t,e){const s=Xn.get(t);return s?new s(e):null}});S.canvas.registerRenderer("video",Xm);S.canvas.registerRenderer("video-basic",Rl);S[Q].register("image-static",Al);S[Q].register("image-scrolling",Pl);const ay=class{constructor(t){var e;return(e=t.scroll)!=null&&e.enabled?new Pl(t):new Al(t)}};S[Q].register("image",ay);S[Q].register("color",ny);S[Q].register("matrix",ey);S[Q].register("sweep",iy);S[Q].register("gradient",Qm);S[Q].register("drop",qm);S[Q].register("sequence",ry);S[Q].register("text",sy);const cy=class{constructor(t){const e=(s,r)=>{const o=tr({mode:s,data:r});if(!o)throw new Error(`Failed to create renderer of type: ${s}`);return o};return new ty(t,e)}};S[Q].register("overlay",cy);const tr=({mode:t,data:e})=>{const s=S[Q].execute(t,e);if(s)return s;throw new Error(`Unknown mode: ${t}`)};var ly=Object.defineProperty,dy=Object.getOwnPropertyDescriptor,Et=(t,e,s,r)=>{for(var o=r>1?void 0:r?dy(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&ly(e,s,o),o};const Ll="canvas-dispatcher-model";function uy(t){if(t=t.replace(/^#/,""),t.length===3&&(t=t.split("").map(s=>s+s).join("")),t.length!==6)return null;const e=parseInt(t,16);return{r:e>>16&255,g:e>>8&255,b:e&255}}let Le=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_content",new Map);l(this,"_patterns",new Map);l(this,"_endpointRenderers");l(this,"pattern");l(this,"data");this.id=t,this.logger=s.logger,this._endpointRenderers=new Te}addNamedEndpoint(t,e){this._endpointRenderers.getModel(t)&&this.logger.warn(`Endpoint "${t}" already exists. Overwriting.`);const s=nn.instance(t).options({apiPath:e.apiPath,width:e.width,height:e.height,fps:e.fps,durationMs:e.durationMs??null,endpoint:t}).build();return this._endpointRenderers.addModel(s),s}addContent(t,e){this._content.has(t)&&this.logger.warn(`Content "${t}" already exists. Overwriting.`),this._content.set(t,e)}addPattern(t,e){this._patterns.has(t)&&this.logger.warn(`Pattern "${t}" already exists. Overwriting.`),this._patterns.set(t,e)}async handlePatternsPost(t,e){var o,n;const s=t.body,r=Array.isArray(s)?s:[s];if(r.some(i=>!i.id||!i.type||!i.data)){(o=e.status)==null||o.call(e,400).send({error:"Invalid pattern data"});return}for(const i of r)this._patterns.has(i.id)&&this.logger.warn(`Pattern "${i.id}" already exists. Overwriting.`),this.addPattern(i.id,i);(n=e.status)==null||n.call(e,200).send({status:"OK"})}async handlePatternApplication(t,e){var d,u,h;const s=t.params.pattern,r=t.params.endpoint,o=this._endpointRenderers.getModel(r);if(!o){(d=e.status)==null||d.call(e,404).send({error:`Endpoint "${r}" not found`});return}if(!this._patterns.has(s)){(u=e.status)==null||u.call(e,404).send({error:`Pattern "${s}" not found`});return}const n=this._patterns.get(s),i=n.type,a=t.body||{};this.data={...n.data,...a};const c=i==="sequence"?{...this.data,patternStore:this._patterns}:this.data;o.renderer=tr({mode:i,data:c}),o.setClearOnComplete(n.clearOnComplete),o.startStreaming(),(h=e.status)==null||h.call(e,200).send({status:"OK"})}async handleColorApplication(t,e){var d,u,h;const s=t.params.color,r=uy(s);if(!r){(d=e.status)==null||d.call(e,400).send({error:"Invalid color format"});return}const o=t.params.endpoint,n=this._endpointRenderers.getModel(o);if(!n){(u=e.status)==null||u.call(e,404).send({error:`Endpoint "${o}" not found`});return}const{r:i,b:a,g:c}=r;n.renderer=tr({mode:"color",data:{r:i,g:c,b:a}}),n.startStreaming(),(h=e.status)==null||h.call(e,200).send({status:"OK"})}async handleEndpointCreation(t,e){var r,o;const s=t.body;if(!s.apiPath||!s.id){(r=e.status)==null||r.call(e,400).send({error:"Name and path are required"});return}this.addNamedEndpoint(s.id,s),(o=e.status)==null||o.call(e,200).send({status:"OK"})}async load(t){var s;const e=t==null?void 0:t.get(ht.loader);e&&((s=e.patterns)==null||s.forEach(r=>{if(!r.id||!r.type||!r.data){this.logger.warn(`Invalid pattern data: ${JSON.stringify(r)}`);return}this.addPattern(r.id,r)}))}};Et([be],Le.prototype,"_endpointRenderers",2);Et([as("/api/ui/canvas/patterns")],Le.prototype,"handlePatternsPost",1);Et([as("/api/ui/canvas/pattern/:endpoint/:pattern")],Le.prototype,"handlePatternApplication",1);Et([as("/api/ui/canvas/color/:endpoint/:color")],Le.prototype,"handleColorApplication",1);Et([as("/api/ui/canvas/endpoint")],Le.prototype,"handleEndpointCreation",1);Le=Et([R(Ll)],Le);const ht=new Ee({class:Le,type:Ll}),{URL:cn}=oe(),{getOne:kl}=se.build({basePath:`${cn}/api/device`}),sr=p.createLogger({name:"device-service",group:"Services"}),Fl=async()=>{sr.debug("sending GET for device serial number");try{const t=await kl({urlOverride:`${cn}/api/kos/device/serialNumber`});return[void 0,t==null?void 0:t.data.serialNumber]}catch(t){if(t instanceof B)return sr.error(`Error fetching device serial number: ${t.payload.error}`),[t.payload.error,void 0]}return["unknownError",void 0]},Nl=async()=>{sr.debug("sending GET for device details");try{const t=await kl({urlOverride:`${cn}/api/kos/device`});return t?[void 0,t.data]:["unknownError",void 0]}catch(t){if(t instanceof B)return sr.error(`Error fetching device serial number: ${t.payload.error}`),[t.payload.error,void 0]}return["unknownError",void 0]},hy=Object.freeze(Object.defineProperty({__proto__:null,getDeviceDetails:Nl,getSerialNumber:Fl},Symbol.toStringTag,{value:"Module"}));var fy=Object.defineProperty,gy=Object.getOwnPropertyDescriptor,Ul=(t,e,s,r)=>{for(var o=r>1?void 0:r?gy(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&fy(e,s,o),o};const jl="device-model",py="/kos/criticalData/changed",my="/kos/criticalData/available";let rr=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_serialNumber");l(this,"_name");l(this,"_nodeId");this.id=t,this.logger=s.logger,this._serialNumber="unassigned",this._name="unassigned",this._nodeId="unassigned"}get serialNumber(){return this._serialNumber}get name(){return this._name}get nodeId(){return this._nodeId}get nodeType(){const[t]=this.nodeId.split("-");return t}get nodeName(){const[,t]=this.nodeId.split("-");return t}updateModel(t){this._serialNumber=t.serialNumber??"unassigned",this._name=t.name??"unassigned",this._nodeId=t.nodeId??"unassigned"}async loadDeviceData(){const[t,e]=await Nl();if(t){this.logger.error(`Error fetching device serial number: ${t}`);return}if(e){const{name:s,nodeId:r}=e;this.updateModel({name:s,nodeId:r,serialNumber:this.serialNumber})}}async loadSerialNumber(){const[t,e]=await Fl();if(t){this.logger.error(`Error fetching device serial number: ${t}`);return}this.updateModel({serialNumber:e,name:this.name,nodeId:this.nodeId})}async handleCriticalDataChanged(){this.logger.debug(`Critical data changed for device ${this.id}`),await this.loadSerialNumber()}async init(){this.logger.debug(`initializing device ${this.id}`)}async load(){this.logger.debug(`loading device ${this.id}`),await this.loadDeviceData(),await this.loadSerialNumber()}};Ul([U({topic:[py,my],websocket:!0})],rr.prototype,"handleCriticalDataChanged",1);rr=Ul([R(jl)],rr);const or=new Ee({class:rr,type:jl});var yy=Object.getOwnPropertyDescriptor,by=(t,e,s,r)=>{for(var o=r>1?void 0:r?yy(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const Bl="network-interface-model";let io=class{constructor(t,e,s){l(this,"id");l(this,"name");l(this,"type");l(this,"nmdevicestate");l(this,"hwaddress");l(this,"mtu");l(this,"configured");l(this,"wifi");l(this,"ethernet");l(this,"ip4settings");l(this,"category");l(this,"logger");this.id=t,this.logger=s.logger,this.name=e.name,this.type=e.type,this.nmdevicestate=e.nmdevicestate,this.hwaddress=e.hwaddress,this.mtu=e.mtu,this.configured=e.configured,this.wifi=e.wifi,this.ethernet=e.ethernet,this.ip4settings=e.ip4settings,this.category=e.category}updateModel(t){this.name=t.name,this.type=t.type,this.nmdevicestate=t.nmdevicestate,this.hwaddress=t.hwaddress,this.mtu=t.mtu,this.configured=t.configured,this.wifi=t.wifi,this.ethernet=t.ethernet,this.ip4settings=t.ip4settings,this.category=t.category}async init(){this.logger.debug(`initializing network-interface ${this.id}`)}async load(){this.logger.debug(`loading network-interface ${this.id}`)}};io=by([R(Bl)],io);const ln=new we({class:io,type:Bl}),{URL:wy}=oe(),{getAll:vy}=se.build({basePath:`${wy}/api/kos/network/interfaces`}),Jn=p.createLogger({name:"network-interface-service",group:"Services"}),Kl=async()=>{Jn.debug("sending GET for copy-logs");try{const t=await vy({});return[void 0,t==null?void 0:t.data]}catch(t){if(t instanceof B)return Jn.error(`Error fetching log file size: ${t.payload.error}`),[t.payload.error,void 0]}return["unknownError",void 0]},My=Object.freeze(Object.defineProperty({__proto__:null,getNetworkInterfaces:Kl},Symbol.toStringTag,{value:"Module"}));var Ey=Object.defineProperty,Ty=Object.getOwnPropertyDescriptor,Hl=(t,e,s,r)=>{for(var o=r>1?void 0:r?Ty(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Ey(e,s,o),o};const zl="network-interface-container-model";let nr=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new Te({parentId:t,indexMap:{byCategory:"category"}})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug(`initializing network-interface-container container ${this.id}`)}async refreshInterfaces(){this.logger.debug("refreshing interfaces");const[t,e]=await Kl();if(t){this.logger.error(`Error loading network interfaces: ${t}`);return}e&&e.forEach(s=>{const r=ln.instance(s.name).forceUpdate.options(s).build();this.addModel(r)})}async load(){this.logger.debug(`loading network-interface-container container ${this.id}`),this.refreshInterfaces()}};Hl([be],nr.prototype,"_models",2);nr=Hl([R(zl)],nr);const ts=new Ee({class:nr,type:zl});ts.addRelatedModel(ln);const{URL:_y}=oe(),{getAll:Iy}=se.build({basePath:`${_y}/api/kos/storage/devices`}),ei=p.createLogger({name:"storage-device-service",group:"Services"}),Gl=async()=>{ei.debug("sending GET for storage-device");const t=await Iy({});return!(t!=null&&t.data)||t.status!==200?(ei.error("Failed to retrieve storage-device data",t),[]):t.data},Sy=Object.freeze(Object.defineProperty({__proto__:null,getStorageDevices:Gl},Symbol.toStringTag,{value:"Module"}));var Oy=Object.getOwnPropertyDescriptor,$y=(t,e,s,r)=>{for(var o=r>1?void 0:r?Oy(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const Vl="storage-device-model";let ao=class{constructor(t,e,s){l(this,"id");l(this,"mountDir");l(this,"removed");l(this,"vendor");l(this,"runTimeMs");l(this,"model");l(this,"nodeId");l(this,"local");l(this,"label");l(this,"syspath");l(this,"logger");this.id=t,this.logger=s.logger,this.mountDir=e.mountDir,this.removed=e.removed,this.vendor=e.vendor,this.runTimeMs=e.runTimeMs,this.model=e.model,this.nodeId=e.nodeId,this.local=e.local,this.label=e.label,this.syspath=e.syspath}updateModel(t){this.mountDir=t.mountDir,this.removed=t.removed,this.vendor=t.vendor,this.runTimeMs=t.runTimeMs,this.model=t.model,this.nodeId=t.nodeId,this.local=t.local,this.label=t.label,this.syspath=t.syspath}async init(){this.logger.debug(`initializing storage-device ${this.id}`)}async load(){this.logger.debug(`loading storage-device ${this.id}`)}};ao=$y([fr(),R(Vl)],ao);const ir=new we({class:ao,type:Vl});var Dy=Object.defineProperty,Cy=Object.getOwnPropertyDescriptor,dn=(t,e,s,r)=>{for(var o=r>1?void 0:r?Cy(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Dy(e,s,o),o};const Yl="storage-device-container-model",Ry="/kos/storage";let ss=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new Te({parentId:t})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug(`initializing storage-device-container container ${this.id}`)}get isStorageInserted(){return this.data.length>0}get volumes(){return this.data}handleStorageAvailability(t){this._models.data.filter(s=>!t.find(r=>r.id===s.id)).forEach(s=>{this.removeModel(s.id)}),t.forEach(s=>{const r=this.getModel(s.id);if(r){const o={...s,kosParentId:this.id};r.updateModel(o)}else{const o={...s,kosParentId:this.id},n=ir.instance(s.id).options(o).build();this.addModel(n)}})}async load(){this.logger.debug(`loading storage-device-container container ${this.id}`),(await Gl()).forEach(e=>{const s={...e,kosParentId:this.id},r=ir.instance(e.id).options(s).build();this.addModel(r)})}};dn([be],ss.prototype,"_models",2);dn([U({topic:Ry,websocket:!0})],ss.prototype,"handleStorageAvailability",1);ss=dn([R(Yl)],ss);const ft=new Ee({class:ss,type:Yl});ft.addRelatedModel(ir);const{URL:un}=oe(),{getAll:Ay,postModel:xy}=se.build({basePath:`${un}/api/kos/update/available`}),ti=p.createLogger({name:"usb-update-service",group:"Services"}),ql=async()=>{ti.debug("sending GET for usb-update");const t=await Ay({urlOverride:`${un}/api/kos/update/available`});return!(t!=null&&t.data)||(t==null?void 0:t.status)!==200?(ti.error("Failed to retrieve usb-update data",t),[]):t.data},Wl=async(t,e,s)=>{const r=await xy({model:{manifestId:t,deviceId:e},tracker:s,urlOverride:`${un}/api/kos/update/install`});if(!(r!=null&&r.data))throw new Error("No response from server");return r.data},Py=Object.freeze(Object.defineProperty({__proto__:null,getAvailableUpdates:ql,installUpdate:Wl},Symbol.toStringTag,{value:"Module"}));var Ly=Object.defineProperty,ky=Object.getOwnPropertyDescriptor,Ql=(t,e,s,r)=>{for(var o=r>1?void 0:r?ky(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Ly(e,s,o),o};const Zl="usb-update-model";let ar=class{constructor(t,e,s){l(this,"id");l(this,"active");l(this,"blocked");l(this,"createTime");l(this,"deviceId");l(this,"manifestId");l(this,"notes");l(this,"futureHandler");l(this,"logger");this.id=t,this.logger=s.logger,this.active=e.active,this.blocked=e.blocked,this.createTime=e.createTime,this.deviceId=e.deviceId,this.manifestId=e.manifestId,this.notes=e.notes,this.futureHandler=new yr(this)}updateModel(t){this.active=t.active,this.blocked=t.blocked,this.createTime=t.createTime,this.deviceId=t.deviceId,this.manifestId=t.manifestId,this.notes=t.notes}reset(){this.futureHandler.removeFuture()}get future(){return this.futureHandler.future}async install(t){if(!t)throw new Error("No tracker provided");return this.logger.info(`Installing update for manifest ${this.manifestId} from device ${this.deviceId}`),Wl(this.manifestId,this.deviceId,t)}async init(){this.logger.debug(`initializing usb-update ${this.id}`)}async load(){this.logger.debug(`loading usb-update ${this.id}`)}};Ql([yn()],ar.prototype,"install",1);ar=Ql([R(Zl)],ar);const hn=new we({class:ar,type:Zl});var Fy=Object.defineProperty,Ny=Object.getOwnPropertyDescriptor,_r=(t,e,s,r)=>{for(var o=r>1?void 0:r?Ny(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Fy(e,s,o),o};const Xl="usb-update-container-model";let gt=class{constructor(t,e,s){l(this,"id");l(this,"disposer");l(this,"storageService");l(this,"_activeUpdate");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new Te({parentId:t})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}get activeUpdate(){return this._activeUpdate}reset(){this.clearActiveUpdate()}clearActiveUpdate(){this._activeUpdate=void 0}updateActiveUpdate(t){this._activeUpdate=t}get isUsbInserted(){return this.storageService.isStorageInserted}get hasAvailableUpdates(){return this._models.data.length>0}async syncAvailableUpdates(){const t=await ql();X(()=>{const e=t.map(s=>`${s.deviceId}-${s.manifestId}`);this._models.data.filter(s=>!e.includes(s.id)).forEach(s=>this.removeModel(s.id)),t.forEach(s=>{const r=`${s.deviceId}-${s.manifestId}`,o=hn.instance(r).forceUpdate.options({...s,createTime:new Date(s.createTime)}).build();this.addModel(o)}),this.data.length===1?this.updateActiveUpdate(this.data[0]):this.clearActiveUpdate()})}usbInsertedEffect(){this.isUsbInserted?this.syncAvailableUpdates():(this._models.clear(),this.clearActiveUpdate())}async init(){this.logger.debug(`initializing usb-update-container container ${this.id}`)}unload(){var t;(t=this.disposer)==null||t.call(this)}async activate(){this.logger.debug(`activating usb-update-container container ${this.id}`),await this.syncAvailableUpdates()}async load(){this.logger.debug(`loading usb-update-container container ${this.id}`)}};_r([yt({modelType:ft.type})],gt.prototype,"storageService",2);_r([be],gt.prototype,"_models",2);_r([la({dependencies:t=>[t.isUsbInserted]})],gt.prototype,"usbInsertedEffect",1);gt=_r([R(Xl)],gt);const rs=new Ee({class:gt,type:Xl});rs.addRelatedModel(hn);const Uy=()=>({...{[vt.type]:{class:Rc},[Pe.type]:{class:Fc,singleton:!0},...ee.registration,...Ve.registration,...dt.registration,...Zs.registration,...Oe.registration,[rn.type]:{class:exports.WsEventModel,singleton:!0},...es.registration,...tn.registration,...Ks.registration}}),fn=Uy(),jy={models:fn,preloadModels:[]},si=!0,Jl=t=>()=>{const e=fn;return Wa(co)(ct).model(dt).model(ft).model(rs).model(or).model(Ys).model(qt).model(qs).model(Zo).model(ts).model(ht).model(nn).model(qo,si).model(us).model(Gc,si),Object.keys(e).forEach(s=>{const r=e[s];qa(co)(s,r)}),{preload:C.model.preloadModel(t),model:C.model.register(t),companion:C.companion.register(t),legacy:C.model.registerLegacyModel(t)}},ye={};ye.core={models:Jl(ye)};ye.preload=C.model.preloadModel(ye);ye.model=C.model.register(ye);ye.companion=C.companion.register(ye);ye.legacy=C.model.registerLegacyModel(ye);const co=ye;class By{registerTroubleRankMapper(e){return S.propertyMapper.registerPropertyMapper(me.TroubleRank,e),this}registerTroubleRoleMapper(e){return S.propertyMapper.registerPropertyMapper(me.TroubleRole,e),this}registerTroubleColorMapper(e){return S.propertyMapper.registerPropertyMapper(me.TroubleColor,e),this}registerModelLoader(e,s){S.loader.registerLoader(e,s)}registerCanvasPatternLoader(e){S.loader.registerLoader(ht.loader,e)}}class fs{constructor(e){l(this,"futureHandler");this.futureHandler=new yr(e)}get future(){return this.futureHandler.future}get progress(){var e;return((e=this.future)==null?void 0:e.progress)||0}get status(){var e;return((e=this.future)==null?void 0:e.status)||"IDLE"}get isRunning(){return this.future?!this.future.endState:!1}get isCancelled(){var e;return((e=this.future)==null?void 0:e.status)==="CANCELLED"||!1}async cancelFuture(){this.future&&await this.future.cancelFuture()}}function Ky(t){const e=new fs(t);t.futureHandler=e.futureHandler}function ed(t){const e=new fs(t),s=t;s.futureHandler=e.futureHandler,Object.defineProperty(t,"future",{get(){return e.future},enumerable:!0,configurable:!0}),Object.defineProperty(t,"progress",{get(){return e.progress},enumerable:!0,configurable:!0}),Object.defineProperty(t,"status",{get(){return e.status},enumerable:!0,configurable:!0}),Object.defineProperty(t,"isRunning",{get(){return e.isRunning},enumerable:!0,configurable:!0}),Object.defineProperty(t,"isCancelled",{get(){return e.isCancelled},enumerable:!0,configurable:!0}),s.cancelFuture=async()=>e.cancelFuture()}function Hy(){return function(t){const e=t;function s(...r){const o=e.apply(this,r)||this;return ed(o),o}return s.prototype=e.prototype,Object.setPrototypeOf(s,e),Object.getOwnPropertyNames(e).forEach(r=>{if(r!=="prototype"&&r!=="length"&&r!=="name"){const o=Object.getOwnPropertyDescriptor(e,r);o&&Object.defineProperty(s,r,o)}}),s}}function zy(t){return new fs(t)}function Gy(t){let e;const s=()=>(e||(e=new fs(t())),e);return{get futureHandler(){return s().futureHandler},get future(){return s().future},get progress(){return s().progress},get status(){return s().status},get isRunning(){return s().isRunning},get isCancelled(){return s().isCancelled},async cancelFuture(){return s().cancelFuture()}}}function Vy(t){return t&&typeof t=="object"&&"futureHandler"in t&&"future"in t&&typeof t.cancelFuture=="function"}function Yy(t){const e=["future","progress","status","isRunning","isCancelled","futureHandler"],s={};for(const r of e){const o=Object.getOwnPropertyDescriptor(t,r);s[r]={exists:r in t,descriptor:o?{enumerable:o.enumerable,configurable:o.configurable,hasGetter:typeof o.get=="function",hasSetter:typeof o.set=="function"}:null,isObservable:t&&typeof t=="object"&&Object.getOwnPropertySymbols(t).some(n=>n.toString().includes("mobx")&&n.toString().includes(r))}}return s}class td{constructor(e,s){l(this,"parent");l(this,"companion");this.companion=e,this.parent=s}getParent(){return this.parent}setupProxy(e={}){const{excludeProperties:s=[],includeLifecycle:r=!1}=e,o=r?[]:["init","load","unload","ready","dispose","destroy","onInit","onLoad","onUnload","onReady","onDispose","onDestroy"],n=["getDependencies","getChildren","update","toJSON","forceUpdate","makeAutoObservable","runInAction","transaction","observe","unobserve","intercept","spy","trace"],i=c=>c==="constructor"||c.startsWith("_")||c.startsWith("__")||o.includes(c)||n.includes(c)||s.includes(c)||c in this.companion,a=this.getAllParentProperties(i);for(const c of a)this.createProxyProperty(c)}getAllParentProperties(e){const s=new Set;Object.getOwnPropertyNames(this.parent).filter(o=>!e(o)).forEach(o=>s.add(o));let r=Object.getPrototypeOf(this.parent);for(;r&&r!==Object.prototype;)Object.getOwnPropertyNames(r).filter(o=>!e(o)).forEach(o=>s.add(o)),r=Object.getPrototypeOf(r);return Array.from(s)}createProxyProperty(e){try{const s=this.parent[e];typeof s=="function"?this.companion[e]=(...r)=>s.apply(this.parent,r):Object.defineProperty(this.companion,e,{get:()=>this.parent[e],set:r=>{this.parent[e]=r},enumerable:!0,configurable:!0})}catch(s){console.debug(`Skipping companion proxy for property ${e}:`,s)}}}function qy(t,e,s={}){const r=new td(t,e);return t.getParent=()=>r.getParent(),Object.defineProperty(t,"_companionMixin",{value:r,enumerable:!1,configurable:!1,writable:!1}),r.setupProxy(s),r}function sd(t){return t&&typeof t=="object"&&"_companionMixin"in t&&typeof t.getParent=="function"}function rd(t){return sd(t)?t._companionMixin:null}function Wy(t){const e=rd(t);if(!e)return{error:"No companion mixin found"};const s=e.getParent(),r=Object.getOwnPropertyNames(t),o=Object.getOwnPropertyNames(s),n=r.filter(i=>o.includes(i)&&i!=="constructor"&&!i.startsWith("_"));return{parentType:s.constructor.name,companionType:t.constructor.name,proxiedProps:n,proxiedCount:n.length}}const Qy=async(t,e)=>{const s=Zo.instance(t).options({}).build(),r=e?`${e}-`:"";return await ae(s),{getState:o=>s.data[`${r}${o}`],updateState:async(o,n)=>{await s.updateState(`${r}${o}`,n)},clean:async()=>{for(const o of s.data.keys)await s.updateState(`${r}${o}`,void 0)},unsubscribe:()=>{He(s)}}},od="kos:service:region",nd="regionId",Zy=`${od}-${nd}`,id=async t=>{const e=Ve.factory(Zy)({path:od,attribute:nd});await ae(e),e.updateProperty(t)},gn="/kos-timer-event",pn="/kos-timer-event/tick",mn="defaultTimerEnd",Pt=p.createLogger({name:"timer-manager"}),Xy=t=>t.updateProperty!==void 0;class ad{constructor(e,s,r){l(this,"name");l(this,"timeout");l(this,"timer");l(this,"state","inactive");l(this,"decrementValue",1);l(this,"remainingTime");l(this,"timeoutActions",new Map);this.name=e;const o=typeof s=="number"?s:s.value||60;this.timeout=o,this.state="inactive",this.remainingTime=o,Xy(s)&&G(()=>{p.info(`Updating config value timer ${e} with new timeout value ${s.value}`);const n=s.value||60;this.updateTimeout(n)}),this.addTimeoutAction({name:mn}),r&&r.forEach(n=>{this.addTimeoutAction(n)})}get id(){return this.name}start(){if(this.state==="active"){Pt.debug(`Timer ${this.name} already started`);return}(this.state==="inactive"||this.state==="paused")&&(this.state="active",this.timer=setInterval(()=>this.updateTimer(),1e3))}pause(){this.timer&&(Pt.debug(`Pausing timer ${this.name}`),this.state="paused",clearInterval(this.timer))}restart(){this.pause(),this.remainingTime=this.timeout,this.start()}reset(){this.pause(),this.remainingTime=this.timeout,this.state="inactive"}updateTimeout(e){this.timeout=e,this.restart()}addTimeoutAction(e){const s=e.remainingTime??0;this.timeoutActions.has(s)||this.timeoutActions.set(s,[]);const r=e.name,o=this.timeoutActions.get(s).find(n=>n.name===r);o?o.action=e.action:this.timeoutActions.get(s).push(e)}removeTimeoutAction(e){for(const[s,r]of this.timeoutActions.entries()){const o=r.filter(n=>n.name!==e);o.length===0?this.timeoutActions.delete(s):this.timeoutActions.set(s,o)}}updateTimer(){if(this.remainingTime=Math.round((this.remainingTime-this.decrementValue)*100)/100,this.remainingTime<=0){this.state==="active"&&this.executeActions(0),this.pause();return}this.state==="active"&&this.executeActions(this.remainingTime)}executeActions(e){this.timeoutActions.has(e)&&this.timeoutActions.get(e).forEach(s=>{var r;Pt.debug(`Executing timer action ${s.name} at ${e}`),(r=s.action)==null||r.call(s,s.name,e),this.notifyTimeoutAction(s),s.singleUse&&(Pt.info(`${this.name} Removing single-use action ${s.name}`),this.removeTimeoutAction(s.name))}),this.notifyTick()}notifyTick(){j(`${pn}/${this.name}`,{name:this.name,remainingTime:this.remainingTime})}notifyTimeoutAction(e){j(gn,{name:this.name,action:e.name,remainingTime:this.remainingTime})}}const Lt=new Map,Je=(t,e)=>{const s=Lt.get(t);if(!s){Pt.error(`Timer ${t} not found`);return}e(s)},cd={createRelativeTimer(t,e,s){const r=new Date,o=Math.round((e.getTime()-r.getTime())/1e3);return this.createTimer(t,o,s)},createTimer(t,e=60,s){if(Lt.has(t))return Lt.get(t);const r=new ad(t,e,s);return Lt.set(t,r),r},getTimer(t){return Lt.get(t)},clearTimer(t){Je(t,e=>e.pause())},restartTimer(t){Je(t,e=>e.restart())},resetTimer(t){Je(t,e=>e.reset())},addTimeoutAction(t,e){Je(t,s=>s.addTimeoutAction(e))},removeTimeoutAction(t,e){Je(t,s=>s.removeTimeoutAction(e))},startTimer(t){Je(t,e=>e.start())}},ld="kos:service:region:settings",dd="timeZone",Jy=`${ld}-${dd}`,lo=async t=>{const e=Ve.factory(Jy)({path:ld,attribute:dd});await ae(e),e.updateProperty(t)},eb=t=>!t||!t.data;function yn(t={}){const{alias:e,namespace:s,abortController:r=!1}=t;return(o,n,i)=>{o[Nt]=o[Nt]||{};const a=i.value,c=async function(...d){const u=mt();p.debug(`Calling future service ${n} with tracker ${u}`);let h,g;r&&(h=new AbortController);const m=ze.initiateFuture({tracker:u,id:No});s&&(m.namespace=s),p.debug(`waiting for future ${m.id} to be ready`),await ae(m),p.debug(`future ${m.id} is ready`),X(()=>{p.debug(`Adding future ${m.id} to futureHandler`),this.futureHandler.addFuture(m,e)}),r&&h&&(g=G(()=>{(m.status==="CANCELLED"||m.endState===xe.Canceled)&&(p.debug(`Future ${m.id} cancelled, aborting request`),h==null||h.abort())}),h.signal.addEventListener("abort",async()=>{if(m.status!=="CANCELLED"&&m.endState!==xe.Canceled&&!m.endState){p.debug(`AbortController aborted, cancelling future ${m.id}`);try{await m.cancelFuture()}catch(v){p.error(`Failed to cancel future ${m.id}:`,v)}}},{once:!0}));const y=()=>{g&&(g(),g=void 0)};try{const v=[...d];if(r&&h){const N=v[v.length-1];N&&typeof N=="object"&&"aborted"in N?v[v.length-1]=h.signal:v.push(h.signal)}v.push(u);const E=await a.apply(this,v);p.debug(`received future response for ${u}`,E);const _=eb(E)?E:E==null?void 0:E.data;return _?(_.progress=1,p.debug("mapping future response to future model"),m.endState?p.debug(`future ${m.id} has already completed. Not updating the model`):Vo(_,m)):this.futureHandler.removeFuture(e),y(),_}catch(v){if(y(),r&&(h!=null&&h.signal.aborted)){const E=new Error("Operation cancelled");throw p.debug(`Operation ${n} was cancelled`),E}throw p.error(v),v}};o[Nt][n]={handler:c}}}const tb=({path:t})=>(e,s)=>{e[F]=e[F]||{},e[F][s]={modelType:es.type,id:`${es.type}-${t}`,options:{path:t},lifecycle:H.INIT}};function sb(t){const{path:e,attribute:s}=t;return(r,o)=>{r[F]=r[F]||{},r[F][o]={modelType:tn.type,id:`${e}-${s}`,options:{path:e,attribute:s},lifecycle:H.INIT}}}const st=p.createLogger({name:"services",group:"Services"}),rb=async(t,e)=>ud(t,e,`${exports.BASE_URL}/api/server/login`),ud=async(t,e,s=`${exports.BASE_URL}/api/login`)=>{const r=await exports.kosFetch(`${s}`,{method:"POST",destinationAddress:"",body:JSON.stringify({email:t,password:e})});if(!r.ok){const n=await r.json();throw Error(`${n==null?void 0:n.error}`)}return await r.json()},ob=async t=>hd(t,`${exports.BASE_URL}/api/server/startPasswordReset`,""),hd=async(t,e=`${exports.BASE_URL}/api/startPasswordReset`,s="server")=>{const r=await exports.kosFetch(`${e}?email=${t}`,{method:"POST",destinationAddress:s});if(!r.ok)throw Error(`There was a problem reseting config; returned status ${r.status}`);return await r.json()},nb=async(t,e)=>fd(t,e,`${exports.BASE_URL}/api/server/resetPassword`),fd=async(t,e,s=`${exports.BASE_URL}/api/resetPassword`)=>{st.debug(`resetting password with token ${t} and password ${e.replace(/./g,"*")}`);const r=await exports.kosFetch(`${s}`,{method:"POST",destinationAddress:"",body:JSON.stringify({token:t,password:e})});if(st.debug(`password reset returned status ${r.status}`),!r.ok){st.error(`password reset failed with message ${r.statusText}`);const n=await r.json();throw Error(`${n==null?void 0:n.error}:There was a problem resetting the password.`)}return await r.json()},ib=async(t,e,s)=>gd(t,e,s,`${exports.BASE_URL}/api/server/acceptInvite`),gd=async(t,e,s,r=`${exports.BASE_URL}/api/server/acceptInvite`)=>{st.debug(`accepting invite with token ${t} and password ${e.replace(/./g,"*")}`);const o=await exports.kosFetch(`${r}`,{method:"POST",destinationAddress:"",body:JSON.stringify({token:t,password:e,name:s})});if(st.debug(`invitation accept returned status ${o.status}`),!o.ok){st.error(`invite failed with message ${o.statusText}`);const i=await o.json();throw Error(`${i==null?void 0:i.error}:There was a problem accepting the invite.`)}return await o.json()};function ab(t,e,s,r){const o=t instanceof Promise?{promise:t,abortController:e,cancelFuture:s,future:r}:t,{promise:n,abortController:i,cancelFuture:a,future:c}=o,d=n;let u=0,h="PENDING",g=!0;const m=new Set;let y;return c&&typeof c=="object"&&(y=M.autorun(()=>{const v=c.progress||0,E=c.status||"PENDING",_=!c.endState;(v!==u||E!==h||_!==g)&&(u=v,h=E,g=_,m.forEach(N=>{try{N(u,h)}catch(x){console.warn("Progress callback error:",x)}}))})),n.finally(()=>{g=!1,i!=null&&i.signal.aborted||(h="COMPLETED",m.forEach(v=>{try{v(u,h)}catch(E){console.warn("Progress callback error:",E)}})),y&&y(),m.clear()}),d.cancel=async()=>{i&&!i.signal.aborted&&i.abort(),a&&await a(),g=!1,h="CANCELLED",m.forEach(v=>{try{v(u,h)}catch(E){console.warn("Progress callback error:",E)}}),y&&y()},d.getController=()=>i,d.isCancelled=()=>(i==null?void 0:i.signal.aborted)??!1,Object.defineProperty(d,"progress",{get:()=>u,enumerable:!0}),Object.defineProperty(d,"status",{get:()=>h,enumerable:!0}),Object.defineProperty(d,"isRunning",{get:()=>g,enumerable:!0}),d.onProgressUpdate=v=>(m.add(v),v(u,h),()=>m.delete(v)),d}const cb=je.keyframes`
113
113
  0% {
114
114
  left: -90px;
115
115
  color: #eee;
@@ -121,13 +121,13 @@ ${d}topics:${e}
121
121
  left: 90px;
122
122
  color: #eee;
123
123
  }
124
- `,cb=je.css`
124
+ `,lb=je.css`
125
125
  font-size: 100px;
126
126
  margin-top: -80px;
127
127
  position: relative;
128
- animation: ${ab} ease-in-out infinite alternate;
128
+ animation: ${cb} ease-in-out infinite alternate;
129
129
  animation-duration: 1.2s;
130
- `,lb=({children:t})=>ni.createPortal(t,document.body);function pd({message:t="Wait a moment while we load your app.",theme:e="light"}){return T.jsx(lb,{children:T.jsxs(db,{theme:e,children:[t,T.jsx("div",{css:cb,children:"."})]})})}const db=co.div`
130
+ `,db=({children:t})=>ii.createPortal(t,document.body);function pd({message:t="Wait a moment while we load your app.",theme:e="light"}){return T.jsx(db,{children:T.jsxs(ub,{theme:e,children:[t,T.jsx("div",{css:lb,children:"."})]})})}const ub=go.div`
131
131
  padding-inline: 20px;
132
132
  width: 100%;
133
133
  height: 100vh;
@@ -141,7 +141,7 @@ ${d}topics:${e}
141
141
  left: 0;
142
142
  color: ${({theme:t})=>t==="light"?"black":"white"};
143
143
  z-index: 10000;
144
- `;class md extends f.Component{constructor(e){super(e),this.state={error:null,errorInfo:null}}componentDidCatch(e,s){this.setState({error:e,errorInfo:s})}render(){return this.state.errorInfo?this.props.fallback||T.jsxs("div",{children:[T.jsx("h2",{children:"Something went wrong."}),T.jsxs("details",{style:{whiteSpace:"pre-wrap"},children:[this.state.error&&this.state.error.toString(),T.jsx("br",{}),this.state.errorInfo.componentStack]})]}):this.props.children}}const ub={normal:"#B5F7F6",warn:"#F3D78A",error:"#FC8486"},hb=({value:t=0,title:e,status:s="normal",subtitle:r})=>{const o=je.css`
144
+ `;class md extends f.Component{constructor(e){super(e),this.state={error:null,errorInfo:null}}componentDidCatch(e,s){this.setState({error:e,errorInfo:s})}render(){return this.state.errorInfo?this.props.fallback||T.jsxs("div",{children:[T.jsx("h2",{children:"Something went wrong."}),T.jsxs("details",{style:{whiteSpace:"pre-wrap"},children:[this.state.error&&this.state.error.toString(),T.jsx("br",{}),this.state.errorInfo.componentStack]})]}):this.props.children}}const hb={normal:"#B5F7F6",warn:"#F3D78A",error:"#FC8486"},fb=({value:t=0,title:e,status:s="normal",subtitle:r})=>{const o=je.css`
145
145
  display: flex;
146
146
  flex-direction: column;
147
147
  `,n=je.css`
@@ -161,7 +161,7 @@ ${d}topics:${e}
161
161
  `,a=je.css`
162
162
  width: ${t}%;
163
163
  height: 35px;
164
- background-color: ${ub[s]};
164
+ background-color: ${hb[s]};
165
165
  text-align: center;
166
166
  line-height: 32px;
167
167
  color: black;
@@ -179,7 +179,7 @@ ${d}topics:${e}
179
179
  transform: translateX(100%) scaleX(0.5);
180
180
  }
181
181
  }
182
- `;return T.jsxs("div",{css:o,children:[T.jsxs("div",{css:n,children:[T.jsx("div",{css:i,children:e}),T.jsx("div",{css:[a,t<0?c:""]})]}),T.jsx("div",{children:r})]})},fb={setModel:()=>!1},Ir=f.createContext(fb),gb=()=>{const t=f.useContext(Ir);if(t==null)throw new Error("useModels must be used within a KosModelProvider");return t.model},yd=({children:t})=>{const[e,s]=f.useState(),r=f.useCallback(o=>(s(o),!0),[s]);return T.jsx(Ir.Provider,{value:{model:e,setModel:r},children:t})},bd=p.createLogger({name:"kos-model-hierarchy-context"}),pb={models:[],addModel:()=>{bd.debug("Default implementation being used. Do Nothing.")}},Sr=f.createContext(pb),mb=({children:t})=>{const[e,s]=f.useState([]),r=f.useCallback(o=>{e.includes(o)||(bd.debug("adding to hierarchy context",o.id),s(n=>[...n,o]))},[e]);return T.jsx(Sr.Provider,{value:{models:e,addModel:r},children:t})},yb=()=>!0,wd=t=>{const e=f.useContext(Sr);if(!e)throw new Error("useContextModelHierarchy must be used within a KosModelCollectionProvider");const s=(t==null?void 0:t.filter)||yb;return f.useMemo(()=>e.models.filter(s),[e.models,s])},bb=t=>wd({filter:s=>{const r=ve(s.id);return(r==null?void 0:r.type)===t}})[0],wb=p.createLogger({name:"kos-model-loader"}),vb=()=>T.jsx("div",{}),vd=({fallback:t,children:e,...s})=>T.jsx(yd,{children:T.jsx(md,{fallback:t,children:T.jsx(f.Suspense,{children:T.jsx(Md,{...s,children:e})})})}),Md=t=>{const[e,s]=f.useState(),[r,o]=f.useState(!1),{setModel:n}=f.useContext(Ir),i=f.useContext(Sr);if(f.useEffect(()=>{t.model&&(s(t.model),n(t.model),o(!0),i&&i.addModel(t.model))},[i,t.model,n]),t.error)throw wb.error(t.error),new Error(t.error);const a=t.loading||T.jsx(vb,{});return T.jsx(T.Fragment,{children:e&&r?t.children:a})},As={header:{title:"Model",createLabel:"Create new Model",deleteLabel:"Delete"},createModal:{okText:"OK",cancelText:"Cancel",title:"Create New Model"}},Ed=f.createContext(As),Mb=({translations:t=As,children:e})=>{const s={header:{...As.header,...t.header},createModal:{...As.createModal,...t.createModal}};return T.jsx(Ed.Provider,{value:s,children:e})};function Eb(t,e){const s=I.create(t,!1,e),r=s.whenReady().then(()=>s);return wo(r)}const Td=f.createContext(void 0),Tb=(t={models:{},preloadModels:[]},e)=>{const s=Eb(t,e),r=({children:o})=>{const n=s.read(),[i,a]=f.useState(n.isOnline);f.useEffect(()=>{const d=G(()=>{a(n.isOnline)});return()=>{d()}},[n]);const c=f.useMemo(()=>({kosCore:n,online:i}),[n,i]);return T.jsx(Td.Provider,{value:c,children:o})};return{KosCoreContextProvider:lo.observer(r)}},_d=()=>{const t=f.useContext(Td);if(t===void 0)throw new Error("useKosCore must be used within a KosCoreContextProvider");return t},_b=8,Ib=(t=0)=>new Promise(e=>{setTimeout(()=>{e(!0)},2**t*10)}),Be=new Map;function Sb(t,e){if(Be.has(t)){const s=Be.get(t);if(s.status==="finished"){const r=I.getInstance().modelManager.getModelById(t);return{kosModel:r,model:r==null?void 0:r.modelData}}else throw s.promise}else{const s=e().then(()=>{Be.set(t,{status:"finished",key:t})},o=>{throw Be.set(t,{status:"error",error:o}),o}),r={status:"pending",promise:s};throw Be.set(t,r),s}}function Ob(t,e){return Sb(t,e)}async function $b(t,e){const{modelId:s,factory:r,modelType:o,options:n,activate:i}=e;let a=0;await t.whenReady();let c;if(n){const u=typeof o=="string"?t.modelManager.getModelFactory(o):r;if(!u)throw Error("No Factory Specified. Cannot create a new instance");c=u.build(s,n)}const d=t.modelManager.getModelById(s);if(!d){if(a>_b)throw Error(`KOS Model ${s} has not been found`);await Ib(a),a=a+1}return await(d==null?void 0:d.whenReady()),d?(c=d.modelData,{kosModel:d,model:c}):{kosModel:void 0,model:void 0}}const q=t=>{const{modelId:e,modelType:s,activate:r,destroyOnUnmount:o}=t,n=_d(),[i,a]=f.useState(!1),[c,d]=f.useState(),{kosModel:u,model:h}=Ob(e||s||"",()=>$b(n.kosCore,t));return f.useEffect(()=>{async function g(){try{return await n.kosCore.whenReady(),r&&await(u==null?void 0:u.fsm.transitionTo(A.GO_ACTIVE,w.ACTIVE)),a(!0),u}catch(y){d(y.message)}}let m;return n.kosCore&&e&&g().then(y=>{m=G(()=>{const v=(y==null?void 0:y.status)===w.READY;a(v)})}).catch(y=>{console.error(y)}),()=>{if(r){if(h!=null&&h.id){const y=n.kosCore.modelManager.getModelById(h.id);y==null||y.fsm.transitionTo(A.GO_INACTIVE,w.INACTIVE).then(()=>{if(o){const v=h.id;He(h).then(()=>{Be.delete(v),m==null||m()})}})}}else o&&h&&He(h).then(()=>{Be.delete(e),m==null||m()})}},[r,o,n.kosCore,u,h,e]),{model:h,ready:i,error:c,status:{model:h,ready:i,error:c},KosModelLoader:vd}},fn=()=>{const t=Ks.type;return q({modelId:t,modelType:Ks.type,options:{}})},gn=f.createContext(void 0),Db=({children:t})=>{const{model:e,ready:s}=fn(),r=f.useMemo(()=>s&&e?{model:e}:{},[s,e]);return T.jsx(gn.Provider,{value:r,children:t})},Cb=()=>{const t=f.useContext(gn);if(!t)throw new Error("useKosTimeContext must be used within a KosTimeProvider");return t},pn=()=>{const t=qs.type;return q({modelId:t,modelType:qs.type,options:{}})};function Rb(t){return()=>e=>{const{model:s,status:r,KosModelLoader:o}=pn();return T.jsx(o,{...r,children:T.jsx(t,{...e,softwareInfo:s})})}}const mn=f.createContext(void 0),Ab=({children:t})=>{const{model:e,ready:s}=pn(),r=f.useMemo(()=>s&&e?{model:e}:{},[s,e]);return T.jsx(mn.Provider,{value:r,children:t})},xb=()=>{const t=f.useContext(mn);if(!t)throw new Error("useSoftwareInfoContext must be used within a SoftwareInfoProvider");return t},Id=new nc,Sd=f.createContext(Id);function Pb({children:t}){return T.jsx(Sd.Provider,{value:Id,children:t})}const yn=f.createContext(void 0),Lb=()=>{const t=window.location.origin,e=ue();return(e==null?void 0:e.host)||t},kb=({children:t,appContext:e,locale:s="en",resolver:r,rootUrl:o,descriptorResolver:n})=>{const[i,a]=f.useState(!1),[c,d]=f.useState(),[u,h]=f.useState(),g=o||Lb(),m=f.useMemo(()=>e??"app/system",[e]);f.useEffect(()=>{async function E(){const N=(Array.isArray(m)?m:[m]).map(W=>(n||Ml(W))()),P=(await Promise.allSettled(N)).map(W=>{if(W.status==="rejected"){p.warn("Failed to load localization descriptor",W.reason);return}return W.value}).filter(W=>!!W).reverse().reduce((W,re)=>{const L=re.path;return Object.keys(re.namespaces).forEach(Ce=>{const V=re.namespaces[Ce];V.basePath=L}),{...W,namespaces:{...W.namespaces,...re.namespaces}}},{});d(P)}E()},[m,n]),f.useEffect(()=>{async function E(){if(c){const _=g,{translations:N}=await Sl.init({lang:s,descriptor:c,defaultNamespace:"common",resolver:r,rootUrl:_});h(N),a(!0)}}E()},[s,c,r,g]);const y=f.useMemo(()=>i?{setLocale:E=>{u&&(u.currentLocale=E)}}:{setLocale:()=>{throw new Error("Translations not ready")}},[i,u]),v=i?t:null;return T.jsx(yn.Provider,{value:y,children:v})},Fb=()=>{const t=f.useContext(yn);if(!t)throw new Error("useTranslationContainerContext must be used within a TranslationContainerProvider");return t},Nb=()=>{const t=ut.type;return q({modelId:t,modelType:ut.type,options:{}})};function Ub(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Nb();return T.jsx(o,{...r,children:T.jsx(t,{...e,canvasDispatcher:s})})}}const jb=(t,e,s)=>{const r=atob(t),o=new Uint8ClampedArray(e*s*4);for(let n=0,i=0;n<r.length&&i<o.length;n+=3,i+=4)o[i]=r.charCodeAt(n),o[i+1]=r.charCodeAt(n+1),o[i+2]=r.charCodeAt(n+2),o[i+3]=255;return o};function Bb({ctx:t,format:e,dataString:s,width:r,height:o,pixelSize:n}){const i=jb(s,r,o),a=new ImageData(i,r,o),c=document.createElement("canvas");c.width=r,c.height=o;const d=c.getContext("2d");d==null||d.putImageData(a,0,0),t.imageSmoothingEnabled=!1,t.clearRect(0,0,r*n,o*n),t.drawImage(c,0,0,r*n,o*n)}const Kb=p.createLogger({name:"canvas-streamer"});Kb.debug("main-view component loaded");const jr=10,Od=lo.observer(({canvasDispatcher:t,height:e=30,width:s=50,defaultFps:r=10,showPreview:o=!1,name:n,apiPath:i="/api/system/canvas"})=>{const a=f.useRef(null),[c,d]=f.useState();f.useEffect(()=>{const h=t.addNamedEndpoint(n,{apiPath:i,fps:r,width:s,height:e,id:n});d(h)},[t]);const u=f.useCallback(h=>{if(a.current&&o){const g=a.current.getContext("2d");g&&Bb({ctx:g,format:"base64",dataString:h,height:e,width:s,pixelSize:jr})}},[s,e,o]);return f.useEffect(()=>{c&&(c.onFrame=u,c.width=s,c.height=e,c.fps=r)},[c,u,s,e,r]),o&&ni.createPortal(T.jsx(zb,{children:T.jsx(Gb,{children:T.jsx("canvas",{ref:a,width:s*jr,height:e*jr,style:{border:"1px solid black"}})})}),document.body)}),Hb=Ub(Od),zb=co.div`
182
+ `;return T.jsxs("div",{css:o,children:[T.jsxs("div",{css:n,children:[T.jsx("div",{css:i,children:e}),T.jsx("div",{css:[a,t<0?c:""]})]}),T.jsx("div",{children:r})]})},gb={setModel:()=>!1},Ir=f.createContext(gb),pb=()=>{const t=f.useContext(Ir);if(t==null)throw new Error("useModels must be used within a KosModelProvider");return t.model},yd=({children:t})=>{const[e,s]=f.useState(),r=f.useCallback(o=>(s(o),!0),[s]);return T.jsx(Ir.Provider,{value:{model:e,setModel:r},children:t})},bd=p.createLogger({name:"kos-model-hierarchy-context"}),mb={models:[],addModel:()=>{bd.debug("Default implementation being used. Do Nothing.")}},Sr=f.createContext(mb),yb=({children:t})=>{const[e,s]=f.useState([]),r=f.useCallback(o=>{e.includes(o)||(bd.debug("adding to hierarchy context",o.id),s(n=>[...n,o]))},[e]);return T.jsx(Sr.Provider,{value:{models:e,addModel:r},children:t})},bb=()=>!0,wd=t=>{const e=f.useContext(Sr);if(!e)throw new Error("useContextModelHierarchy must be used within a KosModelCollectionProvider");const s=(t==null?void 0:t.filter)||bb;return f.useMemo(()=>e.models.filter(s),[e.models,s])},wb=t=>wd({filter:s=>{const r=ve(s.id);return(r==null?void 0:r.type)===t}})[0],vb=p.createLogger({name:"kos-model-loader"}),Mb=()=>T.jsx("div",{}),vd=({fallback:t,children:e,...s})=>T.jsx(yd,{children:T.jsx(md,{fallback:t,children:T.jsx(f.Suspense,{children:T.jsx(Md,{...s,children:e})})})}),Md=t=>{const[e,s]=f.useState(),[r,o]=f.useState(!1),{setModel:n}=f.useContext(Ir),i=f.useContext(Sr);if(f.useEffect(()=>{t.model&&(s(t.model),n(t.model),o(!0),i&&i.addModel(t.model))},[i,t.model,n]),t.error)throw vb.error(t.error),new Error(t.error);const a=t.loading||T.jsx(Mb,{});return T.jsx(T.Fragment,{children:e&&r?t.children:a})},As={header:{title:"Model",createLabel:"Create new Model",deleteLabel:"Delete"},createModal:{okText:"OK",cancelText:"Cancel",title:"Create New Model"}},Ed=f.createContext(As),Eb=({translations:t=As,children:e})=>{const s={header:{...As.header,...t.header},createModal:{...As.createModal,...t.createModal}};return T.jsx(Ed.Provider,{value:s,children:e})};function Tb(t,e){const s=I.create(t,!1,e),r=s.whenReady().then(()=>s);return _o(r)}const Td=f.createContext(void 0),_b=(t={models:{},preloadModels:[]},e)=>{const s=Tb(t,e),r=({children:o})=>{const n=s.read(),[i,a]=f.useState(n.isOnline);f.useEffect(()=>{const d=G(()=>{a(n.isOnline)});return()=>{d()}},[n]);const c=f.useMemo(()=>({kosCore:n,online:i}),[n,i]);return T.jsx(Td.Provider,{value:c,children:o})};return{KosCoreContextProvider:po.observer(r)}},_d=()=>{const t=f.useContext(Td);if(t===void 0)throw new Error("useKosCore must be used within a KosCoreContextProvider");return t},Ib=8,Sb=(t=0)=>new Promise(e=>{setTimeout(()=>{e(!0)},2**t*10)}),Be=new Map;function Ob(t,e){if(Be.has(t)){const s=Be.get(t);if(s.status==="finished"){const r=I.getInstance().modelManager.getModelById(t);return{kosModel:r,model:r==null?void 0:r.modelData}}else throw s.promise}else{const s=e().then(()=>{Be.set(t,{status:"finished",key:t})},o=>{throw Be.set(t,{status:"error",error:o}),o}),r={status:"pending",promise:s};throw Be.set(t,r),s}}function $b(t,e){return Ob(t,e)}async function Db(t,e){const{modelId:s,factory:r,modelType:o,options:n,activate:i}=e;let a=0;await t.whenReady();let c;if(n){const u=typeof o=="string"?t.modelManager.getModelFactory(o):r;if(!u)throw Error("No Factory Specified. Cannot create a new instance");c=u.build(s,n)}const d=t.modelManager.getModelById(s);if(!d){if(a>Ib)throw Error(`KOS Model ${s} has not been found`);await Sb(a),a=a+1}return await(d==null?void 0:d.whenReady()),d?(c=d.modelData,{kosModel:d,model:c}):{kosModel:void 0,model:void 0}}const q=t=>{const{modelId:e,modelType:s,activate:r,destroyOnUnmount:o}=t,n=_d(),[i,a]=f.useState(!1),[c,d]=f.useState(),{kosModel:u,model:h}=$b(e||s||"",()=>Db(n.kosCore,t));return f.useEffect(()=>{async function g(){try{return await n.kosCore.whenReady(),r&&await(u==null?void 0:u.fsm.transitionTo(A.GO_ACTIVE,w.ACTIVE)),a(!0),u}catch(y){d(y.message)}}let m;return n.kosCore&&e&&g().then(y=>{m=G(()=>{const v=(y==null?void 0:y.status)===w.READY;a(v)})}).catch(y=>{console.error(y)}),()=>{if(r){if(h!=null&&h.id){const y=n.kosCore.modelManager.getModelById(h.id);y==null||y.fsm.transitionTo(A.GO_INACTIVE,w.INACTIVE).then(()=>{if(o){const v=h.id;He(h).then(()=>{Be.delete(v),m==null||m()})}})}}else o&&h&&He(h).then(()=>{Be.delete(e),m==null||m()})}},[r,o,n.kosCore,u,h,e]),{model:h,ready:i,error:c,status:{model:h,ready:i,error:c},KosModelLoader:vd}},bn=()=>{const t=Ks.type;return q({modelId:t,modelType:Ks.type,options:{}})},wn=f.createContext(void 0),Cb=({children:t})=>{const{model:e,ready:s}=bn(),r=f.useMemo(()=>s&&e?{model:e}:{},[s,e]);return T.jsx(wn.Provider,{value:r,children:t})},Rb=()=>{const t=f.useContext(wn);if(!t)throw new Error("useKosTimeContext must be used within a KosTimeProvider");return t},vn=()=>{const t=qs.type;return q({modelId:t,modelType:qs.type,options:{}})};function Ab(t){return()=>e=>{const{model:s,status:r,KosModelLoader:o}=vn();return T.jsx(o,{...r,children:T.jsx(t,{...e,softwareInfo:s})})}}const Mn=f.createContext(void 0),xb=({children:t})=>{const{model:e,ready:s}=vn(),r=f.useMemo(()=>s&&e?{model:e}:{},[s,e]);return T.jsx(Mn.Provider,{value:r,children:t})},Pb=()=>{const t=f.useContext(Mn);if(!t)throw new Error("useSoftwareInfoContext must be used within a SoftwareInfoProvider");return t},Id=new ic,Sd=f.createContext(Id);function Lb({children:t}){return T.jsx(Sd.Provider,{value:Id,children:t})}const En=f.createContext(void 0),kb=()=>{const t=window.location.origin,e=ue();return(e==null?void 0:e.host)||t},Fb=({children:t,appContext:e,locale:s="en",resolver:r,rootUrl:o,descriptorResolver:n})=>{const[i,a]=f.useState(!1),[c,d]=f.useState(),[u,h]=f.useState(),g=o||kb(),m=f.useMemo(()=>e??"app/system",[e]);f.useEffect(()=>{async function E(){const N=(Array.isArray(m)?m:[m]).map(W=>(n||Ml(W))()),P=(await Promise.allSettled(N)).map(W=>{if(W.status==="rejected"){p.warn("Failed to load localization descriptor",W.reason);return}return W.value}).filter(W=>!!W).reverse().reduce((W,re)=>{const L=re.path;return Object.keys(re.namespaces).forEach(Ce=>{const V=re.namespaces[Ce];V.basePath=L}),{...W,namespaces:{...W.namespaces,...re.namespaces}}},{});d(P)}E()},[m,n]),f.useEffect(()=>{async function E(){if(c){const _=g,{translations:N}=await Sl.init({lang:s,descriptor:c,defaultNamespace:"common",resolver:r,rootUrl:_});h(N),a(!0)}}E()},[s,c,r,g]);const y=f.useMemo(()=>i?{setLocale:E=>{u&&(u.currentLocale=E)}}:{setLocale:()=>{throw new Error("Translations not ready")}},[i,u]),v=i?t:null;return T.jsx(En.Provider,{value:y,children:v})},Nb=()=>{const t=f.useContext(En);if(!t)throw new Error("useTranslationContainerContext must be used within a TranslationContainerProvider");return t},Ub=()=>{const t=ht.type;return q({modelId:t,modelType:ht.type,options:{}})};function jb(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Ub();return T.jsx(o,{...r,children:T.jsx(t,{...e,canvasDispatcher:s})})}}const Bb=(t,e,s)=>{const r=atob(t),o=new Uint8ClampedArray(e*s*4);for(let n=0,i=0;n<r.length&&i<o.length;n+=3,i+=4)o[i]=r.charCodeAt(n),o[i+1]=r.charCodeAt(n+1),o[i+2]=r.charCodeAt(n+2),o[i+3]=255;return o};function Kb({ctx:t,format:e,dataString:s,width:r,height:o,pixelSize:n}){const i=Bb(s,r,o),a=new ImageData(i,r,o),c=document.createElement("canvas");c.width=r,c.height=o;const d=c.getContext("2d");d==null||d.putImageData(a,0,0),t.imageSmoothingEnabled=!1,t.clearRect(0,0,r*n,o*n),t.drawImage(c,0,0,r*n,o*n)}const Hb=p.createLogger({name:"canvas-streamer"});Hb.debug("main-view component loaded");const Br=10,Od=po.observer(({canvasDispatcher:t,height:e=30,width:s=50,defaultFps:r=10,showPreview:o=!1,name:n,apiPath:i="/api/system/canvas"})=>{const a=f.useRef(null),[c,d]=f.useState();f.useEffect(()=>{const h=t.addNamedEndpoint(n,{apiPath:i,fps:r,width:s,height:e,id:n});d(h)},[t]);const u=f.useCallback(h=>{if(a.current&&o){const g=a.current.getContext("2d");g&&Kb({ctx:g,format:"base64",dataString:h,height:e,width:s,pixelSize:Br})}},[s,e,o]);return f.useEffect(()=>{c&&(c.onFrame=u,c.width=s,c.height=e,c.fps=r)},[c,u,s,e,r]),o&&ii.createPortal(T.jsx(Gb,{children:T.jsx(Vb,{children:T.jsx("canvas",{ref:a,width:s*Br,height:e*Br,style:{border:"1px solid black"}})})}),document.body)}),zb=jb(Od),Gb=go.div`
183
183
  display: flex;
184
184
  flex-direction: column;
185
185
  gap: 8px;
@@ -187,9 +187,9 @@ ${d}topics:${e}
187
187
  width: 100%;
188
188
  justify-content: space-between;
189
189
  align-items: center;
190
- `,Gb=co.div`
190
+ `,Vb=go.div`
191
191
  display: flex;
192
192
  flex-direction: column;
193
193
  align-items: center;
194
- `,$d=()=>{const t=or.type;return q({modelId:t,modelType:or.type,options:{}})};function Vb(t){return e=>{const{model:s,status:r,KosModelLoader:o}=$d();return T.jsx(o,{...r,children:T.jsx(t,{...e,device:s})})}}function Yb(t,e,s){const r=new Promise(o=>{I.getInstance().whenReady().then(()=>{const{model:n}=I.getInstance().modelManager.createModelInstance(t,e??t,s);return n.whenReady().then(()=>{o(n.modelData)})})});return wo(r)}function qb(t){return e=>{const{model:s,status:r,KosModelLoader:o}=fn();return T.jsx(o,{...r,children:T.jsx(t,{...e,kosTime:s})})}}const Dd=()=>{const t=ts.type;return q({modelId:t,modelType:ts.type,options:{}})};function Wb(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Dd();return T.jsx(o,{...r,children:T.jsx(t,{...e,networkInterfaceContainer:s})})}}const Cd=()=>{const t=Ys.type;return q({modelId:t,modelType:Ys.type,options:{}})};function Qb(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Cd();return T.jsx(o,{...r,children:T.jsx(t,{...e,oTA:s})})}}function Zb(t,e){f.useEffect(()=>{function s(o){t.current&&!t.current.contains(o.target)&&e()}function r(o){o.key==="Escape"&&e()}return document.addEventListener("mousedown",s),document.addEventListener("keydown",r,!1),()=>{document.removeEventListener("mousedown",s),document.removeEventListener("keydown",r,!1)}},[t,e])}function Xb(t){const e=f.useRef(null),s=t.onAlert;return Zb(e,s),T.jsx("div",{ref:e,style:{width:"100%"},children:t.children})}const Jb=t=>{var d;const{stateProp:e}=t,[s,r]=f.useState((d=t.stateProp)==null?void 0:d.value),[o,n]=f.useState(!1),[i,a]=f.useState(void 0);return f.useEffect(()=>{async function u(h){try{h&&(await ae(h),n(!0))}catch(g){a(g.message)}}u(e)},[e]),f.useEffect(()=>{const u=G(()=>{e&&o&&r(e.value)});return()=>{u()}},[o,e]),[s,{ready:o,error:i}]},Rd=()=>{const[t,e]=f.useState(!1),[s,r]=f.useState([]),o=ht.type,n=q({modelId:o,modelType:ht.type,options:{}});return f.useEffect(()=>{const i=G(()=>{var a,c;e(((a=n.model)==null?void 0:a.isStorageInserted)??!1),r(((c=n.model)==null?void 0:c.data)??[])});return()=>{i()}},[n.model]),{...n,inserted:t,devices:s}};function ew(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Rd();return T.jsx(o,{...r,children:T.jsx(t,{...e,storageDeviceContainer:s})})}}const Br=p.createLogger({name:"use-timer"}),tw=({timerName:t,onTimerExpired:e,onTimerTick:s,timerEventActions:r,autoStart:o})=>{const n=cd.getTimer(t);f.useEffect(()=>{if(!n){console.warn(`Timer with name ${t} does not exist.`);return}const d=O(ln,u=>{const{name:h,action:g,remainingTime:m}=u==null?void 0:u.body;h===t&&(g===un?e({name:h,action:g,remainingTime:m,timer:n}):r!=null&&r[g]&&r[g]({name:h,action:g,remainingTime:m,timer:n}))});return o&&n.start(),()=>{d.unsubscribe()}},[o,e,r,t,n]),f.useEffect(()=>{if(!n||!s)return;const d=`${dn}/${t}`,u=O(d,h=>{const{name:g,remainingTime:m}=h==null?void 0:h.body;g===t&&s({name:g,remainingTime:m,timer:n})});return()=>{u.unsubscribe()}},[s,t,n]);const i=f.useCallback(()=>{n?n.start():Br.warn(`Timer with name ${t} does not exist.`)},[n,t]),a=f.useCallback(()=>{n?n.reset():Br.warn(`Timer with name ${t} does not exist.`)},[n,t]),c=f.useCallback(()=>{n?n.pause():Br.warn(`Timer with name ${t} does not exist.`)},[n,t]);return{timer:n,start:i,reset:a,pause:c}},sw=t=>{const e=/[\\^$.*+?()[\]{}|]/g;return RegExp(e.source).test(t)?t.replace(e,"\\$&"):t},rw=t=>t instanceof RegExp,ow=t=>typeof t=="string",nw=(t,e,s)=>{if(t===""||e==="")return t;let r=e;rw(r)||(r=new RegExp("("+sw(r)+")","gi"));const o=t.split(r);for(let n=1,i=o.length;n<i;n+=2)o[n]=s(o[n],n);return o},Ad=(t,e,s)=>{let r=t;return Array.isArray(r)||(r=[r]),r.flatMap(o=>ow(o)?nw(o,e,s):o)};function iw(t,e){let s=t;return Object.entries(e).forEach(([r,o])=>{const n=new RegExp(`<${r}>(.*?)</${r}>|<${r}/>`,"g");s=Ad(s,n,(i,a)=>o.type==="br"?T.jsx("br",{}):f.cloneElement(o,{key:`${r}-${a}`},i))}),s}const aw=t=>{const{i18nKey:e,t:s,defaults:r,components:o,values:n={},context:i}=t,a=s(e,{defaultValue:r,data:n,context:i,returnObjects:!0}),c=iw(a,o||{});return T.jsx("span",{className:t.className,children:c})},tt=new Map;function cw(t,e){if(tt.has(t)){const s=tt.get(t);if(s.status==="finished")return s.result;throw s.promise}else{const s=e().then(o=>{tt.set(t,{status:"finished",result:o})},o=>{throw tt.set(t,{status:"error",error:o}),o}),r={status:"pending",promise:s};throw tt.set(t,r),s}}function no(t,e){return cw(t,e)}const lw=async()=>{const t=await za(Oe.type);return await ae(t.model),t.model},dw=async(t,e,s)=>{const r=t.resolveNamespace(e);await ae(r);for(const o of s){const n=t.resolveNamespace(o);await ae(n),tt.set(o,{status:"finished",result:n})}return r},uw=(t,e)=>{const s=[t].flat(),[r,...o]=s,n=no(Oe.type,lw),i=s.join("__"),a=no(i,()=>dw(n,r,o)),c=f.useMemo(()=>({exists:u=>{const h=e!=null&&e.keyPrefix?`${e.keyPrefix}.${u}`:u;return a?a.exists(h):!1}}),[e==null?void 0:e.keyPrefix,a]);return{t:f.useCallback((u,h)=>{const g=e!=null&&e.keyPrefix?`${e.keyPrefix}.${u}`:u;return a?a.resolveKey(g,h):(p.debug(`Translation model ${t} not ready for key: ${g}`),g)},[e==null?void 0:e.keyPrefix,t,a]),i18n:c}},xd=()=>{const t=Oe.type;return q({modelId:t,modelType:Oe.type,options:{}})};function hw(t){return e=>{const{model:s,status:r,KosModelLoader:o}=xd();return T.jsx(o,{...r,children:T.jsx(t,{...e,translationContainer:s})})}}const fw=t=>q({modelId:t,modelType:Jt.type}),bn=()=>q({modelId:lt.type,modelType:lt.type,options:{}}),gw=({troubleType:t,condition:e})=>{const{model:s}=bn(),[r,o]=f.useState(!1),[n,i]=f.useState([]),a=f.useCallback(()=>{var c,d;return n.length>0&&((c=n[0])!=null&&c.resolvable)?(d=n[0])==null?void 0:d.resolve():Promise.resolve(void 0)},[n]);return f.useEffect(()=>G(()=>{const d=(t?s==null?void 0:s.troubles.getIndexByKey("byType",t):s==null?void 0:s.troubles.data)||[],u=e?d.filter(e):d;o(u.length>0),i(u)}),[e,s,t]),[r,a,n.length>0?n[0]:void 0,n]};function pw(t){return e=>{const{model:s,status:r,KosModelLoader:o}=bn();return T.jsx(o,{...r,children:T.jsx(t,{...e,troubleContainer:s})})}}const Pd=()=>{const t=rs.type,e=q({modelId:t,modelType:rs.type,options:{},activate:!0,destroyOnUnmount:!0}),[s,r]=f.useState(!1),[o,n]=f.useState(!1),[i,a]=f.useState([]);return f.useEffect(()=>{const c=G(()=>{var d,u,h;r(((d=e.model)==null?void 0:d.isUsbInserted)??!1),n(((u=e.model)==null?void 0:u.hasAvailableUpdates)??!1),a(((h=e.model)==null?void 0:h.data)??[])});return()=>{c()}},[e.model]),{...e,inserted:s,updateAvailable:o,updates:i}};function mw(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Pd();return T.jsx(o,{...r,children:T.jsx(t,{...e,usbUpdateContainer:s})})}}const yw=({path:t,propKey:e})=>{const{status:s}=q({modelType:Yt.type,modelId:t,options:{path:t}}),[r,o]=f.useState(!1),[n,i]=f.useState(),[a,c]=f.useState(""),[d,u]=f.useState(),h=g=>{n&&e&&n.updateProperty(e,g)};return f.useEffect(()=>{var g;s.model&&i(s.model),s.model&&e&&((g=s.model)!=null&&g.props.has(e)?c(s.model.props[e]):u(`property ${e} not found`)),s.ready&&o(s.ready)},[s.ready,s.model,e]),f.useEffect(()=>{e&&M.autorun(()=>{const g=n==null?void 0:n.props[e];c(g||"")})},[n,e]),{config:n,ready:r,value:a,error:d,updateValue:h}},bw=(t,e)=>{switch(e.type){case"UPDATE":return e.payload;default:return t}},Ld=({configProperty:t,optionsTransformer:e})=>{const[s,r]=f.useState(!1),[o,n]=f.useState(""),[i,a]=f.useReducer(bw,{value:String(t==null?void 0:t.value),displayValue:t==null?void 0:t.displayValue,significantValue:t==null?void 0:t.significantValue,unit:t==null?void 0:t.unit,options:t==null?void 0:t.options,mappedOptions:[],updateProperty:t==null?void 0:t.updateProperty,displayOptions:t==null?void 0:t.displayOptions}),c=f.useCallback(d=>{var h;let u="factory";typeof d=="string"?u=d:(h=d==null?void 0:d.target)!=null&&h.value&&(u=d.target.value),u&&(t==null||t.updateProperty(u))},[t]);return f.useEffect(()=>{async function d(u){try{u&&(await ae(u),r(!0))}catch(h){n(h.message)}}d(t)},[t]),f.useEffect(()=>{const d=G(()=>{if(t&&s){let u=[];e&&(u=e(t.options)),a({type:"UPDATE",payload:{value:String(t.value),displayValue:t.displayValue,significantValue:t.significantValue,unit:t.unit,options:t.options,mappedOptions:u,updateProperty:t.updateProperty,displayOptions:t==null?void 0:t.displayOptions}})}});return()=>{d()}},[t,e,s]),{...i,configSelectProps:{onChange:c,value:i.value,options:e?i.mappedOptions||[]:i.options||[]},ready:s,error:o}};function ww(t,e){const s=e??new Date().getFullYear(),r=[31,28,31,30,31,30,31,31,30,31,30,31];return t===1&&(s%4===0&&s%100!==0||s%400===0)?29:r[t]??0}function vw(t,e){return new Date(t,e,0).getDate()}function kd(t,e){const s=ww(e,t),r=[];for(let o=1;o<=s;o++)r.push(o);return r}function Fd(){return[...Array(12).keys()].map(e=>new Date(0,e).getMonth())}function Nd(t=[2018,2028]){const e=[];for(let s=t[0];s<=t[1];s++)e.push(s);return e}function Ud(t,e=[2018,2028]){const s=Nd(e);return t==="long"?s:s.map(r=>Number(r.toString().substring(2)))}function wn(t="numeric",e="en-US"){const s=new Intl.DateTimeFormat(e,{month:t,timeZone:"UTC"}).format;return[...Array(12).keys()].map(r=>s(new Date(Date.UTC(0,r,1))))}function Mw({locale:t="en-US",year:e,month:s,day:r,formatOptions:o={weekday:"long",year:"numeric",month:"long",day:"numeric"},displayOrder:n}){const i=s-1,a=new Date(e,i,r),c=new Intl.DateTimeFormat(t,{month:o.month}).format(a),d=new Intl.DateTimeFormat(t,{year:o.year}).format(a),u=new Intl.DateTimeFormat(t,{day:o.day}).format(a);return n?n=="MMDDYY"?`${c} ${u} ${d}`:n==="DDMMYY"?`${u} ${c} ${d}`:n==="YYMMDD"?`${d} ${c} ${u}`:`${d} ${u} ${c}`:new Intl.DateTimeFormat(t,o).format(a)}function ge(t){return t.toString().length===2?new Date(Date.parse(`01 Jan 20${t}`)).getFullYear():t}function Ew(t){return typeof t=="string"?new Date(Date.parse(`01 ${t.substring(0,3)} 2023`)).getMonth()+1:t}function jd(t,e,s){const r=ge(e),o=new Date(r,t,1).getDay(),n=new Date(r,t+1,0).getDate();return[...Array(42).keys()].map(a=>a<o||a>n+o-1?{label:"",value:0,disabled:!0}:s[a-o])}function Lt(t,e,s){const r=e-1,o=new Date(t,r,s);return new Date(o).getMonth()===r&&new Date(o).getDate()===s}function kt(t,e){return new Date(t,e,0).getDate()}function Bd(t="en-US",e="short"){const s=new Intl.DateTimeFormat(t,{weekday:e}).format;return[...Array(7).keys()].map(r=>s(new Date(Date.UTC(2021,5,r))))}function Kd({locale:t="en-US",year:e=new Date().getFullYear(),month:s=new Date().getMonth(),yearRange:r=[2018,2028],daysOfWeekFilter:o=[],formatOptions:{yearFormat:n="long",monthFormat:i="long",dayFormat:a="short"}={}}){const c=vn(n,r),d=Hd(n,r,t),u=zd(i,t),h=Gd(i,t),g=Mn(e,s),m=Vd(e,s,t,o),y=Wd(s,e,m),v=Yd(t,a);return{daysArray:g,monthsArray:u,yearsArray:c,yearsOptionsArray:d,monthsOptionsArray:h,daysOptionsArray:m,calendarDayArray:y,dayNamesArray:v}}function vn(t="long",e=[2018,2028]){return f.useMemo(()=>Ud(t,e),[t,e])}function Hd(t="long",e=[2018,2028],s="en-US"){const r=vn(t,e);return f.useMemo(()=>r.map(n=>({label:n.toLocaleString(s).replace(",",""),value:n})),[s,r])}function zd(t,e="en-US"){return f.useMemo(()=>wn(t,e),[t,e])}function Gd(t,e="en-US"){const s=f.useMemo(()=>Fd(),[]),r=f.useMemo(()=>wn(t,e),[t,e]);return f.useMemo(()=>[...Array(12).keys()].map(n=>({label:r[n],value:Number(s[n])})),[r,s])}function Mn(t,e){const s=ge(t);return f.useMemo(()=>kd(s,e),[e,s])}const Tw=(t,e,s,r=[])=>{const o=new Date(t,e,s).getDay();return r.length>0&&r.includes(o)};function Vd(t,e,s="en-US",r=[]){const o=Mn(t,e);return f.useMemo(()=>o.map(i=>({label:i.toLocaleString(s),value:i,disabled:Tw(t,e,i,r)})),[r,s,e,o,t])}function Yd(t="en-US",e="short"){return f.useMemo(()=>Bd(t,e),[t,e])}function qd({year:t=new Date().getFullYear(),month:e=new Date().getMonth(),day:s=new Date().getDate(),formatString:r}){const o=e,n=new Date(t,o,s);return{formattedDate:Re.format(n,r)}}function Wd(t,e,s){return f.useMemo(()=>jd(t,e,s),[t,e,s])}var Qd=(t=>(t.MMDDYY="MMDDYY",t.DDMMYY="DDMMYY",t.YYMMDD="YYMMDD",t.YYDDMM="YYDDMM",t))(Qd||{});function _w({locale:t="en-US",date:{year:e=new Date().getFullYear(),month:s=new Date().getMonth(),day:r=new Date().getDate()}={year:new Date().getFullYear(),month:new Date().getMonth(),day:new Date().getDate()},formatOptions:{yearFormat:o="long",monthFormat:n="long",dayFormat:i="short",formatString:a="yyyy/MM/dd"}={},filterOptions:{yearsRange:c=[2018,2028],daysOfWeekFilter:d=[]}={}}){const[u,h]=f.useState(e),[g,m]=f.useState(c),[y,v]=f.useState(s),[E,_]=f.useState(r);f.useEffect(()=>{h(e)},[e]),f.useEffect(()=>{v(s)},[s]),f.useEffect(()=>{_(r)},[r]);const{yearsArray:N,yearsOptionsArray:x,monthsArray:D,monthsOptionsArray:P,daysArray:W,daysOptionsArray:re,calendarDayArray:L,dayNamesArray:Ce}=Kd({locale:t,year:u,yearRange:g,month:y,formatOptions:{yearFormat:o,monthFormat:n,dayFormat:i},daysOfWeekFilter:d}),{formattedDate:V}=qd({year:u,month:y,day:E,formatString:a});return{dateActions:{setYear:h,setYearRange:m,setMonth:v,setDay:_,nextMonth:()=>{const Z=y<11?ge(u):ge(u+1),ne=y<11?y+1:0;if(!Lt(Z,ne,E)){const Fe=kt(Z,ne);_(Fe)}ne===0&&h(Z),v(ne)},previousMonth:()=>{const Z=ge(y===0?u-1:u),ne=y===0?11:y-1;if(!Lt(Z,ne,E)){const Fe=kt(Z,ne);_(Fe)}ne===11&&h(Z),v(ne)},nextYear:()=>{const Z=u<g[1]?u+1:g[0],ne=ge(Z);if(Lt(ne,y,E))h(Z);else{const Fe=kt(ge(u+1),y);_(Fe),h(Z)}},previousYear:()=>{const Z=u>g[0]?u-1:g[0],ne=ge(Z);if(Lt(ne,y,E))h(Z);else{const Fe=kt(ge(u-1),y);_(Fe),h(Z)}}},dateState:{year:u,yearRange:g,month:y,day:E,yearsArray:N,yearsOptionsArray:x,monthsArray:D,monthsOptionsArray:P,daysArray:W,daysOptionsArray:re,calendarDayNames:Ce,calendarDayArray:L,formattedDate:V}}}function Zd({date:t=new Date,dateFormat:e,timeFormat:s,options:r={}}){const[o,n]=f.useState("Formatting Time..."),[i,a]=f.useState("Formatting Date..."),c=!!r.ignoreDateFormat,{model:d,ready:u}=q({modelId:ee.type,modelType:ee.type,options:{}}),h=typeof t=="string"?Re.parseISO(t):t;return f.useEffect(()=>{c?a(""):e?a(Re.format(h,e)):u&&a(Re.format(h,d!=null&&d.selectedDateFormat?d==null?void 0:d.selectedDateFormat:""))},[c,t,e,h,d,u]),f.useEffect(()=>{s?n(Re.format(h,s)):u&&n(Re.format(h,d!=null&&d.selectedTimeFormat?d==null?void 0:d.selectedTimeFormat:""))},[t,s,h,d,u]),{formattedDate:i,formattedTime:o}}const Xd=({secondsFromMidnight:t=0})=>{const[e,s]=f.useState(0),[r,o]=f.useState(0),[n,i]=f.useState(0),[a,c]=f.useState(new Date),{formattedTime:d}=Zd({date:a,options:{ignoreDateFormat:!0}});return f.useEffect(()=>{const u=Number(t),h=Math.floor(u/3600),g=Math.floor(u%3600/60),m=u%60;s(h),o(g),i(m);const y=new Date;y.setHours(0,0,0,0);const v=new Date(y.getTime()+u*1e3);c(new Date(v))},[t]),{hours:e,minutes:r,seconds:n,formattedTime:d,timeActions:{setHours:s,setMinutes:o,setSeconds:i}}},Iw=({configProperty:t})=>{const{value:e}=Ld({configProperty:t}),s=parseInt(e||"0",10),{hours:r,minutes:o,seconds:n,formattedTime:i,timeActions:a}=Xd({secondsFromMidnight:s}),c=f.useRef();return f.useEffect(()=>{const d=r*3600+o*60+n;return c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{t&&t.updateProperty(d.toString())},100),()=>{c.current&&clearTimeout(c.current)}},[t,r,o,n]),{hours:r,minutes:o,seconds:n,formattedTime:i,timeActions:a}};function Sw(t,e={}){const{intervalMs:s=5*60*1e3,immediate:r=!0}=e;f.useEffect(()=>{const o=()=>{try{t({__warmup:!0})}catch{}};r&&("requestIdleCallback"in window?requestIdleCallback(o):setTimeout(o,1));const n=s?setInterval(o,s):null;return()=>{n&&clearInterval(n)}},[t,s,r])}const Ow=t=>T.jsx("option",{title:t.id,value:t.format,children:t.format},t.id),$w=(t=Ow)=>{const[e,s]=f.useState([]),[r,o]=f.useState(),{model:n,ready:i}=q({modelType:ee.type,modelId:ee.type,options:{}});f.useEffect(()=>{const c=G(()=>{s((n==null?void 0:n.dateFormatOptions.map(t))||[])});return()=>{c()}},[n,i,t]),f.useEffect(()=>{const c=G(()=>{n!=null&&n.dateFormatId&&(n!=null&&n.selectedDateFormat)&&o({id:n==null?void 0:n.dateFormatId,value:n==null?void 0:n.selectedDateFormat})});return()=>{c()}},[n==null?void 0:n.selectedDateFormat,n==null?void 0:n.dateFormatId]);const a=f.useCallback(c=>{var u;let d="";typeof c=="string"?d=c:(u=c==null?void 0:c.target)!=null&&u.value&&(d=c.target.value),d&&(n==null||n.setSelectedDateFormat(d))},[n]);return{raw:(n==null?void 0:n.dateFormatOptions.map(c=>c.id))??[],regionModel:n,selectedDateFormat:(r==null?void 0:r.value)||"",dateFormatId:(r==null?void 0:r.id)||"",updateDateFormat:a,props:{onChange:a,value:(r==null?void 0:r.id)||"",options:e}}},Dw=t=>T.jsx("option",{title:t,value:t,children:t},t),Jd="kos:service:region:settings",eu="timeZone",Cw=`${Jd}-${eu}`,Rw=(t=Dw)=>{const[e,s]=f.useState([]),[r,o]=f.useState(""),{model:n,ready:i}=q({modelType:ee.type,modelId:ee.type,options:{}}),a=Ve.factory(Cw)({path:Jd,attribute:eu});f.useEffect(()=>{const d=G(()=>{s((n==null?void 0:n.timeZones.map(t))||[]),n!=null&&n.timeZones.length&&oo(n==null?void 0:n.timeZones[0])});return()=>{d()}},[n,i,t]),f.useEffect(()=>{const d=G(()=>{o(a.value||"")});return()=>{d()}},[a.value]);const c=f.useCallback(d=>{var h;let u="factory";typeof d=="string"?u=d:(h=d==null?void 0:d.target)!=null&&h.value&&(u=d.target.value),u&&oo(u)},[]);return{options:e,raw:(n==null?void 0:n.timeZones)??[],regionModel:n,selectedTimeZone:r,timeZones:(n==null?void 0:n.timeZones)??[],updateTimeZone:c,selectProps:{onChange:c,value:r,options:e}}},tu="kos:service:region",su="regionId",Aw=`${tu}-${su}`,xw=t=>T.jsx("option",{title:t,value:t,children:t},t),ru=(t=xw)=>{const[e,s]=f.useState([]),[r,o]=f.useState("factory"),{model:n,ready:i}=q({modelType:ee.type,modelId:ee.type,options:{}}),a=Ve.factory(Aw)({path:tu,attribute:su});f.useEffect(()=>{const d=G(()=>{s((n==null?void 0:n.availableRegions.map(t))||[])});return()=>{d()}},[n,i,t]),f.useEffect(()=>{const d=G(()=>{o(a.value||"factory")});return()=>{d()}},[a.value]);const c=f.useCallback(d=>{var h;let u="factory";typeof d=="string"?u=d:(h=d==null?void 0:d.target)!=null&&h.value&&(u=d.target.value),u&&id(u)},[]);return{raw:(n==null?void 0:n.availableRegions)??[],regionModel:n,regionData:n==null?void 0:n.selectedRegion,selectedRegion:r,updateRegion:c,regionSelectProps:{onChange:c,value:r,options:e}}},Pw=t=>T.jsx("option",{title:t.id,value:t.format,children:t.format},t.id),Lw=(t=Pw)=>{const[e,s]=f.useState([]),[r,o]=f.useState(),{model:n,ready:i}=q({modelType:ee.type,modelId:ee.type,options:{}});f.useEffect(()=>{const c=G(()=>{s((n==null?void 0:n.timeFormatOptions.map(t))||[])});return()=>{c()}},[n,i,t]),f.useEffect(()=>{const c=G(()=>{n!=null&&n.timeFormatId&&(n!=null&&n.selectedTimeFormat)&&o({id:n==null?void 0:n.timeFormatId,value:n==null?void 0:n.selectedTimeFormat})});return()=>{c()}},[n==null?void 0:n.selectedTimeFormat,n==null?void 0:n.timeFormatId]);const a=f.useCallback(c=>{var u;let d="";typeof c=="string"?d=c:(u=c==null?void 0:c.target)!=null&&u.value&&(d=c.target.value),d&&(n==null||n.setSelectedTimeFormat(d))},[n]);return{raw:(n==null?void 0:n.timeFormatOptions.map(c=>c.id))??[],regionModel:n,selectedTimeFormat:(r==null?void 0:r.value)??"",timeFormatId:(r==null?void 0:r.id)??"",updateTimeFormat:a,props:{onChange:a,value:(r==null?void 0:r.id)??"",options:e}}},kw=(t,e)=>f.useMemo(()=>Ro(t),e),Fw={config:{attributes:!0,childList:!0,subtree:!0}};function Nw(t,e,s=Fw){const[r,o]=f.useState(null);f.useEffect(()=>{if(!e||typeof e!="function")throw new Error("A valid callback function is required");const n=new MutationObserver(e);o(n)},[e,s,o]),f.useEffect(()=>{if(!r)return()=>{};if(!t)throw new Error("A valid DOM element is required");const{config:n}=s;try{r.observe(t,n)}catch(i){p.error(i)}return()=>{r&&r.disconnect()}},[r,t,s])}const ou={validateStart:function(t){return!0},validateStop:function(t){const e=t.event.currentTarget.getBoundingClientRect(),[s,r]=t.xy;return s<e.left||s>e.right||r<e.top||r>e.bottom}},Kr=p.createLogger({name:"usePressGesture",group:"kos-hooks"});function Uw({onPressed:t,onRelease:e,intersectionStrategy:s=ou}){const r=f.useRef(!1),o=pu.useGesture({onDragStart:c=>{Kr.info("onDragStart",c.type),s.validateStart(c)&&(t&&t(),r.current=!0)},onDrag:c=>{Kr.info("onDrag",c.type),r.current&&s.validateStop(c)&&(e&&e(),r.current=!1)},onDragEnd:c=>{Kr.info("onDragEnd",c.type),r.current&&e&&(e(),r.current=!1)}}),n=()=>{t&&t(),r.current=!0},i=()=>{r.current&&e&&(e(),r.current=!1)},a=()=>{r.current&&e&&(e(),r.current=!1)};return{dom:o,mesh:()=>({onPointerDown:n,onPointerUp:i,onPointerOut:a})}}const nu=()=>{const[t,e]=f.useState(!1),s=I.getInstance();return f.useEffect(()=>{const r=G(()=>{s&&s.reloading!==t&&e(s.reloading)});return()=>{r()}},[s,t]),[t]};function iu(t=!1,e="2-digit"){return f.useMemo(()=>{const s=t?12:24;return Array.from({length:s},(r,o)=>{const n=t&&o===0?12:o%s;return{id:o,label:e==="2-digit"?n.toString().padStart(2,"0"):n.toString()}})},[e,t])}function io(t,e="2-digit",s=0,r=0){return f.useMemo(()=>Array.from({length:t},(o,n)=>{const i=String(n+s);return{id:n+r,label:e==="2-digit"?i.padStart(2,"0"):i}}),[t,s,r,e])}function au(t="en-US"){return f.useMemo(()=>["AM","PM"].map(e=>{const s=new Intl.DateTimeFormat(t,{hour:"2-digit",hour12:!0}).formatToParts(new Date().setHours(e==="AM"?0:12))[2].value;return{id:s,label:s}}),[t])}function cu({formatOptions:{hour12:t=!0,hour:e="2-digit",minute:s="2-digit",second:r="2-digit"}={hour12:!0,hour:"2-digit",minute:"2-digit",second:"2-digit"},locale:o="en-US"}){const n=iu(t,e),i=io(60,s),a=io(60,r),c=au(o);return{hourOptions:n,minuteOptions:i,secondOptions:a,amPmOptions:c}}function lu(t,e){return Re.format(t,e)}function du({formatOptions:t,initialDate:e=new Date,locale:s="en-US",format:r="HH:mm"}){const[o,n]=f.useState(e),i=f.useCallback(v=>{n(E=>{const _=new Date(E);return _.setHours(Number(v)),_})},[]),a=f.useCallback(v=>{n(E=>{const _=new Date(E);return _.setMinutes(Number(v)),_})},[]),c=f.useCallback(v=>{n(E=>{const _=new Date(E);return _.setSeconds(Number(v)),_})},[]),d=f.useCallback(v=>{const E=new Date(v);n(E)},[]),u=lu(o,r),{hourOptions:h,minuteOptions:g,secondOptions:m,amPmOptions:y}=cu({formatOptions:t,locale:s});return{amPmOptions:y,formattedTime:u,hourOptions:h,minuteOptions:g,secondOptions:m,setHours:i,setMinutes:a,setSeconds:c,setTime:d,time:new Date(o)}}const jw=t=>{const{regionModel:e}=ru(),s=f.useMemo(()=>({hour12:e==null?void 0:e.is12HourTimeFormat}),[e==null?void 0:e.is12HourTimeFormat]);return du({...t,locale:e==null?void 0:e.regionId,format:e==null?void 0:e.selectedTimeFormat,formatOptions:s})};function Bw(t){return e=>{const[s]=nu();return s?T.jsx(pd,{message:"Wait a moment while your project reloads..."}):T.jsx(t,{...e})}}const si=p.createLogger({name:"studio-properties-service",group:"Services"}),Kw="/api/kos/studio/properties",uu=async t=>{if(si.debug("sending GET for studio-properties"),!t)throw si.error("connectionId is undefined"),new Error("connectionId is undefined");return await De.get(Kw,{},{destinationAddress:t,timeout:500})},Hw=Object.freeze(Object.defineProperty({__proto__:null,getStudioProperties:uu},Symbol.toStringTag,{value:"Module"}));var zw=Object.getOwnPropertyDescriptor,Gw=(t,e,s,r)=>{for(var o=r>1?void 0:r?zw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const hu="studio-properties-model",Vw="/kos/studio/properties",ri={"kos.studio.tool.legacy":1};let ao=class{constructor(t,e,s){l(this,"id");l(this,"connectionId");l(this,"unsubscribe",null);l(this,"logger");l(this,"data");this.id=t,this.logger=s.logger,this.data=Ae(),this.connectionId=e.connectionId}async init(){this.logger.debug(`initializing studio-properties ${this.id}`)}async load(){this.logger.debug(`loading studio-properties ${this.id}`)}async terminatePropertiesSession(){var t;(t=this.unsubscribe)==null||t.call(this)}async initializePropertiesSession(){this.unsubscribe=nt.getInstance().subscribeTopic({topic:Vw,destinationAddress:this.connectionId,callback:s=>{this.logger.error(`Received studio-properties message for connection ${this.connectionId}: ${JSON.stringify(s)}`)}});const[t,e]=await uu(this.connectionId);if(t){this.logger.error(`Error loading studio-properties: ${t}`),this.data.setValues(ri);return}if(e){const s=Object.keys(e).reduce((r,o)=>(r[o]=e[o]??o,r),{});this.data.setValues(s??ri),p.ifDebug(()=>this.logger.debug(`studio-properties loaded: ${JSON.stringify(s)}`))}}get(t){return this.data[t]}createObservableProperty(t){return Ro(()=>this.get(t))}};ao=Gw([R(hu)],ao);const Yw=new we({class:ao,type:hu});Object.defineProperty(exports,"makeAutoObservable",{enumerable:!0,get:()=>M.makeAutoObservable});Object.defineProperty(exports,"makeObservable",{enumerable:!0,get:()=>M.makeObservable});Object.defineProperty(exports,"kosComponent",{enumerable:!0,get:()=>lo.observer});exports.AuthState=Za;exports.BrowserKosRouter=ic;exports.BrowserRouter=Ho;exports.CanvasDispatcher=ut;exports.CanvasDispatcherServices=Hm;exports.CanvasRenderer=en;exports.CanvasStreamer=Hb;exports.CanvasStreamerBase=Od;exports.ChildModels=Nt;exports.CompanionDecoratorMixin=td;exports.CompanionParentModel=Ls;exports.ConfigBean=Yt;exports.CoreExtensionManager=jy;exports.CoreModels=cn;exports.CreateModelTranslationsContext=Ed;exports.CreateModelTranslationsProvider=Mb;exports.DateDisplayFormat=Qd;exports.DateHelpers=Ru;exports.DependencyLifecycle=H;exports.DependencyModels=F;exports.Device=or;exports.DeviceServices=uy;exports.DomIntersectionStrategy=ou;exports.EVENT_KOS_MODEL_READY=go;exports.EVENT_TROUBLE_ADDED=lg;exports.EVENT_TROUBLE_REMOVED=dg;exports.EXTENSION_CANVAS_RENDERER=Q;exports.EXTENSION_FEATURE_FLAG_RESOLVER=Zi;exports.EXTENSION_TROUBLE_DATA_MAPPER=Gs;exports.EXTENSION_TROUBLE_MAPPER=hs;exports.ErrorBoundaryWithFallback=md;exports.EventBus=wu;exports.EventBusFunctional=Mu;exports.EventBusState=Tu;exports.ExtensionManager=S;exports.FUTURE_CONTAINER_MODEL_TYPE=Pc;exports.FUTURE_MODEL_TYPE=_c;exports.FUTURE_NOT_ASSIGNED=xo;exports.FeatureFlagService=Xi;exports.FetchError=B;exports.FutureContainerFactory=Pe;exports.FutureContainerModel=kc;exports.FutureEndState=xe;exports.FutureFactory=wt;exports.FutureHandler=yr;exports.FutureManager=ze;exports.FutureModel=Cc;exports.FutureService=Ft;exports.HEADER_CACHE_CONTROL=li;exports.HEADER_CONTENT_TYPE=ci;exports.HEADER_DESTINATION_ADDR=$e;exports.HEADER_FOS_REQUEST_ID=di;exports.HEADER_METHOD=cr;exports.HEADER_ORDERED=ho;exports.HEADER_REQUEST_ID=os;exports.HEADER_REQUEST_TYPE=Me;exports.HEADER_RESPONSE_ID=lr;exports.HEADER_SOURCE_ADDR=ai;exports.HEADER_TOPIC=ii;exports.HEADER_URL=gt;exports.HEADER_WORK_TRACKER=fo;exports.HttpRouteHandlers=Ie;exports.KOS_MODEL_ID=xs;exports.KeyValue=Vo;exports.KeyValueServices=np;exports.Kos=te;exports.KosConfigPropertySpec=Ve;exports.KosContainerIndex=Do;exports.KosContextBean=oc;exports.KosContextManager=z;exports.KosCore=I;exports.KosCoreModelPropertyMapper=me;exports.KosDataContainer=Co;exports.KosDependencyTypes=lh;exports.KosExtensionUtils=Lu;exports.KosFeatureFlags=Ji;exports.KosFetchMethods=Ia;exports.KosGlobalConfig=To;exports.KosHttpRouteManager=So;exports.KosLog=p;exports.KosLogManager=zc;exports.KosLogManagerServices=up;exports.KosMockEvents=fi;exports.KosModel=ja;exports.KosModelCollectionProvider=mb;exports.KosModelContainer=Te;exports.KosModelContext=Ir;exports.KosModelEvents=A;exports.KosModelFactory=Kt;exports.KosModelFutureContainerMixin=fs;exports.KosModelLoader=vd;exports.KosModelLoaderDisplay=Md;exports.KosModelManager=Ha;exports.KosModelProvider=yd;exports.KosModelRegistrationFactory=we;exports.KosModelRegistry=ro;exports.KosModelState=w;exports.KosModelSymbol=oa;exports.KosModelVisitor=kf;exports.KosObservableData=ec;exports.KosRegistration=sg;exports.KosSingletonRegistration=rg;exports.KosTime=Ks;exports.KosTimeContext=gn;exports.KosTimeProvider=Db;exports.KosTimeServices=bp;exports.KosTimer=ad;exports.KosToken=nc;exports.KosTranslationProvider=kb;exports.KosTranslations=Sl;exports.KosWSTransportStatus=Ua;exports.KosWsEvents=ns;exports.LOADER_FEATURE_FLAG=Yu;exports.LOGIN_HOST=ui;exports.LOGIN_URL=mu;exports.LoadingMessage=pd;exports.LogBlock=Xt;exports.LogBlockContainer=Mr;exports.LogConfig=jt;exports.LogStream=zt;exports.LogStreamContainer=us;exports.LogStreamServices=Dp;exports.MODEL_DELETION_DELAY=Ka;exports.MiddlewareChain=Ja;exports.ModelEffects=Ke;exports.MultipleFutureHandler=Fg;exports.NestedModelContext=Sr;exports.NetworkInterface=rn;exports.NetworkInterfaceContainer=ts;exports.NetworkInterfaceServices=vy;exports.ObservableData=Ae;exports.Ota=Ys;exports.OutsideAlerter=Xb;exports.PLUGIN_EXTENSION_NAME=ku;exports.PORT=hi;exports.PROFILE_LOG_DEBUG=Bi;exports.PROFILE_LOG_INFO=Ki;exports.PROFILE_RELAX_STORE_VALIDATION=Nu;exports.PROFILE_TOOLS_PREVIEW=ji;exports.ParentModel=Ut;exports.PluginExtensionManager=Fu;exports.ProgressBar=hb;exports.ReferenceConfig=Os;exports.RegionInfo=ee;exports.RegionServices=vg;exports.RegistrationManager=C;exports.Registry=Uy;exports.STATUS=uo;exports.ServiceFactory=se;exports.SingletonKosModelRegistrationFactory=Ee;exports.SoftwareInfo=qs;exports.SoftwareInfoContext=mn;exports.SoftwareInfoProvider=Ab;exports.SoftwareInfoServices=dm;exports.StateBean=es;exports.StateBeanServices=pm;exports.StateProp=Qo;exports.StatePropServices=Im;exports.StorageDevice=ir;exports.StorageDeviceContainer=ht;exports.StorageDeviceServices=Iy;exports.StudioProperties=Yw;exports.StudioPropertiesServices=Hw;exports.SubscriptionHandlers=J;exports.TIMER_END=un;exports.TIMER_EVENT=ln;exports.TOPIC_TIMER_TICK_EVENT=dn;exports.TimerManager=cd;exports.TokenContext=Sd;exports.TokenProvider=Pb;exports.Topics=Ht;exports.Trans=aw;exports.TransitionMap=$s;exports.Transitions=_o;exports.Translation=Zs;exports.TranslationContainer=Oe;exports.TranslationContainerContext=yn;exports.TranslationContext=Lm;exports.TransportFactory=Vr;exports.Trouble=Jt;exports.TroubleContainer=lt;exports.TroubleServices=qp;exports.Troubles=de;exports.UsbUpdate=an;exports.UsbUpdateContainer=rs;exports.UsbUpdateServices=xy;exports.WS_EVENT_TYPE=Ol;exports.WebSocketEvents=pe;exports.WebSocketTransport=nt;exports.WsEventFactory=Xo;exports.acceptOrgInvitation=gd;exports.addDaysToDate=Ai;exports.addFuture=Sc;exports.addMonthsToDate=Ri;exports.api=Rc;exports.applyMixins=Iu;exports.arraysEqual=Su;exports.buildConfigBeanModel=fg;exports.buildFuture=Ko;exports.buildFutureModel=$c;exports.cancelFuture=Oc;exports.checkAppsStarted=ag;exports.convert=No;exports.convertFileSizeRaw=_u;exports.convertWithUnits=Sg;exports.createBaseMessage=$a;exports.createBroadcastMessageResponse=Pa;exports.createCancellablePromise=ib;exports.createClient=Oo;exports.createFosBaseMessage=Oa;exports.createHeaders=Da;exports.createKosHtpMessageResponse=La;exports.createKosMessage=Aa;exports.createKosMessageResponse=ka;exports.createKosModelFutureManager=Hy;exports.createLazyKosModelFutureManager=zy;exports.createMessageBody=ke;exports.createModelDependency=wa;exports.createOptionKey=Ju;exports.createPropKey=Ge;exports.createReadableStream=Ca;exports.createStudioMessage=Sa;exports.createStudioMessageRequest=Ra;exports.createStudioMessageResponse=xa;exports.debounce=Ni;exports.del=ia;exports.deleteFuture=Ic;exports.destroyKosModel=He;exports.evaluateScopes=gc;exports.executeChildrenModelLifecycle=Ea;exports.executeDependentModelLifecycle=It;exports.executeListLifecycle=Ma;exports.extractTrailingWildcard=la;exports.fetchModel=Yb;exports.findModel=uf;exports.findModels=Ga;exports.formatDate=Li;exports.formatDateSince=Ci;exports.formatDateTime=Fi;exports.formatTime=ki;exports.get=na;exports.getAllKosCompanionModels=Va;exports.getCalendarMonthArray=jd;exports.getCompanionMixin=rd;exports.getConfigBean=fc;exports.getDayStrings=Bd;exports.getDays=vw;exports.getDaysArray=kd;exports.getDaysInMonth=Eo;exports.getDependenciesByLifecycle=va;exports.getFormattedDate=Mw;exports.getFormattedMonth=Ew;exports.getFormattedMonthsArray=wn;exports.getFormattedYear=ge;exports.getFormattedYearsArray=Ud;exports.getFutures=zg;exports.getHttpRouteHandlers=aa;exports.getKosCompanionModel=hf;exports.getKosLocalizationDescriptor=Ml;exports.getKosMessageLogging=Vi;exports.getKosModel=za;exports.getKosModelSync=ve;exports.getKosModelType=df;exports.getKosSessionKey=rc;exports.getLastDayOfMonth=kt;exports.getLocalizationDescriptor=Om;exports.getLogLevel=Gi;exports.getLogMessageToStudio=Yi;exports.getMessageBody=Gr;exports.getMonthsArray=Fd;exports.getObservableCompanions=ff;exports.getQueryParams=ue;exports.getStartedApps=cg;exports.getTranslations=vl;exports.getYearsArray=Nd;exports.hasCompanionMixin=sd;exports.hasDecimals=uc;exports.hasHttpRouteHandlers=ks;exports.hasKosModelFutureSupport=Gy;exports.hasKosProfile=Hr;exports.hasTrailingWildcard=da;exports.hslStringToHex=ta;exports.hslToHex=ea;exports.httpDelete=uh;exports.initKosProvider=Tb;exports.inspectCompanionMixin=qy;exports.inspectFutureObservability=Vy;exports.isBoolean=Lo;exports.isKosCompanionTypeFactory=Ba;exports.isKosDataModel=Bt;exports.isKosLoggingEnabled=Bu;exports.isKosModel=he;exports.isKosModelContainer=Io;exports.isKosModelReady=Fs;exports.isLeapYear=Mo;exports.isLocalRefId=Qf;exports.isNumber=pr;exports.isPrintable=Eh;exports.isTroubleAware=km;exports.isValidDate=Lt;exports.kosAction=X;exports.kosAutoEffect=G;exports.kosChild=be;exports.kosCompanion=ah;exports.kosComputed=Ro;exports.kosConfigBean=mr;exports.kosConfigProperty=kg;exports.kosContext=ch;exports.kosDependency=mt;exports.kosEffect=lc;exports.kosFuture=hn;exports.kosLogger=hh;exports.kosModel=R;exports.kosModelEffect=ca;exports.kosObservable=Ao;exports.kosParentAware=fr;exports.kosReference=fh;exports.kosStateBean=eb;exports.kosStateProp=tb;exports.kosSubscribe=gh;exports.kosTopicHandler=U;exports.kosWhen=Wr;exports.login=ud;exports.mapConfigBeanModelToDto=bc;exports.mapDataToModel=zr;exports.mapDtoToConfigBeanModel=mc;exports.mapDtoToFutureModel=Bo;exports.mapDtoToFutureOptions=jo;exports.mapUpdateDtoToConfigBeanModel=yc;exports.modelEventTopicFactory=ua;exports.modelFactory=yt;exports.modelTypeEventTopicFactory=ha;exports.modifyConfigBean=hc;exports.modifyFuture=Gg;exports.pairedClientHeartbeat=Bf;exports.pipe=sc;exports.post=as;exports.preloadKosModel=mf;exports.processId=Cu;exports.processMiddleware=Ff;exports.put=dh;exports.registerCompanionModel=pf;exports.registerCoreModels=Jl;exports.registerExtensionPoint=is;exports.registerHttpRoutes=Lh;exports.registerKosModel=qa;exports.registerLegacyModel=Ya;exports.resetKosModel=lf;exports.resetPassword=fd;exports.resolveBaseUrl=Xa;exports.resolveChild=Ta;exports.resolveContainerDeltas=Ou;exports.resolveItemListDeltas=Du;exports.resolveKosCompanion=Yr;exports.resolveKosContext=Jf;exports.resolveKosProfiles=zi;exports.resolveListDeltas=$u;exports.resolveServiceUrl=oe;exports.resolveVariable=sa;exports.retryWithExponentialBackoff=Hf;exports.sendAsyncIntent=ng;exports.sendBroadcastMessage=Hh;exports.sendIntent=og;exports.sendKosHttpMessageResponse=Na;exports.sendKosMessage=jh;exports.sendKosMessageResponse=Fa;exports.sendRequest=Zf;exports.sendStudioMessage=Kh;exports.sendStudioMessageRequest=Bh;exports.setupCompanionDecoratorMixin=Yy;exports.setupCompleteFutureSupport=ed;exports.setupMinimalFutureSupport=By;exports.startPasswordReset=hd;exports.stringComponentInsert=Ad;exports.studioAcceptOrgInvitation=nb;exports.studioLogin=sb;exports.studioResetPassword=ob;exports.studioStartPasswordReset=rb;exports.subscribeStore=Wy;exports.syncPublish=Xf;exports.transitionToActive=pa;exports.transitionToInit=ba;exports.transitionToLoad=ya;exports.transitionToReady=ma;exports.transitionToUnload=Mh;exports.troubleByTypeReducer=Fm;exports.troubleDataFactory=ul;exports.unloadKosModel=cf;exports.updateCompanionModelRegistration=Uf;exports.updateModelRegistration=Nf;exports.updateRegion=id;exports.updateTimeZone=oo;exports.useAmPmValues=au;exports.useCalendarDayArray=Wd;exports.useConfigBean=yw;exports.useConfigProperty=Ld;exports.useContextModel=gb;exports.useContextModelHierarchy=wd;exports.useDateArrays=Kd;exports.useDateProps=_w;exports.useDateRelativeConfig=Iw;exports.useDateRelativeData=Xd;exports.useDayNames=Yd;exports.useDayOptions=Vd;exports.useDays=Mn;exports.useDevice=$d;exports.useFormattedDate=qd;exports.useFormattedTime=lu;exports.useFunctionWarmup=Sw;exports.useHourValues=iu;exports.useKosCore=_d;exports.useKosDateFormats=$w;exports.useKosModel=q;exports.useKosRegions=ru;exports.useKosTime=fn;exports.useKosTimeContext=Cb;exports.useKosTimeFormats=Lw;exports.useKosTimeZones=Rw;exports.useKosTranslation=uw;exports.useKosTranslationContext=Fb;exports.useLocalComputed=kw;exports.useModelFromHierarchy=bb;exports.useMonths=zd;exports.useMonthsOptions=Gd;exports.useMutationObserver=Nw;exports.useNetworkInterfaceContainer=Dd;exports.useOta=Cd;exports.usePressGesture=Uw;exports.useProjectReload=nu;exports.useRegionTimeProps=jw;exports.useRegionalTimeDate=Zd;exports.useSoftwareInfo=pn;exports.useSoftwareInfoContext=xb;exports.useStateProperty=Jb;exports.useStorageDeviceContainer=Rd;exports.useSuspenseData=no;exports.useTimeOptions=cu;exports.useTimeProps=du;exports.useTimeValues=io;exports.useTimer=tw;exports.useTranslationContainer=xd;exports.useTroubleContainerModel=bn;exports.useTroubleModel=fw;exports.useTroublePresence=gw;exports.useUsbUpdateContainer=Pd;exports.useYears=vn;exports.useYearsOptions=Hd;exports.uuid=pt;exports.variableToHex=qu;exports.waitForAppToStart=ig;exports.waitForAppsToStart=cc;exports.waitForRequest=$o;exports.whenReady=ae;exports.withDevice=Vb;exports.withKosModelFutures=Ky;exports.withKosTime=qb;exports.withNetworkInterfaceContainer=Wb;exports.withOta=Qb;exports.withProjectReloading=Bw;exports.withSoftwareInfo=Rb;exports.withStorageDeviceContainer=ew;exports.withTranslationContainer=hw;exports.withTroubleContainer=pw;exports.withUsbUpdateContainer=mw;exports.wrapPromise=wo;
194
+ `,$d=()=>{const t=or.type;return q({modelId:t,modelType:or.type,options:{}})};function Yb(t){return e=>{const{model:s,status:r,KosModelLoader:o}=$d();return T.jsx(o,{...r,children:T.jsx(t,{...e,device:s})})}}function qb(t,e,s){const r=new Promise(o=>{I.getInstance().whenReady().then(()=>{const{model:n}=I.getInstance().modelManager.createModelInstance(t,e??t,s);return n.whenReady().then(()=>{o(n.modelData)})})});return _o(r)}function Wb(t){return e=>{const{model:s,status:r,KosModelLoader:o}=bn();return T.jsx(o,{...r,children:T.jsx(t,{...e,kosTime:s})})}}const Dd=()=>{const t=ts.type;return q({modelId:t,modelType:ts.type,options:{}})};function Qb(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Dd();return T.jsx(o,{...r,children:T.jsx(t,{...e,networkInterfaceContainer:s})})}}const Cd=()=>{const t=Ys.type;return q({modelId:t,modelType:Ys.type,options:{}})};function Zb(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Cd();return T.jsx(o,{...r,children:T.jsx(t,{...e,oTA:s})})}}function Xb(t,e){f.useEffect(()=>{function s(o){t.current&&!t.current.contains(o.target)&&e()}function r(o){o.key==="Escape"&&e()}return document.addEventListener("mousedown",s),document.addEventListener("keydown",r,!1),()=>{document.removeEventListener("mousedown",s),document.removeEventListener("keydown",r,!1)}},[t,e])}function Jb(t){const e=f.useRef(null),s=t.onAlert;return Xb(e,s),T.jsx("div",{ref:e,style:{width:"100%"},children:t.children})}const ew=t=>{var d;const{stateProp:e}=t,[s,r]=f.useState((d=t.stateProp)==null?void 0:d.value),[o,n]=f.useState(!1),[i,a]=f.useState(void 0);return f.useEffect(()=>{async function u(h){try{h&&(await ae(h),n(!0))}catch(g){a(g.message)}}u(e)},[e]),f.useEffect(()=>{const u=G(()=>{e&&o&&r(e.value)});return()=>{u()}},[o,e]),[s,{ready:o,error:i}]},Rd=()=>{const[t,e]=f.useState(!1),[s,r]=f.useState([]),o=ft.type,n=q({modelId:o,modelType:ft.type,options:{}});return f.useEffect(()=>{const i=G(()=>{var a,c;e(((a=n.model)==null?void 0:a.isStorageInserted)??!1),r(((c=n.model)==null?void 0:c.data)??[])});return()=>{i()}},[n.model]),{...n,inserted:t,devices:s}};function tw(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Rd();return T.jsx(o,{...r,children:T.jsx(t,{...e,storageDeviceContainer:s})})}}const Kr=p.createLogger({name:"use-timer"}),sw=({timerName:t,onTimerExpired:e,onTimerTick:s,timerEventActions:r,autoStart:o})=>{const n=cd.getTimer(t);f.useEffect(()=>{if(!n){console.warn(`Timer with name ${t} does not exist.`);return}const d=O(gn,u=>{const{name:h,action:g,remainingTime:m}=u==null?void 0:u.body;h===t&&(g===mn?e({name:h,action:g,remainingTime:m,timer:n}):r!=null&&r[g]&&r[g]({name:h,action:g,remainingTime:m,timer:n}))});return o&&n.start(),()=>{d.unsubscribe()}},[o,e,r,t,n]),f.useEffect(()=>{if(!n||!s)return;const d=`${pn}/${t}`,u=O(d,h=>{const{name:g,remainingTime:m}=h==null?void 0:h.body;g===t&&s({name:g,remainingTime:m,timer:n})});return()=>{u.unsubscribe()}},[s,t,n]);const i=f.useCallback(()=>{n?n.start():Kr.warn(`Timer with name ${t} does not exist.`)},[n,t]),a=f.useCallback(()=>{n?n.reset():Kr.warn(`Timer with name ${t} does not exist.`)},[n,t]),c=f.useCallback(()=>{n?n.pause():Kr.warn(`Timer with name ${t} does not exist.`)},[n,t]);return{timer:n,start:i,reset:a,pause:c}},rw=t=>{const e=/[\\^$.*+?()[\]{}|]/g;return RegExp(e.source).test(t)?t.replace(e,"\\$&"):t},ow=t=>t instanceof RegExp,nw=t=>typeof t=="string",iw=(t,e,s)=>{if(t===""||e==="")return t;let r=e;ow(r)||(r=new RegExp("("+rw(r)+")","gi"));const o=t.split(r);for(let n=1,i=o.length;n<i;n+=2)o[n]=s(o[n],n);return o},Ad=(t,e,s)=>{let r=t;return Array.isArray(r)||(r=[r]),r.flatMap(o=>nw(o)?iw(o,e,s):o)};function aw(t,e){let s=t;return Object.entries(e).forEach(([r,o])=>{const n=new RegExp(`<${r}>(.*?)</${r}>|<${r}/>`,"g");s=Ad(s,n,(i,a)=>o.type==="br"?T.jsx("br",{}):f.cloneElement(o,{key:`${r}-${a}`},i))}),s}const cw=t=>{const{i18nKey:e,t:s,defaults:r,components:o,values:n={},context:i}=t,a=s(e,{defaultValue:r,data:n,context:i,returnObjects:!0}),c=aw(a,o||{});return T.jsx("span",{className:t.className,children:c})},tt=new Map;function lw(t,e){if(tt.has(t)){const s=tt.get(t);if(s.status==="finished")return s.result;throw s.promise}else{const s=e().then(o=>{tt.set(t,{status:"finished",result:o})},o=>{throw tt.set(t,{status:"error",error:o}),o}),r={status:"pending",promise:s};throw tt.set(t,r),s}}function uo(t,e){return lw(t,e)}const dw=async()=>{const t=await Ga(Oe.type);return await ae(t.model),t.model},uw=async(t,e,s)=>{const r=t.resolveNamespace(e);await ae(r);for(const o of s){const n=t.resolveNamespace(o);await ae(n),tt.set(o,{status:"finished",result:n})}return r},hw=(t,e)=>{const s=[t].flat(),[r,...o]=s,n=uo(Oe.type,dw),i=s.join("__"),a=uo(i,()=>uw(n,r,o)),c=f.useMemo(()=>({exists:u=>{const h=e!=null&&e.keyPrefix?`${e.keyPrefix}.${u}`:u;return a?a.exists(h):!1}}),[e==null?void 0:e.keyPrefix,a]);return{t:f.useCallback((u,h)=>{const g=e!=null&&e.keyPrefix?`${e.keyPrefix}.${u}`:u;return a?a.resolveKey(g,h):(p.debug(`Translation model ${t} not ready for key: ${g}`),g)},[e==null?void 0:e.keyPrefix,t,a]),i18n:c}},xd=()=>{const t=Oe.type;return q({modelId:t,modelType:Oe.type,options:{}})};function fw(t){return e=>{const{model:s,status:r,KosModelLoader:o}=xd();return T.jsx(o,{...r,children:T.jsx(t,{...e,translationContainer:s})})}}const gw=t=>q({modelId:t,modelType:ct.type}),Tn=()=>q({modelId:dt.type,modelType:dt.type,options:{}}),pw=({troubleType:t,condition:e})=>{const{model:s}=Tn(),[r,o]=f.useState(!1),[n,i]=f.useState([]),a=f.useCallback(()=>{var c,d;return n.length>0&&((c=n[0])!=null&&c.resolvable)?(d=n[0])==null?void 0:d.resolve():Promise.resolve(void 0)},[n]);return f.useEffect(()=>G(()=>{const d=(t?s==null?void 0:s.troubles.getIndexByKey("byType",t):s==null?void 0:s.troubles.data)||[],u=e?d.filter(e):d;o(u.length>0),i(u)}),[e,s,t]),[r,a,n.length>0?n[0]:void 0,n]};function mw(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Tn();return T.jsx(o,{...r,children:T.jsx(t,{...e,troubleContainer:s})})}}const Pd=()=>{const t=rs.type,e=q({modelId:t,modelType:rs.type,options:{},activate:!0,destroyOnUnmount:!0}),[s,r]=f.useState(!1),[o,n]=f.useState(!1),[i,a]=f.useState([]);return f.useEffect(()=>{const c=G(()=>{var d,u,h;r(((d=e.model)==null?void 0:d.isUsbInserted)??!1),n(((u=e.model)==null?void 0:u.hasAvailableUpdates)??!1),a(((h=e.model)==null?void 0:h.data)??[])});return()=>{c()}},[e.model]),{...e,inserted:s,updateAvailable:o,updates:i}};function yw(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Pd();return T.jsx(o,{...r,children:T.jsx(t,{...e,usbUpdateContainer:s})})}}const bw=({path:t,propKey:e})=>{const{status:s}=q({modelType:qt.type,modelId:t,options:{path:t}}),[r,o]=f.useState(!1),[n,i]=f.useState(),[a,c]=f.useState(""),[d,u]=f.useState(),h=g=>{n&&e&&n.updateProperty(e,g)};return f.useEffect(()=>{var g;s.model&&i(s.model),s.model&&e&&((g=s.model)!=null&&g.props.has(e)?c(s.model.props[e]):u(`property ${e} not found`)),s.ready&&o(s.ready)},[s.ready,s.model,e]),f.useEffect(()=>{e&&M.autorun(()=>{const g=n==null?void 0:n.props[e];c(g||"")})},[n,e]),{config:n,ready:r,value:a,error:d,updateValue:h}},ww=(t,e)=>{switch(e.type){case"UPDATE":return e.payload;default:return t}},Ld=({configProperty:t,optionsTransformer:e})=>{const[s,r]=f.useState(!1),[o,n]=f.useState(""),[i,a]=f.useReducer(ww,{value:String(t==null?void 0:t.value),displayValue:t==null?void 0:t.displayValue,significantValue:t==null?void 0:t.significantValue,unit:t==null?void 0:t.unit,options:t==null?void 0:t.options,mappedOptions:[],updateProperty:t==null?void 0:t.updateProperty,displayOptions:t==null?void 0:t.displayOptions}),c=f.useCallback(d=>{var h;let u="factory";typeof d=="string"?u=d:(h=d==null?void 0:d.target)!=null&&h.value&&(u=d.target.value),u&&(t==null||t.updateProperty(u))},[t]);return f.useEffect(()=>{async function d(u){try{u&&(await ae(u),r(!0))}catch(h){n(h.message)}}d(t)},[t]),f.useEffect(()=>{const d=G(()=>{if(t&&s){let u=[];e&&(u=e(t.options)),a({type:"UPDATE",payload:{value:String(t.value),displayValue:t.displayValue,significantValue:t.significantValue,unit:t.unit,options:t.options,mappedOptions:u,updateProperty:t.updateProperty,displayOptions:t==null?void 0:t.displayOptions}})}});return()=>{d()}},[t,e,s]),{...i,configSelectProps:{onChange:c,value:i.value,options:e?i.mappedOptions||[]:i.options||[]},ready:s,error:o}};function vw(t,e){const s=e??new Date().getFullYear(),r=[31,28,31,30,31,30,31,31,30,31,30,31];return t===1&&(s%4===0&&s%100!==0||s%400===0)?29:r[t]??0}function Mw(t,e){return new Date(t,e,0).getDate()}function kd(t,e){const s=vw(e,t),r=[];for(let o=1;o<=s;o++)r.push(o);return r}function Fd(){return[...Array(12).keys()].map(e=>new Date(0,e).getMonth())}function Nd(t=[2018,2028]){const e=[];for(let s=t[0];s<=t[1];s++)e.push(s);return e}function Ud(t,e=[2018,2028]){const s=Nd(e);return t==="long"?s:s.map(r=>Number(r.toString().substring(2)))}function _n(t="numeric",e="en-US"){const s=new Intl.DateTimeFormat(e,{month:t,timeZone:"UTC"}).format;return[...Array(12).keys()].map(r=>s(new Date(Date.UTC(0,r,1))))}function Ew({locale:t="en-US",year:e,month:s,day:r,formatOptions:o={weekday:"long",year:"numeric",month:"long",day:"numeric"},displayOrder:n}){const i=s-1,a=new Date(e,i,r),c=new Intl.DateTimeFormat(t,{month:o.month}).format(a),d=new Intl.DateTimeFormat(t,{year:o.year}).format(a),u=new Intl.DateTimeFormat(t,{day:o.day}).format(a);return n?n=="MMDDYY"?`${c} ${u} ${d}`:n==="DDMMYY"?`${u} ${c} ${d}`:n==="YYMMDD"?`${d} ${c} ${u}`:`${d} ${u} ${c}`:new Intl.DateTimeFormat(t,o).format(a)}function ge(t){return t.toString().length===2?new Date(Date.parse(`01 Jan 20${t}`)).getFullYear():t}function Tw(t){return typeof t=="string"?new Date(Date.parse(`01 ${t.substring(0,3)} 2023`)).getMonth()+1:t}function jd(t,e,s){const r=ge(e),o=new Date(r,t,1).getDay(),n=new Date(r,t+1,0).getDate();return[...Array(42).keys()].map(a=>a<o||a>n+o-1?{label:"",value:0,disabled:!0}:s[a-o])}function kt(t,e,s){const r=e-1,o=new Date(t,r,s);return new Date(o).getMonth()===r&&new Date(o).getDate()===s}function Ft(t,e){return new Date(t,e,0).getDate()}function Bd(t="en-US",e="short"){const s=new Intl.DateTimeFormat(t,{weekday:e}).format;return[...Array(7).keys()].map(r=>s(new Date(Date.UTC(2021,5,r))))}function Kd({locale:t="en-US",year:e=new Date().getFullYear(),month:s=new Date().getMonth(),yearRange:r=[2018,2028],daysOfWeekFilter:o=[],formatOptions:{yearFormat:n="long",monthFormat:i="long",dayFormat:a="short"}={}}){const c=In(n,r),d=Hd(n,r,t),u=zd(i,t),h=Gd(i,t),g=Sn(e,s),m=Vd(e,s,t,o),y=Wd(s,e,m),v=Yd(t,a);return{daysArray:g,monthsArray:u,yearsArray:c,yearsOptionsArray:d,monthsOptionsArray:h,daysOptionsArray:m,calendarDayArray:y,dayNamesArray:v}}function In(t="long",e=[2018,2028]){return f.useMemo(()=>Ud(t,e),[t,e])}function Hd(t="long",e=[2018,2028],s="en-US"){const r=In(t,e);return f.useMemo(()=>r.map(n=>({label:n.toLocaleString(s).replace(",",""),value:n})),[s,r])}function zd(t,e="en-US"){return f.useMemo(()=>_n(t,e),[t,e])}function Gd(t,e="en-US"){const s=f.useMemo(()=>Fd(),[]),r=f.useMemo(()=>_n(t,e),[t,e]);return f.useMemo(()=>[...Array(12).keys()].map(n=>({label:r[n],value:Number(s[n])})),[r,s])}function Sn(t,e){const s=ge(t);return f.useMemo(()=>kd(s,e),[e,s])}const _w=(t,e,s,r=[])=>{const o=new Date(t,e,s).getDay();return r.length>0&&r.includes(o)};function Vd(t,e,s="en-US",r=[]){const o=Sn(t,e);return f.useMemo(()=>o.map(i=>({label:i.toLocaleString(s),value:i,disabled:_w(t,e,i,r)})),[r,s,e,o,t])}function Yd(t="en-US",e="short"){return f.useMemo(()=>Bd(t,e),[t,e])}function qd({year:t=new Date().getFullYear(),month:e=new Date().getMonth(),day:s=new Date().getDate(),formatString:r}){const o=e,n=new Date(t,o,s);return{formattedDate:Re.format(n,r)}}function Wd(t,e,s){return f.useMemo(()=>jd(t,e,s),[t,e,s])}var Qd=(t=>(t.MMDDYY="MMDDYY",t.DDMMYY="DDMMYY",t.YYMMDD="YYMMDD",t.YYDDMM="YYDDMM",t))(Qd||{});function Iw({locale:t="en-US",date:{year:e=new Date().getFullYear(),month:s=new Date().getMonth(),day:r=new Date().getDate()}={year:new Date().getFullYear(),month:new Date().getMonth(),day:new Date().getDate()},formatOptions:{yearFormat:o="long",monthFormat:n="long",dayFormat:i="short",formatString:a="yyyy/MM/dd"}={},filterOptions:{yearsRange:c=[2018,2028],daysOfWeekFilter:d=[]}={}}){const[u,h]=f.useState(e),[g,m]=f.useState(c),[y,v]=f.useState(s),[E,_]=f.useState(r);f.useEffect(()=>{h(e)},[e]),f.useEffect(()=>{v(s)},[s]),f.useEffect(()=>{_(r)},[r]);const{yearsArray:N,yearsOptionsArray:x,monthsArray:D,monthsOptionsArray:P,daysArray:W,daysOptionsArray:re,calendarDayArray:L,dayNamesArray:Ce}=Kd({locale:t,year:u,yearRange:g,month:y,formatOptions:{yearFormat:o,monthFormat:n,dayFormat:i},daysOfWeekFilter:d}),{formattedDate:V}=qd({year:u,month:y,day:E,formatString:a});return{dateActions:{setYear:h,setYearRange:m,setMonth:v,setDay:_,nextMonth:()=>{const Z=y<11?ge(u):ge(u+1),ne=y<11?y+1:0;if(!kt(Z,ne,E)){const Fe=Ft(Z,ne);_(Fe)}ne===0&&h(Z),v(ne)},previousMonth:()=>{const Z=ge(y===0?u-1:u),ne=y===0?11:y-1;if(!kt(Z,ne,E)){const Fe=Ft(Z,ne);_(Fe)}ne===11&&h(Z),v(ne)},nextYear:()=>{const Z=u<g[1]?u+1:g[0],ne=ge(Z);if(kt(ne,y,E))h(Z);else{const Fe=Ft(ge(u+1),y);_(Fe),h(Z)}},previousYear:()=>{const Z=u>g[0]?u-1:g[0],ne=ge(Z);if(kt(ne,y,E))h(Z);else{const Fe=Ft(ge(u-1),y);_(Fe),h(Z)}}},dateState:{year:u,yearRange:g,month:y,day:E,yearsArray:N,yearsOptionsArray:x,monthsArray:D,monthsOptionsArray:P,daysArray:W,daysOptionsArray:re,calendarDayNames:Ce,calendarDayArray:L,formattedDate:V}}}function Zd({date:t=new Date,dateFormat:e,timeFormat:s,options:r={}}){const[o,n]=f.useState("Formatting Time..."),[i,a]=f.useState("Formatting Date..."),c=!!r.ignoreDateFormat,{model:d,ready:u}=q({modelId:ee.type,modelType:ee.type,options:{}}),h=typeof t=="string"?Re.parseISO(t):t;return f.useEffect(()=>{c?a(""):e?a(Re.format(h,e)):u&&a(Re.format(h,d!=null&&d.selectedDateFormat?d==null?void 0:d.selectedDateFormat:""))},[c,t,e,h,d,u]),f.useEffect(()=>{s?n(Re.format(h,s)):u&&n(Re.format(h,d!=null&&d.selectedTimeFormat?d==null?void 0:d.selectedTimeFormat:""))},[t,s,h,d,u]),{formattedDate:i,formattedTime:o}}const Xd=({secondsFromMidnight:t=0})=>{const[e,s]=f.useState(0),[r,o]=f.useState(0),[n,i]=f.useState(0),[a,c]=f.useState(new Date),{formattedTime:d}=Zd({date:a,options:{ignoreDateFormat:!0}});return f.useEffect(()=>{const u=Number(t),h=Math.floor(u/3600),g=Math.floor(u%3600/60),m=u%60;s(h),o(g),i(m);const y=new Date;y.setHours(0,0,0,0);const v=new Date(y.getTime()+u*1e3);c(new Date(v))},[t]),{hours:e,minutes:r,seconds:n,formattedTime:d,timeActions:{setHours:s,setMinutes:o,setSeconds:i}}},Sw=({configProperty:t})=>{const{value:e}=Ld({configProperty:t}),s=parseInt(e||"0",10),{hours:r,minutes:o,seconds:n,formattedTime:i,timeActions:a}=Xd({secondsFromMidnight:s}),c=f.useRef();return f.useEffect(()=>{const d=r*3600+o*60+n;return c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{t&&t.updateProperty(d.toString())},100),()=>{c.current&&clearTimeout(c.current)}},[t,r,o,n]),{hours:r,minutes:o,seconds:n,formattedTime:i,timeActions:a}};function Ow(t,e={}){const{intervalMs:s=5*60*1e3,immediate:r=!0}=e;f.useEffect(()=>{const o=()=>{try{t({__warmup:!0})}catch{}};r&&("requestIdleCallback"in window?requestIdleCallback(o):setTimeout(o,1));const n=s?setInterval(o,s):null;return()=>{n&&clearInterval(n)}},[t,s,r])}const $w=t=>T.jsx("option",{title:t.id,value:t.format,children:t.format},t.id),Dw=(t=$w)=>{const[e,s]=f.useState([]),[r,o]=f.useState(),{model:n,ready:i}=q({modelType:ee.type,modelId:ee.type,options:{}});f.useEffect(()=>{const c=G(()=>{s((n==null?void 0:n.dateFormatOptions.map(t))||[])});return()=>{c()}},[n,i,t]),f.useEffect(()=>{const c=G(()=>{n!=null&&n.dateFormatId&&(n!=null&&n.selectedDateFormat)&&o({id:n==null?void 0:n.dateFormatId,value:n==null?void 0:n.selectedDateFormat})});return()=>{c()}},[n==null?void 0:n.selectedDateFormat,n==null?void 0:n.dateFormatId]);const a=f.useCallback(c=>{var u;let d="";typeof c=="string"?d=c:(u=c==null?void 0:c.target)!=null&&u.value&&(d=c.target.value),d&&(n==null||n.setSelectedDateFormat(d))},[n]);return{raw:(n==null?void 0:n.dateFormatOptions.map(c=>c.id))??[],regionModel:n,selectedDateFormat:(r==null?void 0:r.value)||"",dateFormatId:(r==null?void 0:r.id)||"",updateDateFormat:a,props:{onChange:a,value:(r==null?void 0:r.id)||"",options:e}}},Cw=t=>T.jsx("option",{title:t,value:t,children:t},t),Jd="kos:service:region:settings",eu="timeZone",Rw=`${Jd}-${eu}`,Aw=(t=Cw)=>{const[e,s]=f.useState([]),[r,o]=f.useState(""),{model:n,ready:i}=q({modelType:ee.type,modelId:ee.type,options:{}}),a=Ve.factory(Rw)({path:Jd,attribute:eu});f.useEffect(()=>{const d=G(()=>{s((n==null?void 0:n.timeZones.map(t))||[]),n!=null&&n.timeZones.length&&lo(n==null?void 0:n.timeZones[0])});return()=>{d()}},[n,i,t]),f.useEffect(()=>{const d=G(()=>{o(a.value||"")});return()=>{d()}},[a.value]);const c=f.useCallback(d=>{var h;let u="factory";typeof d=="string"?u=d:(h=d==null?void 0:d.target)!=null&&h.value&&(u=d.target.value),u&&lo(u)},[]);return{options:e,raw:(n==null?void 0:n.timeZones)??[],regionModel:n,selectedTimeZone:r,timeZones:(n==null?void 0:n.timeZones)??[],updateTimeZone:c,selectProps:{onChange:c,value:r,options:e}}},tu="kos:service:region",su="regionId",xw=`${tu}-${su}`,Pw=t=>T.jsx("option",{title:t,value:t,children:t},t),ru=(t=Pw)=>{const[e,s]=f.useState([]),[r,o]=f.useState("factory"),{model:n,ready:i}=q({modelType:ee.type,modelId:ee.type,options:{}}),a=Ve.factory(xw)({path:tu,attribute:su});f.useEffect(()=>{const d=G(()=>{s((n==null?void 0:n.availableRegions.map(t))||[])});return()=>{d()}},[n,i,t]),f.useEffect(()=>{const d=G(()=>{o(a.value||"factory")});return()=>{d()}},[a.value]);const c=f.useCallback(d=>{var h;let u="factory";typeof d=="string"?u=d:(h=d==null?void 0:d.target)!=null&&h.value&&(u=d.target.value),u&&id(u)},[]);return{raw:(n==null?void 0:n.availableRegions)??[],regionModel:n,regionData:n==null?void 0:n.selectedRegion,selectedRegion:r,updateRegion:c,regionSelectProps:{onChange:c,value:r,options:e}}},Lw=t=>T.jsx("option",{title:t.id,value:t.format,children:t.format},t.id),kw=(t=Lw)=>{const[e,s]=f.useState([]),[r,o]=f.useState(),{model:n,ready:i}=q({modelType:ee.type,modelId:ee.type,options:{}});f.useEffect(()=>{const c=G(()=>{s((n==null?void 0:n.timeFormatOptions.map(t))||[])});return()=>{c()}},[n,i,t]),f.useEffect(()=>{const c=G(()=>{n!=null&&n.timeFormatId&&(n!=null&&n.selectedTimeFormat)&&o({id:n==null?void 0:n.timeFormatId,value:n==null?void 0:n.selectedTimeFormat})});return()=>{c()}},[n==null?void 0:n.selectedTimeFormat,n==null?void 0:n.timeFormatId]);const a=f.useCallback(c=>{var u;let d="";typeof c=="string"?d=c:(u=c==null?void 0:c.target)!=null&&u.value&&(d=c.target.value),d&&(n==null||n.setSelectedTimeFormat(d))},[n]);return{raw:(n==null?void 0:n.timeFormatOptions.map(c=>c.id))??[],regionModel:n,selectedTimeFormat:(r==null?void 0:r.value)??"",timeFormatId:(r==null?void 0:r.id)??"",updateTimeFormat:a,props:{onChange:a,value:(r==null?void 0:r.id)??"",options:e}}},Fw=(t,e)=>f.useMemo(()=>ko(t),e),Nw={config:{attributes:!0,childList:!0,subtree:!0}};function Uw(t,e,s=Nw){const[r,o]=f.useState(null);f.useEffect(()=>{if(!e||typeof e!="function")throw new Error("A valid callback function is required");const n=new MutationObserver(e);o(n)},[e,s,o]),f.useEffect(()=>{if(!r)return()=>{};if(!t)throw new Error("A valid DOM element is required");const{config:n}=s;try{r.observe(t,n)}catch(i){p.error(i)}return()=>{r&&r.disconnect()}},[r,t,s])}const ou={validateStart:function(t){return!0},validateStop:function(t){const e=t.event.currentTarget.getBoundingClientRect(),[s,r]=t.xy;return s<e.left||s>e.right||r<e.top||r>e.bottom}},Hr=p.createLogger({name:"usePressGesture",group:"kos-hooks"});function jw({onPressed:t,onRelease:e,intersectionStrategy:s=ou}){const r=f.useRef(!1),o=pu.useGesture({onDragStart:c=>{Hr.info("onDragStart",c.type),s.validateStart(c)&&(t&&t(),r.current=!0)},onDrag:c=>{Hr.info("onDrag",c.type),r.current&&s.validateStop(c)&&(e&&e(),r.current=!1)},onDragEnd:c=>{Hr.info("onDragEnd",c.type),r.current&&e&&(e(),r.current=!1)}}),n=()=>{t&&t(),r.current=!0},i=()=>{r.current&&e&&(e(),r.current=!1)},a=()=>{r.current&&e&&(e(),r.current=!1)};return{dom:o,mesh:()=>({onPointerDown:n,onPointerUp:i,onPointerOut:a})}}const nu=()=>{const[t,e]=f.useState(!1),s=I.getInstance();return f.useEffect(()=>{const r=G(()=>{s&&s.reloading!==t&&e(s.reloading)});return()=>{r()}},[s,t]),[t]};function iu(t=!1,e="2-digit"){return f.useMemo(()=>{const s=t?12:24;return Array.from({length:s},(r,o)=>{const n=t&&o===0?12:o%s;return{id:o,label:e==="2-digit"?n.toString().padStart(2,"0"):n.toString()}})},[e,t])}function ho(t,e="2-digit",s=0,r=0){return f.useMemo(()=>Array.from({length:t},(o,n)=>{const i=String(n+s);return{id:n+r,label:e==="2-digit"?i.padStart(2,"0"):i}}),[t,s,r,e])}function au(t="en-US"){return f.useMemo(()=>["AM","PM"].map(e=>{const s=new Intl.DateTimeFormat(t,{hour:"2-digit",hour12:!0}).formatToParts(new Date().setHours(e==="AM"?0:12))[2].value;return{id:s,label:s}}),[t])}function cu({formatOptions:{hour12:t=!0,hour:e="2-digit",minute:s="2-digit",second:r="2-digit"}={hour12:!0,hour:"2-digit",minute:"2-digit",second:"2-digit"},locale:o="en-US"}){const n=iu(t,e),i=ho(60,s),a=ho(60,r),c=au(o);return{hourOptions:n,minuteOptions:i,secondOptions:a,amPmOptions:c}}function lu(t,e){return Re.format(t,e)}function du({formatOptions:t,initialDate:e=new Date,locale:s="en-US",format:r="HH:mm"}){const[o,n]=f.useState(e),i=f.useCallback(v=>{n(E=>{const _=new Date(E);return _.setHours(Number(v)),_})},[]),a=f.useCallback(v=>{n(E=>{const _=new Date(E);return _.setMinutes(Number(v)),_})},[]),c=f.useCallback(v=>{n(E=>{const _=new Date(E);return _.setSeconds(Number(v)),_})},[]),d=f.useCallback(v=>{const E=new Date(v);n(E)},[]),u=lu(o,r),{hourOptions:h,minuteOptions:g,secondOptions:m,amPmOptions:y}=cu({formatOptions:t,locale:s});return{amPmOptions:y,formattedTime:u,hourOptions:h,minuteOptions:g,secondOptions:m,setHours:i,setMinutes:a,setSeconds:c,setTime:d,time:new Date(o)}}const Bw=t=>{const{regionModel:e}=ru(),s=f.useMemo(()=>({hour12:e==null?void 0:e.is12HourTimeFormat}),[e==null?void 0:e.is12HourTimeFormat]);return du({...t,locale:e==null?void 0:e.regionId,format:e==null?void 0:e.selectedTimeFormat,formatOptions:s})};function Kw(t){return e=>{const[s]=nu();return s?T.jsx(pd,{message:"Wait a moment while your project reloads..."}):T.jsx(t,{...e})}}const ri=p.createLogger({name:"studio-properties-service",group:"Services"}),Hw="/api/kos/studio/properties",uu=async t=>{if(ri.debug("sending GET for studio-properties"),!t)throw ri.error("connectionId is undefined"),new Error("connectionId is undefined");return await De.get(Hw,{},{destinationAddress:t,timeout:500})},zw=Object.freeze(Object.defineProperty({__proto__:null,getStudioProperties:uu},Symbol.toStringTag,{value:"Module"}));var Gw=Object.getOwnPropertyDescriptor,Vw=(t,e,s,r)=>{for(var o=r>1?void 0:r?Gw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const hu="studio-properties-model",Yw="/kos/studio/properties",oi={"kos.studio.tool.legacy":1};let fo=class{constructor(t,e,s){l(this,"id");l(this,"connectionId");l(this,"unsubscribe",null);l(this,"logger");l(this,"data");this.id=t,this.logger=s.logger,this.data=Ae(),this.connectionId=e.connectionId}async init(){this.logger.debug(`initializing studio-properties ${this.id}`)}async load(){this.logger.debug(`loading studio-properties ${this.id}`)}async terminatePropertiesSession(){var t;(t=this.unsubscribe)==null||t.call(this)}async initializePropertiesSession(){this.unsubscribe=nt.getInstance().subscribeTopic({topic:Yw,destinationAddress:this.connectionId,callback:s=>{this.logger.error(`Received studio-properties message for connection ${this.connectionId}: ${JSON.stringify(s)}`)}});const[t,e]=await uu(this.connectionId);if(t){this.logger.error(`Error loading studio-properties: ${t}`),this.data.setValues(oi);return}if(e){const s=Object.keys(e).reduce((r,o)=>(r[o]=e[o]??o,r),{});this.data.setValues(s??oi),p.ifDebug(()=>this.logger.debug(`studio-properties loaded: ${JSON.stringify(s)}`))}}get(t){return this.data[t]}createObservableProperty(t){return ko(()=>this.get(t))}};fo=Vw([R(hu)],fo);const qw=new we({class:fo,type:hu});Object.defineProperty(exports,"makeAutoObservable",{enumerable:!0,get:()=>M.makeAutoObservable});Object.defineProperty(exports,"makeObservable",{enumerable:!0,get:()=>M.makeObservable});Object.defineProperty(exports,"kosComponent",{enumerable:!0,get:()=>po.observer});exports.AuthState=Xa;exports.BrowserKosRouter=ac;exports.BrowserRouter=qo;exports.CanvasDispatcher=ht;exports.CanvasDispatcherServices=zm;exports.CanvasRenderer=nn;exports.CanvasStreamer=zb;exports.CanvasStreamerBase=Od;exports.ChildModels=Ut;exports.CompanionDecoratorMixin=td;exports.CompanionParentModel=Ls;exports.ConfigBean=qt;exports.CoreExtensionManager=By;exports.CoreModels=fn;exports.CreateModelTranslationsContext=Ed;exports.CreateModelTranslationsProvider=Eb;exports.DateDisplayFormat=Qd;exports.DateHelpers=Ru;exports.DependencyLifecycle=H;exports.DependencyModels=F;exports.Device=or;exports.DeviceServices=hy;exports.DomIntersectionStrategy=ou;exports.EVENT_KOS_MODEL_READY=wo;exports.EVENT_TROUBLE_ADDED=lg;exports.EVENT_TROUBLE_REMOVED=dg;exports.EXTENSION_CANVAS_RENDERER=Q;exports.EXTENSION_FEATURE_FLAG_RESOLVER=Xi;exports.EXTENSION_TROUBLE_DATA_MAPPER=Gs;exports.EXTENSION_TROUBLE_MAPPER=hs;exports.ErrorBoundaryWithFallback=md;exports.EventBus=wu;exports.EventBusFunctional=Mu;exports.EventBusState=Tu;exports.ExtensionManager=S;exports.FUTURE_CONTAINER_MODEL_TYPE=Lc;exports.FUTURE_MODEL_TYPE=Ic;exports.FUTURE_NOT_ASSIGNED=No;exports.FeatureFlagService=Ji;exports.FetchError=B;exports.FutureContainerFactory=Pe;exports.FutureContainerModel=Fc;exports.FutureEndState=xe;exports.FutureFactory=vt;exports.FutureHandler=yr;exports.FutureManager=ze;exports.FutureModel=Rc;exports.FutureService=Nt;exports.HEADER_CACHE_CONTROL=di;exports.HEADER_CONTENT_TYPE=li;exports.HEADER_DESTINATION_ADDR=$e;exports.HEADER_FOS_REQUEST_ID=ui;exports.HEADER_METHOD=cr;exports.HEADER_ORDERED=yo;exports.HEADER_REQUEST_ID=os;exports.HEADER_REQUEST_TYPE=Me;exports.HEADER_RESPONSE_ID=lr;exports.HEADER_SOURCE_ADDR=ci;exports.HEADER_TOPIC=ai;exports.HEADER_URL=pt;exports.HEADER_WORK_TRACKER=bo;exports.HttpRouteHandlers=Ie;exports.KOS_MODEL_ID=xs;exports.KeyValue=Zo;exports.KeyValueServices=np;exports.Kos=te;exports.KosConfigPropertySpec=Ve;exports.KosContainerIndex=Po;exports.KosContextBean=nc;exports.KosContextManager=z;exports.KosCore=I;exports.KosCoreModelPropertyMapper=me;exports.KosDataContainer=Lo;exports.KosDependencyTypes=lh;exports.KosExtensionUtils=Lu;exports.KosFeatureFlags=ea;exports.KosFetchMethods=Sa;exports.KosGlobalConfig=$o;exports.KosHttpRouteManager=Ro;exports.KosLog=p;exports.KosLogManager=Gc;exports.KosLogManagerServices=up;exports.KosMockEvents=gi;exports.KosModel=Ba;exports.KosModelCollectionProvider=yb;exports.KosModelContainer=Te;exports.KosModelContext=Ir;exports.KosModelEvents=A;exports.KosModelFactory=Ht;exports.KosModelFutureContainerMixin=fs;exports.KosModelLoader=vd;exports.KosModelLoaderDisplay=Md;exports.KosModelManager=za;exports.KosModelProvider=yd;exports.KosModelRegistrationFactory=we;exports.KosModelRegistry=co;exports.KosModelState=w;exports.KosModelSymbol=na;exports.KosModelVisitor=kf;exports.KosObservableData=tc;exports.KosRegistration=sg;exports.KosSingletonRegistration=rg;exports.KosTime=Ks;exports.KosTimeContext=wn;exports.KosTimeProvider=Cb;exports.KosTimeServices=bp;exports.KosTimer=ad;exports.KosToken=ic;exports.KosTranslationProvider=Fb;exports.KosTranslations=Sl;exports.KosWSTransportStatus=ja;exports.KosWsEvents=ns;exports.LOADER_FEATURE_FLAG=Yu;exports.LOGIN_HOST=hi;exports.LOGIN_URL=mu;exports.LoadingMessage=pd;exports.LogBlock=Jt;exports.LogBlockContainer=Mr;exports.LogConfig=Bt;exports.LogStream=Gt;exports.LogStreamContainer=us;exports.LogStreamServices=Dp;exports.MODEL_DELETION_DELAY=Ha;exports.MiddlewareChain=ec;exports.ModelEffects=Ke;exports.MultipleFutureHandler=Fg;exports.NestedModelContext=Sr;exports.NetworkInterface=ln;exports.NetworkInterfaceContainer=ts;exports.NetworkInterfaceServices=My;exports.ObservableData=Ae;exports.Ota=Ys;exports.OutsideAlerter=Jb;exports.PLUGIN_EXTENSION_NAME=ku;exports.PORT=fi;exports.PROFILE_LOG_DEBUG=Ki;exports.PROFILE_LOG_INFO=Hi;exports.PROFILE_RELAX_STORE_VALIDATION=Nu;exports.PROFILE_TOOLS_PREVIEW=Bi;exports.ParentModel=jt;exports.PluginExtensionManager=Fu;exports.ProgressBar=fb;exports.ReferenceConfig=Os;exports.RegionInfo=ee;exports.RegionServices=vg;exports.RegistrationManager=C;exports.Registry=jy;exports.STATUS=mo;exports.ServiceFactory=se;exports.SingletonKosModelRegistrationFactory=Ee;exports.SoftwareInfo=qs;exports.SoftwareInfoContext=Mn;exports.SoftwareInfoProvider=xb;exports.SoftwareInfoServices=um;exports.StateBean=es;exports.StateBeanServices=mm;exports.StateProp=tn;exports.StatePropServices=Sm;exports.StorageDevice=ir;exports.StorageDeviceContainer=ft;exports.StorageDeviceServices=Sy;exports.StudioProperties=qw;exports.StudioPropertiesServices=zw;exports.SubscriptionHandlers=J;exports.TIMER_END=mn;exports.TIMER_EVENT=gn;exports.TOPIC_TIMER_TICK_EVENT=pn;exports.TimerManager=cd;exports.TokenContext=Sd;exports.TokenProvider=Lb;exports.Topics=zt;exports.Trans=cw;exports.TransitionMap=$s;exports.Transitions=Do;exports.Translation=Zs;exports.TranslationContainer=Oe;exports.TranslationContainerContext=En;exports.TranslationContext=km;exports.TransportFactory=Yr;exports.Trouble=ct;exports.TroubleContainer=dt;exports.TroubleServices=qp;exports.Troubles=de;exports.UsbUpdate=hn;exports.UsbUpdateContainer=rs;exports.UsbUpdateServices=Py;exports.WS_EVENT_TYPE=Ol;exports.WebSocketEvents=pe;exports.WebSocketTransport=nt;exports.WsEventFactory=rn;exports.acceptOrgInvitation=gd;exports.addDaysToDate=xi;exports.addFuture=Oc;exports.addMonthsToDate=Ai;exports.api=Ac;exports.applyMixins=Iu;exports.arraysEqual=Su;exports.buildConfigBeanModel=fg;exports.buildFuture=Yo;exports.buildFutureModel=Dc;exports.cancelFuture=$c;exports.checkAppsStarted=ag;exports.convert=Ho;exports.convertFileSizeRaw=_u;exports.convertWithUnits=Sg;exports.createBaseMessage=Da;exports.createBroadcastMessageResponse=La;exports.createCancellablePromise=ab;exports.createClient=Ao;exports.createFosBaseMessage=$a;exports.createHeaders=Ca;exports.createKosHtpMessageResponse=ka;exports.createKosMessage=xa;exports.createKosMessageResponse=Fa;exports.createKosModelFutureManager=zy;exports.createLazyKosModelFutureManager=Gy;exports.createMessageBody=ke;exports.createModelDependency=va;exports.createOptionKey=Ju;exports.createPropKey=Ge;exports.createReadableStream=Ra;exports.createStudioMessage=Oa;exports.createStudioMessageRequest=Aa;exports.createStudioMessageResponse=Pa;exports.debounce=Ui;exports.del=aa;exports.deleteFuture=Sc;exports.destroyKosModel=He;exports.evaluateScopes=pc;exports.executeChildrenModelLifecycle=Ta;exports.executeDependentModelLifecycle=St;exports.executeListLifecycle=Ea;exports.extractTrailingWildcard=da;exports.fetchModel=qb;exports.findModel=uf;exports.findModels=Va;exports.formatDate=ki;exports.formatDateSince=Ri;exports.formatDateTime=Ni;exports.formatTime=Fi;exports.get=ia;exports.getAllKosCompanionModels=Ya;exports.getCalendarMonthArray=jd;exports.getCompanionMixin=rd;exports.getConfigBean=gc;exports.getDayStrings=Bd;exports.getDays=Mw;exports.getDaysArray=kd;exports.getDaysInMonth=Oo;exports.getDependenciesByLifecycle=Ma;exports.getFormattedDate=Ew;exports.getFormattedMonth=Tw;exports.getFormattedMonthsArray=_n;exports.getFormattedYear=ge;exports.getFormattedYearsArray=Ud;exports.getFutures=zg;exports.getHttpRouteHandlers=ca;exports.getKosCompanionModel=hf;exports.getKosLocalizationDescriptor=Ml;exports.getKosMessageLogging=Yi;exports.getKosModel=Ga;exports.getKosModelSync=ve;exports.getKosModelType=df;exports.getKosSessionKey=oc;exports.getLastDayOfMonth=Ft;exports.getLocalizationDescriptor=$m;exports.getLogLevel=Vi;exports.getLogMessageToStudio=qi;exports.getMessageBody=Vr;exports.getMonthsArray=Fd;exports.getObservableCompanions=ff;exports.getQueryParams=ue;exports.getStartedApps=cg;exports.getTranslations=vl;exports.getYearsArray=Nd;exports.hasCompanionMixin=sd;exports.hasDecimals=hc;exports.hasHttpRouteHandlers=ks;exports.hasKosModelFutureSupport=Vy;exports.hasKosProfile=zr;exports.hasTrailingWildcard=ua;exports.hslStringToHex=sa;exports.hslToHex=ta;exports.httpDelete=uh;exports.initKosProvider=_b;exports.inspectCompanionMixin=Wy;exports.inspectFutureObservability=Yy;exports.isBoolean=jo;exports.isKosCompanionTypeFactory=Ka;exports.isKosDataModel=Kt;exports.isKosLoggingEnabled=Bu;exports.isKosModel=he;exports.isKosModelContainer=Co;exports.isKosModelReady=Fs;exports.isLeapYear=So;exports.isLocalRefId=Qf;exports.isNumber=pr;exports.isPrintable=Eh;exports.isTroubleAware=Fm;exports.isValidDate=kt;exports.kosAction=X;exports.kosAutoEffect=G;exports.kosChild=be;exports.kosCompanion=ah;exports.kosComputed=ko;exports.kosConfigBean=mr;exports.kosConfigProperty=kg;exports.kosContext=ch;exports.kosDependency=yt;exports.kosEffect=dc;exports.kosFuture=yn;exports.kosLogger=hh;exports.kosModel=R;exports.kosModelEffect=la;exports.kosObservable=Fo;exports.kosParentAware=fr;exports.kosReference=fh;exports.kosStateBean=tb;exports.kosStateProp=sb;exports.kosSubscribe=gh;exports.kosTopicHandler=U;exports.kosWhen=Qr;exports.login=ud;exports.mapConfigBeanModelToDto=wc;exports.mapDataToModel=Gr;exports.mapDtoToConfigBeanModel=yc;exports.mapDtoToFutureModel=Vo;exports.mapDtoToFutureOptions=Go;exports.mapUpdateDtoToConfigBeanModel=bc;exports.modelEventTopicFactory=ha;exports.modelFactory=bt;exports.modelTypeEventTopicFactory=fa;exports.modifyConfigBean=fc;exports.modifyFuture=Gg;exports.pairedClientHeartbeat=Bf;exports.pipe=rc;exports.post=as;exports.preloadKosModel=mf;exports.processId=Cu;exports.processMiddleware=Ff;exports.put=dh;exports.registerCompanionModel=pf;exports.registerCoreModels=Jl;exports.registerExtensionPoint=is;exports.registerHttpRoutes=Lh;exports.registerKosModel=Wa;exports.registerLegacyModel=qa;exports.resetKosModel=lf;exports.resetPassword=fd;exports.resolveBaseUrl=Ja;exports.resolveChild=_a;exports.resolveContainerDeltas=Ou;exports.resolveItemListDeltas=Du;exports.resolveKosCompanion=qr;exports.resolveKosContext=Jf;exports.resolveKosProfiles=Gi;exports.resolveListDeltas=$u;exports.resolveServiceUrl=oe;exports.resolveVariable=ra;exports.retryWithExponentialBackoff=Hf;exports.sendAsyncIntent=ng;exports.sendBroadcastMessage=Hh;exports.sendIntent=og;exports.sendKosHttpMessageResponse=Ua;exports.sendKosMessage=jh;exports.sendKosMessageResponse=Na;exports.sendRequest=Zf;exports.sendStudioMessage=Kh;exports.sendStudioMessageRequest=Bh;exports.setupCompanionDecoratorMixin=qy;exports.setupCompleteFutureSupport=ed;exports.setupMinimalFutureSupport=Ky;exports.startPasswordReset=hd;exports.stringComponentInsert=Ad;exports.studioAcceptOrgInvitation=ib;exports.studioLogin=rb;exports.studioResetPassword=nb;exports.studioStartPasswordReset=ob;exports.subscribeStore=Qy;exports.syncPublish=Xf;exports.transitionToActive=ma;exports.transitionToInit=wa;exports.transitionToLoad=ba;exports.transitionToReady=ya;exports.transitionToUnload=Mh;exports.troubleByTypeReducer=Nm;exports.troubleDataFactory=ul;exports.unloadKosModel=cf;exports.updateCompanionModelRegistration=Uf;exports.updateModelRegistration=Nf;exports.updateRegion=id;exports.updateTimeZone=lo;exports.useAmPmValues=au;exports.useCalendarDayArray=Wd;exports.useConfigBean=bw;exports.useConfigProperty=Ld;exports.useContextModel=pb;exports.useContextModelHierarchy=wd;exports.useDateArrays=Kd;exports.useDateProps=Iw;exports.useDateRelativeConfig=Sw;exports.useDateRelativeData=Xd;exports.useDayNames=Yd;exports.useDayOptions=Vd;exports.useDays=Sn;exports.useDevice=$d;exports.useFormattedDate=qd;exports.useFormattedTime=lu;exports.useFunctionWarmup=Ow;exports.useHourValues=iu;exports.useKosCore=_d;exports.useKosDateFormats=Dw;exports.useKosModel=q;exports.useKosRegions=ru;exports.useKosTime=bn;exports.useKosTimeContext=Rb;exports.useKosTimeFormats=kw;exports.useKosTimeZones=Aw;exports.useKosTranslation=hw;exports.useKosTranslationContext=Nb;exports.useLocalComputed=Fw;exports.useModelFromHierarchy=wb;exports.useMonths=zd;exports.useMonthsOptions=Gd;exports.useMutationObserver=Uw;exports.useNetworkInterfaceContainer=Dd;exports.useOta=Cd;exports.usePressGesture=jw;exports.useProjectReload=nu;exports.useRegionTimeProps=Bw;exports.useRegionalTimeDate=Zd;exports.useSoftwareInfo=vn;exports.useSoftwareInfoContext=Pb;exports.useStateProperty=ew;exports.useStorageDeviceContainer=Rd;exports.useSuspenseData=uo;exports.useTimeOptions=cu;exports.useTimeProps=du;exports.useTimeValues=ho;exports.useTimer=sw;exports.useTranslationContainer=xd;exports.useTroubleContainerModel=Tn;exports.useTroubleModel=gw;exports.useTroublePresence=pw;exports.useUsbUpdateContainer=Pd;exports.useYears=In;exports.useYearsOptions=Hd;exports.uuid=mt;exports.variableToHex=qu;exports.waitForAppToStart=ig;exports.waitForAppsToStart=lc;exports.waitForRequest=xo;exports.whenReady=ae;exports.withDevice=Yb;exports.withKosModelFutures=Hy;exports.withKosTime=Wb;exports.withNetworkInterfaceContainer=Qb;exports.withOta=Zb;exports.withProjectReloading=Kw;exports.withSoftwareInfo=Ab;exports.withStorageDeviceContainer=tw;exports.withTranslationContainer=fw;exports.withTroubleContainer=mw;exports.withUsbUpdateContainer=yw;exports.wrapPromise=_o;
195
195
  //# sourceMappingURL=index.cjs.map