@kosdev-code/kos-ui-sdk 2.1.15 → 2.1.17

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.
@@ -1 +1 @@
1
- {"version":3,"file":"log.d.ts","sourceRoot":"","sources":["../../../../../../../packages/sdk/kos-ui-sdk/src/core/core/log/log.ts"],"names":[],"mappings":"AAAA,OAAO,GAAiB,MAAM,UAAU,CAAC;AAsFzC,eAAO,MAAM,MAAM;kBALyB,YAAY;iBAAZ,YAAY;iBAAZ,YAAY;kBAAZ,YAAY;sBAYpC,MAAM;;;;oCAEQ;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE;qBAkB/C,GAAG,EAAE;wBAIF,GAAG,EAAE;;;;;;;;;;;;;;;;;;CAI1B,CAAC"}
1
+ {"version":3,"file":"log.d.ts","sourceRoot":"","sources":["../../../../../../../packages/sdk/kos-ui-sdk/src/core/core/log/log.ts"],"names":[],"mappings":"AAAA,OAAO,GAAiB,MAAM,UAAU,CAAC;AA8FzC,eAAO,MAAM,MAAM;kBALyB,YAAY;iBAAZ,YAAY;iBAAZ,YAAY;kBAAZ,YAAY;sBAYpC,MAAM;;;;oCAEQ;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE;qBAkB/C,GAAG,EAAE;wBAIF,GAAG,EAAE;;;;;;;;;;;;;;;;;;CAI1B,CAAC"}
package/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var mh=Object.defineProperty;var yh=(e,t,s)=>t in e?mh(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var l=(e,t,s)=>(yh(e,typeof t!="symbol"?t+"":t,s),s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const C=require("loglevel"),E=require("mobx"),y=require("robot3"),je=require("date-fns"),T=require("@emotion/react/jsx-runtime"),No=require("@emotion/styled"),sa=require("react-dom"),qe=require("@emotion/react"),g=require("react"),Uo=require("mobx-react-lite"),bh=require("@use-gesture/react"),Sr="method",ra="topic",At="url",Is="request-id",$r="response-id",jo="status",Le="dst-addr",oa="src-addr",Oe="type",Bo="ordered",Ko="tracker",na="Content-Type",ia="Cache-Control",aa="requestId",ca=process.env.KOS_LOGIN_URL||"http://localhost",la=process.env.KOS_APP_PORT||"8080",vh=`${ca}:${la}`,Xs="{MODEL_ID}";var Ss=(e=>(e.SEND="/ws/log/msg/send",e.RECEIVED="/ws/log/msg/receive",e))(Ss||{}),ua=(e=>(e.MSG_RECEIVE="/mock/msg/receive",e))(ua||{});const Ho="/kos/model/ready/";C.info("Initializing event bus");globalThis.kos=globalThis.kos||{};globalThis.kos.subscriptions=globalThis.kos.subscriptions||{};const K=globalThis.kos.subscriptions,wh=()=>Symbol("eventKey");function zo(e){return K[e]&&Object.getOwnPropertySymbols(K[e]).length>0}function $(e,t){const s=wh();return K[e]||(C.debug(`Initializing subscription for ${e}`),K[e]={}),C.debug(`Subscribing to ${e} with id ${s.toString()}`),K[e][s]=t,{count:K[e]?Object.getOwnPropertySymbols(K[e]).length:0,unsubscribe:()=>(C.debug(`Unsubscribing from ${e} with id ${s.toString()}`),K[e]&&K[e][s]&&delete K[e][s],K[e]&&Object.getOwnPropertySymbols(K[e]).length===0&&delete K[e],{count:K[e]?Object.getOwnPropertySymbols(K[e]).length:0})}}function z(e,t,s={}){if(!K[e]||Object.getOwnPropertySymbols(K[e]).length===0)return C.debug(`No subscriptions for ${e}. Not publishing.`),{eventType:e,subscribers:0};const r=Object.getOwnPropertySymbols(K[e]).length;return Object.getOwnPropertySymbols(K[e]).forEach(o=>{if(s.sync){const n=s.sync;C.debug(`Performing sync publish for ${e} with sync id ${n}`),K[e][o]({body:t,headers:s}).then(i=>{C.debug(`Response recieved for ${n}, publishing back to source.`),z(n,i)})}else C.debug(`Performing async publish for ${e}`),K[e][o]({body:t,headers:s})}),{eventType:e,subscribers:r}}function Eh(){C.warn("Resetting event bus"),Object.keys(K).forEach(e=>delete K[e])}function da(e,t){const s=$(e,r=>{s.unsubscribe(),t(r)});return s.unsubscribe}function Go(e,t){return new Promise((s,r)=>{let o=null;const n=da(e,i=>{o&&clearTimeout(o),s(i)});t&&(o=setTimeout(()=>{n(),r(new Error(`Timeout waiting for event: ${e}`))},t))})}const Mh=Object.freeze(Object.defineProperty({__proto__:null,hasEventSubscriptions:zo,once:da,publish:z,reset:Eh,subscribe:$,waitFor:Go},Symbol.toStringTag,{value:"Module"}));function Cr(e,t){const s=$(e,r=>{s.unsubscribe(),t(r)});return s.unsubscribe}function Dr(e,t){return new Promise((s,r)=>{let o=null;const n=Cr(e,i=>{o&&clearTimeout(o),s(i)});t&&(o=setTimeout(()=>{n(),r(new Error(`Timeout waiting for event: ${e}`))},t))})}function ha(e,t){const s=e.map(r=>Dr(r,t));return Promise.all(s)}function fa(e,t){return new Promise((s,r)=>{const o=[];let n=null,i=!1;const a=()=>{o.forEach(c=>c()),n&&clearTimeout(n)};e.forEach(c=>{const u=Cr(c,d=>{i||(i=!0,a(),s({eventType:c,data:d}))});o.push(u)}),t&&(n=setTimeout(()=>{i||(i=!0,a(),r(new Error(`Timeout waiting for any event: ${e.join(", ")}`)))},t))})}function pa(e,t,s){return $(e,o=>{o&&t(o)&&s(o)}).unsubscribe}function ga(e,t,s){return $(e,o=>{if(o){const n=t(o);s(n)}}).unsubscribe}function ma(e,t,s){let r=null;const o=$(e,n=>{r&&clearTimeout(r),r=setTimeout(()=>{s(n)},t)});return()=>{r&&clearTimeout(r),o.unsubscribe()}}function ya(e,t,s){let r=0,o=null;const n=$(e,i=>{const a=Date.now(),c=a-r;c>=t?(r=a,s(i)):o||(o=setTimeout(()=>{r=Date.now(),s(i),o=null},t-c))});return()=>{o&&clearTimeout(o),n.unsubscribe()}}function ba(e,t,s){let r=[],o=null;const n=()=>{r.length>0&&(s([...r]),r=[])},i=$(e,a=>{a&&(r.push(a),o||(o=setTimeout(()=>{n(),o=null},t)))});return()=>{o&&(clearTimeout(o),n()),i.unsubscribe()}}function Vo(e,t=1){const s=[];return $(e,r=>{r&&(s.push(r),s.length>t&&s.shift())}),{subscribe:r=>(s.forEach(o=>r(o)),$(e,r))}}function va(e,t){const s=e.map(r=>$(r,o=>{o&&t(r,o)}));return()=>{s.forEach(r=>r.unsubscribe())}}function wa(e,t){let s=e;const r=[],o=new Set;return Object.values(t).forEach(n=>{Object.keys(n).forEach(i=>{o.add(i)})}),o.forEach(n=>{const{unsubscribe:i}=$(n,a=>{const c=t[s];c&&c[n]&&(s=c[n](a))});r.push(i)}),{get state(){return s},unsubscribe:()=>{r.forEach(n=>n())}}}function Ea(e,t,s,r){const o=Dr(t,r);return z(e,s),o}async function*Ma(e){const t=[],s=[],r=$(e,o=>{o&&(s.length>0?s.shift()(o):t.push(o))});try{for(;;)t.length>0?yield t.shift():yield await new Promise(o=>{s.push(o)})}finally{r.unsubscribe()}}const Th={once:Cr,waitFor:Dr,waitForAll:ha,race:fa,filter:pa,map:ga,debounce:ma,throttle:ya,buffer:ba,replay:Vo,merge:va,stateMachine:wa,request:Ea,eventIterator:Ma},_h=Object.freeze(Object.defineProperty({__proto__:null,EventBusFunctional:Th,buffer:ba,debounce:ma,eventIterator:Ma,filter:pa,map:ga,merge:va,once:Cr,race:fa,replay:Vo,request:Ea,stateMachine:wa,throttle:ya,waitFor:Dr,waitForAll:ha},Symbol.toStringTag,{value:"Module"}));async function xr(e,t){const{getCurrentState:s,transformState:r,shouldUseFetchedState:o,timeout:n}=t,i=Go(e,n),a=await s(),c=r?r(a):a;return o&&o(c)?(i.catch(()=>{}),c):await Promise.race([i,new Promise(d=>{setTimeout(()=>d(c),100)})])}function Ta(e,t,s){const{getCurrentState:r,transformState:o}=s;let n=!1;const i=$(e,a=>{a&&(n=!0,t(a))});return Promise.resolve(r()).then(a=>{const c=o?o(a):a;n||t(c)}).catch(a=>{console.error("Failed to fetch initial state:",a)}),i.unsubscribe}function _a(e,t){let s;const r=new Set,o=async()=>{try{typeof t=="string"?s=await(await fetch(t)).json():s=await t(),r.forEach(a=>a(s))}catch(a){throw console.error("Failed to fetch initial state:",a),a}};$(e,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 Yo(e,t){if(typeof e=="string")return xr(e,t);const s=e,{getCurrentState:r,shouldUseFetchedState:o,timeout:n}=t,i=await r(),a=t.transformState?t.transformState(i):i;if(o&&o(a))return a;const c=s.map(d=>Go(d,n)),u=await Promise.all(c);return u[u.length-1]}function Oa(e,t,s){const{fetchMissedEvents:r,checkInterval:o=3e4,deduplicateById:n}=s,i=new Set,a=$(e,async u=>{if(u){if(n){const d=n(u);if(i.has(d))return;i.add(d),i.size>1e3&&Array.from(i).slice(0,500).forEach(f=>i.delete(f))}await t(u)}}),c=setInterval(async()=>{try{const u=await r(),d=Array.isArray(u)?u:[u];for(const h of d)if(n){const f=n(h);i.has(f)||(i.add(f),await t(h))}else await t(h)}catch(u){console.error("Failed to fetch missed events:",u)}},o);return()=>{a.unsubscribe(),clearInterval(c)}}function Ia(e){const{connectEvent:t,disconnectEvent:s,errorEvent:r,dataEvent:o,fetchInitialState:n,reconnectDelay:i=5e3}=e,a={state:"disconnected",data:void 0,async waitForConnection(d){if(a.state==="connected"&&a.data)return a.data;const h=await xr(t,{getCurrentState:n,shouldUseFetchedState:f=>!!f,timeout:d});return a.state="connected",a.data=h,u(),h},subscribe(d){return c.add(d),d(a),()=>{c.delete(d)}},async reconnect(){a.state="connecting",u();try{const d=await n();a.state="connected",a.data=d,u()}catch{a.state="error",u(),setTimeout(()=>{a.state==="error"&&a.reconnect()},i)}}},c=new Set,u=()=>{c.forEach(d=>d(a))};return $(t,d=>{a.state="connected",d!=null&&d.body&&(a.data=d.body),u()}),$(s,()=>{a.state="disconnected",u(),setTimeout(()=>{a.state==="disconnected"&&a.reconnect()},i)}),r&&$(r,()=>{a.state="error",u()}),o&&$(o,d=>{d!=null&&d.body&&a.state==="connected"&&(a.data=d.body,u())}),a.reconnect(),a}const Oh={waitForOrGetState:xr,subscribeWithInitialState:Ta,createStatefulEventStream:_a,waitForAllWithState:Yo,createResilientEventHandler:Oa,createConnectionStateManager:Ia},Ih=Object.freeze(Object.defineProperty({__proto__:null,EventBusState:Oh,createConnectionStateManager:Ia,createResilientEventHandler:Oa,createStatefulEventStream:_a,subscribeWithInitialState:Ta,waitForAllWithState:Yo,waitForOrGetState:xr},Symbol.toStringTag,{value:"Module"})),Sh=(e,t=0)=>{if(!+e)return{value:0,scale:"bytes",toString:()=>"0 bytes"};const s=1024,r=t<0?0:t,o=["bytes","KB","MB","GB","TB"],n=Math.floor(Math.log(e)/Math.log(s)),i=parseFloat((e/Math.pow(s,n)).toFixed(r)),a=o[n];return{value:i,scale:a,toString:()=>`${i} ${a}`}};function qo(e){let t="pending",s;const r=e.then(n=>{t="success",s=n},n=>{t="error",s=n});return{read:()=>{switch(t){case"pending":throw r;case"error":throw s;default:return s}}}}function tt(){return"xxxxxxxx-xxxx-4xxx-2xxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){const t=Math.random()*16|0;return(e=="x"?t:t&3|8).toString(16)})}function $h(e,t){t.forEach(s=>{Object.getOwnPropertyNames(s.prototype).forEach(r=>{const o=Object.getOwnPropertyDescriptor(s.prototype,r);Object.defineProperty(e.prototype,r,o)})})}function Ch(e,t){const s=e??[],r=t??[];return s.length!==r.length?!1:s.every((o,n)=>o===r[n])}const Wo=(e,t)=>{const s=e.map(n=>n.id);return t.map(n=>n.id).filter(n=>!s.includes(n))},Sa=e=>e,$a=e=>e,Dh=({container:e,onAddItem:t,onUpdateItem:s,onRemoveItem:r=Sa,idMapper:o=$a})=>n=>{const i=n.map(o),c=Wo(i,e.data).map(r).filter(Boolean);e.removeAll(c);const u=i.map(d=>{const h=e.getModel(d.id);return h&&s?s(d,h):t(d)}).filter(Boolean);e.addAll(u)},xh=({container:e,onAddItem:t,onRemoveItem:s=Sa,idMapper:r=$a})=>o=>{const n=o.map(r);Wo(n,e.models).forEach(s),n.forEach(t)},Ah=({items:e,onAddItem:t,onRemoveItem:s,idMapper:r=o=>o})=>o=>{const n=o.map(r);Wo(n,e).forEach(s),n.forEach(t)},Ph=(e,t="parent-")=>{let s=e;return s.startsWith(t)&&(s=s.replace(t,"")),s},pi=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"}),gi=[{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 Ca(e){let t=(e.getTime()-Date.now())/1e3;for(let s=0;s<=gi.length;s++){const r=gi[s];if(Math.abs(t)<r.amount)return pi.format(Math.round(t),r.name);t/=r.amount}return pi.format(Math.round(t),"years")}const Qo=e=>e%4===0&&e%100!==0||e%400===0,Zo=(e,t)=>[31,Qo(e)?29:28,31,30,31,30,31,31,30,31,30,31][t],Da=(e,t)=>{const s=new Date(e),r=e.getDate();return s.setDate(1),s.setMonth(s.getMonth()+t),s.setDate(Math.min(r,Zo(s.getFullYear(),s.getMonth()))),s},xa=(e,t)=>{const s=new Date(e);return s.setDate(s.getDate()+t),s},yt="en-US",Aa={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"}},Pa={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"}},Ra=(e,{dateStyle:t="short",locales:s=yt}={dateStyle:"short",locales:yt})=>{const r=t==="short"?Aa.short:{dateStyle:t};return new Intl.DateTimeFormat(s,r).format(e)},ka=(e,{locales:t=yt,timeStyle:s="short"}={locales:yt,timeStyle:"short"})=>{const r=Pa[s];return new Intl.DateTimeFormat(t,r).format(e)},La=(e,{dateStyle:t="short",locales:s=yt,timeStyle:r="short"}={dateStyle:"short",locales:yt,timeStyle:"short"})=>{const o={...t&&Aa[t],...r&&Pa[r]};return new Intl.DateTimeFormat(s,o).format(e)},Rh=Object.freeze(Object.defineProperty({__proto__:null,addDaysToDate:xa,addMonthsToDate:Da,formatDate:Ra,formatDateSince:Ca,formatDateTime:La,formatTime:ka,getDaysInMonth:Zo,isLeapYear:Qo},Symbol.toStringTag,{value:"Module"}));function Fa(e,t,s=300){let r;return(...o)=>{clearTimeout(r),r=setTimeout(()=>{t.apply(e,o)},s)}}const te="canvas-renderer",Xr=new Map,mi=new Map,Jr=new Map,eo=new Map,$s=(e,t)=>{Na[e]=t},Na={indexExtension:{registerIndexExtension:(e,t)=>{const s=eo.get(e)||{};Object.assign(s,t),eo.set(e,t)},loadIndexExtensions:e=>eo.get(e)||{}},loader:{registerLoader:(e,t)=>{mi.set(e,t)},executeLoader:async(e,t)=>{const s=mi.get(e);if(s)return await s(t)}},propertyMapper:{registerPropertyMapper:(e,t)=>{Jr.set(e,t)},hasMapper:e=>Jr.has(e),executeMapper:(e,t,s)=>{const r=Jr.get(e);return r?r(t,s):""}},dataMapper:{registerDataMapper:(e,t)=>{const s=Xr.get(e)||[];s.push(t),Xr.set(e,s)},executeMapper:async(e,t,s)=>{const r=Xr.get(e);if(!r)return{};const o={};for(const n of r){const i=await n(t,s);Object.assign(o,i)}return o}},canvas:{registerRenderer:(e,t)=>{if(!S[te]){console.warn(`Canvas renderer extension point is not registered. Cannot register renderer "${e}".`);return}S[te].register(e,t)}}},S=Na,kh=async({context:e,extension:t})=>{const s=await S.loader.executeLoader(t,{});return e==null||e.set(t,s),s},Lh=async({extension:e,contextData:t,data:s})=>await S.dataMapper.executeMapper(e,s,t),Fh=async({extension:e,contextData:t,data:s})=>await S.propertyMapper.executeMapper(e,s,t),Nh=Object.freeze(Object.defineProperty({__proto__:null,executeDataMapperExtension:Lh,executeLoaderExtension:kh,executePropertyMapperExtension:Fh},Symbol.toStringTag,{value:"Module"})),Uh="Extensions";class jh{constructor(){l(this,"extensions");this.extensions={}}register(t,s,r){this.extensions[t]={},this.extensions[t][s]={component:r}}get(t,s){if(!this.extensions[t])throw new Error(`Extension point ${t} not found`);return this.extensions[t][s]}get allExtensions(){return this.extensions}}const ge=(e=null)=>(e||window.location.search.replace("?","")).split("&").map(t=>{const[s,r]=t.split("=");return[s,decodeURIComponent(r||"")]}).reduce((t,[s,r])=>(t[s]=r,t),{}),Ua="studio.tools.preview",Bh="studio.relax.store.validation",ja="studio.log.debug",Ba="studio.log.info",Kh={profiles:[Ua]};var ta;const Hh=((ta=globalThis.getKosConfig)==null?void 0:ta.call(globalThis))||JSON.stringify(Kh),Ka=JSON.parse(Hh);globalThis.kosConfig=Ka;const Xo=Ka,Ha=()=>Xo.profiles||[],yo=e=>Ha().includes(e),zh=()=>Xo.logging||!1,Gh=()=>{const e=yo(ja),t=yo(Ba);return e?"DEBUG":t?"INFO":void 0},za=()=>{const e=ge(),t=Gh(),r=e.kosLogLevel??t??window.kosLogLevel??process.env.KOS_LOG_LEVEL;return r||"WARN"},Ga=()=>window.kosMessageLogging||process.env.KOS_MESSAGE_LOGGING==="true",Va=()=>window.kosMessageStudioLogging||process.env.KOS_MESSAGE_STUDIO_LOGGING==="true",Ya="ws-log",Vh=C.methodFactory,qa=Ga(),Yh=Va();C.methodFactory=function(e,t,s){const r=Vh(e,t,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!==Ya||qa&&Yh)&&globalThis.kosLog(`UI: ${a}${o}`)}};let Wa=za();C.setLevel(Wa);window.setKosLogLevel=e=>{Wa=e,C.setLevel(e)};const Js=C.getLogger(Ya);window.enableKosMessageLog=()=>{Js.setLevel(C.levels.INFO)};window.disableKosMessageLog=()=>{Js.setLevel(C.levels.ERROR)};qa?window.enableKosMessageLog():window.disableKosMessageLog();const qh=["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(";"),Wh=["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(";"),ks=e=>t=>{C.getLevel()<=e&&t()},m={...C,ifDebug:ks(C.levels.DEBUG),ifInfo:ks(C.levels.INFO),ifWarn:ks(C.levels.WARN),ifError:ks(C.levels.ERROR),getLogger:e=>C.getLogger(`kos::${e}`),getLoggers:()=>C.getLoggers(),createLogger:({name:e,group:t})=>{var n,i,a,c;const s=`${t?`${t}:`:"kos"}::${e}`,r=C.getLogger(s);let o=(i=(n=globalThis.kos.logOverrides)==null?void 0:n.find(u=>u.name===s))==null?void 0:i.level;return o?r.setLevel(o):(o=(c=(a=globalThis.kos.logOverrides)==null?void 0:a.find(u=>s.startsWith(u.name)))==null?void 0:c.level,o&&r.setLevel(o)),r},wsSend:(...e)=>{const t=String(e).replace(/\n/g,"\\n");Js.info(`%c⬆ ${t}`,qh)},wsReceive:(...e)=>{const t=String(e).replace(/\n/g,"\\n");Js.info(`%c⬇ ${t}`,Wh)}},Qa="featureFlagResolver",Ls=new Map;$s(Qa,{register:(e,t)=>{var s;Ls.has(e)||Ls.set(e,[]),(s=Ls.get(e))==null||s.push(t)},execute:async(e,t)=>{const s=Ls.get(e);if(!s)return[];const r=s.map(a=>a(t)),n=(await Promise.allSettled(r)).map(a=>a.status==="fulfilled"?a.value:(m.info(`Feature flag resolver ${e} failed: ${a.reason}`),[])).flat(),i=Array.from(new Set(n)).reduce((a,c)=>(a[c]=!0,a),{});return Xa.updateFlags(i),Object.keys(i)}});const Qh="kos.loader.featureFlag";class Za{constructor(t={}){l(this,"flags",{});this.flags=t}isFeatureEnabled(t){return!!this.flags[t]}enableFeature(t){this.flags[t]=!0}disableFeature(t){this.flags[t]=!1}toggleFeature(t){this.flags[t]=!this.flags[t]}updateFlags(t){this.flags={...this.flags,...t}}}window.KosFeatureFlags=window.KosFeatureFlags??new Za;const Xa=window.KosFeatureFlags,Ja=(e,t,s)=>{s/=100;const r=t*Math.min(s,1-s)/100,o=n=>{const i=(n+e/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)}`},ec=e=>{const s=new RegExp("hsl\\((\\d+),\\s+(\\d+)\\%,\\s+(\\d+)\\%\\)").exec(e);if(!s)throw Error("Invalid HSL string");return Ja(parseInt(s[1]),parseInt(s[2]),parseInt(s[3]))},tc=(e,t)=>getComputedStyle(e).getPropertyValue(t),Zh=(e,t)=>ec(tc(e,t)),Xh=(e,t)=>{const s={...e};return s.id&&delete s.id,s},bo=(e,t,s=Xh)=>{const r=s(e,t);E.runInAction(()=>{Object.assign(t,r)})},to=new Map,sc={addToDeletionQueue:(e,t)=>{const s=to.get(e)||[];s.push(t),to.set(e,s)},cancelDeletion:e=>{const t=to.get(e);t&&t.forEach(s=>{clearTimeout(s)})}},Jh=m.createLogger({name:"kos-dependency-manager"});class ef{constructor(){l(this,"_usedByCache",new Map);l(this,"_usesCache",new Map)}add(t,s){sc.cancelDeletion(s);const r=this._usedByCache.get(s)||[];r.includes(t)||r.push(t),this._usedByCache.set(s,r);const o=this._usesCache.get(t)||[];o.includes(s)||o.push(s),this._usesCache.set(t,o)}remove(t,s){const r=this._usedByCache.get(s)||[];this._usedByCache.set(s,r.filter(n=>n!==t));const o=this._usesCache.get(t)||[];this._usesCache.set(t,o.filter(n=>n!==s))}canDestroy(t){const s=this._usedByCache.get(t);return s!=null&&s.length?(Jh.info(`Model ${t} is still used by: ${s.join(", ")}`),!1):!0}clear(){this._usedByCache.clear(),this._usesCache.clear()}}var v=(e=>(e.CREATING="creating",e.CREATED="created",e.INITIALIZING="initializing",e.INITIALIZED="initialized",e.LOADING="loading",e.LOADED="loaded",e.ONLINE="online",e.READYING="readying",e.READY="ready",e.READY_FAILED="ready_failed",e.RESETTING="resetting",e.RESET="reset",e.OFFLINE="offline",e.UNLOADING="unloading",e.UNLOADED="unloaded",e.FAILED="failed",e.INACTIVE="inactive",e.ACTIVE="active",e.ACTIVATING="activating",e.DEACTIVATING="deactivating",e))(v||{}),R=(e=>(e.CREATE="create",e.INITIALIZE="init",e.LOAD="load",e.READY="ready",e.GO_ONLINE="go_online",e.GO_OFFLINE="go_offline",e.RESET="go_offline",e.UNLOAD="unload",e.FAILED="failed",e.GO_ACTIVE="go_active",e.GO_INACTIVE="go_inactive",e.TIMEOUT="timeout",e))(R||{});const yi=m.createLogger({name:"kos-model-cache"});class tf{constructor(t=[]){l(this,"_modelsById",E.observable.map(new Map));l(this,"_toDelete",new Map);l(this,"_preloaded",[]);l(this,"_isPreloaded",!1);this.preloadKeys=t}get models(){return Array.from(this._modelsById.values()).map(t=>t).filter(t=>!this._toDelete.has(t.modelId))}getModelById(t){if(t&&!this._toDelete.has(t))return this._modelsById.get(t)}addModel(t){const s=this.getModelById(t.modelId)||t;return this._modelsById.set(s.modelId,s),s}removeModel(t){this._modelsById.delete(t),this._toDelete.delete(t)}hasModel(t){return!!t&&this._modelsById.has(t)&&!this._toDelete.has(t)}restoreFromDeleteCache(t){if(t&&this._toDelete.has(t)){const s=this._toDelete.get(t);this._toDelete.delete(t),this._modelsById.set(t,s)}}markForDeletion(t){this._modelsById.delete(t.modelId),this._toDelete.set(t.modelId,t)}preload(t){return this._isPreloaded?(yi.debug("Returning cached preloaded models"),this._preloaded):(this._preloaded=this.preloadKeys.map(s=>(yi.debug(`Preloading model: ${typeof s=="string"?s:s.modelType}`),t(s))).filter(s=>!!s),this._isPreloaded=!0,this._preloaded)}}const ee=Symbol("SubscriptionHandlers"),k=Symbol("DependencyModels"),os=Symbol("FutureService"),Be=Symbol("ChildModels"),ns=Symbol("ParentModel"),is=Symbol("LogConfig"),Vs=Symbol("ReferenceConfig"),Jo=Symbol("KosModelSymbol"),Ze=Symbol("ModelEffects"),bt=Symbol("CompanionParentModel"),en=Symbol("FutureContainerSetup"),tn=Symbol("MultipleFutureContainerSetup"),as=Symbol("FutureAliases"),sn=Symbol("TroubleAwareSetup"),rn=Symbol("LoggerSetup"),on=Symbol("ContainerAwareSetup"),Ie=(e,t)=>{e[Be]=e[Be]||{},e[Be][t]=!0},st=e=>`{PROP_${String(e)}}`,sf=e=>`{PROP_${String(e)}}`,rf=st("kosParentId"),Ar=e=>t=>{t[ns]=t[ns]||{};const s=(e==null?void 0:e.parentId)||rf;t[ns]={parentId:s}};function of(e){return t=>{const s=(e==null?void 0:e.mode)||"decorator",r=(e==null?void 0:e.parentProperty)||"companionParent",o=(e==null?void 0:e.excludeProperties)||[];return Ar()(t),t.prototype[bt]={mode:s,parentProperty:r,excludeProperties:o},t}}function rc(e){return t=>{const s=e!=null&&e.legacy?"_models":(e==null?void 0:e.containerProperty)||"container",r=(e==null?void 0:e.includeMethods)!==!1,o=(e==null?void 0:e.includeGetters)!==!1,n=(e==null?void 0:e.modelsProperty)||"models",i=(e==null?void 0:e.containerOptions)||{};return t.prototype[on]={containerProperty:s,includeMethods:r,includeGetters:o,modelsProperty:n,containerOptions:i,legacy:(e==null?void 0:e.legacy)||!1},t}}function nf(e,t,s){const r=s.value;s.value=function(...o){const n=V.getContext(this.id);return o.push(n),r.apply(this,o)}}function af(e){return t=>{const s=(e==null?void 0:e.mode)||"full",r=(e==null?void 0:e.handlerProperty)||"futureHandler";return t.prototype[en]={mode:s,handlerProperty:r},t}}function cf(e){return t=>{const s=(e==null?void 0:e.mode)||"full",r=(e==null?void 0:e.handlerProperty)||"futureHandler";return t.prototype[tn]={mode:s,handlerProperty:r},t}}var H=(e=>(e.INIT="init",e.LOAD="load",e.READY="ready",e.ACTIVATE="activate",e.ONLINE="online",e))(H||{});const lf=Object.freeze(Object.defineProperty({__proto__:null,DependencyLifecycle:H},Symbol.toStringTag,{value:"Module"})),xe=Symbol("HttpRouteHandlers"),bi="__httpBrowserRouter";function Pr(e){return function(s){return function(r,o,n){r[xe]=r[xe]||[];const i={method:e,path:s,handler:o};return r[xe].push(i),r[k]=r[k]||{},r[k][bi]||(r[k][bi]={modelType:"browser-router-model",lifecycle:H.INIT}),n}}}const oc=Pr("GET"),Cs=Pr("POST"),uf=Pr("PUT"),nc=Pr("DELETE"),df=nc;function er(e){return!!(e!=null&&e[xe])&&e[xe].length>0}function ic(e){return(e==null?void 0:e[xe])||[]}const hf=({group:e}={group:""})=>t=>{t[is]=t[is]||{},t[is]={group:e}};class ac{static create({modelId:t,modelTypeName:s,component:r}){const o=[r??"kos",s,t].filter(Boolean).join(".");return m.createLogger({name:o})}}function cc(e){return t=>{const s=(e==null?void 0:e.loggerProperty)||"logger",r=e==null?void 0:e.loggerContext;t.prototype[rn]={loggerProperty:s,loggerContext:r};const o=()=>{var i;return(i=t.prototype[Jo])==null?void 0:i.type};let n;return Object.defineProperty(t.prototype,s,{get(){if(!n){const i=o();n=ac.create({modelTypeName:r||i,component:"kos-model"})}return n},enumerable:!1,configurable:!1}),t}}function lc(e){return(t,s,r)=>{t[Ze]=t[Ze]||{},t[Ze][s]={dependencies:e==null?void 0:e.dependencies,value:r.value},r.value=function(){throw new Error(`Method ${s} cannot be called directly.`)}}}const ff=e=>(t,s)=>{t[Vs]=t[Vs]||{},t[Vs][s]=e};function pf(e){return t=>{const s=(e==null?void 0:e.pathProperty)||"path";return t.prototype[sn]={pathProperty:s},t.prototype[k]=t.prototype[k]||{},t.prototype[k].troubleContainer={modelType:"trouble-container-model",id:"trouble-container-model",options:{},lazy:!1},t}}const Pt=({modelType:e,id:t,options:s,lifecycle:r})=>(o,n)=>{o[k]=o[k]||{},o[k][n]={modelType:e,id:t,options:s,lifecycle:r||H.INIT}};class uc{constructor(t,s){l(this,"futures");l(this,"defaultContext");l(this,"context");l(this,"disposers",new Map);l(this,"container");this.futures=mn.map(new Map),this.context="",this.defaultContext=s||"",this.container=t,E.makeAutoObservable(this)}get allFutures(){return Array.from(this.futures.values())}get future(){return this.futures.get(this.defaultContext)}addFuture(t,s){this.futures.set(s||t.id,t),this.context=s||t.id;const r=Y(()=>{var o,n;(t.endState||t.progress)&&((n=(o=this.container)==null?void 0:o.onFutureUpdate)==null||n.call(o,t))});this.disposers.set(s||t.id,r)}removeFuture(t){var s;this.futures.delete(t||this.context),(s=this.disposers.get(t||this.context))==null||s(),this.disposers.delete(t||this.context)}getFuture(t){return this.futures.get(t||this.context)}get futureMap(){return this.futures}}class Rr{constructor(t){l(this,"disposer");l(this,"_future");l(this,"container");l(this,"onFutureUpdate");this._future=void 0,this.container=t,E.makeAutoObservable(this)}removeFuture(){var t;this._future=void 0,(t=this.disposer)==null||t.call(this),this.disposer=void 0}get future(){return this._future}getFuture(){return this._future}addFuture(t){this._future=t;const s=Y(()=>{var r,o;(t.endState||t.progress)&&((o=(r=this.container)==null?void 0:r.onFutureUpdate)==null||o.call(r,t))});this.disposer=s}get allFutures(){return this._future?[this._future]:[]}get timeRemaining(){var t;return((t=this._future)==null?void 0:t.timeRemaining)||""}get status(){var t;return((t=this._future)==null?void 0:t.status)||"NOT_RESOLVED"}get progress(){var t;return((t=this._future)==null?void 0:t.progress)||-1}async cancel(){if(this._future)try{await this._future.cancelFuture()}catch(t){throw m.error(t),t}}}const dc=(e,t)=>{const s=t.type;return e[s]||(e[s]=[]),e[s].push(t),e},hc=Symbol("KosObservableData");class fc{constructor(){l(this,"map");l(this,"_revision",1);l(this,"atomMap",new Map);l(this,"proxyHandler",{get:(t,s)=>{var r;return s==="_revision"||t[s]!==void 0?t[s]:this.atomMap.has(s)&&(r=this.atomMap.get(s))!=null&&r.reportObserved()?this.getValue(s):this.getValue(s)},set:(t,s,r)=>{var o;return this.map.has(s),this.setValue(s,r),this.atomMap.has(s)||this.atomMap.set(s,E.createAtom(s.toString())),(o=this.atomMap.get(s))==null||o.reportChanged(),!0},ownKeys:()=>[...Array.from(this.map.keys()),"_revision"]});this.map=E.observable.map(new Map),E.makeObservable(this,{_revision:E.observable})}setValue(t,s){const r=this.map.has(t);this.map.set(t,s),r||E.action(()=>{this._revision++})()}getValue(t){return this.map.get(t)}has(t){return this.map.has(t)}get entries(){return Array.from(this.map.entries())}get keys(){return this._revision,Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}setValues(t){t&&Object.keys(t).forEach(s=>{this.setValue(s,t[s])})}get proxy(){return new Proxy(this,this.proxyHandler)}}fc.prototype[hc]=!0;function gf(e,t){return new Proxy(e,{construct:(s,r)=>{const o=new e(...r);return o.setValues(t),o.proxy}})}const Te=e=>{const t=gf(fc,e);return new t(e)};function mf(e,t){return e.length!==t.length?!1:e.every(s=>t.includes(s))}class nn{constructor({container:t,key:s}){l(this,"_container");l(this,"_map");l(this,"_key");l(this,"data");this._container=t,this._map=E.observable.map(new Map),this._key=s,this.data=Te(),this.generateIndex(),E.autorun(()=>{this._container.revision&&this.generateIndex()}),E.makeAutoObservable(this)}refresh(){this.generateIndex()}addItemToIndex(t,s,r=this._map,o=this.data){const n=r.get(t)||new Set;n.add(s),r.set(t,n),o[t]=Array.from(n)}resolveIndex(t,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(mf(n,i))m.debug(`KosContainerIndex - Index ${o} is the same`);else{this.data[o]=n;const a=t.get(o)||new Set;this._map.set(o,a)}})}generateIndex(){E.runInAction(async()=>{const t=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,t,s)}):typeof o=="string"||typeof o=="number"?this.addItemToIndex(String(o),r,t,s):typeof o=="boolean"&&this.addItemToIndex(String(o),r,t,s)}this.resolveIndex(t,s)})}get keys(){return Array.from(this._map.keys())}get index(){return this._map}getByKey(t){const s=this._map.get(t);return s?Array.from(s):[]}}function yf(e,t,s=[]){const r=Object.getOwnPropertyDescriptors(e);return Object.keys(r).filter(i=>E.isComputedProp(e,i)).filter(i=>s.includes(i)).map(i=>E.reaction(()=>e[i],(a,c)=>{t({name:i,newValue:a,oldValue:c})}))}const Kt=m.createLogger({name:"kos-container-model"});class Se{constructor(t){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=E.observable.map(new Map),this._sortKey=t==null?void 0:t.sortKey,this._revision=1;const s=t!=null&&t.extensionId?S.indexExtension.loadIndexExtensions(t.extensionId):{},r=(t==null?void 0:t.indexMap)||{};this._optionsMap={...r,...s};const o=t!=null&&t.indexMap?Object.keys(t.indexMap).reduce((n,i)=>(n[i]=void 0,n),{}):{};this._index=E.observable.map(o),this.idx=Te(),this._parentId=t==null?void 0:t.parentId,E.makeAutoObservable(this),this.init()}init(){Object.keys(this._optionsMap).forEach(t=>{const s=this._optionsMap[t],r=new nn({container:this,key:s});this._index.set(t,r),this.idx[t]=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((t,s)=>{var r;return t[s]=(r=this.index.get(s))==null?void 0:r.keys,t},{})}sortFn(t,s){const r=this._sortKey;return r?String(t[r]).localeCompare(String(s[r]),void 0,{numeric:!0}):0}get data(){const t=Array.from(this._data.values());return this._sortKey&&t.sort(this.sortFn.bind(this)),t}increment(){E.runInAction(()=>{this._revision=this._revision+1})}addAll(t){E.runInAction(()=>{t.forEach(s=>this.addModel(s,!0))}),this.increment()}removeAll(t){E.runInAction(()=>{t.forEach(s=>this.removeModel(s,!0)),this.increment()})}addModel(t,s){this._data.set(t.id||"",t),t.id&&this._parentId&&V.setParentContext(t.id,this._parentId),s||this.increment();const r=this._disposerMap.get(t.id);r&&(r(),this._disposerMap.delete(t.id));const o=Object.entries(this._optionsMap||{}),n=Object.values(this._optionsMap||{}),i=new Map(o.map(([d,h])=>[h,d])),a=d=>{var f,p;n.includes(d.name)&&((f=this.index.get(i.get(d.name)))==null||f.refresh());const h=o.filter(([,b])=>typeof b=="function");for(const[b]of h)(p=this.index.get(b))==null||p.refresh()},c=yf(t,a,n.filter(d=>typeof d=="string")),u=E.observe(t,a);this._disposerMap.set(t.id||"",()=>[u,...c].forEach(d=>d()))}removeModel(t,s){this._data.delete(t),s||this.increment();const r=this._disposerMap.get(t);r&&(r(),this._disposerMap.delete(t))}updateModel(t){this._data.set(t.id||"",t),this.increment()}getModel(t){return this._data.get(t)}getIndexKeys(t){return this.index.has(t)?this.index.get(t).keys??[]:(Kt.info(`index ${t} not found in ${Array.from(this.index.keys())}`),[])}getIndexByKey(t,s){if(this.index.has(t)){const r=this.index.get(t);return r.index.has(s)?r.getByKey(s):(Kt.info(`key ${s} not found in ${t} index: ${Array.from(r.index.keys())}`),[])}else return Kt.info(`index ${t} not found in ${Array.from(this.index.keys())}`),[]}async clear(){this._data.forEach(t=>{const s=t.id;Xe(t).then(()=>{Kt.debug(`${s} destroyed, removing from map`),this.removeModel(s,!0)}).catch(r=>Kt.error(r))}),this.increment()}filter(t,s){return this.data.filter(t,s)}sort(t){return this.data.sort(t)}map(t,s){return this.data.map(t,s)}forEach(t,s){this.data.forEach(t,s)}toJSON(){return{indexes:this.indexKeys,data:this.data.map(s=>({id:s.id,type:s.constructor.name}))}}}const ue=async e=>{if(e.id){const t=I.getInstance().modelManager.getModelById(e.id);if(!t)throw new Error(`Model with ID ${e.id} not found`);await(t==null?void 0:t.whenReady())}else throw new Error("Data model must have a valid ID");return e},Xe=async e=>{await I.getInstance().whenReady(),await I.getInstance().modelManager.initiateDestroyModel(e)},bf=async e=>{if(await I.getInstance().whenReady(),!e.id)throw new Error("Model ID is required");const t=I.getInstance().modelManager.getModelById(e.id);t&&await t.fsm.transitionTo(R.UNLOAD,v.UNLOADED)},vf=async e=>{await I.getInstance().whenReady(),await I.getInstance().modelManager.reloadModel(e),m.debug(`reload model initiated for model ${e.id}, model ready: ${tr(e)} - ${Date.now()} `),await ue(e),m.debug(`reload model complete for model ${e.id}, model ready: ${tr(e)} - ${Date.now()} `)},wf=async e=>{if(await I.getInstance().whenReady(),!e)throw new Error("Model ID is required");const t=I.getInstance().modelManager.getModelById(e);return t==null?void 0:t.modelTypeName},pc=async e=>{if(await I.getInstance().whenReady(),!e)throw new Error("Model ID is required");const t=I.getInstance().modelManager.getModelById(e);return{model:t==null?void 0:t.modelData,type:t==null?void 0:t.modelTypeName}},_e=e=>{if(!e)throw new Error("Model ID is required");const t=I.getInstance().modelManager.getModelById(e);return{model:t==null?void 0:t.modelData,type:t==null?void 0:t.modelTypeName}},gc=(e,t)=>{if(!e)throw new Error("Model type is required");return I.getInstance().modelManager.getModelsByType(e).filter(o=>Object.keys(t).every(n=>o[n]===t[n]))},Ef=(e,t)=>gc(e,t)[0],Mf=(e,t)=>{if(!e.id)throw new Error("Model ID is required");const s=I.getInstance().modelManager.getModelById(e.id);if(!s)throw new Error("Model not found");const r=s.companionModels.get(t);return r==null?void 0:r.modelData},mc=e=>{if(!e.id)throw new Error("Model ID is required");const t=I.getInstance().modelManager.getModelById(e.id);if(!t)throw new Error("Model not found");return Array.from(t.companionModels.all()).map(r=>r.modelData)},Tf=e=>{if(!e)throw new Error("Model ID is required");const t=I.getInstance().modelManager.getModelById(e);if(!t)throw new Error("Model not found");return t.companionModels.data},vo=(e,t)=>{const s=I.getInstance().modelManager.getModelById(e);if(!s){m.info(`Model not found for id ${e}`);return}return Array.from(s.companionModels.all()).find(o=>t(o.modelData))},Ee=e=>t=>Object.getPrototypeOf(t).modelTypeId===e,tr=e=>{const t=I.getInstance().modelManager.getModelById(e.id);if(!t)throw new Error("Model not found");return t.isReady()},_f=m.createLogger({name:"kos-model-factory"}),cs={byModelType:e=>I.getInstance().modelManager.getModelFactory(e),getModelInstance:(e,t,s)=>{const r=cs.byModelType(t);if(!r)throw _f.error(`No registered factory found for model type ${t}. Please register a factory for this model type. `),Error(`No factory found for model type ${t}`);return r.build(e,s)}},ie={Factory:{create:e=>t=>(s,r)=>(r&&V.setParentContext(t,r),cs.getModelInstance(t,e,s))},Singleton:{create:e=>(t,s)=>(s&&V.setParentContext(e,s),cs.getModelInstance(e,e,t))},Model:{instance:e=>t=>cs.getModelInstance(t,e)}};window.KosRegistry=window.KosRegistry||{coreModels:new Map,preloadModels:[],companionModels:new Map,models:new Map};const vi=window.KosRegistry.coreModels,so=window.KosRegistry.preloadModels,ro=window.KosRegistry.companionModels,Fs=window.KosRegistry.models,x={model:{registerLegacyModel:e=>(t,s)=>(vi.set(t,s),{preload:x.model.preloadModel(e),model:x.model.register(e),companion:x.companion.register(e),legacy:x.model.registerLegacyModel(e),root:e}),preloadModel:e=>t=>(so.includes(t)||so.push(t),{preload:x.model.preloadModel(e),model:x.model.register(e),companion:x.companion.register(e),legacy:x.model.registerLegacyModel(e),root:e}),register:e=>(t,s)=>{const r=oo(t)?t.registration():t;return Fs.set(r.type,r),oo(t)&&t.relatedModels.forEach(o=>Fs.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],oo(t)&&t.relatedModels.forEach(o=>I.getInstance().modelManager.registry.models[o.type]=o.registration().registration))),s&&x.model.preloadModel(e)(r.type),{preload:x.model.preloadModel(e),model:x.model.register(e),companion:x.companion.register(e),legacy:x.model.registerLegacyModel(e),root:e}},get:e=>Fs.get(e),getAll:()=>Array.from(Fs.entries()),getPreloadModels:()=>so,getLegacyModels:()=>Array.from(vi.entries()).reduce((e,[t,s])=>(e[t]=s,e),{})},companion:{register:e=>(t,s)=>{const r=ro.get(t)||[];return r.push(s),ro.set(t,r),{preload:x.model.preloadModel(e),model:x.model.register(e),companion:x.companion.register(e),legacy:x.model.registerLegacyModel(e),root:e}},getAll:()=>Array.from(ro.entries())}},yc=x.model.registerLegacyModel,bc=x.model.register,Of=x.companion.register,If=x.model.preloadModel,an=e=>typeof e.updateModel=="function",oo=e=>e.registration!==void 0&&typeof e.registration=="function";class vc{constructor(t){l(this,"singleton");l(this,"type");l(this,"loader");l(this,"class");l(this,"guard");l(this,"factory");l(this,"relatedModels",[]);this.singleton=t.singleton,this.guard=Ee(t.type),this.type=t.type,this.loader=`kos.extension.model.loader.${t.type}`,this.factory=t.factory,this.class=t.class}addRelatedModel(t){this.relatedModels.push(t)}registerRelatedModels(){this.relatedModels.forEach(t=>t.register())}register(){x.model.register({})(this.registration()),this.registerRelatedModels()}}class me extends vc{constructor(t){super({...t,singleton:!1,factory:ie.Factory.create(t.type)})}instance(t){const s=this.factory(t);return{get:()=>{const r=_e(t);if(!r)throw new Error("Model not found with id "+t);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(an(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 Me extends vc{constructor(t){super({...t,singleton:!0,factory:ie.Singleton.create(t.type)})}instance(){const t=this.factory;return{get:()=>{const r=_e(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=t(r);if(this.guard(o)){if(an(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=t(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 no=m.createLogger({name:"resolve-parameters"}),vt=({value:e,modelId:t,modelData:s})=>{let r=e;if(Array.isArray(r))return[...e];if(typeof r!="string"&&typeof r!="object")return r;if(typeof r=="object")r=Object.keys(r).reduce((o,n)=>(o[n]=vt({value:r[n],modelId:t,modelData:s}),o),{});else if(typeof r=="string"){const o=new RegExp("{PROP_(.+?)}","g");let n=r!=null&&r.includes(Xs)?r.replace(Xs,t):r;if(s){let i=!1;const a=/^{PROP_.+?}$/.test(n);if(n=n.replace(o,(c,u)=>{if(Object.getOwnPropertyNames(s).includes(u)||Object.getOwnPropertyNames(Object.getPrototypeOf(s)).includes(u)){const h=s[u];return h?(no.debug(`Resolved ${c} to ${h}`),h):(no[a?"debug":"warn"](`Property ${u} is falsy${a?"":" in composite string"}, marking for undefined return`),i=!0,c)}return no[a?"debug":"warn"](`Property ${u} not found in modelData${a?"":" for composite string"}`),c}),i)return}return n}else return r;return r},wo=m.createLogger({group:"decorators",name:"kos-model"});function Sf(e,t,s){var n;const r=(n=e[ns])==null?void 0:n.parentId;if(!r)return;const o=vt({value:r,modelData:s,modelId:t});o&&typeof o=="string"&&V.setParentContext(t,o)}function $f(e){const t=e[os];t&&Object.entries(t).forEach(([s,{handler:r}])=>{e[s]=r})}function Cf(e,t){const s=e[k]||{};Object.entries(s).forEach(([r,o])=>{const n=vt({value:o.id||o.modelType,modelData:e,modelId:t}),i=Object.entries((o==null?void 0:o.options)||{}).reduce((a,[c,u])=>(a[c]=vt({value:u,modelData:e,modelId:t}),a),{});if(typeof n=="string"){if(!o.lazy){const a=I.getInstance().modelManager.createModelInstance(o.modelType,n,i);e[r]=a.data}I.getInstance().modelManager.addDependency(t,n)}})}function Df(e){const t=e[en];if(!t)return;const{mode:s,handlerProperty:r}=t,o=new Rr(e);e[r]=o,s==="full"&&(Object.defineProperty(e,"future",{get(){return o.future},enumerable:!0,configurable:!0}),Object.defineProperty(e,"progress",{get(){var n;return((n=o.future)==null?void 0:n.progress)||0},enumerable:!0,configurable:!0}),Object.defineProperty(e,"status",{get(){var n;return((n=o.future)==null?void 0:n.status)||"IDLE"},enumerable:!0,configurable:!0}),Object.defineProperty(e,"isRunning",{get(){return o.future?!o.future.endState:!1},enumerable:!0,configurable:!0}),Object.defineProperty(e,"isCancelled",{get(){var n;return((n=o.future)==null?void 0:n.status)==="CANCELLED"||!1},enumerable:!0,configurable:!0}),e.cancelFuture=async()=>{o.future&&await o.future.cancelFuture()})}function xf(e){const t=e[tn];if(!t)return;const{mode:s,handlerProperty:r}=t,o=new uc(e);e[r]=o,Object.defineProperty(e,"future",{get(){return o.future},enumerable:!0,configurable:!0});const n=e[as];n instanceof Map&&n.forEach(i=>{const a=`${i}Future`;Object.defineProperty(e,a,{get(){return o.futureMap.get(i)},enumerable:!0,configurable:!0}),s==="full"&&(Object.defineProperty(e,`${i}Progress`,{get(){const c=o.futureMap.get(i);return(c==null?void 0:c.progress)||0},enumerable:!0,configurable:!0}),Object.defineProperty(e,`${i}Status`,{get(){const c=o.futureMap.get(i);return(c==null?void 0:c.status)||"IDLE"},enumerable:!0,configurable:!0}),Object.defineProperty(e,`${i}IsRunning`,{get(){const c=o.futureMap.get(i);return c?!c.endState:!1},enumerable:!0,configurable:!0}),Object.defineProperty(e,`${i}IsCancelled`,{get(){const c=o.futureMap.get(i);return(c==null?void 0:c.status)==="CANCELLED"||!1},enumerable:!0,configurable:!0}),e[`cancel${i.charAt(0).toUpperCase()}${i.slice(1)}`]=async()=>{const c=o.futureMap.get(i);c&&await c.cancelFuture()})}),s==="full"&&(Object.defineProperty(e,"progress",{get(){var i;return((i=o.future)==null?void 0:i.progress)||0},enumerable:!0,configurable:!0}),Object.defineProperty(e,"status",{get(){var i;return((i=o.future)==null?void 0:i.status)||"IDLE"},enumerable:!0,configurable:!0}),Object.defineProperty(e,"isRunning",{get(){return o.future?!o.future.endState:!1},enumerable:!0,configurable:!0}),Object.defineProperty(e,"isCancelled",{get(){var i;return((i=o.future)==null?void 0:i.status)==="CANCELLED"||!1},enumerable:!0,configurable:!0}),e.cancelFuture=async()=>{o.future&&await o.future.cancelFuture()})}function Af(e){const t=e[sn];if(!t)return;const{pathProperty:s}=t;Object.defineProperty(e,"troubles",{get(){const r=this[s];if(r==null){const o=`@kosTroubleAware: Path property '${s}' is undefined on model ${this.id||"unknown"}. Returning empty troubles array.`;return this.logger&&typeof this.logger.warn=="function"?this.logger.warn(o):console.warn(o),[]}return this.troubleContainer.troubles.getIndexByKey("byIface",r).sort((o,n)=>n.rank-o.rank)},enumerable:!0,configurable:!0}),Object.defineProperty(e,"troubleStatus",{get(){return""},enumerable:!0,configurable:!0}),Object.defineProperty(e,"troublesByType",{get(){return this.troubles.reduce(dc,{})},enumerable:!0,configurable:!0})}function Pf(e,t){const s=e[on];if(!s)return;const{containerProperty:r,includeMethods:o,includeGetters:n,modelsProperty:i,containerOptions:a,legacy:c}=s,u={...a,parentId:a.parentId||t},d=new Se(u);e[r]=d,e[Be]||(e[Be]={}),e[Be][r]=d,o&&(e.getModel=h=>d.getModel(h),e.addModel=h=>{d.addModel(h)},e.removeModel=h=>{d.removeModel(h)}),n&&(Object.defineProperty(e,i,{get(){return d},enumerable:!0,configurable:!0}),Object.defineProperty(e,"data",{get(){return d.data},enumerable:!0,configurable:!0}))}function Rf(e,t){const s=e.constructor.prototype[bt];if(!s)return;const{mode:r,parentProperty:o,excludeProperties:n}=s,i=t[o];if(!i){wo.warn(`Companion decorator configured but no parent model found at '${o}'`);return}if(e.getCompanionParent=()=>i,r==="composition")return;const a=["init","load","unload","ready","dispose","destroy","activate"],c=["getDependencies","getChildren","update","toJSON","forceUpdate","makeAutoObservable","runInAction","transaction","observe","unobserve","intercept","spy","trace","getCompanionParent"],u=p=>{const b=i.constructor.prototype[ee]||{};return Object.values(b).some(w=>{const M=w==null?void 0:w.handler;return M===i[p]||M===i.constructor.prototype[p]})},d=p=>p==="constructor"||p.startsWith("_")||p.startsWith("__")||a.includes(p)||c.includes(p)||n.includes(p)||u(p)||p in e,h=new Set;Object.getOwnPropertyNames(i).filter(p=>!d(p)).forEach(p=>h.add(p));let f=Object.getPrototypeOf(i);for(;f&&f!==Object.prototype;)Object.getOwnPropertyNames(f).filter(p=>!d(p)).forEach(p=>h.add(p)),f=Object.getPrototypeOf(f);for(const p of h)try{const b=i[p];typeof b=="function"?e[p]=(...w)=>b.apply(i,w):Object.defineProperty(e,p,{get:()=>i[p],set:w=>{i[p]=w},enumerable:!0,configurable:!0})}catch(b){wo.debug(`Skipping companion proxy for property ${p}:`,b)}}function kf(e){try{return E.makeAutoObservable(e)}catch(t){return wo.error("Failed to make observable:",t),e}}const Lf={construct(e,t){var c;const[s,r={}]=t,o=V.createContext(s);Sf(e,s,r);const i=!!e.prototype[rn]?null:m.createLogger({name:e.prototype.modelTypeId,group:((c=e[is])==null?void 0:c.group)??"kos-model"}),a=new e(s,r,{logger:i,kosContext:o});return $f(a),Df(a),xf(a),Af(a),Pf(a,s),Rf(a,r),Cf(a,s),kf(a)}};function A(e){return t=>{var n,i;const s=t,r=typeof e=="string"?{modelTypeId:e,autoRegister:!1}:{autoRegister:!1,...e};s.prototype.modelTypeId=r.modelTypeId,s.prototype[Jo]=!0,(n=s.prototype)[ee]??(n[ee]={}),(i=s.prototype)[k]??(i[k]={}),m.ifDebug(()=>{m.debug(`Registering model with id ${r.modelTypeId}`)});const o=new Proxy(s,Lf);if(r.singleton!==void 0){let a;r.singleton?a=new Me({class:o,type:r.modelTypeId}):a=new me({class:o,type:r.modelTypeId}),Object.defineProperty(o,"Registration",{value:a,writable:!1,enumerable:!0,configurable:!1}),r.autoRegister&&a.register()}return o}}const Ff=({topic:e,handler:t,websocket:s=!1,condition:r=()=>!0})=>o=>{o[ee]=o[ee]||{},Array.isArray(e)?e.forEach(n=>{o[ee][n]={websocket:s,handler:t,condition:r}}):o[ee][e]={websocket:s,handler:Fa(o,E.action(t),200),condition:r}};function wc(e,t,s){const r={};if(!e.endsWith("/*"))return r;const o=e.slice(0,-2);if(t.startsWith(o)){const n=t.slice(o.length+1),i=s||"path";r[i]=n}return r}function Ec(e){return e.endsWith("/*")}function U({topic:e,condition:t=(_,F)=>!0,transform:s=_=>_,websocket:r=!1,fos:o=!1,bridge:n=!1,skipParse:i=!1,lifecycle:a,destinationAddress:c,debounce:u,throttle:d,buffer:h,filter:f,once:p,replay:b,wildcardName:w,flow:M}){return(_,F,Q)=>{_[ee]=_[ee]||{};let O=Q.value;const W=typeof u=="number"?u:u==null?void 0:u.delay,B=typeof d=="number"?d:d==null?void 0:d.interval;W&&W>0?O=Nf(O,u):B&&B>0?O=Uf(O,d):h?O=jf(O,h):p&&(O=Bf(O));let J=t;if(f){const $e=t;J=(hi,fi,Zr)=>f(Zr)?$e(hi,fi,Zr):!1}const Ue={websocket:r,fos:o,bridge:n,handler:O,condition:J,transform:s,lifecycle:a,skipParse:i,destinationAddress:c,wildcardName:w,flow:M};Array.isArray(e)?e.forEach($e=>{_[ee][$e]=Ue}):_[ee][e]=Ue,b&&Kf(e,b.bufferSize)}}function Nf(e,t){const s=typeof t=="number"?t:t.delay,r=typeof t=="object"?t.discardIntermediate:!1;let o=null,n=[];return function(i){r?(o&&clearTimeout(o),o=setTimeout(()=>{e.call(this,i),o=null},s)):(n.push(i),o&&clearTimeout(o),o=setTimeout(()=>{const a=[...n];n=[],e.call(this,a),o=null},s))}}function Uf(e,t){const s=typeof t=="number"?t:t.interval,r=typeof t=="object"?t.discardIntermediate:!1;let o=0,n=null,i=[],a=!1;const c=function(){if(i.length>0){const u=[...i];i=[],e.call(this,u)}};return function(u){const d=Date.now(),h=d-o;r?h>=s?(o=d,e.call(this,u)):n||(n=setTimeout(()=>{o=Date.now(),e.call(this,u),n=null},s-h)):(i.push(u),h>=s?(o=d,c.call(this)):a||(a=!0,n=setTimeout(()=>{o=Date.now(),c.call(this),n=null,a=!1},s-h)))}}function jf(e,t){const s=[];let r=null;const o=t.maxSize||1e3,n=i=>{s.length>0&&(e.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},t.time))}}function Bf(e){let t=!1;return function(s){t||(t=!0,e.call(this,s))}}function Kf(e,t){(Array.isArray(e)?e:[e]).forEach(r=>{Vo(r,t)})}function Mc(e,t){return`${Ho}${e}${t?`/${t}`:`/${e}`}`}function Tc(e){return`${Ho}${e}`}function io(e){const t=[];return new Promise((s,r)=>{for(const{condition:o,onMatch:n}of e){const i=E.when(o,()=>{t.forEach(a=>a());try{n==null||n(),s()}catch(a){r(a)}});t.push(i)}})}const _c=5e3;class Hf extends Error{constructor(s,r){super(s);l(this,"model");this.model=r}}const Oc=(e,t,s)=>{let r;return{promise:new Promise((i,a)=>{r=setTimeout(()=>{m.error(`Model ${t.modelId} - ${t.modelTypeName} - ${s} timed out after ${e}ms`),a(new Hf(`${t.modelId} - ${t.modelTypeName} - ${s}`,t))},e)}),cancel:()=>{r&&clearTimeout(r)}}},Ic=e=>e.fsm.transitionTo(R.GO_ACTIVE,v.ACTIVE),Sc=e=>e.whenReady(),$c=e=>e.fsm.transitionTo(R.LOAD,v.LOADED),zf=e=>e.fsm.transitionTo(R.UNLOAD,v.UNLOADED),Cc=e=>e.fsm.transitionTo(R.INITIALIZE,v.INITIALIZED);var cn=(e=>(e.ACTIVE="active",e.READY="ready",e.LOAD="load",e.UNLOAD="unload",e.INIT="init",e))(cn||{});const Ys={active:Ic,ready:Sc,load:$c,init:Cc},Dc=(e,t)=>{const s=t.id||t.modelType,r=vt({value:s,modelData:e.modelData,modelId:e.modelId});m.debug(`activating dependent model ${t.modelType} with id ${r}`);const o=Object.keys((t==null?void 0:t.options)||{}).reduce((i,a)=>{const c=t.options[a];return i[a]=vt({value:c,modelData:e.modelData,modelId:e.modelId}),i},{});return{dependentModel:I.getInstance().modelManager.createModelInstance(t.modelType,r,o),dataModelId:r}},xc=(e,t=H.READY)=>{var o;const s=((o=e.modelData)==null?void 0:o[k])||{};return Object.keys(s).length===0?(m.debug(`${e.modelId} has no dependencies. Returning`),[]):Object.keys(s).filter(n=>s[n].lifecycle===t).map(n=>{const i=s[n],{dependentModel:a,dataModelId:c}=Dc(e,i);e.modelData[n]=a.data,m.debug(`waiting for dependent model ${i.modelType} with id ${c} - waiting for WHENREADY`);const u=async(f,p,b)=>{var w;await((w=f.whenReady)==null?void 0:w.call(f)),m.debug(`dependent model ${p} with id ${b} - READY`)},{promise:d,cancel:h}=Oc(_c,e,e.status);return Promise.race([u(a.model,i.modelType,c).then(()=>{h()}).catch(f=>{console.error(`Error waiting for dependent model ${i.modelType} with id ${c}:`,f),h()}),d])}).filter(n=>!!n)},Ac=async(e,t,s,r)=>{if(m.debug(`Execute lifecycle with ${t.length} models`),t.length===0){m.debug(`${e.modelId} has no children. Returning`);return}if(!s){m.error(`${e.modelId} is not transitioning with a valid target ${s}`);return}const o=t.map(a=>{let c;return Ys[s]&&a?c=Ys[s](a):(a||m.error("model is undefined. This shouldn't happen"),Ys[s]||m.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:(m.error(`No model found ${a.modelId}`),!1):(m.error(`No promise found ${a.modelId}`),!1)),i=(await Promise.allSettled(o.map(a=>{var d;const{promise:c,cancel:u}=Oc(_c,a.model,a.status);return Promise.race([(d=a.promise)==null?void 0:d.then(()=>{u()}).catch(h=>{m.error(`Model ${a.modelId} - ${a.type} failed to transition to ${s}: ${h.message}`),u()}),c])}))).filter(a=>a.status==="rejected");i.length>0&&m.error(`Model ${e.modelId} had ${i.length} failed child models on ${r}`)},Pc=async(e,t,s)=>{await Ac(e,e.getChildren().filter(r=>!!r),t,s)},zt=async(e,t)=>{const r=(await Promise.allSettled(xc(e,t))).filter(o=>o.status==="rejected");r.length&&(m.error(`There were ${r.length} failed dependent models on ${t}`),m.error(r))},Gf=e=>typeof e.toJSON=="function",ls=e=>e[k]!==void 0,ln=e=>e.revision!==void 0&&e.index!==void 0,Rc=e=>{if(e){if(ls(e))return e;if(ln(e))return e.data;if(e instanceof Map||e instanceof E.ObservableMap||e instanceof Set)return Array.from(e.values()).filter(ls);if(Array.isArray(e))return e.filter(ls)}};function Vf(e){const t=`KosModel(${e.modelTypeName}:${e.modelId})`;try{Object.defineProperty(e,Symbol.toStringTag,{value:t,configurable:!0})}catch{e.toString=()=>t}try{Object.defineProperty(e.constructor,"name",{value:`KosModel_${e.modelTypeName}`,configurable:!0})}catch{e.constructor.name=`KosModel_${e.modelTypeName}`}const s=["fsm","effectManager","subscriptionManager","onlineLifecycleManager","companionManager","childResolver","_offlineQueue"];for(const r of s)r in e&&Object.defineProperty(e,r,{enumerable:!1});Object.defineProperty(e,"debugState",{enumerable:!1,configurable:!0,get(){var r,o,n;return{id:e.modelId,type:e.modelTypeName,initialized:e.initialized,loaded:e.loaded,status:e.status,onlineStatus:e.onlineStatus,activeStatus:e.activeStatus,companions:(o=(r=e.companionManager)==null?void 0:r.all())==null?void 0:o.map(i=>i.modelTypeName),children:(n=e.getChildren)==null?void 0:n.call(e).map(i=>i.modelId),effects:!!e.effectManager,subs:!!e.subscriptionManager}}}),Yf(e.modelData,e.modelTypeName,e.modelId,e)}function Yf(e,t,s,r){Object.defineProperty(e,Symbol.toStringTag,{value:`KosModelData(${t}:${s})`,configurable:!0});try{Object.defineProperty(e.constructor,"name",{value:`${t}ModelData`,configurable:!0})}catch{e.constructor.name=`${t}ModelData`}Object.defineProperty(e,"debugState",{enumerable:!1,configurable:!0,get(){var a,c,u;const o=((a=r.getChildren)==null?void 0:a.call(r))||[],n=((c=r.companionManager)==null?void 0:c.all())||[],i=r.modelData[k]||{};return{id:s,type:t,companions:{count:n.length,data:n.map(d=>({type:d.modelTypeName,id:d.modelId}))},dependencies:{count:Object.keys(i).length,data:Object.values(i).map(d=>({id:d.id||d.modelType,type:d.modelType,options:d.options,lifecycle:d.lifecycle}))},children:{count:o.length,data:o.map(d=>({id:d.modelId,type:d.modelTypeName}))},data:((u=e.toJSON)==null?void 0:u.call(e))||{},subs:!!r.subscriptionManager}}}),Object.defineProperty(e,"toJSON",{configurable:!0,enumerable:!1,writable:!0,value:()=>{const o={};for(const n of Object.keys(e))if(!(n.startsWith("_")||typeof e[n]=="function"))try{const i=e[n];ls(i)?o[`[KOS Model] ${n}`]=typeof i.toJSON=="function"?i.toJSON():{id:i.id,type:i.constructor.name}:ln(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 qf{constructor(t){this.model=t}resolve(){const t=new Set([...this.getResolvedDecoratedChildren(),...this.getAdditionalChildren(),...this.model.companionModels.all()]),s=Array.from(t).map(r=>this.model.modelManager.getModelById(r.id||"")).filter(r=>r&&r.status!==v.FAILED).filter(r=>!!r);return s.forEach(r=>{try{V.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 t=((s=this.model.modelData)==null?void 0:s[Be])||{};return Object.keys(t).map(r=>Rc(this.model.modelData[r])).filter(r=>!!r).flat()}getAdditionalChildren(){var t,s;return((s=(t=this.model.modelData)==null?void 0:t.getChildren)==null?void 0:s.call(t))||[]}}class Wf{constructor(t){l(this,"companions",new E.ObservableMap);this.hostModel=t}add(t){this.companions.set(t.modelTypeName,t)}clear(){this.companions.clear()}get(t){return this.companions.get(t)}all(){return[...this.companions.values()]}get data(){return this.companions}}class Qf{constructor(t,s,r,o){l(this,"disposers",[]);this.modelTypeName=t,this.modelId=s,this.modelData=r,this.log=o}setup(){var s;const t=((s=this.modelData)==null?void 0:s[Ze])||{};for(const r of Object.keys(t)){const{value:o,dependencies:n,options:i}=t[r],a=o.bind(this.modelData),c=()=>{this.log.info(`Running effect ${r} for ${this.modelTypeName} (${this.modelId})`),E.runInAction(()=>a())},u=n?E.reaction(()=>n(this.modelData),c,{fireImmediately:!!(i!=null&&i.fireImmediately)}):E.autorun(c);this.disposers.push(u)}}disposeAll(){for(const t of this.disposers)try{t()}catch(s){this.log.info(`Failed to dispose effect for ${this.modelId}`,s)}this.disposers=[]}}const Zf=m.createLogger({name:"model-active-machine"}),Xf=e=>{const t=y.createMachine(v.INACTIVE,{[v.FAILED]:y.state(y.transition(R.GO_ACTIVE,v.ACTIVATING)),[v.INACTIVE]:y.state(y.transition(R.GO_ACTIVE,v.ACTIVATING)),[v.ACTIVATING]:y.invoke(()=>(e.activeStatus=v.ACTIVATING,e.activate()),y.transition("done",v.ACTIVE,y.action(()=>{e.activeStatus=v.ACTIVE})),y.transition("error",v.FAILED,y.action(()=>{e.activeStatus=v.FAILED}))),[v.ACTIVE]:y.state(y.transition(R.GO_INACTIVE,v.DEACTIVATING)),[v.DEACTIVATING]:y.invoke(()=>(e.activeStatus=v.DEACTIVATING,e.deactivate()),y.transition("done",v.INACTIVE,y.action(()=>{e.activeStatus=v.INACTIVE})),y.transition("error",v.FAILED,y.action(()=>{e.activeStatus=v.FAILED})))});return{service:y.interpret(t,r=>Zf.debug(r.machine.current)),machine:t}},wi=m.createLogger({name:"model-online-machine"}),Jf=e=>{const t=y.createMachine(v.OFFLINE,{[v.ONLINE]:y.state(y.transition(R.GO_OFFLINE,v.OFFLINE,y.action(async()=>{await e.offline(),e.onlineStatus=v.OFFLINE}))),[v.OFFLINE]:y.state(y.transition(R.GO_ONLINE,v.ONLINE,y.action(async()=>{wi.debug(`Going online with model ${e.modelId}`),await e.online(),e.onlineStatus=v.ONLINE,await e.fsm.transitionTo(R.INITIALIZE,v.INITIALIZED)})))}),s=y.interpret(t,r=>wi.debug(r.machine.current));return{machine:t,service:s}},ep=e=>{var r;const t=Xf(e).service,s=Jf(e).service;return y.createMachine(v.CREATING,{[v.CREATING]:y.state(y.transition(R.CREATE,v.CREATED)),[v.CREATED]:y.state(y.immediate(v.INITIALIZING)),[v.INITIALIZING]:y.invoke(()=>(X(()=>{e.status=v.INITIALIZING}),e.init()),y.transition("done",v.INITIALIZED,y.action(()=>{e.status=v.INITIALIZED})),y.transition("error",v.FAILED,y.action(()=>{m.error(`Model ${e.modelId} - ${e.modelTypeName} failed to initialize. Transitioning to FAILED state.`),e.status=v.FAILED}))),[v.INITIALIZED]:y.state(y.immediate(v.LOADING)),[v.LOADING]:y.invoke(()=>(X(()=>{e.status=v.LOADING}),e.load()),y.transition("done",v.LOADED,y.action(()=>{e.status=v.LOADED})),y.transition("error",v.FAILED,y.action(()=>{e.status=v.FAILED}))),[v.LOADED]:y.state(y.immediate(v.READYING),y.transition(R.UNLOAD,v.UNLOADING)),[v.RESETTING]:y.invoke(()=>{var o;return X(()=>{e.status=v.RESETTING}),(o=e.unload)==null||o.call(e),e.load()},y.transition("done",v.LOADED,y.action(()=>{e.status=v.LOADED}))),[v.READYING]:y.invoke(()=>(X(()=>{e.status=v.READYING}),e.ready()),y.transition("done",v.READY,y.action(()=>{X(()=>{e.status=v.READY}),s.send(R.GO_ONLINE)})),y.transition("error",v.FAILED,y.action(()=>{e.status=v.FAILED}))),[v.READY]:y.state(y.transition(R.UNLOAD,v.UNLOADED,y.action((r=e.unload)==null?void 0:r.bind(e))),y.transition(R.RESET,v.RESETTING),y.transition(R.GO_ONLINE,v.READY,y.action(()=>{s.send(R.GO_ONLINE)})),y.transition(R.GO_OFFLINE,v.READY,y.action(()=>{s.send(R.GO_OFFLINE)})),y.transition(R.GO_ACTIVE,v.READY,y.action(()=>{t.send(R.GO_ACTIVE)})),y.transition(R.GO_INACTIVE,v.READY,y.action(()=>{t.send(R.GO_INACTIVE)}))),[v.UNLOADED]:y.state(),[v.FAILED]:y.state()})},tp=m.createLogger({name:"kos-model-lifecycle"}),sp=e=>({service:y.interpret(ep(e),s=>tp.debug(`state machine for model ${e.modelId}: ${s.machine.current});`))});class rp{constructor(t,s){l(this,"disposer");l(this,"service");this.model=t,this.log=s;const r=sp(t);this.service=r.service,this.service.send(R.CREATE)}get current(){return this.service.machine.current}async transitionTo(t,s,r=v.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 ${t} toward target ${s}`),new Promise((n,i)=>{var a;(a=this.disposer)==null||a.call(this),this.disposer=E.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 ${t}`))):(this.log.debug(`Model ${this.model.modelId} reached target state ${s}`),n())}),this.service.send(t)}).finally(()=>{var n;(n=this.disposer)==null||n.call(this),this.disposer=void 0}))}getTransitionStatusFor(t){return[v.ACTIVE,v.INACTIVE].includes(t)?this.model.activeStatus:this.model.status}}const kc="browser-router-model";class un{constructor(t,s){l(this,"logger");l(this,"model");l(this,"router",null);l(this,"registered",!1);l(this,"registeredRoutes",[]);this.model=t,this.logger=s}registerAll(){var s;if(!er(this.model))return;let t=this.model.__httpBrowserRouter;if(!t)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"){t=o;break}}if(t||(t=(s=_e(kc))==null?void 0:s.model),!t)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(t)}setRouter(t){this.router=t,this.registered||this.registerRoutes()}hasRoutes(){return er(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 t=ic(this.model);t.length!==0&&(this.logger.debug(`Registering ${t.length} HTTP routes`),t.forEach(s=>{this.registerRoute(s)}),this.registered=!0)}resolvePropKey(t){const s=/\{PROP_([^}]+)\}/g;let r=t;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(t))!==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: ${t}`)}return r}registerRoute(t){if(!this.router)return;const s=this.model[t.handler];if(!s||typeof s!="function"){this.logger.error(`Handler method '${t.handler}' not found on model`);return}const r=this.resolvePropKey(t.path);this.logger.debug(`Registering ${t.method} ${r} -> ${t.handler}`+(r!==t.path?` (resolved from ${t.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 ${t.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(t.method,r),this.router.use(t.method,r,o),this.registeredRoutes.push({method:t.method,path:r})}checkForDuplicateRoute(t,s){if(!this.router)return;this.router.getRoutes().find(n=>n.method===t&&n.path===s)&&this.logger.warn(`Duplicate route detected: ${t} ${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 t=0;for(const s of this.registeredRoutes){const r=this.router.remove(s.method,s.path);t+=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 ${t} routes from browser router`)}this.registered=!1,this.registeredRoutes=[],this.router=null}getRegisteredRoutes(){return[...this.registeredRoutes]}}function op(e,t){if(!er(e))return;const s=_e(kc);if(!(s!=null&&s.model))throw t.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 un(e,t).setRouter(s.model)}class np{constructor(t){l(this,"queue",[]);this.log=t}enqueue(t){this.queue.push(t)}flush(){if(this.queue.length!==0){this.log.warn(`Processing ${this.queue.length} offline message(s)`);for(const t of this.queue)try{t()}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 ip{constructor(t,s){l(this,"unsubscribers",[]);this.model=t,this.log=s}register(){const t=this.model.modelId,s=$("/kosCore/online",async()=>{this.log.debug(`Online event received for ${t}, waiting for readiness...`),await this.model.whenReady(),this.log.debug(`${t} is ready — sending GO_ONLINE`),await this.model.fsm.transitionTo(R.GO_ONLINE,v.ONLINE)}),r=$("/kosCore/offline",async()=>{this.log.debug(`Offline event received for ${t} — sending GO_OFFLINE`),await this.model.fsm.transitionTo(R.GO_OFFLINE,v.OFFLINE)});this.unsubscribers.push(s.unsubscribe),this.unsubscribers.push(r.unsubscribe)}dispose(){this.unsubscribers.forEach(t=>t()),this.unsubscribers=[]}}class ap{constructor(t){l(this,"subscription");l(this,"unsubscribe");l(this,"eventType");this.eventType=t,this.subscription={queue:[],resolvers:[],closed:!1};const s=$(t,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(t=>{this.subscription.closed?t({done:!0,value:void 0}):this.subscription.resolvers.push(s=>{t({done:!1,value:s})})})}async return(){return this.subscription.closed=!0,this.unsubscribe(),this.subscription.resolvers.forEach(t=>{t(void 0)}),this.subscription.resolvers=[],{done:!0,value:void 0}}async throw(t){throw this.subscription.closed=!0,this.unsubscribe(),t}[Symbol.asyncIterator](){return this}}function Ei(e){return new ap(e)}var Lc=(e=>(e.GET="GET",e.PUT="PUT",e.POST="POST",e.DELETE="DELETE",e))(Lc||{});const Fc=({path:e,requestId:t,method:s,destinationAddress:r})=>{let o=`${Sr}:${s}
1
+ "use strict";var mh=Object.defineProperty;var yh=(e,t,s)=>t in e?mh(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var l=(e,t,s)=>(yh(e,typeof t!="symbol"?t+"":t,s),s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const C=require("loglevel"),E=require("mobx"),y=require("robot3"),je=require("date-fns"),T=require("@emotion/react/jsx-runtime"),No=require("@emotion/styled"),sa=require("react-dom"),qe=require("@emotion/react"),g=require("react"),Uo=require("mobx-react-lite"),bh=require("@use-gesture/react"),Sr="method",ra="topic",At="url",Is="request-id",$r="response-id",jo="status",Le="dst-addr",oa="src-addr",Oe="type",Bo="ordered",Ko="tracker",na="Content-Type",ia="Cache-Control",aa="requestId",ca=process.env.KOS_LOGIN_URL||"http://localhost",la=process.env.KOS_APP_PORT||"8080",vh=`${ca}:${la}`,Xs="{MODEL_ID}";var Ss=(e=>(e.SEND="/ws/log/msg/send",e.RECEIVED="/ws/log/msg/receive",e))(Ss||{}),ua=(e=>(e.MSG_RECEIVE="/mock/msg/receive",e))(ua||{});const Ho="/kos/model/ready/";C.info("Initializing event bus");globalThis.kos=globalThis.kos||{};globalThis.kos.subscriptions=globalThis.kos.subscriptions||{};const K=globalThis.kos.subscriptions,wh=()=>Symbol("eventKey");function zo(e){return K[e]&&Object.getOwnPropertySymbols(K[e]).length>0}function $(e,t){const s=wh();return K[e]||(C.debug(`Initializing subscription for ${e}`),K[e]={}),C.debug(`Subscribing to ${e} with id ${s.toString()}`),K[e][s]=t,{count:K[e]?Object.getOwnPropertySymbols(K[e]).length:0,unsubscribe:()=>(C.debug(`Unsubscribing from ${e} with id ${s.toString()}`),K[e]&&K[e][s]&&delete K[e][s],K[e]&&Object.getOwnPropertySymbols(K[e]).length===0&&delete K[e],{count:K[e]?Object.getOwnPropertySymbols(K[e]).length:0})}}function z(e,t,s={}){if(!K[e]||Object.getOwnPropertySymbols(K[e]).length===0)return C.debug(`No subscriptions for ${e}. Not publishing.`),{eventType:e,subscribers:0};const r=Object.getOwnPropertySymbols(K[e]).length;return Object.getOwnPropertySymbols(K[e]).forEach(o=>{if(s.sync){const n=s.sync;C.debug(`Performing sync publish for ${e} with sync id ${n}`),K[e][o]({body:t,headers:s}).then(i=>{C.debug(`Response recieved for ${n}, publishing back to source.`),z(n,i)})}else C.debug(`Performing async publish for ${e}`),K[e][o]({body:t,headers:s})}),{eventType:e,subscribers:r}}function Eh(){C.warn("Resetting event bus"),Object.keys(K).forEach(e=>delete K[e])}function da(e,t){const s=$(e,r=>{s.unsubscribe(),t(r)});return s.unsubscribe}function Go(e,t){return new Promise((s,r)=>{let o=null;const n=da(e,i=>{o&&clearTimeout(o),s(i)});t&&(o=setTimeout(()=>{n(),r(new Error(`Timeout waiting for event: ${e}`))},t))})}const Mh=Object.freeze(Object.defineProperty({__proto__:null,hasEventSubscriptions:zo,once:da,publish:z,reset:Eh,subscribe:$,waitFor:Go},Symbol.toStringTag,{value:"Module"}));function Cr(e,t){const s=$(e,r=>{s.unsubscribe(),t(r)});return s.unsubscribe}function Dr(e,t){return new Promise((s,r)=>{let o=null;const n=Cr(e,i=>{o&&clearTimeout(o),s(i)});t&&(o=setTimeout(()=>{n(),r(new Error(`Timeout waiting for event: ${e}`))},t))})}function ha(e,t){const s=e.map(r=>Dr(r,t));return Promise.all(s)}function fa(e,t){return new Promise((s,r)=>{const o=[];let n=null,i=!1;const a=()=>{o.forEach(c=>c()),n&&clearTimeout(n)};e.forEach(c=>{const u=Cr(c,d=>{i||(i=!0,a(),s({eventType:c,data:d}))});o.push(u)}),t&&(n=setTimeout(()=>{i||(i=!0,a(),r(new Error(`Timeout waiting for any event: ${e.join(", ")}`)))},t))})}function pa(e,t,s){return $(e,o=>{o&&t(o)&&s(o)}).unsubscribe}function ga(e,t,s){return $(e,o=>{if(o){const n=t(o);s(n)}}).unsubscribe}function ma(e,t,s){let r=null;const o=$(e,n=>{r&&clearTimeout(r),r=setTimeout(()=>{s(n)},t)});return()=>{r&&clearTimeout(r),o.unsubscribe()}}function ya(e,t,s){let r=0,o=null;const n=$(e,i=>{const a=Date.now(),c=a-r;c>=t?(r=a,s(i)):o||(o=setTimeout(()=>{r=Date.now(),s(i),o=null},t-c))});return()=>{o&&clearTimeout(o),n.unsubscribe()}}function ba(e,t,s){let r=[],o=null;const n=()=>{r.length>0&&(s([...r]),r=[])},i=$(e,a=>{a&&(r.push(a),o||(o=setTimeout(()=>{n(),o=null},t)))});return()=>{o&&(clearTimeout(o),n()),i.unsubscribe()}}function Vo(e,t=1){const s=[];return $(e,r=>{r&&(s.push(r),s.length>t&&s.shift())}),{subscribe:r=>(s.forEach(o=>r(o)),$(e,r))}}function va(e,t){const s=e.map(r=>$(r,o=>{o&&t(r,o)}));return()=>{s.forEach(r=>r.unsubscribe())}}function wa(e,t){let s=e;const r=[],o=new Set;return Object.values(t).forEach(n=>{Object.keys(n).forEach(i=>{o.add(i)})}),o.forEach(n=>{const{unsubscribe:i}=$(n,a=>{const c=t[s];c&&c[n]&&(s=c[n](a))});r.push(i)}),{get state(){return s},unsubscribe:()=>{r.forEach(n=>n())}}}function Ea(e,t,s,r){const o=Dr(t,r);return z(e,s),o}async function*Ma(e){const t=[],s=[],r=$(e,o=>{o&&(s.length>0?s.shift()(o):t.push(o))});try{for(;;)t.length>0?yield t.shift():yield await new Promise(o=>{s.push(o)})}finally{r.unsubscribe()}}const Th={once:Cr,waitFor:Dr,waitForAll:ha,race:fa,filter:pa,map:ga,debounce:ma,throttle:ya,buffer:ba,replay:Vo,merge:va,stateMachine:wa,request:Ea,eventIterator:Ma},_h=Object.freeze(Object.defineProperty({__proto__:null,EventBusFunctional:Th,buffer:ba,debounce:ma,eventIterator:Ma,filter:pa,map:ga,merge:va,once:Cr,race:fa,replay:Vo,request:Ea,stateMachine:wa,throttle:ya,waitFor:Dr,waitForAll:ha},Symbol.toStringTag,{value:"Module"}));async function xr(e,t){const{getCurrentState:s,transformState:r,shouldUseFetchedState:o,timeout:n}=t,i=Go(e,n),a=await s(),c=r?r(a):a;return o&&o(c)?(i.catch(()=>{}),c):await Promise.race([i,new Promise(d=>{setTimeout(()=>d(c),100)})])}function Ta(e,t,s){const{getCurrentState:r,transformState:o}=s;let n=!1;const i=$(e,a=>{a&&(n=!0,t(a))});return Promise.resolve(r()).then(a=>{const c=o?o(a):a;n||t(c)}).catch(a=>{console.error("Failed to fetch initial state:",a)}),i.unsubscribe}function _a(e,t){let s;const r=new Set,o=async()=>{try{typeof t=="string"?s=await(await fetch(t)).json():s=await t(),r.forEach(a=>a(s))}catch(a){throw console.error("Failed to fetch initial state:",a),a}};$(e,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 Yo(e,t){if(typeof e=="string")return xr(e,t);const s=e,{getCurrentState:r,shouldUseFetchedState:o,timeout:n}=t,i=await r(),a=t.transformState?t.transformState(i):i;if(o&&o(a))return a;const c=s.map(d=>Go(d,n)),u=await Promise.all(c);return u[u.length-1]}function Oa(e,t,s){const{fetchMissedEvents:r,checkInterval:o=3e4,deduplicateById:n}=s,i=new Set,a=$(e,async u=>{if(u){if(n){const d=n(u);if(i.has(d))return;i.add(d),i.size>1e3&&Array.from(i).slice(0,500).forEach(f=>i.delete(f))}await t(u)}}),c=setInterval(async()=>{try{const u=await r(),d=Array.isArray(u)?u:[u];for(const h of d)if(n){const f=n(h);i.has(f)||(i.add(f),await t(h))}else await t(h)}catch(u){console.error("Failed to fetch missed events:",u)}},o);return()=>{a.unsubscribe(),clearInterval(c)}}function Ia(e){const{connectEvent:t,disconnectEvent:s,errorEvent:r,dataEvent:o,fetchInitialState:n,reconnectDelay:i=5e3}=e,a={state:"disconnected",data:void 0,async waitForConnection(d){if(a.state==="connected"&&a.data)return a.data;const h=await xr(t,{getCurrentState:n,shouldUseFetchedState:f=>!!f,timeout:d});return a.state="connected",a.data=h,u(),h},subscribe(d){return c.add(d),d(a),()=>{c.delete(d)}},async reconnect(){a.state="connecting",u();try{const d=await n();a.state="connected",a.data=d,u()}catch{a.state="error",u(),setTimeout(()=>{a.state==="error"&&a.reconnect()},i)}}},c=new Set,u=()=>{c.forEach(d=>d(a))};return $(t,d=>{a.state="connected",d!=null&&d.body&&(a.data=d.body),u()}),$(s,()=>{a.state="disconnected",u(),setTimeout(()=>{a.state==="disconnected"&&a.reconnect()},i)}),r&&$(r,()=>{a.state="error",u()}),o&&$(o,d=>{d!=null&&d.body&&a.state==="connected"&&(a.data=d.body,u())}),a.reconnect(),a}const Oh={waitForOrGetState:xr,subscribeWithInitialState:Ta,createStatefulEventStream:_a,waitForAllWithState:Yo,createResilientEventHandler:Oa,createConnectionStateManager:Ia},Ih=Object.freeze(Object.defineProperty({__proto__:null,EventBusState:Oh,createConnectionStateManager:Ia,createResilientEventHandler:Oa,createStatefulEventStream:_a,subscribeWithInitialState:Ta,waitForAllWithState:Yo,waitForOrGetState:xr},Symbol.toStringTag,{value:"Module"})),Sh=(e,t=0)=>{if(!+e)return{value:0,scale:"bytes",toString:()=>"0 bytes"};const s=1024,r=t<0?0:t,o=["bytes","KB","MB","GB","TB"],n=Math.floor(Math.log(e)/Math.log(s)),i=parseFloat((e/Math.pow(s,n)).toFixed(r)),a=o[n];return{value:i,scale:a,toString:()=>`${i} ${a}`}};function qo(e){let t="pending",s;const r=e.then(n=>{t="success",s=n},n=>{t="error",s=n});return{read:()=>{switch(t){case"pending":throw r;case"error":throw s;default:return s}}}}function tt(){return"xxxxxxxx-xxxx-4xxx-2xxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){const t=Math.random()*16|0;return(e=="x"?t:t&3|8).toString(16)})}function $h(e,t){t.forEach(s=>{Object.getOwnPropertyNames(s.prototype).forEach(r=>{const o=Object.getOwnPropertyDescriptor(s.prototype,r);Object.defineProperty(e.prototype,r,o)})})}function Ch(e,t){const s=e??[],r=t??[];return s.length!==r.length?!1:s.every((o,n)=>o===r[n])}const Wo=(e,t)=>{const s=e.map(n=>n.id);return t.map(n=>n.id).filter(n=>!s.includes(n))},Sa=e=>e,$a=e=>e,Dh=({container:e,onAddItem:t,onUpdateItem:s,onRemoveItem:r=Sa,idMapper:o=$a})=>n=>{const i=n.map(o),c=Wo(i,e.data).map(r).filter(Boolean);e.removeAll(c);const u=i.map(d=>{const h=e.getModel(d.id);return h&&s?s(d,h):t(d)}).filter(Boolean);e.addAll(u)},xh=({container:e,onAddItem:t,onRemoveItem:s=Sa,idMapper:r=$a})=>o=>{const n=o.map(r);Wo(n,e.models).forEach(s),n.forEach(t)},Ah=({items:e,onAddItem:t,onRemoveItem:s,idMapper:r=o=>o})=>o=>{const n=o.map(r);Wo(n,e).forEach(s),n.forEach(t)},Ph=(e,t="parent-")=>{let s=e;return s.startsWith(t)&&(s=s.replace(t,"")),s},pi=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"}),gi=[{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 Ca(e){let t=(e.getTime()-Date.now())/1e3;for(let s=0;s<=gi.length;s++){const r=gi[s];if(Math.abs(t)<r.amount)return pi.format(Math.round(t),r.name);t/=r.amount}return pi.format(Math.round(t),"years")}const Qo=e=>e%4===0&&e%100!==0||e%400===0,Zo=(e,t)=>[31,Qo(e)?29:28,31,30,31,30,31,31,30,31,30,31][t],Da=(e,t)=>{const s=new Date(e),r=e.getDate();return s.setDate(1),s.setMonth(s.getMonth()+t),s.setDate(Math.min(r,Zo(s.getFullYear(),s.getMonth()))),s},xa=(e,t)=>{const s=new Date(e);return s.setDate(s.getDate()+t),s},yt="en-US",Aa={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"}},Pa={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"}},Ra=(e,{dateStyle:t="short",locales:s=yt}={dateStyle:"short",locales:yt})=>{const r=t==="short"?Aa.short:{dateStyle:t};return new Intl.DateTimeFormat(s,r).format(e)},ka=(e,{locales:t=yt,timeStyle:s="short"}={locales:yt,timeStyle:"short"})=>{const r=Pa[s];return new Intl.DateTimeFormat(t,r).format(e)},La=(e,{dateStyle:t="short",locales:s=yt,timeStyle:r="short"}={dateStyle:"short",locales:yt,timeStyle:"short"})=>{const o={...t&&Aa[t],...r&&Pa[r]};return new Intl.DateTimeFormat(s,o).format(e)},Rh=Object.freeze(Object.defineProperty({__proto__:null,addDaysToDate:xa,addMonthsToDate:Da,formatDate:Ra,formatDateSince:Ca,formatDateTime:La,formatTime:ka,getDaysInMonth:Zo,isLeapYear:Qo},Symbol.toStringTag,{value:"Module"}));function Fa(e,t,s=300){let r;return(...o)=>{clearTimeout(r),r=setTimeout(()=>{t.apply(e,o)},s)}}const te="canvas-renderer",Xr=new Map,mi=new Map,Jr=new Map,eo=new Map,$s=(e,t)=>{Na[e]=t},Na={indexExtension:{registerIndexExtension:(e,t)=>{const s=eo.get(e)||{};Object.assign(s,t),eo.set(e,t)},loadIndexExtensions:e=>eo.get(e)||{}},loader:{registerLoader:(e,t)=>{mi.set(e,t)},executeLoader:async(e,t)=>{const s=mi.get(e);if(s)return await s(t)}},propertyMapper:{registerPropertyMapper:(e,t)=>{Jr.set(e,t)},hasMapper:e=>Jr.has(e),executeMapper:(e,t,s)=>{const r=Jr.get(e);return r?r(t,s):""}},dataMapper:{registerDataMapper:(e,t)=>{const s=Xr.get(e)||[];s.push(t),Xr.set(e,s)},executeMapper:async(e,t,s)=>{const r=Xr.get(e);if(!r)return{};const o={};for(const n of r){const i=await n(t,s);Object.assign(o,i)}return o}},canvas:{registerRenderer:(e,t)=>{if(!S[te]){console.warn(`Canvas renderer extension point is not registered. Cannot register renderer "${e}".`);return}S[te].register(e,t)}}},S=Na,kh=async({context:e,extension:t})=>{const s=await S.loader.executeLoader(t,{});return e==null||e.set(t,s),s},Lh=async({extension:e,contextData:t,data:s})=>await S.dataMapper.executeMapper(e,s,t),Fh=async({extension:e,contextData:t,data:s})=>await S.propertyMapper.executeMapper(e,s,t),Nh=Object.freeze(Object.defineProperty({__proto__:null,executeDataMapperExtension:Lh,executeLoaderExtension:kh,executePropertyMapperExtension:Fh},Symbol.toStringTag,{value:"Module"})),Uh="Extensions";class jh{constructor(){l(this,"extensions");this.extensions={}}register(t,s,r){this.extensions[t]={},this.extensions[t][s]={component:r}}get(t,s){if(!this.extensions[t])throw new Error(`Extension point ${t} not found`);return this.extensions[t][s]}get allExtensions(){return this.extensions}}const ge=(e=null)=>(e||window.location.search.replace("?","")).split("&").map(t=>{const[s,r]=t.split("=");return[s,decodeURIComponent(r||"")]}).reduce((t,[s,r])=>(t[s]=r,t),{}),Ua="studio.tools.preview",Bh="studio.relax.store.validation",ja="studio.log.debug",Ba="studio.log.info",Kh={profiles:[Ua]};var ta;const Hh=((ta=globalThis.getKosConfig)==null?void 0:ta.call(globalThis))||JSON.stringify(Kh),Ka=JSON.parse(Hh);globalThis.kosConfig=Ka;const Xo=Ka,Ha=()=>Xo.profiles||[],yo=e=>Ha().includes(e),zh=()=>Xo.logging||!1,Gh=()=>{const e=yo(ja),t=yo(Ba);return e?"DEBUG":t?"INFO":void 0},za=()=>{const e=ge(),t=Gh(),r=e.kosLogLevel??t??window.kosLogLevel??process.env.KOS_LOG_LEVEL;return r||"WARN"},Ga=()=>window.kosMessageLogging||process.env.KOS_MESSAGE_LOGGING==="true",Va=()=>window.kosMessageStudioLogging||process.env.KOS_MESSAGE_STUDIO_LOGGING==="true",Ya="ws-log",Vh=C.methodFactory,qa=Ga(),Yh=Va();C.methodFactory=function(e,t,s){const r=Vh(e,t,s);return function(...o){var c;const n=s?String(s):"",i=n?`[${String(n).substring(n.lastIndexOf(":")+1)}] | `:"[root] | ",a=o.map(u=>typeof u=="object"?JSON.stringify(u):String(u)).join(" ");r(`${i}${a}`),(c=globalThis==null?void 0:globalThis.kosConfig)!=null&&c.logging&&globalThis.kosLog&&(s!==Ya||qa&&Yh)&&globalThis.kosLog(`UI: ${i}${a}`)}};let Wa=za();C.setLevel(Wa);window.setKosLogLevel=e=>{Wa=e,C.setLevel(e)};const Js=C.getLogger(Ya);window.enableKosMessageLog=()=>{Js.setLevel(C.levels.INFO)};window.disableKosMessageLog=()=>{Js.setLevel(C.levels.ERROR)};qa?window.enableKosMessageLog():window.disableKosMessageLog();const qh=["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(";"),Wh=["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(";"),ks=e=>t=>{C.getLevel()<=e&&t()},m={...C,ifDebug:ks(C.levels.DEBUG),ifInfo:ks(C.levels.INFO),ifWarn:ks(C.levels.WARN),ifError:ks(C.levels.ERROR),getLogger:e=>C.getLogger(`kos::${e}`),getLoggers:()=>C.getLoggers(),createLogger:({name:e,group:t})=>{var n,i,a,c;const s=`${t?`${t}:`:"kos"}::${e}`,r=C.getLogger(s);let o=(i=(n=globalThis.kos.logOverrides)==null?void 0:n.find(u=>u.name===s))==null?void 0:i.level;return o?r.setLevel(o):(o=(c=(a=globalThis.kos.logOverrides)==null?void 0:a.find(u=>s.startsWith(u.name)))==null?void 0:c.level,o&&r.setLevel(o)),r},wsSend:(...e)=>{const t=String(e).replace(/\n/g,"\\n");Js.info(`%c⬆ ${t}`,qh)},wsReceive:(...e)=>{const t=String(e).replace(/\n/g,"\\n");Js.info(`%c⬇ ${t}`,Wh)}},Qa="featureFlagResolver",Ls=new Map;$s(Qa,{register:(e,t)=>{var s;Ls.has(e)||Ls.set(e,[]),(s=Ls.get(e))==null||s.push(t)},execute:async(e,t)=>{const s=Ls.get(e);if(!s)return[];const r=s.map(a=>a(t)),n=(await Promise.allSettled(r)).map(a=>a.status==="fulfilled"?a.value:(m.info(`Feature flag resolver ${e} failed: ${a.reason}`),[])).flat(),i=Array.from(new Set(n)).reduce((a,c)=>(a[c]=!0,a),{});return Xa.updateFlags(i),Object.keys(i)}});const Qh="kos.loader.featureFlag";class Za{constructor(t={}){l(this,"flags",{});this.flags=t}isFeatureEnabled(t){return!!this.flags[t]}enableFeature(t){this.flags[t]=!0}disableFeature(t){this.flags[t]=!1}toggleFeature(t){this.flags[t]=!this.flags[t]}updateFlags(t){this.flags={...this.flags,...t}}}window.KosFeatureFlags=window.KosFeatureFlags??new Za;const Xa=window.KosFeatureFlags,Ja=(e,t,s)=>{s/=100;const r=t*Math.min(s,1-s)/100,o=n=>{const i=(n+e/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)}`},ec=e=>{const s=new RegExp("hsl\\((\\d+),\\s+(\\d+)\\%,\\s+(\\d+)\\%\\)").exec(e);if(!s)throw Error("Invalid HSL string");return Ja(parseInt(s[1]),parseInt(s[2]),parseInt(s[3]))},tc=(e,t)=>getComputedStyle(e).getPropertyValue(t),Zh=(e,t)=>ec(tc(e,t)),Xh=(e,t)=>{const s={...e};return s.id&&delete s.id,s},bo=(e,t,s=Xh)=>{const r=s(e,t);E.runInAction(()=>{Object.assign(t,r)})},to=new Map,sc={addToDeletionQueue:(e,t)=>{const s=to.get(e)||[];s.push(t),to.set(e,s)},cancelDeletion:e=>{const t=to.get(e);t&&t.forEach(s=>{clearTimeout(s)})}},Jh=m.createLogger({name:"kos-dependency-manager"});class ef{constructor(){l(this,"_usedByCache",new Map);l(this,"_usesCache",new Map)}add(t,s){sc.cancelDeletion(s);const r=this._usedByCache.get(s)||[];r.includes(t)||r.push(t),this._usedByCache.set(s,r);const o=this._usesCache.get(t)||[];o.includes(s)||o.push(s),this._usesCache.set(t,o)}remove(t,s){const r=this._usedByCache.get(s)||[];this._usedByCache.set(s,r.filter(n=>n!==t));const o=this._usesCache.get(t)||[];this._usesCache.set(t,o.filter(n=>n!==s))}canDestroy(t){const s=this._usedByCache.get(t);return s!=null&&s.length?(Jh.info(`Model ${t} is still used by: ${s.join(", ")}`),!1):!0}clear(){this._usedByCache.clear(),this._usesCache.clear()}}var v=(e=>(e.CREATING="creating",e.CREATED="created",e.INITIALIZING="initializing",e.INITIALIZED="initialized",e.LOADING="loading",e.LOADED="loaded",e.ONLINE="online",e.READYING="readying",e.READY="ready",e.READY_FAILED="ready_failed",e.RESETTING="resetting",e.RESET="reset",e.OFFLINE="offline",e.UNLOADING="unloading",e.UNLOADED="unloaded",e.FAILED="failed",e.INACTIVE="inactive",e.ACTIVE="active",e.ACTIVATING="activating",e.DEACTIVATING="deactivating",e))(v||{}),R=(e=>(e.CREATE="create",e.INITIALIZE="init",e.LOAD="load",e.READY="ready",e.GO_ONLINE="go_online",e.GO_OFFLINE="go_offline",e.RESET="go_offline",e.UNLOAD="unload",e.FAILED="failed",e.GO_ACTIVE="go_active",e.GO_INACTIVE="go_inactive",e.TIMEOUT="timeout",e))(R||{});const yi=m.createLogger({name:"kos-model-cache"});class tf{constructor(t=[]){l(this,"_modelsById",E.observable.map(new Map));l(this,"_toDelete",new Map);l(this,"_preloaded",[]);l(this,"_isPreloaded",!1);this.preloadKeys=t}get models(){return Array.from(this._modelsById.values()).map(t=>t).filter(t=>!this._toDelete.has(t.modelId))}getModelById(t){if(t&&!this._toDelete.has(t))return this._modelsById.get(t)}addModel(t){const s=this.getModelById(t.modelId)||t;return this._modelsById.set(s.modelId,s),s}removeModel(t){this._modelsById.delete(t),this._toDelete.delete(t)}hasModel(t){return!!t&&this._modelsById.has(t)&&!this._toDelete.has(t)}restoreFromDeleteCache(t){if(t&&this._toDelete.has(t)){const s=this._toDelete.get(t);this._toDelete.delete(t),this._modelsById.set(t,s)}}markForDeletion(t){this._modelsById.delete(t.modelId),this._toDelete.set(t.modelId,t)}preload(t){return this._isPreloaded?(yi.debug("Returning cached preloaded models"),this._preloaded):(this._preloaded=this.preloadKeys.map(s=>(yi.debug(`Preloading model: ${typeof s=="string"?s:s.modelType}`),t(s))).filter(s=>!!s),this._isPreloaded=!0,this._preloaded)}}const ee=Symbol("SubscriptionHandlers"),k=Symbol("DependencyModels"),os=Symbol("FutureService"),Be=Symbol("ChildModels"),ns=Symbol("ParentModel"),is=Symbol("LogConfig"),Vs=Symbol("ReferenceConfig"),Jo=Symbol("KosModelSymbol"),Ze=Symbol("ModelEffects"),bt=Symbol("CompanionParentModel"),en=Symbol("FutureContainerSetup"),tn=Symbol("MultipleFutureContainerSetup"),as=Symbol("FutureAliases"),sn=Symbol("TroubleAwareSetup"),rn=Symbol("LoggerSetup"),on=Symbol("ContainerAwareSetup"),Ie=(e,t)=>{e[Be]=e[Be]||{},e[Be][t]=!0},st=e=>`{PROP_${String(e)}}`,sf=e=>`{PROP_${String(e)}}`,rf=st("kosParentId"),Ar=e=>t=>{t[ns]=t[ns]||{};const s=(e==null?void 0:e.parentId)||rf;t[ns]={parentId:s}};function of(e){return t=>{const s=(e==null?void 0:e.mode)||"decorator",r=(e==null?void 0:e.parentProperty)||"companionParent",o=(e==null?void 0:e.excludeProperties)||[];return Ar()(t),t.prototype[bt]={mode:s,parentProperty:r,excludeProperties:o},t}}function rc(e){return t=>{const s=e!=null&&e.legacy?"_models":(e==null?void 0:e.containerProperty)||"container",r=(e==null?void 0:e.includeMethods)!==!1,o=(e==null?void 0:e.includeGetters)!==!1,n=(e==null?void 0:e.modelsProperty)||"models",i=(e==null?void 0:e.containerOptions)||{};return t.prototype[on]={containerProperty:s,includeMethods:r,includeGetters:o,modelsProperty:n,containerOptions:i,legacy:(e==null?void 0:e.legacy)||!1},t}}function nf(e,t,s){const r=s.value;s.value=function(...o){const n=V.getContext(this.id);return o.push(n),r.apply(this,o)}}function af(e){return t=>{const s=(e==null?void 0:e.mode)||"full",r=(e==null?void 0:e.handlerProperty)||"futureHandler";return t.prototype[en]={mode:s,handlerProperty:r},t}}function cf(e){return t=>{const s=(e==null?void 0:e.mode)||"full",r=(e==null?void 0:e.handlerProperty)||"futureHandler";return t.prototype[tn]={mode:s,handlerProperty:r},t}}var H=(e=>(e.INIT="init",e.LOAD="load",e.READY="ready",e.ACTIVATE="activate",e.ONLINE="online",e))(H||{});const lf=Object.freeze(Object.defineProperty({__proto__:null,DependencyLifecycle:H},Symbol.toStringTag,{value:"Module"})),xe=Symbol("HttpRouteHandlers"),bi="__httpBrowserRouter";function Pr(e){return function(s){return function(r,o,n){r[xe]=r[xe]||[];const i={method:e,path:s,handler:o};return r[xe].push(i),r[k]=r[k]||{},r[k][bi]||(r[k][bi]={modelType:"browser-router-model",lifecycle:H.INIT}),n}}}const oc=Pr("GET"),Cs=Pr("POST"),uf=Pr("PUT"),nc=Pr("DELETE"),df=nc;function er(e){return!!(e!=null&&e[xe])&&e[xe].length>0}function ic(e){return(e==null?void 0:e[xe])||[]}const hf=({group:e}={group:""})=>t=>{t[is]=t[is]||{},t[is]={group:e}};class ac{static create({modelId:t,modelTypeName:s,component:r}){const o=[r??"kos",s,t].filter(Boolean).join(".");return m.createLogger({name:o})}}function cc(e){return t=>{const s=(e==null?void 0:e.loggerProperty)||"logger",r=e==null?void 0:e.loggerContext;t.prototype[rn]={loggerProperty:s,loggerContext:r};const o=()=>{var i;return(i=t.prototype[Jo])==null?void 0:i.type};let n;return Object.defineProperty(t.prototype,s,{get(){if(!n){const i=o();n=ac.create({modelTypeName:r||i,component:"kos-model"})}return n},enumerable:!1,configurable:!1}),t}}function lc(e){return(t,s,r)=>{t[Ze]=t[Ze]||{},t[Ze][s]={dependencies:e==null?void 0:e.dependencies,value:r.value},r.value=function(){throw new Error(`Method ${s} cannot be called directly.`)}}}const ff=e=>(t,s)=>{t[Vs]=t[Vs]||{},t[Vs][s]=e};function pf(e){return t=>{const s=(e==null?void 0:e.pathProperty)||"path";return t.prototype[sn]={pathProperty:s},t.prototype[k]=t.prototype[k]||{},t.prototype[k].troubleContainer={modelType:"trouble-container-model",id:"trouble-container-model",options:{},lazy:!1},t}}const Pt=({modelType:e,id:t,options:s,lifecycle:r})=>(o,n)=>{o[k]=o[k]||{},o[k][n]={modelType:e,id:t,options:s,lifecycle:r||H.INIT}};class uc{constructor(t,s){l(this,"futures");l(this,"defaultContext");l(this,"context");l(this,"disposers",new Map);l(this,"container");this.futures=mn.map(new Map),this.context="",this.defaultContext=s||"",this.container=t,E.makeAutoObservable(this)}get allFutures(){return Array.from(this.futures.values())}get future(){return this.futures.get(this.defaultContext)}addFuture(t,s){this.futures.set(s||t.id,t),this.context=s||t.id;const r=Y(()=>{var o,n;(t.endState||t.progress)&&((n=(o=this.container)==null?void 0:o.onFutureUpdate)==null||n.call(o,t))});this.disposers.set(s||t.id,r)}removeFuture(t){var s;this.futures.delete(t||this.context),(s=this.disposers.get(t||this.context))==null||s(),this.disposers.delete(t||this.context)}getFuture(t){return this.futures.get(t||this.context)}get futureMap(){return this.futures}}class Rr{constructor(t){l(this,"disposer");l(this,"_future");l(this,"container");l(this,"onFutureUpdate");this._future=void 0,this.container=t,E.makeAutoObservable(this)}removeFuture(){var t;this._future=void 0,(t=this.disposer)==null||t.call(this),this.disposer=void 0}get future(){return this._future}getFuture(){return this._future}addFuture(t){this._future=t;const s=Y(()=>{var r,o;(t.endState||t.progress)&&((o=(r=this.container)==null?void 0:r.onFutureUpdate)==null||o.call(r,t))});this.disposer=s}get allFutures(){return this._future?[this._future]:[]}get timeRemaining(){var t;return((t=this._future)==null?void 0:t.timeRemaining)||""}get status(){var t;return((t=this._future)==null?void 0:t.status)||"NOT_RESOLVED"}get progress(){var t;return((t=this._future)==null?void 0:t.progress)||-1}async cancel(){if(this._future)try{await this._future.cancelFuture()}catch(t){throw m.error(t),t}}}const dc=(e,t)=>{const s=t.type;return e[s]||(e[s]=[]),e[s].push(t),e},hc=Symbol("KosObservableData");class fc{constructor(){l(this,"map");l(this,"_revision",1);l(this,"atomMap",new Map);l(this,"proxyHandler",{get:(t,s)=>{var r;return s==="_revision"||t[s]!==void 0?t[s]:this.atomMap.has(s)&&(r=this.atomMap.get(s))!=null&&r.reportObserved()?this.getValue(s):this.getValue(s)},set:(t,s,r)=>{var o;return this.map.has(s),this.setValue(s,r),this.atomMap.has(s)||this.atomMap.set(s,E.createAtom(s.toString())),(o=this.atomMap.get(s))==null||o.reportChanged(),!0},ownKeys:()=>[...Array.from(this.map.keys()),"_revision"]});this.map=E.observable.map(new Map),E.makeObservable(this,{_revision:E.observable})}setValue(t,s){const r=this.map.has(t);this.map.set(t,s),r||E.action(()=>{this._revision++})()}getValue(t){return this.map.get(t)}has(t){return this.map.has(t)}get entries(){return Array.from(this.map.entries())}get keys(){return this._revision,Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}setValues(t){t&&Object.keys(t).forEach(s=>{this.setValue(s,t[s])})}get proxy(){return new Proxy(this,this.proxyHandler)}}fc.prototype[hc]=!0;function gf(e,t){return new Proxy(e,{construct:(s,r)=>{const o=new e(...r);return o.setValues(t),o.proxy}})}const Te=e=>{const t=gf(fc,e);return new t(e)};function mf(e,t){return e.length!==t.length?!1:e.every(s=>t.includes(s))}class nn{constructor({container:t,key:s}){l(this,"_container");l(this,"_map");l(this,"_key");l(this,"data");this._container=t,this._map=E.observable.map(new Map),this._key=s,this.data=Te(),this.generateIndex(),E.autorun(()=>{this._container.revision&&this.generateIndex()}),E.makeAutoObservable(this)}refresh(){this.generateIndex()}addItemToIndex(t,s,r=this._map,o=this.data){const n=r.get(t)||new Set;n.add(s),r.set(t,n),o[t]=Array.from(n)}resolveIndex(t,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(mf(n,i))m.debug(`KosContainerIndex - Index ${o} is the same`);else{this.data[o]=n;const a=t.get(o)||new Set;this._map.set(o,a)}})}generateIndex(){E.runInAction(async()=>{const t=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,t,s)}):typeof o=="string"||typeof o=="number"?this.addItemToIndex(String(o),r,t,s):typeof o=="boolean"&&this.addItemToIndex(String(o),r,t,s)}this.resolveIndex(t,s)})}get keys(){return Array.from(this._map.keys())}get index(){return this._map}getByKey(t){const s=this._map.get(t);return s?Array.from(s):[]}}function yf(e,t,s=[]){const r=Object.getOwnPropertyDescriptors(e);return Object.keys(r).filter(i=>E.isComputedProp(e,i)).filter(i=>s.includes(i)).map(i=>E.reaction(()=>e[i],(a,c)=>{t({name:i,newValue:a,oldValue:c})}))}const Kt=m.createLogger({name:"kos-container-model"});class Se{constructor(t){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=E.observable.map(new Map),this._sortKey=t==null?void 0:t.sortKey,this._revision=1;const s=t!=null&&t.extensionId?S.indexExtension.loadIndexExtensions(t.extensionId):{},r=(t==null?void 0:t.indexMap)||{};this._optionsMap={...r,...s};const o=t!=null&&t.indexMap?Object.keys(t.indexMap).reduce((n,i)=>(n[i]=void 0,n),{}):{};this._index=E.observable.map(o),this.idx=Te(),this._parentId=t==null?void 0:t.parentId,E.makeAutoObservable(this),this.init()}init(){Object.keys(this._optionsMap).forEach(t=>{const s=this._optionsMap[t],r=new nn({container:this,key:s});this._index.set(t,r),this.idx[t]=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((t,s)=>{var r;return t[s]=(r=this.index.get(s))==null?void 0:r.keys,t},{})}sortFn(t,s){const r=this._sortKey;return r?String(t[r]).localeCompare(String(s[r]),void 0,{numeric:!0}):0}get data(){const t=Array.from(this._data.values());return this._sortKey&&t.sort(this.sortFn.bind(this)),t}increment(){E.runInAction(()=>{this._revision=this._revision+1})}addAll(t){E.runInAction(()=>{t.forEach(s=>this.addModel(s,!0))}),this.increment()}removeAll(t){E.runInAction(()=>{t.forEach(s=>this.removeModel(s,!0)),this.increment()})}addModel(t,s){this._data.set(t.id||"",t),t.id&&this._parentId&&V.setParentContext(t.id,this._parentId),s||this.increment();const r=this._disposerMap.get(t.id);r&&(r(),this._disposerMap.delete(t.id));const o=Object.entries(this._optionsMap||{}),n=Object.values(this._optionsMap||{}),i=new Map(o.map(([d,h])=>[h,d])),a=d=>{var f,p;n.includes(d.name)&&((f=this.index.get(i.get(d.name)))==null||f.refresh());const h=o.filter(([,b])=>typeof b=="function");for(const[b]of h)(p=this.index.get(b))==null||p.refresh()},c=yf(t,a,n.filter(d=>typeof d=="string")),u=E.observe(t,a);this._disposerMap.set(t.id||"",()=>[u,...c].forEach(d=>d()))}removeModel(t,s){this._data.delete(t),s||this.increment();const r=this._disposerMap.get(t);r&&(r(),this._disposerMap.delete(t))}updateModel(t){this._data.set(t.id||"",t),this.increment()}getModel(t){return this._data.get(t)}getIndexKeys(t){return this.index.has(t)?this.index.get(t).keys??[]:(Kt.info(`index ${t} not found in ${Array.from(this.index.keys())}`),[])}getIndexByKey(t,s){if(this.index.has(t)){const r=this.index.get(t);return r.index.has(s)?r.getByKey(s):(Kt.info(`key ${s} not found in ${t} index: ${Array.from(r.index.keys())}`),[])}else return Kt.info(`index ${t} not found in ${Array.from(this.index.keys())}`),[]}async clear(){this._data.forEach(t=>{const s=t.id;Xe(t).then(()=>{Kt.debug(`${s} destroyed, removing from map`),this.removeModel(s,!0)}).catch(r=>Kt.error(r))}),this.increment()}filter(t,s){return this.data.filter(t,s)}sort(t){return this.data.sort(t)}map(t,s){return this.data.map(t,s)}forEach(t,s){this.data.forEach(t,s)}toJSON(){return{indexes:this.indexKeys,data:this.data.map(s=>({id:s.id,type:s.constructor.name}))}}}const ue=async e=>{if(e.id){const t=I.getInstance().modelManager.getModelById(e.id);if(!t)throw new Error(`Model with ID ${e.id} not found`);await(t==null?void 0:t.whenReady())}else throw new Error("Data model must have a valid ID");return e},Xe=async e=>{await I.getInstance().whenReady(),await I.getInstance().modelManager.initiateDestroyModel(e)},bf=async e=>{if(await I.getInstance().whenReady(),!e.id)throw new Error("Model ID is required");const t=I.getInstance().modelManager.getModelById(e.id);t&&await t.fsm.transitionTo(R.UNLOAD,v.UNLOADED)},vf=async e=>{await I.getInstance().whenReady(),await I.getInstance().modelManager.reloadModel(e),m.debug(`reload model initiated for model ${e.id}, model ready: ${tr(e)} - ${Date.now()} `),await ue(e),m.debug(`reload model complete for model ${e.id}, model ready: ${tr(e)} - ${Date.now()} `)},wf=async e=>{if(await I.getInstance().whenReady(),!e)throw new Error("Model ID is required");const t=I.getInstance().modelManager.getModelById(e);return t==null?void 0:t.modelTypeName},pc=async e=>{if(await I.getInstance().whenReady(),!e)throw new Error("Model ID is required");const t=I.getInstance().modelManager.getModelById(e);return{model:t==null?void 0:t.modelData,type:t==null?void 0:t.modelTypeName}},_e=e=>{if(!e)throw new Error("Model ID is required");const t=I.getInstance().modelManager.getModelById(e);return{model:t==null?void 0:t.modelData,type:t==null?void 0:t.modelTypeName}},gc=(e,t)=>{if(!e)throw new Error("Model type is required");return I.getInstance().modelManager.getModelsByType(e).filter(o=>Object.keys(t).every(n=>o[n]===t[n]))},Ef=(e,t)=>gc(e,t)[0],Mf=(e,t)=>{if(!e.id)throw new Error("Model ID is required");const s=I.getInstance().modelManager.getModelById(e.id);if(!s)throw new Error("Model not found");const r=s.companionModels.get(t);return r==null?void 0:r.modelData},mc=e=>{if(!e.id)throw new Error("Model ID is required");const t=I.getInstance().modelManager.getModelById(e.id);if(!t)throw new Error("Model not found");return Array.from(t.companionModels.all()).map(r=>r.modelData)},Tf=e=>{if(!e)throw new Error("Model ID is required");const t=I.getInstance().modelManager.getModelById(e);if(!t)throw new Error("Model not found");return t.companionModels.data},vo=(e,t)=>{const s=I.getInstance().modelManager.getModelById(e);if(!s){m.info(`Model not found for id ${e}`);return}return Array.from(s.companionModels.all()).find(o=>t(o.modelData))},Ee=e=>t=>Object.getPrototypeOf(t).modelTypeId===e,tr=e=>{const t=I.getInstance().modelManager.getModelById(e.id);if(!t)throw new Error("Model not found");return t.isReady()},_f=m.createLogger({name:"kos-model-factory"}),cs={byModelType:e=>I.getInstance().modelManager.getModelFactory(e),getModelInstance:(e,t,s)=>{const r=cs.byModelType(t);if(!r)throw _f.error(`No registered factory found for model type ${t}. Please register a factory for this model type. `),Error(`No factory found for model type ${t}`);return r.build(e,s)}},ie={Factory:{create:e=>t=>(s,r)=>(r&&V.setParentContext(t,r),cs.getModelInstance(t,e,s))},Singleton:{create:e=>(t,s)=>(s&&V.setParentContext(e,s),cs.getModelInstance(e,e,t))},Model:{instance:e=>t=>cs.getModelInstance(t,e)}};window.KosRegistry=window.KosRegistry||{coreModels:new Map,preloadModels:[],companionModels:new Map,models:new Map};const vi=window.KosRegistry.coreModels,so=window.KosRegistry.preloadModels,ro=window.KosRegistry.companionModels,Fs=window.KosRegistry.models,x={model:{registerLegacyModel:e=>(t,s)=>(vi.set(t,s),{preload:x.model.preloadModel(e),model:x.model.register(e),companion:x.companion.register(e),legacy:x.model.registerLegacyModel(e),root:e}),preloadModel:e=>t=>(so.includes(t)||so.push(t),{preload:x.model.preloadModel(e),model:x.model.register(e),companion:x.companion.register(e),legacy:x.model.registerLegacyModel(e),root:e}),register:e=>(t,s)=>{const r=oo(t)?t.registration():t;return Fs.set(r.type,r),oo(t)&&t.relatedModels.forEach(o=>Fs.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],oo(t)&&t.relatedModels.forEach(o=>I.getInstance().modelManager.registry.models[o.type]=o.registration().registration))),s&&x.model.preloadModel(e)(r.type),{preload:x.model.preloadModel(e),model:x.model.register(e),companion:x.companion.register(e),legacy:x.model.registerLegacyModel(e),root:e}},get:e=>Fs.get(e),getAll:()=>Array.from(Fs.entries()),getPreloadModels:()=>so,getLegacyModels:()=>Array.from(vi.entries()).reduce((e,[t,s])=>(e[t]=s,e),{})},companion:{register:e=>(t,s)=>{const r=ro.get(t)||[];return r.push(s),ro.set(t,r),{preload:x.model.preloadModel(e),model:x.model.register(e),companion:x.companion.register(e),legacy:x.model.registerLegacyModel(e),root:e}},getAll:()=>Array.from(ro.entries())}},yc=x.model.registerLegacyModel,bc=x.model.register,Of=x.companion.register,If=x.model.preloadModel,an=e=>typeof e.updateModel=="function",oo=e=>e.registration!==void 0&&typeof e.registration=="function";class vc{constructor(t){l(this,"singleton");l(this,"type");l(this,"loader");l(this,"class");l(this,"guard");l(this,"factory");l(this,"relatedModels",[]);this.singleton=t.singleton,this.guard=Ee(t.type),this.type=t.type,this.loader=`kos.extension.model.loader.${t.type}`,this.factory=t.factory,this.class=t.class}addRelatedModel(t){this.relatedModels.push(t)}registerRelatedModels(){this.relatedModels.forEach(t=>t.register())}register(){x.model.register({})(this.registration()),this.registerRelatedModels()}}class me extends vc{constructor(t){super({...t,singleton:!1,factory:ie.Factory.create(t.type)})}instance(t){const s=this.factory(t);return{get:()=>{const r=_e(t);if(!r)throw new Error("Model not found with id "+t);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(an(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 Me extends vc{constructor(t){super({...t,singleton:!0,factory:ie.Singleton.create(t.type)})}instance(){const t=this.factory;return{get:()=>{const r=_e(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=t(r);if(this.guard(o)){if(an(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=t(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 no=m.createLogger({name:"resolve-parameters"}),vt=({value:e,modelId:t,modelData:s})=>{let r=e;if(Array.isArray(r))return[...e];if(typeof r!="string"&&typeof r!="object")return r;if(typeof r=="object")r=Object.keys(r).reduce((o,n)=>(o[n]=vt({value:r[n],modelId:t,modelData:s}),o),{});else if(typeof r=="string"){const o=new RegExp("{PROP_(.+?)}","g");let n=r!=null&&r.includes(Xs)?r.replace(Xs,t):r;if(s){let i=!1;const a=/^{PROP_.+?}$/.test(n);if(n=n.replace(o,(c,u)=>{if(Object.getOwnPropertyNames(s).includes(u)||Object.getOwnPropertyNames(Object.getPrototypeOf(s)).includes(u)){const h=s[u];return h?(no.debug(`Resolved ${c} to ${h}`),h):(no[a?"debug":"warn"](`Property ${u} is falsy${a?"":" in composite string"}, marking for undefined return`),i=!0,c)}return no[a?"debug":"warn"](`Property ${u} not found in modelData${a?"":" for composite string"}`),c}),i)return}return n}else return r;return r},wo=m.createLogger({group:"decorators",name:"kos-model"});function Sf(e,t,s){var n;const r=(n=e[ns])==null?void 0:n.parentId;if(!r)return;const o=vt({value:r,modelData:s,modelId:t});o&&typeof o=="string"&&V.setParentContext(t,o)}function $f(e){const t=e[os];t&&Object.entries(t).forEach(([s,{handler:r}])=>{e[s]=r})}function Cf(e,t){const s=e[k]||{};Object.entries(s).forEach(([r,o])=>{const n=vt({value:o.id||o.modelType,modelData:e,modelId:t}),i=Object.entries((o==null?void 0:o.options)||{}).reduce((a,[c,u])=>(a[c]=vt({value:u,modelData:e,modelId:t}),a),{});if(typeof n=="string"){if(!o.lazy){const a=I.getInstance().modelManager.createModelInstance(o.modelType,n,i);e[r]=a.data}I.getInstance().modelManager.addDependency(t,n)}})}function Df(e){const t=e[en];if(!t)return;const{mode:s,handlerProperty:r}=t,o=new Rr(e);e[r]=o,s==="full"&&(Object.defineProperty(e,"future",{get(){return o.future},enumerable:!0,configurable:!0}),Object.defineProperty(e,"progress",{get(){var n;return((n=o.future)==null?void 0:n.progress)||0},enumerable:!0,configurable:!0}),Object.defineProperty(e,"status",{get(){var n;return((n=o.future)==null?void 0:n.status)||"IDLE"},enumerable:!0,configurable:!0}),Object.defineProperty(e,"isRunning",{get(){return o.future?!o.future.endState:!1},enumerable:!0,configurable:!0}),Object.defineProperty(e,"isCancelled",{get(){var n;return((n=o.future)==null?void 0:n.status)==="CANCELLED"||!1},enumerable:!0,configurable:!0}),e.cancelFuture=async()=>{o.future&&await o.future.cancelFuture()})}function xf(e){const t=e[tn];if(!t)return;const{mode:s,handlerProperty:r}=t,o=new uc(e);e[r]=o,Object.defineProperty(e,"future",{get(){return o.future},enumerable:!0,configurable:!0});const n=e[as];n instanceof Map&&n.forEach(i=>{const a=`${i}Future`;Object.defineProperty(e,a,{get(){return o.futureMap.get(i)},enumerable:!0,configurable:!0}),s==="full"&&(Object.defineProperty(e,`${i}Progress`,{get(){const c=o.futureMap.get(i);return(c==null?void 0:c.progress)||0},enumerable:!0,configurable:!0}),Object.defineProperty(e,`${i}Status`,{get(){const c=o.futureMap.get(i);return(c==null?void 0:c.status)||"IDLE"},enumerable:!0,configurable:!0}),Object.defineProperty(e,`${i}IsRunning`,{get(){const c=o.futureMap.get(i);return c?!c.endState:!1},enumerable:!0,configurable:!0}),Object.defineProperty(e,`${i}IsCancelled`,{get(){const c=o.futureMap.get(i);return(c==null?void 0:c.status)==="CANCELLED"||!1},enumerable:!0,configurable:!0}),e[`cancel${i.charAt(0).toUpperCase()}${i.slice(1)}`]=async()=>{const c=o.futureMap.get(i);c&&await c.cancelFuture()})}),s==="full"&&(Object.defineProperty(e,"progress",{get(){var i;return((i=o.future)==null?void 0:i.progress)||0},enumerable:!0,configurable:!0}),Object.defineProperty(e,"status",{get(){var i;return((i=o.future)==null?void 0:i.status)||"IDLE"},enumerable:!0,configurable:!0}),Object.defineProperty(e,"isRunning",{get(){return o.future?!o.future.endState:!1},enumerable:!0,configurable:!0}),Object.defineProperty(e,"isCancelled",{get(){var i;return((i=o.future)==null?void 0:i.status)==="CANCELLED"||!1},enumerable:!0,configurable:!0}),e.cancelFuture=async()=>{o.future&&await o.future.cancelFuture()})}function Af(e){const t=e[sn];if(!t)return;const{pathProperty:s}=t;Object.defineProperty(e,"troubles",{get(){const r=this[s];if(r==null){const o=`@kosTroubleAware: Path property '${s}' is undefined on model ${this.id||"unknown"}. Returning empty troubles array.`;return this.logger&&typeof this.logger.warn=="function"?this.logger.warn(o):console.warn(o),[]}return this.troubleContainer.troubles.getIndexByKey("byIface",r).sort((o,n)=>n.rank-o.rank)},enumerable:!0,configurable:!0}),Object.defineProperty(e,"troubleStatus",{get(){return""},enumerable:!0,configurable:!0}),Object.defineProperty(e,"troublesByType",{get(){return this.troubles.reduce(dc,{})},enumerable:!0,configurable:!0})}function Pf(e,t){const s=e[on];if(!s)return;const{containerProperty:r,includeMethods:o,includeGetters:n,modelsProperty:i,containerOptions:a,legacy:c}=s,u={...a,parentId:a.parentId||t},d=new Se(u);e[r]=d,e[Be]||(e[Be]={}),e[Be][r]=d,o&&(e.getModel=h=>d.getModel(h),e.addModel=h=>{d.addModel(h)},e.removeModel=h=>{d.removeModel(h)}),n&&(Object.defineProperty(e,i,{get(){return d},enumerable:!0,configurable:!0}),Object.defineProperty(e,"data",{get(){return d.data},enumerable:!0,configurable:!0}))}function Rf(e,t){const s=e.constructor.prototype[bt];if(!s)return;const{mode:r,parentProperty:o,excludeProperties:n}=s,i=t[o];if(!i){wo.warn(`Companion decorator configured but no parent model found at '${o}'`);return}if(e.getCompanionParent=()=>i,r==="composition")return;const a=["init","load","unload","ready","dispose","destroy","activate"],c=["getDependencies","getChildren","update","toJSON","forceUpdate","makeAutoObservable","runInAction","transaction","observe","unobserve","intercept","spy","trace","getCompanionParent"],u=p=>{const b=i.constructor.prototype[ee]||{};return Object.values(b).some(w=>{const M=w==null?void 0:w.handler;return M===i[p]||M===i.constructor.prototype[p]})},d=p=>p==="constructor"||p.startsWith("_")||p.startsWith("__")||a.includes(p)||c.includes(p)||n.includes(p)||u(p)||p in e,h=new Set;Object.getOwnPropertyNames(i).filter(p=>!d(p)).forEach(p=>h.add(p));let f=Object.getPrototypeOf(i);for(;f&&f!==Object.prototype;)Object.getOwnPropertyNames(f).filter(p=>!d(p)).forEach(p=>h.add(p)),f=Object.getPrototypeOf(f);for(const p of h)try{const b=i[p];typeof b=="function"?e[p]=(...w)=>b.apply(i,w):Object.defineProperty(e,p,{get:()=>i[p],set:w=>{i[p]=w},enumerable:!0,configurable:!0})}catch(b){wo.debug(`Skipping companion proxy for property ${p}:`,b)}}function kf(e){try{return E.makeAutoObservable(e)}catch(t){return wo.error("Failed to make observable:",t),e}}const Lf={construct(e,t){var c;const[s,r={}]=t,o=V.createContext(s);Sf(e,s,r);const i=!!e.prototype[rn]?null:m.createLogger({name:e.prototype.modelTypeId,group:((c=e[is])==null?void 0:c.group)??"kos-model"}),a=new e(s,r,{logger:i,kosContext:o});return $f(a),Df(a),xf(a),Af(a),Pf(a,s),Rf(a,r),Cf(a,s),kf(a)}};function A(e){return t=>{var n,i;const s=t,r=typeof e=="string"?{modelTypeId:e,autoRegister:!1}:{autoRegister:!1,...e};s.prototype.modelTypeId=r.modelTypeId,s.prototype[Jo]=!0,(n=s.prototype)[ee]??(n[ee]={}),(i=s.prototype)[k]??(i[k]={}),m.ifDebug(()=>{m.debug(`Registering model with id ${r.modelTypeId}`)});const o=new Proxy(s,Lf);if(r.singleton!==void 0){let a;r.singleton?a=new Me({class:o,type:r.modelTypeId}):a=new me({class:o,type:r.modelTypeId}),Object.defineProperty(o,"Registration",{value:a,writable:!1,enumerable:!0,configurable:!1}),r.autoRegister&&a.register()}return o}}const Ff=({topic:e,handler:t,websocket:s=!1,condition:r=()=>!0})=>o=>{o[ee]=o[ee]||{},Array.isArray(e)?e.forEach(n=>{o[ee][n]={websocket:s,handler:t,condition:r}}):o[ee][e]={websocket:s,handler:Fa(o,E.action(t),200),condition:r}};function wc(e,t,s){const r={};if(!e.endsWith("/*"))return r;const o=e.slice(0,-2);if(t.startsWith(o)){const n=t.slice(o.length+1),i=s||"path";r[i]=n}return r}function Ec(e){return e.endsWith("/*")}function U({topic:e,condition:t=(_,F)=>!0,transform:s=_=>_,websocket:r=!1,fos:o=!1,bridge:n=!1,skipParse:i=!1,lifecycle:a,destinationAddress:c,debounce:u,throttle:d,buffer:h,filter:f,once:p,replay:b,wildcardName:w,flow:M}){return(_,F,Q)=>{_[ee]=_[ee]||{};let O=Q.value;const W=typeof u=="number"?u:u==null?void 0:u.delay,B=typeof d=="number"?d:d==null?void 0:d.interval;W&&W>0?O=Nf(O,u):B&&B>0?O=Uf(O,d):h?O=jf(O,h):p&&(O=Bf(O));let J=t;if(f){const $e=t;J=(hi,fi,Zr)=>f(Zr)?$e(hi,fi,Zr):!1}const Ue={websocket:r,fos:o,bridge:n,handler:O,condition:J,transform:s,lifecycle:a,skipParse:i,destinationAddress:c,wildcardName:w,flow:M};Array.isArray(e)?e.forEach($e=>{_[ee][$e]=Ue}):_[ee][e]=Ue,b&&Kf(e,b.bufferSize)}}function Nf(e,t){const s=typeof t=="number"?t:t.delay,r=typeof t=="object"?t.discardIntermediate:!1;let o=null,n=[];return function(i){r?(o&&clearTimeout(o),o=setTimeout(()=>{e.call(this,i),o=null},s)):(n.push(i),o&&clearTimeout(o),o=setTimeout(()=>{const a=[...n];n=[],e.call(this,a),o=null},s))}}function Uf(e,t){const s=typeof t=="number"?t:t.interval,r=typeof t=="object"?t.discardIntermediate:!1;let o=0,n=null,i=[],a=!1;const c=function(){if(i.length>0){const u=[...i];i=[],e.call(this,u)}};return function(u){const d=Date.now(),h=d-o;r?h>=s?(o=d,e.call(this,u)):n||(n=setTimeout(()=>{o=Date.now(),e.call(this,u),n=null},s-h)):(i.push(u),h>=s?(o=d,c.call(this)):a||(a=!0,n=setTimeout(()=>{o=Date.now(),c.call(this),n=null,a=!1},s-h)))}}function jf(e,t){const s=[];let r=null;const o=t.maxSize||1e3,n=i=>{s.length>0&&(e.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},t.time))}}function Bf(e){let t=!1;return function(s){t||(t=!0,e.call(this,s))}}function Kf(e,t){(Array.isArray(e)?e:[e]).forEach(r=>{Vo(r,t)})}function Mc(e,t){return`${Ho}${e}${t?`/${t}`:`/${e}`}`}function Tc(e){return`${Ho}${e}`}function io(e){const t=[];return new Promise((s,r)=>{for(const{condition:o,onMatch:n}of e){const i=E.when(o,()=>{t.forEach(a=>a());try{n==null||n(),s()}catch(a){r(a)}});t.push(i)}})}const _c=5e3;class Hf extends Error{constructor(s,r){super(s);l(this,"model");this.model=r}}const Oc=(e,t,s)=>{let r;return{promise:new Promise((i,a)=>{r=setTimeout(()=>{m.error(`Model ${t.modelId} - ${t.modelTypeName} - ${s} timed out after ${e}ms`),a(new Hf(`${t.modelId} - ${t.modelTypeName} - ${s}`,t))},e)}),cancel:()=>{r&&clearTimeout(r)}}},Ic=e=>e.fsm.transitionTo(R.GO_ACTIVE,v.ACTIVE),Sc=e=>e.whenReady(),$c=e=>e.fsm.transitionTo(R.LOAD,v.LOADED),zf=e=>e.fsm.transitionTo(R.UNLOAD,v.UNLOADED),Cc=e=>e.fsm.transitionTo(R.INITIALIZE,v.INITIALIZED);var cn=(e=>(e.ACTIVE="active",e.READY="ready",e.LOAD="load",e.UNLOAD="unload",e.INIT="init",e))(cn||{});const Ys={active:Ic,ready:Sc,load:$c,init:Cc},Dc=(e,t)=>{const s=t.id||t.modelType,r=vt({value:s,modelData:e.modelData,modelId:e.modelId});m.debug(`activating dependent model ${t.modelType} with id ${r}`);const o=Object.keys((t==null?void 0:t.options)||{}).reduce((i,a)=>{const c=t.options[a];return i[a]=vt({value:c,modelData:e.modelData,modelId:e.modelId}),i},{});return{dependentModel:I.getInstance().modelManager.createModelInstance(t.modelType,r,o),dataModelId:r}},xc=(e,t=H.READY)=>{var o;const s=((o=e.modelData)==null?void 0:o[k])||{};return Object.keys(s).length===0?(m.debug(`${e.modelId} has no dependencies. Returning`),[]):Object.keys(s).filter(n=>s[n].lifecycle===t).map(n=>{const i=s[n],{dependentModel:a,dataModelId:c}=Dc(e,i);e.modelData[n]=a.data,m.debug(`waiting for dependent model ${i.modelType} with id ${c} - waiting for WHENREADY`);const u=async(f,p,b)=>{var w;await((w=f.whenReady)==null?void 0:w.call(f)),m.debug(`dependent model ${p} with id ${b} - READY`)},{promise:d,cancel:h}=Oc(_c,e,e.status);return Promise.race([u(a.model,i.modelType,c).then(()=>{h()}).catch(f=>{console.error(`Error waiting for dependent model ${i.modelType} with id ${c}:`,f),h()}),d])}).filter(n=>!!n)},Ac=async(e,t,s,r)=>{if(m.debug(`Execute lifecycle with ${t.length} models`),t.length===0){m.debug(`${e.modelId} has no children. Returning`);return}if(!s){m.error(`${e.modelId} is not transitioning with a valid target ${s}`);return}const o=t.map(a=>{let c;return Ys[s]&&a?c=Ys[s](a):(a||m.error("model is undefined. This shouldn't happen"),Ys[s]||m.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:(m.error(`No model found ${a.modelId}`),!1):(m.error(`No promise found ${a.modelId}`),!1)),i=(await Promise.allSettled(o.map(a=>{var d;const{promise:c,cancel:u}=Oc(_c,a.model,a.status);return Promise.race([(d=a.promise)==null?void 0:d.then(()=>{u()}).catch(h=>{m.error(`Model ${a.modelId} - ${a.type} failed to transition to ${s}: ${h.message}`),u()}),c])}))).filter(a=>a.status==="rejected");i.length>0&&m.error(`Model ${e.modelId} had ${i.length} failed child models on ${r}`)},Pc=async(e,t,s)=>{await Ac(e,e.getChildren().filter(r=>!!r),t,s)},zt=async(e,t)=>{const r=(await Promise.allSettled(xc(e,t))).filter(o=>o.status==="rejected");r.length&&(m.error(`There were ${r.length} failed dependent models on ${t}`),m.error(r))},Gf=e=>typeof e.toJSON=="function",ls=e=>e[k]!==void 0,ln=e=>e.revision!==void 0&&e.index!==void 0,Rc=e=>{if(e){if(ls(e))return e;if(ln(e))return e.data;if(e instanceof Map||e instanceof E.ObservableMap||e instanceof Set)return Array.from(e.values()).filter(ls);if(Array.isArray(e))return e.filter(ls)}};function Vf(e){const t=`KosModel(${e.modelTypeName}:${e.modelId})`;try{Object.defineProperty(e,Symbol.toStringTag,{value:t,configurable:!0})}catch{e.toString=()=>t}try{Object.defineProperty(e.constructor,"name",{value:`KosModel_${e.modelTypeName}`,configurable:!0})}catch{e.constructor.name=`KosModel_${e.modelTypeName}`}const s=["fsm","effectManager","subscriptionManager","onlineLifecycleManager","companionManager","childResolver","_offlineQueue"];for(const r of s)r in e&&Object.defineProperty(e,r,{enumerable:!1});Object.defineProperty(e,"debugState",{enumerable:!1,configurable:!0,get(){var r,o,n;return{id:e.modelId,type:e.modelTypeName,initialized:e.initialized,loaded:e.loaded,status:e.status,onlineStatus:e.onlineStatus,activeStatus:e.activeStatus,companions:(o=(r=e.companionManager)==null?void 0:r.all())==null?void 0:o.map(i=>i.modelTypeName),children:(n=e.getChildren)==null?void 0:n.call(e).map(i=>i.modelId),effects:!!e.effectManager,subs:!!e.subscriptionManager}}}),Yf(e.modelData,e.modelTypeName,e.modelId,e)}function Yf(e,t,s,r){Object.defineProperty(e,Symbol.toStringTag,{value:`KosModelData(${t}:${s})`,configurable:!0});try{Object.defineProperty(e.constructor,"name",{value:`${t}ModelData`,configurable:!0})}catch{e.constructor.name=`${t}ModelData`}Object.defineProperty(e,"debugState",{enumerable:!1,configurable:!0,get(){var a,c,u;const o=((a=r.getChildren)==null?void 0:a.call(r))||[],n=((c=r.companionManager)==null?void 0:c.all())||[],i=r.modelData[k]||{};return{id:s,type:t,companions:{count:n.length,data:n.map(d=>({type:d.modelTypeName,id:d.modelId}))},dependencies:{count:Object.keys(i).length,data:Object.values(i).map(d=>({id:d.id||d.modelType,type:d.modelType,options:d.options,lifecycle:d.lifecycle}))},children:{count:o.length,data:o.map(d=>({id:d.modelId,type:d.modelTypeName}))},data:((u=e.toJSON)==null?void 0:u.call(e))||{},subs:!!r.subscriptionManager}}}),Object.defineProperty(e,"toJSON",{configurable:!0,enumerable:!1,writable:!0,value:()=>{const o={};for(const n of Object.keys(e))if(!(n.startsWith("_")||typeof e[n]=="function"))try{const i=e[n];ls(i)?o[`[KOS Model] ${n}`]=typeof i.toJSON=="function"?i.toJSON():{id:i.id,type:i.constructor.name}:ln(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 qf{constructor(t){this.model=t}resolve(){const t=new Set([...this.getResolvedDecoratedChildren(),...this.getAdditionalChildren(),...this.model.companionModels.all()]),s=Array.from(t).map(r=>this.model.modelManager.getModelById(r.id||"")).filter(r=>r&&r.status!==v.FAILED).filter(r=>!!r);return s.forEach(r=>{try{V.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 t=((s=this.model.modelData)==null?void 0:s[Be])||{};return Object.keys(t).map(r=>Rc(this.model.modelData[r])).filter(r=>!!r).flat()}getAdditionalChildren(){var t,s;return((s=(t=this.model.modelData)==null?void 0:t.getChildren)==null?void 0:s.call(t))||[]}}class Wf{constructor(t){l(this,"companions",new E.ObservableMap);this.hostModel=t}add(t){this.companions.set(t.modelTypeName,t)}clear(){this.companions.clear()}get(t){return this.companions.get(t)}all(){return[...this.companions.values()]}get data(){return this.companions}}class Qf{constructor(t,s,r,o){l(this,"disposers",[]);this.modelTypeName=t,this.modelId=s,this.modelData=r,this.log=o}setup(){var s;const t=((s=this.modelData)==null?void 0:s[Ze])||{};for(const r of Object.keys(t)){const{value:o,dependencies:n,options:i}=t[r],a=o.bind(this.modelData),c=()=>{this.log.info(`Running effect ${r} for ${this.modelTypeName} (${this.modelId})`),E.runInAction(()=>a())},u=n?E.reaction(()=>n(this.modelData),c,{fireImmediately:!!(i!=null&&i.fireImmediately)}):E.autorun(c);this.disposers.push(u)}}disposeAll(){for(const t of this.disposers)try{t()}catch(s){this.log.info(`Failed to dispose effect for ${this.modelId}`,s)}this.disposers=[]}}const Zf=m.createLogger({name:"model-active-machine"}),Xf=e=>{const t=y.createMachine(v.INACTIVE,{[v.FAILED]:y.state(y.transition(R.GO_ACTIVE,v.ACTIVATING)),[v.INACTIVE]:y.state(y.transition(R.GO_ACTIVE,v.ACTIVATING)),[v.ACTIVATING]:y.invoke(()=>(e.activeStatus=v.ACTIVATING,e.activate()),y.transition("done",v.ACTIVE,y.action(()=>{e.activeStatus=v.ACTIVE})),y.transition("error",v.FAILED,y.action(()=>{e.activeStatus=v.FAILED}))),[v.ACTIVE]:y.state(y.transition(R.GO_INACTIVE,v.DEACTIVATING)),[v.DEACTIVATING]:y.invoke(()=>(e.activeStatus=v.DEACTIVATING,e.deactivate()),y.transition("done",v.INACTIVE,y.action(()=>{e.activeStatus=v.INACTIVE})),y.transition("error",v.FAILED,y.action(()=>{e.activeStatus=v.FAILED})))});return{service:y.interpret(t,r=>Zf.debug(r.machine.current)),machine:t}},wi=m.createLogger({name:"model-online-machine"}),Jf=e=>{const t=y.createMachine(v.OFFLINE,{[v.ONLINE]:y.state(y.transition(R.GO_OFFLINE,v.OFFLINE,y.action(async()=>{await e.offline(),e.onlineStatus=v.OFFLINE}))),[v.OFFLINE]:y.state(y.transition(R.GO_ONLINE,v.ONLINE,y.action(async()=>{wi.debug(`Going online with model ${e.modelId}`),await e.online(),e.onlineStatus=v.ONLINE,await e.fsm.transitionTo(R.INITIALIZE,v.INITIALIZED)})))}),s=y.interpret(t,r=>wi.debug(r.machine.current));return{machine:t,service:s}},ep=e=>{var r;const t=Xf(e).service,s=Jf(e).service;return y.createMachine(v.CREATING,{[v.CREATING]:y.state(y.transition(R.CREATE,v.CREATED)),[v.CREATED]:y.state(y.immediate(v.INITIALIZING)),[v.INITIALIZING]:y.invoke(()=>(X(()=>{e.status=v.INITIALIZING}),e.init()),y.transition("done",v.INITIALIZED,y.action(()=>{e.status=v.INITIALIZED})),y.transition("error",v.FAILED,y.action(()=>{m.error(`Model ${e.modelId} - ${e.modelTypeName} failed to initialize. Transitioning to FAILED state.`),e.status=v.FAILED}))),[v.INITIALIZED]:y.state(y.immediate(v.LOADING)),[v.LOADING]:y.invoke(()=>(X(()=>{e.status=v.LOADING}),e.load()),y.transition("done",v.LOADED,y.action(()=>{e.status=v.LOADED})),y.transition("error",v.FAILED,y.action(()=>{e.status=v.FAILED}))),[v.LOADED]:y.state(y.immediate(v.READYING),y.transition(R.UNLOAD,v.UNLOADING)),[v.RESETTING]:y.invoke(()=>{var o;return X(()=>{e.status=v.RESETTING}),(o=e.unload)==null||o.call(e),e.load()},y.transition("done",v.LOADED,y.action(()=>{e.status=v.LOADED}))),[v.READYING]:y.invoke(()=>(X(()=>{e.status=v.READYING}),e.ready()),y.transition("done",v.READY,y.action(()=>{X(()=>{e.status=v.READY}),s.send(R.GO_ONLINE)})),y.transition("error",v.FAILED,y.action(()=>{e.status=v.FAILED}))),[v.READY]:y.state(y.transition(R.UNLOAD,v.UNLOADED,y.action((r=e.unload)==null?void 0:r.bind(e))),y.transition(R.RESET,v.RESETTING),y.transition(R.GO_ONLINE,v.READY,y.action(()=>{s.send(R.GO_ONLINE)})),y.transition(R.GO_OFFLINE,v.READY,y.action(()=>{s.send(R.GO_OFFLINE)})),y.transition(R.GO_ACTIVE,v.READY,y.action(()=>{t.send(R.GO_ACTIVE)})),y.transition(R.GO_INACTIVE,v.READY,y.action(()=>{t.send(R.GO_INACTIVE)}))),[v.UNLOADED]:y.state(),[v.FAILED]:y.state()})},tp=m.createLogger({name:"kos-model-lifecycle"}),sp=e=>({service:y.interpret(ep(e),s=>tp.debug(`state machine for model ${e.modelId}: ${s.machine.current});`))});class rp{constructor(t,s){l(this,"disposer");l(this,"service");this.model=t,this.log=s;const r=sp(t);this.service=r.service,this.service.send(R.CREATE)}get current(){return this.service.machine.current}async transitionTo(t,s,r=v.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 ${t} toward target ${s}`),new Promise((n,i)=>{var a;(a=this.disposer)==null||a.call(this),this.disposer=E.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 ${t}`))):(this.log.debug(`Model ${this.model.modelId} reached target state ${s}`),n())}),this.service.send(t)}).finally(()=>{var n;(n=this.disposer)==null||n.call(this),this.disposer=void 0}))}getTransitionStatusFor(t){return[v.ACTIVE,v.INACTIVE].includes(t)?this.model.activeStatus:this.model.status}}const kc="browser-router-model";class un{constructor(t,s){l(this,"logger");l(this,"model");l(this,"router",null);l(this,"registered",!1);l(this,"registeredRoutes",[]);this.model=t,this.logger=s}registerAll(){var s;if(!er(this.model))return;let t=this.model.__httpBrowserRouter;if(!t)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"){t=o;break}}if(t||(t=(s=_e(kc))==null?void 0:s.model),!t)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(t)}setRouter(t){this.router=t,this.registered||this.registerRoutes()}hasRoutes(){return er(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 t=ic(this.model);t.length!==0&&(this.logger.debug(`Registering ${t.length} HTTP routes`),t.forEach(s=>{this.registerRoute(s)}),this.registered=!0)}resolvePropKey(t){const s=/\{PROP_([^}]+)\}/g;let r=t;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(t))!==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: ${t}`)}return r}registerRoute(t){if(!this.router)return;const s=this.model[t.handler];if(!s||typeof s!="function"){this.logger.error(`Handler method '${t.handler}' not found on model`);return}const r=this.resolvePropKey(t.path);this.logger.debug(`Registering ${t.method} ${r} -> ${t.handler}`+(r!==t.path?` (resolved from ${t.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 ${t.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(t.method,r),this.router.use(t.method,r,o),this.registeredRoutes.push({method:t.method,path:r})}checkForDuplicateRoute(t,s){if(!this.router)return;this.router.getRoutes().find(n=>n.method===t&&n.path===s)&&this.logger.warn(`Duplicate route detected: ${t} ${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 t=0;for(const s of this.registeredRoutes){const r=this.router.remove(s.method,s.path);t+=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 ${t} routes from browser router`)}this.registered=!1,this.registeredRoutes=[],this.router=null}getRegisteredRoutes(){return[...this.registeredRoutes]}}function op(e,t){if(!er(e))return;const s=_e(kc);if(!(s!=null&&s.model))throw t.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 un(e,t).setRouter(s.model)}class np{constructor(t){l(this,"queue",[]);this.log=t}enqueue(t){this.queue.push(t)}flush(){if(this.queue.length!==0){this.log.warn(`Processing ${this.queue.length} offline message(s)`);for(const t of this.queue)try{t()}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 ip{constructor(t,s){l(this,"unsubscribers",[]);this.model=t,this.log=s}register(){const t=this.model.modelId,s=$("/kosCore/online",async()=>{this.log.debug(`Online event received for ${t}, waiting for readiness...`),await this.model.whenReady(),this.log.debug(`${t} is ready — sending GO_ONLINE`),await this.model.fsm.transitionTo(R.GO_ONLINE,v.ONLINE)}),r=$("/kosCore/offline",async()=>{this.log.debug(`Offline event received for ${t} — sending GO_OFFLINE`),await this.model.fsm.transitionTo(R.GO_OFFLINE,v.OFFLINE)});this.unsubscribers.push(s.unsubscribe),this.unsubscribers.push(r.unsubscribe)}dispose(){this.unsubscribers.forEach(t=>t()),this.unsubscribers=[]}}class ap{constructor(t){l(this,"subscription");l(this,"unsubscribe");l(this,"eventType");this.eventType=t,this.subscription={queue:[],resolvers:[],closed:!1};const s=$(t,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(t=>{this.subscription.closed?t({done:!0,value:void 0}):this.subscription.resolvers.push(s=>{t({done:!1,value:s})})})}async return(){return this.subscription.closed=!0,this.unsubscribe(),this.subscription.resolvers.forEach(t=>{t(void 0)}),this.subscription.resolvers=[],{done:!0,value:void 0}}async throw(t){throw this.subscription.closed=!0,this.unsubscribe(),t}[Symbol.asyncIterator](){return this}}function Ei(e){return new ap(e)}var Lc=(e=>(e.GET="GET",e.PUT="PUT",e.POST="POST",e.DELETE="DELETE",e))(Lc||{});const Fc=({path:e,requestId:t,method:s,destinationAddress:r})=>{let o=`${Sr}:${s}
2
2
  `;return o+=`topic:${e}
3
3
  `,o+=`${At}:${e}
4
4
  `,o+=`${Is}:${t}
@@ -112,7 +112,7 @@ ${u}topics:${t}
112
112
  gl_FragColor = vec4(rgb, 1.0);
113
113
  }
114
114
  `,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 at{constructor(){l(this,"canvas");l(this,"ctx");l(this,"lastUpdate",0);this.canvas=document.createElement("canvas");const t=this.canvas.getContext("2d");if(!t)throw new Error("2D canvas not supported");this.ctx=t}dispose(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.remove()}shouldStep(t){const s=performance.now();return s-this.lastUpdate>=t?(this.lastUpdate=s,!0):!1}readPixels(t,s){return this.ctx.getImageData(0,0,t,s).data}}function Vn(e){class t extends e{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 t}const ov=Vn(at);class nv extends ov{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,u)=>{i.addColorStop(u*a,c)}),this.ctx.fillStyle=i,this.ctx.fillRect(0,0,s,r),!this.loop&&!this.isOneShotDone&&this.signalDoneIfNeeded()}}const iv=Vn(at);class Uu extends iv{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 av extends Nu{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 cv(e){const t=e.replace("#","");if(!/^[0-9A-Fa-f]{3}$|^[0-9A-Fa-f]{6}$/.test(t))throw new Error(`Invalid hex color: ${e}`);let s,r,o;return t.length===3?(s=parseInt(t[0]+t[0],16),r=parseInt(t[1]+t[1],16),o=parseInt(t[2]+t[2],16)):(s=parseInt(t.substring(0,2),16),r=parseInt(t.substring(2,4),16),o=parseInt(t.substring(4,6),16)),{r:s,g:r,b:o}}function ju(e){return typeof e=="string"?cv(e):e}function vr(e){const t=ju(e);return`rgb(${t.r},${t.g},${t.b})`}class lv extends at{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=ju(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 u=0,d=0,h=0;if(i===c)u=this.baseColor.r,d=this.baseColor.g,h=this.baseColor.b;else if(i<c&&i>c-this.trailColors.length){const p=c-i;if(p<this.trailColors.length){const b=this.trailColors[p];u=b.r,d=b.g,h=b.b}}const f=(i*s+a)*4;n[f]=u,n[f+1]=d,n[f+2]=h,n[f+3]=255}this.ctx.putImageData(o,0,0)}}class uv{constructor(t,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(t.baseRenderer.type,t.baseRenderer.data),this.overlayConfigs=t.overlays,this.persistOverlaysOnComplete=t.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 t of this.overlayConfigs){const s=new Image;s.crossOrigin="anonymous",s.onload=()=>{this.loadedIcons.add(t.src)},s.onerror=r=>{console.error(`Failed to load overlay image: ${t.src}`,r)},s.src=t.src,this.overlayIcons.set(t.src,s)}}calculateOverlayPosition(t,s,r){let o,n;if(typeof t.position=="string")switch(t.position){case"top-left":o=0,n=0;break;case"top-center":o=(s-t.size)/2,n=0;break;case"top-right":o=s-t.size,n=0;break;case"center-left":o=0,n=(r-t.size)/2;break;case"center":o=(s-t.size)/2,n=(r-t.size)/2;break;case"center-right":o=s-t.size,n=(r-t.size)/2;break;case"bottom-left":o=0,n=r-t.size;break;case"bottom-center":o=(s-t.size)/2,n=r-t.size;break;case"bottom-right":o=s-t.size,n=r-t.size;break;default:o=0,n=0}else o=t.position.x,n=t.position.y;return t.offset&&(o+=t.offset.x||0,n+=t.offset.y||0),{x:o,y:n}}reset(){this.baseRenderer.reset(),this.baseRendererCompleted=!1,this.hasSignaledCompletion=!1}renderFrame(t,s){if(this.canvas.width=t,this.canvas.height=s,this.ctx.clearRect(0,0,t,s),this.baseRendererCompleted&&this.persistOverlaysOnComplete)this.renderOverlays(t,s);else{this.baseRenderer.renderFrame(t,s);const r=this.baseRenderer.readPixels(t,s);if(r&&r.length>0){const o=new ImageData(r,t,s);this.ctx.putImageData(o,0,0)}this.renderOverlays(t,s)}}renderOverlays(t,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,t,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(t,s){return this.ctx.getImageData(0,0,t,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(t){this.completionCallback=t,this.hasSignaledCompletion&&t()}isOneShot(){return this.persistOverlaysOnComplete?!1:"isOneShot"in this.baseRenderer&&typeof this.baseRenderer.isOneShot=="function"?this.baseRenderer.isOneShot():!1}}class Bu extends at{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(),u=(c-this.lastFrameTime)/1e3;this.lastFrameTime=c;const d=n*u;switch(o){case"left":this.position+=d;break;case"right":this.position+=d;break;case"up":this.position+=d;break;case"down":this.position+=d;break}}this.drawScrollingImage(s,r,o,i),this.checkScrollCompletion(s,r,o,i)}drawScrollingImage(s,r,o,n){var h,f,p,b,w,M,_,F,Q;const i=this.img.width/this.img.height;let a,c;((h=this.scrollConfig)==null?void 0:h.maintainAspectRatio)!==!1?(f=this.scrollConfig)!=null&&f.height?(c=this.scrollConfig.height,a=c*i):(p=this.scrollConfig)!=null&&p.width?(a=this.scrollConfig.width,c=a/i):o==="left"||o==="right"?(c=r,a=c*i):(a=s,c=a/i):(a=((b=this.scrollConfig)==null?void 0:b.width)||s,c=((w=this.scrollConfig)==null?void 0:w.height)||r);let u,d;switch(o==="left"||o==="right"?(u=0,((M=this.scrollConfig)==null?void 0:M.offsetY)==="center"||((_=this.scrollConfig)==null?void 0:_.offsetY)===void 0?d=(r-c)/2:d=this.scrollConfig.offsetY):(((F=this.scrollConfig)==null?void 0:F.offsetX)==="center"||((Q=this.scrollConfig)==null?void 0:Q.offsetX)===void 0?u=(s-a)/2:u=this.scrollConfig.offsetX,d=0),o){case"left":{const D=s-this.position;if(D<s&&D>-a&&this.ctx.drawImage(this.img,D,d,a,c),this.loopConfig&&this.pauseDuration===0&&this.position>n){const O=D+a+n;O<s&&this.ctx.drawImage(this.img,O,d,a,c)}break}case"right":{const D=-a+this.position;if(D>-a&&D<s&&this.ctx.drawImage(this.img,D,d,a,c),this.loopConfig&&this.pauseDuration===0&&D-n-a>-a){const O=D-a-n;O<s&&this.ctx.drawImage(this.img,O,d,a,c)}break}case"up":{const D=r-this.position;if(D>-c&&D<r&&this.ctx.drawImage(this.img,u,D,a,c),this.loopConfig&&this.pauseDuration===0&&D+c+n<r){const O=D+c+n;O>-c&&this.ctx.drawImage(this.img,u,O,a,c)}break}case"down":{const D=-c+this.position;if(D>-c&&D<r&&this.ctx.drawImage(this.img,u,D,a,c),this.loopConfig&&this.pauseDuration===0&&D-n-c>-c){const O=D-c-n;O<r&&this.ctx.drawImage(this.img,u,O,a,c)}break}}}checkScrollCompletion(s,r,o,n){var h,f,p,b,w;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?(f=this.scrollConfig)!=null&&f.height?(c=this.scrollConfig.height,a=c*i):(p=this.scrollConfig)!=null&&p.width?(a=this.scrollConfig.width,c=a/i):o==="left"||o==="right"?(c=r,a=c*i):(a=s,c=a/i):(a=((b=this.scrollConfig)==null?void 0:b.width)||s,c=((w=this.scrollConfig)==null?void 0:w.height)||r),o){case"left":case"right":this.loopConfig;break;case"up":case"down":this.loopConfig;break}let u=!1;const d=1;switch(o){case"left":u=s-this.position<-a-d;break;case"right":u=-a+this.position>s+d;break;case"up":u=r-this.position<-c-d;break;case"down":u=-c+this.position>r+d;break}u&&(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=vr(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 dv extends at{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(`
115
- `),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=vr(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(),u=(c-this.lastFrameTime)/1e3;this.lastFrameTime=c;const d=n*u;switch(o){case"left":case"right":case"up":case"down":this.position+=d;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],u=(s-c)/2,d=n+i*this.lineHeight;this.ctx.fillText(a,u,d)}}drawScrollingText(s,r,o,n){var c,u,d,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"||((u=this.scrollConfig)==null?void 0:u.offsetY)===void 0?a=(r-this.textHeight)/2:a=this.scrollConfig.offsetY):(((d=this.scrollConfig)==null?void 0:d.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 u=c+this.textWidth+n;u<r&&this.drawTextBlock(u,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 u=c-this.textWidth-n;u<r&&this.drawTextBlock(u,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 u=c+this.textHeight+n;u>-this.textHeight&&this.drawTextBlock(i,u,"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 u=c-this.textHeight-n;u<o&&this.drawTextBlock(i,u,"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 u=r+n*this.lineHeight;this.ctx.fillText(i,c,u)}}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 hv{constructor(t){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=t.patterns,this.loopConfig=t.loop??!1,this.transitionDuration=t.transitionDuration??0,this.patternOverrides=t.patternOverrides??{},this.patternStore=t.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 t=this.patterns[this.currentPatternIndex],s=this.patternStore.get(t);if(!s){console.warn(`Pattern "${t}" not found in store, skipping`),this.moveToNextPattern();return}this.currentRenderer&&((i=(n=this.currentRenderer).dispose)==null||i.call(n));const r=this.patternOverrides[t]??{},o={...s.data,...r};try{this.currentRenderer=wr({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(u){console.error(`Failed to create renderer for pattern "${t}":`,u),this.moveToNextPattern()}}isDoneAware(t){return typeof(t==null?void 0:t.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 t,s;(s=(t=this.currentRenderer)==null?void 0:t.play)==null||s.call(t)}pause(){var t,s;(s=(t=this.currentRenderer)==null?void 0:t.pause)==null||s.call(t)}renderFrame(t,s){this.width=t,this.height=s,this.canvas.width=t,this.canvas.height=s,this.currentRenderer&&this.currentRenderer.renderFrame(t,s)}readPixels(t,s){return this.currentRenderer?this.currentRenderer.readPixels(t,s):this.ctx.getImageData(0,0,t,s).data}onDone(t){this.completionCallback=t}isOneShot(){var t,s;return this.loopConfig===!1||this.loopConfig===1?this.patterns.length===1&&this.currentRenderer?((s=(t=this.currentRenderer).isOneShot)==null?void 0:s.call(t))??!1:!0:!1}dispose(){var t,s;this.currentRenderer&&((s=(t=this.currentRenderer).dispose)==null||s.call(t)),this.completionCallback=null}setPatternStore(t){this.patternStore=t,this.patterns.length>0&&this.loadCurrentPattern()}}const fv=Vn(at);class pv extends fv{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=vr(r)}setColor(s){this.color=vr(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 gv extends at{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,f,p)=>(p<0&&(p+=1),p>1&&(p-=1),p<.16666666666666666?h+(f-h)*6*p:p<.5?f:p<.6666666666666666?h+(f-h)*(.6666666666666666-p)*6:h),u=o<.5?o*(1+r):o+r-o*r,d=2*o-u;n=c(d,u,s+1/3),i=c(d,u,s),a=c(d,u,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 u=(c+this.offset)%s/s,d=this.minHue/360+u*((this.maxHue-this.minHue)/360),[h,f,p]=this.hslToRgb(d,1,.5);n[i++]=h,n[i++]=f,n[i++]=p,n[i++]=255}this.ctx.putImageData(o,0,0)}}const qi=new Map;$s(te,{register(e,t){qi.set(e,t)},execute(e,t){const s=qi.get(e);return s?new s(t):null}});S.canvas.registerRenderer("video",av);S.canvas.registerRenderer("video-basic",Nu);S[te].register("image-static",Uu);S[te].register("image-scrolling",Bu);const mv=class{constructor(e){var t;return(t=e.scroll)!=null&&t.enabled?new Bu(e):new Uu(e)}};S[te].register("image",mv);S[te].register("color",pv);S[te].register("matrix",lv);S[te].register("sweep",gv);S[te].register("gradient",nv);S[te].register("drop",rv);S[te].register("sequence",hv);S[te].register("text",dv);const yv=class{constructor(e){const t=(s,r)=>{const o=wr({mode:s,data:r});if(!o)throw new Error(`Failed to create renderer of type: ${s}`);return o};return new uv(e,t)}};S[te].register("overlay",yv);const wr=({mode:e,data:t})=>{const s=S[te].execute(e,t);if(s)return s;throw new Error(`Unknown mode: ${e}`)};var bv=Object.defineProperty,vv=Object.getOwnPropertyDescriptor,Bt=(e,t,s,r)=>{for(var o=r>1?void 0:r?vv(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&bv(t,s,o),o};const Ku="canvas-dispatcher-model";function wv(e){if(e=e.replace(/^#/,""),e.length===3&&(e=e.split("").map(s=>s+s).join("")),e.length!==6)return null;const t=parseInt(e,16);return{r:t>>16&255,g:t>>8&255,b:t&255}}let ze=class{constructor(e,t,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=e,this.logger=s.logger,this._endpointRenderers=new Se}addNamedEndpoint(e,t){this._endpointRenderers.getModel(e)&&this.logger.warn(`Endpoint "${e}" already exists. Overwriting.`);const s=Gn.instance(e).options({apiPath:t.apiPath,width:t.width,height:t.height,fps:t.fps,durationMs:t.durationMs??null,endpoint:e}).build();return this._endpointRenderers.addModel(s),s}addContent(e,t){this._content.has(e)&&this.logger.warn(`Content "${e}" already exists. Overwriting.`),this._content.set(e,t)}addPattern(e,t){this._patterns.has(e)&&this.logger.warn(`Pattern "${e}" already exists. Overwriting.`),this._patterns.set(e,t)}async handlePatternsPost(e,t){var o,n;const s=e.body,r=Array.isArray(s)?s:[s];if(r.some(i=>!i.id||!i.type||!i.data)){(o=t.status)==null||o.call(t,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=t.status)==null||n.call(t,200).send({status:"OK"})}async handlePatternApplication(e,t){var u,d,h;const s=e.params.pattern,r=e.params.endpoint,o=this._endpointRenderers.getModel(r);if(!o){(u=t.status)==null||u.call(t,404).send({error:`Endpoint "${r}" not found`});return}if(!this._patterns.has(s)){(d=t.status)==null||d.call(t,404).send({error:`Pattern "${s}" not found`});return}const n=this._patterns.get(s),i=n.type,a=e.body||{};this.data={...n.data,...a};const c=i==="sequence"?{...this.data,patternStore:this._patterns}:this.data;o.renderer=wr({mode:i,data:c}),o.setClearOnComplete(n.clearOnComplete),o.startStreaming(),(h=t.status)==null||h.call(t,200).send({status:"OK"})}async handleColorApplication(e,t){var u,d,h;const s=e.params.color,r=wv(s);if(!r){(u=t.status)==null||u.call(t,400).send({error:"Invalid color format"});return}const o=e.params.endpoint,n=this._endpointRenderers.getModel(o);if(!n){(d=t.status)==null||d.call(t,404).send({error:`Endpoint "${o}" not found`});return}const{r:i,b:a,g:c}=r;n.renderer=wr({mode:"color",data:{r:i,g:c,b:a}}),n.startStreaming(),(h=t.status)==null||h.call(t,200).send({status:"OK"})}async handleEndpointCreation(e,t){var r,o;const s=e.body;if(!s.apiPath||!s.id){(r=t.status)==null||r.call(t,400).send({error:"Name and path are required"});return}this.addNamedEndpoint(s.id,s),(o=t.status)==null||o.call(t,200).send({status:"OK"})}async load(e){var s;const t=e==null?void 0:e.get(Ct.loader);t&&((s=t.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)}))}};Bt([Ie],ze.prototype,"_endpointRenderers",2);Bt([Cs("/api/ui/canvas/patterns")],ze.prototype,"handlePatternsPost",1);Bt([Cs("/api/ui/canvas/pattern/:endpoint/:pattern")],ze.prototype,"handlePatternApplication",1);Bt([Cs("/api/ui/canvas/color/:endpoint/:color")],ze.prototype,"handleColorApplication",1);Bt([Cs("/api/ui/canvas/endpoint")],ze.prototype,"handleEndpointCreation",1);ze=Bt([A(Ku)],ze);const Ct=new Me({class:ze,type:Ku}),{URL:Yn}=ae(),{getOne:Hu}=oe.build({basePath:`${Yn}/api/device`}),Er=m.createLogger({name:"device-service",group:"Services"}),zu=async()=>{Er.debug("sending GET for device serial number");try{const e=await Hu({urlOverride:`${Yn}/api/kos/device/serialNumber`});return[void 0,e==null?void 0:e.data.serialNumber]}catch(e){if(e instanceof pe)return Er.error(`Error fetching device serial number: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},Gu=async()=>{Er.debug("sending GET for device details");try{const e=await Hu({urlOverride:`${Yn}/api/kos/device`});return e?[void 0,e.data]:["unknownError",void 0]}catch(e){if(e instanceof pe)return Er.error(`Error fetching device serial number: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},Ev=Object.freeze(Object.defineProperty({__proto__:null,getDeviceDetails:Gu,getSerialNumber:zu},Symbol.toStringTag,{value:"Module"}));var Mv=Object.defineProperty,Tv=Object.getOwnPropertyDescriptor,Vu=(e,t,s,r)=>{for(var o=r>1?void 0:r?Tv(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Mv(t,s,o),o};const Yu="device-model",_v="/kos/criticalData/changed",Ov="/kos/criticalData/available";let Mr=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"_serialNumber");l(this,"_name");l(this,"_nodeId");this.id=e,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[e]=this.nodeId.split("-");return e}get nodeName(){const[,e]=this.nodeId.split("-");return e}updateModel(e){this._serialNumber=e.serialNumber??"unassigned",this._name=e.name??"unassigned",this._nodeId=e.nodeId??"unassigned"}async loadDeviceData(){const[e,t]=await Gu();if(e){this.logger.error(`Error fetching device serial number: ${e}`);return}if(t){const{name:s,nodeId:r}=t;this.updateModel({name:s,nodeId:r,serialNumber:this.serialNumber})}}async loadSerialNumber(){const[e,t]=await zu();if(e){this.logger.error(`Error fetching device serial number: ${e}`);return}this.updateModel({serialNumber:t,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()}};Vu([U({topic:[_v,Ov],websocket:!0})],Mr.prototype,"handleCriticalDataChanged",1);Mr=Vu([A(Yu)],Mr);const Tr=new Me({class:Mr,type:Yu});var Iv=Object.getOwnPropertyDescriptor,Sv=(e,t,s,r)=>{for(var o=r>1?void 0:r?Iv(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=i(o)||o);return o};const qu="network-interface-model";let xo=class{constructor(e,t,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=e,this.logger=s.logger,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}updateModel(e){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}async init(){this.logger.debug(`initializing network-interface ${this.id}`)}async load(){this.logger.debug(`loading network-interface ${this.id}`)}};xo=Sv([A(qu)],xo);const qn=new me({class:xo,type:qu}),{URL:$v}=ae(),{getAll:Cv}=oe.build({basePath:`${$v}/api/kos/network/interfaces`}),Wi=m.createLogger({name:"network-interface-service",group:"Services"}),Wu=async()=>{Wi.debug("sending GET for copy-logs");try{const e=await Cv({});return[void 0,e==null?void 0:e.data]}catch(e){if(e instanceof pe)return Wi.error(`Error fetching log file size: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},Dv=Object.freeze(Object.defineProperty({__proto__:null,getNetworkInterfaces:Wu},Symbol.toStringTag,{value:"Module"}));var xv=Object.defineProperty,Av=Object.getOwnPropertyDescriptor,Qu=(e,t,s,r)=>{for(var o=r>1?void 0:r?Av(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&xv(t,s,o),o};const Zu="network-interface-container-model";let _r=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=e,this.logger=s.logger,this._models=new Se({parentId:e,indexMap:{byCategory:"category"}})}getModel(e){return this._models.getModel(e)}get models(){return this._models}get data(){return this._models.data}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}async init(){this.logger.debug(`initializing network-interface-container container ${this.id}`)}async refreshInterfaces(){this.logger.debug("refreshing interfaces");const[e,t]=await Wu();if(e){this.logger.error(`Error loading network interfaces: ${e}`);return}t&&t.forEach(s=>{const r=qn.instance(s.name).forceUpdate.options(s).build();this.addModel(r)})}async load(){this.logger.debug(`loading network-interface-container container ${this.id}`),this.refreshInterfaces()}};Qu([Ie],_r.prototype,"_models",2);_r=Qu([A(Zu)],_r);const Ts=new Me({class:_r,type:Zu});Ts.addRelatedModel(qn);const{URL:Pv}=ae(),{getAll:Rv}=oe.build({basePath:`${Pv}/api/kos/storage/devices`}),Qi=m.createLogger({name:"storage-device-service",group:"Services"}),Xu=async()=>{Qi.debug("sending GET for storage-device");const e=await Rv({});return!(e!=null&&e.data)||e.status!==200?(Qi.error("Failed to retrieve storage-device data",e),[]):e.data},kv=Object.freeze(Object.defineProperty({__proto__:null,getStorageDevices:Xu},Symbol.toStringTag,{value:"Module"}));var Lv=Object.getOwnPropertyDescriptor,Fv=(e,t,s,r)=>{for(var o=r>1?void 0:r?Lv(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=i(o)||o);return o};const Ju="storage-device-model";let Ao=class{constructor(e,t,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=e,this.logger=s.logger,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}updateModel(e){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}async init(){this.logger.debug(`initializing storage-device ${this.id}`)}async load(){this.logger.debug(`loading storage-device ${this.id}`)}};Ao=Fv([Ar(),A(Ju)],Ao);const Or=new me({class:Ao,type:Ju});var Nv=Object.defineProperty,Uv=Object.getOwnPropertyDescriptor,Wn=(e,t,s,r)=>{for(var o=r>1?void 0:r?Uv(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Nv(t,s,o),o};const ed="storage-device-container-model",jv="/kos/storage";let _s=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=e,this.logger=s.logger,this._models=new Se({parentId:e})}getModel(e){return this._models.getModel(e)}get models(){return this._models}get data(){return this._models.data}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}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(e){this._models.data.filter(s=>!e.find(r=>r.id===s.id)).forEach(s=>{this.removeModel(s.id)}),e.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=Or.instance(s.id).options(o).build();this.addModel(n)}})}async load(){this.logger.debug(`loading storage-device-container container ${this.id}`),(await Xu()).forEach(t=>{const s={...t,kosParentId:this.id},r=Or.instance(t.id).options(s).build();this.addModel(r)})}};Wn([Ie],_s.prototype,"_models",2);Wn([U({topic:jv,websocket:!0})],_s.prototype,"handleStorageAvailability",1);_s=Wn([A(ed)],_s);const Dt=new Me({class:_s,type:ed});Dt.addRelatedModel(Or);const{URL:Qn}=ae(),{getAll:Bv,postModel:Kv}=oe.build({basePath:`${Qn}/api/kos/update/available`}),Zi=m.createLogger({name:"usb-update-service",group:"Services"}),td=async()=>{Zi.debug("sending GET for usb-update");const e=await Bv({urlOverride:`${Qn}/api/kos/update/available`});return!(e!=null&&e.data)||(e==null?void 0:e.status)!==200?(Zi.error("Failed to retrieve usb-update data",e),[]):e.data},sd=async(e,t,s)=>{const r=await Kv({model:{manifestId:e,deviceId:t},tracker:s,urlOverride:`${Qn}/api/kos/update/install`});if(!(r!=null&&r.data))throw new Error("No response from server");return r.data},Hv=Object.freeze(Object.defineProperty({__proto__:null,getAvailableUpdates:td,installUpdate:sd},Symbol.toStringTag,{value:"Module"}));var zv=Object.defineProperty,Gv=Object.getOwnPropertyDescriptor,rd=(e,t,s,r)=>{for(var o=r>1?void 0:r?Gv(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&zv(t,s,o),o};const od="usb-update-model";let Ir=class{constructor(e,t,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=e,this.logger=s.logger,this.active=t.active,this.blocked=t.blocked,this.createTime=t.createTime,this.deviceId=t.deviceId,this.manifestId=t.manifestId,this.notes=t.notes,this.futureHandler=new Rr(this)}updateModel(e){this.active=e.active,this.blocked=e.blocked,this.createTime=e.createTime,this.deviceId=e.deviceId,this.manifestId=e.manifestId,this.notes=e.notes}reset(){this.futureHandler.removeFuture()}get future(){return this.futureHandler.future}async install(e){if(!e)throw new Error("No tracker provided");return this.logger.info(`Installing update for manifest ${this.manifestId} from device ${this.deviceId}`),sd(this.manifestId,this.deviceId,e)}async init(){this.logger.debug(`initializing usb-update ${this.id}`)}async load(){this.logger.debug(`loading usb-update ${this.id}`)}};rd([si()],Ir.prototype,"install",1);Ir=rd([A(od)],Ir);const Zn=new me({class:Ir,type:od});var Vv=Object.defineProperty,Yv=Object.getOwnPropertyDescriptor,qr=(e,t,s,r)=>{for(var o=r>1?void 0:r?Yv(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Vv(t,s,o),o};const nd="usb-update-container-model";let xt=class{constructor(e,t,s){l(this,"id");l(this,"disposer");l(this,"storageService");l(this,"_activeUpdate");l(this,"logger");l(this,"_models");this.id=e,this.logger=s.logger,this._models=new Se({parentId:e})}getModel(e){return this._models.getModel(e)}get models(){return this._models}get data(){return this._models.data}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}get activeUpdate(){return this._activeUpdate}reset(){this.clearActiveUpdate()}clearActiveUpdate(){this._activeUpdate=void 0}updateActiveUpdate(e){this._activeUpdate=e}get isUsbInserted(){return this.storageService.isStorageInserted}get hasAvailableUpdates(){return this._models.data.length>0}async syncAvailableUpdates(){const e=await td();X(()=>{const t=e.map(s=>`${s.deviceId}-${s.manifestId}`);this._models.data.filter(s=>!t.includes(s.id)).forEach(s=>this.removeModel(s.id)),e.forEach(s=>{const r=`${s.deviceId}-${s.manifestId}`,o=Zn.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 e;(e=this.disposer)==null||e.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}`)}};qr([Pt({modelType:Dt.type})],xt.prototype,"storageService",2);qr([Ie],xt.prototype,"_models",2);qr([lc({dependencies:e=>[e.isUsbInserted]})],xt.prototype,"usbInsertedEffect",1);xt=qr([A(nd)],xt);const Os=new Me({class:xt,type:nd});Os.addRelatedModel(Zn);const qv=()=>({...{[Lt.type]:{class:Dl},[He.type]:{class:Ll,singleton:!0},...re.registration,...rt.registration,...St.registration,...mr.registration,...ke.registration,[Hn.type]:{class:exports.WsEventModel,singleton:!0},...Ms.registration,...Bn.registration,...ar.registration}}),Xn=qv(),Wv={models:Xn,preloadModels:[]},Xi=!0,id=e=>()=>{const t=Xn;return bc(Po)(Es).model(St).model(Dt).model(Os).model(Tr).model(hr).model(ps).model(fr).model(Dn).model(Ts).model(Ct).model(Gn).model(Yl).model(Sn,Xi).model(Ps).model(Ql,Xi),Object.keys(t).forEach(s=>{const r=t[s];yc(Po)(s,r)}),{preload:x.model.preloadModel(e),model:x.model.register(e),companion:x.companion.register(e),legacy:x.model.registerLegacyModel(e)}},we={};we.core={models:id(we)};we.preload=x.model.preloadModel(we);we.model=x.model.register(we);we.companion=x.companion.register(we);we.legacy=x.model.registerLegacyModel(we);const Po=we;class Qv{registerTroubleRankMapper(t){return S.propertyMapper.registerPropertyMapper(be.TroubleRank,t),this}registerTroubleRoleMapper(t){return S.propertyMapper.registerPropertyMapper(be.TroubleRole,t),this}registerTroubleColorMapper(t){return S.propertyMapper.registerPropertyMapper(be.TroubleColor,t),this}registerModelLoader(t,s){S.loader.registerLoader(t,s)}registerCanvasPatternLoader(t){S.loader.registerLoader(Ct.loader,t)}}const Zv=async(e,t)=>{const s=Dn.instance(e).options({}).build(),r=t?`${t}-`:"";return await ue(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:()=>{Xe(s)}}},ad="kos:service:region",cd="regionId",Xv=`${ad}-${cd}`,ld=async e=>{const t=rt.factory(Xv)({path:ad,attribute:cd});await ue(t),t.updateProperty(e)},Jn="/kos-timer-event",ei="/kos-timer-event/tick",ti="defaultTimerEnd",es=m.createLogger({name:"timer-manager"}),Jv=e=>e.updateProperty!==void 0;class ud{constructor(t,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=t;const o=typeof s=="number"?s:s.value||60;this.timeout=o,this.state="inactive",this.remainingTime=o,Jv(s)&&Y(()=>{m.info(`Updating config value timer ${t} with new timeout value ${s.value}`);const n=s.value||60;this.updateTimeout(n)}),this.addTimeoutAction({name:ti}),r&&r.forEach(n=>{this.addTimeoutAction(n)})}get id(){return this.name}start(){if(this.state==="active"){es.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&&(es.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(t){this.timeout=t,this.restart()}addTimeoutAction(t){const s=t.remainingTime??0;this.timeoutActions.has(s)||this.timeoutActions.set(s,[]);const r=t.name,o=this.timeoutActions.get(s).find(n=>n.name===r);o?o.action=t.action:this.timeoutActions.get(s).push(t)}removeTimeoutAction(t){for(const[s,r]of this.timeoutActions.entries()){const o=r.filter(n=>n.name!==t);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(t){this.timeoutActions.has(t)&&this.timeoutActions.get(t).forEach(s=>{var r;es.debug(`Executing timer action ${s.name} at ${t}`),(r=s.action)==null||r.call(s,s.name,t),this.notifyTimeoutAction(s),s.singleUse&&(es.info(`${this.name} Removing single-use action ${s.name}`),this.removeTimeoutAction(s.name))}),this.notifyTick()}notifyTick(){z(`${ei}/${this.name}`,{name:this.name,remainingTime:this.remainingTime})}notifyTimeoutAction(t){z(Jn,{name:this.name,action:t.name,remainingTime:this.remainingTime})}}const ts=new Map,ht=(e,t)=>{const s=ts.get(e);if(!s){es.error(`Timer ${e} not found`);return}t(s)},dd={createRelativeTimer(e,t,s){const r=new Date,o=Math.round((t.getTime()-r.getTime())/1e3);return this.createTimer(e,o,s)},createTimer(e,t=60,s){if(ts.has(e))return ts.get(e);const r=new ud(e,t,s);return ts.set(e,r),r},getTimer(e){return ts.get(e)},clearTimer(e){ht(e,t=>t.pause())},restartTimer(e){ht(e,t=>t.restart())},resetTimer(e){ht(e,t=>t.reset())},addTimeoutAction(e,t){ht(e,s=>s.addTimeoutAction(t))},removeTimeoutAction(e,t){ht(e,s=>s.removeTimeoutAction(t))},startTimer(e){ht(e,t=>t.start())}},hd="kos:service:region:settings",fd="timeZone",ew=`${hd}-${fd}`,Ro=async e=>{const t=rt.factory(ew)({path:hd,attribute:fd});await ue(t),t.updateProperty(e)},tw=e=>!e||!e.data;function si(e={}){const{alias:t,namespace:s,abortController:r=!1}=e;return(o,n,i)=>{o[os]=o[os]||{},t&&(o[as]=o[as]||new Map,o[as].set(n,t));const a=i.value,c=async function(...u){const d=tt();m.debug(`Calling future service ${n} with tracker ${d}`);let h,f;r&&(h=new AbortController);const p=Je.initiateFuture({tracker:d,id:yn});s&&(p.namespace=s),m.debug(`waiting for future ${p.id} to be ready`),await ue(p),m.debug(`future ${p.id} is ready`),X(()=>{m.debug(`Adding future ${p.id} to futureHandler`),this.futureHandler.addFuture(p,t)}),r&&h&&(f=Y(()=>{(p.status==="CANCELLED"||p.endState===Ke.Canceled)&&(m.debug(`Future ${p.id} cancelled, aborting request`),h==null||h.abort())}),h.signal.addEventListener("abort",async()=>{if(p.status!=="CANCELLED"&&p.endState!==Ke.Canceled&&!p.endState){m.debug(`AbortController aborted, cancelling future ${p.id}`);try{await p.cancelFuture()}catch(w){m.error(`Failed to cancel future ${p.id}:`,w)}}},{once:!0}));const b=()=>{f&&(f(),f=void 0)};try{const w=[...u];if(r&&h){const F=w[w.length-1];F&&typeof F=="object"&&"aborted"in F?w[w.length-1]=h.signal:w.push(h.signal)}w.push(d);const M=await a.apply(this,w);m.debug(`received future response for ${d}`,M);const _=tw(M)?M:M==null?void 0:M.data;return _?(_.progress=1,m.debug("mapping future response to future model"),p.endState?m.debug(`future ${p.id} has already completed. Not updating the model`):On(_,p)):this.futureHandler.removeFuture(t),b(),_}catch(w){if(b(),r&&(h!=null&&h.signal.aborted)){const M=new Error("Operation cancelled");throw m.debug(`Operation ${n} was cancelled`),M}throw m.error(w),w}};o[os][n]={handler:c}}}const sw=({path:e})=>(t,s)=>{t[k]=t[k]||{},t[k][s]={modelType:Ms.type,id:`${Ms.type}-${e}`,options:{path:e},lifecycle:H.INIT}};function rw(e){const{path:t,attribute:s}=e;return(r,o)=>{r[k]=r[k]||{},r[k][o]={modelType:Bn.type,id:`${t}-${s}`,options:{path:t,attribute:s},lifecycle:H.INIT}}}const mt=m.createLogger({name:"services",group:"Services"}),ow=async(e,t)=>pd(e,t,`${exports.BASE_URL}/api/server/login`),pd=async(e,t,s=`${exports.BASE_URL}/api/login`)=>{const r=await exports.kosFetch(`${s}`,{method:"POST",destinationAddress:"",body:JSON.stringify({email:e,password:t})});if(!r.ok){const n=await r.json();throw Error(`${n==null?void 0:n.error}`)}return await r.json()},nw=async e=>gd(e,`${exports.BASE_URL}/api/server/startPasswordReset`,""),gd=async(e,t=`${exports.BASE_URL}/api/startPasswordReset`,s="server")=>{const r=await exports.kosFetch(`${t}?email=${e}`,{method:"POST",destinationAddress:s});if(!r.ok)throw Error(`There was a problem reseting config; returned status ${r.status}`);return await r.json()},iw=async(e,t)=>md(e,t,`${exports.BASE_URL}/api/server/resetPassword`),md=async(e,t,s=`${exports.BASE_URL}/api/resetPassword`)=>{mt.debug(`resetting password with token ${e} and password ${t.replace(/./g,"*")}`);const r=await exports.kosFetch(`${s}`,{method:"POST",destinationAddress:"",body:JSON.stringify({token:e,password:t})});if(mt.debug(`password reset returned status ${r.status}`),!r.ok){mt.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()},aw=async(e,t,s)=>yd(e,t,s,`${exports.BASE_URL}/api/server/acceptInvite`),yd=async(e,t,s,r=`${exports.BASE_URL}/api/server/acceptInvite`)=>{mt.debug(`accepting invite with token ${e} and password ${t.replace(/./g,"*")}`);const o=await exports.kosFetch(`${r}`,{method:"POST",destinationAddress:"",body:JSON.stringify({token:e,password:t,name:s})});if(mt.debug(`invitation accept returned status ${o.status}`),!o.ok){mt.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 cw(e,t,s,r){const o=e instanceof Promise?{promise:e,abortController:t,cancelFuture:s,future:r}:e,{promise:n,abortController:i,cancelFuture:a,future:c}=o,u=n;let d=0,h="PENDING",f=!0;const p=new Set;let b;return c&&typeof c=="object"&&(b=E.autorun(()=>{const w=c.progress||0,M=c.status||"PENDING",_=!c.endState;(w!==d||M!==h||_!==f)&&(d=w,h=M,f=_,p.forEach(F=>{try{F(d,h)}catch(Q){console.warn("Progress callback error:",Q)}}))})),n.finally(()=>{f=!1,i!=null&&i.signal.aborted||(h="COMPLETED",p.forEach(w=>{try{w(d,h)}catch(M){console.warn("Progress callback error:",M)}})),b&&b(),p.clear()}),u.cancel=async()=>{i&&!i.signal.aborted&&i.abort(),a&&await a(),f=!1,h="CANCELLED",p.forEach(w=>{try{w(d,h)}catch(M){console.warn("Progress callback error:",M)}}),b&&b()},u.getController=()=>i,u.isCancelled=()=>(i==null?void 0:i.signal.aborted)??!1,Object.defineProperty(u,"progress",{get:()=>d,enumerable:!0}),Object.defineProperty(u,"status",{get:()=>h,enumerable:!0}),Object.defineProperty(u,"isRunning",{get:()=>f,enumerable:!0}),u.onProgressUpdate=w=>(p.add(w),w(d,h),()=>p.delete(w)),u}const lw=qe.keyframes`
115
+ `),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=vr(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(),u=(c-this.lastFrameTime)/1e3;this.lastFrameTime=c;const d=n*u;switch(o){case"left":case"right":case"up":case"down":this.position+=d;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],u=(s-c)/2,d=n+i*this.lineHeight;this.ctx.fillText(a,u,d)}}drawScrollingText(s,r,o,n){var c,u,d,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"||((u=this.scrollConfig)==null?void 0:u.offsetY)===void 0?a=(r-this.textHeight)/2:a=this.scrollConfig.offsetY):(((d=this.scrollConfig)==null?void 0:d.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 u=c+this.textWidth+n;u<r&&this.drawTextBlock(u,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 u=c-this.textWidth-n;u<r&&this.drawTextBlock(u,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 u=c+this.textHeight+n;u>-this.textHeight&&this.drawTextBlock(i,u,"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 u=c-this.textHeight-n;u<o&&this.drawTextBlock(i,u,"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 u=r+n*this.lineHeight;this.ctx.fillText(i,c,u)}}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 hv{constructor(t){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=t.patterns,this.loopConfig=t.loop??!1,this.transitionDuration=t.transitionDuration??0,this.patternOverrides=t.patternOverrides??{},this.patternStore=t.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 t=this.patterns[this.currentPatternIndex],s=this.patternStore.get(t);if(!s){console.warn(`Pattern "${t}" not found in store, skipping`),this.moveToNextPattern();return}this.currentRenderer&&((i=(n=this.currentRenderer).dispose)==null||i.call(n));const r=this.patternOverrides[t]??{},o={...s.data,...r};try{this.currentRenderer=wr({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(u){console.error(`Failed to create renderer for pattern "${t}":`,u),this.moveToNextPattern()}}isDoneAware(t){return typeof(t==null?void 0:t.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 t,s;(s=(t=this.currentRenderer)==null?void 0:t.play)==null||s.call(t)}pause(){var t,s;(s=(t=this.currentRenderer)==null?void 0:t.pause)==null||s.call(t)}renderFrame(t,s){this.width=t,this.height=s,this.canvas.width=t,this.canvas.height=s,this.currentRenderer&&this.currentRenderer.renderFrame(t,s)}readPixels(t,s){return this.currentRenderer?this.currentRenderer.readPixels(t,s):this.ctx.getImageData(0,0,t,s).data}onDone(t){this.completionCallback=t}isOneShot(){var t,s;return this.loopConfig===!1||this.loopConfig===1?this.patterns.length===1&&this.currentRenderer?((s=(t=this.currentRenderer).isOneShot)==null?void 0:s.call(t))??!1:!0:!1}dispose(){var t,s;this.currentRenderer&&((s=(t=this.currentRenderer).dispose)==null||s.call(t)),this.completionCallback=null}setPatternStore(t){this.patternStore=t,this.patterns.length>0&&this.loadCurrentPattern()}}const fv=Vn(at);class pv extends fv{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=vr(r)}setColor(s){this.color=vr(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 gv extends at{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,f,p)=>(p<0&&(p+=1),p>1&&(p-=1),p<.16666666666666666?h+(f-h)*6*p:p<.5?f:p<.6666666666666666?h+(f-h)*(.6666666666666666-p)*6:h),u=o<.5?o*(1+r):o+r-o*r,d=2*o-u;n=c(d,u,s+1/3),i=c(d,u,s),a=c(d,u,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 u=(c+this.offset)%s/s,d=this.minHue/360+u*((this.maxHue-this.minHue)/360),[h,f,p]=this.hslToRgb(d,1,.5);n[i++]=h,n[i++]=f,n[i++]=p,n[i++]=255}this.ctx.putImageData(o,0,0)}}const qi=new Map;$s(te,{register(e,t){qi.set(e,t)},execute(e,t){const s=qi.get(e);return s?new s(t):null}});S.canvas.registerRenderer("video",av);S.canvas.registerRenderer("video-basic",Nu);S[te].register("image-static",Uu);S[te].register("image-scrolling",Bu);const mv=class{constructor(e){var t;return(t=e.scroll)!=null&&t.enabled?new Bu(e):new Uu(e)}};S[te].register("image",mv);S[te].register("color",pv);S[te].register("matrix",lv);S[te].register("sweep",gv);S[te].register("gradient",nv);S[te].register("drop",rv);S[te].register("sequence",hv);S[te].register("text",dv);const yv=class{constructor(e){const t=(s,r)=>{const o=wr({mode:s,data:r});if(!o)throw new Error(`Failed to create renderer of type: ${s}`);return o};return new uv(e,t)}};S[te].register("overlay",yv);const wr=({mode:e,data:t})=>{const s=S[te].execute(e,t);if(s)return s;throw new Error(`Unknown mode: ${e}`)};var bv=Object.defineProperty,vv=Object.getOwnPropertyDescriptor,Bt=(e,t,s,r)=>{for(var o=r>1?void 0:r?vv(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&bv(t,s,o),o};const Ku="canvas-dispatcher-model";function wv(e){if(e=e.replace(/^#/,""),e.length===3&&(e=e.split("").map(s=>s+s).join("")),e.length!==6)return null;const t=parseInt(e,16);return{r:t>>16&255,g:t>>8&255,b:t&255}}let ze=class{constructor(e,t,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=e,this.logger=s.logger,this._endpointRenderers=new Se}addNamedEndpoint(e,t){this._endpointRenderers.getModel(e)&&this.logger.warn(`Endpoint "${e}" already exists. Overwriting.`);const s=Gn.instance(e).options({apiPath:t.apiPath,width:t.width,height:t.height,fps:t.fps,durationMs:t.durationMs??null,endpoint:e}).build();return this._endpointRenderers.addModel(s),s}addContent(e,t){this._content.has(e)&&this.logger.warn(`Content "${e}" already exists. Overwriting.`),this._content.set(e,t)}addPattern(e,t){this._patterns.has(e)&&this.logger.warn(`Pattern "${e}" already exists. Overwriting.`),this._patterns.set(e,t)}async handlePatternsPost(e,t){var o,n;const s=e.body,r=Array.isArray(s)?s:[s];if(r.some(i=>!i.id||!i.type||!i.data)){(o=t.status)==null||o.call(t,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=t.status)==null||n.call(t,200).send({status:"OK"})}async handlePatternApplication(e,t){var u,d,h;const s=e.params.pattern,r=e.params.endpoint,o=this._endpointRenderers.getModel(r);if(!o){(u=t.status)==null||u.call(t,404).send({error:`Endpoint "${r}" not found`});return}if(!this._patterns.has(s)){(d=t.status)==null||d.call(t,404).send({error:`Pattern "${s}" not found`});return}const n=this._patterns.get(s),i=n.type,a=e.body||{};this.data={...n.data,...a};const c=i==="sequence"?{...this.data,patternStore:this._patterns}:this.data;o.renderer=wr({mode:i,data:c}),o.setClearOnComplete(n.clearOnComplete),o.startStreaming(),(h=t.status)==null||h.call(t,200).send({status:"OK"})}async handleColorApplication(e,t){var u,d,h;const s=e.params.color,r=wv(s);if(!r){(u=t.status)==null||u.call(t,400).send({error:"Invalid color format"});return}const o=e.params.endpoint,n=this._endpointRenderers.getModel(o);if(!n){(d=t.status)==null||d.call(t,404).send({error:`Endpoint "${o}" not found`});return}const{r:i,b:a,g:c}=r;n.renderer=wr({mode:"color",data:{r:i,g:c,b:a}}),n.startStreaming(),(h=t.status)==null||h.call(t,200).send({status:"OK"})}async handleEndpointCreation(e,t){var r,o;const s=e.body;if(!s.apiPath||!s.id){(r=t.status)==null||r.call(t,400).send({error:"Name and path are required"});return}this.addNamedEndpoint(s.id,s),(o=t.status)==null||o.call(t,200).send({status:"OK"})}async load(e){var s;const t=e==null?void 0:e.get(Ct.loader);t&&((s=t.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)}))}};Bt([Ie],ze.prototype,"_endpointRenderers",2);Bt([Cs("/api/ui/canvas/patterns")],ze.prototype,"handlePatternsPost",1);Bt([Cs("/api/ui/canvas/pattern/:endpoint/:pattern")],ze.prototype,"handlePatternApplication",1);Bt([Cs("/api/ui/canvas/color/:endpoint/:color")],ze.prototype,"handleColorApplication",1);Bt([Cs("/api/ui/canvas/endpoint")],ze.prototype,"handleEndpointCreation",1);ze=Bt([A(Ku)],ze);const Ct=new Me({class:ze,type:Ku}),{URL:Yn}=ae(),{getOne:Hu}=oe.build({basePath:`${Yn}/api/device`}),Er=m.createLogger({name:"device-service",group:"Services"}),zu=async()=>{Er.debug("sending GET for device serial number");try{const e=await Hu({urlOverride:`${Yn}/api/kos/device/serialNumber`});return[void 0,e==null?void 0:e.data.serialNumber]}catch(e){if(e instanceof pe)return Er.error(`Error fetching device serial number: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},Gu=async()=>{Er.debug("sending GET for device details");try{const e=await Hu({urlOverride:`${Yn}/api/kos/device`});return e?[void 0,e.data]:["unknownError",void 0]}catch(e){if(e instanceof pe)return Er.error(`Error fetching device serial number: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},Ev=Object.freeze(Object.defineProperty({__proto__:null,getDeviceDetails:Gu,getSerialNumber:zu},Symbol.toStringTag,{value:"Module"}));var Mv=Object.defineProperty,Tv=Object.getOwnPropertyDescriptor,Vu=(e,t,s,r)=>{for(var o=r>1?void 0:r?Tv(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Mv(t,s,o),o};const Yu="device-model",_v="/kos/criticalData/changed",Ov="/kos/criticalData/available";let Mr=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"_serialNumber");l(this,"_name");l(this,"_nodeId");this.id=e,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[e]=this.nodeId.split("-");return e}get nodeName(){const[,e]=this.nodeId.split("-");return e}updateModel(e){this._serialNumber=e.serialNumber??"unassigned",this._name=e.name??"unassigned",this._nodeId=e.nodeId??"unassigned"}async loadDeviceData(){const[e,t]=await Gu();if(e){this.logger.error(`Error fetching device serial number: ${e}`);return}if(t){const{name:s,nodeId:r}=t;this.updateModel({name:s,nodeId:r,serialNumber:this.serialNumber})}}async loadSerialNumber(){const[e,t]=await zu();if(e){this.logger.error(`Error fetching device serial number: ${e}`);return}this.updateModel({serialNumber:t,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()}};Vu([U({topic:[_v,Ov],websocket:!0})],Mr.prototype,"handleCriticalDataChanged",1);Mr=Vu([A(Yu)],Mr);const Tr=new Me({class:Mr,type:Yu});var Iv=Object.getOwnPropertyDescriptor,Sv=(e,t,s,r)=>{for(var o=r>1?void 0:r?Iv(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=i(o)||o);return o};const qu="network-interface-model";let xo=class{constructor(e,t,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=e,this.logger=s.logger,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}updateModel(e){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}async init(){this.logger.debug(`initializing network-interface ${this.id}`)}async load(){this.logger.debug(`loading network-interface ${this.id}`)}};xo=Sv([A(qu)],xo);const qn=new me({class:xo,type:qu}),{URL:$v}=ae(),{getAll:Cv}=oe.build({basePath:`${$v}/api/kos/network/interfaces`}),Wi=m.createLogger({name:"network-interface-service",group:"Services"}),Wu=async()=>{Wi.debug("sending GET for copy-logs");try{const e=await Cv({});return[void 0,e==null?void 0:e.data]}catch(e){if(e instanceof pe)return Wi.error(`Error fetching log file size: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},Dv=Object.freeze(Object.defineProperty({__proto__:null,getNetworkInterfaces:Wu},Symbol.toStringTag,{value:"Module"}));var xv=Object.defineProperty,Av=Object.getOwnPropertyDescriptor,Qu=(e,t,s,r)=>{for(var o=r>1?void 0:r?Av(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&xv(t,s,o),o};const Zu="network-interface-container-model";let _r=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=e,this.logger=s.logger,this._models=new Se({parentId:e,indexMap:{byCategory:"category"}})}getModel(e){return this._models.getModel(e)}get models(){return this._models}get data(){return this._models.data}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}async init(){this.logger.debug(`initializing network-interface-container container ${this.id}`)}async refreshInterfaces(){this.logger.debug("refreshing interfaces");const[e,t]=await Wu();if(e){this.logger.error(`Error loading network interfaces: ${e}`);return}t&&t.forEach(s=>{const r=qn.instance(s.name).forceUpdate.options(s).build();this.addModel(r)})}async load(){this.logger.debug(`loading network-interface-container container ${this.id}`),this.refreshInterfaces()}};Qu([Ie],_r.prototype,"_models",2);_r=Qu([A(Zu)],_r);const Ts=new Me({class:_r,type:Zu});Ts.addRelatedModel(qn);const{URL:Pv}=ae(),{getAll:Rv}=oe.build({basePath:`${Pv}/api/kos/storage/devices`}),Qi=m.createLogger({name:"storage-device-service",group:"Services"}),Xu=async()=>{Qi.debug("sending GET for storage-device");const e=await Rv({});return!(e!=null&&e.data)||e.status!==200?(Qi.error("Failed to retrieve storage-device data",e),[]):e.data},kv=Object.freeze(Object.defineProperty({__proto__:null,getStorageDevices:Xu},Symbol.toStringTag,{value:"Module"}));var Lv=Object.getOwnPropertyDescriptor,Fv=(e,t,s,r)=>{for(var o=r>1?void 0:r?Lv(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=i(o)||o);return o};const Ju="storage-device-model";let Ao=class{constructor(e,t,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=e,this.logger=s.logger,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}updateModel(e){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}async init(){this.logger.debug(`initializing storage-device ${this.id}`)}async load(){this.logger.debug(`loading storage-device ${this.id}`)}};Ao=Fv([Ar(),A(Ju)],Ao);const Or=new me({class:Ao,type:Ju});var Nv=Object.defineProperty,Uv=Object.getOwnPropertyDescriptor,Wn=(e,t,s,r)=>{for(var o=r>1?void 0:r?Uv(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Nv(t,s,o),o};const ed="storage-device-container-model",jv="/kos/storage";let _s=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=e,this.logger=s.logger,this._models=new Se({parentId:e})}getModel(e){return this._models.getModel(e)}get models(){return this._models}get data(){return this._models.data}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}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(e){this._models.data.filter(s=>!e.find(r=>r.id===s.id)).forEach(s=>{this.removeModel(s.id)}),e.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=Or.instance(s.id).options(o).build();this.addModel(n)}})}async load(){this.logger.debug(`loading storage-device-container container ${this.id}`),(await Xu()).forEach(t=>{if(t.deviceType!=="disk"){const s={...t,kosParentId:this.id},r=Or.instance(t.id).options(s).build();this.addModel(r)}})}};Wn([Ie],_s.prototype,"_models",2);Wn([U({topic:jv,websocket:!0})],_s.prototype,"handleStorageAvailability",1);_s=Wn([A(ed)],_s);const Dt=new Me({class:_s,type:ed});Dt.addRelatedModel(Or);const{URL:Qn}=ae(),{getAll:Bv,postModel:Kv}=oe.build({basePath:`${Qn}/api/kos/update/available`}),Zi=m.createLogger({name:"usb-update-service",group:"Services"}),td=async()=>{Zi.debug("sending GET for usb-update");const e=await Bv({urlOverride:`${Qn}/api/kos/update/available`});return!(e!=null&&e.data)||(e==null?void 0:e.status)!==200?(Zi.error("Failed to retrieve usb-update data",e),[]):e.data},sd=async(e,t,s)=>{const r=await Kv({model:{manifestId:e,deviceId:t},tracker:s,urlOverride:`${Qn}/api/kos/update/install`});if(!(r!=null&&r.data))throw new Error("No response from server");return r.data},Hv=Object.freeze(Object.defineProperty({__proto__:null,getAvailableUpdates:td,installUpdate:sd},Symbol.toStringTag,{value:"Module"}));var zv=Object.defineProperty,Gv=Object.getOwnPropertyDescriptor,rd=(e,t,s,r)=>{for(var o=r>1?void 0:r?Gv(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&zv(t,s,o),o};const od="usb-update-model";let Ir=class{constructor(e,t,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=e,this.logger=s.logger,this.active=t.active,this.blocked=t.blocked,this.createTime=t.createTime,this.deviceId=t.deviceId,this.manifestId=t.manifestId,this.notes=t.notes,this.futureHandler=new Rr(this)}updateModel(e){this.active=e.active,this.blocked=e.blocked,this.createTime=e.createTime,this.deviceId=e.deviceId,this.manifestId=e.manifestId,this.notes=e.notes}reset(){this.futureHandler.removeFuture()}get future(){return this.futureHandler.future}async install(e){if(!e)throw new Error("No tracker provided");return this.logger.info(`Installing update for manifest ${this.manifestId} from device ${this.deviceId}`),sd(this.manifestId,this.deviceId,e)}async init(){this.logger.debug(`initializing usb-update ${this.id}`)}async load(){this.logger.debug(`loading usb-update ${this.id}`)}};rd([si()],Ir.prototype,"install",1);Ir=rd([A(od)],Ir);const Zn=new me({class:Ir,type:od});var Vv=Object.defineProperty,Yv=Object.getOwnPropertyDescriptor,qr=(e,t,s,r)=>{for(var o=r>1?void 0:r?Yv(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Vv(t,s,o),o};const nd="usb-update-container-model";let xt=class{constructor(e,t,s){l(this,"id");l(this,"disposer");l(this,"storageService");l(this,"_activeUpdate");l(this,"logger");l(this,"_models");this.id=e,this.logger=s.logger,this._models=new Se({parentId:e})}getModel(e){return this._models.getModel(e)}get models(){return this._models}get data(){return this._models.data}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}get activeUpdate(){return this._activeUpdate}reset(){this.clearActiveUpdate()}clearActiveUpdate(){this._activeUpdate=void 0}updateActiveUpdate(e){this._activeUpdate=e}get isUsbInserted(){return this.storageService.isStorageInserted}get hasAvailableUpdates(){return this._models.data.length>0}async syncAvailableUpdates(){const e=await td();X(()=>{const t=e.map(s=>`${s.deviceId}-${s.manifestId}`);this._models.data.filter(s=>!t.includes(s.id)).forEach(s=>this.removeModel(s.id)),e.forEach(s=>{const r=`${s.deviceId}-${s.manifestId}`,o=Zn.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 e;(e=this.disposer)==null||e.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}`)}};qr([Pt({modelType:Dt.type})],xt.prototype,"storageService",2);qr([Ie],xt.prototype,"_models",2);qr([lc({dependencies:e=>[e.isUsbInserted]})],xt.prototype,"usbInsertedEffect",1);xt=qr([A(nd)],xt);const Os=new Me({class:xt,type:nd});Os.addRelatedModel(Zn);const qv=()=>({...{[Lt.type]:{class:Dl},[He.type]:{class:Ll,singleton:!0},...re.registration,...rt.registration,...St.registration,...mr.registration,...ke.registration,[Hn.type]:{class:exports.WsEventModel,singleton:!0},...Ms.registration,...Bn.registration,...ar.registration}}),Xn=qv(),Wv={models:Xn,preloadModels:[]},Xi=!0,id=e=>()=>{const t=Xn;return bc(Po)(Es).model(St).model(Dt).model(Os).model(Tr).model(hr).model(ps).model(fr).model(Dn).model(Ts).model(Ct).model(Gn).model(Yl).model(Sn,Xi).model(Ps).model(Ql,Xi),Object.keys(t).forEach(s=>{const r=t[s];yc(Po)(s,r)}),{preload:x.model.preloadModel(e),model:x.model.register(e),companion:x.companion.register(e),legacy:x.model.registerLegacyModel(e)}},we={};we.core={models:id(we)};we.preload=x.model.preloadModel(we);we.model=x.model.register(we);we.companion=x.companion.register(we);we.legacy=x.model.registerLegacyModel(we);const Po=we;class Qv{registerTroubleRankMapper(t){return S.propertyMapper.registerPropertyMapper(be.TroubleRank,t),this}registerTroubleRoleMapper(t){return S.propertyMapper.registerPropertyMapper(be.TroubleRole,t),this}registerTroubleColorMapper(t){return S.propertyMapper.registerPropertyMapper(be.TroubleColor,t),this}registerModelLoader(t,s){S.loader.registerLoader(t,s)}registerCanvasPatternLoader(t){S.loader.registerLoader(Ct.loader,t)}}const Zv=async(e,t)=>{const s=Dn.instance(e).options({}).build(),r=t?`${t}-`:"";return await ue(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:()=>{Xe(s)}}},ad="kos:service:region",cd="regionId",Xv=`${ad}-${cd}`,ld=async e=>{const t=rt.factory(Xv)({path:ad,attribute:cd});await ue(t),t.updateProperty(e)},Jn="/kos-timer-event",ei="/kos-timer-event/tick",ti="defaultTimerEnd",es=m.createLogger({name:"timer-manager"}),Jv=e=>e.updateProperty!==void 0;class ud{constructor(t,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=t;const o=typeof s=="number"?s:s.value||60;this.timeout=o,this.state="inactive",this.remainingTime=o,Jv(s)&&Y(()=>{m.info(`Updating config value timer ${t} with new timeout value ${s.value}`);const n=s.value||60;this.updateTimeout(n)}),this.addTimeoutAction({name:ti}),r&&r.forEach(n=>{this.addTimeoutAction(n)})}get id(){return this.name}start(){if(this.state==="active"){es.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&&(es.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(t){this.timeout=t,this.restart()}addTimeoutAction(t){const s=t.remainingTime??0;this.timeoutActions.has(s)||this.timeoutActions.set(s,[]);const r=t.name,o=this.timeoutActions.get(s).find(n=>n.name===r);o?o.action=t.action:this.timeoutActions.get(s).push(t)}removeTimeoutAction(t){for(const[s,r]of this.timeoutActions.entries()){const o=r.filter(n=>n.name!==t);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(t){this.timeoutActions.has(t)&&this.timeoutActions.get(t).forEach(s=>{var r;es.debug(`Executing timer action ${s.name} at ${t}`),(r=s.action)==null||r.call(s,s.name,t),this.notifyTimeoutAction(s),s.singleUse&&(es.info(`${this.name} Removing single-use action ${s.name}`),this.removeTimeoutAction(s.name))}),this.notifyTick()}notifyTick(){z(`${ei}/${this.name}`,{name:this.name,remainingTime:this.remainingTime})}notifyTimeoutAction(t){z(Jn,{name:this.name,action:t.name,remainingTime:this.remainingTime})}}const ts=new Map,ht=(e,t)=>{const s=ts.get(e);if(!s){es.error(`Timer ${e} not found`);return}t(s)},dd={createRelativeTimer(e,t,s){const r=new Date,o=Math.round((t.getTime()-r.getTime())/1e3);return this.createTimer(e,o,s)},createTimer(e,t=60,s){if(ts.has(e))return ts.get(e);const r=new ud(e,t,s);return ts.set(e,r),r},getTimer(e){return ts.get(e)},clearTimer(e){ht(e,t=>t.pause())},restartTimer(e){ht(e,t=>t.restart())},resetTimer(e){ht(e,t=>t.reset())},addTimeoutAction(e,t){ht(e,s=>s.addTimeoutAction(t))},removeTimeoutAction(e,t){ht(e,s=>s.removeTimeoutAction(t))},startTimer(e){ht(e,t=>t.start())}},hd="kos:service:region:settings",fd="timeZone",ew=`${hd}-${fd}`,Ro=async e=>{const t=rt.factory(ew)({path:hd,attribute:fd});await ue(t),t.updateProperty(e)},tw=e=>!e||!e.data;function si(e={}){const{alias:t,namespace:s,abortController:r=!1}=e;return(o,n,i)=>{o[os]=o[os]||{},t&&(o[as]=o[as]||new Map,o[as].set(n,t));const a=i.value,c=async function(...u){const d=tt();m.debug(`Calling future service ${n} with tracker ${d}`);let h,f;r&&(h=new AbortController);const p=Je.initiateFuture({tracker:d,id:yn});s&&(p.namespace=s),m.debug(`waiting for future ${p.id} to be ready`),await ue(p),m.debug(`future ${p.id} is ready`),X(()=>{m.debug(`Adding future ${p.id} to futureHandler`),this.futureHandler.addFuture(p,t)}),r&&h&&(f=Y(()=>{(p.status==="CANCELLED"||p.endState===Ke.Canceled)&&(m.debug(`Future ${p.id} cancelled, aborting request`),h==null||h.abort())}),h.signal.addEventListener("abort",async()=>{if(p.status!=="CANCELLED"&&p.endState!==Ke.Canceled&&!p.endState){m.debug(`AbortController aborted, cancelling future ${p.id}`);try{await p.cancelFuture()}catch(w){m.error(`Failed to cancel future ${p.id}:`,w)}}},{once:!0}));const b=()=>{f&&(f(),f=void 0)};try{const w=[...u];if(r&&h){const F=w[w.length-1];F&&typeof F=="object"&&"aborted"in F?w[w.length-1]=h.signal:w.push(h.signal)}w.push(d);const M=await a.apply(this,w);m.debug(`received future response for ${d}`,M);const _=tw(M)?M:M==null?void 0:M.data;return _?(_.progress=1,m.debug("mapping future response to future model"),p.endState?m.debug(`future ${p.id} has already completed. Not updating the model`):On(_,p)):this.futureHandler.removeFuture(t),b(),_}catch(w){if(b(),r&&(h!=null&&h.signal.aborted)){const M=new Error("Operation cancelled");throw m.debug(`Operation ${n} was cancelled`),M}throw m.error(w),w}};o[os][n]={handler:c}}}const sw=({path:e})=>(t,s)=>{t[k]=t[k]||{},t[k][s]={modelType:Ms.type,id:`${Ms.type}-${e}`,options:{path:e},lifecycle:H.INIT}};function rw(e){const{path:t,attribute:s}=e;return(r,o)=>{r[k]=r[k]||{},r[k][o]={modelType:Bn.type,id:`${t}-${s}`,options:{path:t,attribute:s},lifecycle:H.INIT}}}const mt=m.createLogger({name:"services",group:"Services"}),ow=async(e,t)=>pd(e,t,`${exports.BASE_URL}/api/server/login`),pd=async(e,t,s=`${exports.BASE_URL}/api/login`)=>{const r=await exports.kosFetch(`${s}`,{method:"POST",destinationAddress:"",body:JSON.stringify({email:e,password:t})});if(!r.ok){const n=await r.json();throw Error(`${n==null?void 0:n.error}`)}return await r.json()},nw=async e=>gd(e,`${exports.BASE_URL}/api/server/startPasswordReset`,""),gd=async(e,t=`${exports.BASE_URL}/api/startPasswordReset`,s="server")=>{const r=await exports.kosFetch(`${t}?email=${e}`,{method:"POST",destinationAddress:s});if(!r.ok)throw Error(`There was a problem reseting config; returned status ${r.status}`);return await r.json()},iw=async(e,t)=>md(e,t,`${exports.BASE_URL}/api/server/resetPassword`),md=async(e,t,s=`${exports.BASE_URL}/api/resetPassword`)=>{mt.debug(`resetting password with token ${e} and password ${t.replace(/./g,"*")}`);const r=await exports.kosFetch(`${s}`,{method:"POST",destinationAddress:"",body:JSON.stringify({token:e,password:t})});if(mt.debug(`password reset returned status ${r.status}`),!r.ok){mt.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()},aw=async(e,t,s)=>yd(e,t,s,`${exports.BASE_URL}/api/server/acceptInvite`),yd=async(e,t,s,r=`${exports.BASE_URL}/api/server/acceptInvite`)=>{mt.debug(`accepting invite with token ${e} and password ${t.replace(/./g,"*")}`);const o=await exports.kosFetch(`${r}`,{method:"POST",destinationAddress:"",body:JSON.stringify({token:e,password:t,name:s})});if(mt.debug(`invitation accept returned status ${o.status}`),!o.ok){mt.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 cw(e,t,s,r){const o=e instanceof Promise?{promise:e,abortController:t,cancelFuture:s,future:r}:e,{promise:n,abortController:i,cancelFuture:a,future:c}=o,u=n;let d=0,h="PENDING",f=!0;const p=new Set;let b;return c&&typeof c=="object"&&(b=E.autorun(()=>{const w=c.progress||0,M=c.status||"PENDING",_=!c.endState;(w!==d||M!==h||_!==f)&&(d=w,h=M,f=_,p.forEach(F=>{try{F(d,h)}catch(Q){console.warn("Progress callback error:",Q)}}))})),n.finally(()=>{f=!1,i!=null&&i.signal.aborted||(h="COMPLETED",p.forEach(w=>{try{w(d,h)}catch(M){console.warn("Progress callback error:",M)}})),b&&b(),p.clear()}),u.cancel=async()=>{i&&!i.signal.aborted&&i.abort(),a&&await a(),f=!1,h="CANCELLED",p.forEach(w=>{try{w(d,h)}catch(M){console.warn("Progress callback error:",M)}}),b&&b()},u.getController=()=>i,u.isCancelled=()=>(i==null?void 0:i.signal.aborted)??!1,Object.defineProperty(u,"progress",{get:()=>d,enumerable:!0}),Object.defineProperty(u,"status",{get:()=>h,enumerable:!0}),Object.defineProperty(u,"isRunning",{get:()=>f,enumerable:!0}),u.onProgressUpdate=w=>(p.add(w),w(d,h),()=>p.delete(w)),u}const lw=qe.keyframes`
116
116
  0% {
117
117
  left: -90px;
118
118
  color: #eee;